2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 47 Store Directory Routines */
11 #define CLEAN_BUF_SZ 16384
15 #include "ConfigOption.h"
17 #include "DiskIO/DiskIOModule.h"
18 #include "DiskIO/DiskIOStrategy.h"
23 #include "RebuildState.h"
24 #include "SquidConfig.h"
25 #include "SquidMath.h"
26 #include "SquidTime.h"
27 #include "StatCounters.h"
28 #include "store_key_md5.h"
29 #include "StoreSearchUFS.h"
30 #include "StoreSwapLogData.h"
32 #include "UFSSwapDir.h"
41 int Fs::Ufs::UFSSwapDir::NumberOfUFSDirs
= 0;
42 int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping
= NULL
;
44 class UFSCleanLog
: public SwapDir::CleanLog
48 UFSCleanLog(SwapDir
*);
49 /** Get the next entry that is a candidate for clean log writing
51 virtual const StoreEntry
*nextEntry();
52 /** "write" an entry to the clean log file.
54 virtual void write(StoreEntry
const &);
61 RemovalPolicyWalker
*walker
;
65 UFSCleanLog::UFSCleanLog(SwapDir
*aSwapDir
) :
66 cur(NULL
), newLog(NULL
), cln(NULL
), outbuf(NULL
),
67 outbuf_offset(0), fd(-1),walker(NULL
), sd(aSwapDir
)
71 UFSCleanLog::nextEntry()
73 const StoreEntry
*entry
= NULL
;
76 entry
= walker
->Next(walker
);
82 UFSCleanLog::write(StoreEntry
const &e
)
85 static size_t ss
= sizeof(StoreSwapLogData
);
86 s
.op
= (char) SWAP_LOG_ADD
;
87 s
.swap_filen
= e
.swap_filen
;
88 s
.timestamp
= e
.timestamp
;
89 s
.lastref
= e
.lastref
;
90 s
.expires
= e
.expires
;
91 s
.lastmod
= e
.lastmod
;
92 s
.swap_file_sz
= e
.swap_file_sz
;
93 s
.refcount
= e
.refcount
;
95 memcpy(&s
.key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
97 memcpy(outbuf
+ outbuf_offset
, &s
, ss
);
101 if (outbuf_offset
+ ss
>= CLEAN_BUF_SZ
) {
102 if (FD_WRITE_METHOD(fd
, outbuf
, outbuf_offset
) < 0) {
103 /* XXX This error handling should probably move up to the caller */
104 debugs(50, DBG_CRITICAL
, HERE
<< newLog
<< ": write: " << xstrerror());
105 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
119 Fs::Ufs::UFSSwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
121 if (!SwapDir::canStore(e
, diskSpaceNeeded
, load
))
132 FreeObject(void *address
)
134 StoreSwapLogData
*anObject
= static_cast <StoreSwapLogData
*>(address
);
139 rev_int_sort(const void *A
, const void *B
)
141 const int *i1
= (const int *)A
;
142 const int *i2
= (const int *)B
;
147 Fs::Ufs::UFSSwapDir::parseSizeL1L2()
149 int i
= GetInteger();
151 fatal("UFSSwapDir::parseSizeL1L2: invalid size value");
153 const uint64_t size
= static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
155 /* just reconfigure it */
157 if (size
== maxSize())
158 debugs(3, 2, "Cache dir '" << path
<< "' size remains unchanged at " << i
<< " MB");
160 debugs(3, DBG_IMPORTANT
, "Cache dir '" << path
<< "' size changed to " << i
<< " MB");
168 fatal("UFSSwapDir::parseSizeL1L2: invalid level 1 directories value");
173 fatal("UFSSwapDir::parseSizeL1L2: invalid level 2 directories value");
177 Fs::Ufs::UFSSwapDir::reconfigure()
184 Fs::Ufs::UFSSwapDir::parse (int anIndex
, char *aPath
)
187 path
= xstrdup(aPath
);
191 /* Initialise replacement policy stuff */
192 repl
= createRemovalPolicy(Config
.replPolicy
);
198 Fs::Ufs::UFSSwapDir::changeIO(DiskIOModule
*module
)
200 DiskIOStrategy
*anIO
= module
->createStrategy();
202 ioType
= xstrdup(module
->type());
206 /* Change the IO Options */
208 if (currentIOOptions
&& currentIOOptions
->options
.size() > 2) {
209 delete currentIOOptions
->options
.back();
210 currentIOOptions
->options
.pop_back();
213 /* TODO: factor out these 4 lines */
214 ConfigOption
*ioOptions
= IO
->io
->getOptionTree();
216 if (currentIOOptions
&& ioOptions
)
217 currentIOOptions
->options
.push_back(ioOptions
);
221 Fs::Ufs::UFSSwapDir::optionIOParse(char const *option
, const char *value
, int isaReconfig
)
223 if (strcmp(option
, "IOEngine") != 0)
227 /* silently ignore this */
233 DiskIOModule
*module
= DiskIOModule::Find(value
);
244 Fs::Ufs::UFSSwapDir::optionIODump(StoreEntry
* e
) const
246 storeAppendPrintf(e
, " IOEngine=%s", ioType
);
250 Fs::Ufs::UFSSwapDir::getOptionTree() const
252 ConfigOption
*parentResult
= SwapDir::getOptionTree();
254 if (currentIOOptions
== NULL
)
255 currentIOOptions
= new ConfigOptionVector();
257 currentIOOptions
->options
.push_back(parentResult
);
259 currentIOOptions
->options
.push_back(new ConfigOptionAdapter
<UFSSwapDir
>(*const_cast<UFSSwapDir
*>(this), &UFSSwapDir::optionIOParse
, &UFSSwapDir::optionIODump
));
261 if (ConfigOption
*ioOptions
= IO
->io
->getOptionTree())
262 currentIOOptions
->options
.push_back(ioOptions
);
264 ConfigOption
* result
= currentIOOptions
;
266 currentIOOptions
= NULL
;
272 Fs::Ufs::UFSSwapDir::init()
274 debugs(47, 3, HERE
<< "Initialising UFS SwapDir engine.");
275 /* Parsing must be finished by now - force to NULL, don't delete */
276 currentIOOptions
= NULL
;
277 static int started_clean_event
= 0;
278 static const char *errmsg
=
279 "\tFailed to verify one of the swap directories, Check cache.log\n"
280 "\tfor details. Run 'squid -z' to create swap directories\n"
281 "\tif needed, or if running Squid for the first time.";
284 if (verifyCacheDirs())
291 if (!started_clean_event
) {
292 eventAdd("UFS storeDirClean", CleanEvent
, NULL
, 15.0, 1);
293 started_clean_event
= 1;
296 (void) storeDirGetBlkSize(path
, &fs
.blksize
);
300 Fs::Ufs::UFSSwapDir::create()
302 debugs(47, 3, "Creating swap space in " << path
);
303 createDirectory(path
, 0);
307 Fs::Ufs::UFSSwapDir::UFSSwapDir(char const *aType
, const char *anIOType
) :
316 currentIOOptions(new ConfigOptionVector()),
317 ioType(xstrdup(anIOType
)),
321 /* modulename is only set to disk modules that are built, by configure,
322 * so the Find call should never return NULL here.
324 IO
= new Fs::Ufs::UFSStrategy(DiskIOModule::Find(anIOType
)->createStrategy());
327 Fs::Ufs::UFSSwapDir::~UFSSwapDir()
329 if (swaplog_fd
> -1) {
330 file_close(swaplog_fd
);
336 delete currentIOOptions
;
340 Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry
&e
) const
342 debugs(47, DBG_CRITICAL
, HERE
<< "FILENO "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
343 debugs(47, DBG_CRITICAL
, HERE
<< "PATH " << fullPath(e
.swap_filen
, NULL
) );
348 Fs::Ufs::UFSSwapDir::doubleCheck(StoreEntry
& e
)
353 if (::stat(fullPath(e
.swap_filen
, NULL
), &sb
) < 0) {
354 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Missing swap file");
359 if ((off_t
)e
.swap_file_sz
!= sb
.st_size
) {
360 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Size Mismatch. Entry size: "
361 << e
.swap_file_sz
<< ", file size: " << sb
.st_size
);
370 Fs::Ufs::UFSSwapDir::statfs(StoreEntry
& sentry
) const
377 storeAppendPrintf(&sentry
, "First level subdirectories: %d\n", l1
);
378 storeAppendPrintf(&sentry
, "Second level subdirectories: %d\n", l2
);
379 storeAppendPrintf(&sentry
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
380 storeAppendPrintf(&sentry
, "Current Size: %.2f KB\n", currentSize() / 1024.0);
381 storeAppendPrintf(&sentry
, "Percent Used: %0.2f%%\n",
382 Math::doublePercent(currentSize(), maxSize()));
383 storeAppendPrintf(&sentry
, "Filemap bits in use: %d of %d (%d%%)\n",
384 map
->numFilesInMap(), map
->capacity(),
385 Math::intPercent(map
->numFilesInMap(), map
->capacity()));
386 x
= storeDirGetUFSStats(path
, &totl_kb
, &free_kb
, &totl_in
, &free_in
);
389 storeAppendPrintf(&sentry
, "Filesystem Space in use: %d/%d KB (%d%%)\n",
392 Math::intPercent(totl_kb
- free_kb
, totl_kb
));
393 storeAppendPrintf(&sentry
, "Filesystem Inodes in use: %d/%d (%d%%)\n",
396 Math::intPercent(totl_in
- free_in
, totl_in
));
399 storeAppendPrintf(&sentry
, "Flags:");
402 storeAppendPrintf(&sentry
, " SELECTED");
405 storeAppendPrintf(&sentry
, " READ-ONLY");
407 storeAppendPrintf(&sentry
, "\n");
413 Fs::Ufs::UFSSwapDir::maintain()
415 /* TODO: possible options for improvement;
417 * Note that too much aggression here is not good. It means that disk
418 * controller is getting a long queue of removals to act on, along
419 * with its regular I/O queue, and that client traffic is 'paused'
420 * and growing the network I/O queue as well while the scan happens.
421 * Possibly bad knock-on effects as Squid catches up on all that.
423 * Bug 2448 may have been a sign of what can wrong. At the least it
424 * provides a test case for aggression effects in overflow conditions.
426 * - base removal limit on space saved, instead of count ?
428 * - base removal rate on a traffic speed counter ?
429 * as the purge took up more time out of the second it would grow to
430 * a graceful full pause
432 * - pass out a value to cause another event to be scheduled immediately
433 * instead of waiting a whole second more ?
434 * knock on; schedule less if all caches are under low-water
436 * - admin configurable removal rate or count ?
437 * the current numbers are arbitrary, config helps with experimental
438 * trials and future-proofing the install base.
439 * we also have this indirectly by shifting the relative positions
440 * of low-, high- water and the total capacity limit.
443 /* We can't delete objects while rebuilding swap */
444 /* XXX FIXME each store should start maintaining as it comes online. */
445 if (StoreController::store_dirs_rebuilding
) {
446 debugs(47, DBG_IMPORTANT
, StoreController::store_dirs_rebuilding
<< " cache_dir still rebuilding. Skip GC for " << path
);
450 // minSize() is swap_low_watermark in bytes
451 const uint64_t lowWaterSz
= minSize();
453 if (currentSize() < lowWaterSz
) {
454 debugs(47, 2, "space still available in " << path
);
458 // maxSize() is cache_dir total size in bytes
459 const uint64_t highWaterSz
= ((maxSize() * Config
.Swap
.highWaterMark
) / 100);
461 // f is percentage of 'gap' filled between low- and high-water.
462 // Used to reduced purge rate when between water markers, and
463 // to multiply it more agressively the further above high-water
464 // it reaches. But in a graceful linear growth curve.
466 if (highWaterSz
> lowWaterSz
) {
467 // might be equal. n/0 is bad.
468 f
= (double) (currentSize() - lowWaterSz
) / (highWaterSz
- lowWaterSz
);
471 // how deep to look for a single object that can be removed
472 int max_scan
= (int) (f
* 400.0 + 100.0);
474 // try to purge only this many objects this cycle.
475 int max_remove
= (int) (f
* 300.0 + 20.0);
478 * This is kinda cheap, but so we need this priority hack?
480 debugs(47, 3, "f=" << f
<< ", max_scan=" << max_scan
<< ", max_remove=" << max_remove
);
482 RemovalPurgeWalker
*walker
= repl
->PurgeInit(repl
, max_scan
);
485 // only purge while above low-water
486 while (currentSize() >= lowWaterSz
) {
488 // stop if we reached max removals for this cycle,
489 // Bug 2448 may be from this not clearing enough,
490 // but it predates the current algorithm so not sure
491 if (removed
>= max_remove
)
494 StoreEntry
*e
= walker
->Next(walker
);
496 // stop if all objects are locked / in-use,
497 // or the cache is empty
499 break; /* no more objects */
506 walker
->Done(walker
);
507 debugs(47, (removed
? 2 : 3), path
<<
508 " removed " << removed
<< "/" << max_remove
<< " f=" <<
509 std::setprecision(4) << f
<< " max_scan=" << max_scan
);
511 // what if cache is still over the high watermark ?
512 // Store::Maintain() schedules another purge in 1 second.
516 Fs::Ufs::UFSSwapDir::reference(StoreEntry
&e
)
518 debugs(47, 3, HERE
<< "referencing " << &e
<< " " <<
519 e
.swap_dirn
<< "/" << e
.swap_filen
);
521 if (repl
->Referenced
)
522 repl
->Referenced(repl
, &e
, &e
.repl
);
526 Fs::Ufs::UFSSwapDir::dereference(StoreEntry
& e
, bool)
528 debugs(47, 3, HERE
<< "dereferencing " << &e
<< " " <<
529 e
.swap_dirn
<< "/" << e
.swap_filen
);
531 if (repl
->Dereferenced
)
532 repl
->Dereferenced(repl
, &e
, &e
.repl
);
534 return true; // keep e in the global store_table
537 StoreIOState::Pointer
538 Fs::Ufs::UFSSwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
540 return IO
->create (this, &e
, file_callback
, aCallback
, callback_data
);
543 StoreIOState::Pointer
544 Fs::Ufs::UFSSwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
546 return IO
->open (this, &e
, file_callback
, aCallback
, callback_data
);
550 Fs::Ufs::UFSSwapDir::mapBitTest(sfileno filn
)
552 return map
->testBit(filn
);
556 Fs::Ufs::UFSSwapDir::mapBitSet(sfileno filn
)
562 Fs::Ufs::UFSSwapDir::mapBitReset(sfileno filn
)
565 * We have to test the bit before calling clearBit as
566 * it doesn't do bounds checking and blindly assumes
567 * filn is a valid file number, but it might not be because
568 * the map is dynamic in size. Also clearing an already clear
569 * bit puts the map counter of-of-whack.
572 if (map
->testBit(filn
))
577 Fs::Ufs::UFSSwapDir::mapBitAllocate()
580 fn
= map
->allocate(suggest
);
587 Fs::Ufs::UFSSwapDir::swapSubDir(int subdirn
)const
589 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
590 assert(0 <= subdirn
&& subdirn
< l1
);
591 snprintf(fullfilename
, MAXPATHLEN
, "%s/%02X", path
, subdirn
);
596 Fs::Ufs::UFSSwapDir::createDirectory(const char *aPath
, int should_exist
)
603 if (0 == ::stat(aPath
, &st
)) {
604 if (S_ISDIR(st
.st_mode
)) {
605 debugs(47, (should_exist
? 3 : DBG_IMPORTANT
), aPath
<< " exists");
607 fatalf("Swap directory %s is not a directory.", aPath
);
609 } else if (0 == mkdir(aPath
, 0755)) {
610 debugs(47, (should_exist
? DBG_IMPORTANT
: 3), aPath
<< " created");
613 fatalf("Failed to make swap directory %s: %s",
621 Fs::Ufs::UFSSwapDir::pathIsDirectory(const char *aPath
)const
626 if (::stat(aPath
, &sb
) < 0) {
627 debugs(47, DBG_CRITICAL
, "ERROR: " << aPath
<< ": " << xstrerror());
631 if (S_ISDIR(sb
.st_mode
) == 0) {
632 debugs(47, DBG_CRITICAL
, "WARNING: " << aPath
<< " is not a directory");
640 Fs::Ufs::UFSSwapDir::verifyCacheDirs()
642 if (!pathIsDirectory(path
))
645 for (int j
= 0; j
< l1
; ++j
) {
646 char const *aPath
= swapSubDir(j
);
648 if (!pathIsDirectory(aPath
))
656 Fs::Ufs::UFSSwapDir::createSwapSubDirs()
658 LOCAL_ARRAY(char, name
, MAXPATHLEN
);
660 for (int i
= 0; i
< l1
; ++i
) {
661 snprintf(name
, MAXPATHLEN
, "%s/%02X", path
, i
);
665 if (createDirectory(name
, 0))
670 debugs(47, DBG_IMPORTANT
, "Making directories in " << name
);
672 for (int k
= 0; k
< l2
; ++k
) {
673 snprintf(name
, MAXPATHLEN
, "%s/%02X/%02X", path
, i
, k
);
674 createDirectory(name
, should_exist
);
680 Fs::Ufs::UFSSwapDir::logFile(char const *ext
) const
682 LOCAL_ARRAY(char, lpath
, MAXPATHLEN
);
683 LOCAL_ARRAY(char, pathtmp
, MAXPATHLEN
);
684 LOCAL_ARRAY(char, digit
, 32);
687 if (Config
.Log
.swap
) {
688 xstrncpy(pathtmp
, path
, MAXPATHLEN
- 64);
691 while ((pathtmp2
= strchr(pathtmp2
, '/')) != NULL
)
694 while (strlen(pathtmp
) && pathtmp
[strlen(pathtmp
) - 1] == '.')
695 pathtmp
[strlen(pathtmp
) - 1] = '\0';
697 for (pathtmp2
= pathtmp
; *pathtmp2
== '.'; ++pathtmp2
);
698 snprintf(lpath
, MAXPATHLEN
- 64, Config
.Log
.swap
, pathtmp2
);
700 if (strncmp(lpath
, Config
.Log
.swap
, MAXPATHLEN
- 64) == 0) {
702 snprintf(digit
, 32, "%02d", index
);
703 strncat(lpath
, digit
, 3);
706 xstrncpy(lpath
, path
, MAXPATHLEN
- 64);
707 strcat(lpath
, "/swap.state");
711 strncat(lpath
, ext
, 16);
717 Fs::Ufs::UFSSwapDir::openLog()
721 swaplog_fd
= file_open(logPath
, O_WRONLY
| O_CREAT
| O_BINARY
);
723 if (swaplog_fd
< 0) {
724 debugs(50, DBG_IMPORTANT
, "ERROR opening swap log " << logPath
<< ": " << xstrerror());
725 fatal("UFSSwapDir::openLog: Failed to open swap log.");
728 debugs(50, 3, HERE
<< "Cache Dir #" << index
<< " log opened on FD " << swaplog_fd
);
730 if (0 == NumberOfUFSDirs
)
731 assert(NULL
== UFSDirToGlobalDirMapping
);
735 assert(NumberOfUFSDirs
<= Config
.cacheSwap
.n_configured
);
739 Fs::Ufs::UFSSwapDir::closeLog()
741 if (swaplog_fd
< 0) /* not open */
744 file_close(swaplog_fd
);
746 debugs(47, 3, "Cache Dir #" << index
<< " log closed on FD " << swaplog_fd
);
752 assert(NumberOfUFSDirs
>= 0);
754 if (0 == NumberOfUFSDirs
)
755 safe_free(UFSDirToGlobalDirMapping
);
759 Fs::Ufs::UFSSwapDir::validL1(int anInt
) const
765 Fs::Ufs::UFSSwapDir::validL2(int anInt
) const
771 Fs::Ufs::UFSSwapDir::addDiskRestore(const cache_key
* key
,
773 uint64_t swap_file_sz
,
782 StoreEntry
*e
= NULL
;
783 debugs(47, 5, HERE
<< storeKeyText(key
) <<
784 ", fileno="<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << file_number
);
785 /* if you call this you'd better be sure file_number is not
787 e
= new StoreEntry();
788 e
->store_status
= STORE_OK
;
789 e
->setMemStatus(NOT_IN_MEMORY
);
790 e
->swap_status
= SWAPOUT_DONE
;
791 e
->swap_filen
= file_number
;
792 e
->swap_dirn
= index
;
793 e
->swap_file_sz
= swap_file_sz
;
794 e
->lastref
= lastref
;
795 e
->timestamp
= timestamp
;
796 e
->expires
= expires
;
797 e
->lastmod
= lastmod
;
798 e
->refcount
= refcount
;
800 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
801 EBIT_CLR(e
->flags
, KEY_PRIVATE
);
802 e
->ping_status
= PING_NONE
;
803 EBIT_CLR(e
->flags
, ENTRY_VALIDATED
);
804 mapBitSet(e
->swap_filen
);
805 cur_size
+= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
807 e
->hashInsert(key
); /* do it after we clear KEY_PRIVATE */
813 Fs::Ufs::UFSSwapDir::undoAddDiskRestore(StoreEntry
*e
)
815 debugs(47, 5, HERE
<< *e
);
816 replacementRemove(e
); // checks swap_dirn so do it before we invalidate it
817 // Do not unlink the file as it might be used by a subsequent entry.
818 mapBitReset(e
->swap_filen
);
821 cur_size
-= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
826 Fs::Ufs::UFSSwapDir::rebuild()
828 ++StoreController::store_dirs_rebuilding
;
829 eventAdd("storeRebuild", Fs::Ufs::RebuildState::RebuildStep
, new Fs::Ufs::RebuildState(this), 0.0, 1);
833 Fs::Ufs::UFSSwapDir::closeTmpSwapLog()
835 char *swaplog_path
= xstrdup(logFile(NULL
)); // where the swaplog should be
836 char *tmp_path
= xstrdup(logFile(".new")); // the temporary file we have generated
838 file_close(swaplog_fd
);
840 if (xrename(tmp_path
, swaplog_path
) < 0) {
841 fatalf("Failed to rename log file %s to %s", tmp_path
, swaplog_path
);
844 fd
= file_open(swaplog_path
, O_WRONLY
| O_CREAT
| O_BINARY
);
847 debugs(50, DBG_IMPORTANT
, "ERROR: " << swaplog_path
<< ": " << xstrerror());
848 fatalf("Failed to open swap log %s", swaplog_path
);
854 debugs(47, 3, "Cache Dir #" << index
<< " log opened on FD " << fd
);
858 Fs::Ufs::UFSSwapDir::openTmpSwapLog(int *clean_flag
, int *zero_flag
)
860 char *swaplog_path
= xstrdup(logFile(NULL
));
861 char *clean_path
= xstrdup(logFile(".last-clean"));
862 char *new_path
= xstrdup(logFile(".new"));
866 struct stat clean_sb
;
870 if (::stat(swaplog_path
, &log_sb
) < 0) {
871 debugs(47, DBG_IMPORTANT
, "Cache Dir #" << index
<< ": No log file");
872 safe_free(swaplog_path
);
873 safe_free(clean_path
);
878 *zero_flag
= log_sb
.st_size
== 0 ? 1 : 0;
879 /* close the existing write-only FD */
882 file_close(swaplog_fd
);
884 /* open a write-only FD for the new log */
885 fd
= file_open(new_path
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
888 debugs(50, DBG_IMPORTANT
, "ERROR: while opening swap log" << new_path
<< ": " << xstrerror());
889 fatalf("Failed to open swap log %s", new_path
);
895 const StoreSwapLogHeader header
;
897 buf
.init(header
.record_size
, header
.record_size
);
898 buf
.append(reinterpret_cast<const char*>(&header
), sizeof(header
));
899 // Pad to keep in sync with UFSSwapDir::writeCleanStart().
900 memset(buf
.space(), 0, header
.gapSize());
901 buf
.appended(header
.gapSize());
902 file_write(swaplog_fd
, -1, buf
.content(), buf
.contentSize(),
903 NULL
, NULL
, buf
.freeFunc());
906 /* open a read-only stream of the old log */
907 fp
= fopen(swaplog_path
, "rb");
910 debugs(50, DBG_CRITICAL
, "ERROR: while opening " << swaplog_path
<< ": " << xstrerror());
911 fatalf("Failed to open swap log for reading %s", swaplog_path
);
914 memset(&clean_sb
, '\0', sizeof(struct stat
));
916 if (::stat(clean_path
, &clean_sb
) < 0)
918 else if (clean_sb
.st_mtime
< log_sb
.st_mtime
)
923 safeunlink(clean_path
, 1);
925 safe_free(swaplog_path
);
927 safe_free(clean_path
);
935 * Begin the process to write clean cache state. For AUFS this means
936 * opening some log files and allocating write buffers. Return 0 if
937 * we succeed, and assign the 'func' and 'data' return pointers.
940 Fs::Ufs::UFSSwapDir::writeCleanStart()
942 UFSCleanLog
*state
= new UFSCleanLog(this);
943 StoreSwapLogHeader header
;
950 state
->newLog
= xstrdup(logFile(".clean"));
951 state
->fd
= file_open(state
->newLog
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
954 xfree(state
->newLog
);
959 state
->cur
= xstrdup(logFile(NULL
));
960 state
->cln
= xstrdup(logFile(".last-clean"));
961 state
->outbuf
= (char *)xcalloc(CLEAN_BUF_SZ
, 1);
962 state
->outbuf_offset
= 0;
964 memcpy(state
->outbuf
, &header
, sizeof(StoreSwapLogHeader
));
965 // Leave a gap to keep in sync with UFSSwapDir::openTmpSwapLog().
966 memset(state
->outbuf
+ sizeof(StoreSwapLogHeader
), 0, header
.gapSize());
967 state
->outbuf_offset
+= header
.record_size
;
969 state
->walker
= repl
->WalkInit(repl
);
970 ::unlink(state
->cln
);
971 debugs(47, 3, HERE
<< "opened " << state
->newLog
<< ", FD " << state
->fd
);
974 if (::stat(state
->cur
, &sb
) == 0)
975 fchmod(state
->fd
, sb
.st_mode
);
984 Fs::Ufs::UFSSwapDir::writeCleanDone()
986 UFSCleanLog
*state
= (UFSCleanLog
*)cleanLog
;
995 state
->walker
->Done(state
->walker
);
997 if (FD_WRITE_METHOD(state
->fd
, state
->outbuf
, state
->outbuf_offset
) < 0) {
998 debugs(50, DBG_CRITICAL
, HERE
<< state
->newLog
<< ": write: " << xstrerror());
999 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
1000 file_close(state
->fd
);
1002 ::unlink(state
->newLog
);
1005 safe_free(state
->outbuf
);
1007 * You can't rename open files on Microsoft "operating systems"
1008 * so we have to close before renaming.
1011 /* save the fd value for a later test */
1015 if (state
->fd
>= 0) {
1016 #if _SQUID_OS2_ || _SQUID_WINDOWS_
1017 file_close(state
->fd
);
1021 xrename(state
->newLog
, state
->cur
);
1024 /* touch a timestamp file if we're not still validating */
1025 if (StoreController::store_dirs_rebuilding
)
1030 file_close(file_open(state
->cln
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
));
1033 safe_free(state
->cur
);
1035 safe_free(state
->newLog
);
1037 safe_free(state
->cln
);
1040 file_close(state
->fd
);
1050 Fs::Ufs::UFSSwapDir::CleanEvent(void *)
1052 static int swap_index
= 0;
1057 * Assert that there are UFS cache_dirs configured, otherwise
1058 * we should never be called.
1060 assert(NumberOfUFSDirs
);
1062 if (NULL
== UFSDirToGlobalDirMapping
) {
1065 * Initialize the little array that translates UFS cache_dir
1066 * number into the Config.cacheSwap.swapDirs array index.
1068 UFSDirToGlobalDirMapping
= (int *)xcalloc(NumberOfUFSDirs
, sizeof(*UFSDirToGlobalDirMapping
));
1070 for (i
= 0, n
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1071 /* This is bogus, the controller should just clean each instance once */
1072 sd
= dynamic_cast <SwapDir
*>(INDEXSD(i
));
1074 if (!UFSSwapDir::IsUFSDir(sd
))
1077 UFSSwapDir
*usd
= dynamic_cast<UFSSwapDir
*>(sd
);
1081 UFSDirToGlobalDirMapping
[n
] = i
;
1084 j
+= (usd
->l1
* usd
->l2
);
1087 assert(n
== NumberOfUFSDirs
);
1089 * Start the commonUfsDirClean() swap_index with a random
1090 * value. j equals the total number of UFS level 2
1093 std::mt19937
mt(static_cast<uint32_t>(getCurrentTime() & 0xFFFFFFFF));
1094 xuniform_int_distribution
<> dist(0, j
);
1095 swap_index
= dist(mt
);
1098 /* if the rebuild is finished, start cleaning directories. */
1099 if (0 == StoreController::store_dirs_rebuilding
) {
1100 n
= DirClean(swap_index
);
1104 eventAdd("storeDirClean", CleanEvent
, NULL
,
1105 15.0 * exp(-0.25 * n
), 1);
1109 Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir
* sd
)
1111 UFSSwapDir
*mySD
= dynamic_cast<UFSSwapDir
*>(sd
);
1112 return (mySD
!= 0) ;
1116 * XXX: this is broken - it assumes all cache dirs use the same
1117 * l1 and l2 scheme. -RBC 20021215. Partial fix is in place -
1118 * if not UFSSwapDir return 0;
1121 Fs::Ufs::UFSSwapDir::FilenoBelongsHere(int fn
, int F0
, int F1
, int F2
)
1126 assert(F0
< Config
.cacheSwap
.n_configured
);
1127 assert (UFSSwapDir::IsUFSDir (dynamic_cast<SwapDir
*>(INDEXSD(F0
))));
1128 UFSSwapDir
*sd
= dynamic_cast<UFSSwapDir
*>(INDEXSD(F0
));
1137 D1
= ((filn
/ L2
) / L2
) % L1
;
1142 D2
= (filn
/ L2
) % L2
;
1151 Fs::Ufs::UFSSwapDir::validFileno(sfileno filn
, int flag
) const
1157 * If flag is set it means out-of-range file number should
1158 * be considered invalid.
1161 if (filn
> map
->capacity())
1168 Fs::Ufs::UFSSwapDir::unlinkFile(sfileno f
)
1170 debugs(79, 3, HERE
<< "unlinking fileno " << std::setfill('0') <<
1171 std::hex
<< std::uppercase
<< std::setw(8) << f
<< " '" <<
1172 fullPath(f
,NULL
) << "'");
1173 /* commonUfsDirMapBitReset(this, f); */
1174 IO
->unlinkFile(fullPath(f
,NULL
));
1178 Fs::Ufs::UFSSwapDir::unlinkdUseful() const
1180 // unlinkd may be useful only in workers
1181 return IamWorkerProcess() && IO
->io
->unlinkdUseful();
1185 Fs::Ufs::UFSSwapDir::unlink(StoreEntry
& e
)
1187 debugs(79, 3, HERE
<< "dirno " << index
<< ", fileno "<<
1188 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
1189 if (e
.swap_status
== SWAPOUT_DONE
) {
1190 cur_size
-= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1193 replacementRemove(&e
);
1194 mapBitReset(e
.swap_filen
);
1195 UFSSwapDir::unlinkFile(e
.swap_filen
);
1199 Fs::Ufs::UFSSwapDir::replacementAdd(StoreEntry
* e
)
1201 debugs(47, 4, HERE
<< "added node " << e
<< " to dir " << index
);
1202 repl
->Add(repl
, e
, &e
->repl
);
1206 Fs::Ufs::UFSSwapDir::replacementRemove(StoreEntry
* e
)
1210 if (e
->swap_dirn
< 0)
1213 SD
= INDEXSD(e
->swap_dirn
);
1215 assert (dynamic_cast<UFSSwapDir
*>(SD
.getRaw()) == this);
1217 debugs(47, 4, HERE
<< "remove node " << e
<< " from dir " << index
);
1219 repl
->Remove(repl
, e
, &e
->repl
);
1223 Fs::Ufs::UFSSwapDir::dump(StoreEntry
& entry
) const
1225 storeAppendPrintf(&entry
, " %" PRIu64
" %d %d", maxSize() >> 20, l1
, l2
);
1226 dumpOptions(&entry
);
1230 Fs::Ufs::UFSSwapDir::fullPath(sfileno filn
, char *fullpath
) const
1232 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
1237 fullpath
= fullfilename
;
1241 snprintf(fullpath
, MAXPATHLEN
, "%s/%02X/%02X/%08X",
1243 ((filn
/ L2
) / L2
) % L1
,
1251 Fs::Ufs::UFSSwapDir::callback()
1253 return IO
->callback();
1257 Fs::Ufs::UFSSwapDir::sync()
1263 Fs::Ufs::UFSSwapDir::swappedOut(const StoreEntry
&e
)
1265 cur_size
+= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1270 Fs::Ufs::UFSSwapDir::search(String
const url
, HttpRequest
*)
1273 fatal ("Cannot search by url yet\n");
1275 return new Fs::Ufs::StoreSearchUFS (this);
1279 Fs::Ufs::UFSSwapDir::logEntry(const StoreEntry
& e
, int op
) const
1281 StoreSwapLogData
*s
= new StoreSwapLogData
;
1283 s
->swap_filen
= e
.swap_filen
;
1284 s
->timestamp
= e
.timestamp
;
1285 s
->lastref
= e
.lastref
;
1286 s
->expires
= e
.expires
;
1287 s
->lastmod
= e
.lastmod
;
1288 s
->swap_file_sz
= e
.swap_file_sz
;
1289 s
->refcount
= e
.refcount
;
1291 memcpy(s
->key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
1293 file_write(swaplog_fd
,
1296 sizeof(StoreSwapLogData
),
1303 Fs::Ufs::UFSSwapDir::DirClean(int swap_index
)
1305 DIR *dir_pointer
= NULL
;
1307 LOCAL_ARRAY(char, p1
, MAXPATHLEN
+ 1);
1308 LOCAL_ARRAY(char, p2
, MAXPATHLEN
+ 1);
1312 int fn
; /* same as swapfileno, but with dirn bits set */
1318 N0
= NumberOfUFSDirs
;
1319 D0
= UFSDirToGlobalDirMapping
[swap_index
% N0
];
1320 SD
= dynamic_cast<UFSSwapDir
*>(INDEXSD(D0
));
1323 D1
= (swap_index
/ N0
) % N1
;
1325 D2
= ((swap_index
/ N0
) / N1
) % N2
;
1326 snprintf(p1
, MAXPATHLEN
, "%s/%02X/%02X",
1328 debugs(36, 3, HERE
<< "Cleaning directory " << p1
);
1329 dir_pointer
= opendir(p1
);
1331 if (dir_pointer
== NULL
) {
1332 if (errno
== ENOENT
) {
1333 debugs(36, DBG_CRITICAL
, HERE
<< "WARNING: Creating " << p1
);
1334 if (mkdir(p1
, 0777) == 0)
1338 debugs(50, DBG_CRITICAL
, HERE
<< p1
<< ": " << xstrerror());
1344 while ((de
= readdir(dir_pointer
)) != NULL
&& k
< 20) {
1345 if (sscanf(de
->d_name
, "%X", &swapfileno
) != 1)
1348 fn
= swapfileno
; /* XXX should remove this cruft ! */
1350 if (SD
->validFileno(fn
, 1))
1351 if (SD
->mapBitTest(fn
))
1352 if (UFSSwapDir::FilenoBelongsHere(fn
, D0
, D1
, D2
))
1355 files
[k
] = swapfileno
;
1359 closedir(dir_pointer
);
1364 qsort(files
, k
, sizeof(int), rev_int_sort
);
1369 for (n
= 0; n
< k
; ++n
) {
1370 debugs(36, 3, HERE
<< "Cleaning file "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << files
[n
]);
1371 snprintf(p2
, MAXPATHLEN
+ 1, "%s/%08X", p1
, files
[n
]);
1373 ++statCounter
.swap
.files_cleaned
;
1376 debugs(36, 3, HERE
<< "Cleaned " << k
<< " unused files from " << p1
);