1 /* Copyright 2001-2004 The Apache Software Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 * htcacheclean.c: simple program for cleaning of
18 * the disk cache of the Apache HTTP server
20 * Contributed by Andreas Steinmetz <ast@domdv.de>
26 #include "apr_strings.h"
27 #include "apr_file_io.h"
28 #include "apr_file_info.h"
29 #include "apr_pools.h"
31 #include "apr_thread_proc.h"
32 #include "apr_signal.h"
33 #include "apr_getopt.h"
44 /* mod_disk_cache.c extract start */
46 #define DISK_FORMAT_VERSION 0
48 /* Indicates the format of the header struct stored on-disk. */
50 /* The HTTP status code returned for this response. */
52 /* The size of the entity name that follows. */
54 /* The number of times we've cached this entity. */
55 apr_size_t entity_version;
56 /* Miscellaneous time values. */
59 apr_time_t request_time;
60 apr_time_t response_time;
63 #define CACHE_HEADER_SUFFIX ".header"
64 #define CACHE_DATA_SUFFIX ".data"
65 /* mod_disk_cache.c extract end */
67 /* mod_disk_cache.c related definitions start */
70 * this is based on #define AP_TEMPFILE "/aptmpXXXXXX"
72 * the above definition could be reworked into the following:
74 * #define AP_TEMPFILE_PREFIX "/"
75 * #define AP_TEMPFILE_BASE "aptmp"
76 * #define AP_TEMPFILE_SUFFIX "XXXXXX"
77 * #define AP_TEMPFILE_BASELEN strlen(AP_TEMPFILE_BASE)
78 * #define AP_TEMPFILE_NAMELEN strlen(AP_TEMPFILE_BASE AP_TEMPFILE_SUFFIX)
79 * #define AP_TEMPFILE AP_TEMPFILE_PREFIX AP_TEMPFILE_BASE AP_TEMPFILE_SUFFIX
81 * these definitions would then match the definitions below:
84 #define AP_TEMPFILE_BASE "aptmp"
85 #define AP_TEMPFILE_SUFFIX "XXXXXX"
86 #define AP_TEMPFILE_BASELEN strlen(AP_TEMPFILE_BASE)
87 #define AP_TEMPFILE_NAMELEN strlen(AP_TEMPFILE_BASE AP_TEMPFILE_SUFFIX)
89 /* mod_disk_cache.c related definitions end */
91 /* define the following for debugging */
95 * Note: on Linux delays <= 2ms are busy waits without
96 * scheduling, so never use a delay <= 2ms below
99 #define NICE_DELAY 10000 /* usecs */
100 #define DELETE_NICE 10 /* be nice after this amount of delete ops */
101 #define STAT_ATTEMPTS 10 /* maximum stat attempts for a file */
102 #define STAT_DELAY 5000 /* usecs */
103 #define HEADER 1 /* headers file */
104 #define DATA 2 /* body file */
105 #define TEMP 4 /* temporary file */
106 #define HEADERDATA (HEADER|DATA)
107 #define MAXDEVIATION 3600 /* secs */
108 #define SECS_PER_MIN 60
110 #define MBYTE 1048576
112 #define DIRINFO (APR_FINFO_MTIME|APR_FINFO_SIZE|APR_FINFO_TYPE|APR_FINFO_LINK)
114 typedef struct _direntry {
115 APR_RING_ENTRY(_direntry) link;
116 int type; /* type of file/fileset: TEMP, HEADER, DATA, HEADERDATA */
117 apr_time_t htime; /* headers file modification time */
118 apr_time_t dtime; /* body file modification time */
119 apr_off_t hsize; /* headers file size */
120 apr_off_t dsize; /* body or temporary file size */
121 char *basename; /* file/fileset base name */
124 typedef struct _entry {
125 APR_RING_ENTRY(_entry) link;
126 apr_time_t expire; /* cache entry exiration time */
127 apr_time_t response_time; /* cache entry time of last response to client */
128 apr_time_t htime; /* headers file modification time */
129 apr_time_t dtime; /* body file modification time */
130 apr_off_t hsize; /* headers file size */
131 apr_off_t dsize; /* body or temporary file size */
132 char *basename; /* fileset base name */
136 static int delcount; /* file deletion count for nice mode */
137 static int interrupted; /* flag: true if SIGINT or SIGTERM occurred */
138 static int realclean; /* flag: true means user said apache is not running */
139 static int verbose; /* flag: true means print statistics */
140 static int benice; /* flag: true means nice mode is activated */
141 static int dryrun; /* flag: true means dry run, don't actually delete
143 static int baselen; /* string length of the path to the proxy directory */
144 static apr_time_t now; /* start time of this processing run */
146 static apr_file_t *errfile; /* stderr file handle */
147 static apr_off_t unsolicited; /* file size summary for deleted unsolicited
149 static APR_RING_ENTRY(_entry) root; /* ENTRY ring anchor */
154 * fake delete for debug purposes
156 #define apr_file_remove fake_file_remove
157 static void fake_file_remove(char *pathname, apr_pool_t *p)
161 /* stat and printing to simulate some deletion system load and to
162 display what would actually have happened */
163 apr_stat(&info, pathname, DIRINFO, p);
164 apr_file_printf(errfile, "would delete %s\n", pathname);
169 * called on SIGINT or SIGTERM
171 static void setterm(int unused)
174 apr_file_printf(errfile, "interrupt\n");
180 * called in out of memory condition
182 static int oom(int unused)
184 static int called = 0;
186 /* be careful to call exit() only once */
195 * print purge statistics
197 static void printstats(apr_off_t total, apr_off_t sum, apr_off_t max,
198 apr_off_t etotal, apr_off_t entries)
200 char ttype, stype, mtype, utype;
201 apr_off_t tfrag, sfrag, ufrag;
208 tfrag = ((total * 10) / KBYTE) % 10;
210 if (total >= KBYTE) {
212 tfrag = ((total * 10) / KBYTE) % 10;
217 sfrag = ((sum * 10) / KBYTE) % 10;
221 sfrag = ((sum * 10) / KBYTE) % 10;
232 apr_file_printf(errfile, "Statistics:\n");
235 ufrag = ((unsolicited * 10) / KBYTE) % 10;
236 unsolicited /= KBYTE;
237 if (unsolicited >= KBYTE) {
239 ufrag = ((unsolicited * 10) / KBYTE) % 10;
240 unsolicited /= KBYTE;
242 if (!unsolicited && !ufrag) {
245 apr_file_printf(errfile, "unsolicited size %d.%d%c\n",
246 (int)(unsolicited), (int)(ufrag), utype);
248 apr_file_printf(errfile, "size limit %d.0%c\n", (int)(max), mtype);
249 apr_file_printf(errfile, "total size was %d.%d%c, total size now "
251 (int)(total), (int)(tfrag), ttype, (int)(sum),
252 (int)(sfrag), stype);
253 apr_file_printf(errfile, "total entries was %d, total entries now %d\n",
254 (int)(etotal), (int)(entries));
258 * delete a single file
260 static void delete_file(char *path, char *basename, apr_pool_t *pool)
269 /* temp pool, otherwise lots of memory could be allocated */
270 apr_pool_create(&p, pool);
271 nextpath = apr_pstrcat(p, path, "/", basename, NULL);
272 apr_file_remove(nextpath, p);
276 if (++delcount >= DELETE_NICE) {
277 apr_sleep(NICE_DELAY);
284 * delete cache file set
286 static void delete_entry(char *path, char *basename, apr_pool_t *pool)
295 /* temp pool, otherwise lots of memory could be allocated */
296 apr_pool_create(&p, pool);
298 nextpath = apr_pstrcat(p, path, "/", basename, CACHE_HEADER_SUFFIX, NULL);
299 apr_file_remove(nextpath, p);
301 nextpath = apr_pstrcat(p, path, "/", basename, CACHE_DATA_SUFFIX, NULL);
302 apr_file_remove(nextpath, p);
308 if (delcount >= DELETE_NICE) {
309 apr_sleep(NICE_DELAY);
316 * walk the cache directory tree
318 static int process_dir(char *path, apr_pool_t *pool)
328 apr_time_t current, deviation;
329 char *nextpath, *base, *ext;
330 APR_RING_ENTRY(_direntry) anchor;
334 disk_cache_info_t disk_info;
336 APR_RING_INIT(&anchor, _direntry, link);
337 apr_pool_create(&p, pool);
338 h = apr_hash_make(p);
341 deviation = MAXDEVIATION * APR_USEC_PER_SEC;
343 if (apr_dir_open(&dir, path, p) != APR_SUCCESS) {
347 while (apr_dir_read(&info, 0, dir) == APR_SUCCESS && !interrupted) {
348 /* skip first two entries which will always be '.' and '..' */
353 d = apr_pcalloc(p, sizeof(DIRENTRY));
354 d->basename = apr_pstrcat(p, path, "/", info.name, NULL);
355 APR_RING_INSERT_TAIL(&anchor, d, _direntry, link);
366 for (d = APR_RING_FIRST(&anchor);
367 !interrupted && d != APR_RING_SENTINEL(&anchor, _direntry, link);
369 n = APR_RING_NEXT(d, link);
370 base = strrchr(d->basename, '/');
374 ext = strchr(base, '.');
376 /* there may be temporary files which may be gone before
377 * processing, always skip these if not in realclean mode
379 if (!ext && !realclean) {
380 if (!strncasecmp(base, AP_TEMPFILE_BASE, AP_TEMPFILE_BASELEN)
381 && strlen(base) == AP_TEMPFILE_NAMELEN) {
386 /* this may look strange but apr_stat() may return errno which
387 * is system dependent and there may be transient failures,
388 * so just blindly retry for a short while
390 retries = STAT_ATTEMPTS;
391 status = APR_SUCCESS;
393 if (status != APR_SUCCESS) {
394 apr_sleep(STAT_DELAY);
396 status = apr_stat(&info, d->basename, DIRINFO, p);
397 } while (status != APR_SUCCESS && !interrupted && --retries);
399 /* what may happen here is that apache did create a file which
400 * we did detect but then does delete the file before we can
401 * get file information, so if we don't get any file information
402 * we will ignore the file in this case
404 if (status != APR_SUCCESS) {
405 if (!realclean && !interrupted) {
411 if (info.filetype == APR_DIR) {
412 if (process_dir(d->basename, pool)) {
418 if (info.filetype != APR_REG) {
423 if (!strncasecmp(base, AP_TEMPFILE_BASE, AP_TEMPFILE_BASELEN)
424 && strlen(base) == AP_TEMPFILE_NAMELEN) {
427 d->dsize = info.size;
428 apr_hash_set(h, d->basename, APR_HASH_KEY_STRING, d);
433 if (!strcasecmp(ext, CACHE_HEADER_SUFFIX)) {
436 /* if a user manually creates a '.header' file */
437 if (d->basename[0] == '\0') {
440 t = apr_hash_get(h, d->basename, APR_HASH_KEY_STRING);
445 d->htime = info.mtime;
446 d->hsize = info.size;
447 apr_hash_set(h, d->basename, APR_HASH_KEY_STRING, d);
451 if (!strcasecmp(ext, CACHE_DATA_SUFFIX)) {
454 /* if a user manually creates a '.data' file */
455 if (d->basename[0] == '\0') {
458 t = apr_hash_get(h, d->basename, APR_HASH_KEY_STRING);
463 d->dtime = info.mtime;
464 d->dsize = info.size;
465 apr_hash_set(h, d->basename, APR_HASH_KEY_STRING, d);
473 path[baselen] = '\0';
475 for (i = apr_hash_first(p, h); i && !interrupted; i = apr_hash_next(i)) {
478 apr_hash_this(i, NULL, NULL, &hvalue);
483 nextpath = apr_pstrcat(p, path, "/", d->basename,
484 CACHE_HEADER_SUFFIX, NULL);
485 if (apr_file_open(&fd, nextpath, APR_READ, APR_OS_DEFAULT,
487 len = sizeof(disk_cache_info_t);
488 if (apr_file_read_full(fd, &disk_info, len,
489 &len) == APR_SUCCESS) {
491 if (disk_info.format == DISK_FORMAT_VERSION) {
492 e = apr_palloc(pool, sizeof(ENTRY));
493 APR_RING_INSERT_TAIL(&root, e, _entry, link);
494 e->expire = disk_info.expire;
495 e->response_time = disk_info.response_time;
500 e->basename = apr_palloc(pool,
501 strlen(d->basename) + 1);
502 strcpy(e->basename, d->basename);
510 /* we have a somehow unreadable headers file which is associated
511 * with a data file. this may be caused by apache currently
512 * rewriting the headers file. thus we may delete the file set
513 * either in realclean mode or if the headers file modification
514 * timestamp is not within a specified positive or negative offset
515 * to the current time.
517 current = apr_time_now();
518 if (realclean || d->htime < current - deviation
519 || d->htime > current + deviation) {
520 delete_entry(path, d->basename, p);
521 unsolicited += d->hsize;
522 unsolicited += d->dsize;
526 /* single data and header files may be deleted either in realclean
527 * mode or if their modification timestamp is not within a
528 * specified positive or negative offset to the current time.
529 * this handling is necessary due to possible race conditions
530 * between apache and this process
533 current = apr_time_now();
534 if (realclean || d->htime < current - deviation
535 || d->htime > current + deviation) {
536 delete_entry(path, d->basename, p);
537 unsolicited += d->hsize;
542 current = apr_time_now();
543 if (realclean || d->dtime < current - deviation
544 || d->dtime > current + deviation) {
545 delete_entry(path, d->basename, p);
546 unsolicited += d->dsize;
550 /* temp files may only be deleted in realclean mode which
551 * is asserted above if a tempfile is in the hash array
554 delete_file(path, d->basename, p);
555 unsolicited += d->dsize;
567 apr_sleep(NICE_DELAY);
578 * purge cache entries
580 static void purge(char *path, apr_pool_t *pool, apr_off_t max)
582 apr_off_t sum, total, entries, etotal;
583 ENTRY *e, *n, *oldest;
588 for (e = APR_RING_FIRST(&root);
589 e != APR_RING_SENTINEL(&root, _entry, link);
590 e = APR_RING_NEXT(e, link)) {
600 printstats(total, sum, max, etotal, entries);
604 /* process all entries with a timestamp in the future, this may
605 * happen if a wrong system time is corrected
608 for (e = APR_RING_FIRST(&root);
609 e != APR_RING_SENTINEL(&root, _entry, link) && !interrupted;) {
610 n = APR_RING_NEXT(e, link);
611 if (e->response_time > now || e->htime > now || e->dtime > now) {
612 delete_entry(path, e->basename, pool);
616 APR_RING_REMOVE(e, link);
619 printstats(total, sum, max, etotal, entries);
631 /* process all entries with are expired */
632 for (e = APR_RING_FIRST(&root);
633 e != APR_RING_SENTINEL(&root, _entry, link) && !interrupted;) {
634 n = APR_RING_NEXT(e, link);
635 if (e->expire != APR_DATE_BAD && e->expire < now) {
636 delete_entry(path, e->basename, pool);
640 APR_RING_REMOVE(e, link);
643 printstats(total, sum, max, etotal, entries);
655 /* process remaining entries oldest to newest, the check for an emtpy
656 * ring actually isn't necessary except when the compiler does
657 * corrupt 64bit arithmetics which happend to me once, so better safe
660 while (sum > max && !interrupted && !APR_RING_EMPTY(&root, _entry, link)) {
661 oldest = APR_RING_FIRST(&root);
663 for (e = APR_RING_NEXT(oldest, link);
664 e != APR_RING_SENTINEL(&root, _entry, link);
665 e = APR_RING_NEXT(e, link)) {
666 if (e->dtime < oldest->dtime) {
671 delete_entry(path, oldest->basename, pool);
672 sum -= oldest->hsize;
673 sum -= oldest->dsize;
675 APR_RING_REMOVE(oldest, link);
679 printstats(total, sum, max, etotal, entries);
686 static void usage(void)
688 apr_file_printf(errfile, "htcacheclean -- program for cleaning the "
690 apr_file_printf(errfile, "Usage: htcacheclean [-Dvrn] -pPATH -lLIMIT\n");
691 apr_file_printf(errfile, " htcacheclean [-Dvrn] -pPATH -LLIMIT\n");
692 apr_file_printf(errfile, " htcacheclean [-ni] -dINTERVAL -pPATH "
694 apr_file_printf(errfile, " htcacheclean [-ni] -dINTERVAL -pPATH "
696 apr_file_printf(errfile, "Options:\n");
697 apr_file_printf(errfile, " -d Daemonize and repeat cache cleaning "
698 "every INTERVAL minutes. This\n"
699 " option is mutually exclusive with "
700 "the -D, -v and -r options.\n");
701 apr_file_printf(errfile, " -D Do a dry run and don't delete anything. "
702 "This option is mutually\n"
703 " exclusive with the -d option.\n");
704 apr_file_printf(errfile, " -v Be verbose and print statistics. "
705 "This option is mutually exclusive\n"
706 " with the -d option.\n");
707 apr_file_printf(errfile, " -r Clean thoroughly. This assumes that "
708 "the Apache web server\n"
709 " is not running. This option is "
710 "mutually exclusive with the -d option.\n");
711 apr_file_printf(errfile, " -n Be nice. This causes slower processing "
712 "in favour of other processes.\n");
713 apr_file_printf(errfile, " -p Specify PATH as the root directory of "
714 "the disk cache.\n");
715 apr_file_printf(errfile, " -l Specify LIMIT as the total disk cache "
716 "size limit in KBytes.\n");
717 apr_file_printf(errfile, " -L Specify LIMIT as the total disk cache "
718 "size limit in MBytes.\n");
719 apr_file_printf(errfile, " -i Be intelligent and run only when there "
720 "was a modification\n"
721 " of the disk cache. This option is only "
722 "possible together with\n"
723 " the -d option.\n");
730 int main(int argc, const char * const argv[])
733 apr_time_t current, repeat, delay, previous;
735 apr_pool_t *pool, *instance;
738 int retries, isdaemon, limit_found, intelligent, dowork;
741 char *proxypath, *path;
753 previous = 0; /* avoid compiler warning */
756 if (apr_app_initialize(&argc, &argv, NULL) != APR_SUCCESS) {
759 atexit(apr_terminate);
761 if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
764 apr_pool_abort_set(oom, pool);
765 apr_file_open_stderr(&errfile, pool);
766 apr_signal(SIGINT, setterm);
767 apr_signal(SIGTERM, setterm);
769 apr_getopt_init(&o, pool, argc, argv);
772 status = apr_getopt(o, "iDnvrd:l:L:p:", &opt, &arg);
773 if (status == APR_EOF) {
776 else if (status != APR_SUCCESS) {
821 repeat = apr_atoi64(arg);
822 repeat *= SECS_PER_MIN;
823 repeat *= APR_USEC_PER_SEC;
831 max = apr_atoi64(arg);
840 max = apr_atoi64(arg);
848 proxypath = apr_pstrdup(pool, arg);
849 if (apr_filepath_set(proxypath, pool) != APR_SUCCESS) {
857 if (o->ind != argc) {
861 if (isdaemon && (repeat <= 0 || verbose || realclean || dryrun)) {
865 if (!isdaemon && intelligent) {
869 if (!proxypath || max <= 0) {
873 if (apr_filepath_get(&path, 0, pool) != APR_SUCCESS) {
876 baselen = strlen(path);
880 apr_file_close(errfile);
881 apr_proc_detach(APR_PROC_DETACH_DAEMONIZE);
886 apr_pool_create(&instance, pool);
888 now = apr_time_now();
889 APR_RING_INIT(&root, _entry, link);
894 switch (intelligent) {
900 retries = STAT_ATTEMPTS;
901 status = APR_SUCCESS;
904 if (status != APR_SUCCESS) {
905 apr_sleep(STAT_DELAY);
907 status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
908 } while (status != APR_SUCCESS && !interrupted && --retries);
910 if (status == APR_SUCCESS) {
911 previous = info.mtime;
918 retries = STAT_ATTEMPTS;
919 status = APR_SUCCESS;
922 if (status != APR_SUCCESS) {
923 apr_sleep(STAT_DELAY);
925 status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
926 } while (status != APR_SUCCESS && !interrupted && --retries);
928 if (status == APR_SUCCESS) {
929 if (previous != info.mtime) {
932 previous = info.mtime;
940 if (dowork && !interrupted) {
941 if (!process_dir(path, instance) && !interrupted) {
942 purge(path, instance, max);
944 else if (!isdaemon && !interrupted) {
945 apr_file_printf(errfile,
946 "An error occurred, cache cleaning aborted.\n");
950 if (intelligent && !interrupted) {
951 retries = STAT_ATTEMPTS;
952 status = APR_SUCCESS;
954 if (status != APR_SUCCESS) {
955 apr_sleep(STAT_DELAY);
957 status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
958 } while (status != APR_SUCCESS && !interrupted && --retries);
960 if (status == APR_SUCCESS) {
961 previous = info.mtime;
970 apr_pool_destroy(instance);
972 current = apr_time_now();
976 else if (current - now >= repeat) {
980 delay = now + repeat - current;
983 /* we can't sleep the whole delay time here apiece as this is racy
984 * with respect to interrupt delivery - think about what happens
985 * if we have tested for an interrupt, then get scheduled
986 * before the apr_sleep() call and while waiting for the cpu
987 * we do get an interrupt
990 while (delay && !interrupted) {
991 if (delay > APR_USEC_PER_SEC) {
992 apr_sleep(APR_USEC_PER_SEC);
993 delay -= APR_USEC_PER_SEC;
1001 } while (isdaemon && !interrupted);
1003 if (!isdaemon && interrupted) {
1004 apr_file_printf(errfile,
1005 "Cache cleaning aborted due to user request.\n");