]> granicus.if.org Git - apache/blob - support/rotatelogs.c
Allow size units B, K, M, G and combination of
[apache] / support / rotatelogs.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * Simple program to rotate Apache logs without having to kill the server.
19  *
20  * Contributed by Ben Laurie <ben algroup.co.uk>
21  *
22  * 12 Mar 1996
23  *
24  * Ported to APR by Mladen Turk <mturk mappingsoft.com>
25  *
26  * 23 Sep 2001
27  *
28  * -l option added 2004-06-11
29  *
30  * -l causes the use of local time rather than GMT as the base for the
31  * interval.  NB: Using -l in an environment which changes the GMT offset
32  * (such as for BST or DST) can lead to unpredictable results!
33  *
34  * -f option added Feb, 2008. This causes rotatelog to open/create
35  *    the logfile as soon as it's started, not as soon as it sees
36  *    data.
37  *
38  * -v option added Feb, 2008. Verbose output of command line parsing.
39  */
40
41
42 #include "apr.h"
43 #include "apr_lib.h"
44 #include "apr_strings.h"
45 #include "apr_errno.h"
46 #include "apr_file_io.h"
47 #include "apr_file_info.h"
48 #include "apr_general.h"
49 #include "apr_time.h"
50 #include "apr_getopt.h"
51 #include "apr_signal.h"
52
53 #if APR_HAVE_STDLIB_H
54 #include <stdlib.h>
55 #endif
56 #define APR_WANT_STRFUNC
57 #include "apr_want.h"
58
59 #define BUFSIZE         65536
60 #define ERRMSGSZ        256
61
62 #ifndef MAX_PATH
63 #define MAX_PATH        1024
64 #endif
65
66 #ifdef SIGHUP
67 #ifdef SIGINT
68 #define HAVE_SIGNALS    1
69 #define SIG_CHECK       SIGHUP
70 #define SIG_FORCE       SIGINT
71 #endif
72 #endif
73
74 #define CHECK_LOG       0
75 #define CHECK_SIG_CHECK 1
76 #define CHECK_SIG_FORCE 2
77
78 #define ROTATE_NONE     0
79 #define ROTATE_NEW      1
80 #define ROTATE_TIME     2
81 #define ROTATE_SIZE     3
82 #define ROTATE_FORCE    4
83
84 static const char *ROTATE_REASONS[] = {
85     "None",
86     "Open a new file",
87     "Time interval expired",
88     "Maximum size reached",
89     "Forced rotation",
90     NULL
91 };
92
93 typedef struct rotate_config rotate_config_t;
94
95 struct rotate_config {
96     unsigned int sRotation;
97     int tRotation;
98     int utc_offset;
99     int use_localtime;
100     int use_strftime;
101     int force_open;
102     int verbose;
103     const char *szLogRoot;
104 };
105
106 typedef struct rotate_status rotate_status_t;
107
108 struct rotate_status {
109     apr_pool_t *pool;
110     apr_pool_t *pfile;
111     apr_pool_t *pfile_prev;
112     apr_file_t *nLogFD;
113     apr_file_t *nLogFDprev;
114     char filename[MAX_PATH];
115     char errbuf[ERRMSGSZ];
116     int rotateReason;
117     int checkReason;
118     int tLogEnd;
119     int nMessCount;
120 };
121
122 static rotate_config_t config;
123 static rotate_status_t status;
124
125 static void usage(const char *argv0, const char *reason)
126 {
127     if (reason) {
128         fprintf(stderr, "%s\n", reason);
129     }
130     fprintf(stderr,
131             "Usage: %s [-v] [-l] [-f] <logfile> "
132             "{<rotation time in seconds>|<rotation size in megabytes>} "
133             "[offset minutes from UTC]\n\n",
134             argv0);
135 #ifdef OS2
136     fprintf(stderr,
137             "Add this:\n\nTransferLog \"|%s.exe /some/where 86400\"\n\n",
138             argv0);
139 #else
140     fprintf(stderr,
141             "Add this:\n\nTransferLog \"|%s /some/where 86400\"\n\n",
142             argv0);
143     fprintf(stderr,
144             "or \n\nTransferLog \"|%s /some/where 5M\"\n\n", argv0);
145 #endif
146     fprintf(stderr,
147             "to httpd.conf. The generated name will be /some/where.nnnn "
148             "where nnnn is the\nsystem time at which the log nominally "
149             "starts (N.B. if using a rotation time,\nthe time will always "
150             "be a multiple of the rotation time, so you can synchronize\n"
151             "cron scripts with it). At the end of each rotation time or "
152             "when the file size\nis reached a new log is started.\n");
153     exit(1);
154 }
155
156 /*
157  * Get the unix time with timezone corrections
158  * given in the config struct.
159  */
160 static int get_now(rotate_config_t *config)
161 {
162     apr_time_t tNow = apr_time_now();
163     int utc_offset = config->utc_offset;
164     if (config->use_localtime) {
165         /* Check for our UTC offset before using it, since it might
166          * change if there's a switch between standard and daylight
167          * savings time.
168          */
169         apr_time_exp_t lt;
170         apr_time_exp_lt(&lt, tNow);
171         utc_offset = lt.tm_gmtoff;
172     }
173     return (int)apr_time_sec(tNow) + utc_offset;
174 }
175
176 /*
177  * Close a file and destroy the associated pool.
178  */
179 static void closeFile(rotate_config_t *config, apr_pool_t *pool, apr_file_t *file)
180 {
181     if (file != NULL) {
182         if (config->verbose) {
183             apr_finfo_t finfo;
184             apr_int32_t wanted = APR_FINFO_NAME;
185             if (apr_file_info_get(&finfo, wanted, file) == APR_SUCCESS) {
186                 fprintf(stderr, "Closing file %s (%s)\n", finfo.name, finfo.fname);
187             }
188         }
189         apr_file_close(file);
190         if (pool) {
191             apr_pool_destroy(pool);
192         }
193     }
194 }
195
196 /*
197  * Dump the configuration parsing result to STDERR.
198  */
199 static void dumpConfig (rotate_config_t *config)
200 {
201     fprintf(stderr, "Rotation time interval:      %12d\n", config->tRotation);
202     fprintf(stderr, "Rotation size interval:      %12d\n", config->sRotation);
203     fprintf(stderr, "Rotation time UTC offset:    %12d\n", config->utc_offset);
204     fprintf(stderr, "Rotation based on localtime: %12s\n", config->use_localtime ? "yes" : "no");
205     fprintf(stderr, "Rotation file date pattern:  %12s\n", config->use_strftime ? "yes" : "no");
206     fprintf(stderr, "Rotation file forced open:   %12s\n", config->force_open ? "yes" : "no");
207     fprintf(stderr, "Rotation verbose:            %12s\n", config->verbose ? "yes" : "no");
208     fprintf(stderr, "Rotation file name: %21s\n", config->szLogRoot);
209 }
210
211 /*
212  * Check whether we need to rotate.
213  * Possible reasons are:
214  * - No log file open (ROTATE_NEW)
215  * - User forces us to rotate (ROTATE_FORCE)
216  * - Our log file size is already bigger than the
217  *   allowed maximum (ROTATE_SIZE)
218  * - The next log time interval expired (ROTATE_TIME)
219  *
220  * When size and time constraints are both given,
221  * it suffices that one of them is fulfilled.
222  *
223  * If the method finds a reason for rotation,
224  * and it hasn't been called while log data is available,
225  * it will close the open log file as a side effect.
226  */
227 static void checkRotate(rotate_config_t *config, rotate_status_t *status)
228 {
229
230     if (status->nLogFD == NULL) {
231         status->rotateReason = ROTATE_NEW;
232     }
233     else if (status->checkReason == CHECK_SIG_FORCE) {
234         status->rotateReason = ROTATE_FORCE;
235     }
236     else if (config->sRotation) {
237         apr_finfo_t finfo;
238         apr_off_t current_size = -1;
239
240         if (apr_file_info_get(&finfo, APR_FINFO_SIZE, status->nLogFD) == APR_SUCCESS) {
241             current_size = finfo.size;
242         }
243
244         if (current_size > config->sRotation) {
245             status->rotateReason = ROTATE_SIZE;
246         }
247         else if (config->tRotation) {
248             if (get_now(config) >= status->tLogEnd) {
249                 status->rotateReason = ROTATE_TIME;
250             }
251         }
252     }
253     else if (config->tRotation) {
254         if (get_now(config) >= status->tLogEnd) {
255             status->rotateReason = ROTATE_TIME;
256         }
257     }
258     else {
259         fprintf(stderr, "No rotation time or size specified\n");
260         exit(2);
261     }
262
263     if (status->rotateReason != ROTATE_NONE && config->verbose) {
264         fprintf(stderr, "File rotation needed, reason: %s\n", ROTATE_REASONS[status->rotateReason]);
265     }
266
267     /*
268      * Let's close the file before immediately
269      * if we got here via a signal.
270      */
271     if ((status->rotateReason != ROTATE_NONE) &&
272         (status->checkReason != CHECK_LOG)) {
273         closeFile(config, status->pfile, status->nLogFD);
274         status->nLogFD = NULL;
275         status->pfile = NULL;
276     }
277     return;
278 }
279
280 /*
281  * Open a new log file, and if successful
282  * also close the old one.
283  *
284  * The timestamp for the calculation of the file
285  * name of the new log file will be the actual millisecond
286  * timestamp, except when a regular rotation based on a time
287  * interval is configured and the previous interval
288  * is over. Then the timestamp is the starting time
289  * of the actual interval.
290  */
291 static void doRotate(rotate_config_t *config, rotate_status_t *status)
292 {
293
294     int now = get_now(config);
295     int tLogStart;
296     apr_status_t rv;
297
298     status->rotateReason = ROTATE_NONE;
299     status->nLogFDprev = status->nLogFD;
300     status->nLogFD = NULL;
301     status->pfile_prev = status->pfile;
302
303     if (config->tRotation) {
304         int tLogEnd;
305         tLogStart = (now / config->tRotation) * config->tRotation;
306         tLogEnd = tLogStart + config->tRotation;
307         /*
308          * Check if rotation was forced and the last rotation
309          * interval is not yet over. Use the value of now instead
310          * of the time interval boundary for the file name then.
311          */
312         if (tLogStart < status->tLogEnd) {
313             tLogStart = now;
314         }
315         status->tLogEnd = tLogEnd;
316     }
317     else {
318         tLogStart = now;
319     }
320
321     if (config->use_strftime) {
322         apr_time_t tNow = apr_time_from_sec(tLogStart);
323         apr_time_exp_t e;
324         apr_size_t rs;
325
326         apr_time_exp_gmt(&e, tNow);
327         apr_strftime(status->filename, &rs, sizeof(status->filename), config->szLogRoot, &e);
328     }
329     else {
330         sprintf(status->filename, "%s.%010d", config->szLogRoot, tLogStart);
331     }
332     apr_pool_create(&status->pfile, status->pool);
333     if (config->verbose) {
334         fprintf(stderr, "Opening file %s\n", status->filename);
335     }
336     rv = apr_file_open(&status->nLogFD, status->filename, APR_WRITE | APR_CREATE | APR_APPEND,
337                        APR_OS_DEFAULT, status->pfile);
338     if (rv != APR_SUCCESS) {
339         char error[120];
340
341         apr_strerror(rv, error, sizeof error);
342
343         /* Uh-oh. Failed to open the new log file. Try to clear
344          * the previous log file, note the lost log entries,
345          * and keep on truckin'. */
346         if (status->nLogFDprev == NULL) {
347             fprintf(stderr, "Could not open log file '%s' (%s)\n", status->filename, error);
348             exit(2);
349         }
350         else {
351             apr_size_t nWrite;
352             status->nLogFD = status->nLogFDprev;
353             apr_pool_destroy(status->pfile);
354             status->pfile = status->pfile_prev;
355             /* Try to keep this error message constant length
356              * in case it occurs several times. */
357             apr_snprintf(status->errbuf, sizeof status->errbuf,
358                          "Resetting log file due to error opening "
359                          "new log file, %10d messages lost: %-25.25s\n",
360                          status->nMessCount, error);
361             nWrite = strlen(status->errbuf);
362             apr_file_trunc(status->nLogFD, 0);
363             if (apr_file_write(status->nLogFD, status->errbuf, &nWrite) != APR_SUCCESS) {
364                 fprintf(stderr, "Error writing to the file %s\n", status->filename);
365                 exit(2);
366             }
367         }
368     }
369     else {
370         closeFile(config, status->pfile_prev, status->nLogFDprev);
371         status->nLogFDprev = NULL;
372         status->pfile_prev = NULL;
373     }
374     status->nMessCount = 0;
375     /*
376      * Reset marker for signal triggered rotation
377      */
378     status->checkReason = CHECK_LOG;
379 }
380
381 #ifdef HAVE_SIGNALS
382 /*
383  * called on SIG_CHECK and SIG_FORCE
384  */
385 static void external_rotate(int signal)
386 {
387     /*
388      * Set marker for signal triggered rotation check
389      */
390     if (signal == SIG_FORCE) {
391         status.checkReason = CHECK_SIG_FORCE;
392     }
393     else {
394         status.checkReason = CHECK_SIG_CHECK;
395     }
396     /*
397      * Close old file conditionally
398      */
399     checkRotate(&config, &status);
400     /*
401      * Open new file if force flag was set
402      */
403     if (config.force_open && (status.rotateReason != ROTATE_NONE)) {
404         doRotate(&config, &status);
405     }
406 }
407 #endif
408
409 /*
410  * Get a size or time param from a string.
411  * Parameter 'last' indicates, whether the
412  * argument is the last commadnline argument.
413  * UTC offset is only allowed as a last argument
414  * in order to make is distinguishable from the
415  * rotation interval time.
416  */
417 static const char *get_time_or_size(rotate_config_t *config,
418                                     const char *arg, int last) {
419     char *ptr = NULL;
420     /* Byte multiplier */
421     unsigned int mult = 1;
422     if ((ptr = strchr(arg, 'B')) != NULL) { /* Found KB size */
423         mult = 1;
424     }
425     else if ((ptr = strchr(arg, 'K')) != NULL) { /* Found KB size */
426         mult = 1024;
427     }
428     else if ((ptr = strchr(arg, 'M')) != NULL) { /* Found MB size */
429         mult = 1024 * 1024;
430     }
431     else if ((ptr = strchr(arg, 'G')) != NULL) { /* Found GB size */
432         mult = 1024 * 1024 * 1024;
433     }
434     if (ptr) { /* rotation based on file size */
435         if (config->sRotation > 0) {
436             return "Rotation size parameter allowed only once";
437         }
438         if (*(ptr+1) == '\0') {
439             config->sRotation = atoi(arg) * mult;
440         }
441         if (config->sRotation == 0) {
442             return "Invalid rotation size parameter";
443         }
444     }
445     else if ((config->sRotation > 0 || config->tRotation > 0) && last) {
446         /* rotation based on elapsed time */
447         if (config->use_localtime) {
448             return "UTC offset parameter is not valid with -l";
449         }
450         config->utc_offset = atoi(arg) * 60;
451     }
452     else { /* rotation based on elapsed time */
453         if (config->tRotation > 0) {
454             return "Rotation time parameter allowed only once";
455         }
456         config->tRotation = atoi(arg);
457         if (config->tRotation <= 0) {
458             return "Invalid rotation time parameter";
459         }
460     }
461     return NULL;
462 }
463
464 int main (int argc, const char * const argv[])
465 {
466     char buf[BUFSIZE];
467     apr_size_t nRead, nWrite;
468     apr_file_t *f_stdin;
469     apr_getopt_t *opt;
470     apr_status_t rv;
471     char c;
472     const char *optarg;
473     const char *err = NULL;
474
475     apr_app_initialize(&argc, &argv, NULL);
476     atexit(apr_terminate);
477
478     config.sRotation = 0;
479     config.tRotation = 0;
480     config.utc_offset = 0;
481     config.use_localtime = 0;
482     config.use_strftime = 0;
483     config.force_open = 0;
484     config.verbose = 0;
485     status.pool = NULL;
486     status.pfile = NULL;
487     status.pfile_prev = NULL;
488     status.nLogFD = NULL;
489     status.nLogFDprev = NULL;
490     status.tLogEnd = 0;
491     status.rotateReason = ROTATE_NONE;
492     status.checkReason = CHECK_LOG;
493     status.nMessCount = 0;
494
495     apr_pool_create(&status.pool, NULL);
496     apr_getopt_init(&opt, status.pool, argc, argv);
497     while ((rv = apr_getopt(opt, "lfv", &c, &optarg)) == APR_SUCCESS) {
498         switch (c) {
499         case 'l':
500             config.use_localtime = 1;
501             break;
502         case 'f':
503             config.force_open = 1;
504             break;
505         case 'v':
506             config.verbose = 1;
507             break;
508         }
509     }
510
511     if (rv != APR_EOF) {
512         usage(argv[0], NULL /* specific error message already issued */ );
513     }
514
515     /*
516      * After the initial flags we need 2 to 4 arguments,
517      * the file name, either the rotation interval time or size
518      * or both of them, and optionally the UTC offset.
519      */
520     if ((argc - opt->ind < 2) || (argc - opt->ind > 4) ) {
521         usage(argv[0], "Incorrect number of arguments");
522     }
523
524     config.szLogRoot = argv[opt->ind++];
525
526     /* Read in the remaining flags, namely time, size and UTC offset. */
527     for(; opt->ind < argc; opt->ind++) {
528         if ((err = get_time_or_size(&config, argv[opt->ind],
529                                     opt->ind < argc - 1 ? 0 : 1)) != NULL) {
530             usage(argv[0], err);
531         }
532     }
533
534     config.use_strftime = (strchr(config.szLogRoot, '%') != NULL);
535
536     if (apr_file_open_stdin(&f_stdin, status.pool) != APR_SUCCESS) {
537         fprintf(stderr, "Unable to open stdin\n");
538         exit(1);
539     }
540
541     /*
542      * Write out result of config parsing if verbose is set.
543      */
544     if (config.verbose) {
545         dumpConfig(&config);
546     }
547
548     /*
549      * Immediately open the logfile as we start, if we were forced
550      * to do so via '-f'.
551      */
552     if (config.force_open) {
553         doRotate(&config, &status);
554     }
555
556 #ifdef HAVE_SIGNALS
557     apr_signal(SIG_CHECK, external_rotate);
558     apr_signal(SIG_FORCE, external_rotate);
559 #endif
560
561     for (;;) {
562         nRead = sizeof(buf);
563 #ifdef HAVE_SIGNALS
564         apr_signal_unblock(SIG_CHECK);
565         apr_signal_unblock(SIG_FORCE);
566 #endif
567         rv = apr_file_read(f_stdin, buf, &nRead);
568 #ifdef HAVE_SIGNALS
569         apr_signal_block(SIG_FORCE);
570         apr_signal_block(SIG_CHECK);
571 #endif
572         if (rv != APR_SUCCESS) {
573             exit(3);
574         }
575         checkRotate(&config, &status);
576         if (status.rotateReason != ROTATE_NONE) {
577             doRotate(&config, &status);
578         }
579
580         nWrite = nRead;
581         rv = apr_file_write(status.nLogFD, buf, &nWrite);
582         if (rv == APR_SUCCESS && nWrite != nRead) {
583             /* buffer partially written, which for rotatelogs means we encountered
584              * an error such as out of space or quota or some other limit reached;
585              * try to write the rest so we get the real error code
586              */
587             apr_size_t nWritten = nWrite;
588
589             nRead  = nRead - nWritten;
590             nWrite = nRead;
591             rv = apr_file_write(status.nLogFD, buf + nWritten, &nWrite);
592         }
593         if (nWrite != nRead) {
594             char strerrbuf[120];
595             apr_off_t cur_offset;
596
597             cur_offset = 0;
598             if (apr_file_seek(status.nLogFD, APR_CUR, &cur_offset) != APR_SUCCESS) {
599                 cur_offset = -1;
600             }
601             apr_strerror(rv, strerrbuf, sizeof strerrbuf);
602             status.nMessCount++;
603             apr_snprintf(status.errbuf, sizeof status.errbuf,
604                          "Error %d writing to log file at offset %" APR_OFF_T_FMT ". "
605                          "%10d messages lost (%s)\n",
606                          rv, cur_offset, status.nMessCount, strerrbuf);
607             nWrite = strlen(status.errbuf);
608             apr_file_trunc(status.nLogFD, 0);
609             if (apr_file_write(status.nLogFD, status.errbuf, &nWrite) != APR_SUCCESS) {
610                 fprintf(stderr, "Error writing to the file %s\n", status.filename);
611                 exit(2);
612             }
613         }
614         else {
615             status.nMessCount++;
616         }
617     }
618     /* Of course we never, but prevent compiler warnings */
619     return 0;
620 }