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)) {
476 apr_hash_this(i, NULL, NULL, (void **)(&d));
479 nextpath = apr_pstrcat(p, path, "/", d->basename,
480 CACHE_HEADER_SUFFIX, NULL);
481 if (apr_file_open(&fd, nextpath, APR_READ, APR_OS_DEFAULT,
483 len = sizeof(disk_cache_info_t);
484 if (apr_file_read_full(fd, &disk_info, len,
485 &len) == APR_SUCCESS) {
487 if (disk_info.format == DISK_FORMAT_VERSION) {
488 e = apr_palloc(pool, sizeof(ENTRY));
489 APR_RING_INSERT_TAIL(&root, e, _entry, link);
490 e->expire = disk_info.expire;
491 e->response_time = disk_info.response_time;
496 e->basename = apr_palloc(pool,
497 strlen(d->basename) + 1);
498 strcpy(e->basename, d->basename);
506 /* we have a somehow unreadable headers file which is associated
507 * with a data file. this may be caused by apache currently
508 * rewriting the headers file. thus we may delete the file set
509 * either in realclean mode or if the headers file modification
510 * timestamp is not within a specified positive or negative offset
511 * to the current time.
513 current = apr_time_now();
514 if (realclean || d->htime < current - deviation
515 || d->htime > current + deviation) {
516 delete_entry(path, d->basename, p);
517 unsolicited += d->hsize;
518 unsolicited += d->dsize;
522 /* single data and header files may be deleted either in realclean
523 * mode or if their modification timestamp is not within a
524 * specified positive or negative offset to the current time.
525 * this handling is necessary due to possible race conditions
526 * between apache and this process
529 current = apr_time_now();
530 if (realclean || d->htime < current - deviation
531 || d->htime > current + deviation) {
532 delete_entry(path, d->basename, p);
533 unsolicited += d->hsize;
538 current = apr_time_now();
539 if (realclean || d->dtime < current - deviation
540 || d->dtime > current + deviation) {
541 delete_entry(path, d->basename, p);
542 unsolicited += d->dsize;
546 /* temp files may only be deleted in realclean mode which
547 * is asserted above if a tempfile is in the hash array
550 delete_file(path, d->basename, p);
551 unsolicited += d->dsize;
563 apr_sleep(NICE_DELAY);
574 * purge cache entries
576 static void purge(char *path, apr_pool_t *pool, apr_off_t max)
578 apr_off_t sum, total, entries, etotal;
579 ENTRY *e, *n, *oldest;
584 for (e = APR_RING_FIRST(&root);
585 e != APR_RING_SENTINEL(&root, _entry, link);
586 e = APR_RING_NEXT(e, link)) {
596 printstats(total, sum, max, etotal, entries);
600 /* process all entries with a timestamp in the future, this may
601 * happen if a wrong system time is corrected
604 for (e = APR_RING_FIRST(&root);
605 e != APR_RING_SENTINEL(&root, _entry, link) && !interrupted;) {
606 n = APR_RING_NEXT(e, link);
607 if (e->response_time > now || e->htime > now || e->dtime > now) {
608 delete_entry(path, e->basename, pool);
612 APR_RING_REMOVE(e, link);
615 printstats(total, sum, max, etotal, entries);
627 /* process all entries with are expired */
628 for (e = APR_RING_FIRST(&root);
629 e != APR_RING_SENTINEL(&root, _entry, link) && !interrupted;) {
630 n = APR_RING_NEXT(e, link);
631 if (e->expire != APR_DATE_BAD && e->expire < now) {
632 delete_entry(path, e->basename, pool);
636 APR_RING_REMOVE(e, link);
639 printstats(total, sum, max, etotal, entries);
651 /* process remaining entries oldest to newest, the check for an emtpy
652 * ring actually isn't necessary except when the compiler does
653 * corrupt 64bit arithmetics which happend to me once, so better safe
656 while (sum > max && !interrupted && !APR_RING_EMPTY(&root, _entry, link)) {
657 oldest = APR_RING_FIRST(&root);
659 for (e = APR_RING_NEXT(oldest, link);
660 e != APR_RING_SENTINEL(&root, _entry, link);
661 e = APR_RING_NEXT(e, link)) {
662 if (e->dtime < oldest->dtime) {
667 delete_entry(path, oldest->basename, pool);
668 sum -= oldest->hsize;
669 sum -= oldest->dsize;
671 APR_RING_REMOVE(oldest, link);
675 printstats(total, sum, max, etotal, entries);
682 static void usage(void)
684 apr_file_printf(errfile, "htcacheclean -- program for cleaning the "
686 apr_file_printf(errfile, "Usage: htcacheclean [-Dvrn] -pPATH -lLIMIT\n");
687 apr_file_printf(errfile, " htcacheclean [-Dvrn] -pPATH -LLIMIT\n");
688 apr_file_printf(errfile, " htcacheclean [-ni] -dINTERVAL -pPATH "
690 apr_file_printf(errfile, " htcacheclean [-ni] -dINTERVAL -pPATH "
692 apr_file_printf(errfile, "Options:\n");
693 apr_file_printf(errfile, " -d Daemonize and repeat cache cleaning "
694 "every INTERVAL minutes. This\n"
695 " option is mutually exclusive with "
696 "the -D, -v and -r options.\n");
697 apr_file_printf(errfile, " -D Do a dry run and don't delete anything. "
698 "This option is mutually\n"
699 " exclusive with the -d option.\n");
700 apr_file_printf(errfile, " -v Be verbose and print statistics. "
701 "This option is mutually exclusive\n"
702 " with the -d option.\n");
703 apr_file_printf(errfile, " -r Clean thoroughly. This assumes that "
704 "the Apache web server\n"
705 " is not running. This option is "
706 "mutually exclusive with the -d option.\n");
707 apr_file_printf(errfile, " -n Be nice. This causes slower processing "
708 "in favour of other processes.\n");
709 apr_file_printf(errfile, " -p Specify PATH as the root directory of "
710 "the disk cache.\n");
711 apr_file_printf(errfile, " -l Specify LIMIT as the total disk cache "
712 "size limit in KBytes.\n");
713 apr_file_printf(errfile, " -L Specify LIMIT as the total disk cache "
714 "size limit in MBytes.\n");
715 apr_file_printf(errfile, " -i Be intelligent and run only when there "
716 "was a modification\n"
717 " of the disk cache. This option is only "
718 "possible together with\n"
719 " the -d option.\n");
726 int main(int argc, const char * const argv[])
729 apr_time_t current, repeat, delay, previous;
731 apr_pool_t *pool, *instance;
734 int retries, isdaemon, limit_found, intelligent, dowork;
737 char *proxypath, *path;
751 if (apr_app_initialize(&argc, &argv, NULL) != APR_SUCCESS) {
754 atexit(apr_terminate);
756 if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
759 apr_pool_abort_set(oom, pool);
760 apr_file_open_stderr(&errfile, pool);
761 apr_signal(SIGINT, setterm);
762 apr_signal(SIGTERM, setterm);
764 apr_getopt_init(&o, pool, argc, argv);
767 status = apr_getopt(o, "iDnvrd:l:L:p:", &opt, &arg);
768 if (status == APR_EOF) {
771 else if (status != APR_SUCCESS) {
816 repeat = apr_atoi64(arg);
817 repeat *= SECS_PER_MIN;
818 repeat *= APR_USEC_PER_SEC;
826 max = apr_atoi64(arg);
835 max = apr_atoi64(arg);
843 proxypath = apr_pstrdup(pool, arg);
844 if (apr_filepath_set(proxypath, pool) != APR_SUCCESS) {
852 if (o->ind != argc) {
856 if (isdaemon && (repeat <= 0 || verbose || realclean || dryrun)) {
860 if (!isdaemon && intelligent) {
864 if (!proxypath || max <= 0) {
868 if (apr_filepath_get(&path, 0, pool) != APR_SUCCESS) {
871 baselen = strlen(path);
875 apr_file_close(errfile);
876 apr_proc_detach(APR_PROC_DETACH_DAEMONIZE);
881 apr_pool_create(&instance, pool);
883 now = apr_time_now();
884 APR_RING_INIT(&root, _entry, link);
889 switch (intelligent) {
895 retries = STAT_ATTEMPTS;
896 status = APR_SUCCESS;
899 if (status != APR_SUCCESS) {
900 apr_sleep(STAT_DELAY);
902 status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
903 } while (status != APR_SUCCESS && !interrupted && --retries);
905 if (status == APR_SUCCESS) {
906 previous = info.mtime;
913 retries = STAT_ATTEMPTS;
914 status = APR_SUCCESS;
917 if (status != APR_SUCCESS) {
918 apr_sleep(STAT_DELAY);
920 status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
921 } while (status != APR_SUCCESS && !interrupted && --retries);
923 if (status == APR_SUCCESS) {
924 if (previous != info.mtime) {
927 previous = info.mtime;
935 if (dowork && !interrupted) {
936 if (!process_dir(path, instance) && !interrupted) {
937 purge(path, instance, max);
939 else if (!isdaemon && !interrupted) {
940 apr_file_printf(errfile,
941 "An error occurred, cache cleaning aborted.\n");
945 if (intelligent && !interrupted) {
946 retries = STAT_ATTEMPTS;
947 status = APR_SUCCESS;
949 if (status != APR_SUCCESS) {
950 apr_sleep(STAT_DELAY);
952 status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
953 } while (status != APR_SUCCESS && !interrupted && --retries);
955 if (status == APR_SUCCESS) {
956 previous = info.mtime;
965 apr_pool_destroy(instance);
967 current = apr_time_now();
971 else if (current - now >= repeat) {
975 delay = now + repeat - current;
978 /* we can't sleep the whole delay time here apiece as this is racy
979 * with respect to interrupt delivery - think about what happens
980 * if we have tested for an interrupt, then get scheduled
981 * before the apr_sleep() call and while waiting for the cpu
982 * we do get an interrupt
985 while (delay && !interrupted) {
986 if (delay > APR_USEC_PER_SEC) {
987 apr_sleep(APR_USEC_PER_SEC);
988 delay -= APR_USEC_PER_SEC;
996 } while (isdaemon && !interrupted);
998 if (!isdaemon && interrupted) {
999 apr_file_printf(errfile,
1000 "Cache cleaning aborted due to user request.\n");