pconn.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2023 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 48 Persistent Connections */
10 
11 #include "squid.h"
12 #include "base/IoManip.h"
13 #include "base/PackableStream.h"
14 #include "CachePeer.h"
15 #include "comm.h"
16 #include "comm/Connection.h"
17 #include "comm/Read.h"
18 #include "fd.h"
19 #include "fde.h"
20 #include "globals.h"
21 #include "mgr/Registration.h"
22 #include "neighbors.h"
23 #include "pconn.h"
24 #include "PeerPoolMgr.h"
25 #include "SquidConfig.h"
26 #include "Store.h"
27 
28 #define PCONN_FDS_SZ 8 /* pconn set size, increase for better memcache hit rate */
29 
30 //TODO: re-attach to MemPools. WAS: static Mem::Allocator *pconn_fds_pool = nullptr;
33 
34 /* ========== IdleConnList ============================================ */
35 
36 IdleConnList::IdleConnList(const char *aKey, PconnPool *thePool) :
37  capacity_(PCONN_FDS_SZ),
38  size_(0),
39  parent_(thePool)
40 {
41  //Initialize hash_link members
42  key = xstrdup(aKey);
43  next = nullptr;
44 
46 
48 
49 // TODO: re-attach to MemPools. WAS: theList = (?? *)pconn_fds_pool->alloc();
50 }
51 
53 {
54  if (parent_)
55  parent_->unlinkList(this);
56 
57  if (size_) {
58  parent_ = nullptr; // prevent reentrant notifications and deletions
59  closeN(size_);
60  }
61 
62  delete[] theList_;
63 
64  xfree(key);
65 }
66 
73 int
75 {
76  for (int index = size_ - 1; index >= 0; --index) {
77  if (conn->fd == theList_[index]->fd) {
78  debugs(48, 3, "found " << conn << " at index " << index);
79  return index;
80  }
81  }
82 
83  debugs(48, 2, conn << " NOT FOUND!");
84  return -1;
85 }
86 
91 bool
93 {
94  if (index < 0 || index >= size_)
95  return false;
96 
97  // shuffle the remaining entries to fill the new gap.
98  for (; index < size_ - 1; ++index)
99  theList_[index] = theList_[index + 1];
100  theList_[--size_] = nullptr;
101 
102  if (parent_) {
104  if (size_ == 0) {
105  debugs(48, 3, "deleting " << hashKeyStr(this));
106  delete this;
107  }
108  }
109 
110  return true;
111 }
112 
113 // almost a duplicate of removeFD. But drops multiple entries.
114 void
116 {
117  if (n < 1) {
118  debugs(48, 2, "Nothing to do.");
119  return;
120  } else if (n >= (size_t)size_) {
121  debugs(48, 2, "Closing all entries.");
122  while (size_ > 0) {
123  const Comm::ConnectionPointer conn = theList_[--size_];
124  theList_[size_] = nullptr;
125  clearHandlers(conn);
126  conn->close();
127  if (parent_)
129  }
130  } else { //if (n < size_)
131  debugs(48, 2, "Closing " << n << " of " << size_ << " entries.");
132 
133  size_t index;
134  // ensure the first N entries are closed
135  for (index = 0; index < n; ++index) {
136  const Comm::ConnectionPointer conn = theList_[index];
137  theList_[index] = nullptr;
138  clearHandlers(conn);
139  conn->close();
140  if (parent_)
142  }
143  // shuffle the list N down.
144  for (index = 0; index < (size_t)size_ - n; ++index) {
145  theList_[index] = theList_[index + n];
146  }
147  // ensure the last N entries are unset
148  while (index < ((size_t)size_)) {
149  theList_[index] = nullptr;
150  ++index;
151  }
152  size_ -= n;
153  }
154 
155  if (parent_ && size_ == 0) {
156  debugs(48, 3, "deleting " << hashKeyStr(this));
157  delete this;
158  }
159 }
160 
161 void
163 {
164  debugs(48, 3, "removing close handler for " << conn);
165  comm_read_cancel(conn->fd, IdleConnList::Read, this);
166  commUnsetConnTimeout(conn);
167 }
168 
169 void
171 {
172  if (size_ == capacity_) {
173  debugs(48, 3, "growing idle Connection array");
174  capacity_ <<= 1;
175  const Comm::ConnectionPointer *oldList = theList_;
177  for (int index = 0; index < size_; ++index)
178  theList_[index] = oldList[index];
179 
180  delete[] oldList;
181  }
182 
183  if (parent_)
185 
186  theList_[size_] = conn;
187  ++size_;
188  AsyncCall::Pointer readCall = commCbCall(5,4, "IdleConnList::Read",
190  comm_read(conn, fakeReadBuf_, sizeof(fakeReadBuf_), readCall);
191  AsyncCall::Pointer timeoutCall = commCbCall(5,4, "IdleConnList::Timeout",
193  commSetConnTimeout(conn, conn->timeLeft(Config.Timeout.serverIdlePconn), timeoutCall);
194 }
195 
198 bool
200 {
201  const Comm::ConnectionPointer &conn = theList_[i];
202 
203  // connection already closed. useless.
204  if (!Comm::IsConnOpen(conn))
205  return false;
206 
207  // our connection early-read/close handler is scheduled to run already. unsafe
208  if (!COMMIO_FD_READCB(conn->fd)->active())
209  return false;
210 
211  return true;
212 }
213 
216 {
217  for (int i=size_-1; i>=0; --i) {
218 
219  if (!isAvailable(i))
220  continue;
221 
222  // our connection timeout handler is scheduled to run already. unsafe for now.
223  // TODO: cancel the pending timeout callback and allow re-use of the conn.
224  if (fd_table[theList_[i]->fd].timeoutHandler == nullptr)
225  continue;
226 
227  // finally, a match. pop and return it.
228  Comm::ConnectionPointer result = theList_[i];
229  clearHandlers(result);
230  /* may delete this */
231  removeAt(i);
232  return result;
233  }
234 
235  return Comm::ConnectionPointer();
236 }
237 
238 /*
239  * XXX this routine isn't terribly efficient - if there's a pending
240  * read event (which signifies the fd will close in the next IO loop!)
241  * we ignore the FD and move onto the next one. This means, as an example,
242  * if we have a lot of FDs open to a very popular server and we get a bunch
243  * of requests JUST as they timeout (say, it shuts down) we'll be wasting
244  * quite a bit of CPU. Just keep it in mind.
245  */
248 {
249  assert(size_);
250 
251  // small optimization: do the constant bool tests only once.
252  const bool keyCheckAddr = !aKey->local.isAnyAddr();
253  const bool keyCheckPort = aKey->local.port() > 0;
254 
255  for (int i=size_-1; i>=0; --i) {
256 
257  if (!isAvailable(i))
258  continue;
259 
260  // local end port is required, but do not match.
261  if (keyCheckPort && aKey->local.port() != theList_[i]->local.port())
262  continue;
263 
264  // local address is required, but does not match.
265  if (keyCheckAddr && aKey->local.matchIPAddr(theList_[i]->local) != 0)
266  continue;
267 
268  // our connection timeout handler is scheduled to run already. unsafe for now.
269  // TODO: cancel the pending timeout callback and allow re-use of the conn.
270  if (fd_table[theList_[i]->fd].timeoutHandler == nullptr)
271  continue;
272 
273  // finally, a match. pop and return it.
274  Comm::ConnectionPointer result = theList_[i];
275  clearHandlers(result);
276  /* may delete this */
277  removeAt(i);
278  return result;
279  }
280 
281  return Comm::ConnectionPointer();
282 }
283 
284 /* might delete list */
285 void
287 {
288  const int index = findIndexOf(conn);
289  if (index >= 0) {
290  if (parent_)
291  parent_->notifyManager("idle conn closure");
292  clearHandlers(conn);
293  /* might delete this */
294  removeAt(index);
295  conn->close();
296  }
297 }
298 
299 void
300 IdleConnList::Read(const Comm::ConnectionPointer &conn, char *, size_t len, Comm::Flag flag, int, void *data)
301 {
302  debugs(48, 3, len << " bytes from " << conn);
303 
304  if (flag == Comm::ERR_CLOSING) {
305  debugs(48, 3, "Comm::ERR_CLOSING from " << conn);
306  /* Bail out on Comm::ERR_CLOSING - may happen when shutdown aborts our idle FD */
307  return;
308  }
309 
310  IdleConnList *list = (IdleConnList *) data;
311  /* may delete list/data */
312  list->findAndClose(conn);
313 }
314 
315 void
317 {
318  debugs(48, 3, io.conn);
319  IdleConnList *list = static_cast<IdleConnList *>(io.data);
320  /* may delete list/data */
321  list->findAndClose(io.conn);
322 }
323 
324 void
326 {
327  closeN(size_);
328 }
329 
330 /* ========== PconnPool PRIVATE FUNCTIONS ============================================ */
331 
332 const char *
333 PconnPool::key(const Comm::ConnectionPointer &destLink, const char *domain)
334 {
335  LOCAL_ARRAY(char, buf, SQUIDHOSTNAMELEN * 3 + 10);
336 
337  destLink->remote.toUrl(buf, SQUIDHOSTNAMELEN * 3 + 10);
338 
339  // when connecting through a cache_peer, ignore the final destination
340  if (destLink->getPeer())
341  domain = nullptr;
342 
343  if (domain) {
344  const int used = strlen(buf);
345  snprintf(buf+used, SQUIDHOSTNAMELEN * 3 + 10-used, "/%s", domain);
346  }
347 
348  debugs(48,6,"PconnPool::key(" << destLink << ", " << (domain?domain:"[no domain]") << ") is {" << buf << "}" );
349  return buf;
350 }
351 
352 void
353 PconnPool::dumpHist(std::ostream &yaml) const
354 {
355  AtMostOnce heading(
356  " connection use histogram:\n"
357  " # requests per connection: closed connections that carried that many requests\n");
358 
359  for (int i = 0; i < PCONN_HIST_SZ; ++i) {
360  if (hist[i] == 0)
361  continue;
362 
363  yaml << heading <<
364  " " << i << ": " << hist[i] << "\n";
365  }
366 }
367 
368 void
369 PconnPool::dumpHash(std::ostream &yaml) const
370 {
371  const auto hid = table;
372  hash_first(hid);
373  AtMostOnce title(" open connections list:\n");
374  for (auto *walker = hash_next(hid); walker; walker = hash_next(hid)) {
375  yaml << title <<
376  " \"" << static_cast<char *>(walker->key) << "\": " <<
377  static_cast<IdleConnList *>(walker)->count() <<
378  "\n";
379  }
380 }
381 
382 void
383 PconnPool::dump(std::ostream &yaml) const
384 {
385  yaml << "pool " << descr << ":\n";
386  dumpHist(yaml);
387  dumpHash(yaml);
388 }
389 
390 /* ========== PconnPool PUBLIC FUNCTIONS ============================================ */
391 
392 PconnPool::PconnPool(const char *aDescr, const CbcPointer<PeerPoolMgr> &aMgr):
393  table(nullptr), descr(aDescr),
394  mgr(aMgr),
395  theCount(0)
396 {
397  int i;
398  table = hash_create((HASHCMP *) strcmp, 229, hash_string);
399 
400  for (i = 0; i < PCONN_HIST_SZ; ++i)
401  hist[i] = 0;
402 
403  PconnModule::GetInstance()->add(this);
404 }
405 
406 static void
407 DeleteIdleConnList(void *hashItem)
408 {
409  delete static_cast<IdleConnList*>(hashItem);
410 }
411 
413 {
417  descr = nullptr;
418 }
419 
420 void
421 PconnPool::push(const Comm::ConnectionPointer &conn, const char *domain)
422 {
423  if (fdUsageHigh()) {
424  debugs(48, 3, "Not many unused FDs");
425  conn->close();
426  return;
427  } else if (shutting_down) {
428  conn->close();
429  debugs(48, 3, "Squid is shutting down. Refusing to do anything");
430  return;
431  }
432  // TODO: also close used pconns if we exceed peer max-conn limit
433 
434  const char *aKey = key(conn, domain);
435  IdleConnList *list = (IdleConnList *) hash_lookup(table, aKey);
436 
437  if (list == nullptr) {
438  list = new IdleConnList(aKey, this);
439  debugs(48, 3, "new IdleConnList for {" << hashKeyStr(list) << "}" );
440  hash_join(table, list);
441  } else {
442  debugs(48, 3, "found IdleConnList for {" << hashKeyStr(list) << "}" );
443  }
444 
445  list->push(conn);
447 
448  LOCAL_ARRAY(char, desc, FD_DESC_SZ);
449  snprintf(desc, FD_DESC_SZ, "Idle server: %s", aKey);
450  fd_note(conn->fd, desc);
451  debugs(48, 3, "pushed " << conn << " for " << aKey);
452 
453  // successful push notifications resume multi-connection opening sequence
454  notifyManager("push");
455 }
456 
458 PconnPool::pop(const Comm::ConnectionPointer &dest, const char *domain, bool keepOpen)
459 {
460  // always call shared pool first because we need to close an idle
461  // connection there if we have to use a standby connection.
462  if (const auto direct = popStored(dest, domain, keepOpen))
463  return direct;
464 
465  // either there was no pconn to pop or this is not a retriable xaction
466  if (const auto peer = dest->getPeer()) {
467  if (peer->standby.pool)
468  return peer->standby.pool->popStored(dest, domain, true);
469  }
470 
471  return nullptr;
472 }
473 
477 PconnPool::popStored(const Comm::ConnectionPointer &dest, const char *domain, const bool keepOpen)
478 {
479  const char * aKey = key(dest, domain);
480 
481  IdleConnList *list = (IdleConnList *)hash_lookup(table, aKey);
482  if (list == nullptr) {
483  debugs(48, 3, "lookup for key {" << aKey << "} failed.");
484  // failure notifications resume standby conn creation after fdUsageHigh
485  notifyManager("pop lookup failure");
486  return Comm::ConnectionPointer();
487  } else {
488  debugs(48, 3, "found " << hashKeyStr(list) <<
489  (keepOpen ? " to use" : " to kill"));
490  }
491 
492  if (const auto popped = list->findUseable(dest)) { // may delete list
493  // successful pop notifications replenish standby connections pool
494  notifyManager("pop");
495 
496  if (keepOpen)
497  return popped;
498 
499  popped->close();
500  return Comm::ConnectionPointer();
501  }
502 
503  // failure notifications resume standby conn creation after fdUsageHigh
504  notifyManager("pop usability failure");
505  return Comm::ConnectionPointer();
506 }
507 
508 void
509 PconnPool::notifyManager(const char *reason)
510 {
511  if (mgr.valid())
512  PeerPoolMgr::Checkpoint(mgr, reason);
513 }
514 
515 void
517 {
518  hash_table *hid = table;
519  hash_first(hid);
520 
521  // close N connections, one per list, to treat all lists "fairly"
522  for (int i = 0; i < n && count(); ++i) {
523 
524  hash_link *current = hash_next(hid);
525  if (!current) {
526  hash_first(hid);
527  current = hash_next(hid);
528  Must(current); // must have one because the count() was positive
529  }
530 
531  // may delete current
532  static_cast<IdleConnList*>(current)->closeN(1);
533  }
534 }
535 
536 void
538 {
539  theCount -= list->count();
540  assert(theCount >= 0);
541  hash_remove_link(table, list);
542 }
543 
544 void
546 {
547  if (uses >= PCONN_HIST_SZ)
548  uses = PCONN_HIST_SZ - 1;
549 
550  ++hist[uses];
551 }
552 
553 /* ========== PconnModule ============================================ */
554 
555 /*
556  * This simple class exists only for the cache manager
557  */
558 
560 {
562 }
563 
564 PconnModule *
566 {
567  if (instance == nullptr)
568  instance = new PconnModule;
569 
570  return instance;
571 }
572 
573 void
575 {
576  Mgr::RegisterAction("pconn",
577  "Persistent Connection Utilization Histograms",
580 }
581 
582 void
584 {
585  pools.insert(aPool);
586 }
587 
588 void
590 {
591  pools.erase(aPool);
592 }
593 
594 void
595 PconnModule::dump(std::ostream &yaml)
596 {
597  for (const auto &p: pools)
598  p->dump(yaml);
599 }
600 
601 void
603 {
604  PackableStream yaml(*e);
606 }
607 
#define FD_DESC_SZ
Definition: defines.h:32
void closeN(int n)
closes any n connections, regardless of their destination
Definition: pconn.cc:516
void commUnsetConnTimeout(const Comm::ConnectionPointer &conn)
Definition: comm.cc:616
time_t serverIdlePconn
Definition: SquidConfig.h:120
#define LOCAL_ARRAY(type, name, size)
Definition: squid.h:62
~PconnPool()
Definition: pconn.cc:412
void fd_note(int fd, const char *s)
Definition: fd.cc:216
int findIndexOf(const Comm::ConnectionPointer &conn) const
Definition: pconn.cc:74
void closeN(size_t count)
Definition: pconn.cc:115
int fdUsageHigh(void)
Definition: fd.cc:273
static IOCB Read
Definition: pconn.h:72
Comm::ConnectionPointer pop(const Comm::ConnectionPointer &dest, const char *domain, bool keepOpen)
Definition: pconn.cc:458
bool isAnyAddr() const
Definition: Address.cc:190
#define COMMIO_FD_READCB(fd)
Definition: IoCallback.h:78
void dumpHash(std::ostream &) const
Definition: pconn.cc:369
HASHHASH hash_string
Definition: hash.h:45
void hash_remove_link(hash_table *, hash_link *)
Definition: hash.cc:220
void noteConnectionAdded()
Definition: pconn.h:143
#define xstrdup
static PconnModule * GetInstance()
Definition: pconn.cc:565
void noteUses(int uses)
Definition: pconn.cc:545
Comm::ConnectionPointer popStored(const Comm::ConnectionPointer &dest, const char *domain, const bool keepOpen)
Definition: pconn.cc:477
bool IsConnOpen(const Comm::ConnectionPointer &conn)
Definition: Connection.cc:27
hash_link * hash_lookup(hash_table *, const void *)
Definition: hash.cc:146
int HASHCMP(const void *, const void *)
Definition: hash.h:13
char * toUrl(char *buf, unsigned int len) const
Definition: Address.cc:894
int matchIPAddr(const Address &rhs) const
Definition: Address.cc:723
@ ERR_CLOSING
Definition: Flag.h:24
void hashFreeMemory(hash_table *)
Definition: hash.cc:268
bool comm_has_incomplete_write(int fd)
Definition: comm.cc:152
~IdleConnList() override
Definition: pconn.cc:52
void hashFreeItems(hash_table *, HASHFREE *)
Definition: hash.cc:252
int const char size_t
Definition: stub_liblog.cc:83
const char * hashKeyStr(const hash_link *)
Definition: hash.cc:313
void findAndClose(const Comm::ConnectionPointer &conn)
Definition: pconn.cc:286
static void DumpWrapper(StoreEntry *e)
Definition: pconn.cc:602
Comm::ConnectionPointer findUseable(const Comm::ConnectionPointer &key)
Definition: pconn.cc:247
void push(const Comm::ConnectionPointer &conn)
Pass control of the connection to the idle list.
Definition: pconn.cc:170
Pools pools
all live pools
Definition: pconn.h:191
Comm::ConnectionPointer pop()
get first conn which is not pending read fd.
Definition: pconn.cc:215
void comm_read(const Comm::ConnectionPointer &conn, char *buf, int len, AsyncCall::Pointer &callback)
Definition: Read.h:59
static void DeleteIdleConnList(void *hashItem)
Definition: pconn.cc:407
const char * descr
Definition: pconn.h:159
void notifyManager(const char *reason)
Definition: pconn.cc:509
void add(PconnPool *)
Definition: pconn.cc:583
time_t timeLeft(const time_t idleTimeout) const
Definition: Connection.cc:143
CbcPointer< PeerPoolMgr > mgr
optional pool manager (for notifications)
Definition: pconn.h:160
IdleConnList(const char *key, PconnPool *parent)
Definition: pconn.cc:36
void dump(std::ostream &yaml)
Definition: pconn.cc:595
void dumpHist(std::ostream &) const
Definition: pconn.cc:353
unsigned short port() const
Definition: Address.cc:798
Ip::Address local
Definition: Connection.h:146
CachePeer * getPeer() const
Definition: Connection.cc:121
void noteConnectionRemoved()
Definition: pconn.h:144
void push(const Comm::ConnectionPointer &serverConn, const char *domain)
Definition: pconn.cc:421
int count() const
Definition: pconn.h:62
Comm::ConnectionPointer conn
Definition: CommCalls.h:80
Ip::Address remote
Definition: Connection.h:149
CommCbFunPtrCallT< Dialer > * commCbCall(int debugSection, int debugLevel, const char *callName, const Dialer &dialer)
Definition: CommCalls.h:312
#define assert(EX)
Definition: assert.h:17
void registerWithCacheManager(void)
Definition: pconn.cc:574
int count() const
Definition: pconn.h:142
#define CBDATA_CLASS_INIT(type)
Definition: cbdata.h:325
void endingShutdown() override
Definition: pconn.cc:325
void hash_first(hash_table *)
Definition: hash.cc:172
PconnPool * parent_
Definition: pconn.h:93
#define xfree
void unlinkList(IdleConnList *list)
Definition: pconn.cc:537
void clearHandlers(const Comm::ConnectionPointer &conn)
Definition: pconn.cc:162
Flag
Definition: Flag.h:15
bool isAvailable(int i) const
Definition: pconn.cc:199
RefCount< Comm::Connection > ConnectionPointer
Definition: forward.h:26
#define fd_table
Definition: fde.h:189
void remove(PconnPool *)
unregister and forget about this pool object
Definition: pconn.cc:589
PconnPool(const char *aDescription, const CbcPointer< PeerPoolMgr > &aMgr)
Definition: pconn.cc:392
int theCount
the number of pooled connections
Definition: pconn.h:161
int size_
Definition: pconn.h:86
int hist[PCONN_HIST_SZ]
Definition: pconn.h:157
void commSetConnTimeout(const Comm::ConnectionPointer &conn, time_t timeout, AsyncCall::Pointer &callback)
Definition: comm.cc:592
Comm::ConnectionPointer * theList_
Definition: pconn.h:81
static CTCB Timeout
Definition: pconn.h:73
struct SquidConfig::@84 Timeout
hash_table * hash_create(HASHCMP *, int, HASHHASH *)
Definition: hash.cc:108
void RegisterAction(char const *action, char const *desc, OBJH *handler, Protected, Atomic, Format)
Definition: Registration.cc:54
#define PCONN_HIST_SZ
Definition: pconn.h:33
#define Must(condition)
Definition: TextException.h:75
PconnModule()
Definition: pconn.cc:559
int shutting_down
void comm_read_cancel(int fd, IOCB *callback, void *data)
Definition: Read.cc:181
hash_table * table
Definition: pconn.h:158
static PconnModule * instance
Definition: pconn.h:193
int capacity_
Number of entries theList can currently hold without re-allocating (capacity).
Definition: pconn.h:84
static const char * key(const Comm::ConnectionPointer &destLink, const char *domain)
Definition: pconn.cc:333
#define PCONN_FDS_SZ
Definition: pconn.cc:28
static void Checkpoint(const Pointer &mgr, const char *reason)
Definition: PeerPoolMgr.cc:232
bool removeAt(int index)
Definition: pconn.cc:92
hash_link * hash_next(hash_table *)
Definition: hash.cc:188
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:192
void dump(std::ostream &) const
Definition: pconn.cc:383
void hash_join(hash_table *, hash_link *)
Definition: hash.cc:131
#define SQUIDHOSTNAMELEN
Definition: rfc2181.h:30
char fakeReadBuf_[4096]
Definition: pconn.h:95
class SquidConfig Config
Definition: SquidConfig.cc:12

 

Introduction

Documentation

Support

Miscellaneous