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