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 "StoreIOBuffer.h"
24 #include "StoreStats.h"
27 #include "esi/Element.h"
39 extern StoreIoStats store_io_stats
;
41 /// maximum number of entries per cache_dir
42 enum { SwapFilenMax
= 0xFFFFFF }; // keep in sync with StoreEntry::swap_filen
44 class StoreEntry
: public hash_link
, public Packable
48 static DeferredRead::DeferrableRead DeferReader
;
49 bool checkDeferRead(int fd
) const;
51 virtual const char *getMD5Text() const;
53 virtual ~StoreEntry();
55 virtual HttpReply
const *getReply() const;
56 virtual void write (StoreIOBuffer
);
58 /** Check if the Store entry is emtpty
59 * \retval true Store contains 0 bytes of data.
60 * \retval false Store contains 1 or more bytes of data.
61 * \retval false Store contains negative content !!!!!!
63 virtual bool isEmpty() const {
65 return mem_obj
->endOffset() == 0;
67 virtual bool isAccepting() const;
68 virtual size_t bytesWanted(Range
<size_t> const aRange
, bool ignoreDelayPool
= false) const;
69 /// flags [truncated or too big] entry with ENTRY_BAD_LENGTH and releases it
70 void lengthWentBad(const char *reason
);
71 virtual void complete();
72 virtual store_client_t
storeClientType() const;
73 virtual char const *getSerialisedMetaData();
74 /// Store a prepared error response. MemObject locks the reply object.
75 void storeErrorResponse(HttpReply
*reply
);
76 void replaceHttpReply(HttpReply
*, bool andStartWriting
= true);
77 void startWriting(); ///< pack and write reply headers and, maybe, body
78 /// whether we may start writing to disk (now or in the future)
79 virtual bool mayStartSwapOut();
80 virtual void trimMemory(const bool preserveSwappable
);
82 // called when a decision to cache in memory has been made
83 void memOutDecision(const bool willCacheInRam
);
84 // called when a decision to cache on disk has been made
85 void swapOutDecision(const MemObject::SwapOut::Decision
&decision
);
94 void releaseRequest();
96 void cacheNegatively(); /** \todo argh, why both? */
97 void invokeHandlers();
99 void cacheInMemory(); ///< start or continue storing in memory cache
101 /// whether we are in the process of writing this entry to disk
102 bool swappingOut() const { return swap_status
== SWAPOUT_WRITING
; }
103 void swapOutFileClose(int how
);
104 const char *url() const;
105 /// Satisfies cachability requirements shared among disk and RAM caches.
106 /// Encapsulates common checks of mayStartSwapOut() and memoryCachable().
107 /// TODO: Rename and make private so only those two methods can call this.
108 bool checkCachable();
109 int checkNegativeHit() const;
111 int validToSend() const;
112 bool memoryCachable(); ///< checkCachable() and can be cached in memory
114 /// if needed, initialize mem_obj member w/o URI-related information
115 MemObject
*makeMemObject();
117 /// initialize mem_obj member (if needed) and supply URI-related info
118 void createMemObject(const char *storeId
, const char *logUri
, const HttpRequestMethod
&aMethod
);
120 void dump(int debug_lvl
) const;
122 void hashInsert(const cache_key
*);
123 void registerAbort(STABH
* cb
, void *);
125 void setMemStatus(mem_status_t
);
126 void timestampsSet();
127 void unregisterAbort();
128 void destroyMemObject();
131 void delayAwareRead(const Comm::ConnectionPointer
&conn
, char *buf
, int len
, AsyncCall::Pointer callback
);
133 void setNoDelay (bool const);
134 bool modifiedSince(HttpRequest
* request
) const;
135 /// has ETag matching at least one of the If-Match etags
136 bool hasIfMatchEtag(const HttpRequest
&request
) const;
137 /// has ETag matching at least one of the If-None-Match etags
138 bool hasIfNoneMatchEtag(const HttpRequest
&request
) const;
139 /// whether this entry has an ETag; if yes, puts ETag value into parameter
140 bool hasEtag(ETag
&etag
) const;
142 /** What store does this entry belong too ? */
143 virtual RefCount
<SwapDir
> store() const;
146 RemovalPolicyNode repl
;
147 /* START OF ON-DISK STORE_META_STD TLV field */
152 uint64_t swap_file_sz
;
155 /* END OF ON-DISK STORE_META_STD */
157 /// unique ID inside a cache_dir for swapped out entries; -1 for others
158 sfileno swap_filen
:25; // keep in sync with SwapFilenMax
162 mem_status_t mem_status
:3;
164 ping_status_t ping_status
:3;
166 store_status_t store_status
:3;
168 swap_status_t swap_status
:3;
171 static size_t inUseCount();
172 static void getPublicByRequestMethod(StoreClient
* aClient
, HttpRequest
* request
, const HttpRequestMethod
& method
);
173 static void getPublicByRequest(StoreClient
* aClient
, HttpRequest
* request
);
174 static void getPublic(StoreClient
* aClient
, const char *uri
, const HttpRequestMethod
& method
);
176 virtual bool isNull() {
180 void *operator new(size_t byteCount
);
181 void operator delete(void *address
);
182 void setReleaseFlag();
185 ESIElement::Pointer cachedESITree
;
187 virtual int64_t objectLen() const;
188 virtual int64_t contentLen() const;
190 /// claim shared ownership of this entry (for use in a given context)
191 /// matching lock() and unlock() contexts eases leak triage but is optional
192 void lock(const char *context
);
194 /// disclaim shared ownership; may remove entry from store and delete it
195 /// returns remaning lock level (zero for unlocked and possibly gone entry)
196 int unlock(const char *context
);
198 /// returns a local concurrent use counter, for debugging
199 int locks() const { return static_cast<int>(lock_count
); }
201 /// update last reference timestamp and related Store metadata
204 virtual void release();
207 /// call back producer when more buffer space is available
208 void deferProducer(const AsyncCall::Pointer
&producer
);
209 /// calls back producer registered with deferProducer
214 virtual void append(char const *, int);
215 virtual void vappendf(const char *, va_list);
216 virtual void buffer();
217 virtual void flush();
220 void transientsAbandonmentCheck();
223 bool checkTooBig() const;
225 static MemAllocator
*pool
;
227 unsigned short lock_count
; /* Assume < 65536! */
230 /// producer callback registered with deferProducer
231 AsyncCall::Pointer deferredProducer
;
234 bool validLength() const;
235 bool hasOneOfEtags(const String
&reqETags
, const bool allowWeakMatch
) const;
238 std::ostream
&operator <<(std::ostream
&os
, const StoreEntry
&e
);
240 /// \ingroup StoreAPI
241 class NullStoreEntry
:public StoreEntry
245 static NullStoreEntry
*getInstance();
250 const char *getMD5Text() const;
251 HttpReply
const *getReply() const { return NULL
; }
252 void write (StoreIOBuffer
) {}
254 bool isEmpty () const {return true;}
256 virtual size_t bytesWanted(Range
<size_t> const aRange
, bool) const { return aRange
.end
; }
258 void operator delete(void *address
);
262 store_client_t
storeClientType() const {return STORE_MEM_CLIENT
;}
264 char const *getSerialisedMetaData();
265 virtual bool mayStartSwapOut() { return false; }
267 void trimMemory(const bool) {}
269 static NullStoreEntry _instance
;
272 /// \ingroup StoreAPI
273 typedef void (*STOREGETCLIENT
) (StoreEntry
*, void *cbdata
);
277 * Abstract base class that will replace the whole store and swapdir interface.
279 class Store
: public RefCountable
283 /** The root store */
284 static Store
&Root() {
285 if (CurrentRoot
== NULL
)
286 fatal("No Store Root has been set");
289 static void Root(Store
*);
290 static void Root(RefCount
<Store
>);
291 static void Stats(StoreEntry
* output
);
292 static void Maintain(void *unused
);
296 /** Handle pending callbacks - called by the event loop. */
297 virtual int callback() = 0;
299 /** create the resources needed for this store to operate */
300 virtual void create();
303 * Notify this store that its disk is full.
304 \todo XXX move into a protected api call between store files and their stores, rather than a top level api call
306 virtual void diskFull();
308 /** Retrieve a store entry from the store */
309 virtual StoreEntry
* get(const cache_key
*) = 0;
311 /** \todo imeplement the async version */
312 virtual void get(String
const key
, STOREGETCLIENT callback
, void *cbdata
) = 0;
314 /* prepare the store for use. The store need not be usable immediately,
315 * it should respond to readable() and writable() with true as soon
316 * as it can provide those services
318 virtual void init() = 0;
321 * The maximum size the store will support in normal use. Inaccuracy is permitted,
322 * but may throw estimates for memory etc out of whack.
324 virtual uint64_t maxSize() const = 0;
326 /** The minimum size the store will shrink to via normal housekeeping */
327 virtual uint64_t minSize() const = 0;
329 /** current store size */
330 virtual uint64_t currentSize() const = 0;
332 /** the total number of objects stored */
333 virtual uint64_t currentCount() const = 0;
335 /** the maximum object size that can be stored, -1 if unlimited */
336 virtual int64_t maxObjectSize() const = 0;
338 /// collect cache storage-related statistics
339 virtual void getStats(StoreInfoStats
&stats
) const = 0;
342 * Output stats to the provided store entry.
343 \todo make these calls asynchronous
345 virtual void stat(StoreEntry
&) const = 0;
347 /** Sync the store prior to shutdown */
350 /** remove a Store entry from the store */
351 virtual void unlink (StoreEntry
&);
353 /* search in the store */
354 virtual StoreSearch
*search(String
const url
, HttpRequest
*) = 0;
356 /* pulled up from SwapDir for migration.... probably do not belong here */
357 virtual void reference(StoreEntry
&) = 0; /* Reference this object */
359 /// Undo reference(), returning false iff idle e should be destroyed
360 virtual bool dereference(StoreEntry
&, bool wantsLocalMemory
) = 0;
362 virtual void maintain() = 0; /* perform regular maintenance should be private and self registered ... */
364 // XXX: This method belongs to Store::Root/StoreController, but it is here
365 // to avoid casting Root() to StoreController until Root() API is fixed.
366 /// informs stores that this entry will be eventually unlinked
367 virtual void markForUnlink(StoreEntry
&) {}
369 // XXX: This method belongs to Store::Root/StoreController, but it is here
370 // because test cases use non-StoreController derivatives as Root
371 /// called when the entry is no longer needed by any transaction
372 virtual void handleIdleEntry(StoreEntry
&) {}
374 // XXX: This method belongs to Store::Root/StoreController, but it is here
375 // because test cases use non-StoreController derivatives as Root
376 /// called to get rid of no longer needed entry data in RAM, if any
377 virtual void memoryOut(StoreEntry
&, const bool /*preserveSwappable*/) {}
379 // XXX: This method belongs to Store::Root/StoreController, but it is here
380 // to avoid casting Root() to StoreController until Root() API is fixed.
381 /// makes the entry available for collapsing future requests
382 virtual void allowCollapsing(StoreEntry
*, const RequestFlags
&, const HttpRequestMethod
&) {}
384 // XXX: This method belongs to Store::Root/StoreController, but it is here
385 // to avoid casting Root() to StoreController until Root() API is fixed.
386 /// marks the entry completed for collapsed requests
387 virtual void transientsCompleteWriting(StoreEntry
&) {}
389 // XXX: This method belongs to Store::Root/StoreController, but it is here
390 // to avoid casting Root() to StoreController until Root() API is fixed.
391 /// Update local intransit entry after changes made by appending worker.
392 virtual void syncCollapsed(const sfileno
) {}
394 // XXX: This method belongs to Store::Root/StoreController, but it is here
395 // to avoid casting Root() to StoreController until Root() API is fixed.
396 /// calls Root().transients->abandon() if transients are tracked
397 virtual void transientsAbandon(StoreEntry
&) {}
399 // XXX: This method belongs to Store::Root/StoreController, but it is here
400 // to avoid casting Root() to StoreController until Root() API is fixed.
401 /// number of the transient entry readers some time ago
402 virtual int transientReaders(const StoreEntry
&) const { return 0; }
404 // XXX: This method belongs to Store::Root/StoreController, but it is here
405 // to avoid casting Root() to StoreController until Root() API is fixed.
406 /// disassociates the entry from the intransit table
407 virtual void transientsDisconnect(MemObject
&) {}
409 // XXX: This method belongs to Store::Root/StoreController, but it is here
410 // to avoid casting Root() to StoreController until Root() API is fixed.
411 /// removes the entry from the memory cache
412 virtual void memoryUnlink(StoreEntry
&) {}
414 // XXX: This method belongs to Store::Root/StoreController, but it is here
415 // to avoid casting Root() to StoreController until Root() API is fixed.
416 /// disassociates the entry from the memory cache, preserving cached data
417 virtual void memoryDisconnect(StoreEntry
&) {}
419 /// If the entry is not found, return false. Otherwise, return true after
420 /// tying the entry to this cache and setting inSync to updateCollapsed().
421 virtual bool anchorCollapsed(StoreEntry
&, bool &/*inSync*/) { return false; }
423 /// update a local collapsed entry with fresh info from this cache (if any)
424 virtual bool updateCollapsed(StoreEntry
&) { return false; }
427 static RefCount
<Store
> CurrentRoot
;
430 /// \ingroup StoreAPI
431 typedef RefCount
<Store
> StorePointer
;
433 /// \ingroup StoreAPI
434 size_t storeEntryInUse();
436 /// \ingroup StoreAPI
437 const char *storeEntryFlags(const StoreEntry
*);
439 /// \ingroup StoreAPI
440 void storeEntryReplaceObject(StoreEntry
*, HttpReply
*);
442 /// \ingroup StoreAPI
443 StoreEntry
*storeGetPublic(const char *uri
, const HttpRequestMethod
& method
);
445 /// \ingroup StoreAPI
446 StoreEntry
*storeGetPublicByRequest(HttpRequest
* request
);
448 /// \ingroup StoreAPI
449 StoreEntry
*storeGetPublicByRequestMethod(HttpRequest
* request
, const HttpRequestMethod
& method
);
451 /// \ingroup StoreAPI
452 /// Like storeCreatePureEntry(), but also locks the entry and sets entry key.
453 StoreEntry
*storeCreateEntry(const char *, const char *, const RequestFlags
&, const HttpRequestMethod
&);
455 /// \ingroup StoreAPI
456 /// Creates a new StoreEntry with mem_obj and sets initial flags/states.
457 StoreEntry
*storeCreatePureEntry(const char *storeId
, const char *logUrl
, const RequestFlags
&, const HttpRequestMethod
&);
459 /// \ingroup StoreAPI
460 void storeInit(void);
462 /// \ingroup StoreAPI
463 void storeConfigure(void);
465 /// \ingroup StoreAPI
466 void storeFreeMemory(void);
468 /// \ingroup StoreAPI
469 int expiresMoreThan(time_t, time_t);
471 /// \ingroup StoreAPI
472 void storeAppendPrintf(StoreEntry
*, const char *,...) PRINTF_FORMAT_ARG2
;
474 /// \ingroup StoreAPI
475 void storeAppendVPrintf(StoreEntry
*, const char *, va_list ap
);
477 /// \ingroup StoreAPI
478 int storeTooManyDiskFilesOpen(void);
481 /// \ingroup StoreAPI
482 void storeHeapPositionUpdate(StoreEntry
*, SwapDir
*);
484 /// \ingroup StoreAPI
485 void storeSwapFileNumberSet(StoreEntry
* e
, sfileno filn
);
487 /// \ingroup StoreAPI
488 void storeFsInit(void);
490 /// \ingroup StoreAPI
491 void storeFsDone(void);
493 /// \ingroup StoreAPI
494 void storeReplAdd(const char *, REMOVALPOLICYCREATE
*);
496 /// \ingroup StoreAPI
497 extern FREE destroyStoreEntry
;
499 /// \ingroup StoreAPI
500 void storeGetMemSpace(int size
);
502 #endif /* SQUID_STORE_H */