frontend_net: refactor scope of helper classes
[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             int m_no_threads;
53             std::vector<Port> m_ports;
54             int m_listen_duration;
55             int m_session_timeout;
56             int m_connect_max;
57             std::string m_msg_config;
58             yazpp_1::SocketManager mySocketManager;
59             ZAssocServer **az;
60         };
61         class FrontendNet::My_Timer_Thread : public yazpp_1::ISocketObserver {
62         private:
63             yazpp_1::ISocketObservable *m_obs;
64             Pipe m_pipe;
65             bool m_timeout;
66         public:
67             My_Timer_Thread(yazpp_1::ISocketObservable *obs, int duration);
68             void socketNotify(int event);
69             bool timeout();
70         };
71         class FrontendNet::ZAssocChild : public yazpp_1::Z_Assoc {
72         public:
73             ~ZAssocChild();
74             ZAssocChild(yazpp_1::IPDU_Observable *the_PDU_Observable,
75                         mp::ThreadPoolSocketObserver *m_thread_pool_observer,
76                         const mp::Package *package,
77                         std::string route,
78                         const char *msg_config);
79             int m_no_requests;
80             std::string m_route;
81         private:
82             yazpp_1::IPDU_Observer* sessionNotify(
83                 yazpp_1::IPDU_Observable *the_PDU_Observable,
84                 int fd);
85             void recv_GDU(Z_GDU *apdu, int len);
86             
87             void failNotify();
88             void timeoutNotify();
89             void connectNotify();
90         private:
91             mp::ThreadPoolSocketObserver *m_thread_pool_observer;
92             mp::Session m_session;
93             mp::Origin m_origin;
94             bool m_delete_flag;
95             const mp::Package *m_package;
96             const char *m_msg_config;
97         };
98         class FrontendNet::ThreadPoolPackage : public mp::IThreadPoolMsg {
99         public:
100             ThreadPoolPackage(mp::Package *package,
101                               yf::FrontendNet::ZAssocChild *ses,
102                               const char *msg_config);
103             ~ThreadPoolPackage();
104             IThreadPoolMsg *handle();
105             void result(const char *t_info);
106             bool cleanup(void *info);
107         private:
108             yaz_timing_t timer;
109             ZAssocChild *m_assoc_child;
110             mp::Package *m_package;
111             const char *m_msg_config;        
112         }; 
113         class FrontendNet::ZAssocServer : public yazpp_1::Z_Assoc {
114         public:
115             ~ZAssocServer();
116             ZAssocServer(yazpp_1::IPDU_Observable *PDU_Observable, int timeout,
117                          int connect_max, std::string route,
118                          const char *msg_config);
119             void set_package(const mp::Package *package);
120             void set_thread_pool(ThreadPoolSocketObserver *m_thread_pool_observer);
121         private:
122             yazpp_1::IPDU_Observer* sessionNotify(
123                 yazpp_1::IPDU_Observable *the_PDU_Observable,
124                 int fd);
125             void recv_GDU(Z_GDU *apdu, int len);
126             
127             void failNotify();
128             void timeoutNotify();
129             void connectNotify();
130         private:
131             mp::ThreadPoolSocketObserver *m_thread_pool_observer;
132             const mp::Package *m_package;
133             int m_session_timeout;
134             int m_connect_max;
135             yazpp_1::LimitConnect limit_connect;
136             std::string m_route;
137             const char *m_msg_config;
138         };
139     }
140 }
141
142 yf::FrontendNet::ThreadPoolPackage::ThreadPoolPackage(mp::Package *package,
143                                                       ZAssocChild *ses,
144                                                       const char *msg_config) :
145     m_assoc_child(ses), m_package(package), m_msg_config(msg_config)
146 {
147     if (msg_config)
148         timer = yaz_timing_create();
149     else
150         timer = 0;
151 }
152
153 yf::FrontendNet::ThreadPoolPackage::~ThreadPoolPackage()
154 {
155     yaz_timing_destroy(&timer); // timer may be NULL
156     delete m_package;
157 }
158
159 bool yf::FrontendNet::ThreadPoolPackage::cleanup(void *info)
160 {
161     mp::Session *ses = (mp::Session *) info;
162
163     return *ses == m_package->session();
164 }
165
166 void yf::FrontendNet::ThreadPoolPackage::result(const char *t_info)
167 {
168     m_assoc_child->m_no_requests--;
169
170     yazpp_1::GDU *gdu = &m_package->response();
171
172     if (gdu->get())
173     {
174         int len;
175         m_assoc_child->send_GDU(gdu->get(), &len);
176     }
177     else if (!m_package->session().is_closed())
178     {
179         // no response package and yet the session is still open..
180         // means that request is unhandled..
181         yazpp_1::GDU *gdu_req = &m_package->request();
182         Z_GDU *z_gdu = gdu_req->get();
183         if (z_gdu && z_gdu->which == Z_GDU_Z3950)
184         {
185             // For Z39.50, response with a Close and shutdown
186             mp::odr odr;
187             int len;
188             Z_APDU *apdu_response = odr.create_close(
189                 z_gdu->u.z3950, Z_Close_systemProblem, 
190                 "unhandled Z39.50 request");
191
192             m_assoc_child->send_Z_PDU(apdu_response, &len);
193         }
194         else if (z_gdu && z_gdu->which == Z_GDU_HTTP_Request)
195         {
196             // For HTTP, respond with Server Error
197             int len;
198             mp::odr odr;
199             Z_GDU *zgdu_res 
200                 = odr.create_HTTP_Response(m_package->session(), 
201                                            z_gdu->u.HTTP_Request, 500);
202             m_assoc_child->send_GDU(zgdu_res, &len);
203         }
204         m_package->session().close();
205     }
206
207     if (m_assoc_child->m_no_requests == 0 && m_package->session().is_closed())
208     {
209         m_assoc_child->close();
210     }
211
212     if (m_msg_config)
213     {
214         yaz_timing_stop(timer);
215         double duration = yaz_timing_get_real(timer);
216         Z_GDU *z_gdu = gdu->get();
217
218         std::ostringstream os;
219         os  << m_msg_config << " "
220             << *m_package << " "
221             << std::fixed << std::setprecision (6) << duration << " ";
222
223         if (z_gdu) 
224             os << *z_gdu;
225         else
226             os << "-";
227         
228         yaz_log(YLOG_LOG, "%s %s", os.str().c_str(), t_info);
229     }
230
231     delete this;
232 }
233
234 mp::IThreadPoolMsg *yf::FrontendNet::ThreadPoolPackage::handle() 
235 {
236     m_package->move(m_assoc_child->m_route);
237     return this;
238 }
239
240
241 yf::FrontendNet::ZAssocChild::ZAssocChild(
242     yazpp_1::IPDU_Observable *PDU_Observable,
243     mp::ThreadPoolSocketObserver *my_thread_pool,
244     const mp::Package *package,
245     std::string route,
246     const char *msg_config)
247     :  Z_Assoc(PDU_Observable), m_msg_config(msg_config)
248 {
249     m_thread_pool_observer = my_thread_pool;
250     m_no_requests = 0;
251     m_delete_flag = false;
252     m_package = package;
253     m_route = route;
254     const char *peername = PDU_Observable->getpeername();
255     if (!peername)
256         peername = "unknown";
257     m_origin.set_tcpip_address(std::string(peername), m_session.id());
258 }
259
260
261 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocChild::sessionNotify(
262     yazpp_1::IPDU_Observable
263     *the_PDU_Observable, int fd)
264 {
265     return 0;
266 }
267
268 yf::FrontendNet::ZAssocChild::~ZAssocChild()
269 {
270 }
271
272 void yf::FrontendNet::ZAssocChild::recv_GDU(Z_GDU *z_pdu, int len)
273 {
274     m_no_requests++;
275
276     mp::Package *p = new mp::Package(m_session, m_origin);
277
278     ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_msg_config);
279     p->copy_route(*m_package);
280     p->request() = yazpp_1::GDU(z_pdu);
281
282     if (m_msg_config)
283     {
284         if (z_pdu)          
285         {
286             std::ostringstream os;
287             os  << m_msg_config << " "
288                 << *p << " "
289                 << "0.000000" << " " 
290                 << *z_pdu;
291             yaz_log(YLOG_LOG, "%s", os.str().c_str());
292         }
293     }
294     m_thread_pool_observer->put(tp);  
295 }
296
297 void yf::FrontendNet::ZAssocChild::failNotify()
298 {
299     // TODO: send Package to signal "close"
300     if (m_session.is_closed())
301     {
302         if (m_no_requests == 0)
303             delete this;
304         return;
305     }
306     m_no_requests++;
307
308     m_session.close();
309
310     mp::Package *p = new mp::Package(m_session, m_origin);
311
312     ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_msg_config);
313     p->copy_route(*m_package);
314     m_thread_pool_observer->cleanup(tp, &m_session);
315     m_thread_pool_observer->put(tp);
316 }
317
318 void yf::FrontendNet::ZAssocChild::timeoutNotify()
319 {
320     failNotify();
321 }
322
323 void yf::FrontendNet::ZAssocChild::connectNotify()
324 {
325
326 }
327
328 yf::FrontendNet::ZAssocServer::ZAssocServer(
329     yazpp_1::IPDU_Observable *PDU_Observable,
330     int timeout, int connect_max,
331     std::string route, const char *msg_config)
332     : 
333     Z_Assoc(PDU_Observable), m_session_timeout(timeout),
334     m_connect_max(connect_max), m_route(route), m_msg_config(msg_config)
335 {
336     m_package = 0;
337 }
338
339
340 void yf::FrontendNet::ZAssocServer::set_package(const mp::Package *package)
341 {
342     m_package = package;
343 }
344
345 void yf::FrontendNet::ZAssocServer::set_thread_pool(ThreadPoolSocketObserver *observer)
346 {
347     m_thread_pool_observer = observer;
348 }
349
350 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocServer::sessionNotify(yazpp_1::IPDU_Observable
351                                                  *the_PDU_Observable, int fd)
352 {
353
354     const char *peername = the_PDU_Observable->getpeername();
355     if (peername)
356     {
357         limit_connect.add_connect(peername);
358         limit_connect.cleanup(false);
359         int con_sz = limit_connect.get_total(peername);
360         if (m_connect_max && con_sz > m_connect_max)
361             return 0;
362     }
363     ZAssocChild *my = new ZAssocChild(the_PDU_Observable,
364                                       m_thread_pool_observer,
365                                       m_package, m_route, m_msg_config);
366     my->timeout(m_session_timeout);
367     return my;
368 }
369
370 yf::FrontendNet::ZAssocServer::~ZAssocServer()
371 {
372 }
373
374 void yf::FrontendNet::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
375 {
376 }
377
378 void yf::FrontendNet::ZAssocServer::failNotify()
379 {
380 }
381
382 void yf::FrontendNet::ZAssocServer::timeoutNotify()
383 {
384 }
385
386 void yf::FrontendNet::ZAssocServer::connectNotify()
387 {
388 }
389
390 yf::FrontendNet::FrontendNet() : m_p(new Rep)
391 {
392     m_p->m_no_threads = 5;
393     m_p->m_listen_duration = 0;
394     m_p->m_session_timeout = 300; // 5 minutes
395     m_p->m_connect_max = 0;
396     m_p->az = 0;
397 }
398
399 yf::FrontendNet::~FrontendNet()
400 {
401     if (m_p->az)
402     {
403         size_t i;
404         for (i = 0; i<m_p->m_ports.size(); i++)
405             delete m_p->az[i];
406         delete [] m_p->az;
407     }
408     m_p->az = 0;
409 }
410
411 void yf::FrontendNet::stop() const
412 {
413     if (m_p->az)
414     {
415         size_t i;
416         for (i = 0; i<m_p->m_ports.size(); i++)
417             m_p->az[i]->server("");
418     }
419 }
420
421 bool yf::FrontendNet::My_Timer_Thread::timeout()
422 {
423     return m_timeout;
424 }
425
426 yf::FrontendNet::My_Timer_Thread::My_Timer_Thread(
427     yazpp_1::ISocketObservable *obs,
428     int duration) : 
429     m_obs(obs), m_pipe(9123), m_timeout(false)
430 {
431     obs->addObserver(m_pipe.read_fd(), this);
432     obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
433     obs->timeoutObserver(this, duration);
434 }
435
436 void yf::FrontendNet::My_Timer_Thread::socketNotify(int event)
437 {
438     m_timeout = true;
439     m_obs->deleteObserver(this);
440 }
441
442 void yf::FrontendNet::process(Package &package) const
443 {
444     if (m_p->az == 0)
445         return;
446     size_t i;
447     My_Timer_Thread *tt = 0;
448
449     if (m_p->m_listen_duration)
450         tt = new My_Timer_Thread(&m_p->mySocketManager,
451                                  m_p->m_listen_duration);
452     
453     ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads);
454
455     for (i = 0; i<m_p->m_ports.size(); i++)
456     {
457         m_p->az[i]->set_package(&package);
458         m_p->az[i]->set_thread_pool(&tp);
459     }
460     while (m_p->mySocketManager.processEvent() > 0)
461     {
462         int no = m_p->mySocketManager.getNumberOfObservers();
463         if (no <= 1)
464             break;
465         if (tt && tt->timeout())
466             break;
467     }
468     delete tt;
469 }
470
471 void yf::FrontendNet::configure(const xmlNode * ptr, bool test_only,
472                                 const char *path)
473 {
474     if (!ptr || !ptr->children)
475     {
476         throw yf::FilterException("No ports for Frontend");
477     }
478     std::vector<Port> ports;
479     for (ptr = ptr->children; ptr; ptr = ptr->next)
480     {
481         if (ptr->type != XML_ELEMENT_NODE)
482             continue;
483         if (!strcmp((const char *) ptr->name, "port"))
484         {
485             Port port;
486             const struct _xmlAttr *attr;
487             for (attr = ptr->properties; attr; attr = attr->next)
488             {
489                 if (!strcmp((const char *) attr->name, "route"))
490                     port.route = mp::xml::get_text(attr);
491             }
492             port.port = mp::xml::get_text(ptr);
493             ports.push_back(port);
494             
495         }
496         else if (!strcmp((const char *) ptr->name, "threads"))
497         {
498             std::string threads_str = mp::xml::get_text(ptr);
499             int threads = atoi(threads_str.c_str());
500             if (threads < 1)
501                 throw yf::FilterException("Bad value for threads: " 
502                                                    + threads_str);
503             m_p->m_no_threads = threads;
504         }
505         else if (!strcmp((const char *) ptr->name, "timeout"))
506         {
507             std::string timeout_str = mp::xml::get_text(ptr);
508             int timeout = atoi(timeout_str.c_str());
509             if (timeout < 1)
510                 throw yf::FilterException("Bad value for timeout: " 
511                                                    + timeout_str);
512             m_p->m_session_timeout = timeout;
513         }
514         else if (!strcmp((const char *) ptr->name, "connect-max"))
515         {
516             m_p->m_connect_max = mp::xml::get_int(ptr, 0);
517         }
518         else if (!strcmp((const char *) ptr->name, "message"))
519         {
520             m_p->m_msg_config = mp::xml::get_text(ptr);
521         }
522         else
523         {
524             throw yf::FilterException("Bad element " 
525                                       + std::string((const char *)
526                                                     ptr->name));
527         }
528     }
529     if (test_only)
530         return;
531     set_ports(ports);
532 }
533
534 void yf::FrontendNet::set_ports(std::vector<std::string> &ports)
535 {
536     std::vector<Port> nports;
537     size_t i;
538
539     for (i = 0; i < ports.size(); i++)
540     {
541         Port nport;
542
543         nport.port = ports[i];
544
545         nports.push_back(nport);
546     }
547     set_ports(nports);
548 }
549
550
551 void yf::FrontendNet::set_ports(std::vector<Port> &ports)
552 {
553     m_p->m_ports = ports;
554     
555     m_p->az = new yf::FrontendNet::ZAssocServer *[m_p->m_ports.size()];
556     
557     // Create yf::FrontendNet::ZAssocServer for each port
558     size_t i;
559     for (i = 0; i<m_p->m_ports.size(); i++)
560     {
561         // create a PDU assoc object (one per yf::FrontendNet::ZAssocServer)
562         yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
563         
564         // create ZAssoc with PDU Assoc
565         m_p->az[i] = new yf::FrontendNet::ZAssocServer(as, 
566                                           m_p->m_session_timeout,
567                                           m_p->m_connect_max,
568                                           m_p->m_ports[i].route,
569                                           m_p->m_msg_config.length() > 0 ?
570                                           m_p->m_msg_config.c_str() : 0);
571         if (m_p->az[i]->server(m_p->m_ports[i].port.c_str()))
572         {
573             throw yf::FilterException("Unable to bind to address " 
574                                       + std::string(m_p->m_ports[i].port));
575         }
576     }
577 }
578
579 void yf::FrontendNet::set_listen_duration(int d)
580 {
581     m_p->m_listen_duration = d;
582 }
583
584 static yf::Base* filter_creator()
585 {
586     return new yf::FrontendNet;
587 }
588
589 extern "C" {
590     struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
591         0,
592         "frontend_net",
593         filter_creator
594     };
595 }
596
597 /*
598  * Local variables:
599  * c-basic-offset: 4
600  * c-file-style: "Stroustrup"
601  * indent-tabs-mode: nil
602  * End:
603  * vim: shiftwidth=4 tabstop=8 expandtab
604  */
605