]> git.ipfire.org Git - thirdparty/squid.git/blob - src/store.cc
Merged from trunk 13199.
[thirdparty/squid.git] / src / store.cc
1
2 /*
3 * DEBUG: section 20 Storage Manager
4 * AUTHOR: Harvest Derived
5 *
6 * SQUID Web Proxy Cache http://www.squid-cache.org/
7 * ----------------------------------------------------------
8 *
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.
17 *
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.
22 *
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.
27 *
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.
31 *
32 */
33
34 #include "squid.h"
35 #include "CacheDigest.h"
36 #include "CacheManager.h"
37 #include "comm/Connection.h"
38 #include "ETag.h"
39 #include "event.h"
40 #include "fde.h"
41 #include "globals.h"
42 #include "http.h"
43 #include "HttpReply.h"
44 #include "HttpRequest.h"
45 #include "mem_node.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 "Stack.h"
55 #include "StatCounters.h"
56 #include "stmem.h"
57 #include "Store.h"
58 #include "store_digest.h"
59 #include "store_key_md5.h"
60 #include "store_key_md5.h"
61 #include "store_log.h"
62 #include "store_rebuild.h"
63 #include "StoreClient.h"
64 #include "StoreIOState.h"
65 #include "StoreMeta.h"
66 #include "StrList.h"
67 #include "swap_log_op.h"
68 #include "SwapDir.h"
69 #include "tools.h"
70 #if USE_DELAY_POOLS
71 #include "DelayPools.h"
72 #endif
73 #if HAVE_LIMITS_H
74 #include <limits.h>
75 #endif
76
77 #define REBUILD_TIMESTAMP_DELTA_MAX 2
78
79 #define STORE_IN_MEM_BUCKETS (229)
80
81 /** \todo Convert these string constants to enum string-arrays generated */
82
83 const char *memStatusStr[] = {
84 "NOT_IN_MEMORY",
85 "IN_MEMORY"
86 };
87
88 const char *pingStatusStr[] = {
89 "PING_NONE",
90 "PING_WAITING",
91 "PING_DONE"
92 };
93
94 const char *storeStatusStr[] = {
95 "STORE_OK",
96 "STORE_PENDING"
97 };
98
99 const char *swapStatusStr[] = {
100 "SWAPOUT_NONE",
101 "SWAPOUT_WRITING",
102 "SWAPOUT_DONE"
103 };
104
105 /*
106 * This defines an repl type
107 */
108
109 typedef struct _storerepl_entry storerepl_entry_t;
110
111 struct _storerepl_entry {
112 const char *typestr;
113 REMOVALPOLICYCREATE *create;
114 };
115
116 static storerepl_entry_t *storerepl_list = NULL;
117
118 /*
119 * local function prototypes
120 */
121 static int getKeyCounter(void);
122 static OBJH storeCheckCachableStats;
123 static EVH storeLateRelease;
124
125 /*
126 * local variables
127 */
128 static Stack<StoreEntry*> LateReleaseStack;
129 MemAllocator *StoreEntry::pool = NULL;
130
131 StorePointer Store::CurrentRoot = NULL;
132
133 void
134 Store::Root(Store * aRoot)
135 {
136 CurrentRoot = aRoot;
137 }
138
139 void
140 Store::Root(StorePointer aRoot)
141 {
142 Root(aRoot.getRaw());
143 }
144
145 void
146 Store::Stats(StoreEntry * output)
147 {
148 assert (output);
149 Root().stat(*output);
150 }
151
152 void
153 Store::create()
154 {}
155
156 void
157 Store::diskFull()
158 {}
159
160 void
161 Store::sync()
162 {}
163
164 void
165 Store::unlink (StoreEntry &anEntry)
166 {
167 fatal("Store::unlink on invalid Store\n");
168 }
169
170 void *
171 StoreEntry::operator new (size_t bytecount)
172 {
173 assert (bytecount == sizeof (StoreEntry));
174
175 if (!pool) {
176 pool = memPoolCreate ("StoreEntry", bytecount);
177 pool->setChunkSize(2048 * 1024);
178 }
179
180 return pool->alloc();
181 }
182
183 void
184 StoreEntry::operator delete (void *address)
185 {
186 pool->freeOne(address);
187 }
188
189 void
190 StoreEntry::makePublic()
191 {
192 /* This object can be cached for a long time */
193
194 if (!EBIT_TEST(flags, RELEASE_REQUEST))
195 setPublicKey();
196 }
197
198 void
199 StoreEntry::makePrivate()
200 {
201 /* This object should never be cached at all */
202 expireNow();
203 releaseRequest(); /* delete object when not used */
204 }
205
206 void
207 StoreEntry::cacheNegatively()
208 {
209 /* This object may be negatively cached */
210 negativeCache();
211 makePublic();
212 }
213
214 size_t
215 StoreEntry::inUseCount()
216 {
217 if (!pool)
218 return 0;
219 return pool->getInUseCount();
220 }
221
222 const char *
223 StoreEntry::getMD5Text() const
224 {
225 return storeKeyText((const cache_key *)key);
226 }
227
228 #include "comm.h"
229
230 void
231 StoreEntry::DeferReader(void *theContext, CommRead const &aRead)
232 {
233 StoreEntry *anEntry = (StoreEntry *)theContext;
234 anEntry->delayAwareRead(aRead.conn,
235 aRead.buf,
236 aRead.len,
237 aRead.callback);
238 }
239
240 void
241 StoreEntry::delayAwareRead(const Comm::ConnectionPointer &conn, char *buf, int len, AsyncCall::Pointer callback)
242 {
243 size_t amountToRead = bytesWanted(Range<size_t>(0, len));
244 /* sketch: readdeferer* = getdeferer.
245 * ->deferRead (fd, buf, len, callback, DelayAwareRead, this)
246 */
247
248 if (amountToRead == 0) {
249 assert (mem_obj);
250 /* read ahead limit */
251 /* Perhaps these two calls should both live in MemObject */
252 #if USE_DELAY_POOLS
253 if (!mem_obj->readAheadPolicyCanRead()) {
254 #endif
255 mem_obj->delayRead(DeferredRead(DeferReader, this, CommRead(conn, buf, len, callback)));
256 return;
257 #if USE_DELAY_POOLS
258 }
259
260 /* delay id limit */
261 mem_obj->mostBytesAllowed().delayRead(DeferredRead(DeferReader, this, CommRead(conn, buf, len, callback)));
262 return;
263
264 #endif
265
266 }
267
268 if (fd_table[conn->fd].closing()) {
269 // Readers must have closing callbacks if they want to be notified. No
270 // readers appeared to care around 2009/12/14 as they skipped reading
271 // for other reasons. Closing may already be true at the delyaAwareRead
272 // call time or may happen while we wait after delayRead() above.
273 debugs(20, 3, HERE << "wont read from closing " << conn << " for " <<
274 callback);
275 return; // the read callback will never be called
276 }
277
278 comm_read(conn, buf, amountToRead, callback);
279 }
280
281 size_t
282 StoreEntry::bytesWanted (Range<size_t> const aRange, bool ignoreDelayPools) const
283 {
284 if (mem_obj == NULL)
285 return aRange.end;
286
287 #if URL_CHECKSUM_DEBUG
288
289 mem_obj->checkUrlChecksum();
290
291 #endif
292
293 if (!mem_obj->readAheadPolicyCanRead())
294 return 0;
295
296 return mem_obj->mostBytesWanted(aRange.end, ignoreDelayPools);
297 }
298
299 bool
300 StoreEntry::checkDeferRead(int fd) const
301 {
302 return (bytesWanted(Range<size_t>(0,INT_MAX)) == 0);
303 }
304
305 void
306 StoreEntry::setNoDelay (bool const newValue)
307 {
308 if (mem_obj)
309 mem_obj->setNoDelay(newValue);
310 }
311
312 // XXX: Type names mislead. STORE_DISK_CLIENT actually means that we should
313 // open swapin file, aggressively trim memory, and ignore read-ahead gap.
314 // It does not mean we will read from disk exclusively (or at all!).
315 // XXX: May create STORE_DISK_CLIENT with no disk caching configured.
316 // XXX: Collapsed clients cannot predict their type.
317 store_client_t
318 StoreEntry::storeClientType() const
319 {
320 /* The needed offset isn't in memory
321 * XXX TODO: this is wrong for range requests
322 * as the needed offset may *not* be 0, AND
323 * offset 0 in the memory object is the HTTP headers.
324 */
325
326 assert(mem_obj);
327
328 if (mem_obj->inmem_lo)
329 return STORE_DISK_CLIENT;
330
331 if (EBIT_TEST(flags, ENTRY_ABORTED)) {
332 /* I don't think we should be adding clients to aborted entries */
333 debugs(20, DBG_IMPORTANT, "storeClientType: adding to ENTRY_ABORTED entry");
334 return STORE_MEM_CLIENT;
335 }
336
337 if (store_status == STORE_OK) {
338 /* the object has completed. */
339
340 if (mem_obj->inmem_lo == 0 && !isEmpty()) {
341 if (swap_status == SWAPOUT_DONE) {
342 debugs(20,7, HERE << mem_obj << " lo: " << mem_obj->inmem_lo << " hi: " << mem_obj->endOffset() << " size: " << mem_obj->object_sz);
343 if (mem_obj->endOffset() == mem_obj->object_sz) {
344 /* hot object fully swapped in (XXX: or swapped out?) */
345 return STORE_MEM_CLIENT;
346 }
347 } else {
348 /* Memory-only, or currently being swapped out */
349 return STORE_MEM_CLIENT;
350 }
351 }
352 return STORE_DISK_CLIENT;
353 }
354
355 /* here and past, entry is STORE_PENDING */
356 /*
357 * If this is the first client, let it be the mem client
358 */
359 if (mem_obj->nclients == 1)
360 return STORE_MEM_CLIENT;
361
362 /*
363 * If there is no disk file to open yet, we must make this a
364 * mem client. If we can't open the swapin file before writing
365 * to the client, there is no guarantee that we will be able
366 * to open it later when we really need it.
367 */
368 if (swap_status == SWAPOUT_NONE)
369 return STORE_MEM_CLIENT;
370
371 /*
372 * otherwise, make subsequent clients read from disk so they
373 * can not delay the first, and vice-versa.
374 */
375 return STORE_DISK_CLIENT;
376 }
377
378 StoreEntry::StoreEntry() :
379 mem_obj(NULL),
380 timestamp(-1),
381 lastref(-1),
382 expires(-1),
383 lastmod(-1),
384 swap_file_sz(0),
385 refcount(0),
386 flags(0),
387 swap_filen(-1),
388 swap_dirn(-1),
389 mem_status(NOT_IN_MEMORY),
390 ping_status(PING_NONE),
391 store_status(STORE_PENDING),
392 swap_status(SWAPOUT_NONE),
393 lock_count(0)
394 {
395 debugs(20, 5, "StoreEntry constructed, this=" << this);
396 }
397
398 StoreEntry::~StoreEntry()
399 {
400 debugs(20, 5, "StoreEntry destructed, this=" << this);
401 }
402
403 #if USE_ADAPTATION
404 void
405 StoreEntry::deferProducer(const AsyncCall::Pointer &producer)
406 {
407 if (!deferredProducer)
408 deferredProducer = producer;
409 else
410 debugs(20, 5, HERE << "Deferred producer call is allready set to: " <<
411 *deferredProducer << ", requested call: " << *producer);
412 }
413
414 void
415 StoreEntry::kickProducer()
416 {
417 if (deferredProducer != NULL) {
418 ScheduleCallHere(deferredProducer);
419 deferredProducer = NULL;
420 }
421 }
422 #endif
423
424 void
425 StoreEntry::destroyMemObject()
426 {
427 debugs(20, 3, HERE << "destroyMemObject " << mem_obj);
428
429 if (MemObject *mem = mem_obj) {
430 // Store::Root() is FATALly missing during shutdown
431 if (mem->xitTable.index >= 0 && !shutting_down)
432 Store::Root().transientsDisconnect(*mem);
433 if (mem->memCache.index >= 0 && !shutting_down)
434 Store::Root().memoryDisconnect(*this);
435
436 setMemStatus(NOT_IN_MEMORY);
437 mem_obj = NULL;
438 delete mem;
439 }
440 }
441
442 void
443 destroyStoreEntry(void *data)
444 {
445 debugs(20, 3, HERE << "destroyStoreEntry: destroying " << data);
446 StoreEntry *e = static_cast<StoreEntry *>(static_cast<hash_link *>(data));
447 assert(e != NULL);
448
449 if (e == NullStoreEntry::getInstance())
450 return;
451
452 // Store::Root() is FATALly missing during shutdown
453 if (e->swap_filen >= 0 && !shutting_down) {
454 SwapDir &sd = dynamic_cast<SwapDir&>(*e->store());
455 sd.disconnect(*e);
456 }
457
458 e->destroyMemObject();
459
460 e->hashDelete();
461
462 assert(e->key == NULL);
463
464 delete e;
465 }
466
467 /* ----- INTERFACE BETWEEN STORAGE MANAGER AND HASH TABLE FUNCTIONS --------- */
468
469 void
470 StoreEntry::hashInsert(const cache_key * someKey)
471 {
472 debugs(20, 3, "StoreEntry::hashInsert: Inserting Entry " << *this << " key '" << storeKeyText(someKey) << "'");
473 key = storeKeyDup(someKey);
474 hash_join(store_table, this);
475 }
476
477 void
478 StoreEntry::hashDelete()
479 {
480 if (key) { // some test cases do not create keys and do not hashInsert()
481 hash_remove_link(store_table, this);
482 storeKeyFree((const cache_key *)key);
483 key = NULL;
484 }
485 }
486
487 /* -------------------------------------------------------------------------- */
488
489 /* get rid of memory copy of the object */
490 void
491 StoreEntry::purgeMem()
492 {
493 if (mem_obj == NULL)
494 return;
495
496 debugs(20, 3, "StoreEntry::purgeMem: Freeing memory-copy of " << getMD5Text());
497
498 Store::Root().memoryUnlink(*this);
499
500 if (swap_status != SWAPOUT_DONE)
501 release();
502 }
503
504 void
505 StoreEntry::lock(const char *context)
506 {
507 ++lock_count;
508 debugs(20, 3, context << " locked key " << getMD5Text() << ' ' << *this);
509 }
510
511 void
512 StoreEntry::touch()
513 {
514 lastref = squid_curtime;
515 Store::Root().reference(*this);
516 }
517
518 void
519 StoreEntry::setReleaseFlag()
520 {
521 if (EBIT_TEST(flags, RELEASE_REQUEST))
522 return;
523
524 debugs(20, 3, "StoreEntry::setReleaseFlag: '" << getMD5Text() << "'");
525
526 EBIT_SET(flags, RELEASE_REQUEST);
527
528 Store::Root().markForUnlink(*this);
529 }
530
531 void
532 StoreEntry::releaseRequest()
533 {
534 if (EBIT_TEST(flags, RELEASE_REQUEST))
535 return;
536
537 setReleaseFlag(); // makes validToSend() false, preventing future hits
538
539 setPrivateKey();
540 }
541
542 int
543 StoreEntry::unlock(const char *context)
544 {
545 debugs(20, 3, (context ? context : "somebody") <<
546 " unlocking key " << getMD5Text() << ' ' << *this);
547 assert(lock_count > 0);
548 --lock_count;
549
550 if (lock_count)
551 return (int) lock_count;
552
553 if (store_status == STORE_PENDING)
554 setReleaseFlag();
555
556 assert(storePendingNClients(this) == 0);
557
558 if (EBIT_TEST(flags, RELEASE_REQUEST)) {
559 this->release();
560 return 0;
561 }
562
563 if (EBIT_TEST(flags, KEY_PRIVATE))
564 debugs(20, DBG_IMPORTANT, "WARNING: " << __FILE__ << ":" << __LINE__ << ": found KEY_PRIVATE");
565
566 Store::Root().handleIdleEntry(*this); // may delete us
567 return 0;
568 }
569
570 void
571 StoreEntry::getPublicByRequestMethod (StoreClient *aClient, HttpRequest * request, const HttpRequestMethod& method)
572 {
573 assert (aClient);
574 StoreEntry *result = storeGetPublicByRequestMethod( request, method);
575
576 if (!result)
577 aClient->created (NullStoreEntry::getInstance());
578 else
579 aClient->created (result);
580 }
581
582 void
583 StoreEntry::getPublicByRequest (StoreClient *aClient, HttpRequest * request)
584 {
585 assert (aClient);
586 StoreEntry *result = storeGetPublicByRequest (request);
587
588 if (!result)
589 result = NullStoreEntry::getInstance();
590
591 aClient->created (result);
592 }
593
594 void
595 StoreEntry::getPublic (StoreClient *aClient, const char *uri, const HttpRequestMethod& method)
596 {
597 assert (aClient);
598 StoreEntry *result = storeGetPublic (uri, method);
599
600 if (!result)
601 result = NullStoreEntry::getInstance();
602
603 aClient->created (result);
604 }
605
606 StoreEntry *
607 storeGetPublic(const char *uri, const HttpRequestMethod& method)
608 {
609 return Store::Root().get(storeKeyPublic(uri, method));
610 }
611
612 StoreEntry *
613 storeGetPublicByRequestMethod(HttpRequest * req, const HttpRequestMethod& method)
614 {
615 return Store::Root().get(storeKeyPublicByRequestMethod(req, method));
616 }
617
618 StoreEntry *
619 storeGetPublicByRequest(HttpRequest * req)
620 {
621 StoreEntry *e = storeGetPublicByRequestMethod(req, req->method);
622
623 if (e == NULL && req->method == Http::METHOD_HEAD)
624 /* We can generate a HEAD reply from a cached GET object */
625 e = storeGetPublicByRequestMethod(req, Http::METHOD_GET);
626
627 return e;
628 }
629
630 static int
631 getKeyCounter(void)
632 {
633 static int key_counter = 0;
634
635 if (++key_counter < 0)
636 key_counter = 1;
637
638 return key_counter;
639 }
640
641 /* RBC 20050104 AFAICT this should become simpler:
642 * rather than reinserting with a special key it should be marked
643 * as 'released' and then cleaned up when refcounting indicates.
644 * the StoreHashIndex could well implement its 'released' in the
645 * current manner.
646 * Also, clean log writing should skip over ia,t
647 * Otherwise, we need a 'remove from the index but not the store
648 * concept'.
649 */
650 void
651 StoreEntry::setPrivateKey()
652 {
653 const cache_key *newkey;
654
655 if (key && EBIT_TEST(flags, KEY_PRIVATE))
656 return; /* is already private */
657
658 if (key) {
659 setReleaseFlag(); // will markForUnlink(); all caches/workers will know
660
661 // TODO: move into SwapDir::markForUnlink() already called by Root()
662 if (swap_filen > -1)
663 storeDirSwapLog(this, SWAP_LOG_DEL);
664
665 hashDelete();
666 }
667
668 if (mem_obj && mem_obj->hasUris()) {
669 mem_obj->id = getKeyCounter();
670 newkey = storeKeyPrivate(mem_obj->storeId(), mem_obj->method, mem_obj->id);
671 } else {
672 newkey = storeKeyPrivate("JUNK", Http::METHOD_NONE, getKeyCounter());
673 }
674
675 assert(hash_lookup(store_table, newkey) == NULL);
676 EBIT_SET(flags, KEY_PRIVATE);
677 hashInsert(newkey);
678 }
679
680 void
681 StoreEntry::setPublicKey()
682 {
683 const cache_key *newkey;
684
685 if (key && !EBIT_TEST(flags, KEY_PRIVATE))
686 return; /* is already public */
687
688 assert(mem_obj);
689
690 /*
691 * We can't make RELEASE_REQUEST objects public. Depending on
692 * when RELEASE_REQUEST gets set, we might not be swapping out
693 * the object. If we're not swapping out, then subsequent
694 * store clients won't be able to access object data which has
695 * been freed from memory.
696 *
697 * If RELEASE_REQUEST is set, setPublicKey() should not be called.
698 */
699 #if MORE_DEBUG_OUTPUT
700
701 if (EBIT_TEST(flags, RELEASE_REQUEST))
702 debugs(20, DBG_IMPORTANT, "assertion failed: RELEASE key " << key << ", url " << mem_obj->url);
703
704 #endif
705
706 assert(!EBIT_TEST(flags, RELEASE_REQUEST));
707
708 if (mem_obj->request) {
709 HttpRequest *request = mem_obj->request;
710
711 if (!mem_obj->vary_headers) {
712 /* First handle the case where the object no longer varies */
713 safe_free(request->vary_headers);
714 } else {
715 if (request->vary_headers && strcmp(request->vary_headers, mem_obj->vary_headers) != 0) {
716 /* Oops.. the variance has changed. Kill the base object
717 * to record the new variance key
718 */
719 safe_free(request->vary_headers); /* free old "bad" variance key */
720 if (StoreEntry *pe = storeGetPublic(mem_obj->storeId(), mem_obj->method))
721 pe->release();
722 }
723
724 /* Make sure the request knows the variance status */
725 if (!request->vary_headers) {
726 const char *vary = httpMakeVaryMark(request, mem_obj->getReply());
727
728 if (vary)
729 request->vary_headers = xstrdup(vary);
730 }
731 }
732
733 // TODO: storeGetPublic() calls below may create unlocked entries.
734 // We should add/use storeHas() API or lock/unlock those entries.
735 if (mem_obj->vary_headers && !storeGetPublic(mem_obj->storeId(), mem_obj->method)) {
736 /* Create "vary" base object */
737 String vary;
738 StoreEntry *pe = storeCreateEntry(mem_obj->storeId(), mem_obj->logUri(), request->flags, request->method);
739 /* We are allowed to do this typecast */
740 HttpReply *rep = new HttpReply;
741 rep->setHeaders(Http::scOkay, "Internal marker object", "x-squid-internal/vary", -1, -1, squid_curtime + 100000);
742 vary = mem_obj->getReply()->header.getList(HDR_VARY);
743
744 if (vary.size()) {
745 /* Again, we own this structure layout */
746 rep->header.putStr(HDR_VARY, vary.termedBuf());
747 vary.clean();
748 }
749
750 #if X_ACCELERATOR_VARY
751 vary = mem_obj->getReply()->header.getList(HDR_X_ACCELERATOR_VARY);
752
753 if (vary.size() > 0) {
754 /* Again, we own this structure layout */
755 rep->header.putStr(HDR_X_ACCELERATOR_VARY, vary.termedBuf());
756 vary.clean();
757 }
758
759 #endif
760 pe->replaceHttpReply(rep, false); // no write until key is public
761
762 pe->timestampsSet();
763
764 pe->makePublic();
765
766 pe->startWriting(); // after makePublic()
767
768 pe->complete();
769
770 pe->unlock("StoreEntry::setPublicKey+Vary");
771 }
772
773 newkey = storeKeyPublicByRequest(mem_obj->request);
774 } else
775 newkey = storeKeyPublic(mem_obj->storeId(), mem_obj->method);
776
777 if (StoreEntry *e2 = (StoreEntry *)hash_lookup(store_table, newkey)) {
778 debugs(20, 3, "Making old " << *e2 << " private.");
779 e2->setPrivateKey();
780 e2->release();
781
782 if (mem_obj->request)
783 newkey = storeKeyPublicByRequest(mem_obj->request);
784 else
785 newkey = storeKeyPublic(mem_obj->storeId(), mem_obj->method);
786 }
787
788 if (key)
789 hashDelete();
790
791 EBIT_CLR(flags, KEY_PRIVATE);
792
793 hashInsert(newkey);
794
795 if (swap_filen > -1)
796 storeDirSwapLog(this, SWAP_LOG_ADD);
797 }
798
799 StoreEntry *
800 storeCreatePureEntry(const char *url, const char *log_url, const RequestFlags &flags, const HttpRequestMethod& method)
801 {
802 StoreEntry *e = NULL;
803 debugs(20, 3, "storeCreateEntry: '" << url << "'");
804
805 e = new StoreEntry();
806 e->makeMemObject();
807 e->mem_obj->setUris(url, log_url, method);
808
809 if (flags.cachable) {
810 EBIT_CLR(e->flags, RELEASE_REQUEST);
811 } else {
812 e->releaseRequest();
813 }
814
815 e->store_status = STORE_PENDING;
816 e->refcount = 0;
817 e->lastref = squid_curtime;
818 e->timestamp = -1; /* set in StoreEntry::timestampsSet() */
819 e->ping_status = PING_NONE;
820 EBIT_SET(e->flags, ENTRY_VALIDATED);
821 return e;
822 }
823
824 StoreEntry *
825 storeCreateEntry(const char *url, const char *logUrl, const RequestFlags &flags, const HttpRequestMethod& method)
826 {
827 StoreEntry *e = storeCreatePureEntry(url, logUrl, flags, method);
828 e->lock("storeCreateEntry");
829
830 if (neighbors_do_private_keys || !flags.hierarchical)
831 e->setPrivateKey();
832 else
833 e->setPublicKey();
834
835 return e;
836 }
837
838 /* Mark object as expired */
839 void
840 StoreEntry::expireNow()
841 {
842 debugs(20, 3, "StoreEntry::expireNow: '" << getMD5Text() << "'");
843 expires = squid_curtime;
844 }
845
846 void
847 StoreEntry::write (StoreIOBuffer writeBuffer)
848 {
849 assert(mem_obj != NULL);
850 /* This assert will change when we teach the store to update */
851 PROF_start(StoreEntry_write);
852 assert(store_status == STORE_PENDING);
853
854 // XXX: caller uses content offset, but we also store headers
855 if (const HttpReply *reply = mem_obj->getReply())
856 writeBuffer.offset += reply->hdr_sz;
857
858 debugs(20, 5, "storeWrite: writing " << writeBuffer.length << " bytes for '" << getMD5Text() << "'");
859 PROF_stop(StoreEntry_write);
860 storeGetMemSpace(writeBuffer.length);
861 mem_obj->write(writeBuffer);
862
863 if (!EBIT_TEST(flags, DELAY_SENDING))
864 invokeHandlers();
865 }
866
867 /* Append incoming data from a primary server to an entry. */
868 void
869 StoreEntry::append(char const *buf, int len)
870 {
871 assert(mem_obj != NULL);
872 assert(len >= 0);
873 assert(store_status == STORE_PENDING);
874
875 StoreIOBuffer tempBuffer;
876 tempBuffer.data = (char *)buf;
877 tempBuffer.length = len;
878 /*
879 * XXX sigh, offset might be < 0 here, but it gets "corrected"
880 * later. This offset crap is such a mess.
881 */
882 tempBuffer.offset = mem_obj->endOffset() - (getReply() ? getReply()->hdr_sz : 0);
883 write(tempBuffer);
884 }
885
886 void
887 storeAppendPrintf(StoreEntry * e, const char *fmt,...)
888 {
889 va_list args;
890 va_start(args, fmt);
891
892 storeAppendVPrintf(e, fmt, args);
893 va_end(args);
894 }
895
896 /* used be storeAppendPrintf and Packer */
897 void
898 storeAppendVPrintf(StoreEntry * e, const char *fmt, va_list vargs)
899 {
900 LOCAL_ARRAY(char, buf, 4096);
901 buf[0] = '\0';
902 vsnprintf(buf, 4096, fmt, vargs);
903 e->append(buf, strlen(buf));
904 }
905
906 struct _store_check_cachable_hist {
907
908 struct {
909 int non_get;
910 int not_entry_cachable;
911 int wrong_content_length;
912 int negative_cached;
913 int too_big;
914 int too_small;
915 int private_key;
916 int too_many_open_files;
917 int too_many_open_fds;
918 } no;
919
920 struct {
921 int Default;
922 } yes;
923 } store_check_cachable_hist;
924
925 int
926 storeTooManyDiskFilesOpen(void)
927 {
928 if (Config.max_open_disk_fds == 0)
929 return 0;
930
931 if (store_open_disk_fd > Config.max_open_disk_fds)
932 return 1;
933
934 return 0;
935 }
936
937 int
938 StoreEntry::checkTooSmall()
939 {
940 if (EBIT_TEST(flags, ENTRY_SPECIAL))
941 return 0;
942
943 if (STORE_OK == store_status)
944 if (mem_obj->object_sz < 0 ||
945 mem_obj->object_sz < Config.Store.minObjectSize)
946 return 1;
947 if (getReply()->content_length > -1)
948 if (getReply()->content_length < Config.Store.minObjectSize)
949 return 1;
950 return 0;
951 }
952
953 // TODO: remove checks already performed by swapoutPossible()
954 // TODO: move "too many open..." checks outside -- we are called too early/late
955 int
956 StoreEntry::checkCachable()
957 {
958 #if CACHE_ALL_METHODS
959
960 if (mem_obj->method != Http::METHOD_GET) {
961 debugs(20, 2, "StoreEntry::checkCachable: NO: non-GET method");
962 ++store_check_cachable_hist.no.non_get;
963 } else
964 #endif
965 if (store_status == STORE_OK && EBIT_TEST(flags, ENTRY_BAD_LENGTH)) {
966 debugs(20, 2, "StoreEntry::checkCachable: NO: wrong content-length");
967 ++store_check_cachable_hist.no.wrong_content_length;
968 } else if (EBIT_TEST(flags, RELEASE_REQUEST)) {
969 debugs(20, 2, "StoreEntry::checkCachable: NO: not cachable");
970 ++store_check_cachable_hist.no.not_entry_cachable; // TODO: rename?
971 } else if (EBIT_TEST(flags, ENTRY_NEGCACHED)) {
972 debugs(20, 3, "StoreEntry::checkCachable: NO: negative cached");
973 ++store_check_cachable_hist.no.negative_cached;
974 return 0; /* avoid release call below */
975 } else if ((getReply()->content_length > 0 &&
976 getReply()->content_length > store_maxobjsize) ||
977 mem_obj->endOffset() > store_maxobjsize) {
978 debugs(20, 2, "StoreEntry::checkCachable: NO: too big");
979 ++store_check_cachable_hist.no.too_big;
980 } else if (checkTooSmall()) {
981 debugs(20, 2, "StoreEntry::checkCachable: NO: too small");
982 ++store_check_cachable_hist.no.too_small;
983 } else if (EBIT_TEST(flags, KEY_PRIVATE)) {
984 debugs(20, 3, "StoreEntry::checkCachable: NO: private key");
985 ++store_check_cachable_hist.no.private_key;
986 } else if (swap_status != SWAPOUT_NONE) {
987 /*
988 * here we checked the swap_status because the remaining
989 * cases are only relevant only if we haven't started swapping
990 * out the object yet.
991 */
992 return 1;
993 } else if (storeTooManyDiskFilesOpen()) {
994 debugs(20, 2, "StoreEntry::checkCachable: NO: too many disk files open");
995 ++store_check_cachable_hist.no.too_many_open_files;
996 } else if (fdNFree() < RESERVED_FD) {
997 debugs(20, 2, "StoreEntry::checkCachable: NO: too many FD's open");
998 ++store_check_cachable_hist.no.too_many_open_fds;
999 } else {
1000 ++store_check_cachable_hist.yes.Default;
1001 return 1;
1002 }
1003
1004 releaseRequest();
1005 return 0;
1006 }
1007
1008 void
1009 storeCheckCachableStats(StoreEntry *sentry)
1010 {
1011 storeAppendPrintf(sentry, "Category\t Count\n");
1012
1013 #if CACHE_ALL_METHODS
1014
1015 storeAppendPrintf(sentry, "no.non_get\t%d\n",
1016 store_check_cachable_hist.no.non_get);
1017 #endif
1018
1019 storeAppendPrintf(sentry, "no.not_entry_cachable\t%d\n",
1020 store_check_cachable_hist.no.not_entry_cachable);
1021 storeAppendPrintf(sentry, "no.wrong_content_length\t%d\n",
1022 store_check_cachable_hist.no.wrong_content_length);
1023 storeAppendPrintf(sentry, "no.negative_cached\t%d\n",
1024 store_check_cachable_hist.no.negative_cached);
1025 storeAppendPrintf(sentry, "no.too_big\t%d\n",
1026 store_check_cachable_hist.no.too_big);
1027 storeAppendPrintf(sentry, "no.too_small\t%d\n",
1028 store_check_cachable_hist.no.too_small);
1029 storeAppendPrintf(sentry, "no.private_key\t%d\n",
1030 store_check_cachable_hist.no.private_key);
1031 storeAppendPrintf(sentry, "no.too_many_open_files\t%d\n",
1032 store_check_cachable_hist.no.too_many_open_files);
1033 storeAppendPrintf(sentry, "no.too_many_open_fds\t%d\n",
1034 store_check_cachable_hist.no.too_many_open_fds);
1035 storeAppendPrintf(sentry, "yes.default\t%d\n",
1036 store_check_cachable_hist.yes.Default);
1037 }
1038
1039 void
1040 StoreEntry::complete()
1041 {
1042 debugs(20, 3, "storeComplete: '" << getMD5Text() << "'");
1043
1044 if (store_status != STORE_PENDING) {
1045 /*
1046 * if we're not STORE_PENDING, then probably we got aborted
1047 * and there should be NO clients on this entry
1048 */
1049 assert(EBIT_TEST(flags, ENTRY_ABORTED));
1050 assert(mem_obj->nclients == 0);
1051 return;
1052 }
1053
1054 /* This is suspect: mem obj offsets include the headers. do we adjust for that
1055 * in use of object_sz?
1056 */
1057 mem_obj->object_sz = mem_obj->endOffset();
1058
1059 store_status = STORE_OK;
1060
1061 assert(mem_status == NOT_IN_MEMORY);
1062
1063 if (!validLength()) {
1064 EBIT_SET(flags, ENTRY_BAD_LENGTH);
1065 releaseRequest();
1066 }
1067
1068 #if USE_CACHE_DIGESTS
1069 if (mem_obj->request)
1070 mem_obj->request->hier.store_complete_stop = current_time;
1071
1072 #endif
1073 /*
1074 * We used to call invokeHandlers, then storeSwapOut. However,
1075 * Madhukar Reddy <myreddy@persistence.com> reported that
1076 * responses without content length would sometimes get released
1077 * in client_side, thinking that the response is incomplete.
1078 */
1079 invokeHandlers();
1080 }
1081
1082 /*
1083 * Someone wants to abort this transfer. Set the reason in the
1084 * request structure, call the server-side callback and mark the
1085 * entry for releasing
1086 */
1087 void
1088 StoreEntry::abort()
1089 {
1090 ++statCounter.aborted_requests;
1091 assert(store_status == STORE_PENDING);
1092 assert(mem_obj != NULL);
1093 debugs(20, 6, "storeAbort: " << getMD5Text());
1094
1095 lock("StoreEntry::abort"); /* lock while aborting */
1096 negativeCache();
1097
1098 releaseRequest();
1099
1100 EBIT_SET(flags, ENTRY_ABORTED);
1101
1102 setMemStatus(NOT_IN_MEMORY);
1103
1104 store_status = STORE_OK;
1105
1106 /* Notify the server side */
1107
1108 /*
1109 * DPW 2007-05-07
1110 * Should we check abort.data for validity?
1111 */
1112 if (mem_obj->abort.callback) {
1113 if (!cbdataReferenceValid(mem_obj->abort.data))
1114 debugs(20, DBG_IMPORTANT,HERE << "queueing event when abort.data is not valid");
1115 eventAdd("mem_obj->abort.callback",
1116 mem_obj->abort.callback,
1117 mem_obj->abort.data,
1118 0.0,
1119 true);
1120 unregisterAbort();
1121 }
1122
1123 /* XXX Should we reverse these two, so that there is no
1124 * unneeded disk swapping triggered?
1125 */
1126 /* Notify the client side */
1127 invokeHandlers();
1128
1129 // abort swap out, invalidating what was created so far (release follows)
1130 swapOutFileClose(StoreIOState::writerGone);
1131
1132 unlock("StoreEntry::abort"); /* unlock */
1133 }
1134
1135 /**
1136 * Clear Memory storage to accommodate the given object len
1137 */
1138 void
1139 storeGetMemSpace(int size)
1140 {
1141 PROF_start(storeGetMemSpace);
1142 StoreEntry *e = NULL;
1143 int released = 0;
1144 static time_t last_check = 0;
1145 size_t pages_needed;
1146 RemovalPurgeWalker *walker;
1147
1148 if (squid_curtime == last_check) {
1149 PROF_stop(storeGetMemSpace);
1150 return;
1151 }
1152
1153 last_check = squid_curtime;
1154
1155 pages_needed = (size + SM_PAGE_SIZE-1) / SM_PAGE_SIZE;
1156
1157 if (mem_node::InUseCount() + pages_needed < store_pages_max) {
1158 PROF_stop(storeGetMemSpace);
1159 return;
1160 }
1161
1162 debugs(20, 2, "storeGetMemSpace: Starting, need " << pages_needed <<
1163 " pages");
1164
1165 /* XXX what to set as max_scan here? */
1166 walker = mem_policy->PurgeInit(mem_policy, 100000);
1167
1168 while ((e = walker->Next(walker))) {
1169 e->purgeMem();
1170 ++released;
1171
1172 if (mem_node::InUseCount() + pages_needed < store_pages_max)
1173 break;
1174 }
1175
1176 walker->Done(walker);
1177 debugs(20, 3, "storeGetMemSpace stats:");
1178 debugs(20, 3, " " << std::setw(6) << hot_obj_count << " HOT objects");
1179 debugs(20, 3, " " << std::setw(6) << released << " were released");
1180 PROF_stop(storeGetMemSpace);
1181 }
1182
1183 /* thunk through to Store::Root().maintain(). Note that this would be better still
1184 * if registered against the root store itself, but that requires more complex
1185 * update logic - bigger fish to fry first. Long term each store when
1186 * it becomes active will self register
1187 */
1188 void
1189 Store::Maintain(void *notused)
1190 {
1191 Store::Root().maintain();
1192
1193 /* Reregister a maintain event .. */
1194 eventAdd("MaintainSwapSpace", Maintain, NULL, 1.0, 1);
1195
1196 }
1197
1198 /* The maximum objects to scan for maintain storage space */
1199 #define MAINTAIN_MAX_SCAN 1024
1200 #define MAINTAIN_MAX_REMOVE 64
1201
1202 /*
1203 * This routine is to be called by main loop in main.c.
1204 * It removes expired objects on only one bucket for each time called.
1205 *
1206 * This should get called 1/s from main().
1207 */
1208 void
1209 StoreController::maintain()
1210 {
1211 static time_t last_warn_time = 0;
1212
1213 PROF_start(storeMaintainSwapSpace);
1214 swapDir->maintain();
1215
1216 /* this should be emitted by the oversize dir, not globally */
1217
1218 if (Store::Root().currentSize() > Store::Root().maxSize()) {
1219 if (squid_curtime - last_warn_time > 10) {
1220 debugs(20, DBG_CRITICAL, "WARNING: Disk space over limit: "
1221 << Store::Root().currentSize() / 1024.0 << " KB > "
1222 << (Store::Root().maxSize() >> 10) << " KB");
1223 last_warn_time = squid_curtime;
1224 }
1225 }
1226
1227 PROF_stop(storeMaintainSwapSpace);
1228 }
1229
1230 /* release an object from a cache */
1231 void
1232 StoreEntry::release()
1233 {
1234 PROF_start(storeRelease);
1235 debugs(20, 3, "releasing " << *this << ' ' << getMD5Text());
1236 /* If, for any reason we can't discard this object because of an
1237 * outstanding request, mark it for pending release */
1238
1239 if (locked()) {
1240 expireNow();
1241 debugs(20, 3, "storeRelease: Only setting RELEASE_REQUEST bit");
1242 releaseRequest();
1243 PROF_stop(storeRelease);
1244 return;
1245 }
1246
1247 Store::Root().memoryUnlink(*this);
1248
1249 if (StoreController::store_dirs_rebuilding && swap_filen > -1) {
1250 setPrivateKey();
1251
1252 if (swap_filen > -1) {
1253 // lock the entry until rebuilding is done
1254 lock("storeLateRelease");
1255 setReleaseFlag();
1256 LateReleaseStack.push_back(this);
1257 } else {
1258 destroyStoreEntry(static_cast<hash_link *>(this));
1259 // "this" is no longer valid
1260 }
1261
1262 PROF_stop(storeRelease);
1263 return;
1264 }
1265
1266 storeLog(STORE_LOG_RELEASE, this);
1267
1268 if (swap_filen > -1) {
1269 // log before unlink() below clears swap_filen
1270 if (!EBIT_TEST(flags, KEY_PRIVATE))
1271 storeDirSwapLog(this, SWAP_LOG_DEL);
1272
1273 unlink();
1274 }
1275
1276 destroyStoreEntry(static_cast<hash_link *>(this));
1277 PROF_stop(storeRelease);
1278 }
1279
1280 static void
1281 storeLateRelease(void *unused)
1282 {
1283 StoreEntry *e;
1284 int i;
1285 static int n = 0;
1286
1287 if (StoreController::store_dirs_rebuilding) {
1288 eventAdd("storeLateRelease", storeLateRelease, NULL, 1.0, 1);
1289 return;
1290 }
1291
1292 for (i = 0; i < 10; ++i) {
1293 e = LateReleaseStack.count ? LateReleaseStack.pop() : NULL;
1294
1295 if (e == NULL) {
1296 /* done! */
1297 debugs(20, DBG_IMPORTANT, "storeLateRelease: released " << n << " objects");
1298 return;
1299 }
1300
1301 e->unlock("storeLateRelease");
1302 ++n;
1303 }
1304
1305 eventAdd("storeLateRelease", storeLateRelease, NULL, 0.0, 1);
1306 }
1307
1308 /* return 1 if a store entry is locked */
1309 int
1310 StoreEntry::locked() const
1311 {
1312 if (lock_count)
1313 return 1;
1314
1315 /*
1316 * SPECIAL, PUBLIC entries should be "locked";
1317 * XXX: Their owner should lock them then instead of relying on this hack.
1318 */
1319 if (EBIT_TEST(flags, ENTRY_SPECIAL))
1320 if (!EBIT_TEST(flags, KEY_PRIVATE))
1321 return 1;
1322
1323 return 0;
1324 }
1325
1326 bool
1327 StoreEntry::validLength() const
1328 {
1329 int64_t diff;
1330 const HttpReply *reply;
1331 assert(mem_obj != NULL);
1332 reply = getReply();
1333 debugs(20, 3, "storeEntryValidLength: Checking '" << getMD5Text() << "'");
1334 debugs(20, 5, "storeEntryValidLength: object_len = " <<
1335 objectLen());
1336 debugs(20, 5, "storeEntryValidLength: hdr_sz = " << reply->hdr_sz);
1337 debugs(20, 5, "storeEntryValidLength: content_length = " << reply->content_length);
1338
1339 if (reply->content_length < 0) {
1340 debugs(20, 5, "storeEntryValidLength: Unspecified content length: " << getMD5Text());
1341 return 1;
1342 }
1343
1344 if (reply->hdr_sz == 0) {
1345 debugs(20, 5, "storeEntryValidLength: Zero header size: " << getMD5Text());
1346 return 1;
1347 }
1348
1349 if (mem_obj->method == Http::METHOD_HEAD) {
1350 debugs(20, 5, "storeEntryValidLength: HEAD request: " << getMD5Text());
1351 return 1;
1352 }
1353
1354 if (reply->sline.status() == Http::scNotModified)
1355 return 1;
1356
1357 if (reply->sline.status() == Http::scNoContent)
1358 return 1;
1359
1360 diff = reply->hdr_sz + reply->content_length - objectLen();
1361
1362 if (diff == 0)
1363 return 1;
1364
1365 debugs(20, 3, "storeEntryValidLength: " << (diff < 0 ? -diff : diff) << " bytes too " << (diff < 0 ? "big" : "small") <<"; '" << getMD5Text() << "'" );
1366
1367 return 0;
1368 }
1369
1370 static void
1371 storeRegisterWithCacheManager(void)
1372 {
1373 Mgr::RegisterAction("storedir", "Store Directory Stats", Store::Stats, 0, 1);
1374 Mgr::RegisterAction("store_io", "Store IO Interface Stats", &Mgr::StoreIoAction::Create, 0, 1);
1375 Mgr::RegisterAction("store_check_cachable_stats", "storeCheckCachable() Stats",
1376 storeCheckCachableStats, 0, 1);
1377 }
1378
1379 void
1380 storeInit(void)
1381 {
1382 storeKeyInit();
1383 mem_policy = createRemovalPolicy(Config.memPolicy);
1384 storeDigestInit();
1385 storeLogOpen();
1386 eventAdd("storeLateRelease", storeLateRelease, NULL, 1.0, 1);
1387 Store::Root().init();
1388 storeRebuildStart();
1389
1390 storeRegisterWithCacheManager();
1391 }
1392
1393 void
1394 storeConfigure(void)
1395 {
1396 store_swap_high = (long) (((float) Store::Root().maxSize() *
1397 (float) Config.Swap.highWaterMark) / (float) 100);
1398 store_swap_low = (long) (((float) Store::Root().maxSize() *
1399 (float) Config.Swap.lowWaterMark) / (float) 100);
1400 store_pages_max = Config.memMaxSize / sizeof(mem_node);
1401 }
1402
1403 bool
1404 StoreEntry::memoryCachable() const
1405 {
1406 if (mem_obj == NULL)
1407 return 0;
1408
1409 if (mem_obj->data_hdr.size() == 0)
1410 return 0;
1411
1412 if (mem_obj->inmem_lo != 0)
1413 return 0;
1414
1415 if (!Config.onoff.memory_cache_first && swap_status == SWAPOUT_DONE && refcount == 1)
1416 return 0;
1417
1418 return 1;
1419 }
1420
1421 int
1422 StoreEntry::checkNegativeHit() const
1423 {
1424 if (!EBIT_TEST(flags, ENTRY_NEGCACHED))
1425 return 0;
1426
1427 if (expires <= squid_curtime)
1428 return 0;
1429
1430 if (store_status != STORE_OK)
1431 return 0;
1432
1433 return 1;
1434 }
1435
1436 /**
1437 * Set object for negative caching.
1438 * Preserves any expiry information given by the server.
1439 * In absence of proper expiry info it will set to expire immediately,
1440 * or with HTTP-violations enabled the configured negative-TTL is observed
1441 */
1442 void
1443 StoreEntry::negativeCache()
1444 {
1445 // XXX: should make the default for expires 0 instead of -1
1446 // so we can distinguish "Expires: -1" from nothing.
1447 if (expires <= 0)
1448 #if USE_HTTP_VIOLATIONS
1449 expires = squid_curtime + Config.negativeTtl;
1450 #else
1451 expires = squid_curtime;
1452 #endif
1453 EBIT_SET(flags, ENTRY_NEGCACHED);
1454 }
1455
1456 void
1457 storeFreeMemory(void)
1458 {
1459 Store::Root(NULL);
1460 #if USE_CACHE_DIGESTS
1461
1462 if (store_digest)
1463 cacheDigestDestroy(store_digest);
1464
1465 #endif
1466
1467 store_digest = NULL;
1468 }
1469
1470 int
1471 expiresMoreThan(time_t expires, time_t when)
1472 {
1473 if (expires < 0) /* No Expires given */
1474 return 1;
1475
1476 return (expires > (squid_curtime + when));
1477 }
1478
1479 int
1480 StoreEntry::validToSend() const
1481 {
1482 if (EBIT_TEST(flags, RELEASE_REQUEST))
1483 return 0;
1484
1485 if (EBIT_TEST(flags, ENTRY_NEGCACHED))
1486 if (expires <= squid_curtime)
1487 return 0;
1488
1489 if (EBIT_TEST(flags, ENTRY_ABORTED))
1490 return 0;
1491
1492 // now check that the entry has a cache backing or is collapsed
1493 if (swap_filen > -1) // backed by a disk cache
1494 return 1;
1495
1496 if (swappingOut()) // will be backed by a disk cache
1497 return 1;
1498
1499 if (!mem_obj) // not backed by a memory cache and not collapsed
1500 return 0;
1501
1502 if (mem_obj->memCache.index >= 0) // backed by a shared memory cache
1503 return 0;
1504
1505 // StoreEntry::storeClientType() assumes DISK_CLIENT here, but there is no
1506 // disk cache backing so we should not rely on the store cache at all. This
1507 // is wrong for range requests that could feed off nibbled memory (XXX).
1508 if (mem_obj->inmem_lo) // in local memory cache, but got nibbled at
1509 return 0;
1510
1511 return 1;
1512 }
1513
1514 void
1515 StoreEntry::timestampsSet()
1516 {
1517 const HttpReply *reply = getReply();
1518 time_t served_date = reply->date;
1519 int age = reply->header.getInt(HDR_AGE);
1520 /* Compute the timestamp, mimicking RFC2616 section 13.2.3. */
1521 /* make sure that 0 <= served_date <= squid_curtime */
1522
1523 if (served_date < 0 || served_date > squid_curtime)
1524 served_date = squid_curtime;
1525
1526 /* Bug 1791:
1527 * If the returned Date: is more than 24 hours older than
1528 * the squid_curtime, then one of us needs to use NTP to set our
1529 * clock. We'll pretend that our clock is right.
1530 */
1531 else if (served_date < (squid_curtime - 24 * 60 * 60) )
1532 served_date = squid_curtime;
1533
1534 /*
1535 * Compensate with Age header if origin server clock is ahead
1536 * of us and there is a cache in between us and the origin
1537 * server. But DONT compensate if the age value is larger than
1538 * squid_curtime because it results in a negative served_date.
1539 */
1540 if (age > squid_curtime - served_date)
1541 if (squid_curtime > age)
1542 served_date = squid_curtime - age;
1543
1544 // compensate for Squid-to-server and server-to-Squid delays
1545 if (mem_obj && mem_obj->request) {
1546 const time_t request_sent =
1547 mem_obj->request->hier.peer_http_request_sent.tv_sec;
1548 if (0 < request_sent && request_sent < squid_curtime)
1549 served_date -= (squid_curtime - request_sent);
1550 }
1551
1552 if (reply->expires > 0 && reply->date > -1)
1553 expires = served_date + (reply->expires - reply->date);
1554 else
1555 expires = reply->expires;
1556
1557 lastmod = reply->last_modified;
1558
1559 timestamp = served_date;
1560 }
1561
1562 void
1563 StoreEntry::registerAbort(STABH * cb, void *data)
1564 {
1565 assert(mem_obj);
1566 assert(mem_obj->abort.callback == NULL);
1567 mem_obj->abort.callback = cb;
1568 mem_obj->abort.data = cbdataReference(data);
1569 }
1570
1571 void
1572 StoreEntry::unregisterAbort()
1573 {
1574 assert(mem_obj);
1575 if (mem_obj->abort.callback) {
1576 mem_obj->abort.callback = NULL;
1577 cbdataReferenceDone(mem_obj->abort.data);
1578 }
1579 }
1580
1581 void
1582 StoreEntry::dump(int l) const
1583 {
1584 debugs(20, l, "StoreEntry->key: " << getMD5Text());
1585 debugs(20, l, "StoreEntry->next: " << next);
1586 debugs(20, l, "StoreEntry->mem_obj: " << mem_obj);
1587 debugs(20, l, "StoreEntry->timestamp: " << timestamp);
1588 debugs(20, l, "StoreEntry->lastref: " << lastref);
1589 debugs(20, l, "StoreEntry->expires: " << expires);
1590 debugs(20, l, "StoreEntry->lastmod: " << lastmod);
1591 debugs(20, l, "StoreEntry->swap_file_sz: " << swap_file_sz);
1592 debugs(20, l, "StoreEntry->refcount: " << refcount);
1593 debugs(20, l, "StoreEntry->flags: " << storeEntryFlags(this));
1594 debugs(20, l, "StoreEntry->swap_dirn: " << swap_dirn);
1595 debugs(20, l, "StoreEntry->swap_filen: " << swap_filen);
1596 debugs(20, l, "StoreEntry->lock_count: " << lock_count);
1597 debugs(20, l, "StoreEntry->mem_status: " << mem_status);
1598 debugs(20, l, "StoreEntry->ping_status: " << ping_status);
1599 debugs(20, l, "StoreEntry->store_status: " << store_status);
1600 debugs(20, l, "StoreEntry->swap_status: " << swap_status);
1601 }
1602
1603 /*
1604 * NOTE, this function assumes only two mem states
1605 */
1606 void
1607 StoreEntry::setMemStatus(mem_status_t new_status)
1608 {
1609 if (new_status == mem_status)
1610 return;
1611
1612 // are we using a shared memory cache?
1613 if (Config.memShared && IamWorkerProcess()) {
1614 // This method was designed to update replacement policy, not to
1615 // actually purge something from the memory cache (TODO: rename?).
1616 // Shared memory cache does not have a policy that needs updates.
1617 mem_status = new_status;
1618 return;
1619 }
1620
1621 assert(mem_obj != NULL);
1622
1623 if (new_status == IN_MEMORY) {
1624 assert(mem_obj->inmem_lo == 0);
1625
1626 if (EBIT_TEST(flags, ENTRY_SPECIAL)) {
1627 debugs(20, 4, "not inserting special " << *this << " into policy");
1628 } else {
1629 mem_policy->Add(mem_policy, this, &mem_obj->repl);
1630 debugs(20, 4, "inserted " << *this << " key: " << getMD5Text());
1631 }
1632
1633 ++hot_obj_count; // TODO: maintain for the shared hot cache as well
1634 } else {
1635 if (EBIT_TEST(flags, ENTRY_SPECIAL)) {
1636 debugs(20, 4, "not removing special " << *this << " from policy");
1637 } else {
1638 mem_policy->Remove(mem_policy, this, &mem_obj->repl);
1639 debugs(20, 4, "removed " << *this);
1640 }
1641
1642 --hot_obj_count;
1643 }
1644
1645 mem_status = new_status;
1646 }
1647
1648 const char *
1649 StoreEntry::url() const
1650 {
1651 if (this == NULL)
1652 return "[null_entry]";
1653 else if (mem_obj == NULL)
1654 return "[null_mem_obj]";
1655 else
1656 return mem_obj->storeId();
1657 }
1658
1659 MemObject *
1660 StoreEntry::makeMemObject()
1661 {
1662 if (!mem_obj)
1663 mem_obj = new MemObject();
1664 return mem_obj;
1665 }
1666
1667 void
1668 StoreEntry::createMemObject(const char *aUrl, const char *aLogUrl, const HttpRequestMethod &aMethod)
1669 {
1670 makeMemObject();
1671 mem_obj->setUris(aUrl, aLogUrl, aMethod);
1672 }
1673
1674 /* this just sets DELAY_SENDING */
1675 void
1676 StoreEntry::buffer()
1677 {
1678 EBIT_SET(flags, DELAY_SENDING);
1679 }
1680
1681 /* this just clears DELAY_SENDING and Invokes the handlers */
1682 void
1683 StoreEntry::flush()
1684 {
1685 if (EBIT_TEST(flags, DELAY_SENDING)) {
1686 EBIT_CLR(flags, DELAY_SENDING);
1687 invokeHandlers();
1688 }
1689 }
1690
1691 int64_t
1692 StoreEntry::objectLen() const
1693 {
1694 assert(mem_obj != NULL);
1695 return mem_obj->object_sz;
1696 }
1697
1698 int64_t
1699 StoreEntry::contentLen() const
1700 {
1701 assert(mem_obj != NULL);
1702 assert(getReply() != NULL);
1703 return objectLen() - getReply()->hdr_sz;
1704 }
1705
1706 HttpReply const *
1707 StoreEntry::getReply () const
1708 {
1709 if (NULL == mem_obj)
1710 return NULL;
1711
1712 return mem_obj->getReply();
1713 }
1714
1715 void
1716 StoreEntry::reset()
1717 {
1718 assert (mem_obj);
1719 debugs(20, 3, "StoreEntry::reset: " << url());
1720 mem_obj->reset();
1721 HttpReply *rep = (HttpReply *) getReply(); // bypass const
1722 rep->reset();
1723 expires = lastmod = timestamp = -1;
1724 }
1725
1726 /*
1727 * storeFsInit
1728 *
1729 * This routine calls the SETUP routine for each fs type.
1730 * I don't know where the best place for this is, and I'm not going to shuffle
1731 * around large chunks of code right now (that can be done once its working.)
1732 */
1733 void
1734 storeFsInit(void)
1735 {
1736 storeReplSetup();
1737 }
1738
1739 /*
1740 * called to add another store removal policy module
1741 */
1742 void
1743 storeReplAdd(const char *type, REMOVALPOLICYCREATE * create)
1744 {
1745 int i;
1746
1747 /* find the number of currently known repl types */
1748 for (i = 0; storerepl_list && storerepl_list[i].typestr; ++i) {
1749 if (strcmp(storerepl_list[i].typestr, type) == 0) {
1750 debugs(20, DBG_IMPORTANT, "WARNING: Trying to load store replacement policy " << type << " twice.");
1751 return;
1752 }
1753 }
1754
1755 /* add the new type */
1756 storerepl_list = static_cast<storerepl_entry_t *>(xrealloc(storerepl_list, (i + 2) * sizeof(storerepl_entry_t)));
1757
1758 memset(&storerepl_list[i + 1], 0, sizeof(storerepl_entry_t));
1759
1760 storerepl_list[i].typestr = type;
1761
1762 storerepl_list[i].create = create;
1763 }
1764
1765 /*
1766 * Create a removal policy instance
1767 */
1768 RemovalPolicy *
1769 createRemovalPolicy(RemovalPolicySettings * settings)
1770 {
1771 storerepl_entry_t *r;
1772
1773 for (r = storerepl_list; r && r->typestr; ++r) {
1774 if (strcmp(r->typestr, settings->type) == 0)
1775 return r->create(settings->args);
1776 }
1777
1778 debugs(20, DBG_IMPORTANT, "ERROR: Unknown policy " << settings->type);
1779 debugs(20, DBG_IMPORTANT, "ERROR: Be sure to have set cache_replacement_policy");
1780 debugs(20, DBG_IMPORTANT, "ERROR: and memory_replacement_policy in squid.conf!");
1781 fatalf("ERROR: Unknown policy %s\n", settings->type);
1782 return NULL; /* NOTREACHED */
1783 }
1784
1785 #if 0
1786 void
1787 storeSwapFileNumberSet(StoreEntry * e, sfileno filn)
1788 {
1789 if (e->swap_file_number == filn)
1790 return;
1791
1792 if (filn < 0) {
1793 assert(-1 == filn);
1794 storeDirMapBitReset(e->swap_file_number);
1795 storeDirLRUDelete(e);
1796 e->swap_file_number = -1;
1797 } else {
1798 assert(-1 == e->swap_file_number);
1799 storeDirMapBitSet(e->swap_file_number = filn);
1800 storeDirLRUAdd(e);
1801 }
1802 }
1803
1804 #endif
1805
1806 /*
1807 * Replace a store entry with
1808 * a new reply. This eats the reply.
1809 */
1810 void
1811 StoreEntry::replaceHttpReply(HttpReply *rep, bool andStartWriting)
1812 {
1813 debugs(20, 3, "StoreEntry::replaceHttpReply: " << url());
1814
1815 if (!mem_obj) {
1816 debugs(20, DBG_CRITICAL, "Attempt to replace object with no in-memory representation");
1817 return;
1818 }
1819
1820 mem_obj->replaceHttpReply(rep);
1821
1822 if (andStartWriting)
1823 startWriting();
1824 }
1825
1826 void
1827 StoreEntry::startWriting()
1828 {
1829 Packer p;
1830
1831 /* TODO: when we store headers serparately remove the header portion */
1832 /* TODO: mark the length of the headers ? */
1833 /* We ONLY want the headers */
1834 packerToStoreInit(&p, this);
1835
1836 assert (isEmpty());
1837 assert(mem_obj);
1838
1839 const HttpReply *rep = getReply();
1840 assert(rep);
1841
1842 rep->packHeadersInto(&p);
1843 mem_obj->markEndOfReplyHeaders();
1844 EBIT_CLR(flags, ENTRY_FWD_HDR_WAIT);
1845
1846 rep->body.packInto(&p);
1847
1848 packerClean(&p);
1849 }
1850
1851 char const *
1852 StoreEntry::getSerialisedMetaData()
1853 {
1854 StoreMeta *tlv_list = storeSwapMetaBuild(this);
1855 int swap_hdr_sz;
1856 char *result = storeSwapMetaPack(tlv_list, &swap_hdr_sz);
1857 storeSwapTLVFree(tlv_list);
1858 assert (swap_hdr_sz >= 0);
1859 mem_obj->swap_hdr_sz = (size_t) swap_hdr_sz;
1860 return result;
1861 }
1862
1863 void
1864 StoreEntry::trimMemory(const bool preserveSwappable)
1865 {
1866 /*
1867 * DPW 2007-05-09
1868 * Bug #1943. We must not let go any data for IN_MEMORY
1869 * objects. We have to wait until the mem_status changes.
1870 */
1871 if (mem_status == IN_MEMORY)
1872 return;
1873
1874 if (EBIT_TEST(flags, ENTRY_SPECIAL))
1875 return; // cannot trim because we do not load them again
1876
1877 if (preserveSwappable)
1878 mem_obj->trimSwappable();
1879 else
1880 mem_obj->trimUnSwappable();
1881
1882 debugs(88, 7, *this << " inmem_lo=" << mem_obj->inmem_lo);
1883 }
1884
1885 bool
1886 StoreEntry::modifiedSince(HttpRequest * request) const
1887 {
1888 int object_length;
1889 time_t mod_time = lastmod;
1890
1891 if (mod_time < 0)
1892 mod_time = timestamp;
1893
1894 debugs(88, 3, "modifiedSince: '" << url() << "'");
1895
1896 debugs(88, 3, "modifiedSince: mod_time = " << mod_time);
1897
1898 if (mod_time < 0)
1899 return true;
1900
1901 /* Find size of the object */
1902 object_length = getReply()->content_length;
1903
1904 if (object_length < 0)
1905 object_length = contentLen();
1906
1907 if (mod_time > request->ims) {
1908 debugs(88, 3, "--> YES: entry newer than client");
1909 return true;
1910 } else if (mod_time < request->ims) {
1911 debugs(88, 3, "--> NO: entry older than client");
1912 return false;
1913 } else if (request->imslen < 0) {
1914 debugs(88, 3, "--> NO: same LMT, no client length");
1915 return false;
1916 } else if (request->imslen == object_length) {
1917 debugs(88, 3, "--> NO: same LMT, same length");
1918 return false;
1919 } else {
1920 debugs(88, 3, "--> YES: same LMT, different length");
1921 return true;
1922 }
1923 }
1924
1925 bool
1926 StoreEntry::hasEtag(ETag &etag) const
1927 {
1928 if (const HttpReply *reply = getReply()) {
1929 etag = reply->header.getETag(HDR_ETAG);
1930 if (etag.str)
1931 return true;
1932 }
1933 return false;
1934 }
1935
1936 bool
1937 StoreEntry::hasIfMatchEtag(const HttpRequest &request) const
1938 {
1939 const String reqETags = request.header.getList(HDR_IF_MATCH);
1940 return hasOneOfEtags(reqETags, false);
1941 }
1942
1943 bool
1944 StoreEntry::hasIfNoneMatchEtag(const HttpRequest &request) const
1945 {
1946 const String reqETags = request.header.getList(HDR_IF_NONE_MATCH);
1947 // weak comparison is allowed only for HEAD or full-body GET requests
1948 const bool allowWeakMatch = !request.flags.isRanged &&
1949 (request.method == Http::METHOD_GET || request.method == Http::METHOD_HEAD);
1950 return hasOneOfEtags(reqETags, allowWeakMatch);
1951 }
1952
1953 /// whether at least one of the request ETags matches entity ETag
1954 bool
1955 StoreEntry::hasOneOfEtags(const String &reqETags, const bool allowWeakMatch) const
1956 {
1957 const ETag repETag = getReply()->header.getETag(HDR_ETAG);
1958 if (!repETag.str)
1959 return strListIsMember(&reqETags, "*", ',');
1960
1961 bool matched = false;
1962 const char *pos = NULL;
1963 const char *item;
1964 int ilen;
1965 while (!matched && strListGetItem(&reqETags, ',', &item, &ilen, &pos)) {
1966 if (!strncmp(item, "*", ilen))
1967 matched = true;
1968 else {
1969 String str;
1970 str.append(item, ilen);
1971 ETag reqETag;
1972 if (etagParseInit(&reqETag, str.termedBuf())) {
1973 matched = allowWeakMatch ? etagIsWeakEqual(repETag, reqETag) :
1974 etagIsStrongEqual(repETag, reqETag);
1975 }
1976 }
1977 }
1978 return matched;
1979 }
1980
1981 SwapDir::Pointer
1982 StoreEntry::store() const
1983 {
1984 assert(0 <= swap_dirn && swap_dirn < Config.cacheSwap.n_configured);
1985 return INDEXSD(swap_dirn);
1986 }
1987
1988 void
1989 StoreEntry::unlink()
1990 {
1991 store()->unlink(*this); // implies disconnect()
1992 swap_filen = -1;
1993 swap_dirn = -1;
1994 swap_status = SWAPOUT_NONE;
1995 }
1996
1997 /*
1998 * return true if the entry is in a state where
1999 * it can accept more data (ie with write() method)
2000 */
2001 bool
2002 StoreEntry::isAccepting() const
2003 {
2004 if (STORE_PENDING != store_status)
2005 return false;
2006
2007 if (EBIT_TEST(flags, ENTRY_ABORTED))
2008 return false;
2009
2010 return true;
2011 }
2012
2013 std::ostream &operator <<(std::ostream &os, const StoreEntry &e)
2014 {
2015 os << "e:";
2016
2017 if (e.mem_obj) {
2018 if (e.mem_obj->xitTable.index > -1)
2019 os << 't' << e.mem_obj->xitTable.index;
2020 if (e.mem_obj->memCache.index > -1)
2021 os << 'm' << e.mem_obj->memCache.index;
2022 }
2023 if (e.swap_filen > -1 || e.swap_dirn > -1)
2024 os << 'd' << e.swap_filen << '@' << e.swap_dirn;
2025
2026 os << '=';
2027
2028 // print only non-default status values, using unique letters
2029 if (e.mem_status != NOT_IN_MEMORY ||
2030 e.store_status != STORE_PENDING ||
2031 e.swap_status != SWAPOUT_NONE ||
2032 e.ping_status != PING_NONE) {
2033 if (e.mem_status != NOT_IN_MEMORY) os << 'm';
2034 if (e.store_status != STORE_PENDING) os << 's';
2035 if (e.swap_status != SWAPOUT_NONE) os << 'w' << e.swap_status;
2036 if (e.ping_status != PING_NONE) os << 'p' << e.ping_status;
2037 }
2038
2039 // print only set flags, using unique letters
2040 if (e.flags) {
2041 if (EBIT_TEST(e.flags, ENTRY_SPECIAL)) os << 'S';
2042 if (EBIT_TEST(e.flags, ENTRY_REVALIDATE)) os << 'R';
2043 if (EBIT_TEST(e.flags, DELAY_SENDING)) os << 'P';
2044 if (EBIT_TEST(e.flags, RELEASE_REQUEST)) os << 'X';
2045 if (EBIT_TEST(e.flags, REFRESH_REQUEST)) os << 'F';
2046 if (EBIT_TEST(e.flags, ENTRY_DISPATCHED)) os << 'D';
2047 if (EBIT_TEST(e.flags, KEY_PRIVATE)) os << 'I';
2048 if (EBIT_TEST(e.flags, ENTRY_FWD_HDR_WAIT)) os << 'W';
2049 if (EBIT_TEST(e.flags, ENTRY_NEGCACHED)) os << 'N';
2050 if (EBIT_TEST(e.flags, ENTRY_VALIDATED)) os << 'V';
2051 if (EBIT_TEST(e.flags, ENTRY_BAD_LENGTH)) os << 'L';
2052 if (EBIT_TEST(e.flags, ENTRY_ABORTED)) os << 'A';
2053 }
2054
2055 if (e.mem_obj && e.mem_obj->smpCollapsed)
2056 os << 'O';
2057
2058 return os << '/' << &e << '*' << e.locks();
2059 }
2060
2061 /* NullStoreEntry */
2062
2063 NullStoreEntry NullStoreEntry::_instance;
2064
2065 NullStoreEntry *
2066 NullStoreEntry::getInstance()
2067 {
2068 return &_instance;
2069 }
2070
2071 char const *
2072 NullStoreEntry::getMD5Text() const
2073 {
2074 return "N/A";
2075 }
2076
2077 void
2078 NullStoreEntry::operator delete(void*)
2079 {
2080 fatal ("Attempt to delete NullStoreEntry\n");
2081 }
2082
2083 char const *
2084 NullStoreEntry::getSerialisedMetaData()
2085 {
2086 return NULL;
2087 }
2088
2089 #if !_USE_INLINE_
2090 #include "Store.cci"
2091 #endif