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