]> git.ipfire.org Git - thirdparty/squid.git/blob - src/Store.h
Merged from trunk 13199.
[thirdparty/squid.git] / src / Store.h
1 /*
2 *
3 * SQUID Web Proxy Cache http://www.squid-cache.org/
4 * ----------------------------------------------------------
5 *
6 * Squid is the result of efforts by numerous individuals from
7 * the Internet community; see the CONTRIBUTORS file for full
8 * details. Many organizations have provided support for Squid's
9 * development; see the SPONSORS file for full details. Squid is
10 * Copyrighted (C) 2001 by the Regents of the University of
11 * California; see the COPYRIGHT file for full details. Squid
12 * incorporates software developed and/or copyrighted by other
13 * sources; see the CREDITS file for full details.
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program; if not, write to the Free Software
27 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
28 *
29 */
30 #ifndef SQUID_STORE_H
31 #define SQUID_STORE_H
32
33 /**
34 \defgroup StoreAPI Store API
35 \ingroup FileSystems
36 */
37
38 #include "base/RefCount.h"
39 #include "comm/forward.h"
40 #include "CommRead.h"
41 #include "hash.h"
42 #include "HttpReply.h"
43 #include "HttpRequestMethod.h"
44 #include "Range.h"
45 #include "RemovalPolicy.h"
46 #include "StoreIOBuffer.h"
47 #include "StoreStats.h"
48
49 #if USE_SQUID_ESI
50 #include "esi/Element.h"
51 #endif
52
53 #if HAVE_OSTREAM
54 #include <ostream>
55 #endif
56
57 class AsyncCall;
58 class HttpRequest;
59 class MemObject;
60 class Packer;
61 class RequestFlags;
62 class StoreClient;
63 class StoreSearch;
64 class SwapDir;
65
66 extern StoreIoStats store_io_stats;
67
68 /// maximum number of entries per cache_dir
69 enum { SwapFilenMax = 0xFFFFFF }; // keep in sync with StoreEntry::swap_filen
70
71 /**
72 \ingroup StoreAPI
73 */
74 class StoreEntry : public hash_link
75 {
76
77 public:
78 static DeferredRead::DeferrableRead DeferReader;
79 bool checkDeferRead(int fd) const;
80
81 virtual const char *getMD5Text() const;
82 StoreEntry();
83 virtual ~StoreEntry();
84
85 virtual HttpReply const *getReply() const;
86 virtual void write (StoreIOBuffer);
87 virtual _SQUID_INLINE_ bool isEmpty() const;
88 virtual bool isAccepting() const;
89 virtual size_t bytesWanted(Range<size_t> const aRange, bool ignoreDelayPool = false) const;
90 virtual void complete();
91 virtual store_client_t storeClientType() const;
92 virtual char const *getSerialisedMetaData();
93 void replaceHttpReply(HttpReply *, bool andStartWriting = true);
94 void startWriting(); ///< pack and write reply headers and, maybe, body
95 /// whether we may start writing to disk (now or in the future)
96 virtual bool mayStartSwapOut();
97 virtual void trimMemory(const bool preserveSwappable);
98 void abort();
99 void unlink();
100 void makePublic();
101 void makePrivate();
102 void setPublicKey();
103 void setPrivateKey();
104 void expireNow();
105 void releaseRequest();
106 void negativeCache();
107 void cacheNegatively(); /** \todo argh, why both? */
108 void invokeHandlers();
109 void purgeMem();
110 void cacheInMemory(); ///< start or continue storing in memory cache
111 void swapOut();
112 /// whether we are in the process of writing this entry to disk
113 bool swappingOut() const { return swap_status == SWAPOUT_WRITING; }
114 void swapOutFileClose(int how);
115 const char *url() const;
116 int checkCachable();
117 int checkNegativeHit() const;
118 int locked() const;
119 int validToSend() const;
120 bool memoryCachable() const; ///< may be cached in memory
121
122 /// if needed, initialize mem_obj member w/o URI-related information
123 MemObject *makeMemObject();
124
125 /// initialize mem_obj member (if needed) and supply URI-related info
126 void createMemObject(const char *storeId, const char *logUri, const HttpRequestMethod &aMethod);
127
128 void dump(int debug_lvl) const;
129 void hashDelete();
130 void hashInsert(const cache_key *);
131 void registerAbort(STABH * cb, void *);
132 void reset();
133 void setMemStatus(mem_status_t);
134 void timestampsSet();
135 void unregisterAbort();
136 void destroyMemObject();
137 int checkTooSmall();
138
139 void delayAwareRead(const Comm::ConnectionPointer &conn, char *buf, int len, AsyncCall::Pointer callback);
140
141 void setNoDelay (bool const);
142 bool modifiedSince(HttpRequest * request) const;
143 /// has ETag matching at least one of the If-Match etags
144 bool hasIfMatchEtag(const HttpRequest &request) const;
145 /// has ETag matching at least one of the If-None-Match etags
146 bool hasIfNoneMatchEtag(const HttpRequest &request) const;
147 /// whether this entry has an ETag; if yes, puts ETag value into parameter
148 bool hasEtag(ETag &etag) const;
149
150 /** What store does this entry belong too ? */
151 virtual RefCount<SwapDir> store() const;
152
153 MemObject *mem_obj;
154 RemovalPolicyNode repl;
155 /* START OF ON-DISK STORE_META_STD TLV field */
156 time_t timestamp;
157 time_t lastref;
158 time_t expires;
159 time_t lastmod;
160 uint64_t swap_file_sz;
161 uint16_t refcount;
162 uint16_t flags;
163 /* END OF ON-DISK STORE_META_STD */
164
165 /// unique ID inside a cache_dir for swapped out entries; -1 for others
166 sfileno swap_filen:25; // keep in sync with SwapFilenMax
167
168 sdirno swap_dirn:7;
169
170 mem_status_t mem_status:3;
171
172 ping_status_t ping_status:3;
173
174 store_status_t store_status:3;
175
176 swap_status_t swap_status:3;
177
178 public:
179 static size_t inUseCount();
180 static void getPublicByRequestMethod(StoreClient * aClient, HttpRequest * request, const HttpRequestMethod& method);
181 static void getPublicByRequest(StoreClient * aClient, HttpRequest * request);
182 static void getPublic(StoreClient * aClient, const char *uri, const HttpRequestMethod& method);
183
184 virtual bool isNull() {
185 return false;
186 };
187
188 void *operator new(size_t byteCount);
189 void operator delete(void *address);
190 void setReleaseFlag();
191 #if USE_SQUID_ESI
192
193 ESIElement::Pointer cachedESITree;
194 #endif
195 /** append bytes to the buffer */
196 virtual void append(char const *, int len);
197 /** disable sending content to the clients */
198 virtual void buffer();
199 /** flush any buffered content */
200 virtual void flush();
201 virtual int64_t objectLen() const;
202 virtual int64_t contentLen() const;
203
204 /// claim shared ownership of this entry (for use in a given context)
205 /// matching lock() and unlock() contexts eases leak triage but is optional
206 void lock(const char *context);
207
208 /// disclaim shared ownership; may remove entry from store and delete it
209 /// returns remaning lock level (zero for unlocked and possibly gone entry)
210 int unlock(const char *context);
211
212 /// returns a local concurrent use counter, for debugging
213 int locks() const { return static_cast<int>(lock_count); }
214
215 /// update last reference timestamp and related Store metadata
216 void touch();
217
218 virtual void release();
219
220 #if USE_ADAPTATION
221 /// call back producer when more buffer space is available
222 void deferProducer(const AsyncCall::Pointer &producer);
223 /// calls back producer registered with deferProducer
224 void kickProducer();
225 #endif
226
227 private:
228 static MemAllocator *pool;
229
230 unsigned short lock_count; /* Assume < 65536! */
231
232 #if USE_ADAPTATION
233 /// producer callback registered with deferProducer
234 AsyncCall::Pointer deferredProducer;
235 #endif
236
237 bool validLength() const;
238 bool hasOneOfEtags(const String &reqETags, const bool allowWeakMatch) const;
239 };
240
241 std::ostream &operator <<(std::ostream &os, const StoreEntry &e);
242
243 /// \ingroup StoreAPI
244 class NullStoreEntry:public StoreEntry
245 {
246
247 public:
248 static NullStoreEntry *getInstance();
249 bool isNull() {
250 return true;
251 }
252
253 const char *getMD5Text() const;
254 _SQUID_INLINE_ HttpReply const *getReply() const;
255 void write (StoreIOBuffer) {}
256
257 bool isEmpty () const {return true;}
258
259 virtual size_t bytesWanted(Range<size_t> const aRange, bool ignoreDelayPool = false) const { return aRange.end; }
260
261 void operator delete(void *address);
262 void complete() {}
263
264 private:
265 store_client_t storeClientType() const {return STORE_MEM_CLIENT;}
266
267 char const *getSerialisedMetaData();
268 bool mayStartSwapout() {return false;}
269
270 void trimMemory(const bool preserveSwappable) {}
271
272 static NullStoreEntry _instance;
273 };
274
275 /// \ingroup StoreAPI
276 typedef void (*STOREGETCLIENT) (StoreEntry *, void *cbdata);
277
278 /**
279 \ingroup StoreAPI
280 * Abstract base class that will replace the whole store and swapdir interface.
281 */
282 class Store : public RefCountable
283 {
284
285 public:
286 /** The root store */
287 static _SQUID_INLINE_ Store &Root();
288 static void Root(Store *);
289 static void Root(RefCount<Store>);
290 static void Stats(StoreEntry * output);
291 static void Maintain(void *unused);
292
293 virtual ~Store() {}
294
295 /** Handle pending callbacks - called by the event loop. */
296 virtual int callback() = 0;
297
298 /** create the resources needed for this store to operate */
299 virtual void create();
300
301 /**
302 * Notify this store that its disk is full.
303 \todo XXX move into a protected api call between store files and their stores, rather than a top level api call
304 */
305 virtual void diskFull();
306
307 /** Retrieve a store entry from the store */
308 virtual StoreEntry * get(const cache_key *) = 0;
309
310 /** \todo imeplement the async version */
311 virtual void get(String const key , STOREGETCLIENT callback, void *cbdata) = 0;
312
313 /* prepare the store for use. The store need not be usable immediately,
314 * it should respond to readable() and writable() with true as soon
315 * as it can provide those services
316 */
317 virtual void init() = 0;
318
319 /**
320 * The maximum size the store will support in normal use. Inaccuracy is permitted,
321 * but may throw estimates for memory etc out of whack.
322 */
323 virtual uint64_t maxSize() const = 0;
324
325 /** The minimum size the store will shrink to via normal housekeeping */
326 virtual uint64_t minSize() const = 0;
327
328 /** current store size */
329 virtual uint64_t currentSize() const = 0;
330
331 /** the total number of objects stored */
332 virtual uint64_t currentCount() const = 0;
333
334 /** the maximum object size that can be stored, -1 if unlimited */
335 virtual int64_t maxObjectSize() const = 0;
336
337 /// collect cache storage-related statistics
338 virtual void getStats(StoreInfoStats &stats) const = 0;
339
340 /**
341 * Output stats to the provided store entry.
342 \todo make these calls asynchronous
343 */
344 virtual void stat(StoreEntry &) const = 0;
345
346 /** Sync the store prior to shutdown */
347 virtual void sync();
348
349 /** remove a Store entry from the store */
350 virtual void unlink (StoreEntry &);
351
352 /* search in the store */
353 virtual StoreSearch *search(String const url, HttpRequest *) = 0;
354
355 /* pulled up from SwapDir for migration.... probably do not belong here */
356 virtual void reference(StoreEntry &) = 0; /* Reference this object */
357
358 /// Undo reference(), returning false iff idle e should be destroyed
359 virtual bool dereference(StoreEntry &e, bool wantsLocalMemory) = 0;
360
361 virtual void maintain() = 0; /* perform regular maintenance should be private and self registered ... */
362
363 // XXX: This method belongs to Store::Root/StoreController, but it is here
364 // to avoid casting Root() to StoreController until Root() API is fixed.
365 /// informs stores that this entry will be eventually unlinked
366 virtual void markForUnlink(StoreEntry &e) {}
367
368 // XXX: This method belongs to Store::Root/StoreController, but it is here
369 // because test cases use non-StoreController derivatives as Root
370 /// called when the entry is no longer needed by any transaction
371 virtual void handleIdleEntry(StoreEntry &e) {}
372
373 // XXX: This method belongs to Store::Root/StoreController, but it is here
374 // because test cases use non-StoreController derivatives as Root
375 /// called to get rid of no longer needed entry data in RAM, if any
376 virtual void memoryOut(StoreEntry &e, const bool preserveSwappable) {}
377
378 // XXX: This method belongs to Store::Root/StoreController, but it is here
379 // to avoid casting Root() to StoreController until Root() API is fixed.
380 /// makes the entry available for collapsing future requests
381 virtual void allowCollapsing(StoreEntry *e, const RequestFlags &reqFlags, const HttpRequestMethod &reqMethod) {}
382
383 // XXX: This method belongs to Store::Root/StoreController, but it is here
384 // to avoid casting Root() to StoreController until Root() API is fixed.
385 /// marks the entry completed for collapsed requests
386 virtual void transientsCompleteWriting(StoreEntry &e) {}
387
388 // XXX: This method belongs to Store::Root/StoreController, but it is here
389 // to avoid casting Root() to StoreController until Root() API is fixed.
390 /// Update local intransit entry after changes made by appending worker.
391 virtual void syncCollapsed(const sfileno xitIndex) {}
392
393 // XXX: This method belongs to Store::Root/StoreController, but it is here
394 // to avoid casting Root() to StoreController until Root() API is fixed.
395 /// calls Root().transients->abandon() if transients are tracked
396 virtual void transientsAbandon(StoreEntry &e) {}
397
398 // XXX: This method belongs to Store::Root/StoreController, but it is here
399 // to avoid casting Root() to StoreController until Root() API is fixed.
400 /// number of the transient entry readers some time ago
401 virtual int transientReaders(const StoreEntry &e) const { return 0; }
402
403 // XXX: This method belongs to Store::Root/StoreController, but it is here
404 // to avoid casting Root() to StoreController until Root() API is fixed.
405 /// disassociates the entry from the intransit table
406 virtual void transientsDisconnect(MemObject &mem_obj) {}
407
408 // XXX: This method belongs to Store::Root/StoreController, but it is here
409 // to avoid casting Root() to StoreController until Root() API is fixed.
410 /// removes the entry from the memory cache
411 virtual void memoryUnlink(StoreEntry &e) {}
412
413 // XXX: This method belongs to Store::Root/StoreController, but it is here
414 // to avoid casting Root() to StoreController until Root() API is fixed.
415 /// disassociates the entry from the memory cache, preserving cached data
416 virtual void memoryDisconnect(StoreEntry &e) {}
417
418 /// If the entry is not found, return false. Otherwise, return true after
419 /// tying the entry to this cache and setting inSync to updateCollapsed().
420 virtual bool anchorCollapsed(StoreEntry &collapsed, bool &inSync) { return false; }
421
422 /// update a local collapsed entry with fresh info from this cache (if any)
423 virtual bool updateCollapsed(StoreEntry &collapsed) { return false; }
424
425 private:
426 static RefCount<Store> CurrentRoot;
427 };
428
429 /// \ingroup StoreAPI
430 typedef RefCount<Store> StorePointer;
431
432 /// \ingroup StoreAPI
433 size_t storeEntryInUse();
434
435 /// \ingroup StoreAPI
436 const char *storeEntryFlags(const StoreEntry *);
437
438 /// \ingroup StoreAPI
439 void storeEntryReplaceObject(StoreEntry *, HttpReply *);
440
441 /// \ingroup StoreAPI
442 StoreEntry *storeGetPublic(const char *uri, const HttpRequestMethod& method);
443
444 /// \ingroup StoreAPI
445 StoreEntry *storeGetPublicByRequest(HttpRequest * request);
446
447 /// \ingroup StoreAPI
448 StoreEntry *storeGetPublicByRequestMethod(HttpRequest * request, const HttpRequestMethod& method);
449
450 /// \ingroup StoreAPI
451 /// Like storeCreatePureEntry(), but also locks the entry and sets entry key.
452 StoreEntry *storeCreateEntry(const char *, const char *, const RequestFlags &, const HttpRequestMethod&);
453
454 /// \ingroup StoreAPI
455 /// Creates a new StoreEntry with mem_obj and sets initial flags/states.
456 StoreEntry *storeCreatePureEntry(const char *storeId, const char *logUrl, const RequestFlags &, const HttpRequestMethod&);
457
458 /// \ingroup StoreAPI
459 void storeInit(void);
460
461 /// \ingroup StoreAPI
462 void storeConfigure(void);
463
464 /// \ingroup StoreAPI
465 void storeFreeMemory(void);
466
467 /// \ingroup StoreAPI
468 int expiresMoreThan(time_t, time_t);
469
470 /// \ingroup StoreAPI
471 void storeAppendPrintf(StoreEntry *, const char *,...) PRINTF_FORMAT_ARG2;
472
473 /// \ingroup StoreAPI
474 void storeAppendVPrintf(StoreEntry *, const char *, va_list ap);
475
476 /// \ingroup StoreAPI
477 int storeTooManyDiskFilesOpen(void);
478
479 class SwapDir;
480 /// \ingroup StoreAPI
481 void storeHeapPositionUpdate(StoreEntry *, SwapDir *);
482
483 /// \ingroup StoreAPI
484 void storeSwapFileNumberSet(StoreEntry * e, sfileno filn);
485
486 /// \ingroup StoreAPI
487 void storeFsInit(void);
488
489 /// \ingroup StoreAPI
490 void storeFsDone(void);
491
492 /// \ingroup StoreAPI
493 void storeReplAdd(const char *, REMOVALPOLICYCREATE *);
494
495 /// \ingroup StoreAPI
496 extern FREE destroyStoreEntry;
497
498 /**
499 \ingroup StoreAPI
500 \todo should be a subclass of Packer perhaps ?
501 */
502 void packerToStoreInit(Packer * p, StoreEntry * e);
503
504 /// \ingroup StoreAPI
505 void storeGetMemSpace(int size);
506
507 #if _USE_INLINE_
508 #include "Store.cci"
509 #endif
510
511 #endif /* SQUID_STORE_H */