3 * DEBUG: section 20 Storage Manager
4 * AUTHOR: Harvest Derived
6 * SQUID Web Proxy Cache http://www.squid-cache.org/
7 * ----------------------------------------------------------
9 * Squid is the result of efforts by numerous individuals from
10 * the Internet community; see the CONTRIBUTORS file for full
11 * details. Many organizations have provided support for Squid's
12 * development; see the SPONSORS file for full details. Squid is
13 * Copyrighted (C) 2001 by the Regents of the University of
14 * California; see the COPYRIGHT file for full details. Squid
15 * incorporates software developed and/or copyrighted by other
16 * sources; see the CREDITS file for full details.
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program; if not, write to the Free Software
30 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
35 #include "CacheDigest.h"
36 #include "CacheManager.h"
37 #include "comm/Connection.h"
43 #include "HttpReply.h"
44 #include "HttpRequest.h"
46 #include "MemObject.h"
47 #include "mgr/Registration.h"
48 #include "mgr/StoreIoAction.h"
49 #include "profiler/Profiler.h"
50 #include "repl_modules.h"
51 #include "RequestFlags.h"
52 #include "SquidConfig.h"
53 #include "SquidTime.h"
55 #include "StatCounters.h"
58 #include "store_digest.h"
59 #include "store_key_md5.h"
60 #include "store_key_md5.h"
61 #include "store_log.h"
62 #include "store_rebuild.h"
63 #include "StoreClient.h"
64 #include "StoreIOState.h"
65 #include "StoreMeta.h"
67 #include "swap_log_op.h"
71 #include "DelayPools.h"
77 static STMCB storeWriteComplete
;
79 #define REBUILD_TIMESTAMP_DELTA_MAX 2
81 #define STORE_IN_MEM_BUCKETS (229)
83 /** \todo Convert these string constants to enum string-arrays generated */
85 const char *memStatusStr
[] = {
90 const char *pingStatusStr
[] = {
96 const char *storeStatusStr
[] = {
101 const char *swapStatusStr
[] = {
108 * This defines an repl type
111 typedef struct _storerepl_entry storerepl_entry_t
;
113 struct _storerepl_entry
{
115 REMOVALPOLICYCREATE
*create
;
118 static storerepl_entry_t
*storerepl_list
= NULL
;
121 * local function prototypes
123 static int getKeyCounter(void);
124 static OBJH storeCheckCachableStats
;
125 static EVH storeLateRelease
;
130 static Stack
<StoreEntry
*> LateReleaseStack
;
131 MemAllocator
*StoreEntry::pool
= NULL
;
133 StorePointer
Store::CurrentRoot
= NULL
;
136 Store::Root(Store
* aRoot
)
142 Store::Root(StorePointer aRoot
)
144 Root(aRoot
.getRaw());
148 Store::Stats(StoreEntry
* output
)
151 Root().stat(*output
);
167 Store::unlink (StoreEntry
&anEntry
)
169 fatal("Store::unlink on invalid Store\n");
173 StoreEntry::operator new (size_t bytecount
)
175 assert (bytecount
== sizeof (StoreEntry
));
178 pool
= memPoolCreate ("StoreEntry", bytecount
);
179 pool
->setChunkSize(2048 * 1024);
182 return pool
->alloc();
186 StoreEntry::operator delete (void *address
)
188 pool
->freeOne(address
);
192 StoreEntry::makePublic()
194 /* This object can be cached for a long time */
196 if (EBIT_TEST(flags
, ENTRY_CACHABLE
))
201 StoreEntry::makePrivate()
203 /* This object should never be cached at all */
205 releaseRequest(); /* delete object when not used */
206 /* releaseRequest clears ENTRY_CACHABLE flag */
210 StoreEntry::cacheNegatively()
212 /* This object may be negatively cached */
215 if (EBIT_TEST(flags
, ENTRY_CACHABLE
))
220 StoreEntry::inUseCount()
224 return pool
->getInUseCount();
228 StoreEntry::getMD5Text() const
230 return storeKeyText((const cache_key
*)key
);
236 StoreEntry::DeferReader(void *theContext
, CommRead
const &aRead
)
238 StoreEntry
*anEntry
= (StoreEntry
*)theContext
;
239 anEntry
->delayAwareRead(aRead
.conn
,
246 StoreEntry::delayAwareRead(const Comm::ConnectionPointer
&conn
, char *buf
, int len
, AsyncCall::Pointer callback
)
248 size_t amountToRead
= bytesWanted(Range
<size_t>(0, len
));
249 /* sketch: readdeferer* = getdeferer.
250 * ->deferRead (fd, buf, len, callback, DelayAwareRead, this)
253 if (amountToRead
== 0) {
255 /* read ahead limit */
256 /* Perhaps these two calls should both live in MemObject */
258 if (!mem_obj
->readAheadPolicyCanRead()) {
260 mem_obj
->delayRead(DeferredRead(DeferReader
, this, CommRead(conn
, buf
, len
, callback
)));
266 mem_obj
->mostBytesAllowed().delayRead(DeferredRead(DeferReader
, this, CommRead(conn
, buf
, len
, callback
)));
273 if (fd_table
[conn
->fd
].closing()) {
274 // Readers must have closing callbacks if they want to be notified. No
275 // readers appeared to care around 2009/12/14 as they skipped reading
276 // for other reasons. Closing may already be true at the delyaAwareRead
277 // call time or may happen while we wait after delayRead() above.
278 debugs(20, 3, HERE
<< "wont read from closing " << conn
<< " for " <<
280 return; // the read callback will never be called
283 comm_read(conn
, buf
, amountToRead
, callback
);
287 StoreEntry::bytesWanted (Range
<size_t> const aRange
, bool ignoreDelayPools
) const
292 #if URL_CHECKSUM_DEBUG
294 mem_obj
->checkUrlChecksum();
298 if (!mem_obj
->readAheadPolicyCanRead())
301 return mem_obj
->mostBytesWanted(aRange
.end
, ignoreDelayPools
);
305 StoreEntry::checkDeferRead(int fd
) const
307 return (bytesWanted(Range
<size_t>(0,INT_MAX
)) == 0);
311 StoreEntry::setNoDelay (bool const newValue
)
314 mem_obj
->setNoDelay(newValue
);
318 StoreEntry::storeClientType() const
320 /* The needed offset isn't in memory
321 * XXX TODO: this is wrong for range requests
322 * as the needed offset may *not* be 0, AND
323 * offset 0 in the memory object is the HTTP headers.
326 if (mem_status
== IN_MEMORY
&& Config
.memShared
&& IamWorkerProcess()) {
327 // clients of an object cached in shared memory are memory clients
328 return STORE_MEM_CLIENT
;
333 if (mem_obj
->inmem_lo
)
334 return STORE_DISK_CLIENT
;
336 if (EBIT_TEST(flags
, ENTRY_ABORTED
)) {
337 /* I don't think we should be adding clients to aborted entries */
338 debugs(20, DBG_IMPORTANT
, "storeClientType: adding to ENTRY_ABORTED entry");
339 return STORE_MEM_CLIENT
;
342 if (store_status
== STORE_OK
) {
343 /* the object has completed. */
345 if (mem_obj
->inmem_lo
== 0 && !isEmpty()) {
346 if (swap_status
== SWAPOUT_DONE
) {
347 debugs(20,7, HERE
<< mem_obj
<< " lo: " << mem_obj
->inmem_lo
<< " hi: " << mem_obj
->endOffset() << " size: " << mem_obj
->object_sz
);
348 if (mem_obj
->endOffset() == mem_obj
->object_sz
) {
349 /* hot object fully swapped in */
350 return STORE_MEM_CLIENT
;
353 /* Memory-only, or currently being swapped out */
354 return STORE_MEM_CLIENT
;
357 return STORE_DISK_CLIENT
;
360 /* here and past, entry is STORE_PENDING */
362 * If this is the first client, let it be the mem client
364 if (mem_obj
->nclients
== 1)
365 return STORE_MEM_CLIENT
;
368 * If there is no disk file to open yet, we must make this a
369 * mem client. If we can't open the swapin file before writing
370 * to the client, there is no guarantee that we will be able
371 * to open it later when we really need it.
373 if (swap_status
== SWAPOUT_NONE
)
374 return STORE_MEM_CLIENT
;
377 * otherwise, make subsequent clients read from disk so they
378 * can not delay the first, and vice-versa.
380 return STORE_DISK_CLIENT
;
383 StoreEntry::StoreEntry() :
385 hidden_mem_obj(NULL
),
396 mem_status(NOT_IN_MEMORY
),
397 ping_status(PING_NONE
),
398 store_status(STORE_PENDING
),
399 swap_status(SWAPOUT_NONE
)
401 debugs(20, 3, HERE
<< "new StoreEntry " << this);
404 StoreEntry::StoreEntry(const char *aUrl
, const char *aLogUrl
) :
406 hidden_mem_obj(NULL
),
417 mem_status(NOT_IN_MEMORY
),
418 ping_status(PING_NONE
),
419 store_status(STORE_PENDING
),
420 swap_status(SWAPOUT_NONE
)
422 debugs(20, 3, HERE
<< "new StoreEntry " << this);
423 mem_obj
= new MemObject(aUrl
, aLogUrl
);
426 StoreEntry::~StoreEntry()
428 if (swap_filen
>= 0) {
429 SwapDir
&sd
= dynamic_cast<SwapDir
&>(*store());
430 sd
.disconnect(*this);
432 delete hidden_mem_obj
;
437 StoreEntry::deferProducer(const AsyncCall::Pointer
&producer
)
439 if (!deferredProducer
)
440 deferredProducer
= producer
;
442 debugs(20, 5, HERE
<< "Deferred producer call is allready set to: " <<
443 *deferredProducer
<< ", requested call: " << *producer
);
447 StoreEntry::kickProducer()
449 if (deferredProducer
!= NULL
) {
450 ScheduleCallHere(deferredProducer
);
451 deferredProducer
= NULL
;
457 StoreEntry::destroyMemObject()
459 debugs(20, 3, HERE
<< "destroyMemObject " << mem_obj
);
460 setMemStatus(NOT_IN_MEMORY
);
461 MemObject
*mem
= mem_obj
;
464 delete hidden_mem_obj
;
465 hidden_mem_obj
= NULL
;
469 StoreEntry::hideMemObject()
471 debugs(20, 3, HERE
<< "hiding " << mem_obj
);
473 assert(!hidden_mem_obj
);
474 hidden_mem_obj
= mem_obj
;
479 destroyStoreEntry(void *data
)
481 debugs(20, 3, HERE
<< "destroyStoreEntry: destroying " << data
);
482 StoreEntry
*e
= static_cast<StoreEntry
*>(static_cast<hash_link
*>(data
));
485 if (e
== NullStoreEntry::getInstance())
488 e
->destroyMemObject();
492 assert(e
->key
== NULL
);
497 /* ----- INTERFACE BETWEEN STORAGE MANAGER AND HASH TABLE FUNCTIONS --------- */
500 StoreEntry::hashInsert(const cache_key
* someKey
)
502 debugs(20, 3, "StoreEntry::hashInsert: Inserting Entry " << this << " key '" << storeKeyText(someKey
) << "'");
503 key
= storeKeyDup(someKey
);
504 hash_join(store_table
, this);
508 StoreEntry::hashDelete()
510 hash_remove_link(store_table
, this);
511 storeKeyFree((const cache_key
*)key
);
515 /* -------------------------------------------------------------------------- */
517 /* get rid of memory copy of the object */
519 StoreEntry::purgeMem()
524 debugs(20, 3, "StoreEntry::purgeMem: Freeing memory-copy of " << getMD5Text());
528 if (swap_status
!= SWAPOUT_DONE
)
532 /* RBC 20050104 this is wrong- memory ref counting
533 * is not at all equivalent to the store 'usage' concept
534 * which the replacement policies should be acting upon.
535 * specifically, object iteration within stores needs
536 * memory ref counting to prevent race conditions,
537 * but this should not influence store replacement.
544 debugs(20, 3, "StoreEntry::lock: key '" << getMD5Text() <<"' count=" <<
546 lastref
= squid_curtime
;
547 Store::Root().reference(*this);
551 StoreEntry::setReleaseFlag()
553 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
556 debugs(20, 3, "StoreEntry::setReleaseFlag: '" << getMD5Text() << "'");
558 EBIT_SET(flags
, RELEASE_REQUEST
);
562 StoreEntry::releaseRequest()
564 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
570 * Clear cachable flag here because we might get called before
571 * anyone else even looks at the cachability flag. Also, this
572 * prevents httpMakePublic from really setting a public key.
574 EBIT_CLR(flags
, ENTRY_CACHABLE
);
579 /* unlock object, return -1 if object get released after unlock
580 * otherwise lock_count */
585 debugs(20, 3, "StoreEntry::unlock: key '" << getMD5Text() << "' count=" << lock_count
);
588 return (int) lock_count
;
590 if (store_status
== STORE_PENDING
)
593 assert(storePendingNClients(this) == 0);
595 if (EBIT_TEST(flags
, RELEASE_REQUEST
)) {
600 if (EBIT_TEST(flags
, KEY_PRIVATE
))
601 debugs(20, DBG_IMPORTANT
, "WARNING: " << __FILE__
<< ":" << __LINE__
<< ": found KEY_PRIVATE");
603 Store::Root().handleIdleEntry(*this); // may delete us
608 StoreEntry::getPublicByRequestMethod (StoreClient
*aClient
, HttpRequest
* request
, const HttpRequestMethod
& method
)
611 StoreEntry
*result
= storeGetPublicByRequestMethod( request
, method
);
614 aClient
->created (NullStoreEntry::getInstance());
616 aClient
->created (result
);
620 StoreEntry::getPublicByRequest (StoreClient
*aClient
, HttpRequest
* request
)
623 StoreEntry
*result
= storeGetPublicByRequest (request
);
626 result
= NullStoreEntry::getInstance();
628 aClient
->created (result
);
632 StoreEntry::getPublic (StoreClient
*aClient
, const char *uri
, const HttpRequestMethod
& method
)
635 StoreEntry
*result
= storeGetPublic (uri
, method
);
638 result
= NullStoreEntry::getInstance();
640 aClient
->created (result
);
644 storeGetPublic(const char *uri
, const HttpRequestMethod
& method
)
646 return Store::Root().get(storeKeyPublic(uri
, method
));
650 storeGetPublicByRequestMethod(HttpRequest
* req
, const HttpRequestMethod
& method
)
652 return Store::Root().get(storeKeyPublicByRequestMethod(req
, method
));
656 storeGetPublicByRequest(HttpRequest
* req
)
658 StoreEntry
*e
= storeGetPublicByRequestMethod(req
, req
->method
);
660 if (e
== NULL
&& req
->method
== Http::METHOD_HEAD
)
661 /* We can generate a HEAD reply from a cached GET object */
662 e
= storeGetPublicByRequestMethod(req
, Http::METHOD_GET
);
670 static int key_counter
= 0;
672 if (++key_counter
< 0)
678 /* RBC 20050104 AFAICT this should become simpler:
679 * rather than reinserting with a special key it should be marked
680 * as 'released' and then cleaned up when refcounting indicates.
681 * the StoreHashIndex could well implement its 'released' in the
683 * Also, clean log writing should skip over ia,t
684 * Otherwise, we need a 'remove from the index but not the store
688 StoreEntry::setPrivateKey()
690 const cache_key
*newkey
;
692 if (key
&& EBIT_TEST(flags
, KEY_PRIVATE
))
693 return; /* is already private */
697 storeDirSwapLog(this, SWAP_LOG_DEL
);
702 if (mem_obj
!= NULL
) {
703 mem_obj
->id
= getKeyCounter();
704 newkey
= storeKeyPrivate(mem_obj
->url
, mem_obj
->method
, mem_obj
->id
);
706 newkey
= storeKeyPrivate("JUNK", Http::METHOD_NONE
, getKeyCounter());
709 assert(hash_lookup(store_table
, newkey
) == NULL
);
710 EBIT_SET(flags
, KEY_PRIVATE
);
715 StoreEntry::setPublicKey()
717 StoreEntry
*e2
= NULL
;
718 const cache_key
*newkey
;
720 if (key
&& !EBIT_TEST(flags
, KEY_PRIVATE
))
721 return; /* is already public */
726 * We can't make RELEASE_REQUEST objects public. Depending on
727 * when RELEASE_REQUEST gets set, we might not be swapping out
728 * the object. If we're not swapping out, then subsequent
729 * store clients won't be able to access object data which has
730 * been freed from memory.
732 * If RELEASE_REQUEST is set, then ENTRY_CACHABLE should not
733 * be set, and StoreEntry::setPublicKey() should not be called.
735 #if MORE_DEBUG_OUTPUT
737 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
738 debugs(20, DBG_IMPORTANT
, "assertion failed: RELEASE key " << key
<< ", url " << mem_obj
->url
);
742 assert(!EBIT_TEST(flags
, RELEASE_REQUEST
));
744 if (mem_obj
->request
) {
745 HttpRequest
*request
= mem_obj
->request
;
747 if (!mem_obj
->vary_headers
) {
748 /* First handle the case where the object no longer varies */
749 safe_free(request
->vary_headers
);
751 if (request
->vary_headers
&& strcmp(request
->vary_headers
, mem_obj
->vary_headers
) != 0) {
752 /* Oops.. the variance has changed. Kill the base object
753 * to record the new variance key
755 safe_free(request
->vary_headers
); /* free old "bad" variance key */
756 StoreEntry
*pe
= storeGetPublic(mem_obj
->url
, mem_obj
->method
);
762 /* Make sure the request knows the variance status */
763 if (!request
->vary_headers
) {
764 const char *vary
= httpMakeVaryMark(request
, mem_obj
->getReply());
767 request
->vary_headers
= xstrdup(vary
);
771 // TODO: storeGetPublic() calls below may create unlocked entries.
772 // We should add/use storeHas() API or lock/unlock those entries.
773 if (mem_obj
->vary_headers
&& !storeGetPublic(mem_obj
->url
, mem_obj
->method
)) {
774 /* Create "vary" base object */
776 StoreEntry
*pe
= storeCreateEntry(mem_obj
->url
, mem_obj
->log_url
, request
->flags
, request
->method
);
777 /* We are allowed to do this typecast */
778 HttpReply
*rep
= new HttpReply
;
779 rep
->setHeaders(Http::scOkay
, "Internal marker object", "x-squid-internal/vary", -1, -1, squid_curtime
+ 100000);
780 vary
= mem_obj
->getReply()->header
.getList(HDR_VARY
);
783 /* Again, we own this structure layout */
784 rep
->header
.putStr(HDR_VARY
, vary
.termedBuf());
788 #if X_ACCELERATOR_VARY
789 vary
= mem_obj
->getReply()->header
.getList(HDR_X_ACCELERATOR_VARY
);
791 if (vary
.size() > 0) {
792 /* Again, we own this structure layout */
793 rep
->header
.putStr(HDR_X_ACCELERATOR_VARY
, vary
.termedBuf());
798 pe
->replaceHttpReply(rep
, false); // no write until key is public
804 pe
->startWriting(); // after makePublic()
811 newkey
= storeKeyPublicByRequest(mem_obj
->request
);
813 newkey
= storeKeyPublic(mem_obj
->url
, mem_obj
->method
);
815 if ((e2
= (StoreEntry
*) hash_lookup(store_table
, newkey
))) {
816 debugs(20, 3, "StoreEntry::setPublicKey: Making old '" << mem_obj
->url
<< "' private.");
820 if (mem_obj
->request
)
821 newkey
= storeKeyPublicByRequest(mem_obj
->request
);
823 newkey
= storeKeyPublic(mem_obj
->url
, mem_obj
->method
);
829 EBIT_CLR(flags
, KEY_PRIVATE
);
834 storeDirSwapLog(this, SWAP_LOG_ADD
);
838 storeCreateEntry(const char *url
, const char *log_url
, const RequestFlags
&flags
, const HttpRequestMethod
& method
)
840 StoreEntry
*e
= NULL
;
841 MemObject
*mem
= NULL
;
842 debugs(20, 3, "storeCreateEntry: '" << url
<< "'");
844 e
= new StoreEntry(url
, log_url
);
845 e
->lock_count
= 1; /* Note lock here w/o calling storeLock() */
847 mem
->method
= method
;
849 if (neighbors_do_private_keys
|| !flags
.hierarchical
)
854 if (flags
.cachable
) {
855 EBIT_SET(e
->flags
, ENTRY_CACHABLE
);
856 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
858 /* StoreEntry::releaseRequest() clears ENTRY_CACHABLE */
862 e
->store_status
= STORE_PENDING
;
863 e
->setMemStatus(NOT_IN_MEMORY
);
865 e
->lastref
= squid_curtime
;
866 e
->timestamp
= -1; /* set in StoreEntry::timestampsSet() */
867 e
->ping_status
= PING_NONE
;
868 EBIT_SET(e
->flags
, ENTRY_VALIDATED
);
872 /* Mark object as expired */
874 StoreEntry::expireNow()
876 debugs(20, 3, "StoreEntry::expireNow: '" << getMD5Text() << "'");
877 expires
= squid_curtime
;
881 storeWriteComplete (void *data
, StoreIOBuffer wroteBuffer
)
883 PROF_start(storeWriteComplete
);
884 StoreEntry
*e
= (StoreEntry
*)data
;
886 if (EBIT_TEST(e
->flags
, DELAY_SENDING
)) {
887 PROF_stop(storeWriteComplete
);
892 PROF_stop(storeWriteComplete
);
896 StoreEntry::write (StoreIOBuffer writeBuffer
)
898 assert(mem_obj
!= NULL
);
899 /* This assert will change when we teach the store to update */
900 PROF_start(StoreEntry_write
);
901 assert(store_status
== STORE_PENDING
);
903 debugs(20, 5, "storeWrite: writing " << writeBuffer
.length
<< " bytes for '" << getMD5Text() << "'");
904 PROF_stop(StoreEntry_write
);
905 storeGetMemSpace(writeBuffer
.length
);
906 mem_obj
->write (writeBuffer
, storeWriteComplete
, this);
909 /* Append incoming data from a primary server to an entry. */
911 StoreEntry::append(char const *buf
, int len
)
913 assert(mem_obj
!= NULL
);
915 assert(store_status
== STORE_PENDING
);
917 StoreIOBuffer tempBuffer
;
918 tempBuffer
.data
= (char *)buf
;
919 tempBuffer
.length
= len
;
921 * XXX sigh, offset might be < 0 here, but it gets "corrected"
922 * later. This offset crap is such a mess.
924 tempBuffer
.offset
= mem_obj
->endOffset() - (getReply() ? getReply()->hdr_sz
: 0);
929 storeAppendPrintf(StoreEntry
* e
, const char *fmt
,...)
934 storeAppendVPrintf(e
, fmt
, args
);
938 /* used be storeAppendPrintf and Packer */
940 storeAppendVPrintf(StoreEntry
* e
, const char *fmt
, va_list vargs
)
942 LOCAL_ARRAY(char, buf
, 4096);
944 vsnprintf(buf
, 4096, fmt
, vargs
);
945 e
->append(buf
, strlen(buf
));
948 struct _store_check_cachable_hist
{
952 int not_entry_cachable
;
953 int wrong_content_length
;
958 int too_many_open_files
;
959 int too_many_open_fds
;
965 } store_check_cachable_hist
;
968 storeTooManyDiskFilesOpen(void)
970 if (Config
.max_open_disk_fds
== 0)
973 if (store_open_disk_fd
> Config
.max_open_disk_fds
)
980 StoreEntry::checkTooSmall()
982 if (EBIT_TEST(flags
, ENTRY_SPECIAL
))
985 if (STORE_OK
== store_status
)
986 if (mem_obj
->object_sz
< 0 ||
987 mem_obj
->object_sz
< Config
.Store
.minObjectSize
)
989 if (getReply()->content_length
> -1)
990 if (getReply()->content_length
< Config
.Store
.minObjectSize
)
995 // TODO: remove checks already performed by swapoutPossible()
996 // TODO: move "too many open..." checks outside -- we are called too early/late
998 StoreEntry::checkCachable()
1000 #if CACHE_ALL_METHODS
1002 if (mem_obj
->method
!= Http::METHOD_GET
) {
1003 debugs(20, 2, "StoreEntry::checkCachable: NO: non-GET method");
1004 ++store_check_cachable_hist
.no
.non_get
;
1007 if (store_status
== STORE_OK
&& EBIT_TEST(flags
, ENTRY_BAD_LENGTH
)) {
1008 debugs(20, 2, "StoreEntry::checkCachable: NO: wrong content-length");
1009 ++store_check_cachable_hist
.no
.wrong_content_length
;
1010 } else if (!EBIT_TEST(flags
, ENTRY_CACHABLE
)) {
1011 debugs(20, 2, "StoreEntry::checkCachable: NO: not cachable");
1012 ++store_check_cachable_hist
.no
.not_entry_cachable
;
1013 } else if (EBIT_TEST(flags
, ENTRY_NEGCACHED
)) {
1014 debugs(20, 3, "StoreEntry::checkCachable: NO: negative cached");
1015 ++store_check_cachable_hist
.no
.negative_cached
;
1016 return 0; /* avoid release call below */
1017 } else if ((getReply()->content_length
> 0 &&
1018 getReply()->content_length
> store_maxobjsize
) ||
1019 mem_obj
->endOffset() > store_maxobjsize
) {
1020 debugs(20, 2, "StoreEntry::checkCachable: NO: too big");
1021 ++store_check_cachable_hist
.no
.too_big
;
1022 } else if (checkTooSmall()) {
1023 debugs(20, 2, "StoreEntry::checkCachable: NO: too small");
1024 ++store_check_cachable_hist
.no
.too_small
;
1025 } else if (EBIT_TEST(flags
, KEY_PRIVATE
)) {
1026 debugs(20, 3, "StoreEntry::checkCachable: NO: private key");
1027 ++store_check_cachable_hist
.no
.private_key
;
1028 } else if (swap_status
!= SWAPOUT_NONE
) {
1030 * here we checked the swap_status because the remaining
1031 * cases are only relevant only if we haven't started swapping
1032 * out the object yet.
1035 } else if (storeTooManyDiskFilesOpen()) {
1036 debugs(20, 2, "StoreEntry::checkCachable: NO: too many disk files open");
1037 ++store_check_cachable_hist
.no
.too_many_open_files
;
1038 } else if (fdNFree() < RESERVED_FD
) {
1039 debugs(20, 2, "StoreEntry::checkCachable: NO: too many FD's open");
1040 ++store_check_cachable_hist
.no
.too_many_open_fds
;
1042 ++store_check_cachable_hist
.yes
.Default
;
1047 /* StoreEntry::releaseRequest() cleared ENTRY_CACHABLE */
1052 storeCheckCachableStats(StoreEntry
*sentry
)
1054 storeAppendPrintf(sentry
, "Category\t Count\n");
1056 #if CACHE_ALL_METHODS
1058 storeAppendPrintf(sentry
, "no.non_get\t%d\n",
1059 store_check_cachable_hist
.no
.non_get
);
1062 storeAppendPrintf(sentry
, "no.not_entry_cachable\t%d\n",
1063 store_check_cachable_hist
.no
.not_entry_cachable
);
1064 storeAppendPrintf(sentry
, "no.wrong_content_length\t%d\n",
1065 store_check_cachable_hist
.no
.wrong_content_length
);
1066 storeAppendPrintf(sentry
, "no.negative_cached\t%d\n",
1067 store_check_cachable_hist
.no
.negative_cached
);
1068 storeAppendPrintf(sentry
, "no.too_big\t%d\n",
1069 store_check_cachable_hist
.no
.too_big
);
1070 storeAppendPrintf(sentry
, "no.too_small\t%d\n",
1071 store_check_cachable_hist
.no
.too_small
);
1072 storeAppendPrintf(sentry
, "no.private_key\t%d\n",
1073 store_check_cachable_hist
.no
.private_key
);
1074 storeAppendPrintf(sentry
, "no.too_many_open_files\t%d\n",
1075 store_check_cachable_hist
.no
.too_many_open_files
);
1076 storeAppendPrintf(sentry
, "no.too_many_open_fds\t%d\n",
1077 store_check_cachable_hist
.no
.too_many_open_fds
);
1078 storeAppendPrintf(sentry
, "yes.default\t%d\n",
1079 store_check_cachable_hist
.yes
.Default
);
1083 StoreEntry::complete()
1085 debugs(20, 3, "storeComplete: '" << getMD5Text() << "'");
1087 if (store_status
!= STORE_PENDING
) {
1089 * if we're not STORE_PENDING, then probably we got aborted
1090 * and there should be NO clients on this entry
1092 assert(EBIT_TEST(flags
, ENTRY_ABORTED
));
1093 assert(mem_obj
->nclients
== 0);
1097 /* This is suspect: mem obj offsets include the headers. do we adjust for that
1098 * in use of object_sz?
1100 mem_obj
->object_sz
= mem_obj
->endOffset();
1102 store_status
= STORE_OK
;
1104 assert(mem_status
== NOT_IN_MEMORY
);
1106 if (!validLength()) {
1107 EBIT_SET(flags
, ENTRY_BAD_LENGTH
);
1111 #if USE_CACHE_DIGESTS
1112 if (mem_obj
->request
)
1113 mem_obj
->request
->hier
.store_complete_stop
= current_time
;
1117 * We used to call invokeHandlers, then storeSwapOut. However,
1118 * Madhukar Reddy <myreddy@persistence.com> reported that
1119 * responses without content length would sometimes get released
1120 * in client_side, thinking that the response is incomplete.
1126 * Someone wants to abort this transfer. Set the reason in the
1127 * request structure, call the server-side callback and mark the
1128 * entry for releasing
1133 ++statCounter
.aborted_requests
;
1134 assert(store_status
== STORE_PENDING
);
1135 assert(mem_obj
!= NULL
);
1136 debugs(20, 6, "storeAbort: " << getMD5Text());
1138 lock(); /* lock while aborting */
1143 EBIT_SET(flags
, ENTRY_ABORTED
);
1145 setMemStatus(NOT_IN_MEMORY
);
1147 store_status
= STORE_OK
;
1149 /* Notify the server side */
1153 * Should we check abort.data for validity?
1155 if (mem_obj
->abort
.callback
) {
1156 if (!cbdataReferenceValid(mem_obj
->abort
.data
))
1157 debugs(20, DBG_IMPORTANT
,HERE
<< "queueing event when abort.data is not valid");
1158 eventAdd("mem_obj->abort.callback",
1159 mem_obj
->abort
.callback
,
1160 mem_obj
->abort
.data
,
1166 /* XXX Should we reverse these two, so that there is no
1167 * unneeded disk swapping triggered?
1169 /* Notify the client side */
1172 // abort swap out, invalidating what was created so far (release follows)
1173 swapOutFileClose(StoreIOState::writerGone
);
1175 unlock(); /* unlock */
1179 * Clear Memory storage to accommodate the given object len
1182 storeGetMemSpace(int size
)
1184 PROF_start(storeGetMemSpace
);
1185 StoreEntry
*e
= NULL
;
1187 static time_t last_check
= 0;
1188 size_t pages_needed
;
1189 RemovalPurgeWalker
*walker
;
1191 if (squid_curtime
== last_check
) {
1192 PROF_stop(storeGetMemSpace
);
1196 last_check
= squid_curtime
;
1198 pages_needed
= (size
+ SM_PAGE_SIZE
-1) / SM_PAGE_SIZE
;
1200 if (mem_node::InUseCount() + pages_needed
< store_pages_max
) {
1201 PROF_stop(storeGetMemSpace
);
1205 debugs(20, 2, "storeGetMemSpace: Starting, need " << pages_needed
<<
1208 /* XXX what to set as max_scan here? */
1209 walker
= mem_policy
->PurgeInit(mem_policy
, 100000);
1211 while ((e
= walker
->Next(walker
))) {
1215 if (mem_node::InUseCount() + pages_needed
< store_pages_max
)
1219 walker
->Done(walker
);
1220 debugs(20, 3, "storeGetMemSpace stats:");
1221 debugs(20, 3, " " << std::setw(6) << hot_obj_count
<< " HOT objects");
1222 debugs(20, 3, " " << std::setw(6) << released
<< " were released");
1223 PROF_stop(storeGetMemSpace
);
1226 /* thunk through to Store::Root().maintain(). Note that this would be better still
1227 * if registered against the root store itself, but that requires more complex
1228 * update logic - bigger fish to fry first. Long term each store when
1229 * it becomes active will self register
1232 Store::Maintain(void *notused
)
1234 Store::Root().maintain();
1236 /* Reregister a maintain event .. */
1237 eventAdd("MaintainSwapSpace", Maintain
, NULL
, 1.0, 1);
1241 /* The maximum objects to scan for maintain storage space */
1242 #define MAINTAIN_MAX_SCAN 1024
1243 #define MAINTAIN_MAX_REMOVE 64
1246 * This routine is to be called by main loop in main.c.
1247 * It removes expired objects on only one bucket for each time called.
1249 * This should get called 1/s from main().
1252 StoreController::maintain()
1254 static time_t last_warn_time
= 0;
1256 PROF_start(storeMaintainSwapSpace
);
1257 swapDir
->maintain();
1259 /* this should be emitted by the oversize dir, not globally */
1261 if (Store::Root().currentSize() > Store::Root().maxSize()) {
1262 if (squid_curtime
- last_warn_time
> 10) {
1263 debugs(20, DBG_CRITICAL
, "WARNING: Disk space over limit: "
1264 << Store::Root().currentSize() / 1024.0 << " KB > "
1265 << (Store::Root().maxSize() >> 10) << " KB");
1266 last_warn_time
= squid_curtime
;
1270 PROF_stop(storeMaintainSwapSpace
);
1273 /* release an object from a cache */
1275 StoreEntry::release()
1277 PROF_start(storeRelease
);
1278 debugs(20, 3, "storeRelease: Releasing: '" << getMD5Text() << "'");
1279 /* If, for any reason we can't discard this object because of an
1280 * outstanding request, mark it for pending release */
1284 debugs(20, 3, "storeRelease: Only setting RELEASE_REQUEST bit");
1286 PROF_stop(storeRelease
);
1290 if (StoreController::store_dirs_rebuilding
&& swap_filen
> -1) {
1296 if (swap_filen
> -1) {
1298 * Fake a call to StoreEntry->lock() When rebuilding is done,
1299 * we'll just call StoreEntry->unlock() on these.
1303 LateReleaseStack
.push_back(this);
1305 destroyStoreEntry(static_cast<hash_link
*>(this));
1306 // "this" is no longer valid
1309 PROF_stop(storeRelease
);
1313 storeLog(STORE_LOG_RELEASE
, this);
1315 if (swap_filen
> -1) {
1316 // log before unlink() below clears swap_filen
1317 if (!EBIT_TEST(flags
, KEY_PRIVATE
))
1318 storeDirSwapLog(this, SWAP_LOG_DEL
);
1323 setMemStatus(NOT_IN_MEMORY
);
1324 destroyStoreEntry(static_cast<hash_link
*>(this));
1325 PROF_stop(storeRelease
);
1329 storeLateRelease(void *unused
)
1335 if (StoreController::store_dirs_rebuilding
) {
1336 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 1.0, 1);
1340 for (i
= 0; i
< 10; ++i
) {
1341 e
= LateReleaseStack
.count
? LateReleaseStack
.pop() : NULL
;
1345 debugs(20, DBG_IMPORTANT
, "storeLateRelease: released " << n
<< " objects");
1353 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 0.0, 1);
1356 /* return 1 if a store entry is locked */
1358 StoreEntry::locked() const
1363 if (swap_status
== SWAPOUT_WRITING
)
1366 if (store_status
== STORE_PENDING
)
1370 * SPECIAL, PUBLIC entries should be "locked"
1372 if (EBIT_TEST(flags
, ENTRY_SPECIAL
))
1373 if (!EBIT_TEST(flags
, KEY_PRIVATE
))
1380 StoreEntry::validLength() const
1383 const HttpReply
*reply
;
1384 assert(mem_obj
!= NULL
);
1386 debugs(20, 3, "storeEntryValidLength: Checking '" << getMD5Text() << "'");
1387 debugs(20, 5, "storeEntryValidLength: object_len = " <<
1389 debugs(20, 5, "storeEntryValidLength: hdr_sz = " << reply
->hdr_sz
);
1390 debugs(20, 5, "storeEntryValidLength: content_length = " << reply
->content_length
);
1392 if (reply
->content_length
< 0) {
1393 debugs(20, 5, "storeEntryValidLength: Unspecified content length: " << getMD5Text());
1397 if (reply
->hdr_sz
== 0) {
1398 debugs(20, 5, "storeEntryValidLength: Zero header size: " << getMD5Text());
1402 if (mem_obj
->method
== Http::METHOD_HEAD
) {
1403 debugs(20, 5, "storeEntryValidLength: HEAD request: " << getMD5Text());
1407 if (reply
->sline
.status() == Http::scNotModified
)
1410 if (reply
->sline
.status() == Http::scNoContent
)
1413 diff
= reply
->hdr_sz
+ reply
->content_length
- objectLen();
1418 debugs(20, 3, "storeEntryValidLength: " << (diff
< 0 ? -diff
: diff
) << " bytes too " << (diff
< 0 ? "big" : "small") <<"; '" << getMD5Text() << "'" );
1424 storeRegisterWithCacheManager(void)
1426 Mgr::RegisterAction("storedir", "Store Directory Stats", Store::Stats
, 0, 1);
1427 Mgr::RegisterAction("store_io", "Store IO Interface Stats", &Mgr::StoreIoAction::Create
, 0, 1);
1428 Mgr::RegisterAction("store_check_cachable_stats", "storeCheckCachable() Stats",
1429 storeCheckCachableStats
, 0, 1);
1436 mem_policy
= createRemovalPolicy(Config
.memPolicy
);
1439 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 1.0, 1);
1440 Store::Root().init();
1441 storeRebuildStart();
1443 storeRegisterWithCacheManager();
1447 storeConfigure(void)
1449 store_swap_high
= (long) (((float) Store::Root().maxSize() *
1450 (float) Config
.Swap
.highWaterMark
) / (float) 100);
1451 store_swap_low
= (long) (((float) Store::Root().maxSize() *
1452 (float) Config
.Swap
.lowWaterMark
) / (float) 100);
1453 store_pages_max
= Config
.memMaxSize
/ sizeof(mem_node
);
1457 StoreEntry::memoryCachable() const
1459 if (mem_obj
== NULL
)
1462 if (mem_obj
->data_hdr
.size() == 0)
1465 if (mem_obj
->inmem_lo
!= 0)
1468 if (!Config
.onoff
.memory_cache_first
&& swap_status
== SWAPOUT_DONE
&& refcount
== 1)
1475 StoreEntry::checkNegativeHit() const
1477 if (!EBIT_TEST(flags
, ENTRY_NEGCACHED
))
1480 if (expires
<= squid_curtime
)
1483 if (store_status
!= STORE_OK
)
1490 * Set object for negative caching.
1491 * Preserves any expiry information given by the server.
1492 * In absence of proper expiry info it will set to expire immediately,
1493 * or with HTTP-violations enabled the configured negative-TTL is observed
1496 StoreEntry::negativeCache()
1498 // XXX: should make the default for expires 0 instead of -1
1499 // so we can distinguish "Expires: -1" from nothing.
1501 #if USE_HTTP_VIOLATIONS
1502 expires
= squid_curtime
+ Config
.negativeTtl
;
1504 expires
= squid_curtime
;
1506 EBIT_SET(flags
, ENTRY_NEGCACHED
);
1510 storeFreeMemory(void)
1513 #if USE_CACHE_DIGESTS
1516 cacheDigestDestroy(store_digest
);
1520 store_digest
= NULL
;
1524 expiresMoreThan(time_t expires
, time_t when
)
1526 if (expires
< 0) /* No Expires given */
1529 return (expires
> (squid_curtime
+ when
));
1533 StoreEntry::validToSend() const
1535 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
1538 if (EBIT_TEST(flags
, ENTRY_NEGCACHED
))
1539 if (expires
<= squid_curtime
)
1542 if (EBIT_TEST(flags
, ENTRY_ABORTED
))
1549 StoreEntry::timestampsSet()
1551 const HttpReply
*reply
= getReply();
1552 time_t served_date
= reply
->date
;
1553 int age
= reply
->header
.getInt(HDR_AGE
);
1554 /* Compute the timestamp, mimicking RFC2616 section 13.2.3. */
1555 /* make sure that 0 <= served_date <= squid_curtime */
1557 if (served_date
< 0 || served_date
> squid_curtime
)
1558 served_date
= squid_curtime
;
1561 * If the returned Date: is more than 24 hours older than
1562 * the squid_curtime, then one of us needs to use NTP to set our
1563 * clock. We'll pretend that our clock is right.
1565 else if (served_date
< (squid_curtime
- 24 * 60 * 60) )
1566 served_date
= squid_curtime
;
1569 * Compensate with Age header if origin server clock is ahead
1570 * of us and there is a cache in between us and the origin
1571 * server. But DONT compensate if the age value is larger than
1572 * squid_curtime because it results in a negative served_date.
1574 if (age
> squid_curtime
- served_date
)
1575 if (squid_curtime
> age
)
1576 served_date
= squid_curtime
- age
;
1578 // compensate for Squid-to-server and server-to-Squid delays
1579 if (mem_obj
&& mem_obj
->request
) {
1580 const time_t request_sent
=
1581 mem_obj
->request
->hier
.peer_http_request_sent
.tv_sec
;
1582 if (0 < request_sent
&& request_sent
< squid_curtime
)
1583 served_date
-= (squid_curtime
- request_sent
);
1586 if (reply
->expires
> 0 && reply
->date
> -1)
1587 expires
= served_date
+ (reply
->expires
- reply
->date
);
1589 expires
= reply
->expires
;
1591 lastmod
= reply
->last_modified
;
1593 timestamp
= served_date
;
1597 StoreEntry::registerAbort(STABH
* cb
, void *data
)
1600 assert(mem_obj
->abort
.callback
== NULL
);
1601 mem_obj
->abort
.callback
= cb
;
1602 mem_obj
->abort
.data
= cbdataReference(data
);
1606 StoreEntry::unregisterAbort()
1609 if (mem_obj
->abort
.callback
) {
1610 mem_obj
->abort
.callback
= NULL
;
1611 cbdataReferenceDone(mem_obj
->abort
.data
);
1616 StoreEntry::dump(int l
) const
1618 debugs(20, l
, "StoreEntry->key: " << getMD5Text());
1619 debugs(20, l
, "StoreEntry->next: " << next
);
1620 debugs(20, l
, "StoreEntry->mem_obj: " << mem_obj
);
1621 debugs(20, l
, "StoreEntry->timestamp: " << timestamp
);
1622 debugs(20, l
, "StoreEntry->lastref: " << lastref
);
1623 debugs(20, l
, "StoreEntry->expires: " << expires
);
1624 debugs(20, l
, "StoreEntry->lastmod: " << lastmod
);
1625 debugs(20, l
, "StoreEntry->swap_file_sz: " << swap_file_sz
);
1626 debugs(20, l
, "StoreEntry->refcount: " << refcount
);
1627 debugs(20, l
, "StoreEntry->flags: " << storeEntryFlags(this));
1628 debugs(20, l
, "StoreEntry->swap_dirn: " << swap_dirn
);
1629 debugs(20, l
, "StoreEntry->swap_filen: " << swap_filen
);
1630 debugs(20, l
, "StoreEntry->lock_count: " << lock_count
);
1631 debugs(20, l
, "StoreEntry->mem_status: " << mem_status
);
1632 debugs(20, l
, "StoreEntry->ping_status: " << ping_status
);
1633 debugs(20, l
, "StoreEntry->store_status: " << store_status
);
1634 debugs(20, l
, "StoreEntry->swap_status: " << swap_status
);
1638 * NOTE, this function assumes only two mem states
1641 StoreEntry::setMemStatus(mem_status_t new_status
)
1643 if (new_status
== mem_status
)
1646 // are we using a shared memory cache?
1647 if (Config
.memShared
&& IamWorkerProcess()) {
1648 // enumerate calling cases if shared memory is enabled
1649 assert(new_status
!= IN_MEMORY
|| EBIT_TEST(flags
, ENTRY_SPECIAL
));
1650 // This method was designed to update replacement policy, not to
1651 // actually purge something from the memory cache (TODO: rename?).
1652 // Shared memory cache does not have a policy that needs updates.
1653 mem_status
= new_status
;
1657 assert(mem_obj
!= NULL
);
1659 if (new_status
== IN_MEMORY
) {
1660 assert(mem_obj
->inmem_lo
== 0);
1662 if (EBIT_TEST(flags
, ENTRY_SPECIAL
)) {
1663 debugs(20, 4, "StoreEntry::setMemStatus: not inserting special " << mem_obj
->url
<< " into policy");
1665 mem_policy
->Add(mem_policy
, this, &mem_obj
->repl
);
1666 debugs(20, 4, "StoreEntry::setMemStatus: inserted mem node " << mem_obj
->url
<< " key: " << getMD5Text());
1669 ++hot_obj_count
; // TODO: maintain for the shared hot cache as well
1671 if (EBIT_TEST(flags
, ENTRY_SPECIAL
)) {
1672 debugs(20, 4, "StoreEntry::setMemStatus: special entry " << mem_obj
->url
);
1674 mem_policy
->Remove(mem_policy
, this, &mem_obj
->repl
);
1675 debugs(20, 4, "StoreEntry::setMemStatus: removed mem node " << mem_obj
->url
);
1681 mem_status
= new_status
;
1685 StoreEntry::url() const
1688 return "[null_entry]";
1689 else if (mem_obj
== NULL
)
1690 return "[null_mem_obj]";
1692 return mem_obj
->url
;
1696 StoreEntry::createMemObject(const char *aUrl
, const char *aLogUrl
)
1698 debugs(20, 3, "A mem_obj create attempted using : " << aUrl
);
1703 if (hidden_mem_obj
) {
1704 debugs(20, 3, HERE
<< "restoring " << hidden_mem_obj
);
1705 mem_obj
= hidden_mem_obj
;
1706 hidden_mem_obj
= NULL
;
1707 mem_obj
->resetUrls(aUrl
, aLogUrl
);
1711 mem_obj
= new MemObject(aUrl
, aLogUrl
);
1714 /* this just sets DELAY_SENDING */
1716 StoreEntry::buffer()
1718 EBIT_SET(flags
, DELAY_SENDING
);
1721 /* this just clears DELAY_SENDING and Invokes the handlers */
1725 if (EBIT_TEST(flags
, DELAY_SENDING
)) {
1726 EBIT_CLR(flags
, DELAY_SENDING
);
1732 StoreEntry::objectLen() const
1734 assert(mem_obj
!= NULL
);
1735 return mem_obj
->object_sz
;
1739 StoreEntry::contentLen() const
1741 assert(mem_obj
!= NULL
);
1742 assert(getReply() != NULL
);
1743 return objectLen() - getReply()->hdr_sz
;
1747 StoreEntry::getReply () const
1749 if (NULL
== mem_obj
)
1752 return mem_obj
->getReply();
1759 debugs(20, 3, "StoreEntry::reset: " << url());
1761 HttpReply
*rep
= (HttpReply
*) getReply(); // bypass const
1763 expires
= lastmod
= timestamp
= -1;
1769 * This routine calls the SETUP routine for each fs type.
1770 * I don't know where the best place for this is, and I'm not going to shuffle
1771 * around large chunks of code right now (that can be done once its working.)
1780 * called to add another store removal policy module
1783 storeReplAdd(const char *type
, REMOVALPOLICYCREATE
* create
)
1787 /* find the number of currently known repl types */
1788 for (i
= 0; storerepl_list
&& storerepl_list
[i
].typestr
; ++i
) {
1789 if (strcmp(storerepl_list
[i
].typestr
, type
) == 0) {
1790 debugs(20, DBG_IMPORTANT
, "WARNING: Trying to load store replacement policy " << type
<< " twice.");
1795 /* add the new type */
1796 storerepl_list
= static_cast<storerepl_entry_t
*>(xrealloc(storerepl_list
, (i
+ 2) * sizeof(storerepl_entry_t
)));
1798 memset(&storerepl_list
[i
+ 1], 0, sizeof(storerepl_entry_t
));
1800 storerepl_list
[i
].typestr
= type
;
1802 storerepl_list
[i
].create
= create
;
1806 * Create a removal policy instance
1809 createRemovalPolicy(RemovalPolicySettings
* settings
)
1811 storerepl_entry_t
*r
;
1813 for (r
= storerepl_list
; r
&& r
->typestr
; ++r
) {
1814 if (strcmp(r
->typestr
, settings
->type
) == 0)
1815 return r
->create(settings
->args
);
1818 debugs(20, DBG_IMPORTANT
, "ERROR: Unknown policy " << settings
->type
);
1819 debugs(20, DBG_IMPORTANT
, "ERROR: Be sure to have set cache_replacement_policy");
1820 debugs(20, DBG_IMPORTANT
, "ERROR: and memory_replacement_policy in squid.conf!");
1821 fatalf("ERROR: Unknown policy %s\n", settings
->type
);
1822 return NULL
; /* NOTREACHED */
1827 storeSwapFileNumberSet(StoreEntry
* e
, sfileno filn
)
1829 if (e
->swap_file_number
== filn
)
1834 storeDirMapBitReset(e
->swap_file_number
);
1835 storeDirLRUDelete(e
);
1836 e
->swap_file_number
= -1;
1838 assert(-1 == e
->swap_file_number
);
1839 storeDirMapBitSet(e
->swap_file_number
= filn
);
1847 * Replace a store entry with
1848 * a new reply. This eats the reply.
1851 StoreEntry::replaceHttpReply(HttpReply
*rep
, bool andStartWriting
)
1853 debugs(20, 3, "StoreEntry::replaceHttpReply: " << url());
1856 debugs(20, DBG_CRITICAL
, "Attempt to replace object with no in-memory representation");
1860 mem_obj
->replaceHttpReply(rep
);
1862 if (andStartWriting
)
1867 StoreEntry::startWriting()
1871 /* TODO: when we store headers serparately remove the header portion */
1872 /* TODO: mark the length of the headers ? */
1873 /* We ONLY want the headers */
1874 packerToStoreInit(&p
, this);
1879 const HttpReply
*rep
= getReply();
1882 rep
->packHeadersInto(&p
);
1883 mem_obj
->markEndOfReplyHeaders();
1885 rep
->body
.packInto(&p
);
1891 StoreEntry::getSerialisedMetaData()
1893 StoreMeta
*tlv_list
= storeSwapMetaBuild(this);
1895 char *result
= storeSwapMetaPack(tlv_list
, &swap_hdr_sz
);
1896 storeSwapTLVFree(tlv_list
);
1897 assert (swap_hdr_sz
>= 0);
1898 mem_obj
->swap_hdr_sz
= (size_t) swap_hdr_sz
;
1903 StoreEntry::trimMemory(const bool preserveSwappable
)
1907 * Bug #1943. We must not let go any data for IN_MEMORY
1908 * objects. We have to wait until the mem_status changes.
1910 if (mem_status
== IN_MEMORY
)
1913 if (EBIT_TEST(flags
, ENTRY_SPECIAL
))
1914 return; // cannot trim because we do not load them again
1916 if (!preserveSwappable
) {
1917 if (mem_obj
->policyLowestOffsetToKeep(0) == 0) {
1922 * Its not swap-able, and we're about to delete a chunk,
1923 * so we must make it PRIVATE. This is tricky/ugly because
1924 * for the most part, we treat swapable == cachable here.
1927 mem_obj
->trimUnSwappable ();
1929 mem_obj
->trimSwappable ();
1934 StoreEntry::modifiedSince(HttpRequest
* request
) const
1937 time_t mod_time
= lastmod
;
1940 mod_time
= timestamp
;
1942 debugs(88, 3, "modifiedSince: '" << url() << "'");
1944 debugs(88, 3, "modifiedSince: mod_time = " << mod_time
);
1949 /* Find size of the object */
1950 object_length
= getReply()->content_length
;
1952 if (object_length
< 0)
1953 object_length
= contentLen();
1955 if (mod_time
> request
->ims
) {
1956 debugs(88, 3, "--> YES: entry newer than client");
1958 } else if (mod_time
< request
->ims
) {
1959 debugs(88, 3, "--> NO: entry older than client");
1961 } else if (request
->imslen
< 0) {
1962 debugs(88, 3, "--> NO: same LMT, no client length");
1964 } else if (request
->imslen
== object_length
) {
1965 debugs(88, 3, "--> NO: same LMT, same length");
1968 debugs(88, 3, "--> YES: same LMT, different length");
1974 StoreEntry::hasEtag(ETag
&etag
) const
1976 if (const HttpReply
*reply
= getReply()) {
1977 etag
= reply
->header
.getETag(HDR_ETAG
);
1985 StoreEntry::hasIfMatchEtag(const HttpRequest
&request
) const
1987 const String reqETags
= request
.header
.getList(HDR_IF_MATCH
);
1988 return hasOneOfEtags(reqETags
, false);
1992 StoreEntry::hasIfNoneMatchEtag(const HttpRequest
&request
) const
1994 const String reqETags
= request
.header
.getList(HDR_IF_NONE_MATCH
);
1995 // weak comparison is allowed only for HEAD or full-body GET requests
1996 const bool allowWeakMatch
= !request
.flags
.isRanged
&&
1997 (request
.method
== Http::METHOD_GET
|| request
.method
== Http::METHOD_HEAD
);
1998 return hasOneOfEtags(reqETags
, allowWeakMatch
);
2001 /// whether at least one of the request ETags matches entity ETag
2003 StoreEntry::hasOneOfEtags(const String
&reqETags
, const bool allowWeakMatch
) const
2005 const ETag repETag
= getReply()->header
.getETag(HDR_ETAG
);
2007 return strListIsMember(&reqETags
, "*", ',');
2009 bool matched
= false;
2010 const char *pos
= NULL
;
2013 while (!matched
&& strListGetItem(&reqETags
, ',', &item
, &ilen
, &pos
)) {
2014 if (!strncmp(item
, "*", ilen
))
2018 str
.append(item
, ilen
);
2020 if (etagParseInit(&reqETag
, str
.termedBuf())) {
2021 matched
= allowWeakMatch
? etagIsWeakEqual(repETag
, reqETag
) :
2022 etagIsStrongEqual(repETag
, reqETag
);
2030 StoreEntry::store() const
2032 assert(0 <= swap_dirn
&& swap_dirn
< Config
.cacheSwap
.n_configured
);
2033 return INDEXSD(swap_dirn
);
2037 StoreEntry::unlink()
2039 store()->unlink(*this); // implies disconnect()
2042 swap_status
= SWAPOUT_NONE
;
2046 * return true if the entry is in a state where
2047 * it can accept more data (ie with write() method)
2050 StoreEntry::isAccepting() const
2052 if (STORE_PENDING
!= store_status
)
2055 if (EBIT_TEST(flags
, ENTRY_ABORTED
))
2061 std::ostream
&operator <<(std::ostream
&os
, const StoreEntry
&e
)
2063 return os
<< e
.swap_filen
<< '@' << e
.swap_dirn
<< '=' <<
2064 e
.mem_status
<< '/' << e
.ping_status
<< '/' << e
.store_status
<< '/' <<
2068 /* NullStoreEntry */
2070 NullStoreEntry
NullStoreEntry::_instance
;
2073 NullStoreEntry::getInstance()
2079 NullStoreEntry::getMD5Text() const
2085 NullStoreEntry::operator delete(void*)
2087 fatal ("Attempt to delete NullStoreEntry\n");
2091 NullStoreEntry::getSerialisedMetaData()
2097 #include "Store.cci"