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
) :
51 * If the swap.state file exists in the cache_dir, then
52 * we'll use commonUfsDirRebuildFromSwapLog(), otherwise we'll
53 * use commonUfsDirRebuildFromDirectory() to open up each file
54 * and suck in the meta data.
56 int clean
= 0; //TODO: change to bool
57 int zeroLengthLog
= 0;
58 FILE *fp
= sd
->openTmpSwapLog(&clean
, &zeroLengthLog
);
60 if (fp
&& !zeroLengthLog
)
61 LogParser
= Fs::Ufs::UFSSwapLogParser::GetUFSSwapLogParser(fp
);
63 if (LogParser
== NULL
) {
71 flags
.clean
= (clean
!= 0);
75 flags
.need_to_validate
= true;
77 debugs(47, DBG_IMPORTANT
, "Rebuilding storage in " << sd
->path
<< " (" <<
78 (clean
? "clean log" : (LogParser
? "dirty log" : "no log")) << ")");
81 Fs::Ufs::RebuildState::~RebuildState()
83 sd
->closeTmpSwapLog();
90 Fs::Ufs::RebuildState::RebuildStep(void *data
)
92 RebuildState
*rb
= (RebuildState
*)data
;
96 eventAdd("storeRebuild", RebuildStep
, rb
, 0.01, 1);
98 -- StoreController::store_dirs_rebuilding
;
99 storeRebuildComplete(&rb
->counts
);
104 /// load entries from swap.state or files until we run out of entries or time
106 Fs::Ufs::RebuildState::rebuildStep()
110 // Balance our desire to maximize the number of entries processed at once
111 // (and, hence, minimize overheads and total rebuild time) with a
112 // requirement to also process Coordinator events, disk I/Os, etc.
113 const int maxSpentMsec
= 50; // keep small: most RAM I/Os are under 1ms
114 const timeval loopStart
= current_time
;
116 const int totalEntries
= LogParser
? LogParser
->SwapLogEntries() : -1;
120 rebuildFromSwapLog();
122 rebuildFromDirectory();
124 // TODO: teach storeRebuildProgress to handle totalEntries <= 0
125 if (totalEntries
> 0 && (n_read
% 4000 == 0))
126 storeRebuildProgress(sd
->index
, totalEntries
, n_read
);
128 if (opt_foreground_rebuild
)
129 continue; // skip "few entries at a time" check below
132 const double elapsedMsec
= tvSubMsec(loopStart
, current_time
);
133 if (elapsedMsec
> maxSpentMsec
|| elapsedMsec
< 0) {
134 debugs(47, 5, HERE
<< "pausing after " << n_read
<< " entries in " <<
135 elapsedMsec
<< "ms; " << (elapsedMsec
/n_read
) << "ms per entry");
141 /// process one cache file
143 Fs::Ufs::RebuildState::rebuildFromDirectory()
145 cache_key key
[SQUID_MD5_DIGEST_LENGTH
];
149 debugs(47, 3, HERE
<< "DIR #" << sd
->index
);
154 fd
= getNextFile(&filn
, &size
);
157 debugs(47, DBG_IMPORTANT
, "Done scanning " << sd
->path
<< " dir (" <<
158 n_read
<< " entries)");
166 /* lets get file stats here */
170 if (fstat(fd
, &sb
) < 0) {
171 debugs(47, DBG_IMPORTANT
, HERE
<< "fstat(FD " << fd
<< "): " << xstrerror());
173 --store_open_disk_fd
;
179 buf
.init(SM_PAGE_SIZE
, SM_PAGE_SIZE
);
180 if (!storeRebuildLoadEntry(fd
, sd
->index
, buf
, counts
))
183 const uint64_t expectedSize
= sb
.st_size
> 0 ?
184 static_cast<uint64_t>(sb
.st_size
) : 0;
187 const bool parsed
= storeRebuildParseEntry(buf
, tmpe
, key
, counts
,
191 --store_open_disk_fd
;
194 bool accepted
= parsed
&& tmpe
.swap_file_sz
> 0;
195 if (parsed
&& !accepted
) {
196 debugs(47, DBG_IMPORTANT
, "WARNING: Ignoring ufs cache entry with " <<
197 "unknown size: " << tmpe
);
202 // XXX: shouldn't this be a call to commonUfsUnlink?
203 sd
->unlinkFile(filn
); // should we unlink in all failure cases?
207 if (!storeRebuildKeepEntry(tmpe
, key
, counts
))
212 currentEntry(sd
->addDiskRestore(key
,
219 tmpe
.refcount
, /* refcount */
220 tmpe
.flags
, /* flags */
222 storeDirSwapLog(currentEntry(), SWAP_LOG_ADD
);
226 Fs::Ufs::RebuildState::currentEntry() const
232 Fs::Ufs::RebuildState::currentEntry(StoreEntry
*newValue
)
237 /// process one swap log entry
239 Fs::Ufs::RebuildState::rebuildFromSwapLog()
241 StoreSwapLogData swapData
;
243 if (LogParser
->ReadRecord(swapData
) != 1) {
244 debugs(47, DBG_IMPORTANT
, "Done reading " << sd
->path
<< " swaplog (" << n_read
<< " entries)");
254 if (!swapData
.sane()) {
260 * BC: during 2.4 development, we changed the way swap file
261 * numbers are assigned and stored. The high 16 bits used
262 * to encode the SD index number. There used to be a call
263 * to storeDirProperFileno here that re-assigned the index
264 * bits. Now, for backwards compatibility, we just need
267 swapData
.swap_filen
&= 0x00FFFFFF;
269 debugs(47, 3, HERE
<< swap_log_op_str
[(int) swapData
.op
] << " " <<
270 storeKeyText(swapData
.key
) << " "<< std::setfill('0') <<
271 std::hex
<< std::uppercase
<< std::setw(8) <<
272 swapData
.swap_filen
);
274 if (swapData
.op
== SWAP_LOG_ADD
) {
276 } else if (swapData
.op
== SWAP_LOG_DEL
) {
277 /* Delete unless we already have a newer copy anywhere in any store */
278 /* this needs to become
280 * 2) make synthetic request with headers ?? or otherwise search
281 * for a matching object in the store
282 * TODO FIXME change to new async api
284 currentEntry (Store::Root().get(swapData
.key
));
286 if (currentEntry() != NULL
&& swapData
.lastref
>= e
->lastref
) {
289 ++counts
.cancelcount
;
294 x
= ::log(static_cast<double>(++counts
.bad_log_op
)) / ::log(10.0);
296 if (0.0 == x
- (double) (int) x
)
297 debugs(47, DBG_IMPORTANT
, "WARNING: " << counts
.bad_log_op
<< " invalid swap log entries found");
304 ++counts
.scancount
; // XXX: should not this be incremented earlier?
306 if (!sd
->validFileno(swapData
.swap_filen
, 0)) {
311 if (EBIT_TEST(swapData
.flags
, KEY_PRIVATE
)) {
316 /* this needs to become
318 * 2) make synthetic request with headers ?? or otherwise search
319 * for a matching object in the store
320 * TODO FIXME change to new async api
322 currentEntry (Store::Root().get(swapData
.key
));
324 int used
; /* is swapfile already in use? */
326 used
= sd
->mapBitTest(swapData
.swap_filen
);
328 /* If this URL already exists in the cache, does the swap log
329 * appear to have a newer entry? Compare 'lastref' from the
330 * swap log to e->lastref. */
331 /* is the log entry newer than current entry? */
332 int disk_entry_newer
= currentEntry() ? (swapData
.lastref
> currentEntry()->lastref
? 1 : 0) : 0;
334 if (used
&& !disk_entry_newer
) {
335 /* log entry is old, ignore it */
338 } else if (used
&& currentEntry() && currentEntry()->swap_filen
== swapData
.swap_filen
&& currentEntry()->swap_dirn
== sd
->index
) {
339 /* swapfile taken, same URL, newer, update meta */
341 if (currentEntry()->store_status
== STORE_OK
) {
342 currentEntry()->lastref
= swapData
.timestamp
;
343 currentEntry()->timestamp
= swapData
.timestamp
;
344 currentEntry()->expires
= swapData
.expires
;
345 currentEntry()->lastmod
= swapData
.lastmod
;
346 currentEntry()->flags
= swapData
.flags
;
347 currentEntry()->refcount
+= swapData
.refcount
;
348 sd
->dereference(*currentEntry(), false);
350 debug_trap("commonUfsDirRebuildFromSwapLog: bad condition");
351 debugs(47, DBG_IMPORTANT
, HERE
<< "bad condition");
355 /* swapfile in use, not by this URL, log entry is newer */
356 /* This is sorta bad: the log entry should NOT be newer at this
357 * point. If the log is dirty, the filesize check should have
358 * caught this. If the log is clean, there should never be a
360 debugs(47, DBG_IMPORTANT
, "WARNING: newer swaplog entry for dirno " <<
361 sd
->index
<< ", fileno "<< std::setfill('0') << std::hex
<<
362 std::uppercase
<< std::setw(8) << swapData
.swap_filen
);
364 /* I'm tempted to remove the swapfile here just to be safe,
365 * but there is a bad race condition in the NOVM version if
366 * the swapfile has recently been opened for writing, but
367 * not yet opened for reading. Because we can't map
368 * swapfiles back to StoreEntrys, we don't know the state
369 * of the entry using that file. */
370 /* We'll assume the existing entry is valid, probably because
371 * were in a slow rebuild and the the swap file number got taken
372 * and the validation procedure hasn't run. */
373 assert(flags
.need_to_validate
);
376 } else if (currentEntry() && !disk_entry_newer
) {
377 /* key already exists, current entry is newer */
378 /* keep old, ignore new */
381 } else if (currentEntry()) {
382 /* key already exists, this swapfile not being used */
383 /* junk old, load new */
388 /* URL doesnt exist, swapfile not in use */
395 currentEntry(sd
->addDiskRestore(swapData
.key
,
397 swapData
.swap_file_sz
,
406 storeDirSwapLog(currentEntry(), SWAP_LOG_ADD
);
409 /// undo the effects of adding an entry in rebuildFromSwapLog()
411 Fs::Ufs::RebuildState::undoAdd()
413 StoreEntry
*added
= currentEntry();
417 // TODO: Why bother with these two if we are going to release?!
419 added
->releaseRequest();
421 if (added
->swap_filen
> -1) {
422 SwapDir
*someDir
= INDEXSD(added
->swap_dirn
);
424 if (UFSSwapDir
*ufsDir
= dynamic_cast<UFSSwapDir
*>(someDir
))
425 ufsDir
->undoAddDiskRestore(added
);
426 // else the entry was loaded from and/or is currently in a non-UFS dir
427 // Thus, there is no use in preserving its disk file (the only purpose
428 // of undoAddDiskRestore!), even if we could. Instead, we release the
429 // the entry and [eventually] unlink its disk file or free its slot.
436 Fs::Ufs::RebuildState::getNextFile(sfileno
* filn_p
, int *)
440 debugs(47, 3, HERE
<< "flag=" << flags
.init
<< ", " <<
441 sd
->index
<< ": /"<< std::setfill('0') << std::hex
<<
442 std::uppercase
<< std::setw(2) << curlvl1
<< "/" << std::setw(2) <<
448 while (fd
< 0 && done
== 0) {
451 if (!flags
.init
) { /* initialize, open first file */
452 // XXX: 0's should not be needed, constructor inits now
458 assert(Config
.cacheSwap
.n_configured
> 0);
461 if (0 == in_dir
) { /* we need to read in a new directory */
462 snprintf(fullpath
, MAXPATHLEN
, "%s/%02X/%02X",
469 td
= opendir(fullpath
);
474 debugs(47, DBG_IMPORTANT
, HERE
<< "error in opendir (" << fullpath
<< "): " << xstrerror());
476 entry
= readdir(td
); /* skip . and .. */
479 if (entry
== NULL
&& errno
== ENOENT
)
480 debugs(47, DBG_IMPORTANT
, HERE
<< "WARNING: directory does not exist!");
481 debugs(47, 3, HERE
<< "Directory " << fullpath
);
485 if (td
!= NULL
&& (entry
= readdir(td
)) != NULL
) {
488 if (sscanf(entry
->d_name
, "%x", &fn
) != 1) {
489 debugs(47, 3, HERE
<< "invalid entry " << entry
->d_name
);
493 if (!UFSSwapDir::FilenoBelongsHere(fn
, sd
->index
, curlvl1
, curlvl2
)) {
494 debugs(47, 3, HERE
<< std::setfill('0') <<
495 std::hex
<< std::uppercase
<< std::setw(8) << fn
<<
496 " does not belong in " << std::dec
<< sd
->index
<< "/" <<
497 curlvl1
<< "/" << curlvl2
);
502 if (sd
->mapBitTest(fn
)) {
503 debugs(47, 3, HERE
<< "Locked, continuing with next.");
507 snprintf(fullfilename
, MAXPATHLEN
, "%s/%s",
508 fullpath
, entry
->d_name
);
509 debugs(47, 3, HERE
<< "Opening " << fullfilename
);
510 fd
= file_open(fullfilename
, O_RDONLY
| O_BINARY
);
513 debugs(47, DBG_IMPORTANT
, HERE
<< "error opening " << fullfilename
<< ": " << xstrerror());
515 ++store_open_disk_fd
;
527 if (sd
->validL2(++curlvl2
))
532 if (sd
->validL1(++curlvl1
))
545 Fs::Ufs::RebuildState::error() const
551 Fs::Ufs::RebuildState::isDone() const
557 Fs::Ufs::RebuildState::currentItem()
559 return currentEntry();