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 min and max unset,
155 * ie any-sized-object swapdirs. This is a good thing.
158 SwapDir::objectSizeIsAcceptable(int64_t objsize
) const
160 // If the swapdir has no range limits, then it definitely can
161 if (min_objsize
<= 0 && max_objsize
== -1)
165 * If the object size is -1 and the storedir has limits we
166 * can't store it there.
171 // Else, make sure that the object size will fit.
172 return min_objsize
<= objsize
&& max_objsize
> objsize
;
177 * This new selection scheme simply does round-robin on all SwapDirs.
178 * A SwapDir is skipped if it is over the max_size (100%) limit, or
182 storeDirSelectSwapDirRoundRobin(const StoreEntry
* e
)
187 RefCount
<SwapDir
> sd
;
189 ssize_t objsize
= e
->objectLen();
191 objsize
+= e
->mem_obj
->swap_hdr_sz
;
193 for (i
= 0; i
<= Config
.cacheSwap
.n_configured
; i
++) {
194 if (++dirn
>= Config
.cacheSwap
.n_configured
)
197 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
199 if (sd
->flags
.read_only
)
202 if (sd
->cur_size
> sd
->max_size
)
205 if (!sd
->objectSizeIsAcceptable(objsize
))
208 /* check for error or overload condition */
209 load
= sd
->canStore(*e
);
211 if (load
< 0 || load
> 1000) {
222 * Spread load across all of the store directories
224 * Note: We should modify this later on to prefer sticking objects
225 * in the *tightest fit* swapdir to conserve space, along with the
226 * actual swapdir usage. But for now, this hack will do while
227 * testing, so you should order your swapdirs in the config file
228 * from smallest maxobjsize to unlimited (-1) maxobjsize.
230 * We also have to choose nleast == nconf since we need to consider
231 * ALL swapdirs, regardless of state. Again, this is a hack while
232 * we sort out the real usefulness of this algorithm.
235 storeDirSelectSwapDirLeastLoad(const StoreEntry
* e
)
238 ssize_t most_free
= 0, cur_free
;
239 ssize_t least_objsize
= -1;
240 int least_load
= INT_MAX
;
244 RefCount
<SwapDir
> SD
;
246 /* Calculate the object size */
247 objsize
= e
->objectLen();
250 objsize
+= e
->mem_obj
->swap_hdr_sz
;
252 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
253 SD
= dynamic_cast<SwapDir
*>(INDEXSD(i
));
254 SD
->flags
.selected
= 0;
255 load
= SD
->canStore(*e
);
257 if (load
< 0 || load
> 1000) {
261 if (!SD
->objectSizeIsAcceptable(objsize
))
264 if (SD
->flags
.read_only
)
267 if (SD
->cur_size
> SD
->max_size
)
270 if (load
> least_load
)
273 cur_free
= SD
->max_size
- SD
->cur_size
;
275 /* If the load is equal, then look in more details */
276 if (load
== least_load
) {
277 /* closest max_objsize fit */
279 if (least_objsize
!= -1)
280 if (SD
->max_objsize
> least_objsize
|| SD
->max_objsize
== -1)
284 if (cur_free
< most_free
)
289 least_objsize
= SD
->max_objsize
;
290 most_free
= cur_free
;
295 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->flags
.selected
= 1;
301 * An entry written to the swap log MUST have the following
303 * 1. It MUST be a public key. It does no good to log
304 * a public ADD, change the key, then log a private
305 * DEL. So we need to log a DEL before we change a
306 * key from public to private.
307 * 2. It MUST have a valid (> -1) swap_filen.
310 storeDirSwapLog(const StoreEntry
* e
, int op
)
313 assert(!EBIT_TEST(e
->flags
, KEY_PRIVATE
));
314 assert(e
->swap_filen
>= 0);
316 * icons and such; don't write them to the swap log
319 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
))
322 assert(op
> SWAP_LOG_NOP
&& op
< SWAP_LOG_MAX
);
324 debugs(20, 3, "storeDirSwapLog: " <<
325 swap_log_op_str
[op
] << " " <<
326 e
->getMD5Text() << " " <<
327 e
->swap_dirn
<< " " <<
328 std::hex
<< std::uppercase
<< std::setfill('0') << std::setw(8) << e
->swap_filen
);
330 dynamic_cast<SwapDir
*>(INDEXSD(e
->swap_dirn
))->logEntry(*e
, op
);
334 StoreController::updateSize(int64_t size
, int sign
)
336 fatal("StoreController has no independent size\n");
340 SwapDir::updateSize(int64_t size
, int sign
)
342 int64_t blks
= (size
+ fs
.blksize
- 1) / fs
.blksize
;
343 int64_t k
= ((blks
* fs
.blksize
) >> 10) * sign
;
345 store_swap_size
+= k
;
354 StoreController::stat(StoreEntry
&output
) const
356 storeAppendPrintf(&output
, "Store Directory Statistics:\n");
357 storeAppendPrintf(&output
, "Store Entries : %lu\n",
358 (unsigned long int)StoreEntry::inUseCount());
359 storeAppendPrintf(&output
, "Maximum Swap Size : %"PRIu64
" KB\n",
361 storeAppendPrintf(&output
, "Current Store Swap Size: %8lu KB\n",
363 storeAppendPrintf(&output
, "Current Capacity : %"PRId64
"%% used, %"PRId64
"%% free\n",
364 Math::int64Percent(store_swap_size
, maxSize()),
365 Math::int64Percent((maxSize() - store_swap_size
), maxSize()));
366 /* FIXME Here we should output memory statistics */
368 /* now the swapDir */
369 swapDir
->stat(output
);
372 /* if needed, this could be taught to cache the result */
374 StoreController::maxSize() const
376 /* TODO: include memory cache ? */
377 return swapDir
->maxSize();
381 StoreController::minSize() const
383 /* TODO: include memory cache ? */
384 return swapDir
->minSize();
390 if (cur_size
>= max_size
)
395 debugs(20, 1, "WARNING: Shrinking cache_dir #" << index
<< " to " << cur_size
<< " KB");
399 storeDirOpenSwapLogs(void)
401 for (int dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
402 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->openLog();
406 storeDirCloseSwapLogs(void)
408 for (int dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
409 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->closeLog();
413 * storeDirWriteCleanLogs
415 * Writes a "clean" swap log file from in-memory metadata.
416 * This is a rewrite of the original function to troll each
417 * StoreDir and write the logs, and flush at the end of
418 * the run. Thanks goes to Eric Stern, since this solution
419 * came out of his COSS code.
422 storeDirWriteCleanLogs(int reopen
)
424 const StoreEntry
*e
= NULL
;
427 struct timeval start
;
429 RefCount
<SwapDir
> sd
;
433 if (StoreController::store_dirs_rebuilding
) {
434 debugs(20, 1, "Not currently OK to rewrite swap log.");
435 debugs(20, 1, "storeDirWriteCleanLogs: Operation aborted.");
439 debugs(20, 1, "storeDirWriteCleanLogs: Starting...");
441 start
= current_time
;
443 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++) {
444 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
446 if (sd
->writeCleanStart() < 0) {
447 debugs(20, 1, "log.clean.start() failed for dir #" << sd
->index
);
453 * This may look inefficient as CPU wise it is more efficient to do this
454 * sequentially, but I/O wise the parallellism helps as it allows more
455 * hdd spindles to be active.
460 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++) {
461 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
463 if (NULL
== sd
->cleanLog
)
466 e
= sd
->cleanLog
->nextEntry();
476 sd
->cleanLog
->write(*e
);
478 if ((++n
& 0xFFFF) == 0) {
480 debugs(20, 1, " " << std::setw(7) << n
<<
481 " entries written so far.");
487 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; dirn
++)
488 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->writeCleanDone();
491 storeDirOpenSwapLogs();
495 dt
= tvSubDsec(start
, current_time
);
497 debugs(20, 1, " Finished. Wrote " << n
<< " entries.");
498 debugs(20, 1, " Took "<< std::setw(3)<< std::setprecision(2) << dt
<<
499 " seconds ("<< std::setw(6) << ((double) n
/ (dt
> 0.0 ? dt
: 1.0)) << " entries/sec).");
506 StoreController::search(String
const url
, HttpRequest
*request
)
508 /* cheat, for now you can't search the memory hot cache */
509 return swapDir
->search(url
, request
);
513 StoreHashIndex::store(int const x
) const
519 StoreController::sync(void)
521 /* sync mem cache? */
526 * handle callbacks all avaliable fs'es
529 StoreController::callback()
531 /* This will likely double count. Thats ok. */
532 PROF_start(storeDirCallback
);
534 /* mem cache callbacks ? */
535 int result
= swapDir
->callback();
537 PROF_stop(storeDirCallback
);
543 storeDirGetBlkSize(const char *path
, int *blksize
)
549 if (statvfs(path
, &sfs
)) {
550 debugs(50, 1, "" << path
<< ": " << xstrerror());
555 *blksize
= (int) sfs
.f_frsize
;
560 if (statfs(path
, &sfs
)) {
561 debugs(50, 1, "" << path
<< ": " << xstrerror());
566 *blksize
= (int) sfs
.f_bsize
;
569 * Sanity check; make sure we have a meaningful value.
578 #define fsbtoblk(num, fsbs, bs) \
579 (((fsbs) != 0 && (fsbs) < (bs)) ? \
580 (num) / ((bs) / (fsbs)) : (num) * ((fsbs) / (bs)))
582 storeDirGetUFSStats(const char *path
, int *totl_kb
, int *free_kb
, int *totl_in
, int *free_in
)
588 if (statvfs(path
, &sfs
)) {
589 debugs(50, 1, "" << path
<< ": " << xstrerror());
593 *totl_kb
= (int) fsbtoblk(sfs
.f_blocks
, sfs
.f_frsize
, 1024);
594 *free_kb
= (int) fsbtoblk(sfs
.f_bfree
, sfs
.f_frsize
, 1024);
595 *totl_in
= (int) sfs
.f_files
;
596 *free_in
= (int) sfs
.f_ffree
;
601 if (statfs(path
, &sfs
)) {
602 debugs(50, 1, "" << path
<< ": " << xstrerror());
606 *totl_kb
= (int) fsbtoblk(sfs
.f_blocks
, sfs
.f_bsize
, 1024);
607 *free_kb
= (int) fsbtoblk(sfs
.f_bfree
, sfs
.f_bsize
, 1024);
608 *totl_in
= (int) sfs
.f_files
;
609 *free_in
= (int) sfs
.f_ffree
;
616 allocate_new_swapdir(SquidConfig::_cacheSwap
* swap
)
618 if (swap
->swapDirs
== NULL
) {
619 swap
->n_allocated
= 4;
620 swap
->swapDirs
= static_cast<StorePointer
*>(xcalloc(swap
->n_allocated
, sizeof(StorePointer
)));
623 if (swap
->n_allocated
== swap
->n_configured
) {
625 swap
->n_allocated
<<= 1;
626 tmp
= static_cast<StorePointer
*>(xcalloc(swap
->n_allocated
, sizeof(StorePointer
)));
627 memcpy(tmp
, swap
->swapDirs
, swap
->n_configured
* sizeof(SwapDir
*));
628 xfree(swap
->swapDirs
);
629 swap
->swapDirs
= tmp
;
634 free_cachedir(SquidConfig::_cacheSwap
* swap
)
637 /* DON'T FREE THESE FOR RECONFIGURE */
642 for (i
= 0; i
< swap
->n_configured
; i
++) {
643 /* TODO XXX this lets the swapdir free resources asynchronously
644 * swap->swapDirs[i]->deactivate();
645 * but there may be such a means already.
648 swap
->swapDirs
[i
] = NULL
;
651 safe_free(swap
->swapDirs
);
652 swap
->swapDirs
= NULL
;
653 swap
->n_allocated
= 0;
654 swap
->n_configured
= 0;
657 /* this should be a virtual method on StoreEntry,
658 * i.e. e->referenced()
659 * so that the entry can notify the creating Store
662 StoreController::reference(StoreEntry
&e
)
664 /* Notify the fs that we're referencing this object again */
666 if (e
.swap_dirn
> -1)
667 e
.store()->reference(e
);
669 /* Notify the memory cache that we're referencing this object again */
671 if (mem_policy
->Referenced
)
672 mem_policy
->Referenced(mem_policy
, &e
, &e
.mem_obj
->repl
);
677 StoreController::dereference(StoreEntry
& e
)
679 /* Notify the fs that we're not referencing this object any more */
681 if (e
.swap_filen
> -1)
682 e
.store()->dereference(e
);
684 /* Notify the memory cache that we're not referencing this object any more */
686 if (mem_policy
->Dereferenced
)
687 mem_policy
->Dereferenced(mem_policy
, &e
, &e
.mem_obj
->repl
);
694 (const cache_key
*key
)
704 (String
const key
, STOREGETCLIENT aCallback
, void *aCallbackData
)
706 fatal("not implemented");
709 StoreHashIndex::StoreHashIndex()
713 assert (store_table
== NULL
);
716 StoreHashIndex::~StoreHashIndex()
719 hashFreeItems(store_table
, destroyStoreEntry
);
720 hashFreeMemory(store_table
);
726 StoreHashIndex::callback()
735 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
736 if (ndir
>= Config
.cacheSwap
.n_configured
)
737 ndir
= ndir
% Config
.cacheSwap
.n_configured
;
739 int temp_result
= store(ndir
)->callback();
745 result
+= temp_result
;
748 fatal ("too much io\n");
758 StoreHashIndex::create()
760 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
764 /* Lookup an object in the cache.
765 * return just a reference to object, don't start swapping in yet. */
769 (const cache_key
*key
)
771 PROF_start(storeGet
);
772 debugs(20, 3, "storeGet: looking up " << storeKeyText(key
));
773 StoreEntry
*p
= static_cast<StoreEntry
*>(hash_lookup(store_table
, key
));
781 (String
const key
, STOREGETCLIENT aCallback
, void *aCallbackData
)
783 fatal("not implemented");
787 StoreHashIndex::init()
789 /* Calculate size of hash table (maximum currently 64k buckets). */
790 /* this is very bogus, its specific to the any Store maintaining an
791 * in-core index, not global */
792 size_t buckets
= (Store::Root().maxSize() + ( Config
.memMaxSize
>> 10)) / Config
.Store
.avgObjectSize
;
793 debugs(20, 1, "Swap maxSize " << Store::Root().maxSize() <<
794 " + " << ( Config
.memMaxSize
>> 10) << " KB, estimated " << buckets
<< " objects");
795 buckets
/= Config
.Store
.objectsPerBucket
;
796 debugs(20, 1, "Target number of buckets: " << buckets
);
797 /* ideally the full scan period should be configurable, for the
798 * moment it remains at approximately 24 hours. */
799 store_hash_buckets
= storeKeyHashBuckets(buckets
);
800 debugs(20, 1, "Using " << store_hash_buckets
<< " Store buckets");
801 debugs(20, 1, "Max Mem size: " << ( Config
.memMaxSize
>> 10) << " KB");
802 debugs(20, 1, "Max Swap size: " << Store::Root().maxSize() << " KB");
804 store_table
= hash_create(storeKeyHashCmp
,
805 store_hash_buckets
, storeKeyHashHash
);
807 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
808 /* this starts a search of the store dirs, loading their
809 * index. under the new Store api this should be
810 * driven by the StoreHashIndex, not by each store.
812 * That is, the HashIndex should perform a search of each dir it is
813 * indexing to do the hash insertions. The search is then able to
814 * decide 'from-memory', or 'from-clean-log' or 'from-dirty-log' or
817 * Step 1: make the store rebuilds use a search internally
818 * Step 2: change the search logic to use the four modes described
820 * Step 3: have the hash index walk the searches itself.
827 StoreHashIndex::maxSize() const
831 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
832 result
+= store(i
)->maxSize();
838 StoreHashIndex::minSize() const
842 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++)
843 result
+= store(i
)->minSize();
849 StoreHashIndex::stat(StoreEntry
& output
) const
853 /* Now go through each store, calling its stat routine */
855 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
856 storeAppendPrintf(&output
, "\n");
857 store(i
)->stat(output
);
862 StoreHashIndex::reference(StoreEntry
&)
866 StoreHashIndex::dereference(StoreEntry
&)
870 StoreHashIndex::maintain()
875 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; i
++) {
876 /* XXX FixMe: This should be done "in parallell" on the different
877 * cache_dirs, not one at a time.
879 /* call the maintain function .. */
880 store(i
)->maintain();
885 StoreHashIndex::updateSize(int64_t, int)
889 StoreHashIndex::sync()
891 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
)
896 StoreHashIndex::search(String
const url
, HttpRequest
*)
899 fatal ("Cannot search by url yet\n");
901 return new StoreSearchHashIndex (this);
904 CBDATA_CLASS_INIT(StoreSearchHashIndex
);
906 StoreSearchHashIndex::StoreSearchHashIndex(RefCount
<StoreHashIndex
> aSwapDir
) : sd(aSwapDir
), _done (false), bucket (0)
910 StoreSearchHashIndex::StoreSearchHashIndex(StoreSearchHashIndex const &);
913 StoreSearchHashIndex::~StoreSearchHashIndex()
917 StoreSearchHashIndex::next(void (aCallback
)(void *), void *aCallbackData
)
920 aCallback (aCallbackData
);
924 StoreSearchHashIndex::next()
929 while (!isDone() && !entries
.size())
932 return currentItem() != NULL
;
936 StoreSearchHashIndex::error() const
942 StoreSearchHashIndex::isDone() const
944 return bucket
>= store_hash_buckets
|| _done
;
948 StoreSearchHashIndex::currentItem()
953 return entries
.back();
957 StoreSearchHashIndex::copyBucket()
959 /* probably need to lock the store entries...
960 * we copy them all to prevent races on the links. */
961 debugs(47, 3, "StoreSearchHashIndex::copyBucket #" << bucket
);
962 assert (!entries
.size());
963 hash_link
*link_ptr
= NULL
;
964 hash_link
*link_next
= NULL
;
965 link_next
= hash_get_bucket(store_table
, bucket
);
967 while (NULL
!= (link_ptr
= link_next
)) {
968 link_next
= link_ptr
->next
;
969 StoreEntry
*e
= (StoreEntry
*) link_ptr
;
971 entries
.push_back(e
);
975 debugs(47,3, "got entries: " << entries
.size());