Start work on 1line log (ala GFS)
[metaproxy-moved-to-github.git] / src / filter_log.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 #include "filter_log.hpp"
21 #include <metaproxy/package.hpp>
22
23 #include <string>
24 #include <sstream>
25 #include <iomanip>
26 #include <boost/thread/mutex.hpp>
27
28 #include "gduutil.hpp"
29 #include <metaproxy/util.hpp>
30 #include <metaproxy/xmlutil.hpp>
31
32 #include <yaz/zgdu.h>
33 #include <yaz/wrbuf.h>
34 #include <yaz/log.h>
35 #include <yaz/querytowrbuf.h>
36 #include <yaz/timing.h>
37 #include <stdio.h>
38 #include <time.h>
39
40 namespace mp = metaproxy_1;
41 namespace yf = metaproxy_1::filter;
42
43 namespace metaproxy_1 {
44     namespace filter {
45         class Log::Impl {
46         public:
47             class LFile;
48             typedef boost::shared_ptr<Log::Impl::LFile> LFilePtr;
49         public:
50             //Impl();
51             Impl(const std::string &x = "-");
52            ~Impl();
53             void process(metaproxy_1::Package & package);
54             void configure(const xmlNode * ptr);
55         private:
56             void openfile(const std::string &fname);
57             // needs to be static to be called by C pointer-to-function-syntax
58             static void stream_write(ODR o, void *handle, int type, 
59                               const char *buf, int len);
60             // needs to be static to be called by C pointer-to-function-syntax
61             static void option_write(const char *name, void *handle);
62         private:
63             std::string m_msg_config;
64             bool m_1line;
65             bool m_access;
66             bool m_user_access;
67             bool m_req_apdu;
68             bool m_res_apdu;
69             bool m_req_session;
70             bool m_res_session;
71             bool m_init_options;
72             LFilePtr m_file;
73             std::string m_time_format;
74             // Only used during confiqgure stage (no threading), 
75             // for performance avoid opening files which other log filter 
76             // instances already have opened
77             static std::list<LFilePtr> filter_log_files;
78
79             boost::mutex m_session_mutex;
80             std::map<mp::Session, std::string> m_sessions;
81        };
82
83         class Log::Impl::LFile {
84         public:
85             boost::mutex m_mutex;
86             std::string m_fname;
87             FILE *fhandle;
88             ~LFile();
89             LFile(std::string fname);
90             LFile(std::string fname, FILE *outf);
91             void log(const std::string &date_format,
92                      std::ostringstream &os);
93             void flush();
94         };
95         
96     }
97 }
98
99 // define Pimpl wrapper forwarding to Impl
100  
101 yf::Log::Log() : m_p(new Impl)
102 {
103 }
104
105 yf::Log::Log(const std::string &x) : m_p(new Impl(x))
106 {
107 }
108
109 yf::Log::~Log()
110 {  // must have a destructor because of boost::scoped_ptr
111 }
112
113 void yf::Log::configure(const xmlNode *xmlnode, bool test_only,
114                         const char *path)
115 {
116     m_p->configure(xmlnode);
117 }
118
119 void yf::Log::process(mp::Package &package) const
120 {
121     m_p->process(package);
122 }
123
124
125 // static initialization
126 std::list<yf::Log::Impl::LFilePtr> yf::Log::Impl::filter_log_files;
127
128
129 yf::Log::Impl::Impl(const std::string &x)
130     : m_msg_config(x),
131       m_1line(false),
132       m_access(true),
133       m_user_access(false),
134       m_req_apdu(false),
135       m_res_apdu(false),
136       m_req_session(false),
137       m_res_session(false),
138       m_init_options(false),
139       m_time_format("%H:%M:%S-%d/%m")
140 {
141     openfile("");
142 }
143
144
145 yf::Log::Impl::~Impl() 
146 {
147 }
148
149 static void log_DefaultDiagFormat(WRBUF w, Z_DefaultDiagFormat *e)
150 {
151     if (e->condition)
152         wrbuf_printf(w, ODR_INT_PRINTF " ",*e->condition);
153     else
154         wrbuf_puts(w, "?? ");
155     if (e->which == Z_DefaultDiagFormat_v2Addinfo && e->u.v2Addinfo)
156         wrbuf_puts(w, e->u.v2Addinfo);
157     else if (e->which == Z_DefaultDiagFormat_v3Addinfo && e->u.v3Addinfo)
158         wrbuf_puts(w, e->u.v3Addinfo);
159 }
160
161 static void log_DiagRecs(WRBUF w, int num_diagRecs, Z_DiagRec **diags)
162 {
163     if (diags[0]->which != Z_DiagRec_defaultFormat)
164         wrbuf_puts(w ,"(diag not in default format?)");
165     else
166     {
167         Z_DefaultDiagFormat *e = diags[0]->u.defaultFormat;
168         log_DefaultDiagFormat(w, e);
169     }
170 }
171
172 static void log_1_line(Z_APDU *z_req, Z_APDU *z_res, WRBUF w)
173 {
174     switch (z_req->which)
175     {
176     case Z_APDU_searchRequest:
177         if (z_res->which == Z_APDU_searchResponse)
178         {
179             Z_SearchRequest *req = z_req->u.searchRequest;
180             Z_SearchResponse *res = z_res->u.searchResponse;
181             int i;
182             wrbuf_puts(w, "Search ");
183             for (i = 0 ; i < req->num_databaseNames; i++)
184             {
185                 if (i)
186                     wrbuf_printf(w, "+");
187                 wrbuf_puts(w, req->databaseNames[i]);
188             }
189             wrbuf_printf(w, " ");
190             if (!res->records)
191             {
192                 wrbuf_printf(w, "OK " ODR_INT_PRINTF " %s", *res->resultCount,
193                              req->resultSetName);
194             }
195             else if (res->records->which == Z_Records_DBOSD)
196             {
197                 wrbuf_printf(w, "OK " ODR_INT_PRINTF " %s", *res->resultCount,
198                              req->resultSetName);
199             }
200             else if (res->records->which == Z_Records_NSD)
201             {
202                 wrbuf_puts(w, "ERROR ");
203                 log_DefaultDiagFormat(w,
204                                       res->records->u.nonSurrogateDiagnostic);
205             }
206             else if (res->records->which == Z_Records_multipleNSD)
207             {
208                 wrbuf_puts(w, "ERROR ");
209                 log_DiagRecs(
210                     w, 
211                     res->records->u.multipleNonSurDiagnostics->num_diagRecs,
212                     res->records->u.multipleNonSurDiagnostics->diagRecs);
213             }
214             wrbuf_printf(w, " 1+");
215             if (res->numberOfRecordsReturned)
216                 wrbuf_printf(w, ODR_INT_PRINTF " ", *res->numberOfRecordsReturned);
217             else
218                 wrbuf_puts(w, "0 ");
219             
220             yaz_query_to_wrbuf(w, req->query);
221         }
222         break;
223     case Z_APDU_presentRequest:
224         if (z_res->which == Z_APDU_presentResponse)
225         {
226             Z_PresentRequest *req = z_req->u.presentRequest;
227             Z_PresentResponse *res = z_res->u.presentResponse;
228
229             wrbuf_printf(w, "Present ");
230
231
232             if (!res->records)
233             {
234                 wrbuf_printf(w, "OK");
235             }
236             else if (res->records->which == Z_Records_DBOSD)
237             {
238                 wrbuf_printf(w, "OK");
239             }
240             else if (res->records->which == Z_Records_NSD)
241             {
242                 wrbuf_puts(w, "ERROR ");
243                 log_DefaultDiagFormat(w,
244                                       res->records->u.nonSurrogateDiagnostic);
245             }
246             else if (res->records->which == Z_Records_multipleNSD)
247             {
248                 wrbuf_puts(w, "ERROR ");
249                 log_DiagRecs(
250                     w, 
251                     res->records->u.multipleNonSurDiagnostics->num_diagRecs,
252                     res->records->u.multipleNonSurDiagnostics->diagRecs);
253             }
254             wrbuf_printf(w, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
255                 req->resultSetId, *req->resultSetStartPoint,
256                          *req->numberOfRecordsRequested);
257         }
258         break;
259     default:
260         wrbuf_printf(w, "REQ=%d RES=%d", z_req->which, z_res->which);
261     }
262 }
263
264 void yf::Log::Impl::configure(const xmlNode *ptr)
265 {
266     for (ptr = ptr->children; ptr; ptr = ptr->next)
267     {
268         if (ptr->type != XML_ELEMENT_NODE)
269             continue;
270         if (!strcmp((const char *) ptr->name, "message"))
271             m_msg_config = mp::xml::get_text(ptr);
272         else if (!strcmp((const char *) ptr->name, "filename"))
273         {
274             std::string fname = mp::xml::get_text(ptr);
275             openfile(fname);
276         }
277         else if (!strcmp((const char *) ptr->name, "time-format"))
278         {
279             m_time_format = mp::xml::get_text(ptr);
280         }
281         else if (!strcmp((const char *) ptr->name, "category"))
282         {
283             const struct _xmlAttr *attr;
284             for (attr = ptr->properties; attr; attr = attr->next)
285             {
286                 if (!strcmp((const char *) attr->name,  "line"))
287                     m_1line = mp::xml::get_bool(attr->children, true);
288                 else if (!strcmp((const char *) attr->name,  "access"))
289                     m_access = mp::xml::get_bool(attr->children, true);
290                 else if (!strcmp((const char *) attr->name, "user-access"))
291                     m_user_access = mp::xml::get_bool(attr->children, true);
292                 else if (!strcmp((const char *) attr->name, "request-apdu"))
293                     m_req_apdu = mp::xml::get_bool(attr->children, true);
294                 else if (!strcmp((const char *) attr->name, "response-apdu"))
295                     m_res_apdu = mp::xml::get_bool(attr->children, true);
296                 else if (!strcmp((const char *) attr->name, "apdu"))
297                 {
298                     m_req_apdu = mp::xml::get_bool(attr->children, true);
299                     m_res_apdu = m_req_apdu;
300                 }
301                 else if (!strcmp((const char *) attr->name,
302                                  "request-session"))
303                     m_req_session = 
304                         mp::xml::get_bool(attr->children, true);
305                 else if (!strcmp((const char *) attr->name, 
306                                  "response-session"))
307                     m_res_session = 
308                         mp::xml::get_bool(attr->children, true);
309                 else if (!strcmp((const char *) attr->name,
310                                  "session"))
311                 {
312                     m_req_session = 
313                         mp::xml::get_bool(attr->children, true);
314                     m_res_session = m_req_session;
315                 }
316                 else if (!strcmp((const char *) attr->name, 
317                                  "init-options"))
318                     m_init_options = 
319                         mp::xml::get_bool(attr->children, true);
320                 else if (!strcmp((const char *) attr->name, 
321                                  "init-options"))
322                     m_init_options = 
323                         mp::xml::get_bool(attr->children, true);
324                 else
325                     throw mp::filter::FilterException(
326                         "Bad attribute " + std::string((const char *)
327                                                        attr->name));
328             }
329         }
330         else
331         {
332             throw mp::filter::FilterException("Bad element " 
333                                                + std::string((const char *)
334                                                              ptr->name));
335         }
336     }
337 }
338
339 void yf::Log::Impl::process(mp::Package &package)
340 {
341     Z_GDU *gdu_req = package.request().get();
342     std::string user("-");
343
344     yaz_timing_t timer = yaz_timing_create();
345
346     // scope for session lock
347     {
348         boost::mutex::scoped_lock scoped_lock(m_session_mutex);
349         
350         if (gdu_req && gdu_req->which == Z_GDU_Z3950)
351         {
352             Z_APDU *apdu_req = gdu_req->u.z3950;
353             if (apdu_req->which == Z_APDU_initRequest)
354             {
355                 Z_InitRequest *req = apdu_req->u.initRequest;
356                 Z_IdAuthentication *a = req->idAuthentication;
357                 if (a)
358                 {
359                     if (a->which == Z_IdAuthentication_idPass)
360                         user = a->u.idPass->userId;
361                     else if (a->which == Z_IdAuthentication_open)
362                         user = a->u.open;
363                 
364                     m_sessions[package.session()] = user;
365                 }
366             }
367         }
368         std::map<mp::Session,std::string>::iterator it = 
369             m_sessions.find(package.session());
370         if (it != m_sessions.end())
371             user = it->second;
372         
373         if (package.session().is_closed())
374             m_sessions.erase(package.session());
375     }
376     // scope for locking Ostream
377     { 
378         boost::mutex::scoped_lock scoped_lock(m_file->m_mutex);
379  
380         if (m_access)
381         {
382             if (gdu_req)          
383             {
384                 std::ostringstream os;
385                 os  << m_msg_config << " "
386                     << package << " "
387                     << "0.000000" << " " 
388                     << *gdu_req;
389                 m_file->log(m_time_format, os);
390             }
391         }
392
393         if (m_user_access)
394         {
395             if (gdu_req)          
396             {
397                 std::ostringstream os;
398                 os  << m_msg_config << " " << user << " "
399                     << package << " "
400                     << "0.000000" << " " 
401                     << *gdu_req;
402                 m_file->log(m_time_format, os);
403             }
404         }
405
406         if (m_req_session)
407         {
408             std::ostringstream os;
409             os << m_msg_config;
410             os << " request id=" << package.session().id();
411             os << " close=" 
412                << (package.session().is_closed() ? "yes" : "no");
413             m_file->log(m_time_format, os);
414         }
415
416         if (m_init_options)
417         {
418             if (gdu_req && gdu_req->which == Z_GDU_Z3950 &&
419                 gdu_req->u.z3950->which == Z_APDU_initRequest)
420             {
421                 std::ostringstream os;
422                 os << m_msg_config << " init options:";
423                 yaz_init_opt_decode(gdu_req->u.z3950->u.initRequest->options,
424                                     option_write, &os);
425                 m_file->log(m_time_format, os);
426             }
427         }
428         
429         if (m_req_apdu)
430         {
431             if (gdu_req)
432             {
433                 mp::odr odr(ODR_PRINT);
434                 odr_set_stream(odr, m_file->fhandle, stream_write, 0);
435                 z_GDU(odr, &gdu_req, 0, 0);
436             }
437         }
438     }
439     
440     // unlocked during move
441     package.move();
442
443     Z_GDU *gdu_res = package.response().get();
444
445     yaz_timing_stop(timer);
446     double duration = yaz_timing_get_real(timer);
447
448     // scope for locking Ostream 
449     { 
450         boost::mutex::scoped_lock scoped_lock(m_file->m_mutex);
451         
452         if (m_1line)
453         {
454             if (gdu_req && gdu_res && gdu_req->which == Z_GDU_Z3950
455                 && gdu_res->which == Z_GDU_Z3950)
456             {
457                 mp::wrbuf w;
458
459                 log_1_line(gdu_req->u.z3950, gdu_res->u.z3950, w);
460                 const char *message = wrbuf_cstr(w);
461
462                 std::ostringstream os;
463                 os  << m_msg_config << " "
464                     << package << " "
465                     << std::fixed << std::setprecision (6) << duration
466                     << " "
467                     << message;
468                 m_file->log(m_time_format, os);
469             }
470         }
471
472         if (m_access)
473         {
474             if (gdu_res)
475             {
476                 std::ostringstream os;
477                 os  << m_msg_config << " "
478                     << package << " "
479                     << std::fixed << std::setprecision (6) << duration
480                     << " "
481                     << *gdu_res;
482                 m_file->log(m_time_format, os);
483             }
484         }
485         if (m_user_access)
486         {
487             if (gdu_res)
488             {
489                 std::ostringstream os;
490                 os  << m_msg_config << " " << user << " "
491                     << package << " "
492                     << std::fixed << std::setprecision (6) << duration << " "
493                     << *gdu_res;
494                 m_file->log(m_time_format, os);
495             }   
496         }
497
498         if (m_res_session)
499         {
500             std::ostringstream os;
501             os << m_msg_config;
502             os << " response id=" << package.session().id();
503             os << " close=" 
504                << (package.session().is_closed() ? "yes " : "no ")
505                << "duration=" 
506                << std::fixed << std::setprecision (6) << duration;
507             m_file->log(m_time_format, os);
508         }
509
510         if (m_init_options)
511         {
512             if (gdu_res && gdu_res->which == Z_GDU_Z3950 &&
513                 gdu_res->u.z3950->which == Z_APDU_initResponse)
514             {
515                 std::ostringstream os;
516                 os << m_msg_config;
517                 os << " init options:";
518                 yaz_init_opt_decode(gdu_res->u.z3950->u.initResponse->options,
519                                     option_write, &os);
520                 m_file->log(m_time_format, os);
521             }
522         }
523         
524         if (m_res_apdu)
525         {
526             if (gdu_res)
527             {
528                 mp::odr odr(ODR_PRINT);
529                 odr_set_stream(odr, m_file->fhandle, stream_write, 0);
530                 z_GDU(odr, &gdu_res, 0, 0);
531             }
532         }
533     }
534     m_file->flush();
535     yaz_timing_destroy(&timer);
536 }
537
538
539 void yf::Log::Impl::openfile(const std::string &fname)
540 {
541     std::list<LFilePtr>::const_iterator it
542         = filter_log_files.begin();
543     for (; it != filter_log_files.end(); it++)
544     {
545         if ((*it)->m_fname == fname)
546         {
547             m_file = *it;
548             return;
549         }
550     }
551     LFilePtr newfile(new LFile(fname));
552     filter_log_files.push_back(newfile);
553     m_file = newfile;
554 }
555
556
557 void yf::Log::Impl::stream_write(ODR o, void *handle, int type, const char *buf, int len)
558 {
559     FILE *f = (FILE*) handle;
560     fwrite(buf, len, 1, f ? f : yaz_log_file());
561 }
562
563 void yf::Log::Impl::option_write(const char *name, void *handle)
564 {
565     std::ostringstream *os = (std::ostringstream *) handle;
566     *os << " " << name;
567 }
568
569
570 yf::Log::Impl::LFile::LFile(std::string fname) : 
571     m_fname(fname)
572     
573 {
574     if (fname.c_str())
575         fhandle = fopen(fname.c_str(), "a");
576     else
577         fhandle = 0;
578 }
579
580 yf::Log::Impl::LFile::~LFile()
581 {
582 }
583
584 void yf::Log::Impl::LFile::log(const std::string &date_format,
585                                std::ostringstream &os)
586 {
587     if (fhandle)
588     {
589         char datestr[80];
590         time_t ti = time(0);
591 #if HAVE_LOCALTIME_R
592         struct tm tm0, *tm = &tm0;
593         localtime_r(&ti, tm);
594 #else
595         struct tm *tm = localtime(&ti);
596 #endif
597         if (strftime(datestr, sizeof(datestr)-1, date_format.c_str(), tm))
598         {
599             fputs(datestr, fhandle);
600             fputs(" ", fhandle);
601         }
602         fputs(os.str().c_str(), fhandle);
603         fputc('\n', fhandle);
604     }    
605     else
606         yaz_log(YLOG_LOG, "%s", os.str().c_str());
607 }
608
609 void yf::Log::Impl::LFile::flush()
610 {
611     if (fhandle)
612         fflush(fhandle);
613 }
614
615 static mp::filter::Base* filter_creator()
616 {
617     return new mp::filter::Log;
618 }
619
620 extern "C" {
621     struct metaproxy_1_filter_struct metaproxy_1_filter_log = {
622         0,
623         "log",
624         filter_creator
625     };
626 }
627
628 /*
629  * Local variables:
630  * c-basic-offset: 4
631  * c-file-style: "Stroustrup"
632  * indent-tabs-mode: nil
633  * End:
634  * vim: shiftwidth=4 tabstop=8 expandtab
635  */
636