1 /* This file is part of Metaproxy.
2 Copyright (C) Index Data
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
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
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
22 #include <sys/resource.h>
26 #include <metaproxy/util.hpp>
28 #include <metaproxy/filter.hpp>
29 #include <metaproxy/package.hpp>
30 #include "thread_pool_observer.hpp"
31 #include "filter_frontend_net.hpp"
32 #include <yazpp/z-assoc.h>
33 #include <yazpp/pdu-assoc.h>
34 #include <yazpp/socket-manager.h>
35 #include <yazpp/limit-connect.h>
36 #include <yaz/timing.h>
38 #include <yaz/daemon.h>
39 #include "gduutil.hpp"
44 namespace mp = metaproxy_1;
45 namespace yf = metaproxy_1::filter;
47 namespace metaproxy_1 {
49 class FrontendNet::Port {
51 friend class FrontendNet;
54 std::string cert_fname;
57 class FrontendNet::IP_Pattern {
59 friend class FrontendNet;
64 class FrontendNet::Rep {
65 friend class FrontendNet;
70 std::vector<Port> m_ports;
71 int m_listen_duration;
72 int m_session_timeout;
73 std::list<IP_Pattern> connect_max;
74 std::list<IP_Pattern> http_req_max;
75 std::string m_msg_config;
76 std::string m_stat_req;
77 yazpp_1::SocketManager mySocketManager;
79 yazpp_1::PDU_Assoc **pdu;
80 int m_duration_freq[22];
81 double m_duration_lim[22];
82 double m_duration_max;
83 double m_duration_min;
84 double m_duration_total;
90 class FrontendNet::My_Timer_Thread : public yazpp_1::ISocketObserver {
92 yazpp_1::ISocketObservable *m_obs;
96 My_Timer_Thread(yazpp_1::ISocketObservable *obs, int duration);
97 void socketNotify(int event);
100 class FrontendNet::ZAssocChild : public yazpp_1::Z_Assoc {
103 ZAssocChild(yazpp_1::IPDU_Observable *the_PDU_Observable,
104 mp::ThreadPoolSocketObserver *m_thread_pool_observer,
105 const mp::Package *package,
108 yazpp_1::LimitConnect &limit,
109 const char *peername);
113 yazpp_1::IPDU_Observer* sessionNotify(
114 yazpp_1::IPDU_Observable *the_PDU_Observable,
116 void recv_GDU(Z_GDU *apdu, int len);
117 void report(Z_HTTP_Request *hreq);
119 void timeoutNotify();
120 void connectNotify();
122 mp::ThreadPoolSocketObserver *m_thread_pool_observer;
123 mp::Session m_session;
126 const mp::Package *m_package;
128 yazpp_1::LimitConnect &m_limit_http_req;
130 class FrontendNet::ThreadPoolPackage : public mp::IThreadPoolMsg {
132 ThreadPoolPackage(mp::Package *package,
133 yf::FrontendNet::ZAssocChild *ses,
135 ~ThreadPoolPackage();
136 IThreadPoolMsg *handle();
137 void result(const char *t_info);
138 bool cleanup(void *info);
141 ZAssocChild *m_assoc_child;
142 mp::Package *m_package;
145 class FrontendNet::ZAssocServer : public yazpp_1::Z_Assoc {
148 ZAssocServer(yazpp_1::IPDU_Observable *PDU_Observable,
149 FrontendNet::Port *port,
151 void set_package(const mp::Package *package);
152 void set_thread_pool(ThreadPoolSocketObserver *observer);
154 yazpp_1::IPDU_Observer* sessionNotify(
155 yazpp_1::IPDU_Observable *the_PDU_Observable,
157 void recv_GDU(Z_GDU *apdu, int len);
160 void timeoutNotify();
161 void connectNotify();
163 mp::ThreadPoolSocketObserver *m_thread_pool_observer;
164 const mp::Package *m_package;
165 yazpp_1::LimitConnect limit_connect;
166 yazpp_1::LimitConnect limit_http_req;
173 yf::FrontendNet::ThreadPoolPackage::ThreadPoolPackage(mp::Package *package,
176 m_assoc_child(ses), m_package(package), m_p(rep)
178 timer = yaz_timing_create();
181 yf::FrontendNet::ThreadPoolPackage::~ThreadPoolPackage()
183 yaz_timing_destroy(&timer); // timer may be NULL
187 bool yf::FrontendNet::ThreadPoolPackage::cleanup(void *info)
189 mp::Session *ses = (mp::Session *) info;
191 return *ses == m_package->session();
194 void yf::FrontendNet::ThreadPoolPackage::result(const char *t_info)
196 m_assoc_child->m_no_requests--;
198 yazpp_1::GDU *gdu = &m_package->response();
203 m_assoc_child->send_GDU(gdu->get(), &len);
205 yaz_timing_stop(timer);
206 double duration = yaz_timing_get_real(timer);
209 while (m_p->m_duration_lim[ent] != 0.0 && duration > m_p->m_duration_lim[ent])
211 m_p->m_duration_freq[ent]++;
213 m_p->m_duration_total += duration;
215 if (m_p->m_duration_max < duration)
216 m_p->m_duration_max = duration;
218 if (m_p->m_duration_min == 0.0 || m_p->m_duration_min > duration)
219 m_p->m_duration_min = duration;
221 if (m_p->m_msg_config.length())
223 Z_GDU *z_gdu = gdu->get();
225 std::ostringstream os;
226 os << m_p->m_msg_config << " "
228 << std::fixed << std::setprecision (6) << duration << " ";
235 yaz_log(YLOG_LOG, "%s %s", os.str().c_str(), t_info);
238 else if (!m_package->session().is_closed())
240 // no response package and yet the session is still open..
241 // means that request is unhandled..
242 yazpp_1::GDU *gdu_req = &m_package->request();
243 Z_GDU *z_gdu = gdu_req->get();
244 if (z_gdu && z_gdu->which == Z_GDU_Z3950)
246 // For Z39.50, response with a Close and shutdown
249 Z_APDU *apdu_response = odr.create_close(
250 z_gdu->u.z3950, Z_Close_systemProblem,
251 "unhandled Z39.50 request");
253 m_assoc_child->send_Z_PDU(apdu_response, &len);
255 else if (z_gdu && z_gdu->which == Z_GDU_HTTP_Request)
257 // For HTTP, respond with Server Error
261 = odr.create_HTTP_Response(m_package->session(),
262 z_gdu->u.HTTP_Request, 500);
263 m_assoc_child->send_GDU(zgdu_res, &len);
265 m_package->session().close();
268 if (m_assoc_child->m_no_requests == 0 && m_package->session().is_closed())
270 m_assoc_child->close();
277 mp::IThreadPoolMsg *yf::FrontendNet::ThreadPoolPackage::handle()
279 m_package->move(m_assoc_child->m_port->route);
283 yf::FrontendNet::ZAssocChild::ZAssocChild(
284 yazpp_1::IPDU_Observable *PDU_Observable,
285 mp::ThreadPoolSocketObserver *my_thread_pool,
286 const mp::Package *package,
287 Port *port, Rep *rep,
288 yazpp_1::LimitConnect &limit_http_req,
289 const char *peername)
290 : Z_Assoc(PDU_Observable), m_p(rep), m_limit_http_req(limit_http_req)
292 m_thread_pool_observer = my_thread_pool;
294 m_delete_flag = false;
298 addr.append(peername);
300 addr.append(port->port);
301 m_origin.set_tcpip_address(addr, m_session.id());
302 timeout(m_p->m_session_timeout);
305 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocChild::sessionNotify(
306 yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
311 yf::FrontendNet::ZAssocChild::~ZAssocChild()
315 void yf::FrontendNet::ZAssocChild::report(Z_HTTP_Request *hreq)
319 Z_GDU *gdu_res = o.create_HTTP_Response(m_session, hreq, 200);
321 Z_HTTP_Response *hres = gdu_res->u.HTTP_Response;
325 int number_total = 0;
327 for (i = 0; m_p->m_duration_lim[i] != 0.0; i++)
328 number_total += m_p->m_duration_freq[i];
329 number_total += m_p->m_duration_freq[i];
331 wrbuf_puts(w, "<?xml version=\"1.0\"?>\n");
332 wrbuf_puts(w, "<frontend_net>\n");
333 wrbuf_printf(w, " <responses frequency=\"%d\">\n", number_total);
334 for (i = 0; m_p->m_duration_lim[i] != 0.0; i++)
336 if (m_p->m_duration_freq[i] > 0)
338 w, " <response duration_start=\"%f\" "
339 "duration_end=\"%f\" frequency=\"%d\"/>\n",
340 i > 0 ? m_p->m_duration_lim[i - 1] : 0.0,
341 m_p->m_duration_lim[i], m_p->m_duration_freq[i]);
344 if (m_p->m_duration_freq[i] > 0)
346 w, " <response duration_start=\"%f\" frequency=\"%d\"/>\n",
347 m_p->m_duration_lim[i - 1], m_p->m_duration_freq[i]);
349 if (m_p->m_duration_max != 0.0)
351 w, " <response duration_max=\"%f\"/>\n",
352 m_p->m_duration_max);
353 if (m_p->m_duration_min != 0.0)
355 w, " <response duration_min=\"%f\"/>\n",
356 m_p->m_duration_min);
357 if (m_p->m_duration_total != 0.0)
359 w, " <response duration_average=\"%f\"/>\n",
360 m_p->m_duration_total / number_total);
362 wrbuf_puts(w, " </responses>\n");
366 m_thread_pool_observer->get_thread_info(thread_busy, thread_total);
368 wrbuf_printf(w, " <thread_info busy=\"%d\" total=\"%d\"/>\n",
369 thread_busy, thread_total);
371 wrbuf_puts(w, "</frontend_net>\n");
373 hres->content_len = w.len();
374 hres->content_buf = (char *) w.buf();
377 send_GDU(gdu_res, &len);
380 void yf::FrontendNet::ZAssocChild::recv_GDU(Z_GDU *z_pdu, int len)
384 mp::Package *p = new mp::Package(m_session, m_origin);
386 if (z_pdu && z_pdu->which == Z_GDU_HTTP_Request)
388 Z_HTTP_Request *hreq = z_pdu->u.HTTP_Request;
390 const char *f = z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
392 p->origin().set_tcpip_address(std::string(f), m_session.id());
394 if (m_p->m_stat_req.length()
395 && !strcmp(hreq->path, m_p->m_stat_req.c_str()))
403 p->copy_route(*m_package);
404 p->request() = yazpp_1::GDU(z_pdu);
406 if (m_p->m_msg_config.length())
410 std::ostringstream os;
411 os << m_p->m_msg_config << " "
415 yaz_log(YLOG_LOG, "%s", os.str().c_str());
418 if (z_pdu && z_pdu->which == Z_GDU_HTTP_Request)
420 Z_HTTP_Request *hreq = z_pdu->u.HTTP_Request;
421 std::string peername = p->origin().get_address();
423 m_limit_http_req.cleanup(false);
424 int con_sz = m_limit_http_req.get_total(peername.c_str());
425 std::list<IP_Pattern>::const_iterator it = m_p->http_req_max.begin();
426 for (; it != m_p->http_req_max.end(); it++)
428 if (mp::util::match_ip(it->pattern, peername))
430 if (it->verbose > 1 ||
431 (it->value && con_sz >= it->value && it->verbose > 0))
432 yaz_log(YLOG_LOG, "http-req-max pattern=%s ip=%s con_sz=%d value=%d", it->pattern.c_str(), peername.c_str(), con_sz, it->value);
433 if (it->value == 0 || con_sz < it->value)
436 Z_GDU *gdu_res = o.create_HTTP_Response(m_session, hreq, 500);
438 send_GDU(gdu_res, &len);
443 m_limit_http_req.add_connect(peername.c_str());
445 ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
446 m_thread_pool_observer->put(tp);
449 void yf::FrontendNet::ZAssocChild::failNotify()
451 // TODO: send Package to signal "close"
452 if (m_session.is_closed())
454 if (m_no_requests == 0)
462 mp::Package *p = new mp::Package(m_session, m_origin);
464 ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
465 p->copy_route(*m_package);
466 m_thread_pool_observer->cleanup(tp, &m_session);
467 m_thread_pool_observer->put(tp);
470 void yf::FrontendNet::ZAssocChild::timeoutNotify()
475 void yf::FrontendNet::ZAssocChild::connectNotify()
480 yf::FrontendNet::ZAssocServer::ZAssocServer(
481 yazpp_1::IPDU_Observable *PDU_Observable,
485 Z_Assoc(PDU_Observable), m_port(port), m_p(rep)
491 void yf::FrontendNet::ZAssocServer::set_package(const mp::Package *package)
496 void yf::FrontendNet::ZAssocServer::set_thread_pool(
497 mp::ThreadPoolSocketObserver *observer)
499 m_thread_pool_observer = observer;
502 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocServer::sessionNotify(
503 yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
506 const char *peername = the_PDU_Observable->getpeername();
508 peername = "unknown";
511 const char *cp = strchr(peername, ':');
517 limit_connect.cleanup(false);
518 int con_sz = limit_connect.get_total(peername);
519 std::list<IP_Pattern>::const_iterator it = m_p->connect_max.begin();
520 for (; it != m_p->connect_max.end(); it++)
522 if (mp::util::match_ip(it->pattern, peername))
524 if (it->verbose > 1 ||
525 (it->value && con_sz >= it->value && it->verbose > 0))
526 yaz_log(YLOG_LOG, "connect-max pattern=%s ip=%s con_sz=%d value=%d", it->pattern.c_str(), peername, con_sz, it->value);
527 if (it->value == 0 || con_sz < it->value)
532 limit_connect.add_connect(peername);
534 ZAssocChild *my = new ZAssocChild(the_PDU_Observable,
535 m_thread_pool_observer,
536 m_package, m_port, m_p, limit_http_req,
541 yf::FrontendNet::ZAssocServer::~ZAssocServer()
545 void yf::FrontendNet::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
549 void yf::FrontendNet::ZAssocServer::failNotify()
553 void yf::FrontendNet::ZAssocServer::timeoutNotify()
557 void yf::FrontendNet::ZAssocServer::connectNotify()
561 yf::FrontendNet::FrontendNet() : m_p(new Rep)
565 yf::FrontendNet::Rep::Rep()
567 m_max_threads = m_no_threads = 5;
569 m_listen_duration = 0;
570 m_session_timeout = 300; // 5 minutes
573 for (i = 0; i < 22; i++)
574 m_duration_freq[i] = 0;
575 m_duration_lim[0] = 0.000001;
576 m_duration_lim[1] = 0.00001;
577 m_duration_lim[2] = 0.0001;
578 m_duration_lim[3] = 0.001;
579 m_duration_lim[4] = 0.01;
580 m_duration_lim[5] = 0.1;
581 m_duration_lim[6] = 0.2;
582 m_duration_lim[7] = 0.3;
583 m_duration_lim[8] = 0.5;
584 m_duration_lim[9] = 1.0;
585 m_duration_lim[10] = 1.5;
586 m_duration_lim[11] = 2.0;
587 m_duration_lim[12] = 3.0;
588 m_duration_lim[13] = 4.0;
589 m_duration_lim[14] = 5.0;
590 m_duration_lim[15] = 6.0;
591 m_duration_lim[16] = 8.0;
592 m_duration_lim[17] = 10.0;
593 m_duration_lim[18] = 15.0;
594 m_duration_lim[19] = 20.0;
595 m_duration_lim[20] = 30.0;
596 m_duration_lim[21] = 0.0;
597 m_duration_max = 0.0;
598 m_duration_min = 0.0;
599 m_duration_total = 0.0;
603 yf::FrontendNet::Rep::~Rep()
608 for (i = 0; i < m_ports.size(); i++)
616 yf::FrontendNet::~FrontendNet()
620 void yf::FrontendNet::stop(int signo) const
622 m_p->m_stop_signo = signo;
625 void yf::FrontendNet::start() const
628 struct rlimit limit_data;
629 getrlimit(RLIMIT_NOFILE, &limit_data);
630 yaz_log(YLOG_LOG, "getrlimit NOFILE cur=%ld max=%ld",
631 (long) limit_data.rlim_cur, (long) limit_data.rlim_max);
635 bool yf::FrontendNet::My_Timer_Thread::timeout()
640 yf::FrontendNet::My_Timer_Thread::My_Timer_Thread(
641 yazpp_1::ISocketObservable *obs,
643 m_obs(obs), m_pipe(9123), m_timeout(false)
645 obs->addObserver(m_pipe.read_fd(), this);
646 obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
647 obs->timeoutObserver(this, duration);
650 void yf::FrontendNet::My_Timer_Thread::socketNotify(int event)
653 m_obs->deleteObserver(this);
656 void yf::FrontendNet::process(mp::Package &package) const
661 My_Timer_Thread *tt = 0;
663 if (m_p->m_listen_duration)
664 tt = new My_Timer_Thread(&m_p->mySocketManager,
665 m_p->m_listen_duration);
667 ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads,
671 for (i = 0; i<m_p->m_ports.size(); i++)
673 m_p->az[i]->set_package(&package);
674 m_p->az[i]->set_thread_pool(&tp);
676 while (m_p->mySocketManager.processEvent() > 0)
678 if (m_p->m_stop_signo == SIGTERM)
680 yaz_log(YLOG_LOG, "metaproxy received SIGTERM");
684 for (i = 0; i < m_p->m_ports.size(); i++)
686 m_p->pdu[i]->shutdown();
687 m_p->az[i]->server("");
691 break; /* stop right away */
694 if (m_p->m_stop_signo == SIGUSR1)
695 { /* just stop listeners and cont till all sessions are done*/
696 yaz_log(YLOG_LOG, "metaproxy received SIGUSR1");
697 m_p->m_stop_signo = 0;
701 for (i = 0; i < m_p->m_ports.size(); i++)
702 m_p->az[i]->server("");
707 int no = m_p->mySocketManager.getNumberOfObservers();
710 if (tt && tt->timeout())
716 void yf::FrontendNet::configure(const xmlNode * ptr, bool test_only,
719 if (!ptr || !ptr->children)
721 throw yf::FilterException("No ports for Frontend");
723 std::vector<Port> ports;
724 for (ptr = ptr->children; ptr; ptr = ptr->next)
726 if (ptr->type != XML_ELEMENT_NODE)
728 if (!strcmp((const char *) ptr->name, "port"))
732 const char *names[5] = {"route", "max_recv_bytes", "port",
734 std::string values[4];
736 mp::xml::parse_attr(ptr, names, values);
737 port.route = values[0];
738 if (values[1].length() > 0)
739 port.max_recv_bytes = atoi(values[1].c_str());
741 port.max_recv_bytes = 0;
742 if (values[2].length() > 0)
743 port.port = values[2];
745 port.port = mp::xml::get_text(ptr);
746 port.cert_fname = values[3];
747 ports.push_back(port);
749 else if (!strcmp((const char *) ptr->name, "threads"))
751 std::string threads_str = mp::xml::get_text(ptr);
752 int threads = atoi(threads_str.c_str());
754 throw yf::FilterException("Bad value for threads: "
756 m_p->m_no_threads = threads;
758 else if (!strcmp((const char *) ptr->name, "max-threads"))
760 std::string threads_str = mp::xml::get_text(ptr);
761 int threads = atoi(threads_str.c_str());
763 throw yf::FilterException("Bad value for max-threads: "
765 m_p->m_max_threads = threads;
767 else if (!strcmp((const char *) ptr->name, "stack-size"))
769 std::string sz_str = mp::xml::get_text(ptr);
770 int sz = atoi(sz_str.c_str());
772 throw yf::FilterException("Bad value for stack-size: "
774 m_p->m_stack_size = sz * 1024;
776 else if (!strcmp((const char *) ptr->name, "timeout"))
778 std::string timeout_str = mp::xml::get_text(ptr);
779 int timeout = atoi(timeout_str.c_str());
781 throw yf::FilterException("Bad value for timeout: "
783 m_p->m_session_timeout = timeout;
785 else if (!strcmp((const char *) ptr->name, "connect-max"))
787 const char *names[3] = {"ip", "verbose", 0};
788 std::string values[2];
790 mp::xml::parse_attr(ptr, names, values);
792 m.value = mp::xml::get_int(ptr, 0);
793 m.pattern = values[0];
794 m.verbose = values[1].length() ? atoi(values[1].c_str()) : 1;
795 m_p->connect_max.push_back(m);
797 else if (!strcmp((const char *) ptr->name, "http-req-max"))
799 const char *names[3] = {"ip", "verbose", 0};
800 std::string values[2];
802 mp::xml::parse_attr(ptr, names, values);
804 m.value = mp::xml::get_int(ptr, 0);
805 m.pattern = values[0];
806 m.verbose = values[1].length() ? atoi(values[1].c_str()) : 1;
807 m_p->http_req_max.push_back(m);
809 else if (!strcmp((const char *) ptr->name, "message"))
811 m_p->m_msg_config = mp::xml::get_text(ptr);
813 else if (!strcmp((const char *) ptr->name, "stat-req"))
815 m_p->m_stat_req = mp::xml::get_text(ptr);
819 throw yf::FilterException("Bad element "
820 + std::string((const char *)
829 void yf::FrontendNet::set_ports(std::vector<std::string> &ports)
831 std::vector<Port> nports;
834 for (i = 0; i < ports.size(); i++)
838 nport.port = ports[i];
840 nports.push_back(nport);
846 void yf::FrontendNet::set_ports(std::vector<Port> &ports)
848 m_p->m_ports = ports;
850 m_p->az = new yf::FrontendNet::ZAssocServer *[m_p->m_ports.size()];
851 m_p->pdu = new yazpp_1::PDU_Assoc *[m_p->m_ports.size()];
853 // Create yf::FrontendNet::ZAssocServer for each port
855 for (i = 0; i < m_p->m_ports.size(); i++)
857 for (i = 0; i < m_p->m_ports.size(); i++)
859 // create a PDU assoc object (one per yf::FrontendNet::ZAssocServer)
860 yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
862 if (m_p->m_ports[i].cert_fname.length())
863 as->set_cert_fname(m_p->m_ports[i].cert_fname.c_str());
864 // create ZAssoc with PDU Assoc
866 m_p->az[i] = new yf::FrontendNet::ZAssocServer(
867 as, &m_p->m_ports[i], m_p.get());
868 if (m_p->az[i]->server(m_p->m_ports[i].port.c_str()))
870 throw yf::FilterException("Unable to bind to address "
871 + std::string(m_p->m_ports[i].port));
873 COMSTACK cs = as->get_comstack();
875 if (cs && m_p->m_ports[i].max_recv_bytes)
876 cs_set_max_recv_bytes(cs, m_p->m_ports[i].max_recv_bytes);
881 void yf::FrontendNet::set_listen_duration(int d)
883 m_p->m_listen_duration = d;
886 static yf::Base* filter_creator()
888 return new yf::FrontendNet;
892 struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
902 * c-file-style: "Stroustrup"
903 * indent-tabs-mode: nil
905 * vim: shiftwidth=4 tabstop=8 expandtab