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