2de99026bf061d9cbbe303d26a3bbf77f256f572
[gnucomo.git] / src / gcm_input / logrunner.cpp
1 /*
2  * logrunner.c
3  * (c) Peter Roozemaal, feb 2003
4  *
5  * $Id: logrunner.cpp,v 1.4 2007-10-27 08:46:21 arjen Exp $
6  *
7  * 1) compile,
8  * 2) Add 'logfile' elements to the gnucomo configuration file
9  *    defining the name and type of each logfile to scan.
10  *    'filter' elements can be addes to pre-filter lines from the log.
11  *
12  *    example:
13  *       <logfile>
14  *          <name>/var/log/httpd/access_log</name>
15  *          <type>apache access log</type>
16  *       </logfile>
17  *       <logfile>
18  *          <name>/var/log/messages</name>
19  *          <type>system log</type>
20  *          <filter>open_scanner</filter>
21  *          <filter>session closed</filter>
22  *       </logfile>
23  *
24  * 3) run executable and feed the output to gcm_input
25  */
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <netdb.h>
35 #include <stdio.h>
36 #include <signal.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 #include <fstream>
41 #include <list>
42
43 #include <AXE/String.h>
44
45 #include "gnucomo_config.h"
46
47 extern String XML_Entities(String s);
48
49 static const char* const usage =
50    "Usage: logrunner [<options>] [<hostname>]\n\n"
51    "<hostname> is the gnucomo data collection server\n"
52    "Options are:\n"
53    " -1: one-shot; stop after a single pass over one of the configured logfiles\n"
54    " -p <number>: set IP port number to connect to\n"
55    " -c <file>: specify alternative configuration file, default is \'logrunner.conf\'\n"
56    "If no hostname is specified, logrunner sends output to stdout\n";
57
58 class LogFile {
59    String   name;
60    String   type;
61    String   fromhost;
62
63    int     fd;
64    ino_t   inode;
65    off_t   position;
66
67    std::list<regex> filter;
68
69    void copy_data();
70
71 public:
72    LogFile(String n, String t, String fh)
73    {
74       name = n;
75       type = t;
76       fromhost = fh;
77       inode     = 0;
78       position  = 0;
79       fd        = -1;
80    }
81
82    LogFile(const LogFile &lf)
83    {
84       name     = lf.name;
85       type     = lf.type;
86       fromhost = lf.fromhost;
87
88       fd       = lf.fd;
89       inode    = lf.inode;
90       position = lf.position;
91       filter   = lf.filter;
92    }
93
94    String pathname()
95    {
96       return name;
97    }
98
99    void update_status(ino_t i, off_t p)
100    {
101       inode     = i;
102       position  = p;
103    }
104
105    String status()
106    {
107       return name + " " + String(inode) + " " + String(position);
108    }
109
110    void add_filter(String filter_expression)
111    {
112       filter.push_back(filter_expression);
113       std::cerr << "add_filter, filter size is " << filter.size() << "\n";
114    }
115
116    void do_file();
117 };
118
119 static std::list<LogFile>     logs_to_run;
120
121 String confname = "gnucomo";
122 static const char* statusname = "/var/lib/logrunner.status";
123 static const char* newstatusname = "/var/lib/logrunner.status.new";
124
125 static const char *hostname = NULL;
126 static int port = 2996;         /* random magic number */
127 static int out_stream = 1;
128
129 static int oneshot = 0;
130
131 static int something_has_changed = 0;
132    
133 static volatile sig_atomic_t sig_seen = 0;
134
135 static void sighandler(int sig)
136 {
137    sig_seen = sig;
138 }
139
140 static void set_signal_handler(void)
141 {
142    /* These aren't all; but it's a nice set to start with */
143    signal(SIGHUP, sighandler);
144    signal(SIGINT, sighandler);
145    signal(SIGQUIT, sighandler);
146    signal(SIGABRT, sighandler);
147    signal(SIGPIPE, sighandler);
148    signal(SIGTERM, sighandler);
149 }
150
151
152 void open_output()
153 {
154    struct hostent* hostptr;
155    struct sockaddr_in addr;
156    unsigned int namelen = sizeof(addr);
157
158    if ( hostname )
159    {
160       hostptr = gethostbyname(hostname);
161       if ( !hostptr )
162       {
163          fprintf(stderr, "logrunner: FATAL: cannot resolve %s\n", hostname);
164          exit(2);
165       }
166       out_stream = socket(PF_INET, SOCK_STREAM, 0);
167       if ( out_stream < 0 )
168       {
169          fprintf(stderr, "logrunner: FATAL: Socket creation failed\n");
170          exit(2);
171       }
172       addr.sin_family = AF_INET;
173       addr.sin_addr.s_addr = *((long*)(hostptr->h_addr));
174       addr.sin_port = htons(port);
175       if ( connect(out_stream, (struct sockaddr*) &addr, namelen) < 0 )
176       {
177          fprintf(stderr, "logrunner: FATAL: connect to %s failed\n", hostname);
178          exit(2);
179       }
180    }
181    else
182    {
183       out_stream = 1;
184    }
185 }
186
187 void xsend(const char* str)
188 {
189    write(out_stream, str, strlen(str));
190 }
191
192 void xml_header(String type)
193 {
194    char buffer[256];
195    *buffer = 0;
196    gethostname(buffer, sizeof(buffer));
197         xsend("<?xml version='1.0'?>\n");
198    xsend("<gcmt:message xmlns:gcmt=\"http://gnucomo.org/transport/\">\n");
199    xsend("<gcmt:header>\n<gcmt:hostname>");
200    xsend(buffer);
201    xsend("</gcmt:hostname>\n<gcmt:messagetype>");
202    xsend(type);
203    xsend("</gcmt:messagetype>\n</gcmt:header>\n");
204    xsend("<gcmt:data><gcmt:log>");
205 }
206
207 void xml_footer(void)
208 {
209    xsend("</gcmt:log></gcmt:data>\n</gcmt:message>\n");
210 }
211
212 void output(const char* str)
213 {
214    std::cerr << str;
215 }
216
217 void output_error(const char* str)
218 {
219    std::cerr << str << " errno=" << errno << "\n";
220 }
221
222 void LogFile::do_file()
223 {
224    struct stat statinfo;
225    char buffer[80];
226
227    /* inode check */
228    if ( stat(name, &statinfo) )
229    {
230       std::cerr << "!!! logfile: stat failed: " << name << ", errno=" << errno << "\n";
231    }
232    else
233    {
234       if ( statinfo.st_ino != inode )
235       {
236          if ( fd >= 0 )
237          {
238             copy_data();
239             close(fd);
240             fd = -1;
241          }
242          std::cerr << "@@@ logfile: logrotate detected: " << name << "\n";
243          inode = statinfo.st_ino;
244          position = 0;
245       }
246    }
247    if ( fd < 0 )
248    {
249       /* attempt to open the file */
250       fd = open(name, O_RDONLY);
251       if ( fd < 0 )
252       {
253          std::cerr << "!!! logfile: open failed: " << name << ", " << strerror(errno) << "\n";
254          return;
255       }
256       std::cerr << "*** logfile: opened: " << name;
257       std::cerr << "\n*** logfile: resumed read from position ";
258       std::cerr << (long) lseek(fd, position, SEEK_SET)  << "\n";
259       std::cerr << "This logfile has " << filter.size() << " filters.\n";
260    }
261
262    copy_data();
263 }
264
265 void LogFile::copy_data()
266 {
267    char buffer[4096];
268    int ndata;
269
270    /* read data and dump to output */
271    ndata = read(fd, buffer, sizeof(buffer));
272    if ( ndata > 0 )
273    {
274       xml_header(type);
275       while ( ndata > 0 )
276       {
277          //  Make a separate <gcmt:raw> element from each line
278  
279          char *line, *nextline;
280
281          line = buffer;
282          nextline = buffer;
283
284          while (nextline < buffer + ndata)
285          {
286             while (*nextline != '\n' && nextline < buffer + ndata)
287             {
288                nextline++;
289             }
290             if (*nextline == '\n')
291             {
292                // Another line found - make the split.
293                *nextline++ = '\0';
294
295                String logline(line);
296
297                // See if have to select the host and apply filters to this log entry
298
299                bool filtered_out = false;
300
301                if (fromhost && (fromhost.in(logline) == -1 || fromhost.in(logline) > 20))
302                {
303                   filtered_out = true;
304                }
305
306                std::list<regex>::iterator f = filter.begin();
307                while (f != filter.end())
308                {
309                   if (logline == *f)
310                   {
311                      filtered_out = true;
312                   }
313                   f++;
314                }
315
316                if (!filtered_out)
317                {
318                   logline = XML_Entities(logline);
319
320                   write(out_stream, "<gcmt:raw>", 10);
321                   write(out_stream, logline, ~logline);
322                   write(out_stream, "</gcmt:raw>\n", 12);
323                }
324                else
325                {
326                   std::cerr << logline << " is filtred out.\n";
327                }
328
329                line = nextline;
330             }
331          }
332          if (line != nextline)
333          {
334             //  There is still an incomplete line in the buffer.
335             memmove(buffer, line, nextline - line);
336          }
337          position += ndata - (nextline - line);
338          ndata -= line - buffer;
339          ndata += read(fd, buffer + (nextline - line), sizeof(buffer) - (nextline - line));
340       }
341       xml_footer();
342       something_has_changed = 1;
343    }   
344    if ( ndata < 0 )
345    {
346       std::cerr << "!!! logfile: read failed: " << name << ", " << strerror(errno) << "\n";
347       std::cerr << "    file descriptor = " << fd << "\n";
348    }
349 }
350
351 void write_status_file()
352 {
353    FILE* dumpfile;
354    int localerror = 0;
355
356    std::ofstream   statusfile(newstatusname);
357    std::list<LogFile>::iterator lf = logs_to_run.begin();
358    while (lf != logs_to_run.end())
359    {
360       std::cerr  << "Write status for " << lf->pathname() << "\n";
361       statusfile << lf->status() << "\n";
362       lf++;
363    }
364    
365    if ( localerror == 0 )
366    {
367       if ( rename(newstatusname, statusname) )
368       {
369          output_error("!!! dumpstatus: rename failed");
370       }
371    }
372    something_has_changed = 0;
373 }
374
375 void read_status()
376 {
377    FILE* statusfile;
378    char buffer[4096];
379    char* xp;
380    long ino;
381    unsigned long pos;
382    struct fileinfo* fp;
383
384    statusfile = fopen(statusname, "r");
385    if ( statusfile == NULL )
386    {
387       fprintf(stderr, "logrunner: can\'t open status file \'%s\': ",
388          statusname);
389       perror("");
390       return;
391    }
392    while ( fgets(buffer, sizeof(buffer), statusfile ) )
393    {
394       xp = strchr(buffer, ' ');
395       if ( xp )
396       {
397          *xp = 0;
398          sscanf(xp+1, "%ld %lu", &ino, &pos);
399
400          //  Search for the logfile in the list of logs to run
401
402          std::list<LogFile>::iterator lf = logs_to_run.begin();
403          while (lf != logs_to_run.end())
404          {
405             if (lf->pathname() == String(buffer))
406             {
407                std::cerr << "Read status for " << lf->pathname() << "\n";
408                lf->update_status(ino, pos);
409             }
410             lf++;
411          }
412
413       }
414    }
415    fclose(statusfile);
416 }
417
418 void read_config(gnucomo_config cfg)
419 {
420    /*
421     *   The configuration for logrunner is stored in the central Gnucomo
422     *   configuration file. Multiple 'logfile' elements can be put in this
423     *   XML file, one for each logfile to scan.
424     *   Each 'logfile' element has at least a 'name' and a 'type' element
425     *   that denote the pathname of the logfile and the type of its content.
426     */
427
428    String logfilename;
429    String logfiletype;
430    String fromhost;
431
432    int l = 0;
433
434    logfilename = cfg.find_parameter("logfile", "name", l);
435    while (logfilename != String(""))
436    {
437       std::cerr << "Configuration for logfile " << logfilename << "\n";
438       logfiletype = cfg.find_parameter("logfile", "type", l);
439       fromhost = cfg.find_parameter("logfile", "fromhost", l);
440       std::cerr << "LogFile " << logfilename << " of type " << logfiletype << " from host " << fromhost << "\n";
441
442       LogFile lf(logfilename, logfiletype, fromhost);
443
444       int f = 0;
445       String exp  = cfg.find_parameter("logfile", "filter", l, f);
446       while (exp != "")
447       {
448          std::cerr << "Adding filter " << exp << "\n";
449          lf.add_filter(exp);
450
451          f++;
452          exp = cfg.find_parameter("logfile", "filter", l, f);
453       }
454
455       logs_to_run.push_back(lf);
456       std::cerr << "Logfile added to list.\n";
457
458       l++;
459       logfilename = cfg.find_parameter("logfile", "name", l);
460       std::cerr << "Next logfile = " << logfilename << "\n";
461    }
462
463 }
464
465 void process_options(int argc, char* argv[])
466 {
467    const char* const options = "1c:p:";
468    int opt;
469
470    opt = getopt(argc, argv, options);
471    while ( opt != -1 )
472    {
473       switch ( opt )
474       {
475       case '1':
476          oneshot = 1;
477          break;
478       case 'c':
479          confname = strdup(optarg);
480          break;
481       case 'p':
482          port = atoi(optarg);
483          break;
484       default:
485          fputs(usage, stderr);
486          exit(2);
487       }
488       opt = getopt(argc, argv, options);
489    }
490    switch ( argc-optind )
491    {
492    case 0:
493       break;
494    case 1:
495       hostname = argv[optind];
496       break;
497    default:
498       fputs(usage, stderr);
499       exit(2);
500    }
501 }
502
503 int main(int argc, char* argv[])
504 {
505
506    gnucomo_config    cfg;
507
508    process_options(argc, argv);
509    open_output();
510    
511    if (!cfg.read(confname))
512    {
513       std::cerr << "Can not read Gnucomo configuration file for " << confname << ".\n";
514       exit(1);
515    }
516
517    read_config(cfg);
518    read_status();
519
520    set_signal_handler();
521
522    while ( sig_seen == 0 )
523    {
524       std::list<LogFile>::iterator lf = logs_to_run.begin();
525       while (lf != logs_to_run.end() && !(something_has_changed && oneshot))
526       {
527          std::cerr  << "Scanning logfile " << lf->pathname() << "\n";
528          lf->do_file();
529          lf++;
530       }
531
532       if ( something_has_changed )
533       {
534          write_status_file();
535       }
536       if ( oneshot )
537       {
538          return 0;
539       }
540       sleep(1);
541    }
542
543    fprintf(stderr, "logrunner: stopped by signal %d\n", sig_seen);
544    /* shouldn't we close files and release memory here? */
545    return 0;
546 }