frontend_net: report stuff to helper method
[metaproxy-moved-to-github.git] / src / filter_frontend_net.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2012 Index Data
3
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19 #include "config.hpp"
20
21 #include <sstream>
22 #include <iomanip>
23 #include <metaproxy/util.hpp>
24 #include "pipe.hpp"
25 #include <metaproxy/filter.hpp>
26 #include <metaproxy/package.hpp>
27 #include "thread_pool_observer.hpp"
28 #include "filter_frontend_net.hpp"
29 #include <yazpp/z-assoc.h>
30 #include <yazpp/pdu-assoc.h>
31 #include <yazpp/socket-manager.h>
32 #include <yazpp/limit-connect.h>
33 #include <yaz/timing.h>
34 #include <yaz/log.h>
35 #include "gduutil.hpp"
36
37 #include <iostream>
38
39 namespace mp = metaproxy_1;
40 namespace yf = metaproxy_1::filter;
41
42 namespace metaproxy_1 {
43     namespace filter {
44         class FrontendNet::Port {
45             friend class Rep;
46             friend class FrontendNet;
47             std::string port;
48             std::string route;
49         };
50         class FrontendNet::Rep {
51             friend class FrontendNet;
52
53             int m_no_threads;
54             std::vector<Port> m_ports;
55             int m_listen_duration;
56             int m_session_timeout;
57             int m_connect_max;
58             std::string m_msg_config;
59             std::string m_stat_req;
60             yazpp_1::SocketManager mySocketManager;
61             ZAssocServer **az;
62             int m_duration_freq[22];
63             double m_duration_lim[22];
64         public:
65             Rep();
66             ~Rep();
67         };
68         class FrontendNet::My_Timer_Thread : public yazpp_1::ISocketObserver {
69         private:
70             yazpp_1::ISocketObservable *m_obs;
71             Pipe m_pipe;
72             bool m_timeout;
73         public:
74             My_Timer_Thread(yazpp_1::ISocketObservable *obs, int duration);
75             void socketNotify(int event);
76             bool timeout();
77         };
78         class FrontendNet::ZAssocChild : public yazpp_1::Z_Assoc {
79         public:
80             ~ZAssocChild();
81             ZAssocChild(yazpp_1::IPDU_Observable *the_PDU_Observable,
82                         mp::ThreadPoolSocketObserver *m_thread_pool_observer,
83                         const mp::Package *package,
84                         std::string route,
85                         Rep *rep);
86             int m_no_requests;
87             std::string m_route;
88         private:
89             yazpp_1::IPDU_Observer* sessionNotify(
90                 yazpp_1::IPDU_Observable *the_PDU_Observable,
91                 int fd);
92             void recv_GDU(Z_GDU *apdu, int len);
93             void report(Z_HTTP_Request *hreq);
94             void failNotify();
95             void timeoutNotify();
96             void connectNotify();
97         private:
98             mp::ThreadPoolSocketObserver *m_thread_pool_observer;
99             mp::Session m_session;
100             mp::Origin m_origin;
101             bool m_delete_flag;
102             const mp::Package *m_package;
103             Rep *m_p;
104         };
105         class FrontendNet::ThreadPoolPackage : public mp::IThreadPoolMsg {
106         public:
107             ThreadPoolPackage(mp::Package *package,
108                               yf::FrontendNet::ZAssocChild *ses,
109                               Rep *rep);
110             ~ThreadPoolPackage();
111             IThreadPoolMsg *handle();
112             void result(const char *t_info);
113             bool cleanup(void *info);
114         private:
115             yaz_timing_t timer;
116             ZAssocChild *m_assoc_child;
117             mp::Package *m_package;
118             Rep *m_p;
119         }; 
120         class FrontendNet::ZAssocServer : public yazpp_1::Z_Assoc {
121         public:
122             ~ZAssocServer();
123             ZAssocServer(yazpp_1::IPDU_Observable *PDU_Observable,
124                          std::string route,
125                          Rep *rep);
126             void set_package(const mp::Package *package);
127             void set_thread_pool(ThreadPoolSocketObserver *observer);
128         private:
129             yazpp_1::IPDU_Observer* sessionNotify(
130                 yazpp_1::IPDU_Observable *the_PDU_Observable,
131                 int fd);
132             void recv_GDU(Z_GDU *apdu, int len);
133             
134             void failNotify();
135             void timeoutNotify();
136             void connectNotify();
137         private:
138             mp::ThreadPoolSocketObserver *m_thread_pool_observer;
139             const mp::Package *m_package;
140             yazpp_1::LimitConnect limit_connect;
141             std::string m_route;
142             Rep *m_p;
143         };
144     }
145 }
146
147 yf::FrontendNet::ThreadPoolPackage::ThreadPoolPackage(mp::Package *package,
148                                                       ZAssocChild *ses,
149                                                       Rep *rep) :
150     m_assoc_child(ses), m_package(package), m_p(rep)
151 {
152     timer = yaz_timing_create();
153 }
154
155 yf::FrontendNet::ThreadPoolPackage::~ThreadPoolPackage()
156 {
157     yaz_timing_destroy(&timer); // timer may be NULL
158     delete m_package;
159 }
160
161 bool yf::FrontendNet::ThreadPoolPackage::cleanup(void *info)
162 {
163     mp::Session *ses = (mp::Session *) info;
164
165     return *ses == m_package->session();
166 }
167
168 void yf::FrontendNet::ThreadPoolPackage::result(const char *t_info)
169 {
170     m_assoc_child->m_no_requests--;
171
172     yazpp_1::GDU *gdu = &m_package->response();
173
174     if (gdu->get())
175     {
176         int len;
177         m_assoc_child->send_GDU(gdu->get(), &len);
178
179         yaz_timing_stop(timer);
180         double duration = yaz_timing_get_real(timer);
181         
182         size_t ent = 0;
183         while (m_p->m_duration_lim[ent] != 0.0 && duration > m_p->m_duration_lim[ent])
184             ent++;
185         m_p->m_duration_freq[ent]++;
186         
187         if (m_p->m_msg_config.length())
188         {
189             Z_GDU *z_gdu = gdu->get();
190             
191             std::ostringstream os;
192             os  << m_p->m_msg_config << " "
193                 << *m_package << " "
194                 << std::fixed << std::setprecision (6) << duration << " ";
195             
196             if (z_gdu) 
197                 os << *z_gdu;
198             else
199                 os << "-";
200             
201             yaz_log(YLOG_LOG, "%s %s", os.str().c_str(), t_info);
202         }
203     }
204     else if (!m_package->session().is_closed())
205     {
206         // no response package and yet the session is still open..
207         // means that request is unhandled..
208         yazpp_1::GDU *gdu_req = &m_package->request();
209         Z_GDU *z_gdu = gdu_req->get();
210         if (z_gdu && z_gdu->which == Z_GDU_Z3950)
211         {
212             // For Z39.50, response with a Close and shutdown
213             mp::odr odr;
214             int len;
215             Z_APDU *apdu_response = odr.create_close(
216                 z_gdu->u.z3950, Z_Close_systemProblem, 
217                 "unhandled Z39.50 request");
218
219             m_assoc_child->send_Z_PDU(apdu_response, &len);
220         }
221         else if (z_gdu && z_gdu->which == Z_GDU_HTTP_Request)
222         {
223             // For HTTP, respond with Server Error
224             int len;
225             mp::odr odr;
226             Z_GDU *zgdu_res 
227                 = odr.create_HTTP_Response(m_package->session(), 
228                                            z_gdu->u.HTTP_Request, 500);
229             m_assoc_child->send_GDU(zgdu_res, &len);
230         }
231         m_package->session().close();
232     }
233
234     if (m_assoc_child->m_no_requests == 0 && m_package->session().is_closed())
235     {
236         m_assoc_child->close();
237     }
238     
239
240     delete this;
241 }
242
243 mp::IThreadPoolMsg *yf::FrontendNet::ThreadPoolPackage::handle() 
244 {
245     m_package->move(m_assoc_child->m_route);
246     return this;
247 }
248
249 yf::FrontendNet::ZAssocChild::ZAssocChild(
250     yazpp_1::IPDU_Observable *PDU_Observable,
251     mp::ThreadPoolSocketObserver *my_thread_pool,
252     const mp::Package *package,
253     std::string route, Rep *rep)
254     :  Z_Assoc(PDU_Observable), m_p(rep)
255 {
256     m_thread_pool_observer = my_thread_pool;
257     m_no_requests = 0;
258     m_delete_flag = false;
259     m_package = package;
260     m_route = route;
261     const char *peername = PDU_Observable->getpeername();
262     if (!peername)
263         peername = "unknown";
264     m_origin.set_tcpip_address(std::string(peername), m_session.id());
265     timeout(m_p->m_session_timeout);
266 }
267
268 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocChild::sessionNotify(
269     yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
270 {
271     return 0;
272 }
273
274 yf::FrontendNet::ZAssocChild::~ZAssocChild()
275 {
276 }
277
278 void yf::FrontendNet::ZAssocChild::report(Z_HTTP_Request *hreq)
279 {
280     mp::odr o;
281     
282     Z_GDU *gdu_res = o.create_HTTP_Response(m_session, hreq, 200);
283     
284     Z_HTTP_Response *hres = gdu_res->u.HTTP_Response;
285     
286     mp::wrbuf w;
287     size_t i;
288     int number_total = 0;
289     
290     for (i = 0; m_p->m_duration_lim[i] != 0.0; i++)
291         number_total += m_p->m_duration_freq[i];
292     number_total += m_p->m_duration_freq[i];
293     
294     wrbuf_puts(w, "<?xml version=\"1.0\">\n");
295     wrbuf_puts(w, "<frontend_net>\n");
296     wrbuf_printf(w, "  <responses frequency=\"%d\">\n", number_total);
297     for (i = 0; m_p->m_duration_lim[i] != 0.0; i++)
298     {
299         if (m_p->m_duration_freq[i] > 0)
300             wrbuf_printf(
301                 w, "    <response mintime=\"%f\" "
302                 "maxtime=\"%f\" frequency=\"%d\"/>\n",
303                 i > 0 ? m_p->m_duration_lim[i - 1] : 0.0,
304                 m_p->m_duration_lim[i], m_p->m_duration_freq[i]);
305     }
306     
307     if (m_p->m_duration_freq[i] > 0)
308         wrbuf_printf(
309             w, "    <response mintime=\"%f\" frequency=\"%d\"/>\n",
310             m_p->m_duration_lim[i - 1], m_p->m_duration_freq[i]);
311     wrbuf_puts(w, " </responses>\n");
312     wrbuf_puts(w, "</frontend_net>\n");
313     
314     hres->content_len = w.len();
315     hres->content_buf = (char *) w.buf();
316     
317     int len;
318     send_GDU(gdu_res, &len);
319 }
320
321 void yf::FrontendNet::ZAssocChild::recv_GDU(Z_GDU *z_pdu, int len)
322 {
323     m_no_requests++;
324
325     mp::Package *p = new mp::Package(m_session, m_origin);
326
327     if (z_pdu && z_pdu->which == Z_GDU_HTTP_Request)
328     {
329         Z_HTTP_Request *hreq = z_pdu->u.HTTP_Request;
330
331         if (m_p->m_stat_req.length()
332             && !strcmp(hreq->path, m_p->m_stat_req.c_str()))
333         {
334             report(hreq);
335             return;
336         }
337     }
338
339     ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
340     p->copy_route(*m_package);
341     p->request() = yazpp_1::GDU(z_pdu);
342
343     if (m_p->m_msg_config.length())
344     {
345         if (z_pdu)          
346         {
347             std::ostringstream os;
348             os  << m_p->m_msg_config << " "
349                 << *p << " "
350                 << "0.000000" << " " 
351                 << *z_pdu;
352             yaz_log(YLOG_LOG, "%s", os.str().c_str());
353         }
354     }
355     m_thread_pool_observer->put(tp);  
356 }
357
358 void yf::FrontendNet::ZAssocChild::failNotify()
359 {
360     // TODO: send Package to signal "close"
361     if (m_session.is_closed())
362     {
363         if (m_no_requests == 0)
364             delete this;
365         return;
366     }
367     m_no_requests++;
368
369     m_session.close();
370
371     mp::Package *p = new mp::Package(m_session, m_origin);
372
373     ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
374     p->copy_route(*m_package);
375     m_thread_pool_observer->cleanup(tp, &m_session);
376     m_thread_pool_observer->put(tp);
377 }
378
379 void yf::FrontendNet::ZAssocChild::timeoutNotify()
380 {
381     failNotify();
382 }
383
384 void yf::FrontendNet::ZAssocChild::connectNotify()
385 {
386
387 }
388
389 yf::FrontendNet::ZAssocServer::ZAssocServer(
390     yazpp_1::IPDU_Observable *PDU_Observable,
391     std::string route,
392     Rep *rep)
393     : 
394     Z_Assoc(PDU_Observable), m_route(route), m_p(rep)
395 {
396     m_package = 0;
397 }
398
399
400 void yf::FrontendNet::ZAssocServer::set_package(const mp::Package *package)
401 {
402     m_package = package;
403 }
404
405 void yf::FrontendNet::ZAssocServer::set_thread_pool(
406     ThreadPoolSocketObserver *observer)
407 {
408     m_thread_pool_observer = observer;
409 }
410
411 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocServer::sessionNotify(
412     yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
413 {
414
415     const char *peername = the_PDU_Observable->getpeername();
416     if (peername)
417     {
418         limit_connect.add_connect(peername);
419         limit_connect.cleanup(false);
420         int con_sz = limit_connect.get_total(peername);
421         if (m_p->m_connect_max && con_sz > m_p->m_connect_max)
422             return 0;
423     }
424     ZAssocChild *my = new ZAssocChild(the_PDU_Observable,
425                                       m_thread_pool_observer,
426                                       m_package, m_route, m_p);
427     return my;
428 }
429
430 yf::FrontendNet::ZAssocServer::~ZAssocServer()
431 {
432 }
433
434 void yf::FrontendNet::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
435 {
436 }
437
438 void yf::FrontendNet::ZAssocServer::failNotify()
439 {
440 }
441
442 void yf::FrontendNet::ZAssocServer::timeoutNotify()
443 {
444 }
445
446 void yf::FrontendNet::ZAssocServer::connectNotify()
447 {
448 }
449
450 yf::FrontendNet::FrontendNet() : m_p(new Rep)
451 {
452 }
453
454 yf::FrontendNet::Rep::Rep()
455 {
456     m_no_threads = 5;
457     m_listen_duration = 0;
458     m_session_timeout = 300; // 5 minutes
459     m_connect_max = 0;
460     az = 0;
461     size_t i;
462     for (i = 0; i < 22; i++)
463         m_duration_freq[i] = 0;
464     m_duration_lim[0] = 0.000001;
465     m_duration_lim[1] = 0.00001;
466     m_duration_lim[2] = 0.0001;
467     m_duration_lim[3] = 0.001;
468     m_duration_lim[4] = 0.01;
469     m_duration_lim[5] = 0.1;
470     m_duration_lim[6] = 0.2;
471     m_duration_lim[7] = 0.3;
472     m_duration_lim[8] = 0.5;
473     m_duration_lim[9] = 1.0;
474     m_duration_lim[10] = 1.5;
475     m_duration_lim[11] = 2.0;
476     m_duration_lim[12] = 3.0;
477     m_duration_lim[13] = 4.0;
478     m_duration_lim[14] = 5.0;
479     m_duration_lim[15] = 6.0;
480     m_duration_lim[16] = 8.0;
481     m_duration_lim[17] = 10.0;
482     m_duration_lim[18] = 15.0;
483     m_duration_lim[19] = 20.0;
484     m_duration_lim[20] = 30.0;
485     m_duration_lim[21] = 0;
486 }
487
488 yf::FrontendNet::Rep::~Rep()
489 {
490     if (az)
491     {
492         size_t i;
493         for (i = 0; i < m_ports.size(); i++)
494             delete az[i];
495         delete [] az;
496     }
497     az = 0;
498 }
499
500 yf::FrontendNet::~FrontendNet()
501 {
502 }
503
504 void yf::FrontendNet::stop() const
505 {
506     if (m_p->az)
507     {
508         size_t i;
509         for (i = 0; i < m_p->m_ports.size(); i++)
510             m_p->az[i]->server("");
511     }
512 }
513
514 bool yf::FrontendNet::My_Timer_Thread::timeout()
515 {
516     return m_timeout;
517 }
518
519 yf::FrontendNet::My_Timer_Thread::My_Timer_Thread(
520     yazpp_1::ISocketObservable *obs,
521     int duration) : 
522     m_obs(obs), m_pipe(9123), m_timeout(false)
523 {
524     obs->addObserver(m_pipe.read_fd(), this);
525     obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
526     obs->timeoutObserver(this, duration);
527 }
528
529 void yf::FrontendNet::My_Timer_Thread::socketNotify(int event)
530 {
531     m_timeout = true;
532     m_obs->deleteObserver(this);
533 }
534
535 void yf::FrontendNet::process(Package &package) const
536 {
537     if (m_p->az == 0)
538         return;
539     size_t i;
540     My_Timer_Thread *tt = 0;
541
542     if (m_p->m_listen_duration)
543         tt = new My_Timer_Thread(&m_p->mySocketManager,
544                                  m_p->m_listen_duration);
545     
546     ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads);
547
548     for (i = 0; i<m_p->m_ports.size(); i++)
549     {
550         m_p->az[i]->set_package(&package);
551         m_p->az[i]->set_thread_pool(&tp);
552     }
553     while (m_p->mySocketManager.processEvent() > 0)
554     {
555         int no = m_p->mySocketManager.getNumberOfObservers();
556         if (no <= 1)
557             break;
558         if (tt && tt->timeout())
559             break;
560     }
561     delete tt;
562 }
563
564 void yf::FrontendNet::configure(const xmlNode * ptr, bool test_only,
565                                 const char *path)
566 {
567     if (!ptr || !ptr->children)
568     {
569         throw yf::FilterException("No ports for Frontend");
570     }
571     std::vector<Port> ports;
572     for (ptr = ptr->children; ptr; ptr = ptr->next)
573     {
574         if (ptr->type != XML_ELEMENT_NODE)
575             continue;
576         if (!strcmp((const char *) ptr->name, "port"))
577         {
578             Port port;
579             const struct _xmlAttr *attr;
580             for (attr = ptr->properties; attr; attr = attr->next)
581             {
582                 if (!strcmp((const char *) attr->name, "route"))
583                     port.route = mp::xml::get_text(attr);
584             }
585             port.port = mp::xml::get_text(ptr);
586             ports.push_back(port);
587             
588         }
589         else if (!strcmp((const char *) ptr->name, "threads"))
590         {
591             std::string threads_str = mp::xml::get_text(ptr);
592             int threads = atoi(threads_str.c_str());
593             if (threads < 1)
594                 throw yf::FilterException("Bad value for threads: " 
595                                                    + threads_str);
596             m_p->m_no_threads = threads;
597         }
598         else if (!strcmp((const char *) ptr->name, "timeout"))
599         {
600             std::string timeout_str = mp::xml::get_text(ptr);
601             int timeout = atoi(timeout_str.c_str());
602             if (timeout < 1)
603                 throw yf::FilterException("Bad value for timeout: " 
604                                                    + timeout_str);
605             m_p->m_session_timeout = timeout;
606         }
607         else if (!strcmp((const char *) ptr->name, "connect-max"))
608         {
609             m_p->m_connect_max = mp::xml::get_int(ptr, 0);
610         }
611         else if (!strcmp((const char *) ptr->name, "message"))
612         {
613             m_p->m_msg_config = mp::xml::get_text(ptr);
614         }
615         else if (!strcmp((const char *) ptr->name, "stat-req"))
616         {
617             m_p->m_stat_req = mp::xml::get_text(ptr);
618         }
619         else
620         {
621             throw yf::FilterException("Bad element " 
622                                       + std::string((const char *)
623                                                     ptr->name));
624         }
625     }
626     if (test_only)
627         return;
628     set_ports(ports);
629 }
630
631 void yf::FrontendNet::set_ports(std::vector<std::string> &ports)
632 {
633     std::vector<Port> nports;
634     size_t i;
635
636     for (i = 0; i < ports.size(); i++)
637     {
638         Port nport;
639
640         nport.port = ports[i];
641
642         nports.push_back(nport);
643     }
644     set_ports(nports);
645 }
646
647
648 void yf::FrontendNet::set_ports(std::vector<Port> &ports)
649 {
650     m_p->m_ports = ports;
651     
652     m_p->az = new yf::FrontendNet::ZAssocServer *[m_p->m_ports.size()];
653     
654     // Create yf::FrontendNet::ZAssocServer for each port
655     size_t i;
656     for (i = 0; i<m_p->m_ports.size(); i++)
657     {
658         // create a PDU assoc object (one per yf::FrontendNet::ZAssocServer)
659         yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
660         
661         // create ZAssoc with PDU Assoc
662         m_p->az[i] = new yf::FrontendNet::ZAssocServer(
663             as, m_p->m_ports[i].route, m_p.get());
664         if (m_p->az[i]->server(m_p->m_ports[i].port.c_str()))
665         {
666             throw yf::FilterException("Unable to bind to address " 
667                                       + std::string(m_p->m_ports[i].port));
668         }
669     }
670 }
671
672 void yf::FrontendNet::set_listen_duration(int d)
673 {
674     m_p->m_listen_duration = d;
675 }
676
677 static yf::Base* filter_creator()
678 {
679     return new yf::FrontendNet;
680 }
681
682 extern "C" {
683     struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
684         0,
685         "frontend_net",
686         filter_creator
687     };
688 }
689
690 /*
691  * Local variables:
692  * c-basic-offset: 4
693  * c-file-style: "Stroustrup"
694  * indent-tabs-mode: nil
695  * End:
696  * vim: shiftwidth=4 tabstop=8 expandtab
697  */
698