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 "SquidMath.h"
40 #include "SquidTime.h"
42 #include "swap_log_op.h"
45 #if HAVE_SYS_STATVFS_H
46 #include <sys/statvfs.h>
48 #endif /* HAVE_STATVFS */
49 /* statfs() needs <sys/param.h> and <sys/mount.h> on BSD systems */
51 #include <sys/param.h>
54 #include <sys/mount.h>
56 /* Windows and Linux use sys/vfs.h */
61 #include "StoreHashIndex.h"
63 static STDIRSELECT storeDirSelectSwapDirRoundRobin
;
64 static STDIRSELECT storeDirSelectSwapDirLeastLoad
;
67 * store_dirs_rebuilding is initialized to _1_ as a hack so that
68 * storeDirWriteCleanLogs() doesn't try to do anything unless _all_
69 * cache_dirs have been read. For example, without this hack, Squid
70 * will try to write clean log files if -kparse fails (becasue it
73 int StoreController::store_dirs_rebuilding
= 1;
75 StoreController::StoreController() : swapDir (new StoreHashIndex())
78 StoreController::~StoreController()
82 * This function pointer is set according to 'store_dir_select_algorithm'
85 STDIRSELECT
*storeDirSelectSwapDir
= storeDirSelectSwapDirLeastLoad
;
88 StoreController::init()
92 if (0 == strcasecmp(Config
.store_dir_select_algorithm
, "round-robin")) {
93 storeDirSelectSwapDir
= storeDirSelectSwapDirRoundRobin
;
94 debugs(47, 1, "Using Round Robin store dir selection");
96 storeDirSelectSwapDir
= storeDirSelectSwapDirLeastLoad
;
97 debugs(47, 1, "Using Least Load store dir selection");
102 StoreController::createOneStore(Store
&aStore
)
105 * On Windows, fork() is not available.
106 * The following is a workaround for create store directories sequentially
107 * when running on native Windows port.
109 #ifndef _SQUID_MSWIN_
118 #ifndef _SQUID_MSWIN_
126 StoreController::create()
130 #ifndef _SQUID_MSWIN_
138 pid
= wait3(&status
, WNOHANG
, NULL
);
141 pid
= waitpid(-1, &status
, 0);
144 } while (pid
> 0 || (pid
< 0 && errno
== EINTR
));
150 * Determine whether the given directory can handle this object
153 * Note: if the object size is -1, then the only swapdirs that
154 * will return true here are ones that have max_obj_size = -1,
155 * ie any-sized-object swapdirs. This is a good thing.
158 SwapDir::objectSizeIsAcceptable(int64_t objsize
) const
161 * If the swapdir's max_obj_size is -1, then it definitely can
164 if (max_objsize
== -1)
168 * If the object size is -1, then if the storedir isn't -1 we
171 if ((objsize
== -1) && (max_objsize
!= -1))
175 * Else, make sure that the max object size is larger than objsize
177 return max_objsize
> objsize
;
182 * This new selection scheme simply does round-robin on all SwapDirs.
183 * A SwapDir is skipped if it is over the max_size (100%) limit, or
187 storeDirSelectSwapDirRoundRobin(const StoreEntry
* e
)
192 RefCount
<SwapDir
> sd
;
194 ssize_t objsize
= e
->objectLen();
196 objsize
+= e
->mem_obj
->swap_hdr_sz
;
198 for (i
= 0; i
<= Config
.cacheSwap
.n_configured
; i
++) {
199 if (++dirn
>= Config
.cacheSwap
.n_configured
)
202 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
204 if (sd
->flags
.read_only
)
207 if (sd
->cur_size
> sd
->max_size
)
210 if (!sd
->objectSizeIsAcceptable(objsize
))
213 /* check for error or overload condition */
214 load
= sd
->canStore(*e
);
216 if (load
< 0 || load
> 1000) {
227 * Spread load across all of the store directories
229 * Note: We should modify this later on to prefer sticking objects
230 * in the *tightest fit* swapdir to conserve space, along with the
231 * actual swapdir usage. But for now, this hack will do while
232 * testing, so you should order your swapdirs in the config file
233 * from smallest maxobjsize to unlimited (-1) maxobjsize.
235 * We also have to choose nleast == nconf since we need to consider
236 * ALL swapdirs, regardless of state. Again, this is a hack while
237 * we sort out the real usefulness of this algorithm.
240 storeDirSelectSwapDirLeastLoad(const StoreEntry
* e
)
243 ssize_t most_free
= 0, cur_free
;
244 ssize_t least_objsize
= -1;
245 int least_load
= INT_MAX
;
249 RefCount
<SwapDir
> SD
;
251 /* Calculate the object size */
252 objsize
= e
->objectLen();
255 objsize
+= e
->mem_obj
->swap_hdr_sz
;
257 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
258 SD
= dynamic_cast<SwapDir
*>(INDEXSD(i
));
259 SD
->flags
.selected
= 0;
260 load
= SD
->canStore(*e
);
262 if (load
< 0 || load
> 1000) {
266 if (!SD
->objectSizeIsAcceptable(objsize
))
269 if (SD
->flags
.read_only
)
272 if (SD
->cur_size
> SD
->max_size
)
275 if (load
> least_load
)
278 cur_free
= SD
->max_size
- SD
->cur_size
;
280 /* If the load is equal, then look in more details */
281 if (load
== least_load
) {
282 /* closest max_objsize fit */
284 if (least_objsize
!= -1)
285 if (SD
->max_objsize
> least_objsize
|| SD
->max_objsize
== -1)
289 if (cur_free
< most_free
)
294 least_objsize
= SD
->max_objsize
;
295 most_free
= cur_free
;
300 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->flags
.selected
= 1;
306 * An entry written to the swap log MUST have the following
308 * 1. It MUST be a public key. It does no good to log
309 * a public ADD, change the key, then log a private
310 * DEL. So we need to log a DEL before we change a
311 * key from public to private.
312 * 2. It MUST have a valid (> -1) swap_filen.
315 storeDirSwapLog(const StoreEntry
* e
, int op
)
318 assert(!EBIT_TEST(e
->flags
, KEY_PRIVATE
));
319 assert(e
->swap_filen
>= 0);
321 * icons and such; don't write them to the swap log
324 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
))
327 assert(op
> SWAP_LOG_NOP
&& op
< SWAP_LOG_MAX
);
329 debugs(20, 3, "storeDirSwapLog: " <<
330 swap_log_op_str
[op
] << " " <<
331 e
->getMD5Text() << " " <<
332 e
->swap_dirn
<< " " <<
333 std::hex
<< std::uppercase
<< std::setfill('0') << std::setw(8) << e
->swap_filen
);
335 dynamic_cast<SwapDir
*>(INDEXSD(e
->swap_dirn
))->logEntry(*e
, op
);
339 StoreController::updateSize(int64_t size
, int sign
)
341 fatal("StoreController has no independent size\n");
345 SwapDir::updateSize(int64_t size
, int sign
)
347 int64_t blks
= (size
+ fs
.blksize
- 1) / fs
.blksize
;
348 int64_t k
= ((blks
* fs
.blksize
) >> 10) * sign
;
350 store_swap_size
+= k
;
359 StoreController::stat(StoreEntry
&output
) const
361 storeAppendPrintf(&output
, "Store Directory Statistics:\n");
362 storeAppendPrintf(&output
, "Store Entries : %lu\n",
363 (unsigned long int)StoreEntry::inUseCount());
364 storeAppendPrintf(&output
, "Maximum Swap Size : %"PRIu64
" KB\n",
366 storeAppendPrintf(&output
, "Current Store Swap Size: %8lu KB\n",
368 storeAppendPrintf(&output
, "Current Capacity : %"PRId64
"%% used, %"PRId64
"%% free\n",
369 Math::int64Percent(store_swap_size
, maxSize()),
370 Math::int64Percent((maxSize() - store_swap_size
), maxSize()));
371 /* FIXME Here we should output memory statistics */
373 /* now the swapDir */
374 swapDir
->stat(output
);
377 /* if needed, this could be taught to cache the result */
379 StoreController::maxSize() const
381 /* TODO: include memory cache ? */
382 return swapDir
->maxSize();
386 StoreController::minSize() const
388 /* TODO: include memory cache ? */
389 return swapDir
->minSize();
395 if (cur_size
>= max_size
)
400 debugs(20, 1, "WARNING: Shrinking cache_dir #" << index
<< " to " << cur_size
<< " KB");
404 storeDirOpenSwapLogs(void)
406 for (int dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
407 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->openLog();
411 storeDirCloseSwapLogs(void)
413 for (int dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
414 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->closeLog();
418 * storeDirWriteCleanLogs
420 * Writes a "clean" swap log file from in-memory metadata.
421 * This is a rewrite of the original function to troll each
422 * StoreDir and write the logs, and flush at the end of
423 * the run. Thanks goes to Eric Stern, since this solution
424 * came out of his COSS code.
427 storeDirWriteCleanLogs(int reopen
)
429 const StoreEntry
*e
= NULL
;
432 struct timeval start
;
434 RefCount
<SwapDir
> sd
;
438 if (StoreController::store_dirs_rebuilding
) {
439 debugs(20, 1, "Not currently OK to rewrite swap log.");
440 debugs(20, 1, "storeDirWriteCleanLogs: Operation aborted.");
444 debugs(20, 1, "storeDirWriteCleanLogs: Starting...");
446 start
= current_time
;
448 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++) {
449 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
451 if (sd
->writeCleanStart() < 0) {
452 debugs(20, 1, "log.clean.start() failed for dir #" << sd
->index
);
458 * This may look inefficient as CPU wise it is more efficient to do this
459 * sequentially, but I/O wise the parallellism helps as it allows more
460 * hdd spindles to be active.
465 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++) {
466 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
468 if (NULL
== sd
->cleanLog
)
471 e
= sd
->cleanLog
->nextEntry();
481 sd
->cleanLog
->write(*e
);
483 if ((++n
& 0xFFFF) == 0) {
485 debugs(20, 1, " " << std::setw(7) << n
<<
486 " entries written so far.");
492 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++)
493 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->writeCleanDone();
496 storeDirOpenSwapLogs();
500 dt
= tvSubDsec(start
, current_time
);
502 debugs(20, 1, " Finished. Wrote " << n
<< " entries.");
503 debugs(20, 1, " Took "<< std::setw(3)<< std::setprecision(2) << dt
<<
504 " seconds ("<< std::setw(6) << ((double) n
/ (dt
> 0.0 ? dt
: 1.0)) << " entries/sec).");
511 StoreController::search(String
const url
, HttpRequest
*request
)
513 /* cheat, for now you can't search the memory hot cache */
514 return swapDir
->search(url
, request
);
518 StoreHashIndex::store(int const x
) const
524 StoreController::sync(void)
526 /* sync mem cache? */
531 * handle callbacks all avaliable fs'es
534 StoreController::callback()
536 /* This will likely double count. Thats ok. */
537 PROF_start(storeDirCallback
);
539 /* mem cache callbacks ? */
540 int result
= swapDir
->callback();
542 PROF_stop(storeDirCallback
);
548 storeDirGetBlkSize(const char *path
, int *blksize
)
554 if (statvfs(path
, &sfs
)) {
555 debugs(50, 1, "" << path
<< ": " << xstrerror());
560 *blksize
= (int) sfs
.f_frsize
;
565 if (statfs(path
, &sfs
)) {
566 debugs(50, 1, "" << path
<< ": " << xstrerror());
571 *blksize
= (int) sfs
.f_bsize
;
574 * Sanity check; make sure we have a meaningful value.
583 #define fsbtoblk(num, fsbs, bs) \
584 (((fsbs) != 0 && (fsbs) < (bs)) ? \
585 (num) / ((bs) / (fsbs)) : (num) * ((fsbs) / (bs)))
587 storeDirGetUFSStats(const char *path
, int *totl_kb
, int *free_kb
, int *totl_in
, int *free_in
)
593 if (statvfs(path
, &sfs
)) {
594 debugs(50, 1, "" << path
<< ": " << xstrerror());
598 *totl_kb
= (int) fsbtoblk(sfs
.f_blocks
, sfs
.f_frsize
, 1024);
599 *free_kb
= (int) fsbtoblk(sfs
.f_bfree
, sfs
.f_frsize
, 1024);
600 *totl_in
= (int) sfs
.f_files
;
601 *free_in
= (int) sfs
.f_ffree
;
606 if (statfs(path
, &sfs
)) {
607 debugs(50, 1, "" << path
<< ": " << xstrerror());
611 *totl_kb
= (int) fsbtoblk(sfs
.f_blocks
, sfs
.f_bsize
, 1024);
612 *free_kb
= (int) fsbtoblk(sfs
.f_bfree
, sfs
.f_bsize
, 1024);
613 *totl_in
= (int) sfs
.f_files
;
614 *free_in
= (int) sfs
.f_ffree
;
621 allocate_new_swapdir(SquidConfig::_cacheSwap
* swap
)
623 if (swap
->swapDirs
== NULL
) {
624 swap
->n_allocated
= 4;
625 swap
->swapDirs
= static_cast<StorePointer
*>(xcalloc(swap
->n_allocated
, sizeof(StorePointer
)));
628 if (swap
->n_allocated
== swap
->n_configured
) {
630 swap
->n_allocated
<<= 1;
631 tmp
= static_cast<StorePointer
*>(xcalloc(swap
->n_allocated
, sizeof(StorePointer
)));
632 xmemcpy(tmp
, swap
->swapDirs
, swap
->n_configured
* sizeof(SwapDir
*));
633 xfree(swap
->swapDirs
);
634 swap
->swapDirs
= tmp
;
639 free_cachedir(SquidConfig::_cacheSwap
* swap
)
642 /* DON'T FREE THESE FOR RECONFIGURE */
647 for (i
= 0; i
< swap
->n_configured
; i
++) {
648 /* TODO XXX this lets the swapdir free resources asynchronously
649 * swap->swapDirs[i]->deactivate();
650 * but there may be such a means already.
653 swap
->swapDirs
[i
] = NULL
;
656 safe_free(swap
->swapDirs
);
657 swap
->swapDirs
= NULL
;
658 swap
->n_allocated
= 0;
659 swap
->n_configured
= 0;
662 /* this should be a virtual method on StoreEntry,
663 * i.e. e->referenced()
664 * so that the entry can notify the creating Store
667 StoreController::reference(StoreEntry
&e
)
669 /* Notify the fs that we're referencing this object again */
671 if (e
.swap_dirn
> -1)
672 e
.store()->reference(e
);
674 /* Notify the memory cache that we're referencing this object again */
676 if (mem_policy
->Referenced
)
677 mem_policy
->Referenced(mem_policy
, &e
, &e
.mem_obj
->repl
);
682 StoreController::dereference(StoreEntry
& e
)
684 /* Notify the fs that we're not referencing this object any more */
686 if (e
.swap_filen
> -1)
687 e
.store()->dereference(e
);
689 /* Notify the memory cache that we're not referencing this object any more */
691 if (mem_policy
->Dereferenced
)
692 mem_policy
->Dereferenced(mem_policy
, &e
, &e
.mem_obj
->repl
);
699 (const cache_key
*key
)
709 (String
const key
, STOREGETCLIENT aCallback
, void *aCallbackData
)
711 fatal("not implemented");
714 StoreHashIndex::StoreHashIndex()
718 assert (store_table
== NULL
);
721 StoreHashIndex::~StoreHashIndex()
724 hashFreeItems(store_table
, destroyStoreEntry
);
725 hashFreeMemory(store_table
);
731 StoreHashIndex::callback()
740 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
741 if (ndir
>= Config
.cacheSwap
.n_configured
)
742 ndir
= ndir
% Config
.cacheSwap
.n_configured
;
744 int temp_result
= store(ndir
)->callback();
750 result
+= temp_result
;
753 fatal ("too much io\n");
763 StoreHashIndex::create()
765 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
769 /* Lookup an object in the cache.
770 * return just a reference to object, don't start swapping in yet. */
774 (const cache_key
*key
)
776 PROF_start(storeGet
);
777 debugs(20, 3, "storeGet: looking up " << storeKeyText(key
));
778 StoreEntry
*p
= static_cast<StoreEntry
*>(hash_lookup(store_table
, key
));
786 (String
const key
, STOREGETCLIENT aCallback
, void *aCallbackData
)
788 fatal("not implemented");
792 StoreHashIndex::init()
794 /* Calculate size of hash table (maximum currently 64k buckets). */
795 /* this is very bogus, its specific to the any Store maintaining an
796 * in-core index, not global */
797 size_t buckets
= (Store::Root().maxSize() + ( Config
.memMaxSize
>> 10)) / Config
.Store
.avgObjectSize
;
798 debugs(20, 1, "Swap maxSize " << Store::Root().maxSize() <<
799 " + " << ( Config
.memMaxSize
>> 10) << " KB, estimated " << buckets
<< " objects");
800 buckets
/= Config
.Store
.objectsPerBucket
;
801 debugs(20, 1, "Target number of buckets: " << buckets
);
802 /* ideally the full scan period should be configurable, for the
803 * moment it remains at approximately 24 hours. */
804 store_hash_buckets
= storeKeyHashBuckets(buckets
);
805 debugs(20, 1, "Using " << store_hash_buckets
<< " Store buckets");
806 debugs(20, 1, "Max Mem size: " << ( Config
.memMaxSize
>> 10) << " KB");
807 debugs(20, 1, "Max Swap size: " << Store::Root().maxSize() << " KB");
809 store_table
= hash_create(storeKeyHashCmp
,
810 store_hash_buckets
, storeKeyHashHash
);
812 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
813 /* this starts a search of the store dirs, loading their
814 * index. under the new Store api this should be
815 * driven by the StoreHashIndex, not by each store.
817 * That is, the HashIndex should perform a search of each dir it is
818 * indexing to do the hash insertions. The search is then able to
819 * decide 'from-memory', or 'from-clean-log' or 'from-dirty-log' or
822 * Step 1: make the store rebuilds use a search internally
823 * Step 2: change the search logic to use the four modes described
825 * Step 3: have the hash index walk the searches itself.
832 StoreHashIndex::maxSize() const
836 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
837 result
+= store(i
)->maxSize();
843 StoreHashIndex::minSize() const
847 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
848 result
+= store(i
)->minSize();
854 StoreHashIndex::stat(StoreEntry
& output
) const
858 /* Now go through each store, calling its stat routine */
860 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
861 storeAppendPrintf(&output
, "\n");
862 store(i
)->stat(output
);
867 StoreHashIndex::reference(StoreEntry
&)
871 StoreHashIndex::dereference(StoreEntry
&)
875 StoreHashIndex::maintain()
880 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
881 /* XXX FixMe: This should be done "in parallell" on the different
882 * cache_dirs, not one at a time.
884 /* call the maintain function .. */
885 store(i
)->maintain();
890 StoreHashIndex::updateSize(int64_t, int)
894 StoreHashIndex::sync()
896 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
)
901 StoreHashIndex::search(String
const url
, HttpRequest
*)
904 fatal ("Cannot search by url yet\n");
906 return new StoreSearchHashIndex (this);
909 CBDATA_CLASS_INIT(StoreSearchHashIndex
);
911 StoreSearchHashIndex::StoreSearchHashIndex(RefCount
<StoreHashIndex
> aSwapDir
) : sd(aSwapDir
), _done (false), bucket (0)
915 StoreSearchHashIndex::StoreSearchHashIndex(StoreSearchHashIndex const &);
918 StoreSearchHashIndex::~StoreSearchHashIndex()
922 StoreSearchHashIndex::next(void (aCallback
)(void *), void *aCallbackData
)
925 aCallback (aCallbackData
);
929 StoreSearchHashIndex::next()
934 while (!isDone() && !entries
.size())
937 return currentItem() != NULL
;
941 StoreSearchHashIndex::error() const
947 StoreSearchHashIndex::isDone() const
949 return bucket
>= store_hash_buckets
|| _done
;
953 StoreSearchHashIndex::currentItem()
958 return entries
.back();
962 StoreSearchHashIndex::copyBucket()
964 /* probably need to lock the store entries...
965 * we copy them all to prevent races on the links. */
966 debugs(47, 3, "StoreSearchHashIndex::copyBucket #" << bucket
);
967 assert (!entries
.size());
968 hash_link
*link_ptr
= NULL
;
969 hash_link
*link_next
= NULL
;
970 link_next
= hash_get_bucket(store_table
, bucket
);
972 while (NULL
!= (link_ptr
= link_next
)) {
973 link_next
= link_ptr
->next
;
974 StoreEntry
*e
= (StoreEntry
*) link_ptr
;
976 entries
.push_back(e
);
980 debugs(47,3, "got entries: " << entries
.size());