]> granicus.if.org Git - apache/blob - support/rotatelogs.c
Addition to r733479 and r733479:
[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
39
40 #include "apr.h"
41 #include "apr_lib.h"
42 #include "apr_strings.h"
43 #include "apr_errno.h"
44 #include "apr_file_io.h"
45 #include "apr_file_info.h"
46 #include "apr_general.h"
47 #include "apr_time.h"
48 #include "apr_getopt.h"
49
50 #if APR_HAVE_STDLIB_H
51 #include <stdlib.h>
52 #endif
53 #if APR_HAVE_STRING_H
54 #include <string.h>
55 #endif
56 #if APR_HAVE_STRINGS_H
57 #include <strings.h>
58 #endif
59
60 #define BUFSIZE         65536
61 #define ERRMSGSZ        256
62
63 #ifndef MAX_PATH
64 #define MAX_PATH        1024
65 #endif
66
67 typedef struct rotate_config rotate_config_t;
68
69 struct rotate_config {
70     unsigned int sRotation;
71     int tRotation;
72     int utc_offset;
73     int use_localtime;
74     int use_strftime;
75     int force_open;
76     const char *szLogRoot;
77 };
78
79 typedef struct rotate_status rotate_status_t;
80
81 struct rotate_status {
82     apr_pool_t *pool;
83     apr_pool_t *pfile;
84     apr_pool_t *pfile_prev;
85     apr_file_t *nLogFD;
86     apr_file_t *nLogFDprev;
87     char filename[MAX_PATH];
88     char errbuf[ERRMSGSZ];
89     int needsRotate;
90     int tLogEnd;
91     int now;
92     int nMessCount;
93 };
94
95 static rotate_config_t config;
96 static rotate_status_t status;
97
98 static void usage(const char *argv0, const char *reason)
99 {
100     if (reason) {
101         fprintf(stderr, "%s\n", reason);
102     }
103     fprintf(stderr,
104             "Usage: %s [-l] [-f] <logfile> "
105             "{<rotation time in seconds>|<rotation size in megabytes>} "
106             "[offset minutes from UTC]\n\n",
107             argv0);
108 #ifdef OS2
109     fprintf(stderr,
110             "Add this:\n\nTransferLog \"|%s.exe /some/where 86400\"\n\n",
111             argv0);
112 #else
113     fprintf(stderr,
114             "Add this:\n\nTransferLog \"|%s /some/where 86400\"\n\n",
115             argv0);
116     fprintf(stderr,
117             "or \n\nTransferLog \"|%s /some/where 5M\"\n\n", argv0);
118 #endif
119     fprintf(stderr,
120             "to httpd.conf. The generated name will be /some/where.nnnn "
121             "where nnnn is the\nsystem time at which the log nominally "
122             "starts (N.B. if using a rotation time,\nthe time will always "
123             "be a multiple of the rotation time, so you can synchronize\n"
124             "cron scripts with it). At the end of each rotation time or "
125             "when the file size\nis reached a new log is started.\n");
126     exit(1);
127 }
128
129 static int get_now(int use_localtime, int utc_offset)
130 {
131     apr_time_t tNow = apr_time_now();
132     if (use_localtime) {
133         /* Check for our UTC offset before using it, since it might
134          * change if there's a switch between standard and daylight
135          * savings time.
136          */
137         apr_time_exp_t lt;
138         apr_time_exp_lt(&lt, tNow);
139         utc_offset = lt.tm_gmtoff;
140     }
141     return (int)apr_time_sec(tNow) + utc_offset;
142 }
143
144 void checkRotate(rotate_config_t *config, rotate_status_t *status) {
145
146     if (status->nLogFD == NULL) {
147         status->needsRotate = 1;
148     }
149     else if (config->tRotation) {
150         status->now = get_now(config->use_localtime, config->utc_offset);
151         if (status->now >= status->tLogEnd) {
152             status->needsRotate = 1;
153         }
154     }
155     else if (config->sRotation) {
156         apr_finfo_t finfo;
157         apr_off_t current_size = -1;
158
159         if (apr_file_info_get(&finfo, APR_FINFO_SIZE, status->nLogFD) == APR_SUCCESS) {
160             current_size = finfo.size;
161         }
162
163         if (current_size > config->sRotation) {
164             status->needsRotate = 1;
165         }
166     }
167     else {
168         fprintf(stderr, "No rotation time or size specified\n");
169         exit(2);
170     }
171
172     return;
173 }
174
175 void doRotate(rotate_config_t *config, rotate_status_t *status) {
176
177     int tLogStart;
178     apr_status_t rv;
179
180     status->needsRotate = 0;
181     status->nLogFDprev = status->nLogFD;
182     status->nLogFD = NULL;
183     status->pfile_prev = status->pfile;
184
185     status->now = get_now(config->use_localtime, config->utc_offset);
186     if (config->tRotation) {
187         tLogStart = (status->now / config->tRotation) * config->tRotation;
188         status->tLogEnd = tLogStart + config->tRotation;
189     }
190     else {
191         tLogStart = status->now;
192     }
193
194     if (config->use_strftime) {
195         apr_time_t tNow = apr_time_from_sec(tLogStart);
196         apr_time_exp_t e;
197         apr_size_t rs;
198
199         apr_time_exp_gmt(&e, tNow);
200         apr_strftime(status->filename, &rs, sizeof(status->filename), config->szLogRoot, &e);
201     }
202     else {
203         sprintf(status->filename, "%s.%010d", config->szLogRoot, tLogStart);
204     }
205     apr_pool_create(&status->pfile, status->pool);
206     rv = apr_file_open(&status->nLogFD, status->filename, APR_WRITE | APR_CREATE | APR_APPEND,
207                        APR_OS_DEFAULT, status->pfile);
208     if (rv != APR_SUCCESS) {
209         char error[120];
210
211         apr_strerror(rv, error, sizeof error);
212
213         /* Uh-oh. Failed to open the new log file. Try to clear
214          * the previous log file, note the lost log entries,
215          * and keep on truckin'. */
216         if (status->nLogFDprev == NULL) {
217             fprintf(stderr, "Could not open log file '%s' (%s)\n", status->filename, error);
218             exit(2);
219         }
220         else {
221             apr_size_t nWrite;
222             status->nLogFD = status->nLogFDprev;
223             apr_pool_destroy(status->pfile);
224             status->pfile = status->pfile_prev;
225             /* Try to keep this error message constant length
226              * in case it occurs several times. */
227             apr_snprintf(status->errbuf, sizeof status->errbuf,
228                          "Resetting log file due to error opening "
229                          "new log file, %10d messages lost: %-25.25s\n",
230                          status->nMessCount, error);
231             nWrite = strlen(status->errbuf);
232             apr_file_trunc(status->nLogFD, 0);
233             if (apr_file_write(status->nLogFD, status->errbuf, &nWrite) != APR_SUCCESS) {
234                 fprintf(stderr, "Error writing to the file %s\n", status->filename);
235                 exit(2);
236             }
237         }
238     }
239     else if (status->nLogFDprev) {
240         apr_file_close(status->nLogFDprev);
241         if (status->pfile_prev) {
242             apr_pool_destroy(status->pfile_prev);
243             status->pfile_prev = NULL;
244         }
245     }
246     status->nMessCount = 0;
247 }
248
249 int main (int argc, const char * const argv[])
250 {
251     char buf[BUFSIZE];
252     apr_size_t nRead, nWrite;
253     apr_file_t *f_stdin;
254     apr_getopt_t *opt;
255     apr_status_t rv;
256     char c;
257     const char *optarg;
258     char *ptr = NULL;
259
260     apr_app_initialize(&argc, &argv, NULL);
261     atexit(apr_terminate);
262
263     config.sRotation = 0;
264     config.tRotation = 0;
265     config.utc_offset = 0;
266     config.use_localtime = 0;
267     config.use_strftime = 0;
268     config.force_open = 0;
269     status.pool = NULL;
270     status.pfile = NULL;
271     status.pfile_prev = NULL;
272     status.nLogFD = NULL;
273     status.nLogFDprev = NULL;
274     status.tLogEnd = 0;
275     status.needsRotate = 0;
276     status.now = 0;
277     status.nMessCount = 0;
278
279     apr_pool_create(&status.pool, NULL);
280     apr_getopt_init(&opt, status.pool, argc, argv);
281     while ((rv = apr_getopt(opt, "lf", &c, &optarg)) == APR_SUCCESS) {
282         switch (c) {
283         case 'l':
284             config.use_localtime = 1;
285             break;
286         case 'f':
287             config.force_open = 1;
288             break;
289         }
290     }
291
292     if (rv != APR_EOF) {
293         usage(argv[0], NULL /* specific error message already issued */ );
294     }
295
296     if (opt->ind + 2 != argc && opt->ind + 3 != argc) {
297         usage(argv[0], "Incorrect number of arguments");
298     }
299
300     config.szLogRoot = argv[opt->ind++];
301
302     ptr = strchr(argv[opt->ind], 'M');
303     if (ptr) { /* rotation based on file size */
304         if (*(ptr+1) == '\0') {
305             config.sRotation = atoi(argv[opt->ind]) * 1048576;
306         }
307         if (config.sRotation == 0) {
308             usage(argv[0], "Invalid rotation size parameter");
309         }
310     }
311     else { /* rotation based on elapsed time */
312         config.tRotation = atoi(argv[opt->ind]);
313         if (config.tRotation <= 0) {
314             usage(argv[0], "Invalid rotation time parameter");
315         }
316     }
317     opt->ind++;
318
319     if (opt->ind < argc) { /* have UTC offset */
320         if (config.use_localtime) {
321             usage(argv[0], "UTC offset parameter is not valid with -l");
322         }
323         config.utc_offset = atoi(argv[opt->ind]) * 60;
324     }
325
326     config.use_strftime = (strchr(config.szLogRoot, '%') != NULL);
327     if (apr_file_open_stdin(&f_stdin, status.pool) != APR_SUCCESS) {
328         fprintf(stderr, "Unable to open stdin\n");
329         exit(1);
330     }
331
332     /*
333      * Immediately open the logfile as we start, if we were forced
334      * to do so via '-f'.
335      */
336     if (config.force_open) {
337         doRotate(&config, &status);
338     }
339
340     for (;;) {
341         nRead = sizeof(buf);
342         if (apr_file_read(f_stdin, buf, &nRead) != APR_SUCCESS) {
343             exit(3);
344         }
345         checkRotate(&config, &status);
346         if (status.needsRotate) {
347             doRotate(&config, &status);
348         }
349
350         nWrite = nRead;
351         rv = apr_file_write(status.nLogFD, buf, &nWrite);
352         if (rv == APR_SUCCESS && nWrite != nRead) {
353             /* buffer partially written, which for rotatelogs means we encountered
354              * an error such as out of space or quota or some other limit reached;
355              * try to write the rest so we get the real error code
356              */
357             apr_size_t nWritten = nWrite;
358
359             nRead  = nRead - nWritten;
360             nWrite = nRead;
361             rv = apr_file_write(status.nLogFD, buf + nWritten, &nWrite);
362         }
363         if (nWrite != nRead) {
364             char strerrbuf[120];
365             apr_off_t cur_offset;
366
367             cur_offset = 0;
368             if (apr_file_seek(status.nLogFD, APR_CUR, &cur_offset) != APR_SUCCESS) {
369                 cur_offset = -1;
370             }
371             apr_strerror(rv, strerrbuf, sizeof strerrbuf);
372             status.nMessCount++;
373             apr_snprintf(status.errbuf, sizeof status.errbuf,
374                          "Error %d writing to log file at offset %" APR_OFF_T_FMT ". "
375                          "%10d messages lost (%s)\n",
376                          rv, cur_offset, status.nMessCount, strerrbuf);
377             nWrite = strlen(status.errbuf);
378             apr_file_trunc(status.nLogFD, 0);
379             if (apr_file_write(status.nLogFD, status.errbuf, &nWrite) != APR_SUCCESS) {
380                 fprintf(stderr, "Error writing to the file %s\n", status.filename);
381                 exit(2);
382             }
383         }
384         else {
385             status.nMessCount++;
386         }
387     }
388     /* Of course we never, but prevent compiler warnings */
389     return 0;
390 }