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.
12 #include "base/Packable.h"
13 #include "base/RefCount.h"
14 #include "comm/forward.h"
17 #include "http/forward.h"
18 #include "http/RequestMethod.h"
19 #include "HttpReply.h"
20 #include "MemObject.h"
22 #include "RemovalPolicy.h"
23 #include "store_key_md5.h"
24 #include "StoreIOBuffer.h"
25 #include "StoreStats.h"
28 #include "esi/Element.h"
40 extern StoreIoStats store_io_stats
;
42 /// maximum number of entries per cache_dir
43 enum { SwapFilenMax
= 0xFFFFFF }; // keep in sync with StoreEntry::swap_filen
45 class StoreEntry
: public hash_link
, public Packable
49 static DeferredRead::DeferrableRead DeferReader
;
50 bool checkDeferRead(int fd
) const;
52 virtual const char *getMD5Text() const;
54 virtual ~StoreEntry();
56 virtual HttpReply
const *getReply() const;
57 virtual void write (StoreIOBuffer
);
59 /** Check if the Store entry is emtpty
60 * \retval true Store contains 0 bytes of data.
61 * \retval false Store contains 1 or more bytes of data.
62 * \retval false Store contains negative content !!!!!!
64 virtual bool isEmpty() const {
66 return mem_obj
->endOffset() == 0;
68 virtual bool isAccepting() const;
69 virtual size_t bytesWanted(Range
<size_t> const aRange
, bool ignoreDelayPool
= false) const;
70 /// flags [truncated or too big] entry with ENTRY_BAD_LENGTH and releases it
71 void lengthWentBad(const char *reason
);
72 virtual void complete();
73 virtual store_client_t
storeClientType() const;
74 virtual char const *getSerialisedMetaData();
75 /// Store a prepared error response. MemObject locks the reply object.
76 void storeErrorResponse(HttpReply
*reply
);
77 void replaceHttpReply(HttpReply
*, bool andStartWriting
= true);
78 void startWriting(); ///< pack and write reply headers and, maybe, body
79 /// whether we may start writing to disk (now or in the future)
80 virtual bool mayStartSwapOut();
81 virtual void trimMemory(const bool preserveSwappable
);
83 // called when a decision to cache in memory has been made
84 void memOutDecision(const bool willCacheInRam
);
85 // called when a decision to cache on disk has been made
86 void swapOutDecision(const MemObject::SwapOut::Decision
&decision
);
95 void releaseRequest();
97 void cacheNegatively(); /** \todo argh, why both? */
98 void invokeHandlers();
100 void cacheInMemory(); ///< start or continue storing in memory cache
102 /// whether we are in the process of writing this entry to disk
103 bool swappingOut() const { return swap_status
== SWAPOUT_WRITING
; }
104 void swapOutFileClose(int how
);
105 const char *url() const;
106 /// Satisfies cachability requirements shared among disk and RAM caches.
107 /// Encapsulates common checks of mayStartSwapOut() and memoryCachable().
108 /// TODO: Rename and make private so only those two methods can call this.
109 bool checkCachable();
110 int checkNegativeHit() const;
112 int validToSend() const;
113 bool memoryCachable(); ///< checkCachable() and can be cached in memory
115 /// if needed, initialize mem_obj member w/o URI-related information
116 MemObject
*makeMemObject();
118 /// initialize mem_obj member (if needed) and supply URI-related info
119 void createMemObject(const char *storeId
, const char *logUri
, const HttpRequestMethod
&aMethod
);
121 void dump(int debug_lvl
) const;
123 void hashInsert(const cache_key
*);
124 void registerAbort(STABH
* cb
, void *);
126 void setMemStatus(mem_status_t
);
127 void timestampsSet();
128 void unregisterAbort();
129 void destroyMemObject();
132 void delayAwareRead(const Comm::ConnectionPointer
&conn
, char *buf
, int len
, AsyncCall::Pointer callback
);
134 void setNoDelay (bool const);
135 bool modifiedSince(HttpRequest
* request
) const;
136 /// has ETag matching at least one of the If-Match etags
137 bool hasIfMatchEtag(const HttpRequest
&request
) const;
138 /// has ETag matching at least one of the If-None-Match etags
139 bool hasIfNoneMatchEtag(const HttpRequest
&request
) const;
140 /// whether this entry has an ETag; if yes, puts ETag value into parameter
141 bool hasEtag(ETag
&etag
) const;
143 /** What store does this entry belong too ? */
144 virtual RefCount
<SwapDir
> store() const;
147 RemovalPolicyNode repl
;
148 /* START OF ON-DISK STORE_META_STD TLV field */
153 uint64_t swap_file_sz
;
156 /* END OF ON-DISK STORE_META_STD */
158 /// unique ID inside a cache_dir for swapped out entries; -1 for others
159 sfileno swap_filen
:25; // keep in sync with SwapFilenMax
163 mem_status_t mem_status
:3;
165 ping_status_t ping_status
:3;
167 store_status_t store_status
:3;
169 swap_status_t swap_status
:3;
172 static size_t inUseCount();
173 static void getPublicByRequestMethod(StoreClient
* aClient
, HttpRequest
* request
, const HttpRequestMethod
& method
);
174 static void getPublicByRequest(StoreClient
* aClient
, HttpRequest
* request
);
175 static void getPublic(StoreClient
* aClient
, const char *uri
, const HttpRequestMethod
& method
);
177 virtual bool isNull() {
181 void *operator new(size_t byteCount
);
182 void operator delete(void *address
);
183 void setReleaseFlag();
186 ESIElement::Pointer cachedESITree
;
188 /** disable sending content to the clients */
189 virtual void buffer();
190 /** flush any buffered content */
191 virtual void flush();
192 virtual int64_t objectLen() const;
193 virtual int64_t contentLen() const;
195 /// claim shared ownership of this entry (for use in a given context)
196 /// matching lock() and unlock() contexts eases leak triage but is optional
197 void lock(const char *context
);
199 /// disclaim shared ownership; may remove entry from store and delete it
200 /// returns remaning lock level (zero for unlocked and possibly gone entry)
201 int unlock(const char *context
);
203 /// returns a local concurrent use counter, for debugging
204 int locks() const { return static_cast<int>(lock_count
); }
206 /// update last reference timestamp and related Store metadata
209 virtual void release();
212 /// call back producer when more buffer space is available
213 void deferProducer(const AsyncCall::Pointer
&producer
);
214 /// calls back producer registered with deferProducer
219 virtual void append(char const *, int);
220 virtual void vappendf(const char *, va_list);
223 void transientsAbandonmentCheck();
226 bool checkTooBig() const;
228 static MemAllocator
*pool
;
230 unsigned short lock_count
; /* Assume < 65536! */
233 /// producer callback registered with deferProducer
234 AsyncCall::Pointer deferredProducer
;
237 bool validLength() const;
238 bool hasOneOfEtags(const String
&reqETags
, const bool allowWeakMatch
) const;
241 std::ostream
&operator <<(std::ostream
&os
, const StoreEntry
&e
);
243 /// \ingroup StoreAPI
244 class NullStoreEntry
:public StoreEntry
248 static NullStoreEntry
*getInstance();
253 const char *getMD5Text() const;
254 HttpReply
const *getReply() const { return NULL
; }
255 void write (StoreIOBuffer
) {}
257 bool isEmpty () const {return true;}
259 virtual size_t bytesWanted(Range
<size_t> const aRange
, bool) const { return aRange
.end
; }
261 void operator delete(void *address
);
265 store_client_t
storeClientType() const {return STORE_MEM_CLIENT
;}
267 char const *getSerialisedMetaData();
268 virtual bool mayStartSwapOut() { return false; }
270 void trimMemory(const bool) {}
272 static NullStoreEntry _instance
;
275 /// \ingroup StoreAPI
276 typedef void (*STOREGETCLIENT
) (StoreEntry
*, void *cbdata
);
280 * Abstract base class that will replace the whole store and swapdir interface.
282 class Store
: public RefCountable
286 /** The root store */
287 static Store
&Root() {
288 if (CurrentRoot
== NULL
)
289 fatal("No Store Root has been set");
292 static void Root(Store
*);
293 static void Root(RefCount
<Store
>);
294 static void Stats(StoreEntry
* output
);
295 static void Maintain(void *unused
);
299 /** Handle pending callbacks - called by the event loop. */
300 virtual int callback() = 0;
302 /** create the resources needed for this store to operate */
303 virtual void create();
306 * Notify this store that its disk is full.
307 \todo XXX move into a protected api call between store files and their stores, rather than a top level api call
309 virtual void diskFull();
311 /** Retrieve a store entry from the store */
312 virtual StoreEntry
* get(const cache_key
*) = 0;
314 /** \todo imeplement the async version */
315 virtual void get(String
const key
, STOREGETCLIENT callback
, void *cbdata
) = 0;
317 /* prepare the store for use. The store need not be usable immediately,
318 * it should respond to readable() and writable() with true as soon
319 * as it can provide those services
321 virtual void init() = 0;
324 * The maximum size the store will support in normal use. Inaccuracy is permitted,
325 * but may throw estimates for memory etc out of whack.
327 virtual uint64_t maxSize() const = 0;
329 /** The minimum size the store will shrink to via normal housekeeping */
330 virtual uint64_t minSize() const = 0;
332 /** current store size */
333 virtual uint64_t currentSize() const = 0;
335 /** the total number of objects stored */
336 virtual uint64_t currentCount() const = 0;
338 /** the maximum object size that can be stored, -1 if unlimited */
339 virtual int64_t maxObjectSize() const = 0;
341 /// collect cache storage-related statistics
342 virtual void getStats(StoreInfoStats
&stats
) const = 0;
345 * Output stats to the provided store entry.
346 \todo make these calls asynchronous
348 virtual void stat(StoreEntry
&) const = 0;
350 /** Sync the store prior to shutdown */
353 /** remove a Store entry from the store */
354 virtual void unlink (StoreEntry
&);
356 /* search in the store */
357 virtual StoreSearch
*search(String
const url
, HttpRequest
*) = 0;
359 /* pulled up from SwapDir for migration.... probably do not belong here */
360 virtual void reference(StoreEntry
&) = 0; /* Reference this object */
362 /// Undo reference(), returning false iff idle e should be destroyed
363 virtual bool dereference(StoreEntry
&, bool wantsLocalMemory
) = 0;
365 virtual void maintain() = 0; /* perform regular maintenance should be private and self registered ... */
367 // XXX: This method belongs to Store::Root/StoreController, but it is here
368 // to avoid casting Root() to StoreController until Root() API is fixed.
369 /// informs stores that this entry will be eventually unlinked
370 virtual void markForUnlink(StoreEntry
&) {}
372 // XXX: This method belongs to Store::Root/StoreController, but it is here
373 // because test cases use non-StoreController derivatives as Root
374 /// called when the entry is no longer needed by any transaction
375 virtual void handleIdleEntry(StoreEntry
&) {}
377 // XXX: This method belongs to Store::Root/StoreController, but it is here
378 // because test cases use non-StoreController derivatives as Root
379 /// called to get rid of no longer needed entry data in RAM, if any
380 virtual void memoryOut(StoreEntry
&, const bool /*preserveSwappable*/) {}
382 // XXX: This method belongs to Store::Root/StoreController, but it is here
383 // to avoid casting Root() to StoreController until Root() API is fixed.
384 /// makes the entry available for collapsing future requests
385 virtual void allowCollapsing(StoreEntry
*, const RequestFlags
&, const HttpRequestMethod
&) {}
387 // XXX: This method belongs to Store::Root/StoreController, but it is here
388 // to avoid casting Root() to StoreController until Root() API is fixed.
389 /// marks the entry completed for collapsed requests
390 virtual void transientsCompleteWriting(StoreEntry
&) {}
392 // XXX: This method belongs to Store::Root/StoreController, but it is here
393 // to avoid casting Root() to StoreController until Root() API is fixed.
394 /// Update local intransit entry after changes made by appending worker.
395 virtual void syncCollapsed(const sfileno
) {}
397 // XXX: This method belongs to Store::Root/StoreController, but it is here
398 // to avoid casting Root() to StoreController until Root() API is fixed.
399 /// calls Root().transients->abandon() if transients are tracked
400 virtual void transientsAbandon(StoreEntry
&) {}
402 // XXX: This method belongs to Store::Root/StoreController, but it is here
403 // to avoid casting Root() to StoreController until Root() API is fixed.
404 /// number of the transient entry readers some time ago
405 virtual int transientReaders(const StoreEntry
&) const { return 0; }
407 // XXX: This method belongs to Store::Root/StoreController, but it is here
408 // to avoid casting Root() to StoreController until Root() API is fixed.
409 /// disassociates the entry from the intransit table
410 virtual void transientsDisconnect(MemObject
&) {}
412 // XXX: This method belongs to Store::Root/StoreController, but it is here
413 // to avoid casting Root() to StoreController until Root() API is fixed.
414 /// removes the entry from the memory cache
415 virtual void memoryUnlink(StoreEntry
&) {}
417 // XXX: This method belongs to Store::Root/StoreController, but it is here
418 // to avoid casting Root() to StoreController until Root() API is fixed.
419 /// disassociates the entry from the memory cache, preserving cached data
420 virtual void memoryDisconnect(StoreEntry
&) {}
422 /// If the entry is not found, return false. Otherwise, return true after
423 /// tying the entry to this cache and setting inSync to updateCollapsed().
424 virtual bool anchorCollapsed(StoreEntry
&, bool &/*inSync*/) { return false; }
426 /// update a local collapsed entry with fresh info from this cache (if any)
427 virtual bool updateCollapsed(StoreEntry
&) { return false; }
430 static RefCount
<Store
> CurrentRoot
;
433 /// \ingroup StoreAPI
434 typedef RefCount
<Store
> StorePointer
;
436 /// \ingroup StoreAPI
437 size_t storeEntryInUse();
439 /// \ingroup StoreAPI
440 const char *storeEntryFlags(const StoreEntry
*);
442 /// \ingroup StoreAPI
443 void storeEntryReplaceObject(StoreEntry
*, HttpReply
*);
445 /// \ingroup StoreAPI
446 StoreEntry
*storeGetPublic(const char *uri
, const HttpRequestMethod
& method
);
448 /// \ingroup StoreAPI
449 StoreEntry
*storeGetPublicByRequest(HttpRequest
* request
);
451 /// \ingroup StoreAPI
452 StoreEntry
*storeGetPublicByRequestMethod(HttpRequest
* request
, const HttpRequestMethod
& method
);
454 /// \ingroup StoreAPI
455 /// Like storeCreatePureEntry(), but also locks the entry and sets entry key.
456 StoreEntry
*storeCreateEntry(const char *, const char *, const RequestFlags
&, const HttpRequestMethod
&);
458 /// \ingroup StoreAPI
459 /// Creates a new StoreEntry with mem_obj and sets initial flags/states.
460 StoreEntry
*storeCreatePureEntry(const char *storeId
, const char *logUrl
, const RequestFlags
&, const HttpRequestMethod
&);
462 /// \ingroup StoreAPI
463 void storeInit(void);
465 /// \ingroup StoreAPI
466 void storeConfigure(void);
468 /// \ingroup StoreAPI
469 void storeFreeMemory(void);
471 /// \ingroup StoreAPI
472 int expiresMoreThan(time_t, time_t);
474 /// \ingroup StoreAPI
475 void storeAppendPrintf(StoreEntry
*, const char *,...) PRINTF_FORMAT_ARG2
;
477 /// \ingroup StoreAPI
478 void storeAppendVPrintf(StoreEntry
*, const char *, va_list ap
);
480 /// \ingroup StoreAPI
481 int storeTooManyDiskFilesOpen(void);
484 /// \ingroup StoreAPI
485 void storeHeapPositionUpdate(StoreEntry
*, SwapDir
*);
487 /// \ingroup StoreAPI
488 void storeSwapFileNumberSet(StoreEntry
* e
, sfileno filn
);
490 /// \ingroup StoreAPI
491 void storeFsInit(void);
493 /// \ingroup StoreAPI
494 void storeFsDone(void);
496 /// \ingroup StoreAPI
497 void storeReplAdd(const char *, REMOVALPOLICYCREATE
*);
499 /// \ingroup StoreAPI
500 extern FREE destroyStoreEntry
;
502 /// \ingroup StoreAPI
503 void storeGetMemSpace(int size
);
505 #endif /* SQUID_STORE_H */