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 || (con_sz >= it->value && it->verbose > 0))
431 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);
432 if (con_sz < it->value)
435 Z_GDU *gdu_res = o.create_HTTP_Response(m_session, hreq, 500);
437 send_GDU(gdu_res, &len);
442 m_limit_http_req.add_connect(peername.c_str());
444 ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
445 m_thread_pool_observer->put(tp);
448 void yf::FrontendNet::ZAssocChild::failNotify()
450 // TODO: send Package to signal "close"
451 if (m_session.is_closed())
453 if (m_no_requests == 0)
461 mp::Package *p = new mp::Package(m_session, m_origin);
463 ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
464 p->copy_route(*m_package);
465 m_thread_pool_observer->cleanup(tp, &m_session);
466 m_thread_pool_observer->put(tp);
469 void yf::FrontendNet::ZAssocChild::timeoutNotify()
474 void yf::FrontendNet::ZAssocChild::connectNotify()
479 yf::FrontendNet::ZAssocServer::ZAssocServer(
480 yazpp_1::IPDU_Observable *PDU_Observable,
484 Z_Assoc(PDU_Observable), m_port(port), m_p(rep)
490 void yf::FrontendNet::ZAssocServer::set_package(const mp::Package *package)
495 void yf::FrontendNet::ZAssocServer::set_thread_pool(
496 mp::ThreadPoolSocketObserver *observer)
498 m_thread_pool_observer = observer;
501 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocServer::sessionNotify(
502 yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
505 const char *peername = the_PDU_Observable->getpeername();
507 peername = "unknown";
510 const char *cp = strchr(peername, ':');
516 limit_connect.cleanup(false);
517 int con_sz = limit_connect.get_total(peername);
518 std::list<IP_Pattern>::const_iterator it = m_p->connect_max.begin();
519 for (; it != m_p->connect_max.end(); it++)
521 if (mp::util::match_ip(it->pattern, peername))
523 if (it->verbose > 1 || (con_sz >= it->value && it->verbose > 0))
524 yaz_log(YLOG_LOG, "connect-max pattern=%s ip=%s con_sz=%d value=%d", it->pattern.c_str(), peername, con_sz, it->value);
525 if (con_sz < it->value)
530 limit_connect.add_connect(peername);
532 ZAssocChild *my = new ZAssocChild(the_PDU_Observable,
533 m_thread_pool_observer,
534 m_package, m_port, m_p, limit_http_req,
539 yf::FrontendNet::ZAssocServer::~ZAssocServer()
543 void yf::FrontendNet::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
547 void yf::FrontendNet::ZAssocServer::failNotify()
551 void yf::FrontendNet::ZAssocServer::timeoutNotify()
555 void yf::FrontendNet::ZAssocServer::connectNotify()
559 yf::FrontendNet::FrontendNet() : m_p(new Rep)
563 yf::FrontendNet::Rep::Rep()
565 m_max_threads = m_no_threads = 5;
567 m_listen_duration = 0;
568 m_session_timeout = 300; // 5 minutes
571 for (i = 0; i < 22; i++)
572 m_duration_freq[i] = 0;
573 m_duration_lim[0] = 0.000001;
574 m_duration_lim[1] = 0.00001;
575 m_duration_lim[2] = 0.0001;
576 m_duration_lim[3] = 0.001;
577 m_duration_lim[4] = 0.01;
578 m_duration_lim[5] = 0.1;
579 m_duration_lim[6] = 0.2;
580 m_duration_lim[7] = 0.3;
581 m_duration_lim[8] = 0.5;
582 m_duration_lim[9] = 1.0;
583 m_duration_lim[10] = 1.5;
584 m_duration_lim[11] = 2.0;
585 m_duration_lim[12] = 3.0;
586 m_duration_lim[13] = 4.0;
587 m_duration_lim[14] = 5.0;
588 m_duration_lim[15] = 6.0;
589 m_duration_lim[16] = 8.0;
590 m_duration_lim[17] = 10.0;
591 m_duration_lim[18] = 15.0;
592 m_duration_lim[19] = 20.0;
593 m_duration_lim[20] = 30.0;
594 m_duration_lim[21] = 0.0;
595 m_duration_max = 0.0;
596 m_duration_min = 0.0;
597 m_duration_total = 0.0;
601 yf::FrontendNet::Rep::~Rep()
606 for (i = 0; i < m_ports.size(); i++)
614 yf::FrontendNet::~FrontendNet()
618 void yf::FrontendNet::stop(int signo) const
620 m_p->m_stop_signo = signo;
623 void yf::FrontendNet::start() const
626 struct rlimit limit_data;
627 getrlimit(RLIMIT_NOFILE, &limit_data);
628 yaz_log(YLOG_LOG, "getrlimit NOFILE cur=%ld max=%ld",
629 (long) limit_data.rlim_cur, (long) limit_data.rlim_max);
633 bool yf::FrontendNet::My_Timer_Thread::timeout()
638 yf::FrontendNet::My_Timer_Thread::My_Timer_Thread(
639 yazpp_1::ISocketObservable *obs,
641 m_obs(obs), m_pipe(9123), m_timeout(false)
643 obs->addObserver(m_pipe.read_fd(), this);
644 obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
645 obs->timeoutObserver(this, duration);
648 void yf::FrontendNet::My_Timer_Thread::socketNotify(int event)
651 m_obs->deleteObserver(this);
654 void yf::FrontendNet::process(mp::Package &package) const
659 My_Timer_Thread *tt = 0;
661 if (m_p->m_listen_duration)
662 tt = new My_Timer_Thread(&m_p->mySocketManager,
663 m_p->m_listen_duration);
665 ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads,
669 for (i = 0; i<m_p->m_ports.size(); i++)
671 m_p->az[i]->set_package(&package);
672 m_p->az[i]->set_thread_pool(&tp);
674 while (m_p->mySocketManager.processEvent() > 0)
676 if (m_p->m_stop_signo == SIGTERM)
678 yaz_log(YLOG_LOG, "metaproxy received SIGTERM");
682 for (i = 0; i < m_p->m_ports.size(); i++)
684 m_p->pdu[i]->shutdown();
685 m_p->az[i]->server("");
689 break; /* stop right away */
692 if (m_p->m_stop_signo == SIGUSR1)
693 { /* just stop listeners and cont till all sessions are done*/
694 yaz_log(YLOG_LOG, "metaproxy received SIGUSR1");
695 m_p->m_stop_signo = 0;
699 for (i = 0; i < m_p->m_ports.size(); i++)
700 m_p->az[i]->server("");
705 int no = m_p->mySocketManager.getNumberOfObservers();
708 if (tt && tt->timeout())
714 void yf::FrontendNet::configure(const xmlNode * ptr, bool test_only,
717 if (!ptr || !ptr->children)
719 throw yf::FilterException("No ports for Frontend");
721 std::vector<Port> ports;
722 for (ptr = ptr->children; ptr; ptr = ptr->next)
724 if (ptr->type != XML_ELEMENT_NODE)
726 if (!strcmp((const char *) ptr->name, "port"))
730 const char *names[5] = {"route", "max_recv_bytes", "port",
732 std::string values[4];
734 mp::xml::parse_attr(ptr, names, values);
735 port.route = values[0];
736 if (values[1].length() > 0)
737 port.max_recv_bytes = atoi(values[1].c_str());
739 port.max_recv_bytes = 0;
740 if (values[2].length() > 0)
741 port.port = values[2];
743 port.port = mp::xml::get_text(ptr);
744 port.cert_fname = values[3];
745 ports.push_back(port);
747 else if (!strcmp((const char *) ptr->name, "threads"))
749 std::string threads_str = mp::xml::get_text(ptr);
750 int threads = atoi(threads_str.c_str());
752 throw yf::FilterException("Bad value for threads: "
754 m_p->m_no_threads = threads;
756 else if (!strcmp((const char *) ptr->name, "max-threads"))
758 std::string threads_str = mp::xml::get_text(ptr);
759 int threads = atoi(threads_str.c_str());
761 throw yf::FilterException("Bad value for max-threads: "
763 m_p->m_max_threads = threads;
765 else if (!strcmp((const char *) ptr->name, "stack-size"))
767 std::string sz_str = mp::xml::get_text(ptr);
768 int sz = atoi(sz_str.c_str());
770 throw yf::FilterException("Bad value for stack-size: "
772 m_p->m_stack_size = sz * 1024;
774 else if (!strcmp((const char *) ptr->name, "timeout"))
776 std::string timeout_str = mp::xml::get_text(ptr);
777 int timeout = atoi(timeout_str.c_str());
779 throw yf::FilterException("Bad value for timeout: "
781 m_p->m_session_timeout = timeout;
783 else if (!strcmp((const char *) ptr->name, "connect-max"))
785 const char *names[3] = {"ip", "verbose", 0};
786 std::string values[2];
788 mp::xml::parse_attr(ptr, names, values);
790 m.value = mp::xml::get_int(ptr, 0);
791 m.pattern = values[0];
792 m.verbose = values[1].length() ? atoi(values[1].c_str()) : 1;
793 m_p->connect_max.push_back(m);
795 else if (!strcmp((const char *) ptr->name, "http-req-max"))
797 const char *names[3] = {"ip", "verbose", 0};
798 std::string values[2];
800 mp::xml::parse_attr(ptr, names, values);
802 m.value = mp::xml::get_int(ptr, 0);
803 m.pattern = values[0];
804 m.verbose = values[1].length() ? atoi(values[1].c_str()) : 1;
805 m_p->http_req_max.push_back(m);
807 else if (!strcmp((const char *) ptr->name, "message"))
809 m_p->m_msg_config = mp::xml::get_text(ptr);
811 else if (!strcmp((const char *) ptr->name, "stat-req"))
813 m_p->m_stat_req = mp::xml::get_text(ptr);
817 throw yf::FilterException("Bad element "
818 + std::string((const char *)
827 void yf::FrontendNet::set_ports(std::vector<std::string> &ports)
829 std::vector<Port> nports;
832 for (i = 0; i < ports.size(); i++)
836 nport.port = ports[i];
838 nports.push_back(nport);
844 void yf::FrontendNet::set_ports(std::vector<Port> &ports)
846 m_p->m_ports = ports;
848 m_p->az = new yf::FrontendNet::ZAssocServer *[m_p->m_ports.size()];
849 m_p->pdu = new yazpp_1::PDU_Assoc *[m_p->m_ports.size()];
851 // Create yf::FrontendNet::ZAssocServer for each port
853 for (i = 0; i < m_p->m_ports.size(); i++)
855 for (i = 0; i < m_p->m_ports.size(); i++)
857 // create a PDU assoc object (one per yf::FrontendNet::ZAssocServer)
858 yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
860 if (m_p->m_ports[i].cert_fname.length())
861 as->set_cert_fname(m_p->m_ports[i].cert_fname.c_str());
862 // create ZAssoc with PDU Assoc
864 m_p->az[i] = new yf::FrontendNet::ZAssocServer(
865 as, &m_p->m_ports[i], m_p.get());
866 if (m_p->az[i]->server(m_p->m_ports[i].port.c_str()))
868 throw yf::FilterException("Unable to bind to address "
869 + std::string(m_p->m_ports[i].port));
871 COMSTACK cs = as->get_comstack();
873 if (cs && m_p->m_ports[i].max_recv_bytes)
874 cs_set_max_recv_bytes(cs, m_p->m_ports[i].max_recv_bytes);
879 void yf::FrontendNet::set_listen_duration(int d)
881 m_p->m_listen_duration = d;
884 static yf::Base* filter_creator()
886 return new yf::FrontendNet;
890 struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
900 * c-file-style: "Stroustrup"
901 * indent-tabs-mode: nil
903 * vim: shiftwidth=4 tabstop=8 expandtab