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