]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/pconn.cc
4 * DEBUG: section 48 Persistent Connections
5 * AUTHOR: Duane Wessels
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
37 #include "comm/Connection.h"
40 #include "mgr/Registration.h"
45 #define PCONN_FDS_SZ 8 /* pconn set size, increase for better memcache hit rate */
47 //TODO: re-attach to MemPools. WAS: static MemAllocator *pconn_fds_pool = NULL;
48 PconnModule
* PconnModule::instance
= NULL
;
49 CBDATA_CLASS_INIT(IdleConnList
);
51 /* ========== IdleConnList ============================================ */
53 IdleConnList::IdleConnList(const char *key
, PconnPool
*thePool
) :
54 capacity_(PCONN_FDS_SZ
),
58 hash
.key
= xstrdup(key
);
59 theList_
= new Comm::ConnectionPointer
[capacity_
];
60 // TODO: re-attach to MemPools. WAS: theList = (?? *)pconn_fds_pool->alloc();
63 IdleConnList::~IdleConnList()
66 parent_
->unlinkList(this);
73 /** Search the list. Matches by FD socket number.
74 * Performed from the end of list where newest entries are.
76 * \retval <0 The connection is not listed
77 * \retval >=0 The connection array index
80 IdleConnList::findIndexOf(const Comm::ConnectionPointer
&conn
) const
82 for (int index
= size_
- 1; index
>= 0; --index
) {
83 if (conn
->fd
== theList_
[index
]->fd
) {
84 debugs(48, 3, HERE
<< "found " << conn
<< " at index " << index
);
89 debugs(48, 2, HERE
<< conn
<< " NOT FOUND!");
93 /** Remove the entry at specified index.
94 * May perform a shuffle of list entries to fill the gap.
95 * \retval false The index is not an in-use entry.
98 IdleConnList::removeAt(int index
)
100 if (index
< 0 || index
>= size_
)
103 // shuffle the remaining entries to fill the new gap.
104 for (; index
< size_
- 1; ++index
)
105 theList_
[index
] = theList_
[index
+ 1];
106 theList_
[--size_
] = NULL
;
109 parent_
->noteConnectionRemoved();
111 debugs(48, 3, HERE
<< "deleting " << hashKeyStr(&hash
));
119 // almost a duplicate of removeFD. But drops multiple entries.
121 IdleConnList::closeN(size_t n
)
124 debugs(48, 2, HERE
<< "Nothing to do.");
126 } else if (n
>= (size_t)size_
) {
127 debugs(48, 2, HERE
<< "Closing all entries.");
129 const Comm::ConnectionPointer conn
= theList_
[--size_
];
130 theList_
[size_
] = NULL
;
134 parent_
->noteConnectionRemoved();
136 } else { //if (n < size_)
137 debugs(48, 2, HERE
<< "Closing " << n
<< " of " << size_
<< " entries.");
140 // ensure the first N entries are closed
141 for (index
= 0; index
< n
; ++index
) {
142 const Comm::ConnectionPointer conn
= theList_
[index
];
143 theList_
[index
] = NULL
;
147 parent_
->noteConnectionRemoved();
149 // shuffle the list N down.
150 for (index
= 0; index
< (size_t)size_
- n
; ++index
) {
151 theList_
[index
] = theList_
[index
+ n
];
153 // ensure the last N entries are unset
154 while (index
< ((size_t)size_
)) {
155 theList_
[index
] = NULL
;
161 if (parent_
&& size_
== 0) {
162 debugs(48, 3, HERE
<< "deleting " << hashKeyStr(&hash
));
168 IdleConnList::clearHandlers(const Comm::ConnectionPointer
&conn
)
170 debugs(48, 3, HERE
<< "removing close handler for " << conn
);
171 comm_read_cancel(conn
->fd
, IdleConnList::Read
, this);
172 commUnsetConnTimeout(conn
);
176 IdleConnList::push(const Comm::ConnectionPointer
&conn
)
178 if (size_
== capacity_
) {
179 debugs(48, 3, HERE
<< "growing idle Connection array");
181 const Comm::ConnectionPointer
*oldList
= theList_
;
182 theList_
= new Comm::ConnectionPointer
[capacity_
];
183 for (int index
= 0; index
< size_
; ++index
)
184 theList_
[index
] = oldList
[index
];
190 parent_
->noteConnectionAdded();
192 theList_
[size_
] = conn
;
194 AsyncCall::Pointer readCall
= commCbCall(5,4, "IdleConnList::Read",
195 CommIoCbPtrFun(IdleConnList::Read
, this));
196 comm_read(conn
, fakeReadBuf_
, sizeof(fakeReadBuf_
), readCall
);
197 AsyncCall::Pointer timeoutCall
= commCbCall(5,4, "IdleConnList::Timeout",
198 CommTimeoutCbPtrFun(IdleConnList::Timeout
, this));
199 commSetConnTimeout(conn
, Config
.Timeout
.serverIdlePconn
, timeoutCall
);
202 /// Determine whether an entry in the idle list is available for use.
203 /// Returns false if the entry is unset, closed or closing.
205 IdleConnList::isAvailable(int i
) const
207 const Comm::ConnectionPointer
&conn
= theList_
[i
];
209 // connection already closed. useless.
210 if (!Comm::IsConnOpen(conn
))
213 // our connection early-read/close handler is scheduled to run already. unsafe
214 if (!COMMIO_FD_READCB(conn
->fd
)->active())
220 Comm::ConnectionPointer
223 for (int i
=size_
-1; i
>=0; --i
) {
228 // our connection timeout handler is scheduled to run already. unsafe for now.
229 // TODO: cancel the pending timeout callback and allow re-use of the conn.
230 if (fd_table
[theList_
[i
]->fd
].timeoutHandler
== NULL
)
233 // finally, a match. pop and return it.
234 Comm::ConnectionPointer result
= theList_
[i
];
235 /* may delete this */
237 clearHandlers(result
);
241 return Comm::ConnectionPointer();
245 * XXX this routine isn't terribly efficient - if there's a pending
246 * read event (which signifies the fd will close in the next IO loop!)
247 * we ignore the FD and move onto the next one. This means, as an example,
248 * if we have a lot of FDs open to a very popular server and we get a bunch
249 * of requests JUST as they timeout (say, it shuts down) we'll be wasting
250 * quite a bit of CPU. Just keep it in mind.
252 Comm::ConnectionPointer
253 IdleConnList::findUseable(const Comm::ConnectionPointer
&key
)
257 // small optimization: do the constant bool tests only once.
258 const bool keyCheckAddr
= !key
->local
.IsAnyAddr();
259 const bool keyCheckPort
= key
->local
.GetPort() > 0;
261 for (int i
=size_
-1; i
>=0; --i
) {
266 // local end port is required, but dont match.
267 if (keyCheckPort
&& key
->local
.GetPort() != theList_
[i
]->local
.GetPort())
270 // local address is required, but does not match.
271 if (keyCheckAddr
&& key
->local
.matchIPAddr(theList_
[i
]->local
) != 0)
274 // our connection timeout handler is scheduled to run already. unsafe for now.
275 // TODO: cancel the pending timeout callback and allow re-use of the conn.
276 if (fd_table
[theList_
[i
]->fd
].timeoutHandler
== NULL
)
279 // finally, a match. pop and return it.
280 Comm::ConnectionPointer result
= theList_
[i
];
281 /* may delete this */
283 clearHandlers(result
);
287 return Comm::ConnectionPointer();
290 /* might delete list */
292 IdleConnList::findAndClose(const Comm::ConnectionPointer
&conn
)
294 const int index
= findIndexOf(conn
);
296 /* might delete this */
304 IdleConnList::Read(const Comm::ConnectionPointer
&conn
, char *buf
, size_t len
, comm_err_t flag
, int xerrno
, void *data
)
306 debugs(48, 3, HERE
<< len
<< " bytes from " << conn
);
308 if (flag
== COMM_ERR_CLOSING
) {
309 debugs(48, 3, HERE
<< "COMM_ERR_CLOSING from " << conn
);
310 /* Bail out on COMM_ERR_CLOSING - may happen when shutdown aborts our idle FD */
314 IdleConnList
*list
= (IdleConnList
*) data
;
315 /* may delete list/data */
316 list
->findAndClose(conn
);
320 IdleConnList::Timeout(const CommTimeoutCbParams
&io
)
322 debugs(48, 3, HERE
<< io
.conn
);
323 IdleConnList
*list
= static_cast<IdleConnList
*>(io
.data
);
324 /* may delete list/data */
325 list
->findAndClose(io
.conn
);
328 /* ========== PconnPool PRIVATE FUNCTIONS ============================================ */
331 PconnPool::key(const Comm::ConnectionPointer
&destLink
, const char *domain
)
333 LOCAL_ARRAY(char, buf
, SQUIDHOSTNAMELEN
* 3 + 10);
335 destLink
->remote
.ToURL(buf
, SQUIDHOSTNAMELEN
* 3 + 10);
337 const int used
= strlen(buf
);
338 snprintf(buf
+used
, SQUIDHOSTNAMELEN
* 3 + 10-used
, "/%s", domain
);
341 debugs(48,6,"PconnPool::key(" << destLink
<< ", " << (domain
?domain
:"[no domain]") << ") is {" << buf
<< "}" );
346 PconnPool::dumpHist(StoreEntry
* e
) const
349 "%s persistent connection counts:\n"
353 "\t---- ---------\n",
356 for (int i
= 0; i
< PCONN_HIST_SZ
; ++i
) {
360 storeAppendPrintf(e
, "\t%4d %9d\n", i
, hist
[i
]);
365 PconnPool::dumpHash(StoreEntry
*e
) const
367 hash_table
*hid
= table
;
371 for (hash_link
*walker
= hid
->next
; walker
; walker
= hash_next(hid
)) {
372 storeAppendPrintf(e
, "\t item %5d: %s\n", i
, (char *)(walker
->key
));
377 /* ========== PconnPool PUBLIC FUNCTIONS ============================================ */
379 PconnPool::PconnPool(const char *aDescr
) : table(NULL
), descr(aDescr
),
383 table
= hash_create((HASHCMP
*) strcmp
, 229, hash_string
);
385 for (i
= 0; i
< PCONN_HIST_SZ
; ++i
)
388 PconnModule::GetInstance()->add(this);
391 PconnPool::~PconnPool()
394 hashFreeMemory(table
);
398 PconnPool::push(const Comm::ConnectionPointer
&conn
, const char *domain
)
401 debugs(48, 3, HERE
<< "Not many unused FDs");
404 } else if (shutting_down
) {
406 debugs(48, 3, HERE
<< "Squid is shutting down. Refusing to do anything");
410 const char *aKey
= key(conn
, domain
);
411 IdleConnList
*list
= (IdleConnList
*) hash_lookup(table
, aKey
);
414 list
= new IdleConnList(aKey
, this);
415 debugs(48, 3, HERE
<< "new IdleConnList for {" << hashKeyStr(&list
->hash
) << "}" );
416 hash_join(table
, &list
->hash
);
418 debugs(48, 3, HERE
<< "found IdleConnList for {" << hashKeyStr(&list
->hash
) << "}" );
422 assert(!comm_has_incomplete_write(conn
->fd
));
424 LOCAL_ARRAY(char, desc
, FD_DESC_SZ
);
425 snprintf(desc
, FD_DESC_SZ
, "Idle server: %s", aKey
);
426 fd_note(conn
->fd
, desc
);
427 debugs(48, 3, HERE
<< "pushed " << conn
<< " for " << aKey
);
430 Comm::ConnectionPointer
431 PconnPool::pop(const Comm::ConnectionPointer
&destLink
, const char *domain
, bool isRetriable
)
433 const char * aKey
= key(destLink
, domain
);
435 IdleConnList
*list
= (IdleConnList
*)hash_lookup(table
, aKey
);
437 debugs(48, 3, HERE
<< "lookup for key {" << aKey
<< "} failed.");
438 return Comm::ConnectionPointer();
440 debugs(48, 3, HERE
<< "found " << hashKeyStr(&list
->hash
) << (isRetriable
?"(to use)":"(to kill)") );
443 /* may delete list */
444 Comm::ConnectionPointer temp
= list
->findUseable(destLink
);
445 if (!isRetriable
&& Comm::IsConnOpen(temp
))
452 PconnPool::closeN(int n
, const Comm::ConnectionPointer
&destLink
, const char *domain
)
454 // TODO: optimize: we can probably do hash_lookup just once
455 for (int i
= 0; i
< n
; ++i
)
456 pop(destLink
, domain
, false); // may fail!
460 PconnPool::unlinkList(IdleConnList
*list
)
462 theCount
-= list
->count();
463 assert(theCount
>= 0);
464 hash_remove_link(table
, &list
->hash
);
468 PconnPool::noteUses(int uses
)
470 if (uses
>= PCONN_HIST_SZ
)
471 uses
= PCONN_HIST_SZ
- 1;
476 /* ========== PconnModule ============================================ */
479 * This simple class exists only for the cache manager
482 PconnModule::PconnModule() : pools(NULL
), poolCount(0)
484 pools
= (PconnPool
**) xcalloc(MAX_NUM_PCONN_POOLS
, sizeof(*pools
));
485 //TODO: re-link to MemPools. WAS: pconn_fds_pool = memPoolCreate("pconn_fds", PCONN_FDS_SZ * sizeof(int));
486 debugs(48, DBG_CRITICAL
, "persistent connection module initialized");
487 registerWithCacheManager();
491 PconnModule::GetInstance()
493 if (instance
== NULL
)
494 instance
= new PconnModule
;
500 PconnModule::registerWithCacheManager(void)
502 Mgr::RegisterAction("pconn",
503 "Persistent Connection Utilization Histograms",
508 PconnModule::add(PconnPool
*aPool
)
510 assert(poolCount
< MAX_NUM_PCONN_POOLS
);
511 *(pools
+poolCount
) = aPool
;
516 PconnModule::dump(StoreEntry
*e
)
520 for (i
= 0; i
< poolCount
; ++i
) {
521 storeAppendPrintf(e
, "\n Pool %d Stats\n", i
);
522 (*(pools
+i
))->dumpHist(e
);
523 storeAppendPrintf(e
, "\n Pool %d Hash Table\n",i
);
524 (*(pools
+i
))->dumpHash(e
);
529 PconnModule::DumpWrapper(StoreEntry
*e
)
531 PconnModule::GetInstance()->dump(e
);