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 */
14 #include "RebuildState.h"
15 #include "SquidConfig.h"
16 #include "SquidTime.h"
17 #include "store_key_md5.h"
18 #include "store_rebuild.h"
19 #include "StoreSwapLogData.h"
21 #include "UFSSwapLogParser.h"
29 CBDATA_NAMESPACED_CLASS_INIT(Fs::Ufs
,RebuildState
);
31 Fs::Ufs::RebuildState::RebuildState(RefCount
<UFSSwapDir
> aSwapDir
) :
32 sd (aSwapDir
), LogParser(NULL
), e(NULL
), fromLog(true), _done (false)
35 * If the swap.state file exists in the cache_dir, then
36 * we'll use commonUfsDirRebuildFromSwapLog(), otherwise we'll
37 * use commonUfsDirRebuildFromDirectory() to open up each file
38 * and suck in the meta data.
40 int clean
= 0; //TODO: change to bool
41 int zeroLengthLog
= 0;
42 FILE *fp
= sd
->openTmpSwapLog(&clean
, &zeroLengthLog
);
44 if (fp
&& !zeroLengthLog
)
45 LogParser
= Fs::Ufs::UFSSwapLogParser::GetUFSSwapLogParser(fp
);
47 if (LogParser
== NULL
) {
55 flags
.clean
= (clean
!= 0);
59 flags
.need_to_validate
= true;
61 debugs(47, DBG_IMPORTANT
, "Rebuilding storage in " << sd
->path
<< " (" <<
62 (clean
? "clean log" : (LogParser
? "dirty log" : "no log")) << ")");
65 Fs::Ufs::RebuildState::~RebuildState()
67 sd
->closeTmpSwapLog();
74 Fs::Ufs::RebuildState::RebuildStep(void *data
)
76 RebuildState
*rb
= (RebuildState
*)data
;
80 eventAdd("storeRebuild", RebuildStep
, rb
, 0.01, 1);
82 -- StoreController::store_dirs_rebuilding
;
83 storeRebuildComplete(&rb
->counts
);
88 /// load entries from swap.state or files until we run out of entries or time
90 Fs::Ufs::RebuildState::rebuildStep()
94 // Balance our desire to maximize the number of entries processed at once
95 // (and, hence, minimize overheads and total rebuild time) with a
96 // requirement to also process Coordinator events, disk I/Os, etc.
97 const int maxSpentMsec
= 50; // keep small: most RAM I/Os are under 1ms
98 const timeval loopStart
= current_time
;
100 const int totalEntries
= LogParser
? LogParser
->SwapLogEntries() : -1;
104 rebuildFromSwapLog();
106 rebuildFromDirectory();
108 // TODO: teach storeRebuildProgress to handle totalEntries <= 0
109 if (totalEntries
> 0 && (n_read
% 4000 == 0))
110 storeRebuildProgress(sd
->index
, totalEntries
, n_read
);
112 if (opt_foreground_rebuild
)
113 continue; // skip "few entries at a time" check below
116 const double elapsedMsec
= tvSubMsec(loopStart
, current_time
);
117 if (elapsedMsec
> maxSpentMsec
|| elapsedMsec
< 0) {
118 debugs(47, 5, HERE
<< "pausing after " << n_read
<< " entries in " <<
119 elapsedMsec
<< "ms; " << (elapsedMsec
/n_read
) << "ms per entry");
125 /// process one cache file
127 Fs::Ufs::RebuildState::rebuildFromDirectory()
129 cache_key key
[SQUID_MD5_DIGEST_LENGTH
];
133 debugs(47, 3, HERE
<< "DIR #" << sd
->index
);
138 fd
= getNextFile(&filn
, &size
);
141 debugs(47, DBG_IMPORTANT
, "Done scanning " << sd
->path
<< " dir (" <<
142 n_read
<< " entries)");
150 /* lets get file stats here */
154 if (fstat(fd
, &sb
) < 0) {
155 debugs(47, DBG_IMPORTANT
, HERE
<< "fstat(FD " << fd
<< "): " << xstrerror());
157 --store_open_disk_fd
;
163 buf
.init(SM_PAGE_SIZE
, SM_PAGE_SIZE
);
164 if (!storeRebuildLoadEntry(fd
, sd
->index
, buf
, counts
))
167 const uint64_t expectedSize
= sb
.st_size
> 0 ?
168 static_cast<uint64_t>(sb
.st_size
) : 0;
171 const bool parsed
= storeRebuildParseEntry(buf
, tmpe
, key
, counts
,
175 --store_open_disk_fd
;
178 bool accepted
= parsed
&& tmpe
.swap_file_sz
> 0;
179 if (parsed
&& !accepted
) {
180 debugs(47, DBG_IMPORTANT
, "WARNING: Ignoring ufs cache entry with " <<
181 "unknown size: " << tmpe
);
186 // XXX: shouldn't this be a call to commonUfsUnlink?
187 sd
->unlinkFile(filn
); // should we unlink in all failure cases?
191 if (!storeRebuildKeepEntry(tmpe
, key
, counts
))
196 currentEntry(sd
->addDiskRestore(key
,
203 tmpe
.refcount
, /* refcount */
204 tmpe
.flags
, /* flags */
206 storeDirSwapLog(currentEntry(), SWAP_LOG_ADD
);
210 Fs::Ufs::RebuildState::currentEntry() const
216 Fs::Ufs::RebuildState::currentEntry(StoreEntry
*newValue
)
221 /// process one swap log entry
223 Fs::Ufs::RebuildState::rebuildFromSwapLog()
225 StoreSwapLogData swapData
;
227 if (LogParser
->ReadRecord(swapData
) != 1) {
228 debugs(47, DBG_IMPORTANT
, "Done reading " << sd
->path
<< " swaplog (" << n_read
<< " entries)");
238 if (!swapData
.sane()) {
244 * BC: during 2.4 development, we changed the way swap file
245 * numbers are assigned and stored. The high 16 bits used
246 * to encode the SD index number. There used to be a call
247 * to storeDirProperFileno here that re-assigned the index
248 * bits. Now, for backwards compatibility, we just need
251 swapData
.swap_filen
&= 0x00FFFFFF;
253 debugs(47, 3, HERE
<< swap_log_op_str
[(int) swapData
.op
] << " " <<
254 storeKeyText(swapData
.key
) << " "<< std::setfill('0') <<
255 std::hex
<< std::uppercase
<< std::setw(8) <<
256 swapData
.swap_filen
);
258 if (swapData
.op
== SWAP_LOG_ADD
) {
260 } else if (swapData
.op
== SWAP_LOG_DEL
) {
261 /* Delete unless we already have a newer copy anywhere in any store */
262 /* this needs to become
264 * 2) make synthetic request with headers ?? or otherwise search
265 * for a matching object in the store
266 * TODO FIXME change to new async api
268 currentEntry (Store::Root().get(swapData
.key
));
270 if (currentEntry() != NULL
&& swapData
.lastref
>= e
->lastref
) {
273 ++counts
.cancelcount
;
278 x
= ::log(static_cast<double>(++counts
.bad_log_op
)) / ::log(10.0);
280 if (0.0 == x
- (double) (int) x
)
281 debugs(47, DBG_IMPORTANT
, "WARNING: " << counts
.bad_log_op
<< " invalid swap log entries found");
288 ++counts
.scancount
; // XXX: should not this be incremented earlier?
290 if (!sd
->validFileno(swapData
.swap_filen
, 0)) {
295 if (EBIT_TEST(swapData
.flags
, KEY_PRIVATE
)) {
300 /* this needs to become
302 * 2) make synthetic request with headers ?? or otherwise search
303 * for a matching object in the store
304 * TODO FIXME change to new async api
306 currentEntry (Store::Root().get(swapData
.key
));
308 int used
; /* is swapfile already in use? */
310 used
= sd
->mapBitTest(swapData
.swap_filen
);
312 /* If this URL already exists in the cache, does the swap log
313 * appear to have a newer entry? Compare 'lastref' from the
314 * swap log to e->lastref. */
315 /* is the log entry newer than current entry? */
316 int disk_entry_newer
= currentEntry() ? (swapData
.lastref
> currentEntry()->lastref
? 1 : 0) : 0;
318 if (used
&& !disk_entry_newer
) {
319 /* log entry is old, ignore it */
322 } else if (used
&& currentEntry() && currentEntry()->swap_filen
== swapData
.swap_filen
&& currentEntry()->swap_dirn
== sd
->index
) {
323 /* swapfile taken, same URL, newer, update meta */
325 if (currentEntry()->store_status
== STORE_OK
) {
326 currentEntry()->lastref
= swapData
.timestamp
;
327 currentEntry()->timestamp
= swapData
.timestamp
;
328 currentEntry()->expires
= swapData
.expires
;
329 currentEntry()->lastmod
= swapData
.lastmod
;
330 currentEntry()->flags
= swapData
.flags
;
331 currentEntry()->refcount
+= swapData
.refcount
;
332 sd
->dereference(*currentEntry(), false);
334 debug_trap("commonUfsDirRebuildFromSwapLog: bad condition");
335 debugs(47, DBG_IMPORTANT
, HERE
<< "bad condition");
339 /* swapfile in use, not by this URL, log entry is newer */
340 /* This is sorta bad: the log entry should NOT be newer at this
341 * point. If the log is dirty, the filesize check should have
342 * caught this. If the log is clean, there should never be a
344 debugs(47, DBG_IMPORTANT
, "WARNING: newer swaplog entry for dirno " <<
345 sd
->index
<< ", fileno "<< std::setfill('0') << std::hex
<<
346 std::uppercase
<< std::setw(8) << swapData
.swap_filen
);
348 /* I'm tempted to remove the swapfile here just to be safe,
349 * but there is a bad race condition in the NOVM version if
350 * the swapfile has recently been opened for writing, but
351 * not yet opened for reading. Because we can't map
352 * swapfiles back to StoreEntrys, we don't know the state
353 * of the entry using that file. */
354 /* We'll assume the existing entry is valid, probably because
355 * were in a slow rebuild and the the swap file number got taken
356 * and the validation procedure hasn't run. */
357 assert(flags
.need_to_validate
);
360 } else if (currentEntry() && !disk_entry_newer
) {
361 /* key already exists, current entry is newer */
362 /* keep old, ignore new */
365 } else if (currentEntry()) {
366 /* key already exists, this swapfile not being used */
367 /* junk old, load new */
372 /* URL doesnt exist, swapfile not in use */
379 currentEntry(sd
->addDiskRestore(swapData
.key
,
381 swapData
.swap_file_sz
,
390 storeDirSwapLog(currentEntry(), SWAP_LOG_ADD
);
393 /// undo the effects of adding an entry in rebuildFromSwapLog()
395 Fs::Ufs::RebuildState::undoAdd()
397 StoreEntry
*added
= currentEntry();
401 // TODO: Why bother with these two if we are going to release?!
403 added
->releaseRequest();
405 if (added
->swap_filen
> -1) {
406 SwapDir
*someDir
= INDEXSD(added
->swap_dirn
);
408 if (UFSSwapDir
*ufsDir
= dynamic_cast<UFSSwapDir
*>(someDir
))
409 ufsDir
->undoAddDiskRestore(added
);
410 // else the entry was loaded from and/or is currently in a non-UFS dir
411 // Thus, there is no use in preserving its disk file (the only purpose
412 // of undoAddDiskRestore!), even if we could. Instead, we release the
413 // the entry and [eventually] unlink its disk file or free its slot.
420 Fs::Ufs::RebuildState::getNextFile(sfileno
* filn_p
, int *)
424 debugs(47, 3, HERE
<< "flag=" << flags
.init
<< ", " <<
425 sd
->index
<< ": /"<< std::setfill('0') << std::hex
<<
426 std::uppercase
<< std::setw(2) << curlvl1
<< "/" << std::setw(2) <<
432 while (fd
< 0 && done
== 0) {
435 if (!flags
.init
) { /* initialize, open first file */
441 assert(Config
.cacheSwap
.n_configured
> 0);
444 if (0 == in_dir
) { /* we need to read in a new directory */
445 snprintf(fullpath
, MAXPATHLEN
, "%s/%02X/%02X",
452 td
= opendir(fullpath
);
457 debugs(47, DBG_IMPORTANT
, HERE
<< "error in opendir (" << fullpath
<< "): " << xstrerror());
459 entry
= readdir(td
); /* skip . and .. */
462 if (entry
== NULL
&& errno
== ENOENT
)
463 debugs(47, DBG_IMPORTANT
, HERE
<< "WARNING: directory does not exist!");
464 debugs(47, 3, HERE
<< "Directory " << fullpath
);
468 if (td
!= NULL
&& (entry
= readdir(td
)) != NULL
) {
471 if (sscanf(entry
->d_name
, "%x", &fn
) != 1) {
472 debugs(47, 3, HERE
<< "invalid entry " << entry
->d_name
);
476 if (!UFSSwapDir::FilenoBelongsHere(fn
, sd
->index
, curlvl1
, curlvl2
)) {
477 debugs(47, 3, HERE
<< std::setfill('0') <<
478 std::hex
<< std::uppercase
<< std::setw(8) << fn
<<
479 " does not belong in " << std::dec
<< sd
->index
<< "/" <<
480 curlvl1
<< "/" << curlvl2
);
485 if (sd
->mapBitTest(fn
)) {
486 debugs(47, 3, HERE
<< "Locked, continuing with next.");
490 snprintf(fullfilename
, MAXPATHLEN
, "%s/%s",
491 fullpath
, entry
->d_name
);
492 debugs(47, 3, HERE
<< "Opening " << fullfilename
);
493 fd
= file_open(fullfilename
, O_RDONLY
| O_BINARY
);
496 debugs(47, DBG_IMPORTANT
, HERE
<< "error opening " << fullfilename
<< ": " << xstrerror());
498 ++store_open_disk_fd
;
510 if (sd
->validL2(++curlvl2
))
515 if (sd
->validL1(++curlvl1
))
528 Fs::Ufs::RebuildState::error() const
534 Fs::Ufs::RebuildState::isDone() const
540 Fs::Ufs::RebuildState::currentItem()
542 return currentEntry();