5 * DEBUG: section 20 Storage Manager
6 * AUTHOR: Harvest Derived
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
37 #include "CacheManager.h"
38 #include "comm/Connection.h"
43 #include "mgr/Registration.h"
44 #include "StoreClient.h"
46 #include "HttpReply.h"
47 #include "HttpRequest.h"
48 #include "MemObject.h"
50 #include "StoreMeta.h"
52 #include "StoreIOState.h"
54 #include "DelayPools.h"
57 #include "SquidTime.h"
58 #include "swap_log_op.h"
59 #include "mgr/StoreIoAction.h"
61 static STMCB storeWriteComplete
;
63 #define REBUILD_TIMESTAMP_DELTA_MAX 2
65 #define STORE_IN_MEM_BUCKETS (229)
68 /** \todo Convert these string constants to enum string-arrays generated */
70 const char *memStatusStr
[] = {
75 const char *pingStatusStr
[] = {
81 const char *storeStatusStr
[] = {
86 const char *swapStatusStr
[] = {
94 * This defines an repl type
97 typedef struct _storerepl_entry storerepl_entry_t
;
99 struct _storerepl_entry
{
101 REMOVALPOLICYCREATE
*create
;
104 static storerepl_entry_t
*storerepl_list
= NULL
;
108 * local function prototypes
110 static int getKeyCounter(void);
111 static OBJH storeCheckCachableStats
;
112 static EVH storeLateRelease
;
117 static Stack
<StoreEntry
*> LateReleaseStack
;
118 MemAllocator
*StoreEntry::pool
= NULL
;
120 StorePointer
Store::CurrentRoot
= NULL
;
123 Store::Root(Store
* aRoot
)
129 Store::Root(StorePointer aRoot
)
131 Root(aRoot
.getRaw());
135 Store::Stats(StoreEntry
* output
)
138 Root().stat(*output
);
154 Store::unlink (StoreEntry
&anEntry
)
156 fatal("Store::unlink on invalid Store\n");
160 StoreEntry::operator new (size_t bytecount
)
162 assert (bytecount
== sizeof (StoreEntry
));
165 pool
= memPoolCreate ("StoreEntry", bytecount
);
166 pool
->setChunkSize(2048 * 1024);
169 return pool
->alloc();
173 StoreEntry::operator delete (void *address
)
175 pool
->freeOne(address
);
179 StoreEntry::makePublic()
181 /* This object can be cached for a long time */
183 if (EBIT_TEST(flags
, ENTRY_CACHABLE
))
188 StoreEntry::makePrivate()
190 /* This object should never be cached at all */
192 releaseRequest(); /* delete object when not used */
193 /* releaseRequest clears ENTRY_CACHABLE flag */
197 StoreEntry::cacheNegatively()
199 /* This object may be negatively cached */
202 if (EBIT_TEST(flags
, ENTRY_CACHABLE
))
207 StoreEntry::inUseCount()
211 return pool
->getInUseCount();
215 StoreEntry::getMD5Text() const
217 return storeKeyText((const cache_key
*)key
);
223 StoreEntry::DeferReader(void *theContext
, CommRead
const &aRead
)
225 StoreEntry
*anEntry
= (StoreEntry
*)theContext
;
226 anEntry
->delayAwareRead(aRead
.conn
,
233 StoreEntry::delayAwareRead(const Comm::ConnectionPointer
&conn
, char *buf
, int len
, AsyncCall::Pointer callback
)
235 size_t amountToRead
= bytesWanted(Range
<size_t>(0, len
));
236 /* sketch: readdeferer* = getdeferer.
237 * ->deferRead (fd, buf, len, callback, DelayAwareRead, this)
240 if (amountToRead
== 0) {
242 /* read ahead limit */
243 /* Perhaps these two calls should both live in MemObject */
245 if (!mem_obj
->readAheadPolicyCanRead()) {
247 mem_obj
->delayRead(DeferredRead(DeferReader
, this, CommRead(conn
, buf
, len
, callback
)));
253 mem_obj
->mostBytesAllowed().delayRead(DeferredRead(DeferReader
, this, CommRead(conn
, buf
, len
, callback
)));
260 if (fd_table
[conn
->fd
].closing()) {
261 // Readers must have closing callbacks if they want to be notified. No
262 // readers appeared to care around 2009/12/14 as they skipped reading
263 // for other reasons. Closing may already be true at the delyaAwareRead
264 // call time or may happen while we wait after delayRead() above.
265 debugs(20, 3, HERE
<< "wont read from closing " << conn
<< " for " <<
267 return; // the read callback will never be called
270 comm_read(conn
, buf
, amountToRead
, callback
);
274 StoreEntry::bytesWanted (Range
<size_t> const aRange
) const
276 assert (aRange
.size());
279 return aRange
.end
- 1;
281 #if URL_CHECKSUM_DEBUG
283 mem_obj
->checkUrlChecksum();
287 /* Always read *something* here - we haven't got the header yet */
288 if (EBIT_TEST(flags
, ENTRY_FWD_HDR_WAIT
))
289 return aRange
.end
- 1;
291 if (!mem_obj
->readAheadPolicyCanRead())
294 return mem_obj
->mostBytesWanted(aRange
.end
- 1);
298 StoreEntry::checkDeferRead(int fd
) const
300 return (bytesWanted(Range
<size_t>(0,INT_MAX
)) == 0);
304 StoreEntry::setNoDelay (bool const newValue
)
307 mem_obj
->setNoDelay(newValue
);
311 StoreEntry::storeClientType() const
313 /* The needed offset isn't in memory
314 * XXX TODO: this is wrong for range requests
315 * as the needed offset may *not* be 0, AND
316 * offset 0 in the memory object is the HTTP headers.
319 if (mem_status
== IN_MEMORY
&& UsingSmp()) {
320 // clients of an object cached in shared memory are memory clients
321 return STORE_MEM_CLIENT
;
326 if (mem_obj
->inmem_lo
)
327 return STORE_DISK_CLIENT
;
329 if (EBIT_TEST(flags
, ENTRY_ABORTED
)) {
330 /* I don't think we should be adding clients to aborted entries */
331 debugs(20, 1, "storeClientType: adding to ENTRY_ABORTED entry");
332 return STORE_MEM_CLIENT
;
335 if (store_status
== STORE_OK
) {
336 /* the object has completed. */
338 if (mem_obj
->inmem_lo
== 0 && !isEmpty()) {
339 if (swap_status
== SWAPOUT_DONE
) {
340 debugs(20,7, HERE
<< mem_obj
<< " lo: " << mem_obj
->inmem_lo
<< " hi: " << mem_obj
->endOffset() << " size: " << mem_obj
->object_sz
);
341 if (mem_obj
->endOffset() == mem_obj
->object_sz
) {
342 /* hot object fully swapped in */
343 return STORE_MEM_CLIENT
;
346 /* Memory-only, or currently being swapped out */
347 return STORE_MEM_CLIENT
;
350 return STORE_DISK_CLIENT
;
353 /* here and past, entry is STORE_PENDING */
355 * If this is the first client, let it be the mem client
357 if (mem_obj
->nclients
== 1)
358 return STORE_MEM_CLIENT
;
361 * If there is no disk file to open yet, we must make this a
362 * mem client. If we can't open the swapin file before writing
363 * to the client, there is no guarantee that we will be able
364 * to open it later when we really need it.
366 if (swap_status
== SWAPOUT_NONE
)
367 return STORE_MEM_CLIENT
;
370 * otherwise, make subsequent clients read from disk so they
371 * can not delay the first, and vice-versa.
373 return STORE_DISK_CLIENT
;
376 StoreEntry::StoreEntry():
377 hidden_mem_obj(NULL
),
380 debugs(20, 3, HERE
<< "new StoreEntry " << this);
383 expires
= lastmod
= lastref
= timestamp
= -1;
385 swap_status
= SWAPOUT_NONE
;
390 StoreEntry::StoreEntry(const char *aUrl
, const char *aLogUrl
):
391 hidden_mem_obj(NULL
),
394 debugs(20, 3, HERE
<< "new StoreEntry " << this);
395 mem_obj
= new MemObject(aUrl
, aLogUrl
);
397 expires
= lastmod
= lastref
= timestamp
= -1;
399 swap_status
= SWAPOUT_NONE
;
404 StoreEntry::~StoreEntry()
406 if (swap_filen
>= 0) {
407 SwapDir
&sd
= dynamic_cast<SwapDir
&>(*store());
408 sd
.disconnect(*this);
410 delete hidden_mem_obj
;
414 StoreEntry::destroyMemObject()
416 debugs(20, 3, HERE
<< "destroyMemObject " << mem_obj
);
417 setMemStatus(NOT_IN_MEMORY
);
418 MemObject
*mem
= mem_obj
;
421 delete hidden_mem_obj
;
422 hidden_mem_obj
= NULL
;
426 StoreEntry::hideMemObject()
428 debugs(20, 3, HERE
<< "hiding " << mem_obj
);
430 assert(!hidden_mem_obj
);
431 hidden_mem_obj
= mem_obj
;
436 destroyStoreEntry(void *data
)
438 debugs(20, 3, HERE
<< "destroyStoreEntry: destroying " << data
);
439 StoreEntry
*e
= static_cast<StoreEntry
*>(static_cast<hash_link
*>(data
));
442 if (e
== NullStoreEntry::getInstance())
445 e
->destroyMemObject();
449 assert(e
->key
== NULL
);
454 /* ----- INTERFACE BETWEEN STORAGE MANAGER AND HASH TABLE FUNCTIONS --------- */
457 StoreEntry::hashInsert(const cache_key
* someKey
)
459 debugs(20, 3, "StoreEntry::hashInsert: Inserting Entry " << this << " key '" << storeKeyText(someKey
) << "'");
460 key
= storeKeyDup(someKey
);
461 hash_join(store_table
, this);
465 StoreEntry::hashDelete()
467 hash_remove_link(store_table
, this);
468 storeKeyFree((const cache_key
*)key
);
472 /* -------------------------------------------------------------------------- */
475 /* get rid of memory copy of the object */
477 StoreEntry::purgeMem()
482 debugs(20, 3, "StoreEntry::purgeMem: Freeing memory-copy of " << getMD5Text());
486 if (swap_status
!= SWAPOUT_DONE
)
490 /* RBC 20050104 this is wrong- memory ref counting
491 * is not at all equivalent to the store 'usage' concept
492 * which the replacement policies should be acting upon.
493 * specifically, object iteration within stores needs
494 * memory ref counting to prevent race conditions,
495 * but this should not influence store replacement.
502 debugs(20, 3, "StoreEntry::lock: key '" << getMD5Text() <<"' count=" <<
504 lastref
= squid_curtime
;
505 Store::Root().reference(*this);
509 StoreEntry::setReleaseFlag()
511 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
514 debugs(20, 3, "StoreEntry::setReleaseFlag: '" << getMD5Text() << "'");
516 EBIT_SET(flags
, RELEASE_REQUEST
);
520 StoreEntry::releaseRequest()
522 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
528 * Clear cachable flag here because we might get called before
529 * anyone else even looks at the cachability flag. Also, this
530 * prevents httpMakePublic from really setting a public key.
532 EBIT_CLR(flags
, ENTRY_CACHABLE
);
537 /* unlock object, return -1 if object get released after unlock
538 * otherwise lock_count */
543 debugs(20, 3, "StoreEntry::unlock: key '" << getMD5Text() << "' count=" << lock_count
);
546 return (int) lock_count
;
548 if (store_status
== STORE_PENDING
)
551 assert(storePendingNClients(this) == 0);
553 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
559 if (EBIT_TEST(flags
, KEY_PRIVATE
))
560 debugs(20, 1, "WARNING: " << __FILE__
<< ":" << __LINE__
<< ": found KEY_PRIVATE");
562 Store::Root().handleIdleEntry(*this); // may delete us
567 StoreEntry::getPublicByRequestMethod (StoreClient
*aClient
, HttpRequest
* request
, const HttpRequestMethod
& method
)
570 StoreEntry
*result
= storeGetPublicByRequestMethod( request
, method
);
573 aClient
->created (NullStoreEntry::getInstance());
575 aClient
->created (result
);
579 StoreEntry::getPublicByRequest (StoreClient
*aClient
, HttpRequest
* request
)
582 StoreEntry
*result
= storeGetPublicByRequest (request
);
585 result
= NullStoreEntry::getInstance();
587 aClient
->created (result
);
591 StoreEntry::getPublic (StoreClient
*aClient
, const char *uri
, const HttpRequestMethod
& method
)
594 StoreEntry
*result
= storeGetPublic (uri
, method
);
597 result
= NullStoreEntry::getInstance();
599 aClient
->created (result
);
603 storeGetPublic(const char *uri
, const HttpRequestMethod
& method
)
605 return Store::Root().get(storeKeyPublic(uri
, method
));
609 storeGetPublicByRequestMethod(HttpRequest
* req
, const HttpRequestMethod
& method
)
611 return Store::Root().get(storeKeyPublicByRequestMethod(req
, method
));
615 storeGetPublicByRequest(HttpRequest
* req
)
617 StoreEntry
*e
= storeGetPublicByRequestMethod(req
, req
->method
);
619 if (e
== NULL
&& req
->method
== METHOD_HEAD
)
620 /* We can generate a HEAD reply from a cached GET object */
621 e
= storeGetPublicByRequestMethod(req
, METHOD_GET
);
629 static int key_counter
= 0;
631 if (++key_counter
< 0)
637 /* RBC 20050104 AFAICT this should become simpler:
638 * rather than reinserting with a special key it should be marked
639 * as 'released' and then cleaned up when refcounting indicates.
640 * the StoreHashIndex could well implement its 'released' in the
642 * Also, clean log writing should skip over ia,t
643 * Otherwise, we need a 'remove from the index but not the store
647 StoreEntry::setPrivateKey()
649 const cache_key
*newkey
;
651 if (key
&& EBIT_TEST(flags
, KEY_PRIVATE
))
652 return; /* is already private */
656 storeDirSwapLog(this, SWAP_LOG_DEL
);
661 if (mem_obj
!= NULL
) {
662 mem_obj
->id
= getKeyCounter();
663 newkey
= storeKeyPrivate(mem_obj
->url
, mem_obj
->method
, mem_obj
->id
);
665 newkey
= storeKeyPrivate("JUNK", METHOD_NONE
, getKeyCounter());
668 assert(hash_lookup(store_table
, newkey
) == NULL
);
669 EBIT_SET(flags
, KEY_PRIVATE
);
674 StoreEntry::setPublicKey()
676 StoreEntry
*e2
= NULL
;
677 const cache_key
*newkey
;
679 if (key
&& !EBIT_TEST(flags
, KEY_PRIVATE
))
680 return; /* is already public */
685 * We can't make RELEASE_REQUEST objects public. Depending on
686 * when RELEASE_REQUEST gets set, we might not be swapping out
687 * the object. If we're not swapping out, then subsequent
688 * store clients won't be able to access object data which has
689 * been freed from memory.
691 * If RELEASE_REQUEST is set, then ENTRY_CACHABLE should not
692 * be set, and StoreEntry::setPublicKey() should not be called.
694 #if MORE_DEBUG_OUTPUT
696 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
697 debugs(20, 1, "assertion failed: RELEASE key " << key
<< ", url " << mem_obj
->url
);
701 assert(!EBIT_TEST(flags
, RELEASE_REQUEST
));
703 if (mem_obj
->request
) {
704 HttpRequest
*request
= mem_obj
->request
;
706 if (!mem_obj
->vary_headers
) {
707 /* First handle the case where the object no longer varies */
708 safe_free(request
->vary_headers
);
710 if (request
->vary_headers
&& strcmp(request
->vary_headers
, mem_obj
->vary_headers
) != 0) {
711 /* Oops.. the variance has changed. Kill the base object
712 * to record the new variance key
714 safe_free(request
->vary_headers
); /* free old "bad" variance key */
715 StoreEntry
*pe
= storeGetPublic(mem_obj
->url
, mem_obj
->method
);
721 /* Make sure the request knows the variance status */
722 if (!request
->vary_headers
) {
723 const char *vary
= httpMakeVaryMark(request
, mem_obj
->getReply());
726 request
->vary_headers
= xstrdup(vary
);
730 // TODO: storeGetPublic() calls below may create unlocked entries.
731 // We should add/use storeHas() API or lock/unlock those entries.
732 if (mem_obj
->vary_headers
&& !storeGetPublic(mem_obj
->url
, mem_obj
->method
)) {
733 /* Create "vary" base object */
735 StoreEntry
*pe
= storeCreateEntry(mem_obj
->url
, mem_obj
->log_url
, request
->flags
, request
->method
);
736 /* We are allowed to do this typecast */
737 HttpReply
*rep
= new HttpReply
;
738 rep
->setHeaders(HTTP_OK
, "Internal marker object", "x-squid-internal/vary", -1, -1, squid_curtime
+ 100000);
739 vary
= mem_obj
->getReply()->header
.getList(HDR_VARY
);
742 /* Again, we own this structure layout */
743 rep
->header
.putStr(HDR_VARY
, vary
.termedBuf());
747 #if X_ACCELERATOR_VARY
748 vary
= mem_obj
->getReply()->header
.getList(HDR_X_ACCELERATOR_VARY
);
750 if (vary
.defined()) {
751 /* Again, we own this structure layout */
752 rep
->header
.putStr(HDR_X_ACCELERATOR_VARY
, vary
.termedBuf());
757 pe
->replaceHttpReply(rep
);
768 newkey
= storeKeyPublicByRequest(mem_obj
->request
);
770 newkey
= storeKeyPublic(mem_obj
->url
, mem_obj
->method
);
772 if ((e2
= (StoreEntry
*) hash_lookup(store_table
, newkey
))) {
773 debugs(20, 3, "StoreEntry::setPublicKey: Making old '" << mem_obj
->url
<< "' private.");
777 if (mem_obj
->request
)
778 newkey
= storeKeyPublicByRequest(mem_obj
->request
);
780 newkey
= storeKeyPublic(mem_obj
->url
, mem_obj
->method
);
786 EBIT_CLR(flags
, KEY_PRIVATE
);
791 storeDirSwapLog(this, SWAP_LOG_ADD
);
795 storeCreateEntry(const char *url
, const char *log_url
, request_flags flags
, const HttpRequestMethod
& method
)
797 StoreEntry
*e
= NULL
;
798 MemObject
*mem
= NULL
;
799 debugs(20, 3, "storeCreateEntry: '" << url
<< "'");
801 e
= new StoreEntry(url
, log_url
);
802 e
->lock_count
= 1; /* Note lock here w/o calling storeLock() */
804 mem
->method
= method
;
806 if (neighbors_do_private_keys
|| !flags
.hierarchical
)
811 if (flags
.cachable
) {
812 EBIT_SET(e
->flags
, ENTRY_CACHABLE
);
813 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
815 /* StoreEntry::releaseRequest() clears ENTRY_CACHABLE */
819 e
->store_status
= STORE_PENDING
;
820 e
->setMemStatus(NOT_IN_MEMORY
);
822 e
->lastref
= squid_curtime
;
823 e
->timestamp
= -1; /* set in StoreEntry::timestampsSet() */
824 e
->ping_status
= PING_NONE
;
825 EBIT_SET(e
->flags
, ENTRY_VALIDATED
);
829 /* Mark object as expired */
831 StoreEntry::expireNow()
833 debugs(20, 3, "StoreEntry::expireNow: '" << getMD5Text() << "'");
834 expires
= squid_curtime
;
838 storeWriteComplete (void *data
, StoreIOBuffer wroteBuffer
)
840 PROF_start(storeWriteComplete
);
841 StoreEntry
*e
= (StoreEntry
*)data
;
843 if (EBIT_TEST(e
->flags
, DELAY_SENDING
)) {
844 PROF_stop(storeWriteComplete
);
849 PROF_stop(storeWriteComplete
);
853 StoreEntry::write (StoreIOBuffer writeBuffer
)
855 assert(mem_obj
!= NULL
);
856 /* This assert will change when we teach the store to update */
857 PROF_start(StoreEntry_write
);
858 assert(store_status
== STORE_PENDING
);
860 if (!writeBuffer
.length
) {
861 /* the headers are received already, but we have not received
862 * any body data. There are BROKEN abuses of HTTP which require
863 * the headers to be passed along before any body data - see
864 * http://developer.apple.com/documentation/QuickTime/QTSS/Concepts/chapter_2_section_14.html
865 * for an example of such bad behaviour. To accomodate this, if
866 * we have a empty write arrive, we flush to our clients.
869 PROF_stop(StoreEntry_write
);
874 debugs(20, 5, "storeWrite: writing " << writeBuffer
.length
<< " bytes for '" << getMD5Text() << "'");
875 PROF_stop(StoreEntry_write
);
876 storeGetMemSpace(writeBuffer
.length
);
877 mem_obj
->write (writeBuffer
, storeWriteComplete
, this);
880 /* Append incoming data from a primary server to an entry. */
882 StoreEntry::append(char const *buf
, int len
)
884 assert(mem_obj
!= NULL
);
886 assert(store_status
== STORE_PENDING
);
888 StoreIOBuffer tempBuffer
;
889 tempBuffer
.data
= (char *)buf
;
890 tempBuffer
.length
= len
;
892 * XXX sigh, offset might be < 0 here, but it gets "corrected"
893 * later. This offset crap is such a mess.
895 tempBuffer
.offset
= mem_obj
->endOffset() - (getReply() ? getReply()->hdr_sz
: 0);
901 storeAppendPrintf(StoreEntry
* e
, const char *fmt
,...)
906 storeAppendVPrintf(e
, fmt
, args
);
910 /* used be storeAppendPrintf and Packer */
912 storeAppendVPrintf(StoreEntry
* e
, const char *fmt
, va_list vargs
)
914 LOCAL_ARRAY(char, buf
, 4096);
916 vsnprintf(buf
, 4096, fmt
, vargs
);
917 e
->append(buf
, strlen(buf
));
920 struct _store_check_cachable_hist
{
924 int not_entry_cachable
;
925 int wrong_content_length
;
930 int too_many_open_files
;
931 int too_many_open_fds
;
937 } store_check_cachable_hist
;
940 storeTooManyDiskFilesOpen(void)
942 if (Config
.max_open_disk_fds
== 0)
945 if (store_open_disk_fd
> Config
.max_open_disk_fds
)
952 StoreEntry::checkTooSmall()
954 if (EBIT_TEST(flags
, ENTRY_SPECIAL
))
957 if (STORE_OK
== store_status
)
958 if (mem_obj
->object_sz
< 0 ||
959 mem_obj
->object_sz
< Config
.Store
.minObjectSize
)
961 if (getReply()->content_length
> -1)
962 if (getReply()->content_length
< Config
.Store
.minObjectSize
)
967 // TODO: remove checks already performed by swapoutPossible()
968 // TODO: move "too many open..." checks outside -- we are called too early/late
970 StoreEntry::checkCachable()
972 #if CACHE_ALL_METHODS
974 if (mem_obj
->method
!= METHOD_GET
) {
975 debugs(20, 2, "StoreEntry::checkCachable: NO: non-GET method");
976 store_check_cachable_hist
.no
.non_get
++;
979 if (store_status
== STORE_OK
&& EBIT_TEST(flags
, ENTRY_BAD_LENGTH
)) {
980 debugs(20, 2, "StoreEntry::checkCachable: NO: wrong content-length");
981 store_check_cachable_hist
.no
.wrong_content_length
++;
982 } else if (!EBIT_TEST(flags
, ENTRY_CACHABLE
)) {
983 debugs(20, 2, "StoreEntry::checkCachable: NO: not cachable");
984 store_check_cachable_hist
.no
.not_entry_cachable
++;
985 } else if (EBIT_TEST(flags
, ENTRY_NEGCACHED
)) {
986 debugs(20, 3, "StoreEntry::checkCachable: NO: negative cached");
987 store_check_cachable_hist
.no
.negative_cached
++;
988 return 0; /* avoid release call below */
989 } else if ((getReply()->content_length
> 0 &&
990 getReply()->content_length
991 > Config
.Store
.maxObjectSize
) ||
992 mem_obj
->endOffset() > Config
.Store
.maxObjectSize
) {
993 debugs(20, 2, "StoreEntry::checkCachable: NO: too big");
994 store_check_cachable_hist
.no
.too_big
++;
995 } else if (getReply()->content_length
> Config
.Store
.maxObjectSize
) {
996 debugs(20, 2, "StoreEntry::checkCachable: NO: too big");
997 store_check_cachable_hist
.no
.too_big
++;
998 } else if (checkTooSmall()) {
999 debugs(20, 2, "StoreEntry::checkCachable: NO: too small");
1000 store_check_cachable_hist
.no
.too_small
++;
1001 } else if (EBIT_TEST(flags
, KEY_PRIVATE
)) {
1002 debugs(20, 3, "StoreEntry::checkCachable: NO: private key");
1003 store_check_cachable_hist
.no
.private_key
++;
1004 } else if (swap_status
!= SWAPOUT_NONE
) {
1006 * here we checked the swap_status because the remaining
1007 * cases are only relevant only if we haven't started swapping
1008 * out the object yet.
1011 } else if (storeTooManyDiskFilesOpen()) {
1012 debugs(20, 2, "StoreEntry::checkCachable: NO: too many disk files open");
1013 store_check_cachable_hist
.no
.too_many_open_files
++;
1014 } else if (fdNFree() < RESERVED_FD
) {
1015 debugs(20, 2, "StoreEntry::checkCachable: NO: too many FD's open");
1016 store_check_cachable_hist
.no
.too_many_open_fds
++;
1018 store_check_cachable_hist
.yes
.Default
++;
1023 /* StoreEntry::releaseRequest() cleared ENTRY_CACHABLE */
1028 storeCheckCachableStats(StoreEntry
*sentry
)
1030 storeAppendPrintf(sentry
, "Category\t Count\n");
1032 #if CACHE_ALL_METHODS
1034 storeAppendPrintf(sentry
, "no.non_get\t%d\n",
1035 store_check_cachable_hist
.no
.non_get
);
1038 storeAppendPrintf(sentry
, "no.not_entry_cachable\t%d\n",
1039 store_check_cachable_hist
.no
.not_entry_cachable
);
1040 storeAppendPrintf(sentry
, "no.wrong_content_length\t%d\n",
1041 store_check_cachable_hist
.no
.wrong_content_length
);
1042 storeAppendPrintf(sentry
, "no.negative_cached\t%d\n",
1043 store_check_cachable_hist
.no
.negative_cached
);
1044 storeAppendPrintf(sentry
, "no.too_big\t%d\n",
1045 store_check_cachable_hist
.no
.too_big
);
1046 storeAppendPrintf(sentry
, "no.too_small\t%d\n",
1047 store_check_cachable_hist
.no
.too_small
);
1048 storeAppendPrintf(sentry
, "no.private_key\t%d\n",
1049 store_check_cachable_hist
.no
.private_key
);
1050 storeAppendPrintf(sentry
, "no.too_many_open_files\t%d\n",
1051 store_check_cachable_hist
.no
.too_many_open_files
);
1052 storeAppendPrintf(sentry
, "no.too_many_open_fds\t%d\n",
1053 store_check_cachable_hist
.no
.too_many_open_fds
);
1054 storeAppendPrintf(sentry
, "yes.default\t%d\n",
1055 store_check_cachable_hist
.yes
.Default
);
1059 StoreEntry::complete()
1061 debugs(20, 3, "storeComplete: '" << getMD5Text() << "'");
1063 if (store_status
!= STORE_PENDING
) {
1065 * if we're not STORE_PENDING, then probably we got aborted
1066 * and there should be NO clients on this entry
1068 assert(EBIT_TEST(flags
, ENTRY_ABORTED
));
1069 assert(mem_obj
->nclients
== 0);
1073 /* This is suspect: mem obj offsets include the headers. do we adjust for that
1074 * in use of object_sz?
1076 mem_obj
->object_sz
= mem_obj
->endOffset();
1078 store_status
= STORE_OK
;
1080 assert(mem_status
== NOT_IN_MEMORY
);
1082 if (!validLength()) {
1083 EBIT_SET(flags
, ENTRY_BAD_LENGTH
);
1087 #if USE_CACHE_DIGESTS
1088 if (mem_obj
->request
)
1089 mem_obj
->request
->hier
.store_complete_stop
= current_time
;
1093 * We used to call invokeHandlers, then storeSwapOut. However,
1094 * Madhukar Reddy <myreddy@persistence.com> reported that
1095 * responses without content length would sometimes get released
1096 * in client_side, thinking that the response is incomplete.
1102 * Someone wants to abort this transfer. Set the reason in the
1103 * request structure, call the server-side callback and mark the
1104 * entry for releasing
1109 statCounter
.aborted_requests
++;
1110 assert(store_status
== STORE_PENDING
);
1111 assert(mem_obj
!= NULL
);
1112 debugs(20, 6, "storeAbort: " << getMD5Text());
1114 lock(); /* lock while aborting */
1119 EBIT_SET(flags
, ENTRY_ABORTED
);
1121 setMemStatus(NOT_IN_MEMORY
);
1123 store_status
= STORE_OK
;
1125 /* Notify the server side */
1129 * Should we check abort.data for validity?
1131 if (mem_obj
->abort
.callback
) {
1132 if (!cbdataReferenceValid(mem_obj
->abort
.data
))
1133 debugs(20,1,HERE
<< "queueing event when abort.data is not valid");
1134 eventAdd("mem_obj->abort.callback",
1135 mem_obj
->abort
.callback
,
1136 mem_obj
->abort
.data
,
1142 /* XXX Should we reverse these two, so that there is no
1143 * unneeded disk swapping triggered?
1145 /* Notify the client side */
1148 // abort swap out, invalidating what was created so far (release follows)
1149 swapOutFileClose(StoreIOState::writerGone
);
1151 unlock(); /* unlock */
1155 * Clear Memory storage to accommodate the given object len
1158 storeGetMemSpace(int size
)
1160 PROF_start(storeGetMemSpace
);
1161 StoreEntry
*e
= NULL
;
1163 static time_t last_check
= 0;
1164 size_t pages_needed
;
1165 RemovalPurgeWalker
*walker
;
1167 if (squid_curtime
== last_check
) {
1168 PROF_stop(storeGetMemSpace
);
1172 last_check
= squid_curtime
;
1174 pages_needed
= (size
/ SM_PAGE_SIZE
) + 1;
1176 if (mem_node::InUseCount() + pages_needed
< store_pages_max
) {
1177 PROF_stop(storeGetMemSpace
);
1181 debugs(20, 2, "storeGetMemSpace: Starting, need " << pages_needed
<<
1184 /* XXX what to set as max_scan here? */
1185 walker
= mem_policy
->PurgeInit(mem_policy
, 100000);
1187 while ((e
= walker
->Next(walker
))) {
1191 if (mem_node::InUseCount() + pages_needed
< store_pages_max
)
1195 walker
->Done(walker
);
1196 debugs(20, 3, "storeGetMemSpace stats:");
1197 debugs(20, 3, " " << std::setw(6) << hot_obj_count
<< " HOT objects");
1198 debugs(20, 3, " " << std::setw(6) << released
<< " were released");
1199 PROF_stop(storeGetMemSpace
);
1203 /* thunk through to Store::Root().maintain(). Note that this would be better still
1204 * if registered against the root store itself, but that requires more complex
1205 * update logic - bigger fish to fry first. Long term each store when
1206 * it becomes active will self register
1209 Store::Maintain(void *notused
)
1211 Store::Root().maintain();
1213 /* Reregister a maintain event .. */
1214 eventAdd("MaintainSwapSpace", Maintain
, NULL
, 1.0, 1);
1218 /* The maximum objects to scan for maintain storage space */
1219 #define MAINTAIN_MAX_SCAN 1024
1220 #define MAINTAIN_MAX_REMOVE 64
1223 * This routine is to be called by main loop in main.c.
1224 * It removes expired objects on only one bucket for each time called.
1226 * This should get called 1/s from main().
1229 StoreController::maintain()
1231 static time_t last_warn_time
= 0;
1233 PROF_start(storeMaintainSwapSpace
);
1234 swapDir
->maintain();
1236 /* this should be emitted by the oversize dir, not globally */
1238 if (Store::Root().currentSize() > Store::Root().maxSize()) {
1239 if (squid_curtime
- last_warn_time
> 10) {
1240 debugs(20, 0, "WARNING: Disk space over limit: "
1241 << Store::Root().currentSize() / 1024.0 << " KB > "
1242 << (Store::Root().maxSize() >> 10) << " KB");
1243 last_warn_time
= squid_curtime
;
1247 PROF_stop(storeMaintainSwapSpace
);
1250 /* release an object from a cache */
1252 StoreEntry::release()
1254 PROF_start(storeRelease
);
1255 debugs(20, 3, "storeRelease: Releasing: '" << getMD5Text() << "'");
1256 /* If, for any reason we can't discard this object because of an
1257 * outstanding request, mark it for pending release */
1261 debugs(20, 3, "storeRelease: Only setting RELEASE_REQUEST bit");
1263 PROF_stop(storeRelease
);
1267 if (StoreController::store_dirs_rebuilding
&& swap_filen
> -1) {
1273 if (swap_filen
> -1) {
1275 * Fake a call to StoreEntry->lock() When rebuilding is done,
1276 * we'll just call StoreEntry->unlock() on these.
1280 LateReleaseStack
.push_back(this);
1282 destroyStoreEntry(static_cast<hash_link
*>(this));
1283 // "this" is no longer valid
1286 PROF_stop(storeRelease
);
1290 storeLog(STORE_LOG_RELEASE
, this);
1292 if (swap_filen
> -1) {
1293 // log before unlink() below clears swap_filen
1294 if (!EBIT_TEST(flags
, KEY_PRIVATE
))
1295 storeDirSwapLog(this, SWAP_LOG_DEL
);
1300 setMemStatus(NOT_IN_MEMORY
);
1301 destroyStoreEntry(static_cast<hash_link
*>(this));
1302 PROF_stop(storeRelease
);
1306 storeLateRelease(void *unused
)
1312 if (StoreController::store_dirs_rebuilding
) {
1313 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 1.0, 1);
1317 for (i
= 0; i
< 10; i
++) {
1318 e
= LateReleaseStack
.count
? LateReleaseStack
.pop() : NULL
;
1322 debugs(20, 1, "storeLateRelease: released " << n
<< " objects");
1330 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 0.0, 1);
1333 /* return 1 if a store entry is locked */
1335 StoreEntry::locked() const
1340 if (swap_status
== SWAPOUT_WRITING
)
1343 if (store_status
== STORE_PENDING
)
1347 * SPECIAL, PUBLIC entries should be "locked"
1349 if (EBIT_TEST(flags
, ENTRY_SPECIAL
))
1350 if (!EBIT_TEST(flags
, KEY_PRIVATE
))
1357 StoreEntry::validLength() const
1360 const HttpReply
*reply
;
1361 assert(mem_obj
!= NULL
);
1363 debugs(20, 3, "storeEntryValidLength: Checking '" << getMD5Text() << "'");
1364 debugs(20, 5, "storeEntryValidLength: object_len = " <<
1366 debugs(20, 5, "storeEntryValidLength: hdr_sz = " << reply
->hdr_sz
);
1367 debugs(20, 5, "storeEntryValidLength: content_length = " << reply
->content_length
);
1369 if (reply
->content_length
< 0) {
1370 debugs(20, 5, "storeEntryValidLength: Unspecified content length: " << getMD5Text());
1374 if (reply
->hdr_sz
== 0) {
1375 debugs(20, 5, "storeEntryValidLength: Zero header size: " << getMD5Text());
1379 if (mem_obj
->method
== METHOD_HEAD
) {
1380 debugs(20, 5, "storeEntryValidLength: HEAD request: " << getMD5Text());
1384 if (reply
->sline
.status
== HTTP_NOT_MODIFIED
)
1387 if (reply
->sline
.status
== HTTP_NO_CONTENT
)
1390 diff
= reply
->hdr_sz
+ reply
->content_length
- objectLen();
1395 debugs(20, 3, "storeEntryValidLength: " << (diff
< 0 ? -diff
: diff
) << " bytes too " << (diff
< 0 ? "big" : "small") <<"; '" << getMD5Text() << "'" );
1401 storeRegisterWithCacheManager(void)
1403 Mgr::RegisterAction("storedir", "Store Directory Stats", Store::Stats
, 0, 1);
1404 Mgr::RegisterAction("store_io", "Store IO Interface Stats", &Mgr::StoreIoAction::Create
, 0, 1);
1405 Mgr::RegisterAction("store_check_cachable_stats", "storeCheckCachable() Stats",
1406 storeCheckCachableStats
, 0, 1);
1413 mem_policy
= createRemovalPolicy(Config
.memPolicy
);
1416 eventAdd("storeLateRelease", storeLateRelease
, NULL
, 1.0, 1);
1417 Store::Root().init();
1418 storeRebuildStart();
1420 storeRegisterWithCacheManager();
1424 storeConfigure(void)
1426 store_swap_high
= (long) (((float) Store::Root().maxSize() *
1427 (float) Config
.Swap
.highWaterMark
) / (float) 100);
1428 store_swap_low
= (long) (((float) Store::Root().maxSize() *
1429 (float) Config
.Swap
.lowWaterMark
) / (float) 100);
1430 store_pages_max
= Config
.memMaxSize
/ sizeof(mem_node
);
1434 StoreEntry::memoryCachable() const
1436 if (mem_obj
== NULL
)
1439 if (mem_obj
->data_hdr
.size() == 0)
1442 if (mem_obj
->inmem_lo
!= 0)
1445 if (!Config
.onoff
.memory_cache_first
&& swap_status
== SWAPOUT_DONE
&& refcount
== 1)
1449 const int64_t expectedSize
= mem_obj
->expectedReplySize();
1450 // objects of unknown size are not allowed into memory cache, for now
1451 if (expectedSize
< 0 ||
1452 expectedSize
> static_cast<int64_t>(Config
.Store
.maxInMemObjSize
))
1460 StoreEntry::checkNegativeHit() const
1462 if (!EBIT_TEST(flags
, ENTRY_NEGCACHED
))
1465 if (expires
<= squid_curtime
)
1468 if (store_status
!= STORE_OK
)
1475 * Set object for negative caching.
1476 * Preserves any expiry information given by the server.
1477 * In absence of proper expiry info it will set to expire immediately,
1478 * or with HTTP-violations enabled the configured negative-TTL is observed
1481 StoreEntry::negativeCache()
1483 // XXX: should make the default for expires 0 instead of -1
1484 // so we can distinguish "Expires: -1" from nothing.
1486 #if USE_HTTP_VIOLATIONS
1487 expires
= squid_curtime
+ Config
.negativeTtl
;
1489 expires
= squid_curtime
;
1491 EBIT_SET(flags
, ENTRY_NEGCACHED
);
1495 storeFreeMemory(void)
1498 #if USE_CACHE_DIGESTS
1501 cacheDigestDestroy(store_digest
);
1505 store_digest
= NULL
;
1509 expiresMoreThan(time_t expires
, time_t when
)
1511 if (expires
< 0) /* No Expires given */
1514 return (expires
> (squid_curtime
+ when
));
1518 StoreEntry::validToSend() const
1520 if (EBIT_TEST(flags
, RELEASE_REQUEST
))
1523 if (EBIT_TEST(flags
, ENTRY_NEGCACHED
))
1524 if (expires
<= squid_curtime
)
1527 if (EBIT_TEST(flags
, ENTRY_ABORTED
))
1534 StoreEntry::timestampsSet()
1536 const HttpReply
*reply
= getReply();
1537 time_t served_date
= reply
->date
;
1538 int age
= reply
->header
.getInt(HDR_AGE
);
1539 /* Compute the timestamp, mimicking RFC2616 section 13.2.3. */
1540 /* make sure that 0 <= served_date <= squid_curtime */
1542 if (served_date
< 0 || served_date
> squid_curtime
)
1543 served_date
= squid_curtime
;
1546 * If the returned Date: is more than 24 hours older than
1547 * the squid_curtime, then one of us needs to use NTP to set our
1548 * clock. We'll pretend that our clock is right.
1550 else if (served_date
< (squid_curtime
- 24 * 60 * 60) )
1551 served_date
= squid_curtime
;
1554 * Compensate with Age header if origin server clock is ahead
1555 * of us and there is a cache in between us and the origin
1556 * server. But DONT compensate if the age value is larger than
1557 * squid_curtime because it results in a negative served_date.
1559 if (age
> squid_curtime
- served_date
)
1560 if (squid_curtime
> age
)
1561 served_date
= squid_curtime
- age
;
1563 // compensate for Squid-to-server and server-to-Squid delays
1564 if (mem_obj
&& mem_obj
->request
) {
1565 const time_t request_sent
=
1566 mem_obj
->request
->hier
.peer_http_request_sent
.tv_sec
;
1567 if (0 < request_sent
&& request_sent
< squid_curtime
)
1568 served_date
-= (squid_curtime
- request_sent
);
1571 if (reply
->expires
> 0 && reply
->date
> -1)
1572 expires
= served_date
+ (reply
->expires
- reply
->date
);
1574 expires
= reply
->expires
;
1576 lastmod
= reply
->last_modified
;
1578 timestamp
= served_date
;
1582 StoreEntry::registerAbort(STABH
* cb
, void *data
)
1585 assert(mem_obj
->abort
.callback
== NULL
);
1586 mem_obj
->abort
.callback
= cb
;
1587 mem_obj
->abort
.data
= cbdataReference(data
);
1591 StoreEntry::unregisterAbort()
1594 if (mem_obj
->abort
.callback
) {
1595 mem_obj
->abort
.callback
= NULL
;
1596 cbdataReferenceDone(mem_obj
->abort
.data
);
1601 StoreEntry::dump(int l
) const
1603 debugs(20, l
, "StoreEntry->key: " << getMD5Text());
1604 debugs(20, l
, "StoreEntry->next: " << next
);
1605 debugs(20, l
, "StoreEntry->mem_obj: " << mem_obj
);
1606 debugs(20, l
, "StoreEntry->timestamp: " << timestamp
);
1607 debugs(20, l
, "StoreEntry->lastref: " << lastref
);
1608 debugs(20, l
, "StoreEntry->expires: " << expires
);
1609 debugs(20, l
, "StoreEntry->lastmod: " << lastmod
);
1610 debugs(20, l
, "StoreEntry->swap_file_sz: " << swap_file_sz
);
1611 debugs(20, l
, "StoreEntry->refcount: " << refcount
);
1612 debugs(20, l
, "StoreEntry->flags: " << storeEntryFlags(this));
1613 debugs(20, l
, "StoreEntry->swap_dirn: " << swap_dirn
);
1614 debugs(20, l
, "StoreEntry->swap_filen: " << swap_filen
);
1615 debugs(20, l
, "StoreEntry->lock_count: " << lock_count
);
1616 debugs(20, l
, "StoreEntry->mem_status: " << mem_status
);
1617 debugs(20, l
, "StoreEntry->ping_status: " << ping_status
);
1618 debugs(20, l
, "StoreEntry->store_status: " << store_status
);
1619 debugs(20, l
, "StoreEntry->swap_status: " << swap_status
);
1623 * NOTE, this function assumes only two mem states
1626 StoreEntry::setMemStatus(mem_status_t new_status
)
1628 if (new_status
== mem_status
)
1632 assert(new_status
!= IN_MEMORY
); // we do not call this otherwise
1633 // This method was designed to update replacement policy, not to
1634 // actually purge something from the memory cache (TODO: rename?).
1635 // Shared memory cache does not have a policy that needs updates.
1636 mem_status
= new_status
;
1640 assert(mem_obj
!= NULL
);
1642 if (new_status
== IN_MEMORY
) {
1643 assert(mem_obj
->inmem_lo
== 0);
1645 if (EBIT_TEST(flags
, ENTRY_SPECIAL
)) {
1646 debugs(20, 4, "StoreEntry::setMemStatus: not inserting special " << mem_obj
->url
<< " into policy");
1648 mem_policy
->Add(mem_policy
, this, &mem_obj
->repl
);
1649 debugs(20, 4, "StoreEntry::setMemStatus: inserted mem node " << mem_obj
->url
<< " key: " << getMD5Text());
1652 hot_obj_count
++; // TODO: maintain for the shared hot cache as well
1654 if (EBIT_TEST(flags
, ENTRY_SPECIAL
)) {
1655 debugs(20, 4, "StoreEntry::setMemStatus: special entry " << mem_obj
->url
);
1657 mem_policy
->Remove(mem_policy
, this, &mem_obj
->repl
);
1658 debugs(20, 4, "StoreEntry::setMemStatus: removed mem node " << mem_obj
->url
);
1664 mem_status
= new_status
;
1668 StoreEntry::url() const
1671 return "[null_entry]";
1672 else if (mem_obj
== NULL
)
1673 return "[null_mem_obj]";
1675 return mem_obj
->url
;
1679 StoreEntry::createMemObject(const char *aUrl
, const char *aLogUrl
)
1684 if (hidden_mem_obj
) {
1685 debugs(20, 3, HERE
<< "restoring " << hidden_mem_obj
);
1686 mem_obj
= hidden_mem_obj
;
1687 hidden_mem_obj
= NULL
;
1688 mem_obj
->resetUrls(aUrl
, aLogUrl
);
1692 mem_obj
= new MemObject(aUrl
, aLogUrl
);
1695 /* this just sets DELAY_SENDING */
1697 StoreEntry::buffer()
1699 EBIT_SET(flags
, DELAY_SENDING
);
1702 /* this just clears DELAY_SENDING and Invokes the handlers */
1706 if (EBIT_TEST(flags
, DELAY_SENDING
)) {
1707 EBIT_CLR(flags
, DELAY_SENDING
);
1713 StoreEntry::objectLen() const
1715 assert(mem_obj
!= NULL
);
1716 return mem_obj
->object_sz
;
1720 StoreEntry::contentLen() const
1722 assert(mem_obj
!= NULL
);
1723 assert(getReply() != NULL
);
1724 return objectLen() - getReply()->hdr_sz
;
1728 StoreEntry::getReply () const
1730 if (NULL
== mem_obj
)
1733 return mem_obj
->getReply();
1740 debugs(20, 3, "StoreEntry::reset: " << url());
1742 HttpReply
*rep
= (HttpReply
*) getReply(); // bypass const
1744 expires
= lastmod
= timestamp
= -1;
1750 * This routine calls the SETUP routine for each fs type.
1751 * I don't know where the best place for this is, and I'm not going to shuffle
1752 * around large chunks of code right now (that can be done once its working.)
1761 * called to add another store removal policy module
1764 storeReplAdd(const char *type
, REMOVALPOLICYCREATE
* create
)
1768 /* find the number of currently known repl types */
1769 for (i
= 0; storerepl_list
&& storerepl_list
[i
].typestr
; i
++) {
1770 if (strcmp(storerepl_list
[i
].typestr
, type
) == 0) {
1771 debugs(20, 1, "WARNING: Trying to load store replacement policy " << type
<< " twice.");
1776 /* add the new type */
1777 storerepl_list
= static_cast<storerepl_entry_t
*>(xrealloc(storerepl_list
, (i
+ 2) * sizeof(storerepl_entry_t
)));
1779 memset(&storerepl_list
[i
+ 1], 0, sizeof(storerepl_entry_t
));
1781 storerepl_list
[i
].typestr
= type
;
1783 storerepl_list
[i
].create
= create
;
1787 * Create a removal policy instance
1790 createRemovalPolicy(RemovalPolicySettings
* settings
)
1792 storerepl_entry_t
*r
;
1794 for (r
= storerepl_list
; r
&& r
->typestr
; r
++) {
1795 if (strcmp(r
->typestr
, settings
->type
) == 0)
1796 return r
->create(settings
->args
);
1799 debugs(20, 1, "ERROR: Unknown policy " << settings
->type
);
1800 debugs(20, 1, "ERROR: Be sure to have set cache_replacement_policy");
1801 debugs(20, 1, "ERROR: and memory_replacement_policy in squid.conf!");
1802 fatalf("ERROR: Unknown policy %s\n", settings
->type
);
1803 return NULL
; /* NOTREACHED */
1808 storeSwapFileNumberSet(StoreEntry
* e
, sfileno filn
)
1810 if (e
->swap_file_number
== filn
)
1815 storeDirMapBitReset(e
->swap_file_number
);
1816 storeDirLRUDelete(e
);
1817 e
->swap_file_number
= -1;
1819 assert(-1 == e
->swap_file_number
);
1820 storeDirMapBitSet(e
->swap_file_number
= filn
);
1829 * Replace a store entry with
1830 * a new reply. This eats the reply.
1833 StoreEntry::replaceHttpReply(HttpReply
*rep
, bool andStartWriting
)
1835 debugs(20, 3, "StoreEntry::replaceHttpReply: " << url());
1838 debugs(20, 0, "Attempt to replace object with no in-memory representation");
1842 mem_obj
->replaceHttpReply(rep
);
1844 if (andStartWriting
)
1850 StoreEntry::startWriting()
1854 /* TODO: when we store headers serparately remove the header portion */
1855 /* TODO: mark the length of the headers ? */
1856 /* We ONLY want the headers */
1857 packerToStoreInit(&p
, this);
1862 const HttpReply
*rep
= getReply();
1865 rep
->packHeadersInto(&p
);
1866 mem_obj
->markEndOfReplyHeaders();
1868 httpBodyPackInto(&rep
->body
, &p
);
1875 StoreEntry::getSerialisedMetaData()
1877 StoreMeta
*tlv_list
= storeSwapMetaBuild(this);
1879 char *result
= storeSwapMetaPack(tlv_list
, &swap_hdr_sz
);
1880 storeSwapTLVFree(tlv_list
);
1881 assert (swap_hdr_sz
>= 0);
1882 mem_obj
->swap_hdr_sz
= (size_t) swap_hdr_sz
;
1887 StoreEntry::swapoutPossible()
1889 if (!Config
.cacheSwap
.n_configured
)
1892 /* should we swap something out to disk? */
1893 debugs(20, 7, "storeSwapOut: " << url());
1894 debugs(20, 7, "storeSwapOut: store_status = " << storeStatusStr
[store_status
]);
1897 MemObject::SwapOut::Decision
&decision
= mem_obj
->swapout
.decision
;
1899 // if we decided that swapout is not possible, do not repeat same checks
1900 if (decision
== MemObject::SwapOut::swImpossible
) {
1901 debugs(20, 3, "storeSwapOut: already rejected");
1905 // this flag may change so we must check it even if we already said "yes"
1906 if (EBIT_TEST(flags
, ENTRY_ABORTED
)) {
1907 assert(EBIT_TEST(flags
, RELEASE_REQUEST
));
1908 // StoreEntry::abort() already closed the swap out file, if any
1909 decision
= MemObject::SwapOut::swImpossible
;
1913 // if we decided that swapout is possible, do not repeat same checks
1914 if (decision
== MemObject::SwapOut::swPossible
) {
1915 debugs(20, 3, "storeSwapOut: already allowed");
1919 // if we are swapping out already, do not repeat same checks
1920 if (swap_status
!= SWAPOUT_NONE
) {
1921 debugs(20, 3, "storeSwapOut: already started");
1922 decision
= MemObject::SwapOut::swPossible
;
1926 if (!checkCachable()) {
1927 debugs(20, 3, "storeSwapOut: not cachable");
1928 decision
= MemObject::SwapOut::swImpossible
;
1932 if (EBIT_TEST(flags
, ENTRY_SPECIAL
)) {
1933 debugs(20, 3, "storeSwapOut: " << url() << " SPECIAL");
1934 decision
= MemObject::SwapOut::swImpossible
;
1938 // check cache_dir max-size limit if all cache_dirs have it
1939 if (store_maxobjsize
>= 0) {
1940 // TODO: add estimated store metadata size to be conservative
1942 // use guaranteed maximum if it is known
1943 const int64_t expectedEnd
= mem_obj
->expectedReplySize();
1944 debugs(20, 7, "storeSwapOut: expectedEnd = " << expectedEnd
);
1945 if (expectedEnd
> store_maxobjsize
) {
1946 debugs(20, 3, "storeSwapOut: will not fit: " << expectedEnd
<<
1947 " > " << store_maxobjsize
);
1948 decision
= MemObject::SwapOut::swImpossible
;
1949 return false; // known to outgrow the limit eventually
1952 // use current minimum (always known)
1953 const int64_t currentEnd
= mem_obj
->endOffset();
1954 if (currentEnd
> store_maxobjsize
) {
1955 debugs(20, 3, "storeSwapOut: does not fit: " << currentEnd
<<
1956 " > " << store_maxobjsize
);
1957 decision
= MemObject::SwapOut::swImpossible
;
1958 return false; // already does not fit and may only get bigger
1961 // prevent default swPossible answer for yet unknown length
1962 if (expectedEnd
< 0) {
1963 debugs(20, 3, "storeSwapOut: wait for more info: " <<
1965 return false; // may fit later, but will be rejected now
1969 decision
= MemObject::SwapOut::swPossible
;
1974 StoreEntry::trimMemory()
1978 * Bug #1943. We must not let go any data for IN_MEMORY
1979 * objects. We have to wait until the mem_status changes.
1981 if (mem_status
== IN_MEMORY
)
1984 if (!swapOutAble()) {
1985 if (mem_obj
->policyLowestOffsetToKeep(0) == 0) {
1990 * Its not swap-able, and we're about to delete a chunk,
1991 * so we must make it PRIVATE. This is tricky/ugly because
1992 * for the most part, we treat swapable == cachable here.
1995 mem_obj
->trimUnSwappable ();
1997 mem_obj
->trimSwappable ();
2002 StoreEntry::modifiedSince(HttpRequest
* request
) const
2005 time_t mod_time
= lastmod
;
2008 mod_time
= timestamp
;
2010 debugs(88, 3, "modifiedSince: '" << url() << "'");
2012 debugs(88, 3, "modifiedSince: mod_time = " << mod_time
);
2017 /* Find size of the object */
2018 object_length
= getReply()->content_length
;
2020 if (object_length
< 0)
2021 object_length
= contentLen();
2023 if (mod_time
> request
->ims
) {
2024 debugs(88, 3, "--> YES: entry newer than client");
2026 } else if (mod_time
< request
->ims
) {
2027 debugs(88, 3, "--> NO: entry older than client");
2029 } else if (request
->imslen
< 0) {
2030 debugs(88, 3, "--> NO: same LMT, no client length");
2032 } else if (request
->imslen
== object_length
) {
2033 debugs(88, 3, "--> NO: same LMT, same length");
2036 debugs(88, 3, "--> YES: same LMT, different length");
2042 StoreEntry::hasIfMatchEtag(const HttpRequest
&request
) const
2044 const String reqETags
= request
.header
.getList(HDR_IF_MATCH
);
2045 return hasOneOfEtags(reqETags
, false);
2049 StoreEntry::hasIfNoneMatchEtag(const HttpRequest
&request
) const
2051 const String reqETags
= request
.header
.getList(HDR_IF_NONE_MATCH
);
2052 // weak comparison is allowed only for HEAD or full-body GET requests
2053 const bool allowWeakMatch
= !request
.flags
.range
&&
2054 (request
.method
== METHOD_GET
|| request
.method
== METHOD_HEAD
);
2055 return hasOneOfEtags(reqETags
, allowWeakMatch
);
2058 /// whether at least one of the request ETags matches entity ETag
2060 StoreEntry::hasOneOfEtags(const String
&reqETags
, const bool allowWeakMatch
) const
2062 const ETag repETag
= getReply()->header
.getETag(HDR_ETAG
);
2064 return strListIsMember(&reqETags
, "*", ',');
2066 bool matched
= false;
2067 const char *pos
= NULL
;
2070 while (!matched
&& strListGetItem(&reqETags
, ',', &item
, &ilen
, &pos
)) {
2071 if (!strncmp(item
, "*", ilen
))
2075 str
.append(item
, ilen
);
2077 if (etagParseInit(&reqETag
, str
.termedBuf())) {
2078 matched
= allowWeakMatch
? etagIsWeakEqual(repETag
, reqETag
) :
2079 etagIsStrongEqual(repETag
, reqETag
);
2087 StoreEntry::store() const
2089 assert(0 <= swap_dirn
&& swap_dirn
< Config
.cacheSwap
.n_configured
);
2090 return INDEXSD(swap_dirn
);
2094 StoreEntry::unlink()
2096 store()->unlink(*this); // implies disconnect()
2099 swap_status
= SWAPOUT_NONE
;
2103 * return true if the entry is in a state where
2104 * it can accept more data (ie with write() method)
2107 StoreEntry::isAccepting() const
2109 if (STORE_PENDING
!= store_status
)
2112 if (EBIT_TEST(flags
, ENTRY_ABORTED
))
2118 std::ostream
&operator <<(std::ostream
&os
, const StoreEntry
&e
)
2120 return os
<< e
.swap_filen
<< '@' << e
.swap_dirn
<< '=' <<
2121 e
.mem_status
<< '/' << e
.ping_status
<< '/' << e
.store_status
<< '/' <<
2125 /* NullStoreEntry */
2127 NullStoreEntry
NullStoreEntry::_instance
;
2130 NullStoreEntry::getInstance()
2136 NullStoreEntry::getMD5Text() const
2142 NullStoreEntry::operator delete(void*)
2144 fatal ("Attempt to delete NullStoreEntry\n");
2148 NullStoreEntry::getSerialisedMetaData()
2154 #include "Store.cci"