]> git.ipfire.org Git - thirdparty/squid.git/blob - src/neighbors.cc
Identify collapsed transactions (#213)
[thirdparty/squid.git] / src / neighbors.cc
1 /*
2 * Copyright (C) 1996-2018 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 /* DEBUG: section 15 Neighbor Routines */
10
11 #include "squid.h"
12 #include "acl/FilledChecklist.h"
13 #include "anyp/PortCfg.h"
14 #include "base/EnumIterator.h"
15 #include "CacheDigest.h"
16 #include "CachePeer.h"
17 #include "comm/Connection.h"
18 #include "comm/ConnOpener.h"
19 #include "event.h"
20 #include "FwdState.h"
21 #include "globals.h"
22 #include "htcp.h"
23 #include "HttpRequest.h"
24 #include "icmp/net_db.h"
25 #include "ICP.h"
26 #include "int.h"
27 #include "ip/Address.h"
28 #include "ip/tools.h"
29 #include "ipcache.h"
30 #include "MemObject.h"
31 #include "mgr/Registration.h"
32 #include "multicast.h"
33 #include "neighbors.h"
34 #include "NeighborTypeDomainList.h"
35 #include "pconn.h"
36 #include "PeerDigest.h"
37 #include "PeerPoolMgr.h"
38 #include "PeerSelectState.h"
39 #include "RequestFlags.h"
40 #include "SquidConfig.h"
41 #include "SquidMath.h"
42 #include "SquidTime.h"
43 #include "stat.h"
44 #include "Store.h"
45 #include "store_key_md5.h"
46 #include "tools.h"
47
48 /* count mcast group peers every 15 minutes */
49 #define MCAST_COUNT_RATE 900
50
51 bool peerAllowedToUse(const CachePeer *, PeerSelector *);
52 static int peerWouldBePinged(const CachePeer *, PeerSelector *);
53 static void neighborRemove(CachePeer *);
54 static void neighborAlive(CachePeer *, const MemObject *, const icp_common_t *);
55 #if USE_HTCP
56 static void neighborAliveHtcp(CachePeer *, const MemObject *, const HtcpReplyData *);
57 #endif
58 static void neighborCountIgnored(CachePeer *);
59 static void peerRefreshDNS(void *);
60 static IPH peerDNSConfigure;
61 static void peerProbeConnect(CachePeer *, const bool reprobeIfBusy = false);
62 static CNCB peerProbeConnectDone;
63 static void peerCountMcastPeersDone(void *data);
64 static void peerCountMcastPeersStart(void *data);
65 static void peerCountMcastPeersSchedule(CachePeer * p, time_t when);
66 static IRCB peerCountHandleIcpReply;
67
68 static void neighborIgnoreNonPeer(const Ip::Address &, icp_opcode);
69 static OBJH neighborDumpPeers;
70 static OBJH neighborDumpNonPeers;
71 static void dump_peers(StoreEntry * sentry, CachePeer * peers);
72
73 static unsigned short echo_port;
74
75 static int NLateReplies = 0;
76 static CachePeer *first_ping = NULL;
77
78 const char *
79 neighborTypeStr(const CachePeer * p)
80 {
81 if (p->type == PEER_NONE)
82 return "Non-Peer";
83
84 if (p->type == PEER_SIBLING)
85 return "Sibling";
86
87 if (p->type == PEER_MULTICAST)
88 return "Multicast Group";
89
90 return "Parent";
91 }
92
93 CachePeer *
94 whichPeer(const Ip::Address &from)
95 {
96 int j;
97
98 CachePeer *p = NULL;
99 debugs(15, 3, "whichPeer: from " << from);
100
101 for (p = Config.peers; p; p = p->next) {
102 for (j = 0; j < p->n_addresses; ++j) {
103 if (from == p->addresses[j] && from.port() == p->icp.port) {
104 return p;
105 }
106 }
107 }
108
109 return NULL;
110 }
111
112 peer_t
113 neighborType(const CachePeer * p, const AnyP::Uri &url)
114 {
115
116 const NeighborTypeDomainList *d = NULL;
117
118 for (d = p->typelist; d; d = d->next) {
119 if (0 == matchDomainName(url.host(), d->domain))
120 if (d->type != PEER_NONE)
121 return d->type;
122 }
123 #if PEER_MULTICAST_SIBLINGS
124 if (p->type == PEER_MULTICAST)
125 if (p->options.mcast_siblings)
126 return PEER_SIBLING;
127 #endif
128
129 return p->type;
130 }
131
132 /**
133 * \return Whether it is appropriate to fetch REQUEST from PEER.
134 */
135 bool
136 peerAllowedToUse(const CachePeer * p, PeerSelector * ps)
137 {
138 assert(ps);
139 HttpRequest *request = ps->request;
140 assert(request != NULL);
141
142 if (neighborType(p, request->url) == PEER_SIBLING) {
143 #if PEER_MULTICAST_SIBLINGS
144 if (p->type == PEER_MULTICAST && p->options.mcast_siblings &&
145 (request->flags.noCache || request->flags.refresh || request->flags.loopDetected || request->flags.needValidation))
146 debugs(15, 2, "peerAllowedToUse(" << p->name << ", " << request->url.authority() << ") : multicast-siblings optimization match");
147 #endif
148 if (request->flags.noCache)
149 return false;
150
151 if (request->flags.refresh)
152 return false;
153
154 if (request->flags.loopDetected)
155 return false;
156
157 if (request->flags.needValidation)
158 return false;
159 }
160
161 // CONNECT requests are proxy requests. Not to be forwarded to origin servers.
162 // Unless the destination port matches, in which case we MAY perform a 'DIRECT' to this CachePeer.
163 if (p->options.originserver && request->method == Http::METHOD_CONNECT && request->url.port() != p->http_port)
164 return false;
165
166 if (p->access == NULL)
167 return true;
168
169 ACLFilledChecklist checklist(p->access, request, NULL);
170 checklist.al = ps->al;
171 checklist.syncAle(request, nullptr);
172 return checklist.fastCheck().allowed();
173 }
174
175 /* Return TRUE if it is okay to send an ICP request to this CachePeer. */
176 static int
177 peerWouldBePinged(const CachePeer * p, PeerSelector * ps)
178 {
179 assert(ps);
180 HttpRequest *request = ps->request;
181
182 if (p->icp.port == 0)
183 return 0;
184
185 if (p->options.no_query)
186 return 0;
187
188 if (p->options.mcast_responder)
189 return 0;
190
191 if (p->n_addresses == 0)
192 return 0;
193
194 if (p->options.background_ping && (squid_curtime - p->stats.last_query < Config.backgroundPingRate))
195 return 0;
196
197 /* the case below seems strange, but can happen if the
198 * URL host is on the other side of a firewall */
199 if (p->type == PEER_SIBLING)
200 if (!request->flags.hierarchical)
201 return 0;
202
203 if (!peerAllowedToUse(p, ps))
204 return 0;
205
206 /* Ping dead peers every timeout interval */
207 if (squid_curtime - p->stats.last_query > Config.Timeout.deadPeer)
208 return 1;
209
210 if (!neighborUp(p))
211 return 0;
212
213 return 1;
214 }
215
216 bool
217 peerCanOpenMore(const CachePeer *p)
218 {
219 const int effectiveLimit = p->max_conn <= 0 ? Squid_MaxFD : p->max_conn;
220 const int remaining = effectiveLimit - p->stats.conn_open;
221 debugs(15, 7, remaining << '=' << effectiveLimit << '-' << p->stats.conn_open);
222 return remaining > 0;
223 }
224
225 bool
226 peerHasConnAvailable(const CachePeer *p)
227 {
228 // Standby connections can be used without opening new connections.
229 const int standbys = p->standby.pool ? p->standby.pool->count() : 0;
230
231 // XXX: Some idle pconns can be used without opening new connections.
232 // Complication: Idle pconns cannot be reused for some requests.
233 const int usableIdles = 0;
234
235 const int available = standbys + usableIdles;
236 debugs(15, 7, available << '=' << standbys << '+' << usableIdles);
237 return available > 0;
238 }
239
240 void
241 peerConnClosed(CachePeer *p)
242 {
243 --p->stats.conn_open;
244 if (p->standby.waitingForClose && peerCanOpenMore(p)) {
245 p->standby.waitingForClose = false;
246 PeerPoolMgr::Checkpoint(p->standby.mgr, "conn closed");
247 }
248 }
249
250 /* Return TRUE if it is okay to send an HTTP request to this CachePeer. */
251 int
252 peerHTTPOkay(const CachePeer * p, PeerSelector * ps)
253 {
254 if (!peerCanOpenMore(p) && !peerHasConnAvailable(p))
255 return 0;
256
257 if (!peerAllowedToUse(p, ps))
258 return 0;
259
260 if (!neighborUp(p))
261 return 0;
262
263 return 1;
264 }
265
266 int
267 neighborsCount(PeerSelector *ps)
268 {
269 CachePeer *p = NULL;
270 int count = 0;
271
272 for (p = Config.peers; p; p = p->next)
273 if (peerWouldBePinged(p, ps))
274 ++count;
275
276 debugs(15, 3, "neighborsCount: " << count);
277
278 return count;
279 }
280
281 CachePeer *
282 getFirstUpParent(PeerSelector *ps)
283 {
284 assert(ps);
285 HttpRequest *request = ps->request;
286
287 CachePeer *p = NULL;
288
289 for (p = Config.peers; p; p = p->next) {
290 if (!neighborUp(p))
291 continue;
292
293 if (neighborType(p, request->url) != PEER_PARENT)
294 continue;
295
296 if (!peerHTTPOkay(p, ps))
297 continue;
298
299 break;
300 }
301
302 debugs(15, 3, "getFirstUpParent: returning " << (p ? p->host : "NULL"));
303 return p;
304 }
305
306 CachePeer *
307 getRoundRobinParent(PeerSelector *ps)
308 {
309 assert(ps);
310 HttpRequest *request = ps->request;
311
312 CachePeer *p;
313 CachePeer *q = NULL;
314
315 for (p = Config.peers; p; p = p->next) {
316 if (!p->options.roundrobin)
317 continue;
318
319 if (neighborType(p, request->url) != PEER_PARENT)
320 continue;
321
322 if (!peerHTTPOkay(p, ps))
323 continue;
324
325 if (p->weight == 0)
326 continue;
327
328 if (q) {
329 if (p->weight == q->weight) {
330 if (q->rr_count < p->rr_count)
331 continue;
332 } else if ( ((double) q->rr_count / q->weight) < ((double) p->rr_count / p->weight)) {
333 continue;
334 }
335 }
336
337 q = p;
338 }
339
340 if (q)
341 ++ q->rr_count;
342
343 debugs(15, 3, HERE << "returning " << (q ? q->host : "NULL"));
344
345 return q;
346 }
347
348 CachePeer *
349 getWeightedRoundRobinParent(PeerSelector *ps)
350 {
351 assert(ps);
352 HttpRequest *request = ps->request;
353
354 CachePeer *p;
355 CachePeer *q = NULL;
356 int weighted_rtt;
357
358 for (p = Config.peers; p; p = p->next) {
359 if (!p->options.weighted_roundrobin)
360 continue;
361
362 if (neighborType(p, request->url) != PEER_PARENT)
363 continue;
364
365 if (!peerHTTPOkay(p, ps))
366 continue;
367
368 if (q && q->rr_count < p->rr_count)
369 continue;
370
371 q = p;
372 }
373
374 if (q && q->rr_count > 1000000)
375 for (p = Config.peers; p; p = p->next) {
376 if (!p->options.weighted_roundrobin)
377 continue;
378
379 if (neighborType(p, request->url) != PEER_PARENT)
380 continue;
381
382 p->rr_count = 0;
383 }
384
385 if (q) {
386 weighted_rtt = (q->stats.rtt - q->basetime) / q->weight;
387
388 if (weighted_rtt < 1)
389 weighted_rtt = 1;
390
391 q->rr_count += weighted_rtt;
392
393 debugs(15, 3, "getWeightedRoundRobinParent: weighted_rtt " << weighted_rtt);
394 }
395
396 debugs(15, 3, "getWeightedRoundRobinParent: returning " << (q ? q->host : "NULL"));
397 return q;
398 }
399
400 /**
401 * This gets called every 5 minutes to clear the round-robin counter.
402 * The exact timing is an arbitrary default, set on estimate timing of a
403 * large number of requests in a high-performance environment during the
404 * period. The larger the number of requests between cycled resets the
405 * more balanced the operations.
406 *
407 \param data unused.
408 \todo Make the reset timing a selectable parameter in squid.conf
409 */
410 static void
411 peerClearRRLoop(void *data)
412 {
413 peerClearRR();
414 eventAdd("peerClearRR", peerClearRRLoop, data, 5 * 60.0, 0);
415 }
416
417 /**
418 * This gets called on startup and restart to kick off the CachePeer round-robin
419 * maintenance event. It ensures that no matter how many times its called
420 * no more than one event is scheduled.
421 */
422 void
423 peerClearRRStart(void)
424 {
425 static bool event_added = false;
426 if (!event_added) {
427 peerClearRRLoop(NULL);
428 event_added=true;
429 }
430 }
431
432 /**
433 * Called whenever the round-robin counters need to be reset to a sane state.
434 * So far those times are:
435 * - On startup and reconfigure - to set the counters to sane initial settings.
436 * - When a CachePeer has revived from dead, to prevent the revived CachePeer being
437 * flooded with requests which it has 'missed' during the down period.
438 */
439 void
440 peerClearRR()
441 {
442 CachePeer *p = NULL;
443 for (p = Config.peers; p; p = p->next) {
444 p->rr_count = 1;
445 }
446 }
447
448 /**
449 * Perform all actions when a CachePeer is detected revived.
450 */
451 void
452 peerAlive(CachePeer *p)
453 {
454 if (p->stats.logged_state == PEER_DEAD && p->tcp_up) {
455 debugs(15, DBG_IMPORTANT, "Detected REVIVED " << neighborTypeStr(p) << ": " << p->name);
456 p->stats.logged_state = PEER_ALIVE;
457 peerClearRR();
458 if (p->standby.mgr.valid())
459 PeerPoolMgr::Checkpoint(p->standby.mgr, "revived peer");
460 }
461
462 p->stats.last_reply = squid_curtime;
463 p->stats.probe_start = 0;
464 }
465
466 CachePeer *
467 getDefaultParent(PeerSelector *ps)
468 {
469 assert(ps);
470 HttpRequest *request = ps->request;
471
472 CachePeer *p = NULL;
473
474 for (p = Config.peers; p; p = p->next) {
475 if (neighborType(p, request->url) != PEER_PARENT)
476 continue;
477
478 if (!p->options.default_parent)
479 continue;
480
481 if (!peerHTTPOkay(p, ps))
482 continue;
483
484 debugs(15, 3, "getDefaultParent: returning " << p->host);
485
486 return p;
487 }
488
489 debugs(15, 3, "getDefaultParent: returning NULL");
490 return NULL;
491 }
492
493 CachePeer *
494 getNextPeer(CachePeer * p)
495 {
496 return p->next;
497 }
498
499 CachePeer *
500 getFirstPeer(void)
501 {
502 return Config.peers;
503 }
504
505 static void
506 neighborRemove(CachePeer * target)
507 {
508 CachePeer *p = NULL;
509 CachePeer **P = NULL;
510 p = Config.peers;
511 P = &Config.peers;
512
513 while (p) {
514 if (target == p)
515 break;
516
517 P = &p->next;
518
519 p = p->next;
520 }
521
522 if (p) {
523 *P = p->next;
524 p->next = NULL;
525 delete p;
526 --Config.npeers;
527 }
528
529 first_ping = Config.peers;
530 }
531
532 static void
533 neighborsRegisterWithCacheManager()
534 {
535 Mgr::RegisterAction("server_list",
536 "Peer Cache Statistics",
537 neighborDumpPeers, 0, 1);
538
539 if (Comm::IsConnOpen(icpIncomingConn)) {
540 Mgr::RegisterAction("non_peers",
541 "List of Unknown sites sending ICP messages",
542 neighborDumpNonPeers, 0, 1);
543 }
544 }
545
546 void
547 neighbors_init(void)
548 {
549 struct servent *sep = NULL;
550 const char *me = getMyHostname();
551 CachePeer *thisPeer = NULL;
552 CachePeer *next = NULL;
553
554 neighborsRegisterWithCacheManager();
555
556 if (Comm::IsConnOpen(icpIncomingConn)) {
557
558 for (thisPeer = Config.peers; thisPeer; thisPeer = next) {
559 next = thisPeer->next;
560
561 if (0 != strcmp(thisPeer->host, me))
562 continue;
563
564 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
565 if (thisPeer->http_port != s->s.port())
566 continue;
567
568 debugs(15, DBG_IMPORTANT, "WARNING: Peer looks like this host");
569
570 debugs(15, DBG_IMPORTANT, " Ignoring " <<
571 neighborTypeStr(thisPeer) << " " << thisPeer->host <<
572 "/" << thisPeer->http_port << "/" <<
573 thisPeer->icp.port);
574
575 neighborRemove(thisPeer);
576 }
577 }
578 }
579
580 peerRefreshDNS((void *) 1);
581
582 sep = getservbyname("echo", "udp");
583 echo_port = sep ? ntohs((unsigned short) sep->s_port) : 7;
584
585 first_ping = Config.peers;
586 }
587
588 int
589 neighborsUdpPing(HttpRequest * request,
590 StoreEntry * entry,
591 IRCB * callback,
592 PeerSelector *ps,
593 int *exprep,
594 int *timeout)
595 {
596 const char *url = entry->url();
597 MemObject *mem = entry->mem_obj;
598 CachePeer *p = NULL;
599 int i;
600 int reqnum = 0;
601 int flags;
602 int queries_sent = 0;
603 int peers_pinged = 0;
604 int parent_timeout = 0, parent_exprep = 0;
605 int sibling_timeout = 0, sibling_exprep = 0;
606 int mcast_timeout = 0, mcast_exprep = 0;
607
608 if (Config.peers == NULL)
609 return 0;
610
611 assert(!entry->hasDisk());
612
613 mem->start_ping = current_time;
614
615 mem->ping_reply_callback = callback;
616
617 mem->ircb_data = ps;
618
619 reqnum = icpSetCacheKey((const cache_key *)entry->key);
620
621 for (i = 0, p = first_ping; i++ < Config.npeers; p = p->next) {
622 if (p == NULL)
623 p = Config.peers;
624
625 debugs(15, 5, "neighborsUdpPing: Peer " << p->host);
626
627 if (!peerWouldBePinged(p, ps))
628 continue; /* next CachePeer */
629
630 ++peers_pinged;
631
632 debugs(15, 4, "neighborsUdpPing: pinging peer " << p->host << " for '" << url << "'");
633
634 debugs(15, 3, "neighborsUdpPing: key = '" << entry->getMD5Text() << "'");
635
636 debugs(15, 3, "neighborsUdpPing: reqnum = " << reqnum);
637
638 #if USE_HTCP
639 if (p->options.htcp && !p->options.htcp_only_clr) {
640 if (Config.Port.htcp <= 0) {
641 debugs(15, DBG_CRITICAL, "HTCP is disabled! Cannot send HTCP request to peer.");
642 continue;
643 }
644
645 debugs(15, 3, "neighborsUdpPing: sending HTCP query");
646 if (htcpQuery(entry, request, p) <= 0)
647 continue; // unable to send.
648 } else
649 #endif
650 {
651 if (Config.Port.icp <= 0 || !Comm::IsConnOpen(icpOutgoingConn)) {
652 debugs(15, DBG_CRITICAL, "ICP is disabled! Cannot send ICP request to peer.");
653 continue;
654 } else {
655
656 if (p->type == PEER_MULTICAST)
657 mcastSetTtl(icpOutgoingConn->fd, p->mcast.ttl);
658
659 if (p->icp.port == echo_port) {
660 debugs(15, 4, "neighborsUdpPing: Looks like a dumb cache, send DECHO ping");
661 // TODO: Get ALE from callback_data if possible.
662 icpCreateAndSend(ICP_DECHO, 0, url, reqnum, 0,
663 icpOutgoingConn->fd, p->in_addr, nullptr);
664 } else {
665 flags = 0;
666
667 if (Config.onoff.query_icmp)
668 if (p->icp.version == ICP_VERSION_2)
669 flags |= ICP_FLAG_SRC_RTT;
670
671 // TODO: Get ALE from callback_data if possible.
672 icpCreateAndSend(ICP_QUERY, flags, url, reqnum, 0,
673 icpOutgoingConn->fd, p->in_addr, nullptr);
674 }
675 }
676 }
677
678 ++queries_sent;
679
680 ++ p->stats.pings_sent;
681
682 if (p->type == PEER_MULTICAST) {
683 mcast_exprep += p->mcast.n_replies_expected;
684 mcast_timeout += (p->stats.rtt * p->mcast.n_replies_expected);
685 } else if (neighborUp(p)) {
686 /* its alive, expect a reply from it */
687
688 if (neighborType(p, request->url) == PEER_PARENT) {
689 ++parent_exprep;
690 parent_timeout += p->stats.rtt;
691 } else {
692 ++sibling_exprep;
693 sibling_timeout += p->stats.rtt;
694 }
695 } else {
696 /* Neighbor is dead; ping it anyway, but don't expect a reply */
697 /* log it once at the threshold */
698
699 if (p->stats.logged_state == PEER_ALIVE) {
700 debugs(15, DBG_IMPORTANT, "Detected DEAD " << neighborTypeStr(p) << ": " << p->name);
701 p->stats.logged_state = PEER_DEAD;
702 }
703 }
704
705 p->stats.last_query = squid_curtime;
706
707 /*
708 * keep probe_start == 0 for a multicast CachePeer,
709 * so neighborUp() never says this CachePeer is dead.
710 */
711
712 if ((p->type != PEER_MULTICAST) && (p->stats.probe_start == 0))
713 p->stats.probe_start = squid_curtime;
714 }
715
716 if ((first_ping = first_ping->next) == NULL)
717 first_ping = Config.peers;
718
719 /*
720 * How many replies to expect?
721 */
722 *exprep = parent_exprep + sibling_exprep + mcast_exprep;
723
724 /*
725 * If there is a configured timeout, use it
726 */
727 if (Config.Timeout.icp_query)
728 *timeout = Config.Timeout.icp_query;
729 else {
730 if (*exprep > 0) {
731 if (parent_exprep)
732 *timeout = 2 * parent_timeout / parent_exprep;
733 else if (mcast_exprep)
734 *timeout = 2 * mcast_timeout / mcast_exprep;
735 else
736 *timeout = 2 * sibling_timeout / sibling_exprep;
737 } else
738 *timeout = 2000; /* 2 seconds */
739
740 if (Config.Timeout.icp_query_max)
741 if (*timeout > Config.Timeout.icp_query_max)
742 *timeout = Config.Timeout.icp_query_max;
743
744 if (*timeout < Config.Timeout.icp_query_min)
745 *timeout = Config.Timeout.icp_query_min;
746 }
747
748 return peers_pinged;
749 }
750
751 /* lookup the digest of a given CachePeer */
752 lookup_t
753 peerDigestLookup(CachePeer * p, PeerSelector * ps)
754 {
755 #if USE_CACHE_DIGESTS
756 assert(ps);
757 HttpRequest *request = ps->request;
758 const cache_key *key = request ? storeKeyPublicByRequest(request) : NULL;
759 assert(p);
760 assert(request);
761 debugs(15, 5, "peerDigestLookup: peer " << p->host);
762 /* does the peeer have a valid digest? */
763
764 if (!p->digest) {
765 debugs(15, 5, "peerDigestLookup: gone!");
766 return LOOKUP_NONE;
767 } else if (!peerHTTPOkay(p, ps)) {
768 debugs(15, 5, "peerDigestLookup: !peerHTTPOkay");
769 return LOOKUP_NONE;
770 } else if (!p->digest->flags.needed) {
771 debugs(15, 5, "peerDigestLookup: note need");
772 peerDigestNeeded(p->digest);
773 return LOOKUP_NONE;
774 } else if (!p->digest->flags.usable) {
775 debugs(15, 5, "peerDigestLookup: !ready && " << (p->digest->flags.requested ? "" : "!") << "requested");
776 return LOOKUP_NONE;
777 }
778
779 debugs(15, 5, "peerDigestLookup: OK to lookup peer " << p->host);
780 assert(p->digest->cd);
781 /* does digest predict a hit? */
782
783 if (!p->digest->cd->contains(key))
784 return LOOKUP_MISS;
785
786 debugs(15, 5, "peerDigestLookup: peer " << p->host << " says HIT!");
787
788 return LOOKUP_HIT;
789
790 #endif
791
792 return LOOKUP_NONE;
793 }
794
795 /* select best CachePeer based on cache digests */
796 CachePeer *
797 neighborsDigestSelect(PeerSelector *ps)
798 {
799 CachePeer *best_p = NULL;
800 #if USE_CACHE_DIGESTS
801 assert(ps);
802 HttpRequest *request = ps->request;
803
804 int best_rtt = 0;
805 int choice_count = 0;
806 int ichoice_count = 0;
807 CachePeer *p;
808 int p_rtt;
809 int i;
810
811 if (!request->flags.hierarchical)
812 return NULL;
813
814 storeKeyPublicByRequest(request);
815
816 for (i = 0, p = first_ping; i++ < Config.npeers; p = p->next) {
817 lookup_t lookup;
818
819 if (!p)
820 p = Config.peers;
821
822 if (i == 1)
823 first_ping = p;
824
825 lookup = peerDigestLookup(p, ps);
826
827 if (lookup == LOOKUP_NONE)
828 continue;
829
830 ++choice_count;
831
832 if (lookup == LOOKUP_MISS)
833 continue;
834
835 p_rtt = netdbHostRtt(p->host);
836
837 debugs(15, 5, "neighborsDigestSelect: peer " << p->host << " rtt: " << p_rtt);
838
839 /* is this CachePeer better than others in terms of rtt ? */
840 if (!best_p || (p_rtt && p_rtt < best_rtt)) {
841 best_p = p;
842 best_rtt = p_rtt;
843
844 if (p_rtt) /* informative choice (aka educated guess) */
845 ++ichoice_count;
846
847 debugs(15, 4, "neighborsDigestSelect: peer " << p->host << " leads with rtt " << best_rtt);
848 }
849 }
850
851 debugs(15, 4, "neighborsDigestSelect: choices: " << choice_count << " (" << ichoice_count << ")");
852 peerNoteDigestLookup(request, best_p,
853 best_p ? LOOKUP_HIT : (choice_count ? LOOKUP_MISS : LOOKUP_NONE));
854 request->hier.n_choices = choice_count;
855 request->hier.n_ichoices = ichoice_count;
856 #endif
857
858 return best_p;
859 }
860
861 void
862 peerNoteDigestLookup(HttpRequest * request, CachePeer * p, lookup_t lookup)
863 {
864 #if USE_CACHE_DIGESTS
865 if (p)
866 strncpy(request->hier.cd_host, p->host, sizeof(request->hier.cd_host)-1);
867 else
868 *request->hier.cd_host = '\0';
869
870 request->hier.cd_lookup = lookup;
871 debugs(15, 4, "peerNoteDigestLookup: peer " << (p? p->host : "<none>") << ", lookup: " << lookup_t_str[lookup] );
872 #endif
873 }
874
875 static void
876 neighborAlive(CachePeer * p, const MemObject *, const icp_common_t * header)
877 {
878 peerAlive(p);
879 ++ p->stats.pings_acked;
880
881 if ((icp_opcode) header->opcode <= ICP_END)
882 ++ p->icp.counts[header->opcode];
883
884 p->icp.version = (int) header->version;
885 }
886
887 static void
888 neighborUpdateRtt(CachePeer * p, MemObject * mem)
889 {
890 int rtt, rtt_av_factor;
891
892 if (!mem)
893 return;
894
895 if (!mem->start_ping.tv_sec)
896 return;
897
898 rtt = tvSubMsec(mem->start_ping, current_time);
899
900 if (rtt < 1 || rtt > 10000)
901 return;
902
903 rtt_av_factor = RTT_AV_FACTOR;
904
905 if (p->options.weighted_roundrobin)
906 rtt_av_factor = RTT_BACKGROUND_AV_FACTOR;
907
908 p->stats.rtt = Math::intAverage(p->stats.rtt, rtt, p->stats.pings_acked, rtt_av_factor);
909 }
910
911 #if USE_HTCP
912 static void
913 neighborAliveHtcp(CachePeer * p, const MemObject *, const HtcpReplyData * htcp)
914 {
915 peerAlive(p);
916 ++ p->stats.pings_acked;
917 ++ p->htcp.counts[htcp->hit ? 1 : 0];
918 p->htcp.version = htcp->version;
919 }
920
921 #endif
922
923 static void
924 neighborCountIgnored(CachePeer * p)
925 {
926 if (p == NULL)
927 return;
928
929 ++ p->stats.ignored_replies;
930
931 ++NLateReplies;
932 }
933
934 static CachePeer *non_peers = NULL;
935
936 static void
937 neighborIgnoreNonPeer(const Ip::Address &from, icp_opcode opcode)
938 {
939 CachePeer *np;
940
941 for (np = non_peers; np; np = np->next) {
942 if (np->in_addr != from)
943 continue;
944
945 if (np->in_addr.port() != from.port())
946 continue;
947
948 break;
949 }
950
951 if (np == NULL) {
952 np = new CachePeer;
953 np->in_addr = from;
954 np->icp.port = from.port();
955 np->type = PEER_NONE;
956 np->host = new char[MAX_IPSTRLEN];
957 from.toStr(np->host,MAX_IPSTRLEN);
958 np->next = non_peers;
959 non_peers = np;
960 }
961
962 ++ np->icp.counts[opcode];
963
964 if (isPowTen(++np->stats.ignored_replies))
965 debugs(15, DBG_IMPORTANT, "WARNING: Ignored " << np->stats.ignored_replies << " replies from non-peer " << np->host);
966 }
967
968 /* ignoreMulticastReply
969 *
970 * * We want to ignore replies from multicast peers if the
971 * * cache_host_domain rules would normally prevent the CachePeer
972 * * from being used
973 */
974 static int
975 ignoreMulticastReply(CachePeer * p, PeerSelector * ps)
976 {
977 if (p == NULL)
978 return 0;
979
980 if (!p->options.mcast_responder)
981 return 0;
982
983 if (peerHTTPOkay(p, ps))
984 return 0;
985
986 return 1;
987 }
988
989 /**
990 * I should attach these records to the entry. We take the first
991 * hit we get our wait until everyone misses. The timeout handler
992 * call needs to nip this shopping list or call one of the misses.
993 *
994 * If a hit process is already started, then sobeit
995 */
996 void
997 neighborsUdpAck(const cache_key * key, icp_common_t * header, const Ip::Address &from)
998 {
999 CachePeer *p = NULL;
1000 StoreEntry *entry;
1001 MemObject *mem = NULL;
1002 peer_t ntype = PEER_NONE;
1003 icp_opcode opcode = (icp_opcode) header->opcode;
1004
1005 debugs(15, 6, "neighborsUdpAck: opcode " << opcode << " '" << storeKeyText(key) << "'");
1006
1007 if ((entry = Store::Root().findCallbackXXX(key)))
1008 mem = entry->mem_obj;
1009
1010 if ((p = whichPeer(from)))
1011 neighborAlive(p, mem, header);
1012
1013 if (opcode > ICP_END)
1014 return;
1015
1016 const char *opcode_d = icp_opcode_str[opcode];
1017
1018 if (p)
1019 neighborUpdateRtt(p, mem);
1020
1021 /* Does the entry exist? */
1022 if (NULL == entry) {
1023 debugs(12, 3, "neighborsUdpAck: Cache key '" << storeKeyText(key) << "' not found");
1024 neighborCountIgnored(p);
1025 return;
1026 }
1027
1028 /* check if someone is already fetching it */
1029 if (EBIT_TEST(entry->flags, ENTRY_DISPATCHED)) {
1030 debugs(15, 3, "neighborsUdpAck: '" << storeKeyText(key) << "' already being fetched.");
1031 neighborCountIgnored(p);
1032 return;
1033 }
1034
1035 if (mem == NULL) {
1036 debugs(15, 2, "Ignoring " << opcode_d << " for missing mem_obj: " << storeKeyText(key));
1037 neighborCountIgnored(p);
1038 return;
1039 }
1040
1041 if (entry->ping_status != PING_WAITING) {
1042 debugs(15, 2, "neighborsUdpAck: Late " << opcode_d << " for " << storeKeyText(key));
1043 neighborCountIgnored(p);
1044 return;
1045 }
1046
1047 if (!entry->locked()) {
1048 // TODO: many entries are unlocked; why is this reported at level 1?
1049 debugs(12, DBG_IMPORTANT, "neighborsUdpAck: '" << storeKeyText(key) << "' has no locks");
1050 neighborCountIgnored(p);
1051 return;
1052 }
1053
1054 if (!mem->ircb_data) {
1055 debugs(12, DBG_IMPORTANT, "BUG: missing ICP callback data for " << *entry);
1056 neighborCountIgnored(p);
1057 return;
1058 }
1059
1060 debugs(15, 3, "neighborsUdpAck: " << opcode_d << " for '" << storeKeyText(key) << "' from " << (p ? p->host : "source") << " ");
1061
1062 if (p) {
1063 ntype = neighborType(p, mem->request->url);
1064 }
1065
1066 if (ignoreMulticastReply(p, mem->ircb_data)) {
1067 neighborCountIgnored(p);
1068 } else if (opcode == ICP_MISS) {
1069 if (p == NULL) {
1070 neighborIgnoreNonPeer(from, opcode);
1071 } else {
1072 mem->ping_reply_callback(p, ntype, AnyP::PROTO_ICP, header, mem->ircb_data);
1073 }
1074 } else if (opcode == ICP_HIT) {
1075 if (p == NULL) {
1076 neighborIgnoreNonPeer(from, opcode);
1077 } else {
1078 header->opcode = ICP_HIT;
1079 mem->ping_reply_callback(p, ntype, AnyP::PROTO_ICP, header, mem->ircb_data);
1080 }
1081 } else if (opcode == ICP_DECHO) {
1082 if (p == NULL) {
1083 neighborIgnoreNonPeer(from, opcode);
1084 } else if (ntype == PEER_SIBLING) {
1085 debug_trap("neighborsUdpAck: Found non-ICP cache as SIBLING\n");
1086 debug_trap("neighborsUdpAck: non-ICP neighbors must be a PARENT\n");
1087 } else {
1088 mem->ping_reply_callback(p, ntype, AnyP::PROTO_ICP, header, mem->ircb_data);
1089 }
1090 } else if (opcode == ICP_SECHO) {
1091 if (p) {
1092 debugs(15, DBG_IMPORTANT, "Ignoring SECHO from neighbor " << p->host);
1093 neighborCountIgnored(p);
1094 } else {
1095 debugs(15, DBG_IMPORTANT, "Unsolicited SECHO from " << from);
1096 }
1097 } else if (opcode == ICP_DENIED) {
1098 if (p == NULL) {
1099 neighborIgnoreNonPeer(from, opcode);
1100 } else if (p->stats.pings_acked > 100) {
1101 if (100 * p->icp.counts[ICP_DENIED] / p->stats.pings_acked > 95) {
1102 debugs(15, DBG_CRITICAL, "95%% of replies from '" << p->host << "' are UDP_DENIED");
1103 debugs(15, DBG_CRITICAL, "Disabling '" << p->host << "', please check your configuration.");
1104 neighborRemove(p);
1105 p = NULL;
1106 } else {
1107 neighborCountIgnored(p);
1108 }
1109 }
1110 } else if (opcode == ICP_MISS_NOFETCH) {
1111 mem->ping_reply_callback(p, ntype, AnyP::PROTO_ICP, header, mem->ircb_data);
1112 } else {
1113 debugs(15, DBG_CRITICAL, "neighborsUdpAck: Unexpected ICP reply: " << opcode_d);
1114 }
1115 }
1116
1117 CachePeer *
1118 peerFindByName(const char *name)
1119 {
1120 CachePeer *p = NULL;
1121
1122 for (p = Config.peers; p; p = p->next) {
1123 if (!strcasecmp(name, p->name))
1124 break;
1125 }
1126
1127 return p;
1128 }
1129
1130 CachePeer *
1131 peerFindByNameAndPort(const char *name, unsigned short port)
1132 {
1133 CachePeer *p = NULL;
1134
1135 for (p = Config.peers; p; p = p->next) {
1136 if (strcasecmp(name, p->name))
1137 continue;
1138
1139 if (port != p->http_port)
1140 continue;
1141
1142 break;
1143 }
1144
1145 return p;
1146 }
1147
1148 int
1149 neighborUp(const CachePeer * p)
1150 {
1151 if (!p->tcp_up) {
1152 peerProbeConnect(const_cast<CachePeer*>(p));
1153 return 0;
1154 }
1155
1156 /*
1157 * The CachePeer can not be UP if we don't have any IP addresses
1158 * for it.
1159 */
1160 if (0 == p->n_addresses) {
1161 debugs(15, 8, "neighborUp: DOWN (no-ip): " << p->host << " (" << p->in_addr << ")");
1162 return 0;
1163 }
1164
1165 if (p->options.no_query) {
1166 debugs(15, 8, "neighborUp: UP (no-query): " << p->host << " (" << p->in_addr << ")");
1167 return 1;
1168 }
1169
1170 if (p->stats.probe_start != 0 &&
1171 squid_curtime - p->stats.probe_start > Config.Timeout.deadPeer) {
1172 debugs(15, 8, "neighborUp: DOWN (dead): " << p->host << " (" << p->in_addr << ")");
1173 return 0;
1174 }
1175
1176 debugs(15, 8, "neighborUp: UP: " << p->host << " (" << p->in_addr << ")");
1177 return 1;
1178 }
1179
1180 void
1181 peerNoteDigestGone(CachePeer * p)
1182 {
1183 #if USE_CACHE_DIGESTS
1184 cbdataReferenceDone(p->digest);
1185 #endif
1186 }
1187
1188 /// \returns the effective connect timeout for this peer
1189 time_t
1190 peerConnectTimeout(const CachePeer *peer)
1191 {
1192 return peer->connect_timeout_raw > 0 ?
1193 peer->connect_timeout_raw : Config.Timeout.peer_connect;
1194 }
1195
1196 time_t
1197 positiveTimeout(const time_t timeout)
1198 {
1199 return max(static_cast<time_t>(1), timeout);
1200 }
1201
1202 static void
1203 peerDNSConfigure(const ipcache_addrs *ia, const Dns::LookupDetails &, void *data)
1204 {
1205 // TODO: connections to no-longer valid IP addresses should be
1206 // closed when we can detect such IP addresses.
1207
1208 CachePeer *p = (CachePeer *)data;
1209
1210 if (p->n_addresses == 0) {
1211 debugs(15, DBG_IMPORTANT, "Configuring " << neighborTypeStr(p) << " " << p->host << "/" << p->http_port << "/" << p->icp.port);
1212
1213 if (p->type == PEER_MULTICAST)
1214 debugs(15, DBG_IMPORTANT, " Multicast TTL = " << p->mcast.ttl);
1215 }
1216
1217 p->n_addresses = 0;
1218
1219 if (ia == NULL) {
1220 debugs(0, DBG_CRITICAL, "WARNING: DNS lookup for '" << p->host << "' failed!");
1221 return;
1222 }
1223
1224 if (ia->empty()) {
1225 debugs(0, DBG_CRITICAL, "WARNING: No IP address found for '" << p->host << "'!");
1226 return;
1227 }
1228
1229 for (const auto &ip: ia->goodAndBad()) { // TODO: Consider using just good().
1230 if (p->n_addresses < PEER_MAX_ADDRESSES) {
1231 const auto idx = p->n_addresses++;
1232 p->addresses[idx] = ip;
1233 debugs(15, 2, "--> IP address #" << idx << ": " << p->addresses[idx]);
1234 } else {
1235 debugs(15, 3, "ignoring remaining " << (ia->size() - p->n_addresses) << " ips");
1236 break;
1237 }
1238 }
1239
1240 p->in_addr.setEmpty();
1241 p->in_addr = p->addresses[0];
1242 p->in_addr.port(p->icp.port);
1243
1244 peerProbeConnect(p, true); // detect any died or revived peers ASAP
1245
1246 if (p->type == PEER_MULTICAST)
1247 peerCountMcastPeersSchedule(p, 10);
1248
1249 #if USE_ICMP
1250 if (p->type != PEER_MULTICAST && IamWorkerProcess())
1251 if (!p->options.no_netdb_exchange)
1252 eventAddIsh("netdbExchangeStart", netdbExchangeStart, p, 30.0, 1);
1253 #endif
1254
1255 if (p->standby.mgr.valid())
1256 PeerPoolMgr::Checkpoint(p->standby.mgr, "resolved peer");
1257 }
1258
1259 static void
1260 peerRefreshDNS(void *data)
1261 {
1262 CachePeer *p = NULL;
1263
1264 if (eventFind(peerRefreshDNS, NULL))
1265 eventDelete(peerRefreshDNS, NULL);
1266
1267 if (!data && 0 == stat5minClientRequests()) {
1268 /* no recent client traffic, wait a bit */
1269 eventAddIsh("peerRefreshDNS", peerRefreshDNS, NULL, 180.0, 1);
1270 return;
1271 }
1272
1273 for (p = Config.peers; p; p = p->next)
1274 ipcache_nbgethostbyname(p->host, peerDNSConfigure, p);
1275
1276 /* Reconfigure the peers every hour */
1277 eventAddIsh("peerRefreshDNS", peerRefreshDNS, NULL, 3600.0, 1);
1278 }
1279
1280 static void
1281 peerConnectFailedSilent(CachePeer * p)
1282 {
1283 p->stats.last_connect_failure = squid_curtime;
1284
1285 if (!p->tcp_up) {
1286 debugs(15, 2, "TCP connection to " << p->host << "/" << p->http_port <<
1287 " dead");
1288 return;
1289 }
1290
1291 -- p->tcp_up;
1292
1293 if (!p->tcp_up) {
1294 debugs(15, DBG_IMPORTANT, "Detected DEAD " << neighborTypeStr(p) << ": " << p->name);
1295 p->stats.logged_state = PEER_DEAD;
1296 }
1297 }
1298
1299 void
1300 peerConnectFailed(CachePeer *p)
1301 {
1302 debugs(15, DBG_IMPORTANT, "TCP connection to " << p->host << "/" << p->http_port << " failed");
1303 peerConnectFailedSilent(p);
1304 }
1305
1306 void
1307 peerConnectSucceded(CachePeer * p)
1308 {
1309 if (!p->tcp_up) {
1310 debugs(15, 2, "TCP connection to " << p->host << "/" << p->http_port << " succeeded");
1311 p->tcp_up = p->connect_fail_limit; // NP: so peerAlive(p) works properly.
1312 peerAlive(p);
1313 if (!p->n_addresses)
1314 ipcache_nbgethostbyname(p->host, peerDNSConfigure, p);
1315 } else
1316 p->tcp_up = p->connect_fail_limit;
1317 }
1318
1319 /// whether new TCP probes are currently banned
1320 static bool
1321 peerProbeIsBusy(const CachePeer *p)
1322 {
1323 if (p->testing_now > 0) {
1324 debugs(15, 8, "yes, probing " << p);
1325 return true;
1326 }
1327 if (squid_curtime - p->stats.last_connect_probe == 0) {
1328 debugs(15, 8, "yes, just probed " << p);
1329 return true;
1330 }
1331 return false;
1332 }
1333 /*
1334 * peerProbeConnect will be called on dead peers by neighborUp
1335 */
1336 static void
1337 peerProbeConnect(CachePeer *p, const bool reprobeIfBusy)
1338 {
1339 if (peerProbeIsBusy(p)) {
1340 p->reprobe = reprobeIfBusy;
1341 return;
1342 }
1343 p->reprobe = false;
1344
1345 const time_t ctimeout = peerConnectTimeout(p);
1346 /* for each IP address of this CachePeer. find one that we can connect to and probe it. */
1347 for (int i = 0; i < p->n_addresses; ++i) {
1348 Comm::ConnectionPointer conn = new Comm::Connection;
1349 conn->remote = p->addresses[i];
1350 conn->remote.port(p->http_port);
1351 conn->setPeer(p);
1352 getOutgoingAddress(NULL, conn);
1353
1354 ++ p->testing_now;
1355
1356 AsyncCall::Pointer call = commCbCall(15,3, "peerProbeConnectDone", CommConnectCbPtrFun(peerProbeConnectDone, p));
1357 Comm::ConnOpener *cs = new Comm::ConnOpener(conn, call, ctimeout);
1358 cs->setHost(p->host);
1359 AsyncJob::Start(cs);
1360 }
1361
1362 p->stats.last_connect_probe = squid_curtime;
1363 }
1364
1365 static void
1366 peerProbeConnectDone(const Comm::ConnectionPointer &conn, Comm::Flag status, int, void *data)
1367 {
1368 CachePeer *p = (CachePeer*)data;
1369
1370 if (status == Comm::OK) {
1371 peerConnectSucceded(p);
1372 } else {
1373 peerConnectFailedSilent(p);
1374 }
1375
1376 -- p->testing_now;
1377 conn->close();
1378 // TODO: log this traffic.
1379
1380 if (p->reprobe)
1381 peerProbeConnect(p);
1382 }
1383
1384 static void
1385 peerCountMcastPeersSchedule(CachePeer * p, time_t when)
1386 {
1387 if (p->mcast.flags.count_event_pending)
1388 return;
1389
1390 eventAdd("peerCountMcastPeersStart",
1391 peerCountMcastPeersStart,
1392 p,
1393 (double) when, 1);
1394
1395 p->mcast.flags.count_event_pending = true;
1396 }
1397
1398 static void
1399 peerCountMcastPeersStart(void *data)
1400 {
1401 // XXX: Do not create lots of complex fake objects (while abusing their
1402 // APIs) to pass around a few basic data points like start_ping and ping!
1403 CachePeer *p = (CachePeer *)data;
1404 MemObject *mem;
1405 int reqnum;
1406 // TODO: use class AnyP::Uri instead of constructing and re-parsing a string
1407 LOCAL_ARRAY(char, url, MAX_URL);
1408 assert(p->type == PEER_MULTICAST);
1409 p->mcast.flags.count_event_pending = false;
1410 snprintf(url, MAX_URL, "http://");
1411 p->in_addr.toUrl(url+7, MAX_URL -8 );
1412 strcat(url, "/");
1413 const MasterXaction::Pointer mx = new MasterXaction(XactionInitiator::initPeerMcast);
1414 HttpRequest *req = HttpRequest::FromUrl(url, mx);
1415 assert(req != nullptr);
1416 StoreEntry *fake = storeCreateEntry(url, url, RequestFlags(), Http::METHOD_GET);
1417 const auto psstate = new PeerSelector(nullptr);
1418 psstate->request = req;
1419 HTTPMSGLOCK(psstate->request);
1420 psstate->entry = fake;
1421 psstate->peerCountMcastPeerXXX = cbdataReference(p);
1422 psstate->ping.start = current_time;
1423 mem = fake->mem_obj;
1424 mem->request = psstate->request;
1425 mem->start_ping = current_time;
1426 mem->ping_reply_callback = peerCountHandleIcpReply;
1427 mem->ircb_data = psstate;
1428 mcastSetTtl(icpOutgoingConn->fd, p->mcast.ttl);
1429 p->mcast.id = mem->id;
1430 reqnum = icpSetCacheKey((const cache_key *)fake->key);
1431 icpCreateAndSend(ICP_QUERY, 0, url, reqnum, 0,
1432 icpOutgoingConn->fd, p->in_addr, psstate->al);
1433 fake->ping_status = PING_WAITING;
1434 eventAdd("peerCountMcastPeersDone",
1435 peerCountMcastPeersDone,
1436 psstate,
1437 Config.Timeout.mcast_icp_query / 1000.0, 1);
1438 p->mcast.flags.counting = true;
1439 peerCountMcastPeersSchedule(p, MCAST_COUNT_RATE);
1440 }
1441
1442 static void
1443 peerCountMcastPeersDone(void *data)
1444 {
1445 const auto psstate = static_cast<PeerSelector*>(data);
1446 StoreEntry *fake = psstate->entry;
1447
1448 if (cbdataReferenceValid(psstate->peerCountMcastPeerXXX)) {
1449 CachePeer *p = (CachePeer *)psstate->peerCountMcastPeerXXX;
1450 p->mcast.flags.counting = false;
1451 p->mcast.avg_n_members = Math::doubleAverage(p->mcast.avg_n_members, (double) psstate->ping.n_recv, ++p->mcast.n_times_counted, 10);
1452 debugs(15, DBG_IMPORTANT, "Group " << p->host << ": " << psstate->ping.n_recv <<
1453 " replies, "<< std::setw(4)<< std::setprecision(2) <<
1454 p->mcast.avg_n_members <<" average, RTT " << p->stats.rtt);
1455 p->mcast.n_replies_expected = (int) p->mcast.avg_n_members;
1456 }
1457
1458 cbdataReferenceDone(psstate->peerCountMcastPeerXXX);
1459
1460 fake->abort(); // sets ENTRY_ABORTED and initiates releated cleanup
1461 fake->mem_obj->request = nullptr;
1462 fake->unlock("peerCountMcastPeersDone");
1463 delete psstate;
1464 }
1465
1466 static void
1467 peerCountHandleIcpReply(CachePeer * p, peer_t, AnyP::ProtocolType proto, void *, void *data)
1468 {
1469 const auto psstate = static_cast<PeerSelector*>(data);
1470 StoreEntry *fake = psstate->entry;
1471 assert(fake);
1472 MemObject *mem = fake->mem_obj;
1473 assert(mem);
1474 int rtt = tvSubMsec(mem->start_ping, current_time);
1475 assert(proto == AnyP::PROTO_ICP);
1476 ++ psstate->ping.n_recv;
1477 int rtt_av_factor = RTT_AV_FACTOR;
1478
1479 if (p->options.weighted_roundrobin)
1480 rtt_av_factor = RTT_BACKGROUND_AV_FACTOR;
1481
1482 p->stats.rtt = Math::intAverage(p->stats.rtt, rtt, psstate->ping.n_recv, rtt_av_factor);
1483 }
1484
1485 static void
1486 neighborDumpPeers(StoreEntry * sentry)
1487 {
1488 dump_peers(sentry, Config.peers);
1489 }
1490
1491 static void
1492 neighborDumpNonPeers(StoreEntry * sentry)
1493 {
1494 dump_peers(sentry, non_peers);
1495 }
1496
1497 void
1498 dump_peer_options(StoreEntry * sentry, CachePeer * p)
1499 {
1500 if (p->options.proxy_only)
1501 storeAppendPrintf(sentry, " proxy-only");
1502
1503 if (p->options.no_query)
1504 storeAppendPrintf(sentry, " no-query");
1505
1506 if (p->options.background_ping)
1507 storeAppendPrintf(sentry, " background-ping");
1508
1509 if (p->options.no_digest)
1510 storeAppendPrintf(sentry, " no-digest");
1511
1512 if (p->options.default_parent)
1513 storeAppendPrintf(sentry, " default");
1514
1515 if (p->options.roundrobin)
1516 storeAppendPrintf(sentry, " round-robin");
1517
1518 if (p->options.carp)
1519 storeAppendPrintf(sentry, " carp");
1520
1521 #if USE_AUTH
1522 if (p->options.userhash)
1523 storeAppendPrintf(sentry, " userhash");
1524 #endif
1525
1526 if (p->options.sourcehash)
1527 storeAppendPrintf(sentry, " sourcehash");
1528
1529 if (p->options.weighted_roundrobin)
1530 storeAppendPrintf(sentry, " weighted-round-robin");
1531
1532 if (p->options.mcast_responder)
1533 storeAppendPrintf(sentry, " multicast-responder");
1534
1535 #if PEER_MULTICAST_SIBLINGS
1536 if (p->options.mcast_siblings)
1537 storeAppendPrintf(sentry, " multicast-siblings");
1538 #endif
1539
1540 if (p->weight != 1)
1541 storeAppendPrintf(sentry, " weight=%d", p->weight);
1542
1543 if (p->options.closest_only)
1544 storeAppendPrintf(sentry, " closest-only");
1545
1546 #if USE_HTCP
1547 if (p->options.htcp) {
1548 storeAppendPrintf(sentry, " htcp");
1549 if (p->options.htcp_oldsquid || p->options.htcp_no_clr || p->options.htcp_no_purge_clr || p->options.htcp_only_clr) {
1550 bool doneopts = false;
1551 if (p->options.htcp_oldsquid) {
1552 storeAppendPrintf(sentry, "oldsquid");
1553 doneopts = true;
1554 }
1555 if (p->options.htcp_no_clr) {
1556 storeAppendPrintf(sentry, "%sno-clr",(doneopts?",":"="));
1557 doneopts = true;
1558 }
1559 if (p->options.htcp_no_purge_clr) {
1560 storeAppendPrintf(sentry, "%sno-purge-clr",(doneopts?",":"="));
1561 doneopts = true;
1562 }
1563 if (p->options.htcp_only_clr) {
1564 storeAppendPrintf(sentry, "%sonly-clr",(doneopts?",":"="));
1565 //doneopts = true; // uncomment if more opts are added
1566 }
1567 }
1568 }
1569 #endif
1570
1571 if (p->options.no_netdb_exchange)
1572 storeAppendPrintf(sentry, " no-netdb-exchange");
1573
1574 #if USE_DELAY_POOLS
1575 if (p->options.no_delay)
1576 storeAppendPrintf(sentry, " no-delay");
1577 #endif
1578
1579 if (p->login)
1580 storeAppendPrintf(sentry, " login=%s", p->login);
1581
1582 if (p->mcast.ttl > 0)
1583 storeAppendPrintf(sentry, " ttl=%d", p->mcast.ttl);
1584
1585 if (p->connect_timeout_raw > 0)
1586 storeAppendPrintf(sentry, " connect-timeout=%d", (int)p->connect_timeout_raw);
1587
1588 if (p->connect_fail_limit != PEER_TCP_MAGIC_COUNT)
1589 storeAppendPrintf(sentry, " connect-fail-limit=%d", p->connect_fail_limit);
1590
1591 #if USE_CACHE_DIGESTS
1592
1593 if (p->digest_url)
1594 storeAppendPrintf(sentry, " digest-url=%s", p->digest_url);
1595
1596 #endif
1597
1598 if (p->options.allow_miss)
1599 storeAppendPrintf(sentry, " allow-miss");
1600
1601 if (p->options.no_tproxy)
1602 storeAppendPrintf(sentry, " no-tproxy");
1603
1604 if (p->max_conn > 0)
1605 storeAppendPrintf(sentry, " max-conn=%d", p->max_conn);
1606 if (p->standby.limit > 0)
1607 storeAppendPrintf(sentry, " standby=%d", p->standby.limit);
1608
1609 if (p->options.originserver)
1610 storeAppendPrintf(sentry, " originserver");
1611
1612 if (p->domain)
1613 storeAppendPrintf(sentry, " forceddomain=%s", p->domain);
1614
1615 if (p->connection_auth == 0)
1616 storeAppendPrintf(sentry, " connection-auth=off");
1617 else if (p->connection_auth == 1)
1618 storeAppendPrintf(sentry, " connection-auth=on");
1619 else if (p->connection_auth == 2)
1620 storeAppendPrintf(sentry, " connection-auth=auto");
1621
1622 p->secure.dumpCfg(sentry,"tls-");
1623 storeAppendPrintf(sentry, "\n");
1624 }
1625
1626 static void
1627 dump_peers(StoreEntry * sentry, CachePeer * peers)
1628 {
1629 char ntoabuf[MAX_IPSTRLEN];
1630 int i;
1631
1632 if (peers == NULL)
1633 storeAppendPrintf(sentry, "There are no neighbors installed.\n");
1634
1635 for (CachePeer *e = peers; e; e = e->next) {
1636 assert(e->host != NULL);
1637 storeAppendPrintf(sentry, "\n%-11.11s: %s\n",
1638 neighborTypeStr(e),
1639 e->name);
1640 storeAppendPrintf(sentry, "Host : %s/%d/%d\n",
1641 e->host,
1642 e->http_port,
1643 e->icp.port);
1644 storeAppendPrintf(sentry, "Flags :");
1645 dump_peer_options(sentry, e);
1646
1647 for (i = 0; i < e->n_addresses; ++i) {
1648 storeAppendPrintf(sentry, "Address[%d] : %s\n", i,
1649 e->addresses[i].toStr(ntoabuf,MAX_IPSTRLEN) );
1650 }
1651
1652 storeAppendPrintf(sentry, "Status : %s\n",
1653 neighborUp(e) ? "Up" : "Down");
1654 storeAppendPrintf(sentry, "FETCHES : %d\n", e->stats.fetches);
1655 storeAppendPrintf(sentry, "OPEN CONNS : %d\n", e->stats.conn_open);
1656 storeAppendPrintf(sentry, "AVG RTT : %d msec\n", e->stats.rtt);
1657
1658 if (!e->options.no_query) {
1659 storeAppendPrintf(sentry, "LAST QUERY : %8d seconds ago\n",
1660 (int) (squid_curtime - e->stats.last_query));
1661
1662 if (e->stats.last_reply > 0)
1663 storeAppendPrintf(sentry, "LAST REPLY : %8d seconds ago\n",
1664 (int) (squid_curtime - e->stats.last_reply));
1665 else
1666 storeAppendPrintf(sentry, "LAST REPLY : none received\n");
1667
1668 storeAppendPrintf(sentry, "PINGS SENT : %8d\n", e->stats.pings_sent);
1669
1670 storeAppendPrintf(sentry, "PINGS ACKED: %8d %3d%%\n",
1671 e->stats.pings_acked,
1672 Math::intPercent(e->stats.pings_acked, e->stats.pings_sent));
1673 }
1674
1675 storeAppendPrintf(sentry, "IGNORED : %8d %3d%%\n", e->stats.ignored_replies, Math::intPercent(e->stats.ignored_replies, e->stats.pings_acked));
1676
1677 if (!e->options.no_query) {
1678 storeAppendPrintf(sentry, "Histogram of PINGS ACKED:\n");
1679 #if USE_HTCP
1680
1681 if (e->options.htcp) {
1682 storeAppendPrintf(sentry, "\tMisses\t%8d %3d%%\n",
1683 e->htcp.counts[0],
1684 Math::intPercent(e->htcp.counts[0], e->stats.pings_acked));
1685 storeAppendPrintf(sentry, "\tHits\t%8d %3d%%\n",
1686 e->htcp.counts[1],
1687 Math::intPercent(e->htcp.counts[1], e->stats.pings_acked));
1688 } else {
1689 #endif
1690
1691 for (auto op : WholeEnum<icp_opcode>()) {
1692 if (e->icp.counts[op] == 0)
1693 continue;
1694
1695 storeAppendPrintf(sentry, " %12.12s : %8d %3d%%\n",
1696 icp_opcode_str[op],
1697 e->icp.counts[op],
1698 Math::intPercent(e->icp.counts[op], e->stats.pings_acked));
1699 }
1700
1701 #if USE_HTCP
1702
1703 }
1704
1705 #endif
1706
1707 }
1708
1709 if (e->stats.last_connect_failure) {
1710 storeAppendPrintf(sentry, "Last failed connect() at: %s\n",
1711 Time::FormatHttpd(e->stats.last_connect_failure));
1712 }
1713
1714 storeAppendPrintf(sentry, "keep-alive ratio: %d%%\n", Math::intPercent(e->stats.n_keepalives_recv, e->stats.n_keepalives_sent));
1715 }
1716 }
1717
1718 #if USE_HTCP
1719 void
1720 neighborsHtcpReply(const cache_key * key, HtcpReplyData * htcp, const Ip::Address &from)
1721 {
1722 StoreEntry *e = Store::Root().findCallbackXXX(key);
1723 MemObject *mem = NULL;
1724 CachePeer *p;
1725 peer_t ntype = PEER_NONE;
1726 debugs(15, 6, "neighborsHtcpReply: " <<
1727 (htcp->hit ? "HIT" : "MISS") << " " <<
1728 storeKeyText(key) );
1729
1730 if (NULL != e)
1731 mem = e->mem_obj;
1732
1733 if ((p = whichPeer(from)))
1734 neighborAliveHtcp(p, mem, htcp);
1735
1736 /* Does the entry exist? */
1737 if (NULL == e) {
1738 debugs(12, 3, "neighyborsHtcpReply: Cache key '" << storeKeyText(key) << "' not found");
1739 neighborCountIgnored(p);
1740 return;
1741 }
1742
1743 /* check if someone is already fetching it */
1744 if (EBIT_TEST(e->flags, ENTRY_DISPATCHED)) {
1745 debugs(15, 3, "neighborsUdpAck: '" << storeKeyText(key) << "' already being fetched.");
1746 neighborCountIgnored(p);
1747 return;
1748 }
1749
1750 if (mem == NULL) {
1751 debugs(15, 2, "Ignoring reply for missing mem_obj: " << storeKeyText(key));
1752 neighborCountIgnored(p);
1753 return;
1754 }
1755
1756 if (e->ping_status != PING_WAITING) {
1757 debugs(15, 2, "neighborsUdpAck: Entry " << storeKeyText(key) << " is not PING_WAITING");
1758 neighborCountIgnored(p);
1759 return;
1760 }
1761
1762 if (!e->locked()) {
1763 // TODO: many entries are unlocked; why is this reported at level 1?
1764 debugs(12, DBG_IMPORTANT, "neighborsUdpAck: '" << storeKeyText(key) << "' has no locks");
1765 neighborCountIgnored(p);
1766 return;
1767 }
1768
1769 if (!mem->ircb_data) {
1770 debugs(12, DBG_IMPORTANT, "BUG: missing HTCP callback data for " << *e);
1771 neighborCountIgnored(p);
1772 return;
1773 }
1774
1775 if (p) {
1776 ntype = neighborType(p, mem->request->url);
1777 neighborUpdateRtt(p, mem);
1778 }
1779
1780 if (ignoreMulticastReply(p, mem->ircb_data)) {
1781 neighborCountIgnored(p);
1782 return;
1783 }
1784
1785 debugs(15, 3, "neighborsHtcpReply: e = " << e);
1786 mem->ping_reply_callback(p, ntype, AnyP::PROTO_HTCP, htcp, mem->ircb_data);
1787 }
1788
1789 /*
1790 * Send HTCP CLR messages to all peers configured to receive them.
1791 */
1792 void
1793 neighborsHtcpClear(StoreEntry * e, const char *uri, HttpRequest * req, const HttpRequestMethod &method, htcp_clr_reason reason)
1794 {
1795 CachePeer *p;
1796 char buf[128];
1797
1798 for (p = Config.peers; p; p = p->next) {
1799 if (!p->options.htcp) {
1800 continue;
1801 }
1802 if (p->options.htcp_no_clr) {
1803 continue;
1804 }
1805 if (p->options.htcp_no_purge_clr && reason == HTCP_CLR_PURGE) {
1806 continue;
1807 }
1808 debugs(15, 3, "neighborsHtcpClear: sending CLR to " << p->in_addr.toUrl(buf, 128));
1809 htcpClear(e, uri, req, method, p, reason);
1810 }
1811 }
1812
1813 #endif
1814