]> granicus.if.org Git - apache/blob - support/rotatelogs.c
c339c3b6c87ead9ac91e5c486e63dc813e7c4374
[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  */
35
36
37 #include "apr.h"
38 #include "apr_lib.h"
39 #include "apr_strings.h"
40 #include "apr_errno.h"
41 #include "apr_file_io.h"
42 #include "apr_file_info.h"
43 #include "apr_general.h"
44 #include "apr_time.h"
45 #include "apr_getopt.h"
46
47 #if APR_HAVE_STDLIB_H
48 #include <stdlib.h>
49 #endif
50 #if APR_HAVE_STRING_H
51 #include <string.h>
52 #endif
53 #if APR_HAVE_STRINGS_H
54 #include <strings.h>
55 #endif
56
57 #define BUFSIZE         65536
58 #define ERRMSGSZ        128
59
60 #ifndef MAX_PATH
61 #define MAX_PATH        1024
62 #endif
63
64 static void usage(const char *argv0, const char *reason)
65 {
66     if (reason) {
67         fprintf(stderr, "%s\n", reason);
68     }
69     fprintf(stderr,
70             "Usage: %s [-l] <logfile> "
71             "{<rotation time in seconds>|<rotation size in megabytes>} "
72             "[offset minutes from UTC]\n\n",
73             argv0);
74 #ifdef OS2
75     fprintf(stderr,
76             "Add this:\n\nTransferLog \"|%s.exe /some/where 86400\"\n\n",
77             argv0);
78 #else
79     fprintf(stderr,
80             "Add this:\n\nTransferLog \"|%s /some/where 86400\"\n\n",
81             argv0);
82     fprintf(stderr,
83             "or \n\nTransferLog \"|%s /some/where 5M\"\n\n", argv0);
84 #endif
85     fprintf(stderr,
86             "to httpd.conf. The generated name will be /some/where.nnnn "
87             "where nnnn is the\nsystem time at which the log nominally "
88             "starts (N.B. if using a rotation time,\nthe time will always "
89             "be a multiple of the rotation time, so you can synchronize\n"
90             "cron scripts with it). At the end of each rotation time or "
91             "when the file size\nis reached a new log is started.\n");
92     exit(1);
93 }
94
95 static int get_now(int use_localtime, int utc_offset)
96 {
97     apr_time_t tNow = apr_time_now();
98     if (use_localtime) {
99         /* Check for our UTC offset before using it, since it might
100          * change if there's a switch between standard and daylight
101          * savings time.
102          */
103         apr_time_exp_t lt;
104         apr_time_exp_lt(&lt, tNow);
105         utc_offset = lt.tm_gmtoff;
106     }
107     return (int)apr_time_sec(tNow) + utc_offset;
108 }
109
110 int main (int argc, const char * const argv[])
111 {
112     char buf[BUFSIZE], buf2[MAX_PATH], errbuf[ERRMSGSZ];
113     int tLogEnd = 0, tRotation = 0, utc_offset = 0;
114     unsigned int sRotation = 0;
115     int nMessCount = 0;
116     apr_size_t nRead, nWrite;
117     int use_strftime = 0;
118     int use_localtime = 0;
119     int now = 0;
120     const char *szLogRoot;
121     apr_file_t *f_stdin, *nLogFD = NULL, *nLogFDprev = NULL;
122     apr_pool_t *pool;
123     apr_getopt_t *opt;
124     apr_status_t rv;
125     char c;
126     const char *optarg;
127     char *ptr = NULL;
128
129     apr_app_initialize(&argc, &argv, NULL);
130     atexit(apr_terminate);
131
132     apr_pool_create(&pool, NULL);
133     apr_getopt_init(&opt, pool, argc, argv);
134     while ((rv = apr_getopt(opt, "l", &c, &optarg)) == APR_SUCCESS) {
135         switch (c) {
136         case 'l':
137             use_localtime = 1;
138             break;
139         }
140     }
141
142     if (rv != APR_EOF) {
143         usage(argv[0], NULL /* specific error message already issued */ );
144     }
145
146     if (opt->ind + 2 != argc && opt->ind + 3 != argc) {
147         usage(argv[0], "Incorrect number of arguments");
148     }
149
150     szLogRoot = argv[opt->ind++];
151
152     ptr = strchr(argv[opt->ind], 'M');
153     if (ptr) { /* rotation based on file size */
154         if (*(ptr+1) == '\0') {
155             sRotation = atoi(argv[opt->ind]) * 1048576;
156         }
157         if (sRotation == 0) {
158             usage(argv[0], "Invalid rotation size parameter");
159         }
160     }
161     else { /* rotation based on elapsed time */
162         tRotation = atoi(argv[opt->ind]);
163         if (tRotation <= 0) {
164             usage(argv[0], "Invalid rotation time parameter");
165         }
166     }
167     opt->ind++;
168
169     if (opt->ind < argc) { /* have UTC offset */
170         if (use_localtime) {
171             usage(argv[0], "UTC offset parameter is not valid with -l");
172         }
173         utc_offset = atoi(argv[opt->ind]) * 60;
174     }
175
176     use_strftime = (strchr(szLogRoot, '%') != NULL);
177     if (apr_file_open_stdin(&f_stdin, pool) != APR_SUCCESS) {
178         fprintf(stderr, "Unable to open stdin\n");
179         exit(1);
180     }
181
182     for (;;) {
183         nRead = sizeof(buf);
184         if (apr_file_read(f_stdin, buf, &nRead) != APR_SUCCESS) {
185             exit(3);
186         }
187         if (tRotation) {
188             now = get_now(use_localtime, utc_offset);
189             if (nLogFD != NULL && now >= tLogEnd) {
190                 nLogFDprev = nLogFD;
191                 nLogFD = NULL;
192             }
193         }
194         else if (sRotation) {
195             apr_finfo_t finfo;
196             apr_off_t current_size = -1;
197
198             if ((nLogFD != NULL) &&
199                 (apr_file_info_get(&finfo, APR_FINFO_SIZE, nLogFD) == APR_SUCCESS)) {
200                 current_size = finfo.size;
201             }
202
203             if (current_size > sRotation) {
204                 nLogFDprev = nLogFD;
205                 nLogFD = NULL;
206             }
207         }
208         else {
209             fprintf(stderr, "No rotation time or size specified\n");
210             exit(2);
211         }
212
213         if (nLogFD == NULL) {
214             int tLogStart;
215             apr_status_t rv;
216
217             if (tRotation) {
218                 tLogStart = (now / tRotation) * tRotation;
219             }
220             else {
221                 tLogStart = get_now(use_localtime, utc_offset);
222             }
223
224             if (use_strftime) {
225                 apr_time_t tNow = apr_time_from_sec(tLogStart);
226                 apr_time_exp_t e;
227                 apr_size_t rs;
228
229                 apr_time_exp_gmt(&e, tNow);
230                 apr_strftime(buf2, &rs, sizeof(buf2), szLogRoot, &e);
231             }
232             else {
233                 sprintf(buf2, "%s.%010d", szLogRoot, tLogStart);
234             }
235             tLogEnd = tLogStart + tRotation;
236             rv = apr_file_open(&nLogFD, buf2, APR_WRITE | APR_CREATE | APR_APPEND,
237                                APR_OS_DEFAULT, pool);
238             if (rv != APR_SUCCESS) {
239                 char error[120];
240
241                 apr_strerror(rv, error, sizeof error);
242
243                 /* Uh-oh. Failed to open the new log file. Try to clear
244                  * the previous log file, note the lost log entries,
245                  * and keep on truckin'. */
246                 if (nLogFDprev == NULL) {
247                     fprintf(stderr, "Could not open log file '%s' (%s)\n", buf2, error);
248                     exit(2);
249                 }
250                 else {
251                     nLogFD = nLogFDprev;
252                     /* Try to keep this error message constant length
253                      * in case it occurs several times. */
254                     apr_snprintf(errbuf, sizeof errbuf,
255                                  "Resetting log file due to error opening "
256                                  "new log file, %10d messages lost: %-25.25s\n",
257                                  nMessCount, error);
258                     nWrite = strlen(errbuf);
259                     apr_file_trunc(nLogFD, 0);
260                     if (apr_file_write(nLogFD, errbuf, &nWrite) != APR_SUCCESS) {
261                         fprintf(stderr, "Error writing to the file %s\n", buf2);
262                         exit(2);
263                     }
264                 }
265             }
266             else if (nLogFDprev) {
267                 apr_file_close(nLogFDprev);
268             }
269             nMessCount = 0;
270         }
271         nWrite = nRead;
272         apr_file_write(nLogFD, buf, &nWrite);
273         if (nWrite != nRead) {
274             nMessCount++;
275             sprintf(errbuf,
276                     "Error writing to log file. "
277                     "%10d messages lost.\n",
278                     nMessCount);
279             nWrite = strlen(errbuf);
280             apr_file_trunc(nLogFD, 0);
281             if (apr_file_write(nLogFD, errbuf, &nWrite) != APR_SUCCESS) {
282                 fprintf(stderr, "Error writing to the file %s\n", buf2);
283                 exit(2);
284             }
285         }
286         else {
287             nMessCount++;
288         }
289     }
290     /* Of course we never, but prevent compiler warnings */
291     return 0;
292 }