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