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"
54 #include "StatCounters.h"
57 #include "store_digest.h"
58 #include "store_key_md5.h"
59 #include "store_key_md5.h"
60 #include "store_log.h"
61 #include "store_rebuild.h"
62 #include "StoreClient.h"
63 #include "StoreIOState.h"
64 #include "StoreMeta.h"
66 #include "swap_log_op.h"
70 #include "DelayPools.h"
78 #define REBUILD_TIMESTAMP_DELTA_MAX 2
80 #define STORE_IN_MEM_BUCKETS (229)
82 /** \todo Convert these string constants to enum string-arrays generated */
84 const char *memStatusStr
[] = {
89 const char *pingStatusStr
[] = {
95 const char *storeStatusStr
[] = {
100 const char *swapStatusStr
[] = {
107 * This defines an repl type
110 typedef struct _storerepl_entry storerepl_entry_t
;
112 struct _storerepl_entry
{
114 REMOVALPOLICYCREATE
*create
;
117 static storerepl_entry_t
*storerepl_list
= NULL
;
120 * local function prototypes
122 static int getKeyCounter(void);
123 static OBJH storeCheckCachableStats
;
124 static EVH storeLateRelease
;
129 static std::stack
<StoreEntry
*> LateReleaseStack
;
130 MemAllocator
*StoreEntry::pool
= NULL
;
132 StorePointer
Store::CurrentRoot
= NULL
;
135 Store::Root(Store
* aRoot
)
141 Store::Root(StorePointer aRoot
)
143 Root(aRoot
.getRaw());
147 Store::Stats(StoreEntry
* output
)
150 Root().stat(*output
);
166 Store::unlink (StoreEntry
&anEntry
)
168 fatal("Store::unlink on invalid Store\n");
172 StoreEntry::operator new (size_t bytecount
)
174 assert (bytecount
== sizeof (StoreEntry
));
177 pool
= memPoolCreate ("StoreEntry", bytecount
);
178 pool
->setChunkSize(2048 * 1024);
181 return pool
->alloc();
185 StoreEntry::operator delete (void *address
)
187 pool
->freeOne(address
);
191 StoreEntry::makePublic()
193 /* This object can be cached for a long time */
195 if (!EBIT_TEST(flags
, RELEASE_REQUEST
))
200 StoreEntry::makePrivate()
202 /* This object should never be cached at all */
204 releaseRequest(); /* delete object when not used */
208 StoreEntry::cacheNegatively()
210 /* This object may be negatively cached */
216 StoreEntry::inUseCount()
220 return pool
->getInUseCount();
224 StoreEntry::getMD5Text() const
226 return storeKeyText((const cache_key
*)key
);
232 StoreEntry::DeferReader(void *theContext
, CommRead
const &aRead
)
234 StoreEntry
*anEntry
= (StoreEntry
*)theContext
;
235 anEntry
->delayAwareRead(aRead
.conn
,
242 StoreEntry::delayAwareRead(const Comm::ConnectionPointer
&conn
, char *buf
, int len
, AsyncCall::Pointer callback
)
244 size_t amountToRead
= bytesWanted(Range
<size_t>(0, len
));
245 /* sketch: readdeferer* = getdeferer.
246 * ->deferRead (fd, buf, len, callback, DelayAwareRead, this)
249 if (amountToRead
== 0) {
251 /* read ahead limit */
252 /* Perhaps these two calls should both live in MemObject */
254 if (!mem_obj
->readAheadPolicyCanRead()) {
256 mem_obj
->delayRead(DeferredRead(DeferReader
, this, CommRead(conn
, buf
, len
, callback
)));
262 mem_obj
->mostBytesAllowed().delayRead(DeferredRead(DeferReader
, this, CommRead(conn
, buf
, len
, callback
)));
269 if (fd_table
[conn
->fd
].closing()) {
270 // Readers must have closing callbacks if they want to be notified. No
271 // readers appeared to care around 2009/12/14 as they skipped reading
272 // for other reasons. Closing may already be true at the delyaAwareRead
273 // call time or may happen while we wait after delayRead() above.
274 debugs(20, 3, HERE
<< "wont read from closing " << conn
<< " for " <<
276 return; // the read callback will never be called
279 comm_read(conn
, buf
, amountToRead
, callback
);
283 StoreEntry::bytesWanted (Range
<size_t> const aRange
, bool ignoreDelayPools
) const
288 #if URL_CHECKSUM_DEBUG
290 mem_obj
->checkUrlChecksum();
294 if (!mem_obj
->readAheadPolicyCanRead())
297 return mem_obj
->mostBytesWanted(aRange
.end
, ignoreDelayPools
);
301 StoreEntry::checkDeferRead(int fd
) const
303 return (bytesWanted(Range
<size_t>(0,INT_MAX
)) == 0);
307 StoreEntry::setNoDelay (bool const newValue
)
310 mem_obj
->setNoDelay(newValue
);
313 // XXX: Type names mislead. STORE_DISK_CLIENT actually means that we should
314 // open swapin file, aggressively trim memory, and ignore read-ahead gap.
315 // It does not mean we will read from disk exclusively (or at all!).
316 // XXX: May create STORE_DISK_CLIENT with no disk caching configured.
317 // XXX: Collapsed clients cannot predict their type.
319 StoreEntry::storeClientType() const
321 /* The needed offset isn't in memory
322 * XXX TODO: this is wrong for range requests
323 * as the needed offset may *not* be 0, AND
324 * offset 0 in the memory object is the HTTP headers.
329 if (mem_obj
->inmem_lo
)
330 return STORE_DISK_CLIENT
;
332 if (EBIT_TEST(flags
, ENTRY_ABORTED
)) {
333 /* I don't think we should be adding clients to aborted entries */
334 debugs(20, DBG_IMPORTANT
, "storeClientType: adding to ENTRY_ABORTED entry");
335 return STORE_MEM_CLIENT
;
338 if (store_status
== STORE_OK
) {
339 /* the object has completed. */
341 if (mem_obj
->inmem_lo
== 0 && !isEmpty()) {
342 if (swap_status
== SWAPOUT_DONE
) {
343 debugs(20,7, HERE
<< mem_obj
<< " lo: " << mem_obj
->inmem_lo
<< " hi: " << mem_obj
->endOffset() << " size: " << mem_obj
->object_sz
);
344 if (mem_obj
->endOffset() == mem_obj
->object_sz
) {
345 /* hot object fully swapped in (XXX: or swapped out?) */
346 return STORE_MEM_CLIENT
;
349 /* Memory-only, or currently being swapped out */
350 return STORE_MEM_CLIENT
;
353 return STORE_DISK_CLIENT
;
356 /* here and past, entry is STORE_PENDING */
358 * If this is the first client, let it be the mem client
360 if (mem_obj
->nclients
== 1)
361 return STORE_MEM_CLIENT
;
364 * If there is no disk file to open yet, we must make this a
365 * mem client. If we can't open the swapin file before writing
366 * to the client, there is no guarantee that we will be able
367 * to open it later when we really need it.
369 if (swap_status
== SWAPOUT_NONE
)
370 return STORE_MEM_CLIENT
;
373 * otherwise, make subsequent clients read from disk so they
374 * can not delay the first, and vice-versa.
376 return STORE_DISK_CLIENT
;
379 StoreEntry::StoreEntry() :
390 mem_status(NOT_IN_MEMORY
),
391 ping_status(PING_NONE
),
392 store_status(STORE_PENDING
),
393 swap_status(SWAPOUT_NONE
),
396 debugs(20, 5, "StoreEntry constructed, this=" << this);
399 StoreEntry::~StoreEntry()
401 debugs(20, 5, "StoreEntry destructed, this=" << this);
406 StoreEntry::deferProducer(const AsyncCall::Pointer
&producer
)
408 if (!deferredProducer
)
409 deferredProducer
= producer
;
411 debugs(20, 5, HERE
<< "Deferred producer call is allready set to: " <<
412 *deferredProducer
<< ", requested call: " << *producer
);
416 StoreEntry::kickProducer()
418 if (deferredProducer
!= NULL
) {
419 ScheduleCallHere(deferredProducer
);
420 deferredProducer
= NULL
;
426 StoreEntry::destroyMemObject()
428 debugs(20, 3, HERE
<< "destroyMemObject " << mem_obj
);
430 if (MemObject
*mem
= mem_obj
) {
431 // Store::Root() is FATALly missing during shutdown
432 if (mem
->xitTable
.index
>= 0 && !shutting_down
)
433 Store::Root().transientsDisconnect(*mem
);
434 if (mem
->memCache
.index
>= 0 && !shutting_down
)
435 Store::Root().memoryDisconnect(*this);
437 setMemStatus(NOT_IN_MEMORY
);
444 destroyStoreEntry(void *data
)
446 debugs(20, 3, HERE
<< "destroyStoreEntry: destroying " << data
);
447 StoreEntry
*e
= static_cast<StoreEntry
*>(static_cast<hash_link
*>(data
));
450 if (e
== NullStoreEntry::getInstance())
453 // Store::Root() is FATALly missing during shutdown
454 if (e
->swap_filen
>= 0 && !shutting_down
) {
455 SwapDir
&sd
= dynamic_cast<SwapDir
&>(*e
->store());
459 e
->destroyMemObject();
463 assert(e
->key
== NULL
);
468 /* ----- INTERFACE BETWEEN STORAGE MANAGER AND HASH TABLE FUNCTIONS --------- */
471 StoreEntry::hashInsert(const cache_key
* someKey
)
473 debugs(20, 3, "StoreEntry::hashInsert: Inserting Entry " << *this << " key '" << storeKeyText(someKey
) << "'");
474 key
= storeKeyDup(someKey
);
475 hash_join(store_table
, this);
479 StoreEntry::hashDelete()
481 if (key
) { // some test cases do not create keys and do not hashInsert()
482 hash_remove_link(store_table
, this);
483 storeKeyFree((const cache_key
*)key
);
488 /* -------------------------------------------------------------------------- */
490 /* get rid of memory copy of the object */
492 StoreEntry::purgeMem()
497 debugs(20, 3, "StoreEntry::purgeMem: Freeing memory-copy of " << getMD5Text());
499 Store::Root().memoryUnlink(*this);
501 if (swap_status
!= SWAPOUT_DONE
)
506 StoreEntry::lock(const char *context
)
509 debugs(20, 3, context
<< " locked key " << getMD5Text() << ' ' << *this);
515 lastref
= squid_curtime
;
516 Store::Root().reference(*this);
520 StoreEntry::setReleaseFlag()
522 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
525 debugs(20, 3, "StoreEntry::setReleaseFlag: '" << getMD5Text() << "'");
527 EBIT_SET(flags
, RELEASE_REQUEST
);
529 Store::Root().markForUnlink(*this);
533 StoreEntry::releaseRequest()
535 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
538 setReleaseFlag(); // makes validToSend() false, preventing future hits
544 StoreEntry::unlock(const char *context
)
546 debugs(20, 3, (context
? context
: "somebody") <<
547 " unlocking key " << getMD5Text() << ' ' << *this);
548 assert(lock_count
> 0);
552 return (int) lock_count
;
554 if (store_status
== STORE_PENDING
)
557 assert(storePendingNClients(this) == 0);
559 if (EBIT_TEST(flags
, RELEASE_REQUEST
)) {
564 if (EBIT_TEST(flags
, KEY_PRIVATE
))
565 debugs(20, DBG_IMPORTANT
, "WARNING: " << __FILE__
<< ":" << __LINE__
<< ": found KEY_PRIVATE");
567 Store::Root().handleIdleEntry(*this); // may delete us
572 StoreEntry::getPublicByRequestMethod (StoreClient
*aClient
, HttpRequest
* request
, const HttpRequestMethod
& method
)
575 StoreEntry
*result
= storeGetPublicByRequestMethod( request
, method
);
578 aClient
->created (NullStoreEntry::getInstance());
580 aClient
->created (result
);
584 StoreEntry::getPublicByRequest (StoreClient
*aClient
, HttpRequest
* request
)
587 StoreEntry
*result
= storeGetPublicByRequest (request
);
590 result
= NullStoreEntry::getInstance();
592 aClient
->created (result
);
596 StoreEntry::getPublic (StoreClient
*aClient
, const char *uri
, const HttpRequestMethod
& method
)
599 StoreEntry
*result
= storeGetPublic (uri
, method
);
602 result
= NullStoreEntry::getInstance();
604 aClient
->created (result
);
608 storeGetPublic(const char *uri
, const HttpRequestMethod
& method
)
610 return Store::Root().get(storeKeyPublic(uri
, method
));
614 storeGetPublicByRequestMethod(HttpRequest
* req
, const HttpRequestMethod
& method
)
616 return Store::Root().get(storeKeyPublicByRequestMethod(req
, method
));
620 storeGetPublicByRequest(HttpRequest
* req
)
622 StoreEntry
*e
= storeGetPublicByRequestMethod(req
, req
->method
);
624 if (e
== NULL
&& req
->method
== Http::METHOD_HEAD
)
625 /* We can generate a HEAD reply from a cached GET object */
626 e
= storeGetPublicByRequestMethod(req
, Http::METHOD_GET
);
634 static int key_counter
= 0;
636 if (++key_counter
< 0)
642 /* RBC 20050104 AFAICT this should become simpler:
643 * rather than reinserting with a special key it should be marked
644 * as 'released' and then cleaned up when refcounting indicates.
645 * the StoreHashIndex could well implement its 'released' in the
647 * Also, clean log writing should skip over ia,t
648 * Otherwise, we need a 'remove from the index but not the store
652 StoreEntry::setPrivateKey()
654 const cache_key
*newkey
;
656 if (key
&& EBIT_TEST(flags
, KEY_PRIVATE
))
657 return; /* is already private */
660 setReleaseFlag(); // will markForUnlink(); all caches/workers will know
662 // TODO: move into SwapDir::markForUnlink() already called by Root()
664 storeDirSwapLog(this, SWAP_LOG_DEL
);
669 if (mem_obj
&& mem_obj
->hasUris()) {
670 mem_obj
->id
= getKeyCounter();
671 newkey
= storeKeyPrivate(mem_obj
->storeId(), mem_obj
->method
, mem_obj
->id
);
673 newkey
= storeKeyPrivate("JUNK", Http::METHOD_NONE
, getKeyCounter());
676 assert(hash_lookup(store_table
, newkey
) == NULL
);
677 EBIT_SET(flags
, KEY_PRIVATE
);
682 StoreEntry::setPublicKey()
684 const cache_key
*newkey
;
686 if (key
&& !EBIT_TEST(flags
, KEY_PRIVATE
))
687 return; /* is already public */
692 * We can't make RELEASE_REQUEST objects public. Depending on
693 * when RELEASE_REQUEST gets set, we might not be swapping out
694 * the object. If we're not swapping out, then subsequent
695 * store clients won't be able to access object data which has
696 * been freed from memory.
698 * If RELEASE_REQUEST is set, setPublicKey() should not be called.
700 #if MORE_DEBUG_OUTPUT
702 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
703 debugs(20, DBG_IMPORTANT
, "assertion failed: RELEASE key " << key
<< ", url " << mem_obj
->url
);
707 assert(!EBIT_TEST(flags
, RELEASE_REQUEST
));
709 if (mem_obj
->request
) {
710 HttpRequest
*request
= mem_obj
->request
;
712 if (!mem_obj
->vary_headers
) {
713 /* First handle the case where the object no longer varies */
714 safe_free(request
->vary_headers
);
716 if (request
->vary_headers
&& strcmp(request
->vary_headers
, mem_obj
->vary_headers
) != 0) {
717 /* Oops.. the variance has changed. Kill the base object
718 * to record the new variance key
720 safe_free(request
->vary_headers
); /* free old "bad" variance key */
721 if (StoreEntry
*pe
= storeGetPublic(mem_obj
->storeId(), mem_obj
->method
))
725 /* Make sure the request knows the variance status */
726 if (!request
->vary_headers
) {
727 const char *vary
= httpMakeVaryMark(request
, mem_obj
->getReply());
730 request
->vary_headers
= xstrdup(vary
);
734 // TODO: storeGetPublic() calls below may create unlocked entries.
735 // We should add/use storeHas() API or lock/unlock those entries.
736 if (mem_obj
->vary_headers
&& !storeGetPublic(mem_obj
->storeId(), mem_obj
->method
)) {
737 /* Create "vary" base object */
739 StoreEntry
*pe
= storeCreateEntry(mem_obj
->storeId(), mem_obj
->logUri(), request
->flags
, request
->method
);
740 /* We are allowed to do this typecast */
741 HttpReply
*rep
= new HttpReply
;
742 rep
->setHeaders(Http::scOkay
, "Internal marker object", "x-squid-internal/vary", -1, -1, squid_curtime
+ 100000);
743 vary
= mem_obj
->getReply()->header
.getList(HDR_VARY
);
746 /* Again, we own this structure layout */
747 rep
->header
.putStr(HDR_VARY
, vary
.termedBuf());
751 #if X_ACCELERATOR_VARY
752 vary
= mem_obj
->getReply()->header
.getList(HDR_X_ACCELERATOR_VARY
);
754 if (vary
.size() > 0) {
755 /* Again, we own this structure layout */
756 rep
->header
.putStr(HDR_X_ACCELERATOR_VARY
, vary
.termedBuf());
761 pe
->replaceHttpReply(rep
, false); // no write until key is public
767 pe
->startWriting(); // after makePublic()
771 pe
->unlock("StoreEntry::setPublicKey+Vary");
774 newkey
= storeKeyPublicByRequest(mem_obj
->request
);
776 newkey
= storeKeyPublic(mem_obj
->storeId(), mem_obj
->method
);
778 if (StoreEntry
*e2
= (StoreEntry
*)hash_lookup(store_table
, newkey
)) {
779 debugs(20, 3, "Making old " << *e2
<< " private.");
783 if (mem_obj
->request
)
784 newkey
= storeKeyPublicByRequest(mem_obj
->request
);
786 newkey
= storeKeyPublic(mem_obj
->storeId(), mem_obj
->method
);
792 EBIT_CLR(flags
, KEY_PRIVATE
);
797 storeDirSwapLog(this, SWAP_LOG_ADD
);
801 storeCreatePureEntry(const char *url
, const char *log_url
, const RequestFlags
&flags
, const HttpRequestMethod
& method
)
803 StoreEntry
*e
= NULL
;
804 debugs(20, 3, "storeCreateEntry: '" << url
<< "'");
806 e
= new StoreEntry();
808 e
->mem_obj
->setUris(url
, log_url
, method
);
810 if (flags
.cachable
) {
811 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
816 e
->store_status
= STORE_PENDING
;
818 e
->lastref
= squid_curtime
;
819 e
->timestamp
= -1; /* set in StoreEntry::timestampsSet() */
820 e
->ping_status
= PING_NONE
;
821 EBIT_SET(e
->flags
, ENTRY_VALIDATED
);
826 storeCreateEntry(const char *url
, const char *logUrl
, const RequestFlags
&flags
, const HttpRequestMethod
& method
)
828 StoreEntry
*e
= storeCreatePureEntry(url
, logUrl
, flags
, method
);
829 e
->lock("storeCreateEntry");
831 if (neighbors_do_private_keys
|| !flags
.hierarchical
)
839 /* Mark object as expired */
841 StoreEntry::expireNow()
843 debugs(20, 3, "StoreEntry::expireNow: '" << getMD5Text() << "'");
844 expires
= squid_curtime
;
848 StoreEntry::write (StoreIOBuffer writeBuffer
)
850 assert(mem_obj
!= NULL
);
851 /* This assert will change when we teach the store to update */
852 PROF_start(StoreEntry_write
);
853 assert(store_status
== STORE_PENDING
);
855 // XXX: caller uses content offset, but we also store headers
856 if (const HttpReply
*reply
= mem_obj
->getReply())
857 writeBuffer
.offset
+= reply
->hdr_sz
;
859 debugs(20, 5, "storeWrite: writing " << writeBuffer
.length
<< " bytes for '" << getMD5Text() << "'");
860 PROF_stop(StoreEntry_write
);
861 storeGetMemSpace(writeBuffer
.length
);
862 mem_obj
->write(writeBuffer
);
864 if (!EBIT_TEST(flags
, DELAY_SENDING
))
868 /* Append incoming data from a primary server to an entry. */
870 StoreEntry::append(char const *buf
, int len
)
872 assert(mem_obj
!= NULL
);
874 assert(store_status
== STORE_PENDING
);
876 StoreIOBuffer tempBuffer
;
877 tempBuffer
.data
= (char *)buf
;
878 tempBuffer
.length
= len
;
880 * XXX sigh, offset might be < 0 here, but it gets "corrected"
881 * later. This offset crap is such a mess.
883 tempBuffer
.offset
= mem_obj
->endOffset() - (getReply() ? getReply()->hdr_sz
: 0);
888 storeAppendPrintf(StoreEntry
* e
, const char *fmt
,...)
893 storeAppendVPrintf(e
, fmt
, args
);
897 /* used be storeAppendPrintf and Packer */
899 storeAppendVPrintf(StoreEntry
* e
, const char *fmt
, va_list vargs
)
901 LOCAL_ARRAY(char, buf
, 4096);
903 vsnprintf(buf
, 4096, fmt
, vargs
);
904 e
->append(buf
, strlen(buf
));
907 struct _store_check_cachable_hist
{
911 int not_entry_cachable
;
912 int wrong_content_length
;
917 int too_many_open_files
;
918 int too_many_open_fds
;
924 } store_check_cachable_hist
;
927 storeTooManyDiskFilesOpen(void)
929 if (Config
.max_open_disk_fds
== 0)
932 if (store_open_disk_fd
> Config
.max_open_disk_fds
)
939 StoreEntry::checkTooSmall()
941 if (EBIT_TEST(flags
, ENTRY_SPECIAL
))
944 if (STORE_OK
== store_status
)
945 if (mem_obj
->object_sz
< 0 ||
946 mem_obj
->object_sz
< Config
.Store
.minObjectSize
)
948 if (getReply()->content_length
> -1)
949 if (getReply()->content_length
< Config
.Store
.minObjectSize
)
954 // TODO: remove checks already performed by swapoutPossible()
955 // TODO: move "too many open..." checks outside -- we are called too early/late
957 StoreEntry::checkCachable()
959 #if CACHE_ALL_METHODS
961 if (mem_obj
->method
!= Http::METHOD_GET
) {
962 debugs(20, 2, "StoreEntry::checkCachable: NO: non-GET method");
963 ++store_check_cachable_hist
.no
.non_get
;
966 if (store_status
== STORE_OK
&& EBIT_TEST(flags
, ENTRY_BAD_LENGTH
)) {
967 debugs(20, 2, "StoreEntry::checkCachable: NO: wrong content-length");
968 ++store_check_cachable_hist
.no
.wrong_content_length
;
969 } else if (EBIT_TEST(flags
, RELEASE_REQUEST
)) {
970 debugs(20, 2, "StoreEntry::checkCachable: NO: not cachable");
971 ++store_check_cachable_hist
.no
.not_entry_cachable
; // TODO: rename?
972 } else if (EBIT_TEST(flags
, ENTRY_NEGCACHED
)) {
973 debugs(20, 3, "StoreEntry::checkCachable: NO: negative cached");
974 ++store_check_cachable_hist
.no
.negative_cached
;
975 return 0; /* avoid release call below */
976 } else if ((getReply()->content_length
> 0 &&
977 getReply()->content_length
> store_maxobjsize
) ||
978 mem_obj
->endOffset() > store_maxobjsize
) {
979 debugs(20, 2, "StoreEntry::checkCachable: NO: too big");
980 ++store_check_cachable_hist
.no
.too_big
;
981 } else if (checkTooSmall()) {
982 debugs(20, 2, "StoreEntry::checkCachable: NO: too small");
983 ++store_check_cachable_hist
.no
.too_small
;
984 } else if (EBIT_TEST(flags
, KEY_PRIVATE
)) {
985 debugs(20, 3, "StoreEntry::checkCachable: NO: private key");
986 ++store_check_cachable_hist
.no
.private_key
;
987 } else if (swap_status
!= SWAPOUT_NONE
) {
989 * here we checked the swap_status because the remaining
990 * cases are only relevant only if we haven't started swapping
991 * out the object yet.
994 } else if (storeTooManyDiskFilesOpen()) {
995 debugs(20, 2, "StoreEntry::checkCachable: NO: too many disk files open");
996 ++store_check_cachable_hist
.no
.too_many_open_files
;
997 } else if (fdNFree() < RESERVED_FD
) {
998 debugs(20, 2, "StoreEntry::checkCachable: NO: too many FD's open");
999 ++store_check_cachable_hist
.no
.too_many_open_fds
;
1001 ++store_check_cachable_hist
.yes
.Default
;
1010 storeCheckCachableStats(StoreEntry
*sentry
)
1012 storeAppendPrintf(sentry
, "Category\t Count\n");
1014 #if CACHE_ALL_METHODS
1016 storeAppendPrintf(sentry
, "no.non_get\t%d\n",
1017 store_check_cachable_hist
.no
.non_get
);
1020 storeAppendPrintf(sentry
, "no.not_entry_cachable\t%d\n",
1021 store_check_cachable_hist
.no
.not_entry_cachable
);
1022 storeAppendPrintf(sentry
, "no.wrong_content_length\t%d\n",
1023 store_check_cachable_hist
.no
.wrong_content_length
);
1024 storeAppendPrintf(sentry
, "no.negative_cached\t%d\n",
1025 store_check_cachable_hist
.no
.negative_cached
);
1026 storeAppendPrintf(sentry
, "no.too_big\t%d\n",
1027 store_check_cachable_hist
.no
.too_big
);
1028 storeAppendPrintf(sentry
, "no.too_small\t%d\n",
1029 store_check_cachable_hist
.no
.too_small
);
1030 storeAppendPrintf(sentry
, "no.private_key\t%d\n",
1031 store_check_cachable_hist
.no
.private_key
);
1032 storeAppendPrintf(sentry
, "no.too_many_open_files\t%d\n",
1033 store_check_cachable_hist
.no
.too_many_open_files
);
1034 storeAppendPrintf(sentry
, "no.too_many_open_fds\t%d\n",
1035 store_check_cachable_hist
.no
.too_many_open_fds
);
1036 storeAppendPrintf(sentry
, "yes.default\t%d\n",
1037 store_check_cachable_hist
.yes
.Default
);
1041 StoreEntry::complete()
1043 debugs(20, 3, "storeComplete: '" << getMD5Text() << "'");
1045 if (store_status
!= STORE_PENDING
) {
1047 * if we're not STORE_PENDING, then probably we got aborted
1048 * and there should be NO clients on this entry
1050 assert(EBIT_TEST(flags
, ENTRY_ABORTED
));
1051 assert(mem_obj
->nclients
== 0);
1055 /* This is suspect: mem obj offsets include the headers. do we adjust for that
1056 * in use of object_sz?
1058 mem_obj
->object_sz
= mem_obj
->endOffset();
1060 store_status
= STORE_OK
;
1062 assert(mem_status
== NOT_IN_MEMORY
);
1064 if (!validLength()) {
1065 EBIT_SET(flags
, ENTRY_BAD_LENGTH
);
1069 #if USE_CACHE_DIGESTS
1070 if (mem_obj
->request
)
1071 mem_obj
->request
->hier
.store_complete_stop
= current_time
;
1075 * We used to call invokeHandlers, then storeSwapOut. However,
1076 * Madhukar Reddy <myreddy@persistence.com> reported that
1077 * responses without content length would sometimes get released
1078 * in client_side, thinking that the response is incomplete.
1084 * Someone wants to abort this transfer. Set the reason in the
1085 * request structure, call the server-side callback and mark the
1086 * entry for releasing
1091 ++statCounter
.aborted_requests
;
1092 assert(store_status
== STORE_PENDING
);
1093 assert(mem_obj
!= NULL
);
1094 debugs(20, 6, "storeAbort: " << getMD5Text());
1096 lock("StoreEntry::abort"); /* lock while aborting */
1101 EBIT_SET(flags
, ENTRY_ABORTED
);
1103 setMemStatus(NOT_IN_MEMORY
);
1105 store_status
= STORE_OK
;
1107 /* Notify the server side */
1111 * Should we check abort.data for validity?
1113 if (mem_obj
->abort
.callback
) {
1114 if (!cbdataReferenceValid(mem_obj
->abort
.data
))
1115 debugs(20, DBG_IMPORTANT
,HERE
<< "queueing event when abort.data is not valid");
1116 eventAdd("mem_obj->abort.callback",
1117 mem_obj
->abort
.callback
,
1118 mem_obj
->abort
.data
,
1124 /* XXX Should we reverse these two, so that there is no
1125 * unneeded disk swapping triggered?
1127 /* Notify the client side */
1130 // abort swap out, invalidating what was created so far (release follows)
1131 swapOutFileClose(StoreIOState::writerGone
);
1133 unlock("StoreEntry::abort"); /* unlock */
1137 * Clear Memory storage to accommodate the given object len
1140 storeGetMemSpace(int size
)
1142 PROF_start(storeGetMemSpace
);
1143 StoreEntry
*e
= NULL
;
1145 static time_t last_check
= 0;
1146 size_t pages_needed
;
1147 RemovalPurgeWalker
*walker
;
1149 if (squid_curtime
== last_check
) {
1150 PROF_stop(storeGetMemSpace
);
1154 last_check
= squid_curtime
;
1156 pages_needed
= (size
+ SM_PAGE_SIZE
-1) / SM_PAGE_SIZE
;
1158 if (mem_node::InUseCount() + pages_needed
< store_pages_max
) {
1159 PROF_stop(storeGetMemSpace
);
1163 debugs(20, 2, "storeGetMemSpace: Starting, need " << pages_needed
<<
1166 /* XXX what to set as max_scan here? */
1167 walker
= mem_policy
->PurgeInit(mem_policy
, 100000);
1169 while ((e
= walker
->Next(walker
))) {
1173 if (mem_node::InUseCount() + pages_needed
< store_pages_max
)
1177 walker
->Done(walker
);
1178 debugs(20, 3, "storeGetMemSpace stats:");
1179 debugs(20, 3, " " << std::setw(6) << hot_obj_count
<< " HOT objects");
1180 debugs(20, 3, " " << std::setw(6) << released
<< " were released");
1181 PROF_stop(storeGetMemSpace
);
1184 /* thunk through to Store::Root().maintain(). Note that this would be better still
1185 * if registered against the root store itself, but that requires more complex
1186 * update logic - bigger fish to fry first. Long term each store when
1187 * it becomes active will self register
1190 Store::Maintain(void *notused
)
1192 Store::Root().maintain();
1194 /* Reregister a maintain event .. */
1195 eventAdd("MaintainSwapSpace", Maintain
, NULL
, 1.0, 1);
1199 /* The maximum objects to scan for maintain storage space */
1200 #define MAINTAIN_MAX_SCAN 1024
1201 #define MAINTAIN_MAX_REMOVE 64
1204 * This routine is to be called by main loop in main.c.
1205 * It removes expired objects on only one bucket for each time called.
1207 * This should get called 1/s from main().
1210 StoreController::maintain()
1212 static time_t last_warn_time
= 0;
1214 PROF_start(storeMaintainSwapSpace
);
1215 swapDir
->maintain();
1217 /* this should be emitted by the oversize dir, not globally */
1219 if (Store::Root().currentSize() > Store::Root().maxSize()) {
1220 if (squid_curtime
- last_warn_time
> 10) {
1221 debugs(20, DBG_CRITICAL
, "WARNING: Disk space over limit: "
1222 << Store::Root().currentSize() / 1024.0 << " KB > "
1223 << (Store::Root().maxSize() >> 10) << " KB");
1224 last_warn_time
= squid_curtime
;
1228 PROF_stop(storeMaintainSwapSpace
);
1231 /* release an object from a cache */
1233 StoreEntry::release()
1235 PROF_start(storeRelease
);
1236 debugs(20, 3, "releasing " << *this << ' ' << getMD5Text());
1237 /* If, for any reason we can't discard this object because of an
1238 * outstanding request, mark it for pending release */
1242 debugs(20, 3, "storeRelease: Only setting RELEASE_REQUEST bit");
1244 PROF_stop(storeRelease
);
1248 Store::Root().memoryUnlink(*this);
1250 if (StoreController::store_dirs_rebuilding
&& swap_filen
> -1) {
1253 if (swap_filen
> -1) {
1254 // lock the entry until rebuilding is done
1255 lock("storeLateRelease");
1257 LateReleaseStack
.push(this);
1259 destroyStoreEntry(static_cast<hash_link
*>(this));
1260 // "this" is no longer valid
1263 PROF_stop(storeRelease
);
1267 storeLog(STORE_LOG_RELEASE
, this);
1269 if (swap_filen
> -1) {
1270 // log before unlink() below clears swap_filen
1271 if (!EBIT_TEST(flags
, KEY_PRIVATE
))
1272 storeDirSwapLog(this, SWAP_LOG_DEL
);
1277 destroyStoreEntry(static_cast<hash_link
*>(this));
1278 PROF_stop(storeRelease
);
1282 storeLateRelease(void *unused
)
1287 if (StoreController::store_dirs_rebuilding
) {
1288 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 1.0, 1);
1292 // TODO: this works but looks unelegant.
1293 for (int i
= 0; i
< 10; ++i
) {
1294 if (LateReleaseStack
.empty()) {
1295 debugs(20, DBG_IMPORTANT
, "storeLateRelease: released " << n
<< " objects");
1298 e
= LateReleaseStack
.top();
1299 LateReleaseStack
.pop();
1302 e
->unlock("storeLateRelease");
1306 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 0.0, 1);
1309 /* return 1 if a store entry is locked */
1311 StoreEntry::locked() const
1317 * SPECIAL, PUBLIC entries should be "locked";
1318 * XXX: Their owner should lock them then instead of relying on this hack.
1320 if (EBIT_TEST(flags
, ENTRY_SPECIAL
))
1321 if (!EBIT_TEST(flags
, KEY_PRIVATE
))
1328 StoreEntry::validLength() const
1331 const HttpReply
*reply
;
1332 assert(mem_obj
!= NULL
);
1334 debugs(20, 3, "storeEntryValidLength: Checking '" << getMD5Text() << "'");
1335 debugs(20, 5, "storeEntryValidLength: object_len = " <<
1337 debugs(20, 5, "storeEntryValidLength: hdr_sz = " << reply
->hdr_sz
);
1338 debugs(20, 5, "storeEntryValidLength: content_length = " << reply
->content_length
);
1340 if (reply
->content_length
< 0) {
1341 debugs(20, 5, "storeEntryValidLength: Unspecified content length: " << getMD5Text());
1345 if (reply
->hdr_sz
== 0) {
1346 debugs(20, 5, "storeEntryValidLength: Zero header size: " << getMD5Text());
1350 if (mem_obj
->method
== Http::METHOD_HEAD
) {
1351 debugs(20, 5, "storeEntryValidLength: HEAD request: " << getMD5Text());
1355 if (reply
->sline
.status() == Http::scNotModified
)
1358 if (reply
->sline
.status() == Http::scNoContent
)
1361 diff
= reply
->hdr_sz
+ reply
->content_length
- objectLen();
1366 debugs(20, 3, "storeEntryValidLength: " << (diff
< 0 ? -diff
: diff
) << " bytes too " << (diff
< 0 ? "big" : "small") <<"; '" << getMD5Text() << "'" );
1372 storeRegisterWithCacheManager(void)
1374 Mgr::RegisterAction("storedir", "Store Directory Stats", Store::Stats
, 0, 1);
1375 Mgr::RegisterAction("store_io", "Store IO Interface Stats", &Mgr::StoreIoAction::Create
, 0, 1);
1376 Mgr::RegisterAction("store_check_cachable_stats", "storeCheckCachable() Stats",
1377 storeCheckCachableStats
, 0, 1);
1384 mem_policy
= createRemovalPolicy(Config
.memPolicy
);
1387 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 1.0, 1);
1388 Store::Root().init();
1389 storeRebuildStart();
1391 storeRegisterWithCacheManager();
1395 storeConfigure(void)
1397 store_swap_high
= (long) (((float) Store::Root().maxSize() *
1398 (float) Config
.Swap
.highWaterMark
) / (float) 100);
1399 store_swap_low
= (long) (((float) Store::Root().maxSize() *
1400 (float) Config
.Swap
.lowWaterMark
) / (float) 100);
1401 store_pages_max
= Config
.memMaxSize
/ sizeof(mem_node
);
1405 StoreEntry::memoryCachable() const
1407 if (mem_obj
== NULL
)
1410 if (mem_obj
->data_hdr
.size() == 0)
1413 if (mem_obj
->inmem_lo
!= 0)
1416 if (!Config
.onoff
.memory_cache_first
&& swap_status
== SWAPOUT_DONE
&& refcount
== 1)
1423 StoreEntry::checkNegativeHit() const
1425 if (!EBIT_TEST(flags
, ENTRY_NEGCACHED
))
1428 if (expires
<= squid_curtime
)
1431 if (store_status
!= STORE_OK
)
1438 * Set object for negative caching.
1439 * Preserves any expiry information given by the server.
1440 * In absence of proper expiry info it will set to expire immediately,
1441 * or with HTTP-violations enabled the configured negative-TTL is observed
1444 StoreEntry::negativeCache()
1446 // XXX: should make the default for expires 0 instead of -1
1447 // so we can distinguish "Expires: -1" from nothing.
1449 #if USE_HTTP_VIOLATIONS
1450 expires
= squid_curtime
+ Config
.negativeTtl
;
1452 expires
= squid_curtime
;
1454 EBIT_SET(flags
, ENTRY_NEGCACHED
);
1458 storeFreeMemory(void)
1461 #if USE_CACHE_DIGESTS
1464 cacheDigestDestroy(store_digest
);
1468 store_digest
= NULL
;
1472 expiresMoreThan(time_t expires
, time_t when
)
1474 if (expires
< 0) /* No Expires given */
1477 return (expires
> (squid_curtime
+ when
));
1481 StoreEntry::validToSend() const
1483 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
1486 if (EBIT_TEST(flags
, ENTRY_NEGCACHED
))
1487 if (expires
<= squid_curtime
)
1490 if (EBIT_TEST(flags
, ENTRY_ABORTED
))
1493 // now check that the entry has a cache backing or is collapsed
1494 if (swap_filen
> -1) // backed by a disk cache
1497 if (swappingOut()) // will be backed by a disk cache
1500 if (!mem_obj
) // not backed by a memory cache and not collapsed
1503 if (mem_obj
->memCache
.index
>= 0) // backed by a shared memory cache
1506 // StoreEntry::storeClientType() assumes DISK_CLIENT here, but there is no
1507 // disk cache backing so we should not rely on the store cache at all. This
1508 // is wrong for range requests that could feed off nibbled memory (XXX).
1509 if (mem_obj
->inmem_lo
) // in local memory cache, but got nibbled at
1516 StoreEntry::timestampsSet()
1518 const HttpReply
*reply
= getReply();
1519 time_t served_date
= reply
->date
;
1520 int age
= reply
->header
.getInt(HDR_AGE
);
1521 /* Compute the timestamp, mimicking RFC2616 section 13.2.3. */
1522 /* make sure that 0 <= served_date <= squid_curtime */
1524 if (served_date
< 0 || served_date
> squid_curtime
)
1525 served_date
= squid_curtime
;
1528 * If the returned Date: is more than 24 hours older than
1529 * the squid_curtime, then one of us needs to use NTP to set our
1530 * clock. We'll pretend that our clock is right.
1532 else if (served_date
< (squid_curtime
- 24 * 60 * 60) )
1533 served_date
= squid_curtime
;
1536 * Compensate with Age header if origin server clock is ahead
1537 * of us and there is a cache in between us and the origin
1538 * server. But DONT compensate if the age value is larger than
1539 * squid_curtime because it results in a negative served_date.
1541 if (age
> squid_curtime
- served_date
)
1542 if (squid_curtime
> age
)
1543 served_date
= squid_curtime
- age
;
1545 // compensate for Squid-to-server and server-to-Squid delays
1546 if (mem_obj
&& mem_obj
->request
) {
1547 const time_t request_sent
=
1548 mem_obj
->request
->hier
.peer_http_request_sent
.tv_sec
;
1549 if (0 < request_sent
&& request_sent
< squid_curtime
)
1550 served_date
-= (squid_curtime
- request_sent
);
1553 if (reply
->expires
> 0 && reply
->date
> -1)
1554 expires
= served_date
+ (reply
->expires
- reply
->date
);
1556 expires
= reply
->expires
;
1558 lastmod
= reply
->last_modified
;
1560 timestamp
= served_date
;
1564 StoreEntry::registerAbort(STABH
* cb
, void *data
)
1567 assert(mem_obj
->abort
.callback
== NULL
);
1568 mem_obj
->abort
.callback
= cb
;
1569 mem_obj
->abort
.data
= cbdataReference(data
);
1573 StoreEntry::unregisterAbort()
1576 if (mem_obj
->abort
.callback
) {
1577 mem_obj
->abort
.callback
= NULL
;
1578 cbdataReferenceDone(mem_obj
->abort
.data
);
1583 StoreEntry::dump(int l
) const
1585 debugs(20, l
, "StoreEntry->key: " << getMD5Text());
1586 debugs(20, l
, "StoreEntry->next: " << next
);
1587 debugs(20, l
, "StoreEntry->mem_obj: " << mem_obj
);
1588 debugs(20, l
, "StoreEntry->timestamp: " << timestamp
);
1589 debugs(20, l
, "StoreEntry->lastref: " << lastref
);
1590 debugs(20, l
, "StoreEntry->expires: " << expires
);
1591 debugs(20, l
, "StoreEntry->lastmod: " << lastmod
);
1592 debugs(20, l
, "StoreEntry->swap_file_sz: " << swap_file_sz
);
1593 debugs(20, l
, "StoreEntry->refcount: " << refcount
);
1594 debugs(20, l
, "StoreEntry->flags: " << storeEntryFlags(this));
1595 debugs(20, l
, "StoreEntry->swap_dirn: " << swap_dirn
);
1596 debugs(20, l
, "StoreEntry->swap_filen: " << swap_filen
);
1597 debugs(20, l
, "StoreEntry->lock_count: " << lock_count
);
1598 debugs(20, l
, "StoreEntry->mem_status: " << mem_status
);
1599 debugs(20, l
, "StoreEntry->ping_status: " << ping_status
);
1600 debugs(20, l
, "StoreEntry->store_status: " << store_status
);
1601 debugs(20, l
, "StoreEntry->swap_status: " << swap_status
);
1605 * NOTE, this function assumes only two mem states
1608 StoreEntry::setMemStatus(mem_status_t new_status
)
1610 if (new_status
== mem_status
)
1613 // are we using a shared memory cache?
1614 if (Config
.memShared
&& IamWorkerProcess()) {
1615 // This method was designed to update replacement policy, not to
1616 // actually purge something from the memory cache (TODO: rename?).
1617 // Shared memory cache does not have a policy that needs updates.
1618 mem_status
= new_status
;
1622 assert(mem_obj
!= NULL
);
1624 if (new_status
== IN_MEMORY
) {
1625 assert(mem_obj
->inmem_lo
== 0);
1627 if (EBIT_TEST(flags
, ENTRY_SPECIAL
)) {
1628 debugs(20, 4, "not inserting special " << *this << " into policy");
1630 mem_policy
->Add(mem_policy
, this, &mem_obj
->repl
);
1631 debugs(20, 4, "inserted " << *this << " key: " << getMD5Text());
1634 ++hot_obj_count
; // TODO: maintain for the shared hot cache as well
1636 if (EBIT_TEST(flags
, ENTRY_SPECIAL
)) {
1637 debugs(20, 4, "not removing special " << *this << " from policy");
1639 mem_policy
->Remove(mem_policy
, this, &mem_obj
->repl
);
1640 debugs(20, 4, "removed " << *this);
1646 mem_status
= new_status
;
1650 StoreEntry::url() const
1653 return "[null_entry]";
1654 else if (mem_obj
== NULL
)
1655 return "[null_mem_obj]";
1657 return mem_obj
->storeId();
1661 StoreEntry::makeMemObject()
1664 mem_obj
= new MemObject();
1669 StoreEntry::createMemObject(const char *aUrl
, const char *aLogUrl
, const HttpRequestMethod
&aMethod
)
1672 mem_obj
->setUris(aUrl
, aLogUrl
, aMethod
);
1675 /* this just sets DELAY_SENDING */
1677 StoreEntry::buffer()
1679 EBIT_SET(flags
, DELAY_SENDING
);
1682 /* this just clears DELAY_SENDING and Invokes the handlers */
1686 if (EBIT_TEST(flags
, DELAY_SENDING
)) {
1687 EBIT_CLR(flags
, DELAY_SENDING
);
1693 StoreEntry::objectLen() const
1695 assert(mem_obj
!= NULL
);
1696 return mem_obj
->object_sz
;
1700 StoreEntry::contentLen() const
1702 assert(mem_obj
!= NULL
);
1703 assert(getReply() != NULL
);
1704 return objectLen() - getReply()->hdr_sz
;
1708 StoreEntry::getReply () const
1710 if (NULL
== mem_obj
)
1713 return mem_obj
->getReply();
1720 debugs(20, 3, "StoreEntry::reset: " << url());
1722 HttpReply
*rep
= (HttpReply
*) getReply(); // bypass const
1724 expires
= lastmod
= timestamp
= -1;
1730 * This routine calls the SETUP routine for each fs type.
1731 * I don't know where the best place for this is, and I'm not going to shuffle
1732 * around large chunks of code right now (that can be done once its working.)
1741 * called to add another store removal policy module
1744 storeReplAdd(const char *type
, REMOVALPOLICYCREATE
* create
)
1748 /* find the number of currently known repl types */
1749 for (i
= 0; storerepl_list
&& storerepl_list
[i
].typestr
; ++i
) {
1750 if (strcmp(storerepl_list
[i
].typestr
, type
) == 0) {
1751 debugs(20, DBG_IMPORTANT
, "WARNING: Trying to load store replacement policy " << type
<< " twice.");
1756 /* add the new type */
1757 storerepl_list
= static_cast<storerepl_entry_t
*>(xrealloc(storerepl_list
, (i
+ 2) * sizeof(storerepl_entry_t
)));
1759 memset(&storerepl_list
[i
+ 1], 0, sizeof(storerepl_entry_t
));
1761 storerepl_list
[i
].typestr
= type
;
1763 storerepl_list
[i
].create
= create
;
1767 * Create a removal policy instance
1770 createRemovalPolicy(RemovalPolicySettings
* settings
)
1772 storerepl_entry_t
*r
;
1774 for (r
= storerepl_list
; r
&& r
->typestr
; ++r
) {
1775 if (strcmp(r
->typestr
, settings
->type
) == 0)
1776 return r
->create(settings
->args
);
1779 debugs(20, DBG_IMPORTANT
, "ERROR: Unknown policy " << settings
->type
);
1780 debugs(20, DBG_IMPORTANT
, "ERROR: Be sure to have set cache_replacement_policy");
1781 debugs(20, DBG_IMPORTANT
, "ERROR: and memory_replacement_policy in squid.conf!");
1782 fatalf("ERROR: Unknown policy %s\n", settings
->type
);
1783 return NULL
; /* NOTREACHED */
1788 storeSwapFileNumberSet(StoreEntry
* e
, sfileno filn
)
1790 if (e
->swap_file_number
== filn
)
1795 storeDirMapBitReset(e
->swap_file_number
);
1796 storeDirLRUDelete(e
);
1797 e
->swap_file_number
= -1;
1799 assert(-1 == e
->swap_file_number
);
1800 storeDirMapBitSet(e
->swap_file_number
= filn
);
1808 * Replace a store entry with
1809 * a new reply. This eats the reply.
1812 StoreEntry::replaceHttpReply(HttpReply
*rep
, bool andStartWriting
)
1814 debugs(20, 3, "StoreEntry::replaceHttpReply: " << url());
1817 debugs(20, DBG_CRITICAL
, "Attempt to replace object with no in-memory representation");
1821 mem_obj
->replaceHttpReply(rep
);
1823 if (andStartWriting
)
1828 StoreEntry::startWriting()
1832 /* TODO: when we store headers serparately remove the header portion */
1833 /* TODO: mark the length of the headers ? */
1834 /* We ONLY want the headers */
1835 packerToStoreInit(&p
, this);
1840 const HttpReply
*rep
= getReply();
1843 rep
->packHeadersInto(&p
);
1844 mem_obj
->markEndOfReplyHeaders();
1845 EBIT_CLR(flags
, ENTRY_FWD_HDR_WAIT
);
1847 rep
->body
.packInto(&p
);
1853 StoreEntry::getSerialisedMetaData()
1855 StoreMeta
*tlv_list
= storeSwapMetaBuild(this);
1857 char *result
= storeSwapMetaPack(tlv_list
, &swap_hdr_sz
);
1858 storeSwapTLVFree(tlv_list
);
1859 assert (swap_hdr_sz
>= 0);
1860 mem_obj
->swap_hdr_sz
= (size_t) swap_hdr_sz
;
1865 StoreEntry::trimMemory(const bool preserveSwappable
)
1869 * Bug #1943. We must not let go any data for IN_MEMORY
1870 * objects. We have to wait until the mem_status changes.
1872 if (mem_status
== IN_MEMORY
)
1875 if (EBIT_TEST(flags
, ENTRY_SPECIAL
))
1876 return; // cannot trim because we do not load them again
1878 if (preserveSwappable
)
1879 mem_obj
->trimSwappable();
1881 mem_obj
->trimUnSwappable();
1883 debugs(88, 7, *this << " inmem_lo=" << mem_obj
->inmem_lo
);
1887 StoreEntry::modifiedSince(HttpRequest
* request
) const
1890 time_t mod_time
= lastmod
;
1893 mod_time
= timestamp
;
1895 debugs(88, 3, "modifiedSince: '" << url() << "'");
1897 debugs(88, 3, "modifiedSince: mod_time = " << mod_time
);
1902 /* Find size of the object */
1903 object_length
= getReply()->content_length
;
1905 if (object_length
< 0)
1906 object_length
= contentLen();
1908 if (mod_time
> request
->ims
) {
1909 debugs(88, 3, "--> YES: entry newer than client");
1911 } else if (mod_time
< request
->ims
) {
1912 debugs(88, 3, "--> NO: entry older than client");
1914 } else if (request
->imslen
< 0) {
1915 debugs(88, 3, "--> NO: same LMT, no client length");
1917 } else if (request
->imslen
== object_length
) {
1918 debugs(88, 3, "--> NO: same LMT, same length");
1921 debugs(88, 3, "--> YES: same LMT, different length");
1927 StoreEntry::hasEtag(ETag
&etag
) const
1929 if (const HttpReply
*reply
= getReply()) {
1930 etag
= reply
->header
.getETag(HDR_ETAG
);
1938 StoreEntry::hasIfMatchEtag(const HttpRequest
&request
) const
1940 const String reqETags
= request
.header
.getList(HDR_IF_MATCH
);
1941 return hasOneOfEtags(reqETags
, false);
1945 StoreEntry::hasIfNoneMatchEtag(const HttpRequest
&request
) const
1947 const String reqETags
= request
.header
.getList(HDR_IF_NONE_MATCH
);
1948 // weak comparison is allowed only for HEAD or full-body GET requests
1949 const bool allowWeakMatch
= !request
.flags
.isRanged
&&
1950 (request
.method
== Http::METHOD_GET
|| request
.method
== Http::METHOD_HEAD
);
1951 return hasOneOfEtags(reqETags
, allowWeakMatch
);
1954 /// whether at least one of the request ETags matches entity ETag
1956 StoreEntry::hasOneOfEtags(const String
&reqETags
, const bool allowWeakMatch
) const
1958 const ETag repETag
= getReply()->header
.getETag(HDR_ETAG
);
1960 return strListIsMember(&reqETags
, "*", ',');
1962 bool matched
= false;
1963 const char *pos
= NULL
;
1966 while (!matched
&& strListGetItem(&reqETags
, ',', &item
, &ilen
, &pos
)) {
1967 if (!strncmp(item
, "*", ilen
))
1971 str
.append(item
, ilen
);
1973 if (etagParseInit(&reqETag
, str
.termedBuf())) {
1974 matched
= allowWeakMatch
? etagIsWeakEqual(repETag
, reqETag
) :
1975 etagIsStrongEqual(repETag
, reqETag
);
1983 StoreEntry::store() const
1985 assert(0 <= swap_dirn
&& swap_dirn
< Config
.cacheSwap
.n_configured
);
1986 return INDEXSD(swap_dirn
);
1990 StoreEntry::unlink()
1992 store()->unlink(*this); // implies disconnect()
1995 swap_status
= SWAPOUT_NONE
;
1999 * return true if the entry is in a state where
2000 * it can accept more data (ie with write() method)
2003 StoreEntry::isAccepting() const
2005 if (STORE_PENDING
!= store_status
)
2008 if (EBIT_TEST(flags
, ENTRY_ABORTED
))
2014 std::ostream
&operator <<(std::ostream
&os
, const StoreEntry
&e
)
2019 if (e
.mem_obj
->xitTable
.index
> -1)
2020 os
<< 't' << e
.mem_obj
->xitTable
.index
;
2021 if (e
.mem_obj
->memCache
.index
> -1)
2022 os
<< 'm' << e
.mem_obj
->memCache
.index
;
2024 if (e
.swap_filen
> -1 || e
.swap_dirn
> -1)
2025 os
<< 'd' << e
.swap_filen
<< '@' << e
.swap_dirn
;
2029 // print only non-default status values, using unique letters
2030 if (e
.mem_status
!= NOT_IN_MEMORY
||
2031 e
.store_status
!= STORE_PENDING
||
2032 e
.swap_status
!= SWAPOUT_NONE
||
2033 e
.ping_status
!= PING_NONE
) {
2034 if (e
.mem_status
!= NOT_IN_MEMORY
) os
<< 'm';
2035 if (e
.store_status
!= STORE_PENDING
) os
<< 's';
2036 if (e
.swap_status
!= SWAPOUT_NONE
) os
<< 'w' << e
.swap_status
;
2037 if (e
.ping_status
!= PING_NONE
) os
<< 'p' << e
.ping_status
;
2040 // print only set flags, using unique letters
2042 if (EBIT_TEST(e
.flags
, ENTRY_SPECIAL
)) os
<< 'S';
2043 if (EBIT_TEST(e
.flags
, ENTRY_REVALIDATE
)) os
<< 'R';
2044 if (EBIT_TEST(e
.flags
, DELAY_SENDING
)) os
<< 'P';
2045 if (EBIT_TEST(e
.flags
, RELEASE_REQUEST
)) os
<< 'X';
2046 if (EBIT_TEST(e
.flags
, REFRESH_REQUEST
)) os
<< 'F';
2047 if (EBIT_TEST(e
.flags
, ENTRY_DISPATCHED
)) os
<< 'D';
2048 if (EBIT_TEST(e
.flags
, KEY_PRIVATE
)) os
<< 'I';
2049 if (EBIT_TEST(e
.flags
, ENTRY_FWD_HDR_WAIT
)) os
<< 'W';
2050 if (EBIT_TEST(e
.flags
, ENTRY_NEGCACHED
)) os
<< 'N';
2051 if (EBIT_TEST(e
.flags
, ENTRY_VALIDATED
)) os
<< 'V';
2052 if (EBIT_TEST(e
.flags
, ENTRY_BAD_LENGTH
)) os
<< 'L';
2053 if (EBIT_TEST(e
.flags
, ENTRY_ABORTED
)) os
<< 'A';
2056 if (e
.mem_obj
&& e
.mem_obj
->smpCollapsed
)
2059 return os
<< '/' << &e
<< '*' << e
.locks();
2062 /* NullStoreEntry */
2064 NullStoreEntry
NullStoreEntry::_instance
;
2067 NullStoreEntry::getInstance()
2073 NullStoreEntry::getMD5Text() const
2079 NullStoreEntry::operator delete(void*)
2081 fatal ("Attempt to delete NullStoreEntry\n");
2085 NullStoreEntry::getSerialisedMetaData()