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