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