3 * $Id: store_dir.cc,v 1.158 2007/04/17 05:40:18 wessels Exp $
5 * DEBUG: section 47 Store Directory Routines
6 * AUTHOR: Duane Wessels
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
38 #include "MemObject.h"
39 #include "SquidTime.h"
43 #if HAVE_SYS_STATVFS_H
44 #include <sys/statvfs.h>
46 #endif /* HAVE_STATVFS */
47 /* statfs() needs <sys/param.h> and <sys/mount.h> on BSD systems */
49 #include <sys/param.h>
52 #include <sys/mount.h>
54 /* Windows and Linux use sys/vfs.h */
59 #include "StoreHashIndex.h"
61 static STDIRSELECT storeDirSelectSwapDirRoundRobin
;
62 static STDIRSELECT storeDirSelectSwapDirLeastLoad
;
65 * store_dirs_rebuilding is initialized to _1_ as a hack so that
66 * storeDirWriteCleanLogs() doesn't try to do anything unless _all_
67 * cache_dirs have been read. For example, without this hack, Squid
68 * will try to write clean log files if -kparse fails (becasue it
71 int StoreController::store_dirs_rebuilding
= 1;
73 StoreController::StoreController() : swapDir (new StoreHashIndex())
76 StoreController::~StoreController()
80 * This function pointer is set according to 'store_dir_select_algorithm'
83 STDIRSELECT
*storeDirSelectSwapDir
= storeDirSelectSwapDirLeastLoad
;
86 StoreController::init()
90 if (0 == strcasecmp(Config
.store_dir_select_algorithm
, "round-robin")) {
91 storeDirSelectSwapDir
= storeDirSelectSwapDirRoundRobin
;
92 debug(47, 1) ("Using Round Robin store dir selection\n");
94 storeDirSelectSwapDir
= storeDirSelectSwapDirLeastLoad
;
95 debug(47, 1) ("Using Least Load store dir selection\n");
100 StoreController::createOneStore(Store
&aStore
)
103 * On Windows, fork() is not available.
104 * The following is a workaround for create store directories sequentially
105 * when running on native Windows port.
107 #ifndef _SQUID_MSWIN_
116 #ifndef _SQUID_MSWIN_
124 StoreController::create()
128 #ifndef _SQUID_MSWIN_
136 pid
= wait3(&status
, WNOHANG
, NULL
);
139 pid
= waitpid(-1, &status
, 0);
142 } while (pid
> 0 || (pid
< 0 && errno
== EINTR
));
148 * Determine whether the given directory can handle this object
151 * Note: if the object size is -1, then the only swapdirs that
152 * will return true here are ones that have max_obj_size = -1,
153 * ie any-sized-object swapdirs. This is a good thing.
156 SwapDir::objectSizeIsAcceptable(ssize_t objsize
) const
159 * If the swapdir's max_obj_size is -1, then it definitely can
162 if (max_objsize
== -1)
166 * If the object size is -1, then if the storedir isn't -1 we
169 if ((objsize
== -1) && (max_objsize
!= -1))
173 * Else, make sure that the max object size is larger than objsize
175 return max_objsize
> objsize
;
180 * This new selection scheme simply does round-robin on all SwapDirs.
181 * A SwapDir is skipped if it is over the max_size (100%) limit, or
185 storeDirSelectSwapDirRoundRobin(const StoreEntry
* e
)
190 RefCount
<SwapDir
> sd
;
192 for (i
= 0; i
<= Config
.cacheSwap
.n_configured
; i
++) {
193 if (++dirn
>= Config
.cacheSwap
.n_configured
)
196 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
198 if (sd
->flags
.read_only
)
201 if (sd
->cur_size
> sd
->max_size
)
204 if (!sd
->objectSizeIsAcceptable(e
->objectLen()))
207 /* check for error or overload condition */
208 load
= sd
->canStore(*e
);
210 if (load
< 0 || load
> 1000) {
221 * Spread load across all of the store directories
223 * Note: We should modify this later on to prefer sticking objects
224 * in the *tightest fit* swapdir to conserve space, along with the
225 * actual swapdir usage. But for now, this hack will do while
226 * testing, so you should order your swapdirs in the config file
227 * from smallest maxobjsize to unlimited (-1) maxobjsize.
229 * We also have to choose nleast == nconf since we need to consider
230 * ALL swapdirs, regardless of state. Again, this is a hack while
231 * we sort out the real usefulness of this algorithm.
234 storeDirSelectSwapDirLeastLoad(const StoreEntry
* e
)
237 ssize_t most_free
= 0, cur_free
;
238 ssize_t least_objsize
= -1;
239 int least_load
= INT_MAX
;
243 RefCount
<SwapDir
> SD
;
245 /* Calculate the object size */
246 objsize
= e
->objectLen();
249 objsize
+= e
->mem_obj
->swap_hdr_sz
;
251 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
252 SD
= dynamic_cast<SwapDir
*>(INDEXSD(i
));
253 SD
->flags
.selected
= 0;
254 load
= SD
->canStore(*e
);
256 if (load
< 0 || load
> 1000) {
260 if (!SD
->objectSizeIsAcceptable(objsize
))
263 if (SD
->flags
.read_only
)
266 if (SD
->cur_size
> SD
->max_size
)
269 if (load
> least_load
)
272 cur_free
= SD
->max_size
- SD
->cur_size
;
274 /* If the load is equal, then look in more details */
275 if (load
== least_load
) {
276 /* closest max_objsize fit */
278 if (least_objsize
!= -1)
279 if (SD
->max_objsize
> least_objsize
|| SD
->max_objsize
== -1)
283 if (cur_free
< most_free
)
288 least_objsize
= SD
->max_objsize
;
289 most_free
= cur_free
;
294 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->flags
.selected
= 1;
300 * An entry written to the swap log MUST have the following
302 * 1. It MUST be a public key. It does no good to log
303 * a public ADD, change the key, then log a private
304 * DEL. So we need to log a DEL before we change a
305 * key from public to private.
306 * 2. It MUST have a valid (> -1) swap_filen.
309 storeDirSwapLog(const StoreEntry
* e
, int op
)
312 assert(!EBIT_TEST(e
->flags
, KEY_PRIVATE
));
313 assert(e
->swap_filen
>= 0);
315 * icons and such; don't write them to the swap log
318 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
))
321 assert(op
> SWAP_LOG_NOP
&& op
< SWAP_LOG_MAX
);
323 debug(20, 3) ("storeDirSwapLog: %s %s %d %08X\n",
329 dynamic_cast<SwapDir
*>(INDEXSD(e
->swap_dirn
))->logEntry(*e
, op
);
333 StoreController::updateSize(size_t size
, int sign
)
335 fatal("StoreController has no independent size\n");
339 SwapDir::updateSize(size_t size
, int sign
)
341 int blks
= (size
+ fs
.blksize
- 1) / fs
.blksize
;
342 int k
= (blks
* fs
.blksize
>> 10) * sign
;
344 store_swap_size
+= k
;
353 StoreController::stat(StoreEntry
&output
) const
355 storeAppendPrintf(&output
, "Store Directory Statistics:\n");
356 storeAppendPrintf(&output
, "Store Entries : %lu\n",
357 (unsigned long int)StoreEntry::inUseCount());
358 storeAppendPrintf(&output
, "Maximum Swap Size : %8ld KB\n",
359 (long int) maxSize());
360 storeAppendPrintf(&output
, "Current Store Swap Size: %8lu KB\n",
362 storeAppendPrintf(&output
, "Current Capacity : %d%% used, %d%% free\n",
363 percent((int) store_swap_size
, (int) maxSize()),
364 percent((int) (maxSize() - store_swap_size
), (int) maxSize()));
365 /* FIXME Here we should output memory statistics */
367 /* now the swapDir */
368 swapDir
->stat(output
);
371 /* if needed, this could be taught to cache the result */
373 StoreController::maxSize() const
375 /* TODO: include memory cache ? */
376 return swapDir
->maxSize();
380 StoreController::minSize() const
382 /* TODO: include memory cache ? */
383 return swapDir
->minSize();
389 if (cur_size
>= max_size
)
394 debugs(20, 1, "WARNING: Shrinking cache_dir #" << index
<< " to " << cur_size
<< " KB");
398 storeDirOpenSwapLogs(void)
400 for (int dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
401 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->openLog();
405 storeDirCloseSwapLogs(void)
407 for (int dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
408 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->closeLog();
412 * storeDirWriteCleanLogs
414 * Writes a "clean" swap log file from in-memory metadata.
415 * This is a rewrite of the original function to troll each
416 * StoreDir and write the logs, and flush at the end of
417 * the run. Thanks goes to Eric Stern, since this solution
418 * came out of his COSS code.
421 storeDirWriteCleanLogs(int reopen
)
423 const StoreEntry
*e
= NULL
;
426 struct timeval start
;
428 RefCount
<SwapDir
> sd
;
432 if (StoreController::store_dirs_rebuilding
) {
433 debug(20, 1) ("Not currently OK to rewrite swap log.\n");
434 debug(20, 1) ("storeDirWriteCleanLogs: Operation aborted.\n");
438 debug(20, 1) ("storeDirWriteCleanLogs: Starting...\n");
440 start
= current_time
;
442 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++) {
443 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
445 if (sd
->writeCleanStart() < 0) {
446 debug(20, 1) ("log.clean.start() failed for dir #%d\n", sd
->index
);
452 * This may look inefficient as CPU wise it is more efficient to do this
453 * sequentially, but I/O wise the parallellism helps as it allows more
454 * hdd spindles to be active.
459 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++) {
460 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
462 if (NULL
== sd
->cleanLog
)
465 e
= sd
->cleanLog
->nextEntry();
475 sd
->cleanLog
->write(*e
);
477 if ((++n
& 0xFFFF) == 0) {
479 debug(20, 1) (" %7d entries written so far.\n", n
);
485 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++)
486 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->writeCleanDone();
489 storeDirOpenSwapLogs();
493 dt
= tvSubDsec(start
, current_time
);
495 debug(20, 1) (" Finished. Wrote %d entries.\n", n
);
497 debug(20, 1) (" Took %3.1f seconds (%6.1f entries/sec).\n",
498 dt
, (double) n
/ (dt
> 0.0 ? dt
: 1.0));
504 StoreController::search(String
const url
, HttpRequest
*request
)
506 /* cheat, for now you can't search the memory hot cache */
507 return swapDir
->search(url
, request
);
511 StoreHashIndex::store(int const x
) const
517 StoreController::sync(void)
519 /* sync mem cache? */
524 * handle callbacks all avaliable fs'es
527 StoreController::callback()
529 /* This will likely double count. Thats ok. */
530 PROF_start(storeDirCallback
);
532 /* mem cache callbacks ? */
533 int result
= swapDir
->callback();
535 PROF_stop(storeDirCallback
);
541 storeDirGetBlkSize(const char *path
, int *blksize
)
547 if (statvfs(path
, &sfs
)) {
548 debug(50, 1) ("%s: %s\n", path
, xstrerror());
553 *blksize
= (int) sfs
.f_frsize
;
558 if (statfs(path
, &sfs
)) {
559 debug(50, 1) ("%s: %s\n", path
, xstrerror());
564 *blksize
= (int) sfs
.f_bsize
;
567 * Sanity check; make sure we have a meaningful value.
576 #define fsbtoblk(num, fsbs, bs) \
577 (((fsbs) != 0 && (fsbs) < (bs)) ? \
578 (num) / ((bs) / (fsbs)) : (num) * ((fsbs) / (bs)))
580 storeDirGetUFSStats(const char *path
, int *totl_kb
, int *free_kb
, int *totl_in
, int *free_in
)
586 if (statvfs(path
, &sfs
)) {
587 debug(50, 1) ("%s: %s\n", path
, xstrerror());
591 *totl_kb
= (int) fsbtoblk(sfs
.f_blocks
, sfs
.f_frsize
, 1024);
592 *free_kb
= (int) fsbtoblk(sfs
.f_bfree
, sfs
.f_frsize
, 1024);
593 *totl_in
= (int) sfs
.f_files
;
594 *free_in
= (int) sfs
.f_ffree
;
599 if (statfs(path
, &sfs
)) {
600 debug(50, 1) ("%s: %s\n", path
, xstrerror());
604 *totl_kb
= (int) fsbtoblk(sfs
.f_blocks
, sfs
.f_bsize
, 1024);
605 *free_kb
= (int) fsbtoblk(sfs
.f_bfree
, sfs
.f_bsize
, 1024);
606 *totl_in
= (int) sfs
.f_files
;
607 *free_in
= (int) sfs
.f_ffree
;
614 allocate_new_swapdir(_SquidConfig::_cacheSwap
* swap
)
616 if (swap
->swapDirs
== NULL
) {
617 swap
->n_allocated
= 4;
618 swap
->swapDirs
= static_cast<StorePointer
*>(xcalloc(swap
->n_allocated
, sizeof(StorePointer
)));
621 if (swap
->n_allocated
== swap
->n_configured
) {
623 swap
->n_allocated
<<= 1;
624 tmp
= static_cast<StorePointer
*>(xcalloc(swap
->n_allocated
, sizeof(StorePointer
)));
625 xmemcpy(tmp
, swap
->swapDirs
, swap
->n_configured
* sizeof(SwapDir
*));
626 xfree(swap
->swapDirs
);
627 swap
->swapDirs
= tmp
;
632 free_cachedir(_SquidConfig::_cacheSwap
* swap
)
635 /* DON'T FREE THESE FOR RECONFIGURE */
640 for (i
= 0; i
< swap
->n_configured
; i
++) {
641 /* TODO XXX this lets the swapdir free resources asynchronously
642 * swap->swapDirs[i]->deactivate();
643 * but there may be such a means already.
646 swap
->swapDirs
[i
] = NULL
;
649 safe_free(swap
->swapDirs
);
650 swap
->swapDirs
= NULL
;
651 swap
->n_allocated
= 0;
652 swap
->n_configured
= 0;
655 /* this should be a virtual method on StoreEntry,
656 * i.e. e->referenced()
657 * so that the entry can notify the creating Store
660 StoreController::reference(StoreEntry
&e
)
662 /* Notify the fs that we're referencing this object again */
664 if (e
.swap_dirn
> -1)
665 e
.store()->reference(e
);
667 /* Notify the memory cache that we're referencing this object again */
669 if (mem_policy
->Referenced
)
670 mem_policy
->Referenced(mem_policy
, &e
, &e
.mem_obj
->repl
);
675 StoreController::dereference(StoreEntry
& e
)
677 /* Notify the fs that we're not referencing this object any more */
679 if (e
.swap_filen
> -1)
680 e
.store()->dereference(e
);
682 /* Notify the memory cache that we're not referencing this object any more */
684 if (mem_policy
->Dereferenced
)
685 mem_policy
->Dereferenced(mem_policy
, &e
, &e
.mem_obj
->repl
);
692 (const cache_key
*key
)
702 (String
const key
, STOREGETCLIENT callback
, void *cbdata
)
704 fatal("not implemented");
707 StoreHashIndex::StoreHashIndex()
709 assert (store_table
== NULL
);
712 StoreHashIndex::~StoreHashIndex()
715 hashFreeItems(store_table
, destroyStoreEntry
);
716 hashFreeMemory(store_table
);
722 StoreHashIndex::callback()
731 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
732 if (ndir
>= Config
.cacheSwap
.n_configured
)
733 ndir
= ndir
% Config
.cacheSwap
.n_configured
;
735 int temp_result
= store(ndir
)->callback();
741 result
+= temp_result
;
744 fatal ("too much io\n");
754 StoreHashIndex::create()
756 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
760 /* Lookup an object in the cache.
761 * return just a reference to object, don't start swapping in yet. */
765 (const cache_key
*key
)
767 PROF_start(storeGet
);
768 debug(20, 3) ("storeGet: looking up %s\n", storeKeyText(key
));
769 StoreEntry
*p
= static_cast<StoreEntry
*>(hash_lookup(store_table
, key
));
777 (String
const key
, STOREGETCLIENT callback
, void *cbdata
)
779 fatal("not implemented");
783 StoreHashIndex::init()
785 /* Calculate size of hash table (maximum currently 64k buckets). */
786 /* this is very bogus, its specific to the any Store maintaining an
787 * in-core index, not global */
788 size_t buckets
= Store::Root().maxSize() / Config
.Store
.avgObjectSize
;
789 debugs(20, 1, "Swap maxSize " << Store::Root().maxSize() <<
790 " KB, estimated " << buckets
<< " objects");
791 buckets
/= Config
.Store
.objectsPerBucket
;
792 debugs(20, 1, "Target number of buckets: " << buckets
);
793 /* ideally the full scan period should be configurable, for the
794 * moment it remains at approximately 24 hours. */
795 store_hash_buckets
= storeKeyHashBuckets(buckets
);
796 debugs(20, 1, "Using " << store_hash_buckets
<< " Store buckets");
797 debugs(20, 1, "Max Mem size: " << ( Config
.memMaxSize
>> 10) << " KB");
798 debugs(20, 1, "Max Swap size: " << Store::Root().maxSize() << " KB");
800 store_table
= hash_create(storeKeyHashCmp
,
801 store_hash_buckets
, storeKeyHashHash
);
803 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
804 /* this starts a search of the store dirs, loading their
805 * index. under the new Store api this should be
806 * driven by the StoreHashIndex, not by each store.
808 * That is, the HashIndex should perform a search of each dir it is
809 * indexing to do the hash insertions. The search is then able to
810 * decide 'from-memory', or 'from-clean-log' or 'from-dirty-log' or
813 * Step 1: make the store rebuilds use a search internally
814 * Step 2: change the search logic to use the four modes described
816 * Step 3: have the hash index walk the searches itself.
823 StoreHashIndex::maxSize() const
828 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
829 result
+= store(i
)->maxSize();
835 StoreHashIndex::minSize() const
839 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
840 result
+= store(i
)->minSize();
846 StoreHashIndex::stat(StoreEntry
& output
) const
850 /* Now go through each store, calling its stat routine */
852 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
853 storeAppendPrintf(&output
, "\n");
854 store(i
)->stat(output
);
859 StoreHashIndex::reference(StoreEntry
&)
863 StoreHashIndex::dereference(StoreEntry
&)
867 StoreHashIndex::maintain()
872 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
873 /* XXX FixMe: This should be done "in parallell" on the different
874 * cache_dirs, not one at a time.
876 /* call the maintain function .. */
877 store(i
)->maintain();
882 StoreHashIndex::updateSize(size_t, int)
886 StoreHashIndex::sync()
888 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
)
893 StoreHashIndex::search(String
const url
, HttpRequest
*)
896 fatal ("Cannot search by url yet\n");
898 return new StoreSearchHashIndex (this);
901 CBDATA_CLASS_INIT(StoreSearchHashIndex
);
903 StoreSearchHashIndex::StoreSearchHashIndex(RefCount
<StoreHashIndex
> aSwapDir
) : sd(aSwapDir
), _done (false), bucket (0)
907 StoreSearchHashIndex::StoreSearchHashIndex(StoreSearchHashIndex const &);
910 StoreSearchHashIndex::~StoreSearchHashIndex()
914 StoreSearchHashIndex::next(void (callback
)(void *cbdata
), void *cbdata
)
921 StoreSearchHashIndex::next()
926 while (!isDone() && !entries
.size())
929 return currentItem() != NULL
;
933 StoreSearchHashIndex::error() const
939 StoreSearchHashIndex::isDone() const
941 return bucket
>= store_hash_buckets
|| _done
;
945 StoreSearchHashIndex::currentItem()
950 return entries
.back();
954 StoreSearchHashIndex::copyBucket()
956 /* probably need to lock the store entries...
957 * we copy them all to prevent races on the links. */
958 debugs(47, 3, "StoreSearchHashIndex::copyBucket #" << bucket
);
959 assert (!entries
.size());
960 hash_link
*link_ptr
= NULL
;
961 hash_link
*link_next
= NULL
;
962 link_next
= hash_get_bucket(store_table
, bucket
);
964 while (NULL
!= (link_ptr
= link_next
)) {
965 link_next
= link_ptr
->next
;
966 StoreEntry
*e
= (StoreEntry
*) link_ptr
;
968 entries
.push_back(e
);
972 debugs(47,3, "got entries: " << entries
.size());