Store.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2023 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 #ifndef SQUID_SRC_STORE_H
10 #define SQUID_SRC_STORE_H
11 
12 #include "base/DelayedAsyncCalls.h"
13 #include "base/Packable.h"
14 #include "base/Range.h"
15 #include "base/RefCount.h"
16 #include "comm/forward.h"
17 #include "hash.h"
18 #include "http/forward.h"
19 #include "http/RequestMethod.h"
20 #include "HttpReply.h"
21 #include "MemObject.h"
22 #include "RemovalPolicy.h"
23 #include "store/Controller.h"
24 #include "store/forward.h"
25 #include "store_key_md5.h"
26 #include "StoreIOBuffer.h"
27 #include "StoreStats.h"
28 
29 #include <ostream>
30 
31 class AsyncCall;
32 class HttpRequest;
33 class RequestFlags;
34 
36 
37 class StoreEntry : public hash_link, public Packable
38 {
39 
40 public:
41  bool checkDeferRead(int fd) const;
42 
43  const char *getMD5Text() const;
44  StoreEntry();
45  ~StoreEntry() override;
46 
47  MemObject &mem() { assert(mem_obj); return *mem_obj; }
48  const MemObject &mem() const { assert(mem_obj); return *mem_obj; }
49 
53  const HttpReply *hasFreshestReply() const { return mem_obj ? &mem_obj->freshestReply() : nullptr; }
54 
56  bool hasParsedReplyHeader() const;
57 
58  void write(StoreIOBuffer);
59 
65  bool isEmpty() const { return mem().endOffset() == 0; }
66  bool isAccepting() const;
67  size_t bytesWanted(Range<size_t> const aRange, bool ignoreDelayPool = false) const;
68 
71  void completeSuccessfully(const char *whyWeAreSureWeStoredTheWholeReply);
72 
75  void completeTruncated(const char *whyWeConsiderTheReplyTruncated);
76 
78  void complete();
79 
82  const char *getSerialisedMetaData(size_t &length) const;
84  void storeErrorResponse(HttpReply *reply);
85  void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting = true);
86  void startWriting();
87  bool mayStartSwapOut();
89  void trimMemory(const bool preserveSwappable);
90 
91  // called when a decision to cache in memory has been made
92  void memOutDecision(const bool willCacheInRam);
93  // called when a decision to cache on disk has been made
94  void swapOutDecision(const MemObject::SwapOut::Decision &decision);
96  void storeWriterDone();
97 
98  void abort();
99  bool makePublic(const KeyScope keyScope = ksDefault);
100  void makePrivate(const bool shareable);
104  void clearPrivate();
105  bool setPublicKey(const KeyScope keyScope = ksDefault);
109  void clearPublicKeyScope();
110 
112  const cache_key *publicKey() const {
113  return (!EBIT_TEST(flags, KEY_PRIVATE)) ?
114  reinterpret_cast<const cache_key*>(key): // may be nil
115  nullptr;
116  }
117 
121  void setPrivateKey(const bool shareable, const bool permanent);
122 
123  void expireNow();
126  void releaseRequest(const bool shareable = false);
127  void negativeCache();
128  bool cacheNegatively(); // TODO: why both negativeCache() and cacheNegatively() ?
129  void invokeHandlers();
130  void cacheInMemory();
131  void swapOut();
133  bool swappingOut() const { return swap_status == SWAPOUT_WRITING; }
135  bool swappedOut() const { return swap_status == SWAPOUT_DONE; }
137  bool swapoutFailed() const { return swap_status == SWAPOUT_FAILED; }
138  void swapOutFileClose(int how);
139  const char *url() const;
143  bool checkCachable();
144  int checkNegativeHit() const;
145  int locked() const { return lock_count; }
146  int validToSend() const;
147  bool memoryCachable();
148 
151  void createMemObject();
152 
154  void createMemObject(const char *storeId, const char *logUri, const HttpRequestMethod &aMethod);
155 
157  void ensureMemObject(const char *storeId, const char *logUri, const HttpRequestMethod &aMethod);
158 
159  void dump(int debug_lvl) const;
160  void hashDelete();
161  void hashInsert(const cache_key *);
164  void reset();
166  bool timestampsSet();
170  void unregisterAbortCallback(const char *reason);
171  void destroyMemObject();
172  int checkTooSmall();
173 
174  void setNoDelay (bool const);
175  void lastModified(const time_t when) { lastModified_ = when; }
177  time_t lastModified() const {
178  // may still return -1 if timestamp is not set
179  return lastModified_ < 0 ? timestamp : lastModified_;
180  }
182  const char *describeTimestamps() const;
183  // TODO: consider removing currently unsupported imslen parameter
184  bool modifiedSince(const time_t ims, const int imslen = -1) const;
186  bool hasIfMatchEtag(const HttpRequest &request) const;
188  bool hasIfNoneMatchEtag(const HttpRequest &request) const;
190  bool hasEtag(ETag &etag) const;
191 
195  bool updateOnNotModified(const StoreEntry &e304);
196 
198  Store::Disk &disk() const;
201  bool hasDisk(const sdirno dirn = -1, const sfileno filen = -1) const;
204  void attachToDisk(const sdirno, const sfileno, const swap_status_t);
207  void detachFromDisk();
208 
210  bool hasTransients() const { return mem_obj && mem_obj->xitTable.index >= 0; }
212  bool hasMemStore() const { return mem_obj && mem_obj->memCache.index >= 0; }
213 
216 
218  void setCollapsingRequirement(const bool required);
219 
222  /* START OF ON-DISK STORE_META_STD TLV field */
223  time_t timestamp;
224  time_t lastref;
225  time_t expires;
226 private:
227  time_t lastModified_;
228 public:
229  uint64_t swap_file_sz;
230  uint16_t refcount;
231  uint16_t flags;
232  /* END OF ON-DISK STORE_META_STD */
233 
235  sfileno swap_filen:25; // keep in sync with SwapFilenMax
236 
238 
240 
242 
244 
246 
247 public:
248  static size_t inUseCount();
249 
250  void *operator new(size_t byteCount);
251  void operator delete(void *address);
252 
253  int64_t objectLen() const { return mem().object_sz; }
254  int64_t contentLen() const { return objectLen() - mem().baseReply().hdr_sz; }
255 
258  void lock(const char *context);
259 
262  int unlock(const char *context);
263 
265  int locks() const { return static_cast<int>(lock_count); }
266 
268  void touch();
269 
274  void release(const bool shareable = false);
275 
280  void abandon(const char *context) { if (!locked()) doAbandon(context); }
281 
284  bool mayStartHitting() const {
286  }
287 
288 #if USE_ADAPTATION
289  void deferProducer(const AsyncCall::Pointer &producer);
292  void kickProducer();
293 #endif
294 
295  /* Packable API */
296  void append(char const *, int) override;
297  void vappendf(const char *, va_list) override;
298  void buffer() override;
299  void flush() override;
300 
301 protected:
303 
304  void storeWritingCheckpoint();
306  void checkDisk() const;
307 
308 private:
309  void doAbandon(const char *context);
310  bool checkTooBig() const;
311  void forcePublicKey(const cache_key *newkey);
313  const cache_key *calcPublicKey(const KeyScope keyScope);
314 
316  void lengthWentBad(const char *reason);
317 
319 
320  unsigned short lock_count; /* Assume < 65536! */
321 
328 
329 #if USE_ADAPTATION
332 #endif
333 
334  bool validLength() const;
335  bool hasOneOfEtags(const String &reqETags, const bool allowWeakMatch) const;
336 
337  friend std::ostream &operator <<(std::ostream &os, const StoreEntry &e);
338 };
339 
340 std::ostream &operator <<(std::ostream &os, const StoreEntry &e);
341 
343 typedef void (*STOREGETCLIENT) (StoreEntry *, void *cbdata);
344 
345 namespace Store {
346 
349 class EntryGuard {
350 public:
353  EntryGuard(Entry *entry, const char *context):
354  entry_(entry), context_(context) {
355  assert(!entry_ || entry_->locked());
356  }
357 
359  if (entry_) {
360  // something went wrong -- the caller did not unlockAndReset() us
361  onException();
362  }
363  }
364 
365  EntryGuard(EntryGuard &&) = delete; // no copying or moving (for now)
366 
369  Entry *get() {
370  return entry_;
371  }
372 
376  void unlockAndReset(const char *resetContext = nullptr) {
377  if (entry_) {
378  entry_->unlock(resetContext ? resetContext : context_);
379  entry_ = nullptr;
380  }
381  }
382 
383 private:
384  void onException() noexcept;
385 
387  const char *context_;
388 };
389 
390 void Stats(StoreEntry *output);
391 void Maintain(void *unused);
392 }; // namespace Store
393 
395 size_t storeEntryInUse();
396 
398 const char *storeEntryFlags(const StoreEntry *);
399 
402 
404 StoreEntry *storeGetPublic(const char *uri, const HttpRequestMethod& method);
405 
407 StoreEntry *storeGetPublicByRequest(HttpRequest * request, const KeyScope keyScope = ksDefault);
408 
410 StoreEntry *storeGetPublicByRequestMethod(HttpRequest * request, const HttpRequestMethod& method, const KeyScope keyScope = ksDefault);
411 
414 StoreEntry *storeCreateEntry(const char *, const char *, const RequestFlags &, const HttpRequestMethod&);
415 
418 StoreEntry *storeCreatePureEntry(const char *storeId, const char *logUrl, const HttpRequestMethod&);
419 
421 void storeInit(void);
422 
424 void storeConfigure(void);
425 
427 int expiresMoreThan(time_t, time_t);
428 
430 void storeAppendPrintf(StoreEntry *, const char *,...) PRINTF_FORMAT_ARG2;
431 
433 void storeAppendVPrintf(StoreEntry *, const char *, va_list ap);
434 
436 int storeTooManyDiskFilesOpen(void);
437 
440 
443 
445 void storeFsInit(void);
446 
448 void storeFsDone(void);
449 
451 void storeReplAdd(const char *, REMOVALPOLICYCREATE *);
452 
457 extern FREE destroyStoreEntry;
458 
460 void storeGetMemSpace(int size);
461 
462 #endif /* SQUID_SRC_STORE_H */
463 
int hdr_sz
Definition: Message.h:81
void makePrivate(const bool shareable)
Definition: store.cc:174
void Maintain(void *unused)
Definition: store.cc:1132
StoreEntry * storeGetPublicByRequest(HttpRequest *request, const KeyScope keyScope=ksDefault)
Definition: store.cc:516
static Mem::Allocator * pool
Definition: Store.h:318
void abandon(const char *context)
Definition: Store.h:280
int checkTooSmall()
Definition: store.cc:901
time_t timestamp
Definition: Store.h:223
Definition: ETag.h:17
store_client_t storeClientType() const
Definition: store.cc:264
bool validLength() const
Definition: store.cc:1204
bool updateOnNotModified(const StoreEntry &e304)
Definition: store.cc:1452
void ensureMemObject(const char *storeId, const char *logUri, const HttpRequestMethod &aMethod)
initialize mem_obj (if needed) and set URIs/method (if missing)
Definition: store.cc:1589
void unregisterAbortCallback(const char *reason)
Definition: store.cc:1489
void releaseRequest(const bool shareable=false)
Definition: store.cc:458
StoreEntry * adjustVary()
Definition: store.cc:665
void storeGetMemSpace(int size)
Definition: store.cc:1121
const cache_key * publicKey() const
Definition: Store.h:112
void checkDisk() const
does nothing except throwing if disk-associated data members are inconsistent
Definition: store.cc:1961
void FREE(void *)
Definition: forward.h:37
manages a single cache_dir
Definition: Disk.h:21
unsigned char cache_key
Store key.
Definition: forward.h:29
bool makePublic(const KeyScope keyScope=ksDefault)
Definition: store.cc:167
StoreEntry()
Definition: store.cc:338
MemObject * mem_obj
Definition: Store.h:220
~StoreEntry() override
Definition: store.cc:359
void clearPublicKeyScope()
Definition: store.cc:609
const char * url() const
Definition: store.cc:1566
size_t storeEntryInUse()
void storeInit(void)
Definition: store.cc:1257
void append(char const *, int) override
Appends a c-string to existing packed data.
Definition: store.cc:803
void createMemObject()
Definition: store.cc:1575
MemObject & mem()
Definition: Store.h:47
bool shareableWhenPrivate
Definition: Store.h:327
void lock(const char *context)
Definition: store.cc:445
@ KEY_PRIVATE
Definition: enums.h:97
MemCache memCache
current [shared] memory caching state for the entry
Definition: MemObject.h:203
void detachFromDisk()
Definition: store.cc:1953
void onException() noexcept
Definition: store.cc:2100
void touch()
update last reference timestamp and related Store metadata
Definition: store.cc:452
void setPrivateKey(const bool shareable, const bool permanent)
Definition: store.cc:548
bool setPublicKey(const KeyScope keyScope=ksDefault)
Definition: store.cc:575
Entry * entry_
the guarded Entry or nil
Definition: Store.h:386
Definition: cbdata.cc:37
void storeAppendVPrintf(StoreEntry *, const char *, va_list ap)
Definition: store.cc:865
@ SWAPOUT_WRITING
Definition: enums.h:56
time_t lastModified_
received Last-Modified value or -1; use lastModified()
Definition: Store.h:227
uint16_t flags
Definition: Store.h:231
int locks() const
returns a local concurrent use counter, for debugging
Definition: Store.h:265
void storeReplAdd(const char *, REMOVALPOLICYCREATE *)
Definition: store.cc:1645
bool isAccepting() const
Definition: store.cc:1988
time_t expires
Definition: Store.h:225
int64_t endOffset() const
Definition: MemObject.cc:214
int64_t objectLen() const
Definition: Store.h:253
@ SWAPOUT_DONE
Definition: enums.h:59
void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting=true)
Definition: store.cc:1705
swap_status_t
StoreEntry relationship with a disk cache.
Definition: enums.h:50
Store::EntryGuard EntryGuard
Definition: Store.h:302
void startWriting()
Definition: store.cc:1721
void storeSwapFileNumberSet(StoreEntry *e, sfileno filn)
static const char * storeId(const int i)
Definition: testRock.cc:155
void reset()
Definition: store.cc:1621
std::ostream & operator<<(std::ostream &os, const StoreEntry &e)
Definition: store.cc:2044
bool mayStartSwapOut()
whether we may start writing to disk (now or in the future)
void destroyMemObject()
Definition: store.cc:386
StoreIoStats store_io_stats
Definition: store_io.cc:16
#define PRINTF_FORMAT_ARG2
void doAbandon(const char *context)
Definition: store.cc:486
void invokeHandlers()
void storeConfigure(void)
Definition: store.cc:1270
const char * getSerialisedMetaData(size_t &length) const
Definition: store.cc:1750
StoreEntry * storeGetPublicByRequestMethod(HttpRequest *request, const HttpRequestMethod &method, const KeyScope keyScope=ksDefault)
Definition: store.cc:510
Definition: Range.h:18
enum _mem_status_t mem_status_t
int validToSend() const
Definition: store.cc:1347
int size
Definition: ModDevPoll.cc:69
void memOutDecision(const bool willCacheInRam)
Definition: store.cc:1791
store_status_t
Definition: enums.h:44
bool mayStartHitting() const
Definition: Store.h:284
bool hasIfNoneMatchEtag(const HttpRequest &request) const
has ETag matching at least one of the If-None-Match etags
Definition: store.cc:1880
const HttpReply & baseReply() const
Definition: MemObject.h:60
const char * storeEntryFlags(const StoreEntry *)
Definition: stat.cc:253
void abort()
Definition: store.cc:1077
store_client_t
Definition: enums.h:66
bool hasOneOfEtags(const String &reqETags, const bool allowWeakMatch) const
whether at least one of the request ETags matches entity ETag
Definition: store.cc:1891
uint16_t refcount
Definition: Store.h:230
bool hasDisk(const sdirno dirn=-1, const sfileno filen=-1) const
Definition: store.cc:1929
void storeAppendPrintf(StoreEntry *, const char *,...) PRINTF_FORMAT_ARG2
Definition: store.cc:855
friend std::ostream & operator<<(std::ostream &os, const StoreEntry &e)
Definition: store.cc:2044
sdirno swap_dirn
Definition: Store.h:237
#define EBIT_TEST(flag, bit)
Definition: defines.h:67
void setCollapsingRequirement(const bool required)
allow or forbid collapsed requests feeding
Definition: store.cc:2012
int64_t contentLen() const
Definition: Store.h:254
int32_t index
entry position inside the in-transit table
Definition: MemObject.h:189
ping_status_t ping_status
Definition: Store.h:241
bool hasMemStore() const
whether there is a corresponding locked shared memory table entry
Definition: Store.h:212
XitTable xitTable
current [shared] memory caching state for the entry
Definition: MemObject.h:192
int unlock(const char *context)
Definition: store.cc:469
void expireNow()
Definition: store.cc:773
static size_t inUseCount()
Definition: store.cc:199
store_status_t store_status
Definition: Store.h:243
StoreEntry * storeCreatePureEntry(const char *storeId, const char *logUrl, const HttpRequestMethod &)
Definition: store.cc:741
#define assert(EX)
Definition: assert.h:17
void Stats(StoreEntry *output)
Definition: store.cc:126
FREE destroyStoreEntry
void swapOutDecision(const MemObject::SwapOut::Decision &decision)
Definition: store.cc:1800
int checkNegativeHit() const
Definition: store.cc:1300
bool swapoutFailed() const
whether we failed to write this entry to disk
Definition: Store.h:137
void buffer() override
Definition: store.cc:1601
void write(StoreIOBuffer)
Definition: store.cc:780
bool checkCachable()
Definition: store.cc:929
void flush() override
Definition: store.cc:1612
bool cacheNegatively()
Definition: store.cc:188
mem_status_t mem_status
Definition: Store.h:239
Store statistics related to low-level I/O.
Definition: StoreStats.h:57
AsyncCall::Pointer deferredProducer
producer callback registered with deferProducer
Definition: Store.h:331
void unlockAndReset(const char *resetContext=nullptr)
Definition: Store.h:376
void dump(int debug_lvl) const
Definition: store.cc:1499
void storeHeapPositionUpdate(StoreEntry *, SwapDir *)
size_t bytesWanted(Range< size_t > const aRange, bool ignoreDelayPool=false) const
Definition: store.cc:213
void swapOut()
signed_int32_t sfileno
Definition: forward.h:22
int expiresMoreThan(time_t, time_t)
Definition: store.cc:1338
void completeSuccessfully(const char *whyWeAreSureWeStoredTheWholeReply)
Definition: store.cc:1017
StoreEntry * storeCreateEntry(const char *, const char *, const RequestFlags &, const HttpRequestMethod &)
Definition: store.cc:759
void setMemStatus(mem_status_t)
Definition: store.cc:1524
swap_status_t swap_status
Definition: Store.h:245
@ ksDefault
Definition: store_key_md5.h:19
void negativeCache()
Definition: store.cc:1321
void complete()
Definition: store.cc:1031
void cacheInMemory()
start or continue storing in memory cache
signed int sdirno
Definition: forward.h:23
EntryGuard(Entry *entry, const char *context)
Definition: Store.h:353
KeyScope
Definition: store_key_md5.h:18
void storeFsInit(void)
Definition: store.cc:1636
void storeWritingCheckpoint()
Definition: store.cc:1761
int32_t index
entry position inside the memory cache
Definition: MemObject.h:198
StoreEntry * storeGetPublic(const char *uri, const HttpRequestMethod &method)
Definition: store.cc:504
Decision
Decision states for StoreEntry::swapoutPossible() and related code.
Definition: MemObject.h:165
void kickProducer()
calls back producer registered with deferProducer
Definition: store.cc:376
bool checkDeferRead(int fd) const
Definition: store.cc:244
ping_status_t
Definition: enums.h:34
void swapOutFileClose(int how)
const cache_key * calcPublicKey(const KeyScope keyScope)
Definition: store.cc:652
bool timestampsSet()
Definition: store.cc:1387
void hashDelete()
Definition: store.cc:433
int64_t object_sz
Definition: MemObject.h:215
@ SWAPOUT_FAILED
Definition: enums.h:63
bool isEmpty() const
Definition: Store.h:65
const MemObject & mem() const
Definition: Store.h:48
uint64_t swap_file_sz
Definition: Store.h:229
void storeEntryReplaceObject(StoreEntry *, HttpReply *)
void storeFsDone(void)
bool hasTransients() const
whether there is a corresponding locked transients table entry
Definition: Store.h:210
void release(const bool shareable=false)
Definition: store.cc:1146
Store::Disk & disk() const
the disk this entry is [being] cached on; asserts for entries w/o a disk
Definition: store.cc:1920
const HttpReply & freshestReply() const
Definition: MemObject.h:68
void forcePublicKey(const cache_key *newkey)
Definition: store.cc:626
void hashInsert(const cache_key *)
Definition: store.cc:424
bool memoryCachable()
checkCachable() and can be cached in memory
Definition: store.cc:1276
bool checkTooBig() const
Definition: store.cc:918
int storeTooManyDiskFilesOpen(void)
Definition: store.cc:889
void attachToDisk(const sdirno, const sfileno, const swap_status_t)
Definition: store.cc:1940
void lastModified(const time_t when)
Definition: Store.h:175
@ ENTRY_REQUIRES_COLLAPSING
Definition: enums.h:113
void trimMemory(const bool preserveSwappable)
Definition: store.cc:1814
void setNoDelay(bool const)
Definition: store.cc:250
void deferProducer(const AsyncCall::Pointer &producer)
call back producer when more buffer space is available
Definition: store.cc:366
bool hittingRequiresCollapsing() const
whether this entry can feed collapsed requests and only them
Definition: Store.h:215
int locked() const
Definition: Store.h:145
RemovalPolicy * REMOVALPOLICYCREATE(wordlist *args)
Definition: RemovalPolicy.h:80
bool hasParsedReplyHeader() const
whether this entry has access to [deserialized] [HTTP] response headers
Definition: store.cc:231
void(* STOREGETCLIENT)(StoreEntry *, void *cbdata)
Definition: Store.h:343
void lengthWentBad(const char *reason)
flags [truncated or too big] entry with ENTRY_BAD_LENGTH and releases it
Definition: store.cc:1009
void registerAbortCallback(const AsyncCall::Pointer &)
notify the StoreEntry writer of a 3rd-party initiated StoreEntry abort
Definition: store.cc:1481
bool swappingOut() const
whether we are in the process of writing this entry to disk
Definition: Store.h:133
bool swappedOut() const
whether the entire entry is now on disk (possibly marked for deletion)
Definition: Store.h:135
bool modifiedSince(const time_t ims, const int imslen=-1) const
Definition: store.cc:1836
void storeWriterDone()
called when a store writer ends its work (successfully or not)
Definition: store.cc:1808
Entry * get()
Definition: Store.h:369
unsigned short lock_count
Definition: Store.h:320
bool hasIfMatchEtag(const HttpRequest &request) const
has ETag matching at least one of the If-Match etags
Definition: store.cc:1873
bool hasEtag(ETag &etag) const
whether this entry has an ETag; if yes, puts ETag value into parameter
Definition: store.cc:1862
void vappendf(const char *, va_list) override
Definition: store.cc:821
const char * context_
default unlock() message
Definition: Store.h:387
const HttpReply * hasFreshestReply() const
Definition: Store.h:53
const char * describeTimestamps() const
Definition: store.cc:2000
void clearPrivate()
Definition: store.cc:180
void completeTruncated(const char *whyWeConsiderTheReplyTruncated)
Definition: store.cc:1024
time_t lastref
Definition: Store.h:224
const char * getMD5Text() const
Definition: store.cc:207
void storeErrorResponse(HttpReply *reply)
Store a prepared error response. MemObject locks the reply object.
Definition: store.cc:1688
RemovalPolicyNode repl
Definition: Store.h:221
time_t lastModified() const
Definition: Store.h:177
sfileno swap_filen
unique ID inside a cache_dir for swapped out entries; -1 for others
Definition: Store.h:235

 

Introduction

Documentation

Support

Miscellaneous