]> git.ipfire.org Git - thirdparty/squid.git/blob - src/store_dir.cc
Improve statistic reporting for shared Rock caches.
[thirdparty/squid.git] / src / store_dir.cc
1
2 /*
3 * $Id$
4 *
5 * DEBUG: section 47 Store Directory Routines
6 * AUTHOR: Duane Wessels
7 *
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
10 *
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.
19 *
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.
24 *
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.
29 *
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.
33 *
34 */
35
36 #include "squid.h"
37 #include "Store.h"
38 #include "MemObject.h"
39 #include "MemStore.h"
40 #include "mem_node.h"
41 #include "SquidMath.h"
42 #include "SquidTime.h"
43 #include "SwapDir.h"
44 #include "swap_log_op.h"
45
46 #if HAVE_STATVFS
47 #if HAVE_SYS_STATVFS_H
48 #include <sys/statvfs.h>
49 #endif
50 #endif /* HAVE_STATVFS */
51 /* statfs() needs <sys/param.h> and <sys/mount.h> on BSD systems */
52 #if HAVE_SYS_PARAM_H
53 #include <sys/param.h>
54 #endif
55 #if HAVE_SYS_MOUNT_H
56 #include <sys/mount.h>
57 #endif
58 /* Windows and Linux use sys/vfs.h */
59 #if HAVE_SYS_VFS_H
60 #include <sys/vfs.h>
61 #endif
62
63 #include "StoreHashIndex.h"
64
65 static STDIRSELECT storeDirSelectSwapDirRoundRobin;
66 static STDIRSELECT storeDirSelectSwapDirLeastLoad;
67
68 /*
69 * store_dirs_rebuilding is initialized to _1_ as a hack so that
70 * storeDirWriteCleanLogs() doesn't try to do anything unless _all_
71 * cache_dirs have been read. For example, without this hack, Squid
72 * will try to write clean log files if -kparse fails (becasue it
73 * calls fatal()).
74 */
75 int StoreController::store_dirs_rebuilding = 1;
76
77 StoreController::StoreController() : swapDir (new StoreHashIndex())
78 , memStore(NULL)
79 {}
80
81 StoreController::~StoreController()
82 {
83 delete memStore;
84 }
85
86 /*
87 * This function pointer is set according to 'store_dir_select_algorithm'
88 * in squid.conf.
89 */
90 STDIRSELECT *storeDirSelectSwapDir = storeDirSelectSwapDirLeastLoad;
91
92 void
93 StoreController::init()
94 {
95 // XXX: add: if (UsingSmp())
96 memStore = new MemStore;
97 memStore->init();
98
99 swapDir->init();
100
101 if (0 == strcasecmp(Config.store_dir_select_algorithm, "round-robin")) {
102 storeDirSelectSwapDir = storeDirSelectSwapDirRoundRobin;
103 debugs(47, 1, "Using Round Robin store dir selection");
104 } else {
105 storeDirSelectSwapDir = storeDirSelectSwapDirLeastLoad;
106 debugs(47, 1, "Using Least Load store dir selection");
107 }
108 }
109
110 void
111 StoreController::createOneStore(Store &aStore)
112 {
113 /*
114 * On Windows, fork() is not available.
115 * The following is a workaround for create store directories sequentially
116 * when running on native Windows port.
117 */
118 #ifndef _SQUID_MSWIN_
119
120 if (fork())
121 return;
122
123 #endif
124
125 aStore.create();
126
127 #ifndef _SQUID_MSWIN_
128
129 exit(0);
130
131 #endif
132 }
133
134 void
135 StoreController::create()
136 {
137 swapDir->create();
138
139 #ifndef _SQUID_MSWIN_
140
141 pid_t pid;
142
143 do {
144 int status;
145 #ifdef _SQUID_NEXT_
146
147 pid = wait3(&status, WNOHANG, NULL);
148 #else
149
150 pid = waitpid(-1, &status, 0);
151 #endif
152
153 } while (pid > 0 || (pid < 0 && errno == EINTR));
154
155 #endif
156 }
157
158 /**
159 * Determine whether the given directory can handle this object
160 * size
161 *
162 * Note: if the object size is -1, then the only swapdirs that
163 * will return true here are ones that have min and max unset,
164 * ie any-sized-object swapdirs. This is a good thing.
165 */
166 bool
167 SwapDir::objectSizeIsAcceptable(int64_t objsize) const
168 {
169 // If the swapdir has no range limits, then it definitely can
170 if (min_objsize <= 0 && max_objsize == -1)
171 return true;
172
173 /*
174 * If the object size is -1 and the storedir has limits we
175 * can't store it there.
176 */
177 if (objsize == -1)
178 return false;
179
180 // Else, make sure that the object size will fit.
181 return min_objsize <= objsize && max_objsize > objsize;
182 }
183
184
185 /*
186 * This new selection scheme simply does round-robin on all SwapDirs.
187 * A SwapDir is skipped if it is over the max_size (100%) limit, or
188 * overloaded.
189 */
190 static int
191 storeDirSelectSwapDirRoundRobin(const StoreEntry * e)
192 {
193 static int dirn = 0;
194 int i;
195 int load;
196 RefCount<SwapDir> sd;
197
198 // e->objectLen() is negative at this point when we are still STORE_PENDING
199 ssize_t objsize = e->mem_obj->expectedReplySize();
200 if (objsize != -1)
201 objsize += e->mem_obj->swap_hdr_sz;
202
203 for (i = 0; i < Config.cacheSwap.n_configured; i++) {
204 if (++dirn >= Config.cacheSwap.n_configured)
205 dirn = 0;
206
207 sd = dynamic_cast<SwapDir *>(INDEXSD(dirn));
208
209 if (!sd->canStore(*e, objsize, load))
210 continue;
211
212 if (load < 0 || load > 1000) {
213 continue;
214 }
215
216 return dirn;
217 }
218
219 return -1;
220 }
221
222 /*
223 * Spread load across all of the store directories
224 *
225 * Note: We should modify this later on to prefer sticking objects
226 * in the *tightest fit* swapdir to conserve space, along with the
227 * actual swapdir usage. But for now, this hack will do while
228 * testing, so you should order your swapdirs in the config file
229 * from smallest maxobjsize to unlimited (-1) maxobjsize.
230 *
231 * We also have to choose nleast == nconf since we need to consider
232 * ALL swapdirs, regardless of state. Again, this is a hack while
233 * we sort out the real usefulness of this algorithm.
234 */
235 static int
236 storeDirSelectSwapDirLeastLoad(const StoreEntry * e)
237 {
238 ssize_t most_free = 0, cur_free;
239 ssize_t least_objsize = -1;
240 int least_load = INT_MAX;
241 int load;
242 int dirn = -1;
243 int i;
244 RefCount<SwapDir> SD;
245
246 // e->objectLen() is negative at this point when we are still STORE_PENDING
247 ssize_t objsize = e->mem_obj->expectedReplySize();
248
249 if (objsize != -1)
250 objsize += e->mem_obj->swap_hdr_sz;
251
252 for (i = 0; i < Config.cacheSwap.n_configured; i++) {
253 SD = dynamic_cast<SwapDir *>(INDEXSD(i));
254 SD->flags.selected = 0;
255
256 if (!SD->canStore(*e, objsize, load))
257 continue;
258
259 if (load < 0 || load > 1000)
260 continue;
261
262 if (load > least_load)
263 continue;
264
265 cur_free = SD->max_size - SD->cur_size;
266
267 /* If the load is equal, then look in more details */
268 if (load == least_load) {
269 /* closest max_objsize fit */
270
271 if (least_objsize != -1)
272 if (SD->max_objsize > least_objsize || SD->max_objsize == -1)
273 continue;
274
275 /* most free */
276 if (cur_free < most_free)
277 continue;
278 }
279
280 least_load = load;
281 least_objsize = SD->max_objsize;
282 most_free = cur_free;
283 dirn = i;
284 }
285
286 if (dirn >= 0)
287 dynamic_cast<SwapDir *>(INDEXSD(dirn))->flags.selected = 1;
288
289 return dirn;
290 }
291
292 /*
293 * An entry written to the swap log MUST have the following
294 * properties.
295 * 1. It MUST be a public key. It does no good to log
296 * a public ADD, change the key, then log a private
297 * DEL. So we need to log a DEL before we change a
298 * key from public to private.
299 * 2. It MUST have a valid (> -1) swap_filen.
300 */
301 void
302 storeDirSwapLog(const StoreEntry * e, int op)
303 {
304 assert (e);
305 assert(!EBIT_TEST(e->flags, KEY_PRIVATE));
306 assert(e->swap_filen >= 0);
307 /*
308 * icons and such; don't write them to the swap log
309 */
310
311 if (EBIT_TEST(e->flags, ENTRY_SPECIAL))
312 return;
313
314 assert(op > SWAP_LOG_NOP && op < SWAP_LOG_MAX);
315
316 debugs(20, 3, "storeDirSwapLog: " <<
317 swap_log_op_str[op] << " " <<
318 e->getMD5Text() << " " <<
319 e->swap_dirn << " " <<
320 std::hex << std::uppercase << std::setfill('0') << std::setw(8) << e->swap_filen);
321
322 dynamic_cast<SwapDir *>(INDEXSD(e->swap_dirn))->logEntry(*e, op);
323 }
324
325 void
326 StoreController::updateSize(int64_t size, int sign)
327 {
328 fatal("StoreController has no independent size\n");
329 }
330
331 void
332 SwapDir::updateSize(int64_t size, int sign)
333 {
334 int64_t blks = (size + fs.blksize - 1) / fs.blksize;
335 int64_t k = ((blks * fs.blksize) >> 10) * sign;
336 cur_size += k;
337
338 if (sign > 0)
339 n_disk_objects++;
340 else if (sign < 0)
341 n_disk_objects--;
342 }
343
344 void
345 StoreController::stat(StoreEntry &output) const
346 {
347 storeAppendPrintf(&output, "Store Directory Statistics:\n");
348 storeAppendPrintf(&output, "Store Entries : %lu\n",
349 (unsigned long int)StoreEntry::inUseCount());
350 storeAppendPrintf(&output, "Maximum Swap Size : %"PRIu64" KB\n",
351 maxSize());
352 storeAppendPrintf(&output, "Current Store Swap Size: %8lu KB\n",
353 currentSize());
354 storeAppendPrintf(&output, "Current Capacity : %"PRId64"%% used, %"PRId64"%% free\n",
355 Math::int64Percent(currentSize(), maxSize()),
356 Math::int64Percent((maxSize() - currentSize()), maxSize()));
357
358 if (memStore)
359 memStore->stat(output);
360
361 /* now the swapDir */
362 swapDir->stat(output);
363 }
364
365 /* if needed, this could be taught to cache the result */
366 uint64_t
367 StoreController::maxSize() const
368 {
369 /* TODO: include memory cache ? */
370 return swapDir->maxSize();
371 }
372
373 uint64_t
374 StoreController::minSize() const
375 {
376 /* TODO: include memory cache ? */
377 return swapDir->minSize();
378 }
379
380 uint64_t
381 StoreController::currentSize() const
382 {
383 return swapDir->currentSize();
384 }
385
386 uint64_t
387 StoreController::currentCount() const
388 {
389 return swapDir->currentCount();
390 }
391
392 void
393 SwapDir::diskFull()
394 {
395 if (cur_size >= max_size)
396 return;
397
398 max_size = cur_size;
399
400 debugs(20, 1, "WARNING: Shrinking cache_dir #" << index << " to " << cur_size << " KB");
401 }
402
403 void
404 storeDirOpenSwapLogs(void)
405 {
406 for (int dirn = 0; dirn < Config.cacheSwap.n_configured; ++dirn)
407 dynamic_cast<SwapDir *>(INDEXSD(dirn))->openLog();
408 }
409
410 void
411 storeDirCloseSwapLogs(void)
412 {
413 for (int dirn = 0; dirn < Config.cacheSwap.n_configured; ++dirn)
414 dynamic_cast<SwapDir *>(INDEXSD(dirn))->closeLog();
415 }
416
417 /*
418 * storeDirWriteCleanLogs
419 *
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.
425 */
426 int
427 storeDirWriteCleanLogs(int reopen)
428 {
429 const StoreEntry *e = NULL;
430 int n = 0;
431
432 struct timeval start;
433 double dt;
434 RefCount<SwapDir> sd;
435 int dirn;
436 int notdone = 1;
437
438 if (StoreController::store_dirs_rebuilding) {
439 debugs(20, 1, "Not currently OK to rewrite swap log.");
440 debugs(20, 1, "storeDirWriteCleanLogs: Operation aborted.");
441 return 0;
442 }
443
444 debugs(20, 1, "storeDirWriteCleanLogs: Starting...");
445 getCurrentTime();
446 start = current_time;
447
448 for (dirn = 0; dirn < Config.cacheSwap.n_configured; dirn++) {
449 sd = dynamic_cast<SwapDir *>(INDEXSD(dirn));
450
451 if (sd->writeCleanStart() < 0) {
452 debugs(20, 1, "log.clean.start() failed for dir #" << sd->index);
453 continue;
454 }
455 }
456
457 /*
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.
461 */
462 while (notdone) {
463 notdone = 0;
464
465 for (dirn = 0; dirn < Config.cacheSwap.n_configured; dirn++) {
466 sd = dynamic_cast<SwapDir *>(INDEXSD(dirn));
467
468 if (NULL == sd->cleanLog)
469 continue;
470
471 e = sd->cleanLog->nextEntry();
472
473 if (!e)
474 continue;
475
476 notdone = 1;
477
478 if (!sd->canLog(*e))
479 continue;
480
481 sd->cleanLog->write(*e);
482
483 if ((++n & 0xFFFF) == 0) {
484 getCurrentTime();
485 debugs(20, 1, " " << std::setw(7) << n <<
486 " entries written so far.");
487 }
488 }
489 }
490
491 /* Flush */
492 for (dirn = 0; dirn < Config.cacheSwap.n_configured; dirn++)
493 dynamic_cast<SwapDir *>(INDEXSD(dirn))->writeCleanDone();
494
495 if (reopen)
496 storeDirOpenSwapLogs();
497
498 getCurrentTime();
499
500 dt = tvSubDsec(start, current_time);
501
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).");
505
506
507 return n;
508 }
509
510 StoreSearch *
511 StoreController::search(String const url, HttpRequest *request)
512 {
513 /* cheat, for now you can't search the memory hot cache */
514 return swapDir->search(url, request);
515 }
516
517 StorePointer
518 StoreHashIndex::store(int const x) const
519 {
520 return INDEXSD(x);
521 }
522
523 SwapDir &
524 StoreHashIndex::dir(const int i) const
525 {
526 SwapDir *sd = dynamic_cast<SwapDir*>(INDEXSD(i));
527 assert(sd);
528 return *sd;
529 }
530
531 void
532 StoreController::sync(void)
533 {
534 if (memStore)
535 memStore->sync();
536 swapDir->sync();
537 }
538
539 /*
540 * handle callbacks all avaliable fs'es
541 */
542 int
543 StoreController::callback()
544 {
545 /* This will likely double count. Thats ok. */
546 PROF_start(storeDirCallback);
547
548 /* mem cache callbacks ? */
549 int result = swapDir->callback();
550
551 PROF_stop(storeDirCallback);
552
553 return result;
554 }
555
556 int
557 storeDirGetBlkSize(const char *path, int *blksize)
558 {
559 #if HAVE_STATVFS
560
561 struct statvfs sfs;
562
563 if (statvfs(path, &sfs)) {
564 debugs(50, 1, "" << path << ": " << xstrerror());
565 *blksize = 2048;
566 return 1;
567 }
568
569 *blksize = (int) sfs.f_frsize;
570 #else
571
572 struct statfs sfs;
573
574 if (statfs(path, &sfs)) {
575 debugs(50, 1, "" << path << ": " << xstrerror());
576 *blksize = 2048;
577 return 1;
578 }
579
580 *blksize = (int) sfs.f_bsize;
581 #endif
582 /*
583 * Sanity check; make sure we have a meaningful value.
584 */
585
586 if (*blksize < 512)
587 *blksize = 2048;
588
589 return 0;
590 }
591
592 #define fsbtoblk(num, fsbs, bs) \
593 (((fsbs) != 0 && (fsbs) < (bs)) ? \
594 (num) / ((bs) / (fsbs)) : (num) * ((fsbs) / (bs)))
595 int
596 storeDirGetUFSStats(const char *path, int *totl_kb, int *free_kb, int *totl_in, int *free_in)
597 {
598 #if HAVE_STATVFS
599
600 struct statvfs sfs;
601
602 if (statvfs(path, &sfs)) {
603 debugs(50, 1, "" << path << ": " << xstrerror());
604 return 1;
605 }
606
607 *totl_kb = (int) fsbtoblk(sfs.f_blocks, sfs.f_frsize, 1024);
608 *free_kb = (int) fsbtoblk(sfs.f_bfree, sfs.f_frsize, 1024);
609 *totl_in = (int) sfs.f_files;
610 *free_in = (int) sfs.f_ffree;
611 #else
612
613 struct statfs sfs;
614
615 if (statfs(path, &sfs)) {
616 debugs(50, 1, "" << path << ": " << xstrerror());
617 return 1;
618 }
619
620 *totl_kb = (int) fsbtoblk(sfs.f_blocks, sfs.f_bsize, 1024);
621 *free_kb = (int) fsbtoblk(sfs.f_bfree, sfs.f_bsize, 1024);
622 *totl_in = (int) sfs.f_files;
623 *free_in = (int) sfs.f_ffree;
624 #endif
625
626 return 0;
627 }
628
629 void
630 allocate_new_swapdir(SquidConfig::_cacheSwap * swap)
631 {
632 if (swap->swapDirs == NULL) {
633 swap->n_allocated = 4;
634 swap->swapDirs = static_cast<StorePointer *>(xcalloc(swap->n_allocated, sizeof(StorePointer)));
635 }
636
637 if (swap->n_allocated == swap->n_configured) {
638 StorePointer *tmp;
639 swap->n_allocated <<= 1;
640 tmp = static_cast<StorePointer *>(xcalloc(swap->n_allocated, sizeof(StorePointer)));
641 memcpy(tmp, swap->swapDirs, swap->n_configured * sizeof(SwapDir *));
642 xfree(swap->swapDirs);
643 swap->swapDirs = tmp;
644 }
645 }
646
647 void
648 free_cachedir(SquidConfig::_cacheSwap * swap)
649 {
650 int i;
651 /* DON'T FREE THESE FOR RECONFIGURE */
652
653 if (reconfiguring)
654 return;
655
656 for (i = 0; i < swap->n_configured; i++) {
657 /* TODO XXX this lets the swapdir free resources asynchronously
658 * swap->swapDirs[i]->deactivate();
659 * but there may be such a means already.
660 * RBC 20041225
661 */
662 swap->swapDirs[i] = NULL;
663 }
664
665 safe_free(swap->swapDirs);
666 swap->swapDirs = NULL;
667 swap->n_allocated = 0;
668 swap->n_configured = 0;
669 }
670
671 /* this should be a virtual method on StoreEntry,
672 * i.e. e->referenced()
673 * so that the entry can notify the creating Store
674 */
675 void
676 StoreController::reference(StoreEntry &e)
677 {
678 /* Notify the fs that we're referencing this object again */
679
680 if (e.swap_dirn > -1)
681 e.store()->reference(e);
682
683 // Notify the memory cache that we're referencing this object again
684 if (memStore && e.mem_status == IN_MEMORY)
685 memStore->reference(e);
686
687 // TODO: move this code to a non-shared memory cache class when we have it
688 if (e.mem_obj) {
689 if (mem_policy->Referenced)
690 mem_policy->Referenced(mem_policy, &e, &e.mem_obj->repl);
691 }
692 }
693
694 void
695 StoreController::dereference(StoreEntry & e)
696 {
697 /* Notify the fs that we're not referencing this object any more */
698
699 if (e.swap_filen > -1)
700 e.store()->dereference(e);
701
702 // Notify the memory cache that we're not referencing this object any more
703 if (memStore && e.mem_status == IN_MEMORY)
704 memStore->dereference(e);
705
706 // TODO: move this code to a non-shared memory cache class when we have it
707 if (e.mem_obj) {
708 if (mem_policy->Dereferenced)
709 mem_policy->Dereferenced(mem_policy, &e, &e.mem_obj->repl);
710 }
711 }
712
713 StoreEntry *
714 StoreController::get(const cache_key *key)
715 {
716 if (StoreEntry *e = swapDir->get(key)) {
717 // TODO: ignore and maybe handleIdleEntry() unlocked intransit entries
718 // because their backing store slot may be gone already.
719 debugs(20, 3, HERE << "got in-transit entry: " << *e);
720 return e;
721 }
722
723 if (memStore) {
724 if (StoreEntry *e = memStore->get(key)) {
725 debugs(20, 3, HERE << "got mem-cached entry: " << *e);
726 return e;
727 }
728 }
729
730 // TODO: this disk iteration is misplaced; move to StoreHashIndex
731 if (const int cacheDirs = Config.cacheSwap.n_configured) {
732 // ask each cache_dir until the entry is found; use static starting
733 // point to avoid asking the same subset of disks more often
734 // TODO: coordinate with put() to be able to guess the right disk often
735 static int idx = 0;
736 for (int n = 0; n < cacheDirs; ++n) {
737 idx = (idx + 1) % cacheDirs;
738 SwapDir *sd = dynamic_cast<SwapDir*>(INDEXSD(idx));
739 if (!sd->active())
740 continue;
741
742 if (StoreEntry *e = sd->get(key)) {
743 debugs(20, 3, HERE << "cache_dir " << idx <<
744 " got cached entry: " << *e);
745 return e;
746 }
747 }
748 }
749
750 debugs(20, 4, HERE << "none of " << Config.cacheSwap.n_configured <<
751 " cache_dirs have " << storeKeyText(key));
752 return NULL;
753 }
754
755 void
756 StoreController::get(String const key, STOREGETCLIENT aCallback, void *aCallbackData)
757 {
758 fatal("not implemented");
759 }
760
761 void
762 StoreController::handleIdleEntry(StoreEntry &e)
763 {
764 bool keepInLocalMemory = false;
765 if (memStore) {
766 memStore->considerKeeping(e);
767 // leave keepInLocalMemory false; memStore maintains its own cache
768 } else {
769 keepInLocalMemory = e.memoryCachable() && // entry is in good shape and
770 // the local memory cache is not overflowing
771 (mem_node::InUseCount() <= store_pages_max);
772 }
773
774 dereference(e);
775
776 // XXX: Rock store specific: Since each SwapDir controls its index,
777 // unlocked entries should not stay in the global store_table.
778 if (fileno >= 0) {
779 debugs(20, 5, HERE << "destroying unlocked entry: " << &e << ' ' << e);
780 destroyStoreEntry(static_cast<hash_link*>(&e));
781 return;
782 }
783
784 // TODO: move this into [non-shared] memory cache class when we have one
785 if (keepInLocalMemory) {
786 e.setMemStatus(IN_MEMORY);
787 e.mem_obj->unlinkRequest();
788 } else {
789 e.purgeMem(); // may free e
790 }
791 }
792
793 StoreHashIndex::StoreHashIndex()
794 {
795 if (store_table)
796 abort();
797 assert (store_table == NULL);
798 }
799
800 StoreHashIndex::~StoreHashIndex()
801 {
802 if (store_table) {
803 hashFreeItems(store_table, destroyStoreEntry);
804 hashFreeMemory(store_table);
805 store_table = NULL;
806 }
807 }
808
809 int
810 StoreHashIndex::callback()
811 {
812 int result = 0;
813 int j;
814 static int ndir = 0;
815
816 do {
817 j = 0;
818
819 for (int i = 0; i < Config.cacheSwap.n_configured; i++) {
820 if (ndir >= Config.cacheSwap.n_configured)
821 ndir = ndir % Config.cacheSwap.n_configured;
822
823 int temp_result = store(ndir)->callback();
824
825 ++ndir;
826
827 j += temp_result;
828
829 result += temp_result;
830
831 if (j > 100)
832 fatal ("too much io\n");
833 }
834 } while (j > 0);
835
836 ndir++;
837
838 return result;
839 }
840
841 void
842 StoreHashIndex::create()
843 {
844 for (int i = 0; i < Config.cacheSwap.n_configured; i++) {
845 if (dir(i).active())
846 store(i)->create();
847 }
848 }
849
850 /* Lookup an object in the cache.
851 * return just a reference to object, don't start swapping in yet. */
852 StoreEntry *
853 StoreHashIndex::get(const cache_key *key)
854 {
855 PROF_start(storeGet);
856 debugs(20, 3, "storeGet: looking up " << storeKeyText(key));
857 StoreEntry *p = static_cast<StoreEntry *>(hash_lookup(store_table, key));
858 PROF_stop(storeGet);
859 return p;
860 }
861
862 void
863 StoreHashIndex::get(String const key, STOREGETCLIENT aCallback, void *aCallbackData)
864 {
865 fatal("not implemented");
866 }
867
868 void
869 StoreHashIndex::init()
870 {
871 /* Calculate size of hash table (maximum currently 64k buckets). */
872 /* this is very bogus, its specific to the any Store maintaining an
873 * in-core index, not global */
874 size_t buckets = (Store::Root().maxSize() + ( Config.memMaxSize >> 10)) / Config.Store.avgObjectSize;
875 debugs(20, 1, "Swap maxSize " << Store::Root().maxSize() <<
876 " + " << ( Config.memMaxSize >> 10) << " KB, estimated " << buckets << " objects");
877 buckets /= Config.Store.objectsPerBucket;
878 debugs(20, 1, "Target number of buckets: " << buckets);
879 /* ideally the full scan period should be configurable, for the
880 * moment it remains at approximately 24 hours. */
881 store_hash_buckets = storeKeyHashBuckets(buckets);
882 debugs(20, 1, "Using " << store_hash_buckets << " Store buckets");
883 debugs(20, 1, "Max Mem size: " << ( Config.memMaxSize >> 10) << " KB");
884 debugs(20, 1, "Max Swap size: " << Store::Root().maxSize() << " KB");
885
886 store_table = hash_create(storeKeyHashCmp,
887 store_hash_buckets, storeKeyHashHash);
888
889 for (int i = 0; i < Config.cacheSwap.n_configured; i++) {
890 /* this starts a search of the store dirs, loading their
891 * index. under the new Store api this should be
892 * driven by the StoreHashIndex, not by each store.
893 *
894 * That is, the HashIndex should perform a search of each dir it is
895 * indexing to do the hash insertions. The search is then able to
896 * decide 'from-memory', or 'from-clean-log' or 'from-dirty-log' or
897 * 'from-no-log'.
898 *
899 * Step 1: make the store rebuilds use a search internally
900 * Step 2: change the search logic to use the four modes described
901 * above
902 * Step 3: have the hash index walk the searches itself.
903 */
904 if (dir(i).active())
905 store(i)->init();
906 }
907 }
908
909 uint64_t
910 StoreHashIndex::maxSize() const
911 {
912 uint64_t result = 0;
913
914 for (int i = 0; i < Config.cacheSwap.n_configured; i++) {
915 if (dir(i).doReportStat())
916 result += store(i)->maxSize();
917 }
918
919 return result;
920 }
921
922 uint64_t
923 StoreHashIndex::minSize() const
924 {
925 uint64_t result = 0;
926
927 for (int i = 0; i < Config.cacheSwap.n_configured; i++) {
928 if (dir(i).doReportStat())
929 result += store(i)->minSize();
930 }
931
932 return result;
933 }
934
935 uint64_t
936 StoreHashIndex::currentSize() const
937 {
938 uint64_t result = 0;
939
940 for (int i = 0; i < Config.cacheSwap.n_configured; i++) {
941 if (dir(i).doReportStat())
942 result += store(i)->currentSize();
943 }
944
945 return result;
946 }
947
948 uint64_t
949 StoreHashIndex::currentCount() const
950 {
951 uint64_t result = 0;
952
953 for (int i = 0; i < Config.cacheSwap.n_configured; i++) {
954 if (dir(i).doReportStat())
955 result += store(i)->currentCount();
956 }
957
958 return result;
959 }
960
961 void
962 StoreHashIndex::stat(StoreEntry & output) const
963 {
964 int i;
965
966 /* Now go through each store, calling its stat routine */
967
968 for (i = 0; i < Config.cacheSwap.n_configured; i++) {
969 storeAppendPrintf(&output, "\n");
970 store(i)->stat(output);
971 }
972 }
973
974 void
975 StoreHashIndex::reference(StoreEntry&)
976 {}
977
978 void
979 StoreHashIndex::dereference(StoreEntry&)
980 {}
981
982 void
983 StoreHashIndex::maintain()
984 {
985 int i;
986 /* walk each fs */
987
988 for (i = 0; i < Config.cacheSwap.n_configured; i++) {
989 /* XXX FixMe: This should be done "in parallell" on the different
990 * cache_dirs, not one at a time.
991 */
992 /* call the maintain function .. */
993 store(i)->maintain();
994 }
995 }
996
997 void
998 StoreHashIndex::updateSize(int64_t, int)
999 {}
1000
1001 void
1002 StoreHashIndex::sync()
1003 {
1004 for (int i = 0; i < Config.cacheSwap.n_configured; ++i)
1005 store(i)->sync();
1006 }
1007
1008 StoreSearch *
1009 StoreHashIndex::search(String const url, HttpRequest *)
1010 {
1011 if (url.size())
1012 fatal ("Cannot search by url yet\n");
1013
1014 return new StoreSearchHashIndex (this);
1015 }
1016
1017 CBDATA_CLASS_INIT(StoreSearchHashIndex);
1018
1019 StoreSearchHashIndex::StoreSearchHashIndex(RefCount<StoreHashIndex> aSwapDir) : sd(aSwapDir), _done (false), bucket (0)
1020 {}
1021
1022 /* do not link
1023 StoreSearchHashIndex::StoreSearchHashIndex(StoreSearchHashIndex const &);
1024 */
1025
1026 StoreSearchHashIndex::~StoreSearchHashIndex()
1027 {}
1028
1029 void
1030 StoreSearchHashIndex::next(void (aCallback)(void *), void *aCallbackData)
1031 {
1032 next();
1033 aCallback (aCallbackData);
1034 }
1035
1036 bool
1037 StoreSearchHashIndex::next()
1038 {
1039 if (entries.size())
1040 entries.pop_back();
1041
1042 while (!isDone() && !entries.size())
1043 copyBucket();
1044
1045 return currentItem() != NULL;
1046 }
1047
1048 bool
1049 StoreSearchHashIndex::error() const
1050 {
1051 return false;
1052 }
1053
1054 bool
1055 StoreSearchHashIndex::isDone() const
1056 {
1057 return bucket >= store_hash_buckets || _done;
1058 }
1059
1060 StoreEntry *
1061 StoreSearchHashIndex::currentItem()
1062 {
1063 if (!entries.size())
1064 return NULL;
1065
1066 return entries.back();
1067 }
1068
1069 void
1070 StoreSearchHashIndex::copyBucket()
1071 {
1072 /* probably need to lock the store entries...
1073 * we copy them all to prevent races on the links. */
1074 debugs(47, 3, "StoreSearchHashIndex::copyBucket #" << bucket);
1075 assert (!entries.size());
1076 hash_link *link_ptr = NULL;
1077 hash_link *link_next = NULL;
1078 link_next = hash_get_bucket(store_table, bucket);
1079
1080 while (NULL != (link_ptr = link_next)) {
1081 link_next = link_ptr->next;
1082 StoreEntry *e = (StoreEntry *) link_ptr;
1083
1084 entries.push_back(e);
1085 }
1086
1087 bucket++;
1088 debugs(47,3, "got entries: " << entries.size());
1089 }