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