2 * DEBUG: section 47 Store Directory Routines
3 * AUTHOR: Robert Collins
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
32 #define CLEAN_BUF_SZ 16384
36 #include "ConfigOption.h"
38 #include "DiskIO/DiskIOModule.h"
39 #include "DiskIO/DiskIOStrategy.h"
44 #include "RebuildState.h"
45 #include "SquidConfig.h"
46 #include "SquidMath.h"
47 #include "SquidTime.h"
48 #include "StatCounters.h"
49 #include "store_key_md5.h"
50 #include "StoreSearchUFS.h"
51 #include "StoreSwapLogData.h"
53 #include "UFSSwapDir.h"
65 int Fs::Ufs::UFSSwapDir::NumberOfUFSDirs
= 0;
66 int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping
= NULL
;
68 class UFSCleanLog
: public SwapDir::CleanLog
72 UFSCleanLog(SwapDir
*);
73 /** Get the next entry that is a candidate for clean log writing
75 virtual const StoreEntry
*nextEntry();
76 /** "write" an entry to the clean log file.
78 virtual void write(StoreEntry
const &);
85 RemovalPolicyWalker
*walker
;
89 UFSCleanLog::UFSCleanLog(SwapDir
*aSwapDir
) :
90 cur(NULL
), newLog(NULL
), cln(NULL
), outbuf(NULL
),
91 outbuf_offset(0), fd(-1),walker(NULL
), sd(aSwapDir
)
95 UFSCleanLog::nextEntry()
97 const StoreEntry
*entry
= NULL
;
100 entry
= walker
->Next(walker
);
106 UFSCleanLog::write(StoreEntry
const &e
)
109 static size_t ss
= sizeof(StoreSwapLogData
);
110 s
.op
= (char) SWAP_LOG_ADD
;
111 s
.swap_filen
= e
.swap_filen
;
112 s
.timestamp
= e
.timestamp
;
113 s
.lastref
= e
.lastref
;
114 s
.expires
= e
.expires
;
115 s
.lastmod
= e
.lastmod
;
116 s
.swap_file_sz
= e
.swap_file_sz
;
117 s
.refcount
= e
.refcount
;
119 memcpy(&s
.key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
121 memcpy(outbuf
+ outbuf_offset
, &s
, ss
);
125 if (outbuf_offset
+ ss
>= CLEAN_BUF_SZ
) {
126 if (FD_WRITE_METHOD(fd
, outbuf
, outbuf_offset
) < 0) {
127 /* XXX This error handling should probably move up to the caller */
128 debugs(50, DBG_CRITICAL
, HERE
<< newLog
<< ": write: " << xstrerror());
129 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
143 Fs::Ufs::UFSSwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
145 if (!SwapDir::canStore(e
, diskSpaceNeeded
, load
))
156 FreeObject(void *address
)
158 StoreSwapLogData
*anObject
= static_cast <StoreSwapLogData
*>(address
);
162 static QS rev_int_sort
;
164 rev_int_sort(const void *A
, const void *B
)
166 const int *i1
= (const int *)A
;
167 const int *i2
= (const int *)B
;
172 Fs::Ufs::UFSSwapDir::parseSizeL1L2()
174 int i
= GetInteger();
176 fatal("UFSSwapDir::parseSizeL1L2: invalid size value");
178 const uint64_t size
= static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
180 /* just reconfigure it */
182 if (size
== maxSize())
183 debugs(3, 2, "Cache dir '" << path
<< "' size remains unchanged at " << i
<< " MB");
185 debugs(3, DBG_IMPORTANT
, "Cache dir '" << path
<< "' size changed to " << i
<< " MB");
193 fatal("UFSSwapDir::parseSizeL1L2: invalid level 1 directories value");
198 fatal("UFSSwapDir::parseSizeL1L2: invalid level 2 directories value");
202 Fs::Ufs::UFSSwapDir::reconfigure()
209 Fs::Ufs::UFSSwapDir::parse (int anIndex
, char *aPath
)
212 path
= xstrdup(aPath
);
216 /* Initialise replacement policy stuff */
217 repl
= createRemovalPolicy(Config
.replPolicy
);
223 Fs::Ufs::UFSSwapDir::changeIO(DiskIOModule
*module
)
225 DiskIOStrategy
*anIO
= module
->createStrategy();
227 ioType
= xstrdup(module
->type());
231 /* Change the IO Options */
233 if (currentIOOptions
&& currentIOOptions
->options
.size() > 2)
234 delete currentIOOptions
->options
.pop_back();
236 /* TODO: factor out these 4 lines */
237 ConfigOption
*ioOptions
= IO
->io
->getOptionTree();
239 if (currentIOOptions
&& ioOptions
)
240 currentIOOptions
->options
.push_back(ioOptions
);
244 Fs::Ufs::UFSSwapDir::optionIOParse(char const *option
, const char *value
, int isaReconfig
)
246 if (strcmp(option
, "IOEngine") != 0)
250 /* silently ignore this */
256 DiskIOModule
*module
= DiskIOModule::Find(value
);
267 Fs::Ufs::UFSSwapDir::optionIODump(StoreEntry
* e
) const
269 storeAppendPrintf(e
, " IOEngine=%s", ioType
);
273 Fs::Ufs::UFSSwapDir::getOptionTree() const
275 ConfigOption
*parentResult
= SwapDir::getOptionTree();
277 if (currentIOOptions
== NULL
)
278 currentIOOptions
= new ConfigOptionVector();
280 currentIOOptions
->options
.push_back(parentResult
);
282 currentIOOptions
->options
.push_back(new ConfigOptionAdapter
<UFSSwapDir
>(*const_cast<UFSSwapDir
*>(this), &UFSSwapDir::optionIOParse
, &UFSSwapDir::optionIODump
));
284 if (ConfigOption
*ioOptions
= IO
->io
->getOptionTree())
285 currentIOOptions
->options
.push_back(ioOptions
);
287 ConfigOption
* result
= currentIOOptions
;
289 currentIOOptions
= NULL
;
295 Fs::Ufs::UFSSwapDir::init()
297 debugs(47, 3, HERE
<< "Initialising UFS SwapDir engine.");
298 /* Parsing must be finished by now - force to NULL, don't delete */
299 currentIOOptions
= NULL
;
300 static int started_clean_event
= 0;
301 static const char *errmsg
=
302 "\tFailed to verify one of the swap directories, Check cache.log\n"
303 "\tfor details. Run 'squid -z' to create swap directories\n"
304 "\tif needed, or if running Squid for the first time.";
307 if (verifyCacheDirs())
314 if (!started_clean_event
) {
315 eventAdd("UFS storeDirClean", CleanEvent
, NULL
, 15.0, 1);
316 started_clean_event
= 1;
319 (void) storeDirGetBlkSize(path
, &fs
.blksize
);
323 Fs::Ufs::UFSSwapDir::create()
325 debugs(47, 3, "Creating swap space in " << path
);
326 createDirectory(path
, 0);
330 Fs::Ufs::UFSSwapDir::UFSSwapDir(char const *aType
, const char *anIOType
) : SwapDir(aType
), IO(NULL
), map(new FileMap()), suggest(0), swaplog_fd (-1), currentIOOptions(new ConfigOptionVector()), ioType(xstrdup(anIOType
)), cur_size(0), n_disk_objects(0)
332 /* modulename is only set to disk modules that are built, by configure,
333 * so the Find call should never return NULL here.
335 IO
= new Fs::Ufs::UFSStrategy(DiskIOModule::Find(anIOType
)->createStrategy());
338 Fs::Ufs::UFSSwapDir::~UFSSwapDir()
340 if (swaplog_fd
> -1) {
341 file_close(swaplog_fd
);
347 delete currentIOOptions
;
351 Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry
&e
) const
353 debugs(47, DBG_CRITICAL
, HERE
<< "FILENO "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
354 debugs(47, DBG_CRITICAL
, HERE
<< "PATH " << fullPath(e
.swap_filen
, NULL
) );
359 Fs::Ufs::UFSSwapDir::doubleCheck(StoreEntry
& e
)
364 if (::stat(fullPath(e
.swap_filen
, NULL
), &sb
) < 0) {
365 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Missing swap file");
370 if ((off_t
)e
.swap_file_sz
!= sb
.st_size
) {
371 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Size Mismatch. Entry size: "
372 << e
.swap_file_sz
<< ", file size: " << sb
.st_size
);
381 Fs::Ufs::UFSSwapDir::statfs(StoreEntry
& sentry
) const
388 storeAppendPrintf(&sentry
, "First level subdirectories: %d\n", l1
);
389 storeAppendPrintf(&sentry
, "Second level subdirectories: %d\n", l2
);
390 storeAppendPrintf(&sentry
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
391 storeAppendPrintf(&sentry
, "Current Size: %.2f KB\n", currentSize() / 1024.0);
392 storeAppendPrintf(&sentry
, "Percent Used: %0.2f%%\n",
393 Math::doublePercent(currentSize(), maxSize()));
394 storeAppendPrintf(&sentry
, "Filemap bits in use: %d of %d (%d%%)\n",
395 map
->numFilesInMap(), map
->capacity(),
396 Math::intPercent(map
->numFilesInMap(), map
->capacity()));
397 x
= storeDirGetUFSStats(path
, &totl_kb
, &free_kb
, &totl_in
, &free_in
);
400 storeAppendPrintf(&sentry
, "Filesystem Space in use: %d/%d KB (%d%%)\n",
403 Math::intPercent(totl_kb
- free_kb
, totl_kb
));
404 storeAppendPrintf(&sentry
, "Filesystem Inodes in use: %d/%d (%d%%)\n",
407 Math::intPercent(totl_in
- free_in
, totl_in
));
410 storeAppendPrintf(&sentry
, "Flags:");
413 storeAppendPrintf(&sentry
, " SELECTED");
416 storeAppendPrintf(&sentry
, " READ-ONLY");
418 storeAppendPrintf(&sentry
, "\n");
424 Fs::Ufs::UFSSwapDir::maintain()
426 /* We can't delete objects while rebuilding swap */
428 /* XXX FIXME each store should start maintaining as it comes online. */
430 if (StoreController::store_dirs_rebuilding
)
433 StoreEntry
*e
= NULL
;
437 RemovalPurgeWalker
*walker
;
439 double f
= (double) (currentSize() - minSize()) / (maxSize() - minSize());
441 f
= f
< 0.0 ? 0.0 : f
> 1.0 ? 1.0 : f
;
443 int max_scan
= (int) (f
* 400.0 + 100.0);
445 int max_remove
= (int) (f
* 70.0 + 10.0);
448 * This is kinda cheap, but so we need this priority hack?
451 debugs(47, 3, HERE
<< "f=" << f
<< ", max_scan=" << max_scan
<< ", max_remove=" << max_remove
);
453 walker
= repl
->PurgeInit(repl
, max_scan
);
456 if (currentSize() < minSize())
459 if (removed
>= max_remove
)
462 e
= walker
->Next(walker
);
465 break; /* no more objects */
472 walker
->Done(walker
);
473 debugs(47, (removed
? 2 : 3), HERE
<< path
<<
474 " removed " << removed
<< "/" << max_remove
<< " f=" <<
475 std::setprecision(4) << f
<< " max_scan=" << max_scan
);
479 Fs::Ufs::UFSSwapDir::reference(StoreEntry
&e
)
481 debugs(47, 3, HERE
<< "referencing " << &e
<< " " <<
482 e
.swap_dirn
<< "/" << e
.swap_filen
);
484 if (repl
->Referenced
)
485 repl
->Referenced(repl
, &e
, &e
.repl
);
489 Fs::Ufs::UFSSwapDir::dereference(StoreEntry
& e
, bool)
491 debugs(47, 3, HERE
<< "dereferencing " << &e
<< " " <<
492 e
.swap_dirn
<< "/" << e
.swap_filen
);
494 if (repl
->Dereferenced
)
495 repl
->Dereferenced(repl
, &e
, &e
.repl
);
497 return true; // keep e in the global store_table
500 StoreIOState::Pointer
501 Fs::Ufs::UFSSwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
503 return IO
->create (this, &e
, file_callback
, aCallback
, callback_data
);
506 StoreIOState::Pointer
507 Fs::Ufs::UFSSwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
509 return IO
->open (this, &e
, file_callback
, aCallback
, callback_data
);
513 Fs::Ufs::UFSSwapDir::mapBitTest(sfileno filn
)
515 return map
->testBit(filn
);
519 Fs::Ufs::UFSSwapDir::mapBitSet(sfileno filn
)
525 Fs::Ufs::UFSSwapDir::mapBitReset(sfileno filn
)
528 * We have to test the bit before calling clearBit as
529 * it doesn't do bounds checking and blindly assumes
530 * filn is a valid file number, but it might not be because
531 * the map is dynamic in size. Also clearing an already clear
532 * bit puts the map counter of-of-whack.
535 if (map
->testBit(filn
))
540 Fs::Ufs::UFSSwapDir::mapBitAllocate()
543 fn
= map
->allocate(suggest
);
550 Fs::Ufs::UFSSwapDir::swapSubDir(int subdirn
)const
552 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
553 assert(0 <= subdirn
&& subdirn
< l1
);
554 snprintf(fullfilename
, MAXPATHLEN
, "%s/%02X", path
, subdirn
);
559 Fs::Ufs::UFSSwapDir::createDirectory(const char *aPath
, int should_exist
)
566 if (0 == ::stat(aPath
, &st
)) {
567 if (S_ISDIR(st
.st_mode
)) {
568 debugs(47, (should_exist
? 3 : DBG_IMPORTANT
), aPath
<< " exists");
570 fatalf("Swap directory %s is not a directory.", aPath
);
572 } else if (0 == mkdir(aPath
, 0755)) {
573 debugs(47, (should_exist
? DBG_IMPORTANT
: 3), aPath
<< " created");
576 fatalf("Failed to make swap directory %s: %s",
584 Fs::Ufs::UFSSwapDir::pathIsDirectory(const char *aPath
)const
589 if (::stat(aPath
, &sb
) < 0) {
590 debugs(47, DBG_CRITICAL
, "ERROR: " << aPath
<< ": " << xstrerror());
594 if (S_ISDIR(sb
.st_mode
) == 0) {
595 debugs(47, DBG_CRITICAL
, "WARNING: " << aPath
<< " is not a directory");
603 Fs::Ufs::UFSSwapDir::verifyCacheDirs()
605 if (!pathIsDirectory(path
))
608 for (int j
= 0; j
< l1
; ++j
) {
609 char const *aPath
= swapSubDir(j
);
611 if (!pathIsDirectory(aPath
))
619 Fs::Ufs::UFSSwapDir::createSwapSubDirs()
621 LOCAL_ARRAY(char, name
, MAXPATHLEN
);
623 for (int i
= 0; i
< l1
; ++i
) {
624 snprintf(name
, MAXPATHLEN
, "%s/%02X", path
, i
);
628 if (createDirectory(name
, 0))
633 debugs(47, DBG_IMPORTANT
, "Making directories in " << name
);
635 for (int k
= 0; k
< l2
; ++k
) {
636 snprintf(name
, MAXPATHLEN
, "%s/%02X/%02X", path
, i
, k
);
637 createDirectory(name
, should_exist
);
643 Fs::Ufs::UFSSwapDir::logFile(char const *ext
) const
645 LOCAL_ARRAY(char, lpath
, MAXPATHLEN
);
646 LOCAL_ARRAY(char, pathtmp
, MAXPATHLEN
);
647 LOCAL_ARRAY(char, digit
, 32);
650 if (Config
.Log
.swap
) {
651 xstrncpy(pathtmp
, path
, MAXPATHLEN
- 64);
654 while ((pathtmp2
= strchr(pathtmp2
, '/')) != NULL
)
657 while (strlen(pathtmp
) && pathtmp
[strlen(pathtmp
) - 1] == '.')
658 pathtmp
[strlen(pathtmp
) - 1] = '\0';
660 for (pathtmp2
= pathtmp
; *pathtmp2
== '.'; ++pathtmp2
);
661 snprintf(lpath
, MAXPATHLEN
- 64, Config
.Log
.swap
, pathtmp2
);
663 if (strncmp(lpath
, Config
.Log
.swap
, MAXPATHLEN
- 64) == 0) {
665 snprintf(digit
, 32, "%02d", index
);
666 strncat(lpath
, digit
, 3);
669 xstrncpy(lpath
, path
, MAXPATHLEN
- 64);
670 strcat(lpath
, "/swap.state");
674 strncat(lpath
, ext
, 16);
680 Fs::Ufs::UFSSwapDir::openLog()
684 swaplog_fd
= file_open(logPath
, O_WRONLY
| O_CREAT
| O_BINARY
);
686 if (swaplog_fd
< 0) {
687 debugs(50, DBG_IMPORTANT
, "ERROR opening swap log " << logPath
<< ": " << xstrerror());
688 fatal("UFSSwapDir::openLog: Failed to open swap log.");
691 debugs(50, 3, HERE
<< "Cache Dir #" << index
<< " log opened on FD " << swaplog_fd
);
693 if (0 == NumberOfUFSDirs
)
694 assert(NULL
== UFSDirToGlobalDirMapping
);
698 assert(NumberOfUFSDirs
<= Config
.cacheSwap
.n_configured
);
702 Fs::Ufs::UFSSwapDir::closeLog()
704 if (swaplog_fd
< 0) /* not open */
707 file_close(swaplog_fd
);
709 debugs(47, 3, "Cache Dir #" << index
<< " log closed on FD " << swaplog_fd
);
715 assert(NumberOfUFSDirs
>= 0);
717 if (0 == NumberOfUFSDirs
)
718 safe_free(UFSDirToGlobalDirMapping
);
722 Fs::Ufs::UFSSwapDir::validL1(int anInt
) const
728 Fs::Ufs::UFSSwapDir::validL2(int anInt
) const
734 Fs::Ufs::UFSSwapDir::addDiskRestore(const cache_key
* key
,
736 uint64_t swap_file_sz
,
745 StoreEntry
*e
= NULL
;
746 debugs(47, 5, HERE
<< storeKeyText(key
) <<
747 ", fileno="<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << file_number
);
748 /* if you call this you'd better be sure file_number is not
750 e
= new StoreEntry();
751 e
->store_status
= STORE_OK
;
752 e
->setMemStatus(NOT_IN_MEMORY
);
753 e
->swap_status
= SWAPOUT_DONE
;
754 e
->swap_filen
= file_number
;
755 e
->swap_dirn
= index
;
756 e
->swap_file_sz
= swap_file_sz
;
757 e
->lastref
= lastref
;
758 e
->timestamp
= timestamp
;
759 e
->expires
= expires
;
760 e
->lastmod
= lastmod
;
761 e
->refcount
= refcount
;
763 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
764 EBIT_CLR(e
->flags
, KEY_PRIVATE
);
765 e
->ping_status
= PING_NONE
;
766 EBIT_CLR(e
->flags
, ENTRY_VALIDATED
);
767 mapBitSet(e
->swap_filen
);
768 cur_size
+= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
770 e
->hashInsert(key
); /* do it after we clear KEY_PRIVATE */
776 Fs::Ufs::UFSSwapDir::undoAddDiskRestore(StoreEntry
*e
)
778 debugs(47, 5, HERE
<< *e
);
779 replacementRemove(e
); // checks swap_dirn so do it before we invalidate it
780 // Do not unlink the file as it might be used by a subsequent entry.
781 mapBitReset(e
->swap_filen
);
784 cur_size
-= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
789 Fs::Ufs::UFSSwapDir::rebuild()
791 ++StoreController::store_dirs_rebuilding
;
792 eventAdd("storeRebuild", Fs::Ufs::RebuildState::RebuildStep
, new Fs::Ufs::RebuildState(this), 0.0, 1);
796 Fs::Ufs::UFSSwapDir::closeTmpSwapLog()
798 char *swaplog_path
= xstrdup(logFile(NULL
)); // where the swaplog should be
799 char *tmp_path
= xstrdup(logFile(".new")); // the temporary file we have generated
801 file_close(swaplog_fd
);
803 if (xrename(tmp_path
, swaplog_path
) < 0) {
804 fatalf("Failed to rename log file %s to %s", tmp_path
, swaplog_path
);
807 fd
= file_open(swaplog_path
, O_WRONLY
| O_CREAT
| O_BINARY
);
810 debugs(50, DBG_IMPORTANT
, "ERROR: " << swaplog_path
<< ": " << xstrerror());
811 fatalf("Failed to open swap log %s", swaplog_path
);
817 debugs(47, 3, "Cache Dir #" << index
<< " log opened on FD " << fd
);
821 Fs::Ufs::UFSSwapDir::openTmpSwapLog(int *clean_flag
, int *zero_flag
)
823 char *swaplog_path
= xstrdup(logFile(NULL
));
824 char *clean_path
= xstrdup(logFile(".last-clean"));
825 char *new_path
= xstrdup(logFile(".new"));
829 struct stat clean_sb
;
833 if (::stat(swaplog_path
, &log_sb
) < 0) {
834 debugs(47, DBG_IMPORTANT
, "Cache Dir #" << index
<< ": No log file");
835 safe_free(swaplog_path
);
836 safe_free(clean_path
);
841 *zero_flag
= log_sb
.st_size
== 0 ? 1 : 0;
842 /* close the existing write-only FD */
845 file_close(swaplog_fd
);
847 /* open a write-only FD for the new log */
848 fd
= file_open(new_path
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
851 debugs(50, DBG_IMPORTANT
, "ERROR: while opening swap log" << new_path
<< ": " << xstrerror());
852 fatalf("Failed to open swap log %s", new_path
);
858 const StoreSwapLogHeader header
;
860 buf
.init(header
.record_size
, header
.record_size
);
861 buf
.append(reinterpret_cast<const char*>(&header
), sizeof(header
));
862 // Pad to keep in sync with UFSSwapDir::writeCleanStart().
863 memset(buf
.space(), 0, header
.gapSize());
864 buf
.appended(header
.gapSize());
865 file_write(swaplog_fd
, -1, buf
.content(), buf
.contentSize(),
866 NULL
, NULL
, buf
.freeFunc());
869 /* open a read-only stream of the old log */
870 fp
= fopen(swaplog_path
, "rb");
873 debugs(50, DBG_CRITICAL
, "ERROR: while opening " << swaplog_path
<< ": " << xstrerror());
874 fatalf("Failed to open swap log for reading %s", swaplog_path
);
877 memset(&clean_sb
, '\0', sizeof(struct stat
));
879 if (::stat(clean_path
, &clean_sb
) < 0)
881 else if (clean_sb
.st_mtime
< log_sb
.st_mtime
)
886 safeunlink(clean_path
, 1);
888 safe_free(swaplog_path
);
890 safe_free(clean_path
);
898 * Begin the process to write clean cache state. For AUFS this means
899 * opening some log files and allocating write buffers. Return 0 if
900 * we succeed, and assign the 'func' and 'data' return pointers.
903 Fs::Ufs::UFSSwapDir::writeCleanStart()
905 UFSCleanLog
*state
= new UFSCleanLog(this);
906 StoreSwapLogHeader header
;
913 state
->newLog
= xstrdup(logFile(".clean"));
914 state
->fd
= file_open(state
->newLog
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
917 xfree(state
->newLog
);
922 state
->cur
= xstrdup(logFile(NULL
));
923 state
->cln
= xstrdup(logFile(".last-clean"));
924 state
->outbuf
= (char *)xcalloc(CLEAN_BUF_SZ
, 1);
925 state
->outbuf_offset
= 0;
927 memcpy(state
->outbuf
, &header
, sizeof(StoreSwapLogHeader
));
928 // Leave a gap to keep in sync with UFSSwapDir::openTmpSwapLog().
929 memset(state
->outbuf
+ sizeof(StoreSwapLogHeader
), 0, header
.gapSize());
930 state
->outbuf_offset
+= header
.record_size
;
932 state
->walker
= repl
->WalkInit(repl
);
933 ::unlink(state
->cln
);
934 debugs(47, 3, HERE
<< "opened " << state
->newLog
<< ", FD " << state
->fd
);
937 if (::stat(state
->cur
, &sb
) == 0)
938 fchmod(state
->fd
, sb
.st_mode
);
947 Fs::Ufs::UFSSwapDir::writeCleanDone()
949 UFSCleanLog
*state
= (UFSCleanLog
*)cleanLog
;
958 state
->walker
->Done(state
->walker
);
960 if (FD_WRITE_METHOD(state
->fd
, state
->outbuf
, state
->outbuf_offset
) < 0) {
961 debugs(50, DBG_CRITICAL
, HERE
<< state
->newLog
<< ": write: " << xstrerror());
962 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
963 file_close(state
->fd
);
965 ::unlink(state
->newLog
);
968 safe_free(state
->outbuf
);
970 * You can't rename open files on Microsoft "operating systems"
971 * so we have to close before renaming.
974 /* save the fd value for a later test */
978 if (state
->fd
>= 0) {
979 #if _SQUID_OS2_ || _SQUID_WINDOWS_
980 file_close(state
->fd
);
984 xrename(state
->newLog
, state
->cur
);
987 /* touch a timestamp file if we're not still validating */
988 if (StoreController::store_dirs_rebuilding
)
993 file_close(file_open(state
->cln
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
));
996 safe_free(state
->cur
);
998 safe_free(state
->newLog
);
1000 safe_free(state
->cln
);
1003 file_close(state
->fd
);
1013 Fs::Ufs::UFSSwapDir::CleanEvent(void *unused
)
1015 static int swap_index
= 0;
1020 * Assert that there are UFS cache_dirs configured, otherwise
1021 * we should never be called.
1023 assert(NumberOfUFSDirs
);
1025 if (NULL
== UFSDirToGlobalDirMapping
) {
1028 * Initialize the little array that translates UFS cache_dir
1029 * number into the Config.cacheSwap.swapDirs array index.
1031 UFSDirToGlobalDirMapping
= (int *)xcalloc(NumberOfUFSDirs
, sizeof(*UFSDirToGlobalDirMapping
));
1033 for (i
= 0, n
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1034 /* This is bogus, the controller should just clean each instance once */
1035 sd
= dynamic_cast <SwapDir
*>(INDEXSD(i
));
1037 if (!UFSSwapDir::IsUFSDir(sd
))
1040 UFSSwapDir
*usd
= dynamic_cast<UFSSwapDir
*>(sd
);
1044 UFSDirToGlobalDirMapping
[n
] = i
;
1047 j
+= (usd
->l1
* usd
->l2
);
1050 assert(n
== NumberOfUFSDirs
);
1052 * Start the commonUfsDirClean() swap_index with a random
1053 * value. j equals the total number of UFS level 2
1056 swap_index
= (int) (squid_random() % j
);
1059 /* if the rebuild is finished, start cleaning directories. */
1060 if (0 == StoreController::store_dirs_rebuilding
) {
1061 n
= DirClean(swap_index
);
1065 eventAdd("storeDirClean", CleanEvent
, NULL
,
1066 15.0 * exp(-0.25 * n
), 1);
1070 Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir
* sd
)
1072 UFSSwapDir
*mySD
= dynamic_cast<UFSSwapDir
*>(sd
);
1073 return (mySD
!= 0) ;
1077 * XXX: this is broken - it assumes all cache dirs use the same
1078 * l1 and l2 scheme. -RBC 20021215. Partial fix is in place -
1079 * if not UFSSwapDir return 0;
1082 Fs::Ufs::UFSSwapDir::FilenoBelongsHere(int fn
, int F0
, int F1
, int F2
)
1087 assert(F0
< Config
.cacheSwap
.n_configured
);
1088 assert (UFSSwapDir::IsUFSDir (dynamic_cast<SwapDir
*>(INDEXSD(F0
))));
1089 UFSSwapDir
*sd
= dynamic_cast<UFSSwapDir
*>(INDEXSD(F0
));
1098 D1
= ((filn
/ L2
) / L2
) % L1
;
1103 D2
= (filn
/ L2
) % L2
;
1112 Fs::Ufs::UFSSwapDir::validFileno(sfileno filn
, int flag
) const
1118 * If flag is set it means out-of-range file number should
1119 * be considered invalid.
1122 if (filn
> map
->capacity())
1129 Fs::Ufs::UFSSwapDir::unlinkFile(sfileno f
)
1131 debugs(79, 3, HERE
<< "unlinking fileno " << std::setfill('0') <<
1132 std::hex
<< std::uppercase
<< std::setw(8) << f
<< " '" <<
1133 fullPath(f
,NULL
) << "'");
1134 /* commonUfsDirMapBitReset(this, f); */
1135 IO
->unlinkFile(fullPath(f
,NULL
));
1139 Fs::Ufs::UFSSwapDir::unlinkdUseful() const
1141 // unlinkd may be useful only in workers
1142 return IamWorkerProcess() && IO
->io
->unlinkdUseful();
1146 Fs::Ufs::UFSSwapDir::unlink(StoreEntry
& e
)
1148 debugs(79, 3, HERE
<< "dirno " << index
<< ", fileno "<<
1149 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
1150 if (e
.swap_status
== SWAPOUT_DONE
) {
1151 cur_size
-= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1154 replacementRemove(&e
);
1155 mapBitReset(e
.swap_filen
);
1156 UFSSwapDir::unlinkFile(e
.swap_filen
);
1160 Fs::Ufs::UFSSwapDir::replacementAdd(StoreEntry
* e
)
1162 debugs(47, 4, HERE
<< "added node " << e
<< " to dir " << index
);
1163 repl
->Add(repl
, e
, &e
->repl
);
1167 Fs::Ufs::UFSSwapDir::replacementRemove(StoreEntry
* e
)
1171 if (e
->swap_dirn
< 0)
1174 SD
= INDEXSD(e
->swap_dirn
);
1176 assert (dynamic_cast<UFSSwapDir
*>(SD
.getRaw()) == this);
1178 debugs(47, 4, HERE
<< "remove node " << e
<< " from dir " << index
);
1180 repl
->Remove(repl
, e
, &e
->repl
);
1184 Fs::Ufs::UFSSwapDir::dump(StoreEntry
& entry
) const
1186 storeAppendPrintf(&entry
, " %" PRIu64
" %d %d", maxSize() >> 20, l1
, l2
);
1187 dumpOptions(&entry
);
1191 Fs::Ufs::UFSSwapDir::fullPath(sfileno filn
, char *fullpath
) const
1193 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
1198 fullpath
= fullfilename
;
1202 snprintf(fullpath
, MAXPATHLEN
, "%s/%02X/%02X/%08X",
1204 ((filn
/ L2
) / L2
) % L1
,
1212 Fs::Ufs::UFSSwapDir::callback()
1214 return IO
->callback();
1218 Fs::Ufs::UFSSwapDir::sync()
1224 Fs::Ufs::UFSSwapDir::swappedOut(const StoreEntry
&e
)
1226 cur_size
+= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1231 Fs::Ufs::UFSSwapDir::search(String
const url
, HttpRequest
*request
)
1234 fatal ("Cannot search by url yet\n");
1236 return new Fs::Ufs::StoreSearchUFS (this);
1240 Fs::Ufs::UFSSwapDir::logEntry(const StoreEntry
& e
, int op
) const
1242 StoreSwapLogData
*s
= new StoreSwapLogData
;
1244 s
->swap_filen
= e
.swap_filen
;
1245 s
->timestamp
= e
.timestamp
;
1246 s
->lastref
= e
.lastref
;
1247 s
->expires
= e
.expires
;
1248 s
->lastmod
= e
.lastmod
;
1249 s
->swap_file_sz
= e
.swap_file_sz
;
1250 s
->refcount
= e
.refcount
;
1252 memcpy(s
->key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
1254 file_write(swaplog_fd
,
1257 sizeof(StoreSwapLogData
),
1264 Fs::Ufs::UFSSwapDir::DirClean(int swap_index
)
1266 DIR *dir_pointer
= NULL
;
1268 LOCAL_ARRAY(char, p1
, MAXPATHLEN
+ 1);
1269 LOCAL_ARRAY(char, p2
, MAXPATHLEN
+ 1);
1273 int fn
; /* same as swapfileno, but with dirn bits set */
1279 N0
= NumberOfUFSDirs
;
1280 D0
= UFSDirToGlobalDirMapping
[swap_index
% N0
];
1281 SD
= dynamic_cast<UFSSwapDir
*>(INDEXSD(D0
));
1284 D1
= (swap_index
/ N0
) % N1
;
1286 D2
= ((swap_index
/ N0
) / N1
) % N2
;
1287 snprintf(p1
, MAXPATHLEN
, "%s/%02X/%02X",
1289 debugs(36, 3, HERE
<< "Cleaning directory " << p1
);
1290 dir_pointer
= opendir(p1
);
1292 if (dir_pointer
== NULL
) {
1293 if (errno
== ENOENT
) {
1294 debugs(36, DBG_CRITICAL
, HERE
<< "WARNING: Creating " << p1
);
1295 if (mkdir(p1
, 0777) == 0)
1299 debugs(50, DBG_CRITICAL
, HERE
<< p1
<< ": " << xstrerror());
1305 while ((de
= readdir(dir_pointer
)) != NULL
&& k
< 20) {
1306 if (sscanf(de
->d_name
, "%X", &swapfileno
) != 1)
1309 fn
= swapfileno
; /* XXX should remove this cruft ! */
1311 if (SD
->validFileno(fn
, 1))
1312 if (SD
->mapBitTest(fn
))
1313 if (UFSSwapDir::FilenoBelongsHere(fn
, D0
, D1
, D2
))
1316 files
[k
] = swapfileno
;
1320 closedir(dir_pointer
);
1325 qsort(files
, k
, sizeof(int), rev_int_sort
);
1330 for (n
= 0; n
< k
; ++n
) {
1331 debugs(36, 3, HERE
<< "Cleaning file "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << files
[n
]);
1332 snprintf(p2
, MAXPATHLEN
+ 1, "%s/%08X", p1
, files
[n
]);
1334 ++statCounter
.swap
.files_cleaned
;
1337 debugs(36, 3, HERE
<< "Cleaned " << k
<< " unused files from " << p1
);