]> git.ipfire.org Git - thirdparty/squid.git/blob - src/fs/ufs/UFSSwapDir.cc
Merge cleanups branch: split most of typedefs.h
[thirdparty/squid.git] / src / fs / ufs / UFSSwapDir.cc
1 /*
2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
3 *
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.
7 */
8
9 /* DEBUG: section 47 Store Directory Routines */
10
11 #define CLEAN_BUF_SZ 16384
12
13 #include "squid.h"
14 #include "cache_cf.h"
15 #include "ConfigOption.h"
16 #include "disk.h"
17 #include "DiskIO/DiskIOModule.h"
18 #include "DiskIO/DiskIOStrategy.h"
19 #include "fde.h"
20 #include "FileMap.h"
21 #include "globals.h"
22 #include "Parsing.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"
31 #include "tools.h"
32 #include "UFSSwapDir.h"
33
34 #include <cerrno>
35 #include <cmath>
36 #include <random>
37 #if HAVE_SYS_STAT_H
38 #include <sys/stat.h>
39 #endif
40
41 int Fs::Ufs::UFSSwapDir::NumberOfUFSDirs = 0;
42 int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping = NULL;
43
44 class UFSCleanLog : public SwapDir::CleanLog
45 {
46
47 public:
48 UFSCleanLog(SwapDir *);
49 /** Get the next entry that is a candidate for clean log writing
50 */
51 virtual const StoreEntry *nextEntry();
52 /** "write" an entry to the clean log file.
53 */
54 virtual void write(StoreEntry const &);
55 char *cur;
56 char *newLog;
57 char *cln;
58 char *outbuf;
59 off_t outbuf_offset;
60 int fd;
61 RemovalPolicyWalker *walker;
62 SwapDir *sd;
63 };
64
65 UFSCleanLog::UFSCleanLog(SwapDir *aSwapDir) :
66 cur(NULL), newLog(NULL), cln(NULL), outbuf(NULL),
67 outbuf_offset(0), fd(-1),walker(NULL), sd(aSwapDir)
68 {}
69
70 const StoreEntry *
71 UFSCleanLog::nextEntry()
72 {
73 const StoreEntry *entry = NULL;
74
75 if (walker)
76 entry = walker->Next(walker);
77
78 return entry;
79 }
80
81 void
82 UFSCleanLog::write(StoreEntry const &e)
83 {
84 StoreSwapLogData s;
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;
94 s.flags = e.flags;
95 memcpy(&s.key, e.key, SQUID_MD5_DIGEST_LENGTH);
96 s.finalize();
97 memcpy(outbuf + outbuf_offset, &s, ss);
98 outbuf_offset += ss;
99 /* buffered write */
100
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.");
106 file_close(fd);
107 fd = -1;
108 unlink(newLog);
109 sd->cleanLog = NULL;
110 delete this;
111 return;
112 }
113
114 outbuf_offset = 0;
115 }
116 }
117
118 bool
119 Fs::Ufs::UFSSwapDir::canStore(const StoreEntry &e, int64_t diskSpaceNeeded, int &load) const
120 {
121 if (!SwapDir::canStore(e, diskSpaceNeeded, load))
122 return false;
123
124 if (IO->shedLoad())
125 return false;
126
127 load = IO->load();
128 return true;
129 }
130
131 static void
132 FreeObject(void *address)
133 {
134 StoreSwapLogData *anObject = static_cast <StoreSwapLogData *>(address);
135 delete anObject;
136 }
137
138 static int
139 rev_int_sort(const void *A, const void *B)
140 {
141 const int *i1 = (const int *)A;
142 const int *i2 = (const int *)B;
143 return *i2 - *i1;
144 }
145
146 void
147 Fs::Ufs::UFSSwapDir::parseSizeL1L2()
148 {
149 int i = GetInteger();
150 if (i <= 0)
151 fatal("UFSSwapDir::parseSizeL1L2: invalid size value");
152
153 const uint64_t size = static_cast<uint64_t>(i) << 20; // MBytes to Bytes
154
155 /* just reconfigure it */
156 if (reconfiguring) {
157 if (size == maxSize())
158 debugs(3, 2, "Cache dir '" << path << "' size remains unchanged at " << i << " MB");
159 else
160 debugs(3, DBG_IMPORTANT, "Cache dir '" << path << "' size changed to " << i << " MB");
161 }
162
163 max_size = size;
164
165 l1 = GetInteger();
166
167 if (l1 <= 0)
168 fatal("UFSSwapDir::parseSizeL1L2: invalid level 1 directories value");
169
170 l2 = GetInteger();
171
172 if (l2 <= 0)
173 fatal("UFSSwapDir::parseSizeL1L2: invalid level 2 directories value");
174 }
175
176 void
177 Fs::Ufs::UFSSwapDir::reconfigure()
178 {
179 parseSizeL1L2();
180 parseOptions(1);
181 }
182
183 void
184 Fs::Ufs::UFSSwapDir::parse (int anIndex, char *aPath)
185 {
186 index = anIndex;
187 path = xstrdup(aPath);
188
189 parseSizeL1L2();
190
191 /* Initialise replacement policy stuff */
192 repl = createRemovalPolicy(Config.replPolicy);
193
194 parseOptions(0);
195 }
196
197 void
198 Fs::Ufs::UFSSwapDir::changeIO(DiskIOModule *module)
199 {
200 DiskIOStrategy *anIO = module->createStrategy();
201 safe_free(ioType);
202 ioType = xstrdup(module->type());
203
204 delete IO->io;
205 IO->io = anIO;
206 /* Change the IO Options */
207
208 if (currentIOOptions && currentIOOptions->options.size() > 2) {
209 delete currentIOOptions->options.back();
210 currentIOOptions->options.pop_back();
211 }
212
213 /* TODO: factor out these 4 lines */
214 ConfigOption *ioOptions = IO->io->getOptionTree();
215
216 if (currentIOOptions && ioOptions)
217 currentIOOptions->options.push_back(ioOptions);
218 }
219
220 bool
221 Fs::Ufs::UFSSwapDir::optionIOParse(char const *option, const char *value, int isaReconfig)
222 {
223 if (strcmp(option, "IOEngine") != 0)
224 return false;
225
226 if (isaReconfig)
227 /* silently ignore this */
228 return true;
229
230 if (!value)
231 self_destruct();
232
233 DiskIOModule *module = DiskIOModule::Find(value);
234
235 if (!module)
236 self_destruct();
237
238 changeIO(module);
239
240 return true;
241 }
242
243 void
244 Fs::Ufs::UFSSwapDir::optionIODump(StoreEntry * e) const
245 {
246 storeAppendPrintf(e, " IOEngine=%s", ioType);
247 }
248
249 ConfigOption *
250 Fs::Ufs::UFSSwapDir::getOptionTree() const
251 {
252 ConfigOption *parentResult = SwapDir::getOptionTree();
253
254 if (currentIOOptions == NULL)
255 currentIOOptions = new ConfigOptionVector();
256
257 currentIOOptions->options.push_back(parentResult);
258
259 currentIOOptions->options.push_back(new ConfigOptionAdapter<UFSSwapDir>(*const_cast<UFSSwapDir *>(this), &UFSSwapDir::optionIOParse, &UFSSwapDir::optionIODump));
260
261 if (ConfigOption *ioOptions = IO->io->getOptionTree())
262 currentIOOptions->options.push_back(ioOptions);
263
264 ConfigOption* result = currentIOOptions;
265
266 currentIOOptions = NULL;
267
268 return result;
269 }
270
271 void
272 Fs::Ufs::UFSSwapDir::init()
273 {
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.";
282 IO->init();
283
284 if (verifyCacheDirs())
285 fatal(errmsg);
286
287 openLog();
288
289 rebuild();
290
291 if (!started_clean_event) {
292 eventAdd("UFS storeDirClean", CleanEvent, NULL, 15.0, 1);
293 started_clean_event = 1;
294 }
295
296 (void) storeDirGetBlkSize(path, &fs.blksize);
297 }
298
299 void
300 Fs::Ufs::UFSSwapDir::create()
301 {
302 debugs(47, 3, "Creating swap space in " << path);
303 createDirectory(path, 0);
304 createSwapSubDirs();
305 }
306
307 Fs::Ufs::UFSSwapDir::UFSSwapDir(char const *aType, const char *anIOType) :
308 SwapDir(aType),
309 IO(NULL),
310 fsdata(NULL),
311 map(new FileMap()),
312 suggest(0),
313 l1(16),
314 l2(256),
315 swaplog_fd(-1),
316 currentIOOptions(new ConfigOptionVector()),
317 ioType(xstrdup(anIOType)),
318 cur_size(0),
319 n_disk_objects(0)
320 {
321 /* modulename is only set to disk modules that are built, by configure,
322 * so the Find call should never return NULL here.
323 */
324 IO = new Fs::Ufs::UFSStrategy(DiskIOModule::Find(anIOType)->createStrategy());
325 }
326
327 Fs::Ufs::UFSSwapDir::~UFSSwapDir()
328 {
329 if (swaplog_fd > -1) {
330 file_close(swaplog_fd);
331 swaplog_fd = -1;
332 }
333 xfree(ioType);
334 delete map;
335 delete IO;
336 delete currentIOOptions;
337 }
338
339 void
340 Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry &e) const
341 {
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) );
344 e.dump(0);
345 }
346
347 bool
348 Fs::Ufs::UFSSwapDir::doubleCheck(StoreEntry & e)
349 {
350
351 struct stat sb;
352
353 if (::stat(fullPath(e.swap_filen, NULL), &sb) < 0) {
354 debugs(47, DBG_CRITICAL, HERE << "WARNING: Missing swap file");
355 dumpEntry(e);
356 return true;
357 }
358
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);
362 dumpEntry(e);
363 return true;
364 }
365
366 return false;
367 }
368
369 void
370 Fs::Ufs::UFSSwapDir::statfs(StoreEntry & sentry) const
371 {
372 int totl_kb = 0;
373 int free_kb = 0;
374 int totl_in = 0;
375 int free_in = 0;
376 int x;
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);
387
388 if (0 == x) {
389 storeAppendPrintf(&sentry, "Filesystem Space in use: %d/%d KB (%d%%)\n",
390 totl_kb - free_kb,
391 totl_kb,
392 Math::intPercent(totl_kb - free_kb, totl_kb));
393 storeAppendPrintf(&sentry, "Filesystem Inodes in use: %d/%d (%d%%)\n",
394 totl_in - free_in,
395 totl_in,
396 Math::intPercent(totl_in - free_in, totl_in));
397 }
398
399 storeAppendPrintf(&sentry, "Flags:");
400
401 if (flags.selected)
402 storeAppendPrintf(&sentry, " SELECTED");
403
404 if (flags.read_only)
405 storeAppendPrintf(&sentry, " READ-ONLY");
406
407 storeAppendPrintf(&sentry, "\n");
408
409 IO->statfs(sentry);
410 }
411
412 void
413 Fs::Ufs::UFSSwapDir::maintain()
414 {
415 /* TODO: possible options for improvement;
416 *
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.
422 *
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.
425 *
426 * - base removal limit on space saved, instead of count ?
427 *
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
431 *
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
435 *
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.
441 */
442
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);
447 return;
448 }
449
450 // minSize() is swap_low_watermark in bytes
451 const uint64_t lowWaterSz = minSize();
452
453 if (currentSize() < lowWaterSz) {
454 debugs(47, 2, "space still available in " << path);
455 return;
456 }
457
458 // maxSize() is cache_dir total size in bytes
459 const uint64_t highWaterSz = ((maxSize() * Config.Swap.highWaterMark) / 100);
460
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.
465 double f = 1.0;
466 if (highWaterSz > lowWaterSz) {
467 // might be equal. n/0 is bad.
468 f = (double) (currentSize() - lowWaterSz) / (highWaterSz - lowWaterSz);
469 }
470
471 // how deep to look for a single object that can be removed
472 int max_scan = (int) (f * 400.0 + 100.0);
473
474 // try to purge only this many objects this cycle.
475 int max_remove = (int) (f * 300.0 + 20.0);
476
477 /*
478 * This is kinda cheap, but so we need this priority hack?
479 */
480 debugs(47, 3, "f=" << f << ", max_scan=" << max_scan << ", max_remove=" << max_remove);
481
482 RemovalPurgeWalker *walker = repl->PurgeInit(repl, max_scan);
483
484 int removed = 0;
485 // only purge while above low-water
486 while (currentSize() >= lowWaterSz) {
487
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)
492 break;
493
494 StoreEntry *e = walker->Next(walker);
495
496 // stop if all objects are locked / in-use,
497 // or the cache is empty
498 if (!e)
499 break; /* no more objects */
500
501 ++removed;
502
503 e->release();
504 }
505
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);
510
511 // what if cache is still over the high watermark ?
512 // Store::Maintain() schedules another purge in 1 second.
513 }
514
515 void
516 Fs::Ufs::UFSSwapDir::reference(StoreEntry &e)
517 {
518 debugs(47, 3, HERE << "referencing " << &e << " " <<
519 e.swap_dirn << "/" << e.swap_filen);
520
521 if (repl->Referenced)
522 repl->Referenced(repl, &e, &e.repl);
523 }
524
525 bool
526 Fs::Ufs::UFSSwapDir::dereference(StoreEntry & e, bool)
527 {
528 debugs(47, 3, HERE << "dereferencing " << &e << " " <<
529 e.swap_dirn << "/" << e.swap_filen);
530
531 if (repl->Dereferenced)
532 repl->Dereferenced(repl, &e, &e.repl);
533
534 return true; // keep e in the global store_table
535 }
536
537 StoreIOState::Pointer
538 Fs::Ufs::UFSSwapDir::createStoreIO(StoreEntry &e, StoreIOState::STFNCB * file_callback, StoreIOState::STIOCB * aCallback, void *callback_data)
539 {
540 return IO->create (this, &e, file_callback, aCallback, callback_data);
541 }
542
543 StoreIOState::Pointer
544 Fs::Ufs::UFSSwapDir::openStoreIO(StoreEntry &e, StoreIOState::STFNCB * file_callback, StoreIOState::STIOCB * aCallback, void *callback_data)
545 {
546 return IO->open (this, &e, file_callback, aCallback, callback_data);
547 }
548
549 int
550 Fs::Ufs::UFSSwapDir::mapBitTest(sfileno filn)
551 {
552 return map->testBit(filn);
553 }
554
555 void
556 Fs::Ufs::UFSSwapDir::mapBitSet(sfileno filn)
557 {
558 map->setBit(filn);
559 }
560
561 void
562 Fs::Ufs::UFSSwapDir::mapBitReset(sfileno filn)
563 {
564 /*
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.
570 */
571
572 if (map->testBit(filn))
573 map->clearBit(filn);
574 }
575
576 int
577 Fs::Ufs::UFSSwapDir::mapBitAllocate()
578 {
579 int fn;
580 fn = map->allocate(suggest);
581 map->setBit(fn);
582 suggest = fn + 1;
583 return fn;
584 }
585
586 char *
587 Fs::Ufs::UFSSwapDir::swapSubDir(int subdirn)const
588 {
589 LOCAL_ARRAY(char, fullfilename, MAXPATHLEN);
590 assert(0 <= subdirn && subdirn < l1);
591 snprintf(fullfilename, MAXPATHLEN, "%s/%02X", path, subdirn);
592 return fullfilename;
593 }
594
595 int
596 Fs::Ufs::UFSSwapDir::createDirectory(const char *aPath, int should_exist)
597 {
598 int created = 0;
599
600 struct stat st;
601 getCurrentTime();
602
603 if (0 == ::stat(aPath, &st)) {
604 if (S_ISDIR(st.st_mode)) {
605 debugs(47, (should_exist ? 3 : DBG_IMPORTANT), aPath << " exists");
606 } else {
607 fatalf("Swap directory %s is not a directory.", aPath);
608 }
609 } else if (0 == mkdir(aPath, 0755)) {
610 debugs(47, (should_exist ? DBG_IMPORTANT : 3), aPath << " created");
611 created = 1;
612 } else {
613 fatalf("Failed to make swap directory %s: %s",
614 aPath, xstrerror());
615 }
616
617 return created;
618 }
619
620 bool
621 Fs::Ufs::UFSSwapDir::pathIsDirectory(const char *aPath)const
622 {
623
624 struct stat sb;
625
626 if (::stat(aPath, &sb) < 0) {
627 debugs(47, DBG_CRITICAL, "ERROR: " << aPath << ": " << xstrerror());
628 return false;
629 }
630
631 if (S_ISDIR(sb.st_mode) == 0) {
632 debugs(47, DBG_CRITICAL, "WARNING: " << aPath << " is not a directory");
633 return false;
634 }
635
636 return true;
637 }
638
639 bool
640 Fs::Ufs::UFSSwapDir::verifyCacheDirs()
641 {
642 if (!pathIsDirectory(path))
643 return true;
644
645 for (int j = 0; j < l1; ++j) {
646 char const *aPath = swapSubDir(j);
647
648 if (!pathIsDirectory(aPath))
649 return true;
650 }
651
652 return false;
653 }
654
655 void
656 Fs::Ufs::UFSSwapDir::createSwapSubDirs()
657 {
658 LOCAL_ARRAY(char, name, MAXPATHLEN);
659
660 for (int i = 0; i < l1; ++i) {
661 snprintf(name, MAXPATHLEN, "%s/%02X", path, i);
662
663 int should_exist;
664
665 if (createDirectory(name, 0))
666 should_exist = 0;
667 else
668 should_exist = 1;
669
670 debugs(47, DBG_IMPORTANT, "Making directories in " << name);
671
672 for (int k = 0; k < l2; ++k) {
673 snprintf(name, MAXPATHLEN, "%s/%02X/%02X", path, i, k);
674 createDirectory(name, should_exist);
675 }
676 }
677 }
678
679 char *
680 Fs::Ufs::UFSSwapDir::logFile(char const *ext) const
681 {
682 LOCAL_ARRAY(char, lpath, MAXPATHLEN);
683 LOCAL_ARRAY(char, pathtmp, MAXPATHLEN);
684 LOCAL_ARRAY(char, digit, 32);
685 char *pathtmp2;
686
687 if (Config.Log.swap) {
688 xstrncpy(pathtmp, path, MAXPATHLEN - 64);
689 pathtmp2 = pathtmp;
690
691 while ((pathtmp2 = strchr(pathtmp2, '/')) != NULL)
692 *pathtmp2 = '.';
693
694 while (strlen(pathtmp) && pathtmp[strlen(pathtmp) - 1] == '.')
695 pathtmp[strlen(pathtmp) - 1] = '\0';
696
697 for (pathtmp2 = pathtmp; *pathtmp2 == '.'; ++pathtmp2);
698 snprintf(lpath, MAXPATHLEN - 64, Config.Log.swap, pathtmp2);
699
700 if (strncmp(lpath, Config.Log.swap, MAXPATHLEN - 64) == 0) {
701 strcat(lpath, ".");
702 snprintf(digit, 32, "%02d", index);
703 strncat(lpath, digit, 3);
704 }
705 } else {
706 xstrncpy(lpath, path, MAXPATHLEN - 64);
707 strcat(lpath, "/swap.state");
708 }
709
710 if (ext)
711 strncat(lpath, ext, 16);
712
713 return lpath;
714 }
715
716 void
717 Fs::Ufs::UFSSwapDir::openLog()
718 {
719 char *logPath;
720 logPath = logFile();
721 swaplog_fd = file_open(logPath, O_WRONLY | O_CREAT | O_BINARY);
722
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.");
726 }
727
728 debugs(50, 3, HERE << "Cache Dir #" << index << " log opened on FD " << swaplog_fd);
729
730 if (0 == NumberOfUFSDirs)
731 assert(NULL == UFSDirToGlobalDirMapping);
732
733 ++NumberOfUFSDirs;
734
735 assert(NumberOfUFSDirs <= Config.cacheSwap.n_configured);
736 }
737
738 void
739 Fs::Ufs::UFSSwapDir::closeLog()
740 {
741 if (swaplog_fd < 0) /* not open */
742 return;
743
744 file_close(swaplog_fd);
745
746 debugs(47, 3, "Cache Dir #" << index << " log closed on FD " << swaplog_fd);
747
748 swaplog_fd = -1;
749
750 --NumberOfUFSDirs;
751
752 assert(NumberOfUFSDirs >= 0);
753
754 if (0 == NumberOfUFSDirs)
755 safe_free(UFSDirToGlobalDirMapping);
756 }
757
758 bool
759 Fs::Ufs::UFSSwapDir::validL1(int anInt) const
760 {
761 return anInt < l1;
762 }
763
764 bool
765 Fs::Ufs::UFSSwapDir::validL2(int anInt) const
766 {
767 return anInt < l2;
768 }
769
770 StoreEntry *
771 Fs::Ufs::UFSSwapDir::addDiskRestore(const cache_key * key,
772 sfileno file_number,
773 uint64_t swap_file_sz,
774 time_t expires,
775 time_t timestamp,
776 time_t lastref,
777 time_t lastmod,
778 uint32_t refcount,
779 uint16_t newFlags,
780 int)
781 {
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
786 * already in use! */
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;
799 e->flags = newFlags;
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);
806 ++n_disk_objects;
807 e->hashInsert(key); /* do it after we clear KEY_PRIVATE */
808 replacementAdd (e);
809 return e;
810 }
811
812 void
813 Fs::Ufs::UFSSwapDir::undoAddDiskRestore(StoreEntry *e)
814 {
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);
819 e->swap_filen = -1;
820 e->swap_dirn = -1;
821 cur_size -= fs.blksize * sizeInBlocks(e->swap_file_sz);
822 --n_disk_objects;
823 }
824
825 void
826 Fs::Ufs::UFSSwapDir::rebuild()
827 {
828 ++StoreController::store_dirs_rebuilding;
829 eventAdd("storeRebuild", Fs::Ufs::RebuildState::RebuildStep, new Fs::Ufs::RebuildState(this), 0.0, 1);
830 }
831
832 void
833 Fs::Ufs::UFSSwapDir::closeTmpSwapLog()
834 {
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
837 int fd;
838 file_close(swaplog_fd);
839
840 if (xrename(tmp_path, swaplog_path) < 0) {
841 fatalf("Failed to rename log file %s to %s", tmp_path, swaplog_path);
842 }
843
844 fd = file_open(swaplog_path, O_WRONLY | O_CREAT | O_BINARY);
845
846 if (fd < 0) {
847 debugs(50, DBG_IMPORTANT, "ERROR: " << swaplog_path << ": " << xstrerror());
848 fatalf("Failed to open swap log %s", swaplog_path);
849 }
850
851 xfree(swaplog_path);
852 xfree(tmp_path);
853 swaplog_fd = fd;
854 debugs(47, 3, "Cache Dir #" << index << " log opened on FD " << fd);
855 }
856
857 FILE *
858 Fs::Ufs::UFSSwapDir::openTmpSwapLog(int *clean_flag, int *zero_flag)
859 {
860 char *swaplog_path = xstrdup(logFile(NULL));
861 char *clean_path = xstrdup(logFile(".last-clean"));
862 char *new_path = xstrdup(logFile(".new"));
863
864 struct stat log_sb;
865
866 struct stat clean_sb;
867 FILE *fp;
868 int fd;
869
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);
874 safe_free(new_path);
875 return NULL;
876 }
877
878 *zero_flag = log_sb.st_size == 0 ? 1 : 0;
879 /* close the existing write-only FD */
880
881 if (swaplog_fd >= 0)
882 file_close(swaplog_fd);
883
884 /* open a write-only FD for the new log */
885 fd = file_open(new_path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY);
886
887 if (fd < 0) {
888 debugs(50, DBG_IMPORTANT, "ERROR: while opening swap log" << new_path << ": " << xstrerror());
889 fatalf("Failed to open swap log %s", new_path);
890 }
891
892 swaplog_fd = fd;
893
894 {
895 const StoreSwapLogHeader header;
896 MemBuf buf;
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());
904 }
905
906 /* open a read-only stream of the old log */
907 fp = fopen(swaplog_path, "rb");
908
909 if (fp == NULL) {
910 debugs(50, DBG_CRITICAL, "ERROR: while opening " << swaplog_path << ": " << xstrerror());
911 fatalf("Failed to open swap log for reading %s", swaplog_path);
912 }
913
914 memset(&clean_sb, '\0', sizeof(struct stat));
915
916 if (::stat(clean_path, &clean_sb) < 0)
917 *clean_flag = 0;
918 else if (clean_sb.st_mtime < log_sb.st_mtime)
919 *clean_flag = 0;
920 else
921 *clean_flag = 1;
922
923 safeunlink(clean_path, 1);
924
925 safe_free(swaplog_path);
926
927 safe_free(clean_path);
928
929 safe_free(new_path);
930
931 return fp;
932 }
933
934 /*
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.
938 */
939 int
940 Fs::Ufs::UFSSwapDir::writeCleanStart()
941 {
942 UFSCleanLog *state = new UFSCleanLog(this);
943 StoreSwapLogHeader header;
944 #if HAVE_FCHMOD
945
946 struct stat sb;
947 #endif
948
949 cleanLog = NULL;
950 state->newLog = xstrdup(logFile(".clean"));
951 state->fd = file_open(state->newLog, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY);
952
953 if (state->fd < 0) {
954 xfree(state->newLog);
955 delete state;
956 return -1;
957 }
958
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;
963 /*copy the header */
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;
968
969 state->walker = repl->WalkInit(repl);
970 ::unlink(state->cln);
971 debugs(47, 3, HERE << "opened " << state->newLog << ", FD " << state->fd);
972 #if HAVE_FCHMOD
973
974 if (::stat(state->cur, &sb) == 0)
975 fchmod(state->fd, sb.st_mode);
976
977 #endif
978
979 cleanLog = state;
980 return 0;
981 }
982
983 void
984 Fs::Ufs::UFSSwapDir::writeCleanDone()
985 {
986 UFSCleanLog *state = (UFSCleanLog *)cleanLog;
987 int fd;
988
989 if (NULL == state)
990 return;
991
992 if (state->fd < 0)
993 return;
994
995 state->walker->Done(state->walker);
996
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);
1001 state->fd = -1;
1002 ::unlink(state->newLog);
1003 }
1004
1005 safe_free(state->outbuf);
1006 /*
1007 * You can't rename open files on Microsoft "operating systems"
1008 * so we have to close before renaming.
1009 */
1010 closeLog();
1011 /* save the fd value for a later test */
1012 fd = state->fd;
1013 /* rename */
1014
1015 if (state->fd >= 0) {
1016 #if _SQUID_OS2_ || _SQUID_WINDOWS_
1017 file_close(state->fd);
1018 state->fd = -1;
1019 #endif
1020
1021 xrename(state->newLog, state->cur);
1022 }
1023
1024 /* touch a timestamp file if we're not still validating */
1025 if (StoreController::store_dirs_rebuilding)
1026 (void) 0;
1027 else if (fd < 0)
1028 (void) 0;
1029 else
1030 file_close(file_open(state->cln, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY));
1031
1032 /* close */
1033 safe_free(state->cur);
1034
1035 safe_free(state->newLog);
1036
1037 safe_free(state->cln);
1038
1039 if (state->fd >= 0)
1040 file_close(state->fd);
1041
1042 state->fd = -1;
1043
1044 delete state;
1045
1046 cleanLog = NULL;
1047 }
1048
1049 void
1050 Fs::Ufs::UFSSwapDir::CleanEvent(void *)
1051 {
1052 static int swap_index = 0;
1053 int i;
1054 int j = 0;
1055 int n = 0;
1056 /*
1057 * Assert that there are UFS cache_dirs configured, otherwise
1058 * we should never be called.
1059 */
1060 assert(NumberOfUFSDirs);
1061
1062 if (NULL == UFSDirToGlobalDirMapping) {
1063 SwapDir *sd;
1064 /*
1065 * Initialize the little array that translates UFS cache_dir
1066 * number into the Config.cacheSwap.swapDirs array index.
1067 */
1068 UFSDirToGlobalDirMapping = (int *)xcalloc(NumberOfUFSDirs, sizeof(*UFSDirToGlobalDirMapping));
1069
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));
1073
1074 if (!UFSSwapDir::IsUFSDir(sd))
1075 continue;
1076
1077 UFSSwapDir *usd = dynamic_cast<UFSSwapDir *>(sd);
1078
1079 assert (usd);
1080
1081 UFSDirToGlobalDirMapping[n] = i;
1082 ++n;
1083
1084 j += (usd->l1 * usd->l2);
1085 }
1086
1087 assert(n == NumberOfUFSDirs);
1088 /*
1089 * Start the commonUfsDirClean() swap_index with a random
1090 * value. j equals the total number of UFS level 2
1091 * swap directories
1092 */
1093 std::mt19937 mt(static_cast<uint32_t>(getCurrentTime() & 0xFFFFFFFF));
1094 xuniform_int_distribution<> dist(0, j);
1095 swap_index = dist(mt);
1096 }
1097
1098 /* if the rebuild is finished, start cleaning directories. */
1099 if (0 == StoreController::store_dirs_rebuilding) {
1100 n = DirClean(swap_index);
1101 ++swap_index;
1102 }
1103
1104 eventAdd("storeDirClean", CleanEvent, NULL,
1105 15.0 * exp(-0.25 * n), 1);
1106 }
1107
1108 bool
1109 Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir * sd)
1110 {
1111 UFSSwapDir *mySD = dynamic_cast<UFSSwapDir *>(sd);
1112 return (mySD != 0) ;
1113 }
1114
1115 /*
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;
1119 */
1120 bool
1121 Fs::Ufs::UFSSwapDir::FilenoBelongsHere(int fn, int F0, int F1, int F2)
1122 {
1123 int D1, D2;
1124 int L1, L2;
1125 int filn = fn;
1126 assert(F0 < Config.cacheSwap.n_configured);
1127 assert (UFSSwapDir::IsUFSDir (dynamic_cast<SwapDir *>(INDEXSD(F0))));
1128 UFSSwapDir *sd = dynamic_cast<UFSSwapDir *>(INDEXSD(F0));
1129
1130 if (!sd)
1131 return 0;
1132
1133 L1 = sd->l1;
1134
1135 L2 = sd->l2;
1136
1137 D1 = ((filn / L2) / L2) % L1;
1138
1139 if (F1 != D1)
1140 return 0;
1141
1142 D2 = (filn / L2) % L2;
1143
1144 if (F2 != D2)
1145 return 0;
1146
1147 return 1;
1148 }
1149
1150 int
1151 Fs::Ufs::UFSSwapDir::validFileno(sfileno filn, int flag) const
1152 {
1153 if (filn < 0)
1154 return 0;
1155
1156 /*
1157 * If flag is set it means out-of-range file number should
1158 * be considered invalid.
1159 */
1160 if (flag)
1161 if (filn > map->capacity())
1162 return 0;
1163
1164 return 1;
1165 }
1166
1167 void
1168 Fs::Ufs::UFSSwapDir::unlinkFile(sfileno f)
1169 {
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));
1175 }
1176
1177 bool
1178 Fs::Ufs::UFSSwapDir::unlinkdUseful() const
1179 {
1180 // unlinkd may be useful only in workers
1181 return IamWorkerProcess() && IO->io->unlinkdUseful();
1182 }
1183
1184 void
1185 Fs::Ufs::UFSSwapDir::unlink(StoreEntry & e)
1186 {
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);
1191 --n_disk_objects;
1192 }
1193 replacementRemove(&e);
1194 mapBitReset(e.swap_filen);
1195 UFSSwapDir::unlinkFile(e.swap_filen);
1196 }
1197
1198 void
1199 Fs::Ufs::UFSSwapDir::replacementAdd(StoreEntry * e)
1200 {
1201 debugs(47, 4, HERE << "added node " << e << " to dir " << index);
1202 repl->Add(repl, e, &e->repl);
1203 }
1204
1205 void
1206 Fs::Ufs::UFSSwapDir::replacementRemove(StoreEntry * e)
1207 {
1208 StorePointer SD;
1209
1210 if (e->swap_dirn < 0)
1211 return;
1212
1213 SD = INDEXSD(e->swap_dirn);
1214
1215 assert (dynamic_cast<UFSSwapDir *>(SD.getRaw()) == this);
1216
1217 debugs(47, 4, HERE << "remove node " << e << " from dir " << index);
1218
1219 repl->Remove(repl, e, &e->repl);
1220 }
1221
1222 void
1223 Fs::Ufs::UFSSwapDir::dump(StoreEntry & entry) const
1224 {
1225 storeAppendPrintf(&entry, " %" PRIu64 " %d %d", maxSize() >> 20, l1, l2);
1226 dumpOptions(&entry);
1227 }
1228
1229 char *
1230 Fs::Ufs::UFSSwapDir::fullPath(sfileno filn, char *fullpath) const
1231 {
1232 LOCAL_ARRAY(char, fullfilename, MAXPATHLEN);
1233 int L1 = l1;
1234 int L2 = l2;
1235
1236 if (!fullpath)
1237 fullpath = fullfilename;
1238
1239 fullpath[0] = '\0';
1240
1241 snprintf(fullpath, MAXPATHLEN, "%s/%02X/%02X/%08X",
1242 path,
1243 ((filn / L2) / L2) % L1,
1244 (filn / L2) % L2,
1245 filn);
1246
1247 return fullpath;
1248 }
1249
1250 int
1251 Fs::Ufs::UFSSwapDir::callback()
1252 {
1253 return IO->callback();
1254 }
1255
1256 void
1257 Fs::Ufs::UFSSwapDir::sync()
1258 {
1259 IO->sync();
1260 }
1261
1262 void
1263 Fs::Ufs::UFSSwapDir::swappedOut(const StoreEntry &e)
1264 {
1265 cur_size += fs.blksize * sizeInBlocks(e.swap_file_sz);
1266 ++n_disk_objects;
1267 }
1268
1269 StoreSearch *
1270 Fs::Ufs::UFSSwapDir::search(String const url, HttpRequest *)
1271 {
1272 if (url.size())
1273 fatal ("Cannot search by url yet\n");
1274
1275 return new Fs::Ufs::StoreSearchUFS (this);
1276 }
1277
1278 void
1279 Fs::Ufs::UFSSwapDir::logEntry(const StoreEntry & e, int op) const
1280 {
1281 StoreSwapLogData *s = new StoreSwapLogData;
1282 s->op = (char) op;
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;
1290 s->flags = e.flags;
1291 memcpy(s->key, e.key, SQUID_MD5_DIGEST_LENGTH);
1292 s->finalize();
1293 file_write(swaplog_fd,
1294 -1,
1295 s,
1296 sizeof(StoreSwapLogData),
1297 NULL,
1298 NULL,
1299 FreeObject);
1300 }
1301
1302 int
1303 Fs::Ufs::UFSSwapDir::DirClean(int swap_index)
1304 {
1305 DIR *dir_pointer = NULL;
1306
1307 LOCAL_ARRAY(char, p1, MAXPATHLEN + 1);
1308 LOCAL_ARRAY(char, p2, MAXPATHLEN + 1);
1309
1310 int files[20];
1311 int swapfileno;
1312 int fn; /* same as swapfileno, but with dirn bits set */
1313 int n = 0;
1314 int k = 0;
1315 int N0, N1, N2;
1316 int D0, D1, D2;
1317 UFSSwapDir *SD;
1318 N0 = NumberOfUFSDirs;
1319 D0 = UFSDirToGlobalDirMapping[swap_index % N0];
1320 SD = dynamic_cast<UFSSwapDir *>(INDEXSD(D0));
1321 assert (SD);
1322 N1 = SD->l1;
1323 D1 = (swap_index / N0) % N1;
1324 N2 = SD->l2;
1325 D2 = ((swap_index / N0) / N1) % N2;
1326 snprintf(p1, MAXPATHLEN, "%s/%02X/%02X",
1327 SD->path, D1, D2);
1328 debugs(36, 3, HERE << "Cleaning directory " << p1);
1329 dir_pointer = opendir(p1);
1330
1331 if (dir_pointer == NULL) {
1332 if (errno == ENOENT) {
1333 debugs(36, DBG_CRITICAL, HERE << "WARNING: Creating " << p1);
1334 if (mkdir(p1, 0777) == 0)
1335 return 0;
1336 }
1337
1338 debugs(50, DBG_CRITICAL, HERE << p1 << ": " << xstrerror());
1339 safeunlink(p1, 1);
1340 return 0;
1341 }
1342
1343 dirent_t *de;
1344 while ((de = readdir(dir_pointer)) != NULL && k < 20) {
1345 if (sscanf(de->d_name, "%X", &swapfileno) != 1)
1346 continue;
1347
1348 fn = swapfileno; /* XXX should remove this cruft ! */
1349
1350 if (SD->validFileno(fn, 1))
1351 if (SD->mapBitTest(fn))
1352 if (UFSSwapDir::FilenoBelongsHere(fn, D0, D1, D2))
1353 continue;
1354
1355 files[k] = swapfileno;
1356 ++k;
1357 }
1358
1359 closedir(dir_pointer);
1360
1361 if (k == 0)
1362 return 0;
1363
1364 qsort(files, k, sizeof(int), rev_int_sort);
1365
1366 if (k > 10)
1367 k = 10;
1368
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]);
1372 safeunlink(p2, 0);
1373 ++statCounter.swap.files_cleaned;
1374 }
1375
1376 debugs(36, 3, HERE << "Cleaned " << k << " unused files from " << p1);
1377 return k;
1378 }
1379