frontend_net: add facility to log 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         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             
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::recv_GDU(Z_GDU *z_pdu, int len)
279 {
280     m_no_requests++;
281
282     mp::Package *p = new mp::Package(m_session, m_origin);
283
284     if (z_pdu && z_pdu->which == Z_GDU_HTTP_Request)
285     {
286         Z_HTTP_Request *hreq = z_pdu->u.HTTP_Request;
287
288         if (m_p->m_stat_req.length()
289             && !strcmp(hreq->path, m_p->m_stat_req.c_str()))
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 mintime=\"%f\" "
313                         "maxtime=\"%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 mintime=\"%f\" frequency=\"%d\"/>\n",
321                     m_p->m_duration_lim[i - 1], m_p->m_duration_freq[i]);
322             wrbuf_puts(w, " </responses>\n");
323             wrbuf_puts(w, "</frontend_net>\n");
324
325             hres->content_len = w.len();
326             hres->content_buf = (char *) w.buf();
327             
328             int len;
329             send_GDU(gdu_res, &len);
330             return;
331         }
332     }
333
334     ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
335     p->copy_route(*m_package);
336     p->request() = yazpp_1::GDU(z_pdu);
337
338     if (m_p->m_msg_config.length())
339     {
340         if (z_pdu)          
341         {
342             std::ostringstream os;
343             os  << m_p->m_msg_config << " "
344                 << *p << " "
345                 << "0.000000" << " " 
346                 << *z_pdu;
347             yaz_log(YLOG_LOG, "%s", os.str().c_str());
348         }
349     }
350     m_thread_pool_observer->put(tp);  
351 }
352
353 void yf::FrontendNet::ZAssocChild::failNotify()
354 {
355     // TODO: send Package to signal "close"
356     if (m_session.is_closed())
357     {
358         if (m_no_requests == 0)
359             delete this;
360         return;
361     }
362     m_no_requests++;
363
364     m_session.close();
365
366     mp::Package *p = new mp::Package(m_session, m_origin);
367
368     ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
369     p->copy_route(*m_package);
370     m_thread_pool_observer->cleanup(tp, &m_session);
371     m_thread_pool_observer->put(tp);
372 }
373
374 void yf::FrontendNet::ZAssocChild::timeoutNotify()
375 {
376     failNotify();
377 }
378
379 void yf::FrontendNet::ZAssocChild::connectNotify()
380 {
381
382 }
383
384 yf::FrontendNet::ZAssocServer::ZAssocServer(
385     yazpp_1::IPDU_Observable *PDU_Observable,
386     std::string route,
387     Rep *rep)
388     : 
389     Z_Assoc(PDU_Observable), m_route(route), m_p(rep)
390 {
391     m_package = 0;
392 }
393
394
395 void yf::FrontendNet::ZAssocServer::set_package(const mp::Package *package)
396 {
397     m_package = package;
398 }
399
400 void yf::FrontendNet::ZAssocServer::set_thread_pool(
401     ThreadPoolSocketObserver *observer)
402 {
403     m_thread_pool_observer = observer;
404 }
405
406 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocServer::sessionNotify(
407     yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
408 {
409
410     const char *peername = the_PDU_Observable->getpeername();
411     if (peername)
412     {
413         limit_connect.add_connect(peername);
414         limit_connect.cleanup(false);
415         int con_sz = limit_connect.get_total(peername);
416         if (m_p->m_connect_max && con_sz > m_p->m_connect_max)
417             return 0;
418     }
419     ZAssocChild *my = new ZAssocChild(the_PDU_Observable,
420                                       m_thread_pool_observer,
421                                       m_package, m_route, m_p);
422     return my;
423 }
424
425 yf::FrontendNet::ZAssocServer::~ZAssocServer()
426 {
427 }
428
429 void yf::FrontendNet::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
430 {
431 }
432
433 void yf::FrontendNet::ZAssocServer::failNotify()
434 {
435 }
436
437 void yf::FrontendNet::ZAssocServer::timeoutNotify()
438 {
439 }
440
441 void yf::FrontendNet::ZAssocServer::connectNotify()
442 {
443 }
444
445 yf::FrontendNet::FrontendNet() : m_p(new Rep)
446 {
447 }
448
449 yf::FrontendNet::Rep::Rep()
450 {
451     m_no_threads = 5;
452     m_listen_duration = 0;
453     m_session_timeout = 300; // 5 minutes
454     m_connect_max = 0;
455     az = 0;
456     size_t i;
457     for (i = 0; i < 22; i++)
458         m_duration_freq[i] = 0;
459     m_duration_lim[0] = 0.000001;
460     m_duration_lim[1] = 0.00001;
461     m_duration_lim[2] = 0.0001;
462     m_duration_lim[3] = 0.001;
463     m_duration_lim[4] = 0.01;
464     m_duration_lim[5] = 0.1;
465     m_duration_lim[6] = 0.2;
466     m_duration_lim[7] = 0.3;
467     m_duration_lim[8] = 0.5;
468     m_duration_lim[9] = 1.0;
469     m_duration_lim[10] = 1.5;
470     m_duration_lim[11] = 2.0;
471     m_duration_lim[12] = 3.0;
472     m_duration_lim[13] = 4.0;
473     m_duration_lim[14] = 5.0;
474     m_duration_lim[15] = 6.0;
475     m_duration_lim[16] = 8.0;
476     m_duration_lim[17] = 10.0;
477     m_duration_lim[18] = 15.0;
478     m_duration_lim[19] = 20.0;
479     m_duration_lim[20] = 30.0;
480     m_duration_lim[21] = 0;
481 }
482
483
484 yf::FrontendNet::Rep::~Rep()
485 {
486     if (az)
487     {
488         size_t i;
489         for (i = 0; i < m_ports.size(); i++)
490             delete az[i];
491         delete [] az;
492     }
493     az = 0;
494 }
495     
496 yf::FrontendNet::~FrontendNet()
497 {
498 }
499
500 void yf::FrontendNet::stop() const
501 {
502     if (m_p->az)
503     {
504         size_t i;
505         for (i = 0; i < m_p->m_ports.size(); i++)
506             m_p->az[i]->server("");
507     }
508 }
509
510 bool yf::FrontendNet::My_Timer_Thread::timeout()
511 {
512     return m_timeout;
513 }
514
515 yf::FrontendNet::My_Timer_Thread::My_Timer_Thread(
516     yazpp_1::ISocketObservable *obs,
517     int duration) : 
518     m_obs(obs), m_pipe(9123), m_timeout(false)
519 {
520     obs->addObserver(m_pipe.read_fd(), this);
521     obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
522     obs->timeoutObserver(this, duration);
523 }
524
525 void yf::FrontendNet::My_Timer_Thread::socketNotify(int event)
526 {
527     m_timeout = true;
528     m_obs->deleteObserver(this);
529 }
530
531 void yf::FrontendNet::process(Package &package) const
532 {
533     if (m_p->az == 0)
534         return;
535     size_t i;
536     My_Timer_Thread *tt = 0;
537
538     if (m_p->m_listen_duration)
539         tt = new My_Timer_Thread(&m_p->mySocketManager,
540                                  m_p->m_listen_duration);
541     
542     ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads);
543
544     for (i = 0; i<m_p->m_ports.size(); i++)
545     {
546         m_p->az[i]->set_package(&package);
547         m_p->az[i]->set_thread_pool(&tp);
548     }
549     while (m_p->mySocketManager.processEvent() > 0)
550     {
551         int no = m_p->mySocketManager.getNumberOfObservers();
552         if (no <= 1)
553             break;
554         if (tt && tt->timeout())
555             break;
556     }
557     delete tt;
558 }
559
560 void yf::FrontendNet::configure(const xmlNode * ptr, bool test_only,
561                                 const char *path)
562 {
563     if (!ptr || !ptr->children)
564     {
565         throw yf::FilterException("No ports for Frontend");
566     }
567     std::vector<Port> ports;
568     for (ptr = ptr->children; ptr; ptr = ptr->next)
569     {
570         if (ptr->type != XML_ELEMENT_NODE)
571             continue;
572         if (!strcmp((const char *) ptr->name, "port"))
573         {
574             Port port;
575             const struct _xmlAttr *attr;
576             for (attr = ptr->properties; attr; attr = attr->next)
577             {
578                 if (!strcmp((const char *) attr->name, "route"))
579                     port.route = mp::xml::get_text(attr);
580             }
581             port.port = mp::xml::get_text(ptr);
582             ports.push_back(port);
583             
584         }
585         else if (!strcmp((const char *) ptr->name, "threads"))
586         {
587             std::string threads_str = mp::xml::get_text(ptr);
588             int threads = atoi(threads_str.c_str());
589             if (threads < 1)
590                 throw yf::FilterException("Bad value for threads: " 
591                                                    + threads_str);
592             m_p->m_no_threads = threads;
593         }
594         else if (!strcmp((const char *) ptr->name, "timeout"))
595         {
596             std::string timeout_str = mp::xml::get_text(ptr);
597             int timeout = atoi(timeout_str.c_str());
598             if (timeout < 1)
599                 throw yf::FilterException("Bad value for timeout: " 
600                                                    + timeout_str);
601             m_p->m_session_timeout = timeout;
602         }
603         else if (!strcmp((const char *) ptr->name, "connect-max"))
604         {
605             m_p->m_connect_max = mp::xml::get_int(ptr, 0);
606         }
607         else if (!strcmp((const char *) ptr->name, "message"))
608         {
609             m_p->m_msg_config = mp::xml::get_text(ptr);
610         }
611         else if (!strcmp((const char *) ptr->name, "stat-req"))
612         {
613             m_p->m_stat_req = mp::xml::get_text(ptr);
614         }
615         else
616         {
617             throw yf::FilterException("Bad element " 
618                                       + std::string((const char *)
619                                                     ptr->name));
620         }
621     }
622     if (test_only)
623         return;
624     set_ports(ports);
625 }
626
627 void yf::FrontendNet::set_ports(std::vector<std::string> &ports)
628 {
629     std::vector<Port> nports;
630     size_t i;
631
632     for (i = 0; i < ports.size(); i++)
633     {
634         Port nport;
635
636         nport.port = ports[i];
637
638         nports.push_back(nport);
639     }
640     set_ports(nports);
641 }
642
643
644 void yf::FrontendNet::set_ports(std::vector<Port> &ports)
645 {
646     m_p->m_ports = ports;
647     
648     m_p->az = new yf::FrontendNet::ZAssocServer *[m_p->m_ports.size()];
649     
650     // Create yf::FrontendNet::ZAssocServer for each port
651     size_t i;
652     for (i = 0; i<m_p->m_ports.size(); i++)
653     {
654         // create a PDU assoc object (one per yf::FrontendNet::ZAssocServer)
655         yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
656         
657         // create ZAssoc with PDU Assoc
658         m_p->az[i] = new yf::FrontendNet::ZAssocServer(
659             as, m_p->m_ports[i].route, m_p.get());
660         if (m_p->az[i]->server(m_p->m_ports[i].port.c_str()))
661         {
662             throw yf::FilterException("Unable to bind to address " 
663                                       + std::string(m_p->m_ports[i].port));
664         }
665     }
666 }
667
668 void yf::FrontendNet::set_listen_duration(int d)
669 {
670     m_p->m_listen_duration = d;
671 }
672
673 static yf::Base* filter_creator()
674 {
675     return new yf::FrontendNet;
676 }
677
678 extern "C" {
679     struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
680         0,
681         "frontend_net",
682         filter_creator
683     };
684 }
685
686 /*
687  * Local variables:
688  * c-basic-offset: 4
689  * c-file-style: "Stroustrup"
690  * indent-tabs-mode: nil
691  * End:
692  * vim: shiftwidth=4 tabstop=8 expandtab
693  */
694