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