2 * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section 84 Helper process maintenance */
12 #include "base/AsyncCbdataCalls.h"
13 #include "base/Packable.h"
16 #include "comm/Connection.h"
17 #include "comm/Read.h"
18 #include "comm/Write.h"
19 #include "debug/Messages.h"
22 #include "format/Quoting.h"
24 #include "helper/Reply.h"
25 #include "helper/Request.h"
27 #include "SquidConfig.h"
29 #include "SquidMath.h"
33 // helper_stateful_server::data uses explicit alloc()/freeOne() */
36 #define HELPER_MAX_ARGS 64
38 /// The maximum allowed request retries.
41 /// Helpers input buffer size.
42 const size_t ReadBufSize(32*1024);
44 static IOCB helperHandleRead
;
45 static IOCB helperStatefulHandleRead
;
46 static void Enqueue(helper
* hlp
, Helper::Xaction
*);
47 static helper_server
*GetFirstAvailable(const helper::Pointer
&);
48 static helper_stateful_server
*StatefulGetFirstAvailable(const statefulhelper::Pointer
&);
49 static void helperDispatch(helper_server
* srv
, Helper::Xaction
* r
);
50 static void helperStatefulDispatch(helper_stateful_server
* srv
, Helper::Xaction
* r
);
51 static void helperKickQueue(const helper::Pointer
&);
52 static void helperStatefulKickQueue(const statefulhelper::Pointer
&);
53 static void helperStatefulServerDone(helper_stateful_server
* srv
);
54 static void StatefulEnqueue(statefulhelper
* hlp
, Helper::Xaction
* r
);
56 CBDATA_CLASS_INIT(helper_server
);
57 CBDATA_CLASS_INIT(helper_stateful_server
);
59 InstanceIdDefinitions(HelperServerBase
, "Hlpr");
62 HelperServerBase::initStats()
72 HelperServerBase::closePipesSafely(const char *id_name
)
75 shutdown(writePipe
->fd
, SD_BOTH
);
79 if (readPipe
->fd
== writePipe
->fd
)
87 if (WaitForSingleObject(hIpc
, 5000) != WAIT_OBJECT_0
) {
89 debugs(84, DBG_IMPORTANT
, "WARNING: " << id_name
<<
90 " #" << index
<< " (PID " << (long int)pid
<< ") didn't exit in 5 seconds");
100 HelperServerBase::closeWritePipeSafely(const char *id_name
)
103 shutdown(writePipe
->fd
, (readPipe
->fd
== writePipe
->fd
? SD_BOTH
: SD_SEND
));
106 flags
.closing
= true;
107 if (readPipe
->fd
== writePipe
->fd
)
113 if (WaitForSingleObject(hIpc
, 5000) != WAIT_OBJECT_0
) {
115 debugs(84, DBG_IMPORTANT
, "WARNING: " << id_name
<<
116 " #" << index
<< " (PID " << (long int)pid
<< ") didn't exit in 5 seconds");
126 HelperServerBase::dropQueued()
128 while (!requests
.empty()) {
129 // XXX: re-schedule these on another helper?
130 Helper::Xaction
*r
= requests
.front();
131 requests
.pop_front();
133 if (cbdataReferenceValidDone(r
->request
.data
, &cbdata
)) {
134 r
->reply
.result
= Helper::Unknown
;
135 r
->request
.callback(cbdata
, r
->reply
);
142 HelperServerBase::~HelperServerBase()
145 memFreeBuf(rbuf_sz
, rbuf
);
150 helper_server::~helper_server()
161 if (Comm::IsConnOpen(writePipe
))
162 closeWritePipeSafely(parent
->id_name
);
164 dlinkDelete(&link
, &parent
->servers
);
166 assert(parent
->childs
.n_running
> 0);
167 -- parent
->childs
.n_running
;
169 assert(requests
.empty());
173 helper_server::dropQueued()
175 HelperServerBase::dropQueued();
176 requestsIndex
.clear();
179 helper_stateful_server::~helper_stateful_server()
181 /* TODO: walk the local queue of requests and carry them all out */
182 if (Comm::IsConnOpen(writePipe
))
183 closeWritePipeSafely(parent
->id_name
);
185 parent
->cancelReservation(reservationId
);
187 dlinkDelete(&link
, &parent
->servers
);
189 assert(parent
->childs
.n_running
> 0);
190 -- parent
->childs
.n_running
;
192 assert(requests
.empty());
196 helperOpenServers(const helper::Pointer
&hlp
)
202 const char *args
[HELPER_MAX_ARGS
+1]; // save space for a NULL terminator
203 char fd_note_buf
[FD_DESC_SZ
];
213 if (hlp
->cmdline
== nullptr)
216 progname
= hlp
->cmdline
->key
;
218 if ((s
= strrchr(progname
, '/')))
219 shortname
= xstrdup(s
+ 1);
221 shortname
= xstrdup(progname
);
223 /* figure out how many new child are actually needed. */
224 int need_new
= hlp
->childs
.needNew();
226 debugs(84, Important(19), "helperOpenServers: Starting " << need_new
<< "/" << hlp
->childs
.n_max
<< " '" << shortname
<< "' processes");
229 debugs(84, Important(20), "helperOpenServers: No '" << shortname
<< "' processes needed.");
232 procname
= (char *)xmalloc(strlen(shortname
) + 3);
234 snprintf(procname
, strlen(shortname
) + 3, "(%s)", shortname
);
236 args
[nargs
] = procname
;
239 for (w
= hlp
->cmdline
->next
; w
&& nargs
< HELPER_MAX_ARGS
; w
= w
->next
) {
240 args
[nargs
] = w
->key
;
244 args
[nargs
] = nullptr;
247 assert(nargs
<= HELPER_MAX_ARGS
);
249 int successfullyStarted
= 0;
251 for (k
= 0; k
< need_new
; ++k
) {
254 pid
= ipcCreate(hlp
->ipc_type
,
264 debugs(84, DBG_IMPORTANT
, "WARNING: Cannot run '" << progname
<< "' process.");
268 ++successfullyStarted
;
269 ++ hlp
->childs
.n_running
;
270 ++ hlp
->childs
.n_active
;
271 srv
= new helper_server
;
275 srv
->addr
= hlp
->addr
;
276 srv
->readPipe
= new Comm::Connection
;
277 srv
->readPipe
->fd
= rfd
;
278 srv
->writePipe
= new Comm::Connection
;
279 srv
->writePipe
->fd
= wfd
;
280 srv
->rbuf
= (char *)memAllocBuf(ReadBufSize
, &srv
->rbuf_sz
);
281 srv
->wqueue
= new MemBuf
;
283 srv
->nextRequestId
= 0;
284 srv
->replyXaction
= nullptr;
285 srv
->ignoreToEom
= false;
287 dlinkAddTail(srv
, &srv
->link
, &hlp
->servers
);
290 snprintf(fd_note_buf
, FD_DESC_SZ
, "%s #%d", shortname
, k
+ 1);
291 fd_note(rfd
, fd_note_buf
);
293 snprintf(fd_note_buf
, FD_DESC_SZ
, "reading %s #%d", shortname
, k
+ 1);
294 fd_note(rfd
, fd_note_buf
);
295 snprintf(fd_note_buf
, FD_DESC_SZ
, "writing %s #%d", shortname
, k
+ 1);
296 fd_note(wfd
, fd_note_buf
);
299 commSetNonBlocking(rfd
);
302 commSetNonBlocking(wfd
);
304 AsyncCall::Pointer closeCall
= asyncCall(5,4, "helper_server::HelperServerClosed", cbdataDialer(helper_server::HelperServerClosed
, srv
));
305 comm_add_close_handler(rfd
, closeCall
);
307 if (hlp
->timeout
&& hlp
->childs
.concurrency
) {
308 AsyncCall::Pointer timeoutCall
= commCbCall(84, 4, "helper_server::requestTimeout",
309 CommTimeoutCbPtrFun(helper_server::requestTimeout
, srv
));
310 commSetConnTimeout(srv
->readPipe
, hlp
->timeout
, timeoutCall
);
313 AsyncCall::Pointer call
= commCbCall(5,4, "helperHandleRead",
314 CommIoCbPtrFun(helperHandleRead
, srv
));
315 comm_read(srv
->readPipe
, srv
->rbuf
, srv
->rbuf_sz
- 1, call
);
318 // Call handleFewerServers() before hlp->last_restart is updated because
319 // that method uses last_restart to measure the delay since previous start.
320 // TODO: Refactor last_restart code to measure failure frequency rather than
321 // detecting a helper #X failure that is being close to the helper #Y start.
322 if (successfullyStarted
< need_new
)
323 hlp
->handleFewerServers(false);
325 hlp
->last_restart
= squid_curtime
;
326 safe_free(shortname
);
328 helperKickQueue(hlp
);
334 * helperStatefulOpenServers: create the stateful child helper processes
337 helperStatefulOpenServers(const statefulhelper::Pointer
&hlp
)
340 const char *args
[HELPER_MAX_ARGS
+1]; // save space for a NULL terminator
341 char fd_note_buf
[FD_DESC_SZ
];
344 if (hlp
->cmdline
== nullptr)
347 if (hlp
->childs
.concurrency
)
348 debugs(84, DBG_CRITICAL
, "ERROR: concurrency= is not yet supported for stateful helpers ('" << hlp
->cmdline
<< "')");
350 char *progname
= hlp
->cmdline
->key
;
353 if ((s
= strrchr(progname
, '/')))
354 shortname
= xstrdup(s
+ 1);
356 shortname
= xstrdup(progname
);
358 /* figure out haw mant new helpers are needed. */
359 int need_new
= hlp
->childs
.needNew();
361 debugs(84, DBG_IMPORTANT
, "helperOpenServers: Starting " << need_new
<< "/" << hlp
->childs
.n_max
<< " '" << shortname
<< "' processes");
364 debugs(84, DBG_IMPORTANT
, "helperStatefulOpenServers: No '" << shortname
<< "' processes needed.");
367 char *procname
= (char *)xmalloc(strlen(shortname
) + 3);
369 snprintf(procname
, strlen(shortname
) + 3, "(%s)", shortname
);
371 args
[nargs
] = procname
;
374 for (wordlist
*w
= hlp
->cmdline
->next
; w
&& nargs
< HELPER_MAX_ARGS
; w
= w
->next
) {
375 args
[nargs
] = w
->key
;
379 args
[nargs
] = nullptr;
382 assert(nargs
<= HELPER_MAX_ARGS
);
384 int successfullyStarted
= 0;
386 for (int k
= 0; k
< need_new
; ++k
) {
391 pid_t pid
= ipcCreate(hlp
->ipc_type
,
401 debugs(84, DBG_IMPORTANT
, "WARNING: Cannot run '" << progname
<< "' process.");
405 ++successfullyStarted
;
406 ++ hlp
->childs
.n_running
;
407 ++ hlp
->childs
.n_active
;
408 helper_stateful_server
*srv
= new helper_stateful_server
;
412 srv
->addr
= hlp
->addr
;
413 srv
->readPipe
= new Comm::Connection
;
414 srv
->readPipe
->fd
= rfd
;
415 srv
->writePipe
= new Comm::Connection
;
416 srv
->writePipe
->fd
= wfd
;
417 srv
->rbuf
= (char *)memAllocBuf(ReadBufSize
, &srv
->rbuf_sz
);
420 srv
->reservationStart
= 0;
422 dlinkAddTail(srv
, &srv
->link
, &hlp
->servers
);
425 snprintf(fd_note_buf
, FD_DESC_SZ
, "%s #%d", shortname
, k
+ 1);
426 fd_note(rfd
, fd_note_buf
);
428 snprintf(fd_note_buf
, FD_DESC_SZ
, "reading %s #%d", shortname
, k
+ 1);
429 fd_note(rfd
, fd_note_buf
);
430 snprintf(fd_note_buf
, FD_DESC_SZ
, "writing %s #%d", shortname
, k
+ 1);
431 fd_note(wfd
, fd_note_buf
);
434 commSetNonBlocking(rfd
);
437 commSetNonBlocking(wfd
);
439 AsyncCall::Pointer closeCall
= asyncCall(5,4, "helper_stateful_server::HelperServerClosed", cbdataDialer(helper_stateful_server::HelperServerClosed
, srv
));
440 comm_add_close_handler(rfd
, closeCall
);
442 AsyncCall::Pointer call
= commCbCall(5,4, "helperStatefulHandleRead",
443 CommIoCbPtrFun(helperStatefulHandleRead
, srv
));
444 comm_read(srv
->readPipe
, srv
->rbuf
, srv
->rbuf_sz
- 1, call
);
447 // Call handleFewerServers() before hlp->last_restart is updated because
448 // that method uses last_restart to measure the delay since previous start.
449 // TODO: Refactor last_restart code to measure failure frequency rather than
450 // detecting a helper #X failure that is being close to the helper #Y start.
451 if (successfullyStarted
< need_new
)
452 hlp
->handleFewerServers(false);
454 hlp
->last_restart
= squid_curtime
;
455 safe_free(shortname
);
457 helperStatefulKickQueue(hlp
);
461 helper::submitRequest(Helper::Xaction
*r
)
465 if ((srv
= GetFirstAvailable(this)))
466 helperDispatch(srv
, r
);
473 /// handles helperSubmit() and helperStatefulSubmit() failures
475 SubmissionFailure(const helper::Pointer
&hlp
, HLPCB
*callback
, void *data
)
477 auto result
= Helper::Error
;
479 debugs(84, 3, "no helper");
480 result
= Helper::Unknown
;
482 // else pretend the helper has responded with ERR
484 callback(data
, Helper::Reply(result
));
488 helperSubmit(const helper::Pointer
&hlp
, const char *buf
, HLPCB
* callback
, void *data
)
490 if (!hlp
|| !hlp
->trySubmit(buf
, callback
, data
))
491 SubmissionFailure(hlp
, callback
, data
);
494 /// whether queuing an additional request would overload the helper
496 helper::queueFull() const {
497 return stats
.queue_size
>= static_cast<int>(childs
.queue_size
);
501 helper::overloaded() const {
502 return stats
.queue_size
> static_cast<int>(childs
.queue_size
);
505 /// synchronizes queue-dependent measurements with the current queue state
507 helper::syncQueueStats()
511 debugs(84, 5, id_name
<< " still overloaded; dropped " << droppedRequests
);
513 overloadStart
= squid_curtime
;
514 debugs(84, 3, id_name
<< " became overloaded");
518 debugs(84, 5, id_name
<< " is no longer overloaded");
519 if (droppedRequests
) {
520 debugs(84, DBG_IMPORTANT
, "helper " << id_name
<<
521 " is no longer overloaded after dropping " << droppedRequests
<<
522 " requests in " << (squid_curtime
- overloadStart
) << " seconds");
530 /// prepares the helper for request submission
531 /// returns true if and only if the submission should proceed
532 /// may kill Squid if the helper remains overloaded for too long
536 // re-sync for the configuration may have changed since the last submission
539 // Nothing special to do if the new request does not overload (i.e., the
540 // queue is not even full yet) or only _starts_ overloading this helper
541 // (i.e., the queue is currently at its limit).
545 if (squid_curtime
- overloadStart
<= 180)
546 return true; // also OK: overload has not persisted long enough to panic
548 if (childs
.onPersistentOverload
== Helper::ChildConfig::actDie
)
549 fatalf("Too many queued %s requests; see on-persistent-overload.", id_name
);
551 if (!droppedRequests
) {
552 debugs(84, DBG_IMPORTANT
, "WARNING: dropping requests to overloaded " <<
553 id_name
<< " helper configured with on-persistent-overload=err");
556 debugs(84, 3, "failed to send " << droppedRequests
<< " helper requests to " << id_name
);
561 helper::trySubmit(const char *buf
, HLPCB
* callback
, void *data
)
564 return false; // request was dropped
566 submit(buf
, callback
, data
); // will send or queue
567 return true; // request submitted or queued
570 /// dispatches or enqueues a helper requests; does not enforce queue limits
572 helper::submit(const char *buf
, HLPCB
* callback
, void *data
)
574 Helper::Xaction
*r
= new Helper::Xaction(callback
, data
, buf
);
576 debugs(84, DBG_DATA
, Raw("buf", buf
, strlen(buf
)));
579 /// Submit request or callback the caller with a Helper::Error error.
580 /// If the reservation is not set then reserves a new helper.
582 helperStatefulSubmit(const statefulhelper::Pointer
&hlp
, const char *buf
, HLPCB
* callback
, void *data
, const Helper::ReservationId
& reservation
)
584 if (!hlp
|| !hlp
->trySubmit(buf
, callback
, data
, reservation
))
585 SubmissionFailure(hlp
, callback
, data
);
588 /// If possible, submit request. Otherwise, either kill Squid or return false.
590 statefulhelper::trySubmit(const char *buf
, HLPCB
* callback
, void *data
, const Helper::ReservationId
& reservation
)
593 return false; // request was dropped
595 submit(buf
, callback
, data
, reservation
); // will send or queue
596 return true; // request submitted or queued
600 statefulhelper::reserveServer(helper_stateful_server
* srv
)
602 // clear any old reservation
603 if (srv
->reserved()) {
604 reservations
.erase(srv
->reservationId
);
605 srv
->clearReservation();
609 reservations
.insert(Reservations::value_type(srv
->reservationId
, srv
));
613 statefulhelper::cancelReservation(const Helper::ReservationId reservation
)
615 const auto it
= reservations
.find(reservation
);
616 if (it
== reservations
.end())
619 helper_stateful_server
*srv
= it
->second
;
620 reservations
.erase(it
);
621 srv
->clearReservation();
623 // schedule a queue kick
624 AsyncCall::Pointer call
= asyncCall(5,4, "helperStatefulServerDone", cbdataDialer(helperStatefulServerDone
, srv
));
625 ScheduleCallHere(call
);
628 helper_stateful_server
*
629 statefulhelper::findServer(const Helper::ReservationId
& reservation
)
631 const auto it
= reservations
.find(reservation
);
632 if (it
== reservations
.end())
638 helper_stateful_server::reserve()
640 assert(!reservationId
);
641 reservationStart
= squid_curtime
;
642 reservationId
= Helper::ReservationId::Next();
643 debugs(84, 3, "srv-" << index
<< " reservation id = " << reservationId
);
647 helper_stateful_server::clearReservation()
649 debugs(84, 3, "srv-" << index
<< " reservation id = " << reservationId
);
655 reservationId
.clear();
656 reservationStart
= 0;
660 statefulhelper::submit(const char *buf
, HLPCB
* callback
, void *data
, const Helper::ReservationId
& reservation
)
662 Helper::Xaction
*r
= new Helper::Xaction(callback
, data
, buf
);
664 if (buf
&& reservation
) {
665 debugs(84, 5, reservation
);
666 helper_stateful_server
*lastServer
= findServer(reservation
);
668 debugs(84, DBG_CRITICAL
, "ERROR: Helper " << id_name
<< " reservation expired (" << reservation
<< ")");
669 r
->reply
.result
= Helper::TimedOut
;
670 r
->request
.callback(r
->request
.data
, r
->reply
);
674 debugs(84, 5, "StatefulSubmit dispatching");
675 helperStatefulDispatch(lastServer
, r
);
677 helper_stateful_server
*srv
;
678 if ((srv
= StatefulGetFirstAvailable(this))) {
680 helperStatefulDispatch(srv
, r
);
682 StatefulEnqueue(this, r
);
685 debugs(84, DBG_DATA
, "placeholder: '" << r
->request
.placeholder
<<
686 "', " << Raw("buf", buf
, (!buf
?0:strlen(buf
))));
692 helper::packStatsInto(Packable
*p
, const char *label
) const
695 p
->appendf("%s:\n", label
);
697 p
->appendf(" program: %s\n", cmdline
->key
);
698 p
->appendf(" number active: %d of %d (%d shutting down)\n", childs
.n_active
, childs
.n_max
, (childs
.n_running
- childs
.n_active
));
699 p
->appendf(" requests sent: %d\n", stats
.requests
);
700 p
->appendf(" replies received: %d\n", stats
.replies
);
701 p
->appendf(" requests timedout: %d\n", stats
.timedout
);
702 p
->appendf(" queue length: %d\n", stats
.queue_size
);
703 p
->appendf(" avg service time: %d msec\n", stats
.avg_svc_time
);
705 p
->appendf("%7s\t%7s\t%7s\t%11s\t%11s\t%11s\t%6s\t%7s\t%7s\t%7s\n",
717 for (dlink_node
*link
= servers
.head
; link
; link
= link
->next
) {
718 HelperServerBase
*srv
= static_cast<HelperServerBase
*>(link
->data
);
720 Helper::Xaction
*xaction
= srv
->requests
.empty() ? nullptr : srv
->requests
.front();
721 double tt
= 0.001 * (xaction
? tvSubMsec(xaction
->request
.dispatch_time
, current_time
) : tvSubMsec(srv
->dispatch_time
, srv
->answer_time
));
722 p
->appendf("%7u\t%7d\t%7d\t%11" PRIu64
"\t%11" PRIu64
"\t%11" PRIu64
"\t%c%c%c%c%c%c\t%7.3f\t%7d\t%s\n",
729 srv
->stats
.pending
? 'B' : ' ',
730 srv
->flags
.writing
? 'W' : ' ',
731 srv
->flags
.closing
? 'C' : ' ',
732 srv
->reserved() ? 'R' : ' ',
733 srv
->flags
.shutdown
? 'S' : ' ',
734 xaction
&& xaction
->request
.placeholder
? 'P' : ' ',
737 xaction
? Format::QuoteMimeBlob(xaction
->request
.buf
) : "(none)");
740 p
->append("\nFlags key:\n"
745 " S\tSHUTDOWN PENDING\n"
746 " P\tPLACEHOLDER\n", 101);
750 helper::willOverload() const {
751 return queueFull() && !(childs
.needNew() || GetFirstAvailable(this));
755 helper::Make(const char *name
)
757 return new helper(name
);
760 statefulhelper::Pointer
761 statefulhelper::Make(const char *name
)
763 return new statefulhelper(name
);
767 helperShutdown(const helper::Pointer
&hlp
)
769 dlink_node
*link
= hlp
->servers
.head
;
773 srv
= (helper_server
*)link
->data
;
776 if (srv
->flags
.shutdown
) {
777 debugs(84, 3, "helperShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " has already SHUT DOWN.");
781 assert(hlp
->childs
.n_active
> 0);
782 -- hlp
->childs
.n_active
;
783 srv
->flags
.shutdown
= true; /* request it to shut itself down */
785 if (srv
->flags
.closing
) {
786 debugs(84, 3, "helperShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is CLOSING.");
790 if (srv
->stats
.pending
) {
791 debugs(84, 3, "helperShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is BUSY.");
795 debugs(84, 3, "helperShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " shutting down.");
796 /* the rest of the details is dealt with in the helperServerFree
799 srv
->closePipesSafely(hlp
->id_name
);
804 helperStatefulShutdown(const statefulhelper::Pointer
&hlp
)
806 dlink_node
*link
= hlp
->servers
.head
;
807 helper_stateful_server
*srv
;
810 srv
= (helper_stateful_server
*)link
->data
;
813 if (srv
->flags
.shutdown
) {
814 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " has already SHUT DOWN.");
818 assert(hlp
->childs
.n_active
> 0);
819 -- hlp
->childs
.n_active
;
820 srv
->flags
.shutdown
= true; /* request it to shut itself down */
822 if (srv
->stats
.pending
) {
823 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is BUSY.");
827 if (srv
->flags
.closing
) {
828 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is CLOSING.");
832 if (srv
->reserved()) {
834 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is RESERVED. Closing anyway.");
836 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is RESERVED. Not Shutting Down Yet.");
841 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " shutting down.");
843 /* the rest of the details is dealt with in the helperStatefulServerFree
846 srv
->closePipesSafely(hlp
->id_name
);
852 /* note, don't free id_name, it probably points to static memory */
854 // TODO: if the queue is not empty it will leak Helper::Request's
856 debugs(84, DBG_CRITICAL
, "WARNING: freeing " << id_name
<< " helper with " << stats
.queue_size
<< " requests queued");
860 helper::handleKilledServer(HelperServerBase
*srv
, bool &needsNewServers
)
862 needsNewServers
= false;
863 if (!srv
->flags
.shutdown
) {
864 assert(childs
.n_active
> 0);
866 debugs(84, DBG_CRITICAL
, "WARNING: " << id_name
<< " #" << srv
->index
<< " exited");
868 handleFewerServers(srv
->stats
.replies
>= 1);
870 if (childs
.needNew() > 0) {
871 srv
->flags
.shutdown
= true;
872 needsNewServers
= true;
878 helper::handleFewerServers(const bool madeProgress
)
880 const auto needNew
= childs
.needNew();
883 return; // some server(s) have died, but we still have enough
885 debugs(80, DBG_IMPORTANT
, "Too few " << id_name
<< " processes are running (need " << needNew
<< "/" << childs
.n_max
<< ")" <<
886 Debug::Extra
<< "active processes: " << childs
.n_active
<<
887 Debug::Extra
<< "processes configured to start at (re)configuration: " << childs
.n_startup
);
889 if (childs
.n_active
< childs
.n_startup
&& last_restart
> squid_curtime
- 30) {
891 debugs(80, DBG_CRITICAL
, "ERROR: The " << id_name
<< " helpers are crashing too rapidly, need help!");
893 fatalf("The %s helpers are crashing too rapidly, need help!", id_name
);
898 helper_server::HelperServerClosed(helper_server
*srv
)
900 const auto hlp
= srv
->parent
;
902 bool needsNewServers
= false;
903 hlp
->handleKilledServer(srv
, needsNewServers
);
904 if (needsNewServers
) {
905 debugs(80, DBG_IMPORTANT
, "Starting new helpers");
906 helperOpenServers(hlp
);
914 // XXX: Almost duplicates helper_server::HelperServerClosed() because helperOpenServers() is not a virtual method of the `helper` class
915 // TODO: Fix the `helper` class hierarchy to use virtual functions.
917 helper_stateful_server::HelperServerClosed(helper_stateful_server
*srv
)
919 const auto hlp
= srv
->parent
;
921 bool needsNewServers
= false;
922 hlp
->handleKilledServer(srv
, needsNewServers
);
923 if (needsNewServers
) {
924 debugs(80, DBG_IMPORTANT
, "Starting new helpers");
925 helperStatefulOpenServers(hlp
);
934 helper_server::popRequest(int request_number
)
936 Helper::Xaction
*r
= nullptr;
937 helper_server::RequestIndex::iterator it
;
938 if (parent
->childs
.concurrency
) {
939 // If concurrency supported retrieve request from ID
940 it
= requestsIndex
.find(request_number
);
941 if (it
!= requestsIndex
.end()) {
943 requests
.erase(it
->second
);
944 requestsIndex
.erase(it
);
946 } else if(!requests
.empty()) {
947 // Else get the first request from queue, if any
948 r
= requests
.front();
949 requests
.pop_front();
955 /// Calls back with a pointer to the buffer with the helper output
957 helperReturnBuffer(helper_server
* srv
, const helper::Pointer
&hlp
, char * msg
, size_t msgSize
, char * msgEnd
)
959 if (Helper::Xaction
*r
= srv
->replyXaction
) {
960 const bool hasSpace
= r
->reply
.accumulate(msg
, msgSize
);
962 debugs(84, DBG_IMPORTANT
, "ERROR: Disconnecting from a " <<
963 "helper that overflowed " << srv
->rbuf_sz
<< "-byte " <<
964 "Squid input buffer: " << hlp
->id_name
<< " #" << srv
->index
);
965 srv
->closePipesSafely(hlp
->id_name
);
970 return; // We are waiting for more data.
973 if (cbdataReferenceValid(r
->request
.data
)) {
975 if (r
->reply
.result
== Helper::BrokenHelper
&& r
->request
.retries
< MAX_RETRIES
) {
976 debugs(84, DBG_IMPORTANT
, "ERROR: helper: " << r
->reply
<< ", attempt #" << (r
->request
.retries
+ 1) << " of 2");
979 HLPCB
*callback
= r
->request
.callback
;
980 r
->request
.callback
= nullptr;
981 void *cbdata
= nullptr;
982 if (cbdataReferenceValidDone(r
->request
.data
, &cbdata
))
983 callback(cbdata
, r
->reply
);
987 -- srv
->stats
.pending
;
988 ++ srv
->stats
.replies
;
990 ++ hlp
->stats
.replies
;
992 srv
->answer_time
= current_time
;
994 srv
->dispatch_time
= r
->request
.dispatch_time
;
996 hlp
->stats
.avg_svc_time
=
997 Math::intAverage(hlp
->stats
.avg_svc_time
,
998 tvSubMsec(r
->request
.dispatch_time
, current_time
),
999 hlp
->stats
.replies
, REDIRECT_AV_FACTOR
);
1001 // release or re-submit parsedRequestXaction object
1002 srv
->replyXaction
= nullptr;
1004 ++r
->request
.retries
;
1005 hlp
->submitRequest(r
);
1010 if (hlp
->timeout
&& hlp
->childs
.concurrency
)
1011 srv
->checkForTimedOutRequests(hlp
->retryTimedOut
);
1013 if (!srv
->flags
.shutdown
) {
1014 helperKickQueue(hlp
);
1015 } else if (!srv
->flags
.closing
&& !srv
->stats
.pending
) {
1016 srv
->closeWritePipeSafely(srv
->parent
->id_name
);
1021 helperHandleRead(const Comm::ConnectionPointer
&conn
, char *, size_t len
, Comm::Flag flag
, int, void *data
)
1023 helper_server
*srv
= (helper_server
*)data
;
1024 const auto hlp
= srv
->parent
;
1025 assert(cbdataReferenceValid(data
));
1027 /* Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us */
1029 if (flag
== Comm::ERR_CLOSING
) {
1033 assert(conn
->fd
== srv
->readPipe
->fd
);
1035 debugs(84, 5, "helperHandleRead: " << len
<< " bytes from " << hlp
->id_name
<< " #" << srv
->index
);
1037 if (flag
!= Comm::OK
|| len
== 0) {
1038 srv
->closePipesSafely(hlp
->id_name
);
1042 srv
->roffset
+= len
;
1043 srv
->rbuf
[srv
->roffset
] = '\0';
1044 debugs(84, DBG_DATA
, Raw("accumulated", srv
->rbuf
, srv
->roffset
));
1046 if (!srv
->stats
.pending
&& !srv
->stats
.timedout
) {
1047 /* someone spoke without being spoken to */
1048 debugs(84, DBG_IMPORTANT
, "ERROR: helperHandleRead: unexpected read from " <<
1049 hlp
->id_name
<< " #" << srv
->index
<< ", " << (int)len
<<
1050 " bytes '" << srv
->rbuf
<< "'");
1053 srv
->rbuf
[0] = '\0';
1056 bool needsMore
= false;
1057 char *msg
= srv
->rbuf
;
1058 while (*msg
&& !needsMore
) {
1060 char *eom
= strchr(msg
, hlp
->eom
);
1063 debugs(84, 3, "helperHandleRead: end of reply found");
1064 if (eom
> msg
&& eom
[-1] == '\r' && hlp
->eom
== '\n') {
1066 // rewind to the \r octet which is the real terminal now
1067 // and remember that we have to skip forward 2 places now.
1074 if (!srv
->ignoreToEom
&& !srv
->replyXaction
) {
1076 if (hlp
->childs
.concurrency
) {
1078 i
= strtol(msg
, &e
, 10);
1079 // Do we need to check for e == msg? Means wrong response from helper.
1080 // Will be dropped as "unexpected reply on channel 0"
1081 needsMore
= !(xisspace(*e
) || (eom
&& e
== eom
));
1084 while (*msg
&& xisspace(*msg
))
1086 } // else not enough data to compute request number
1088 if (!(srv
->replyXaction
= srv
->popRequest(i
))) {
1089 if (srv
->stats
.timedout
) {
1090 debugs(84, 3, "Timedout reply received for request-ID: " << i
<< " , ignore");
1092 debugs(84, DBG_IMPORTANT
, "ERROR: helperHandleRead: unexpected reply on channel " <<
1093 i
<< " from " << hlp
->id_name
<< " #" << srv
->index
<<
1094 " '" << srv
->rbuf
<< "'");
1096 srv
->ignoreToEom
= true;
1098 } // else we need to just append reply data to the current Xaction
1101 size_t msgSize
= eom
? eom
- msg
: (srv
->roffset
- (msg
- srv
->rbuf
));
1102 assert(msgSize
<= srv
->rbuf_sz
);
1103 helperReturnBuffer(srv
, hlp
, msg
, msgSize
, eom
);
1104 msg
+= msgSize
+ skip
;
1105 assert(static_cast<size_t>(msg
- srv
->rbuf
) <= srv
->rbuf_sz
);
1107 // The next message should not ignored.
1108 if (eom
&& srv
->ignoreToEom
)
1109 srv
->ignoreToEom
= false;
1111 assert(skip
== 0 && eom
== nullptr);
1115 size_t msgSize
= (srv
->roffset
- (msg
- srv
->rbuf
));
1116 assert(msgSize
<= srv
->rbuf_sz
);
1117 memmove(srv
->rbuf
, msg
, msgSize
);
1118 srv
->roffset
= msgSize
;
1119 srv
->rbuf
[srv
->roffset
] = '\0';
1121 // All of the responses parsed and msg points at the end of read data
1122 assert(static_cast<size_t>(msg
- srv
->rbuf
) == srv
->roffset
);
1126 if (Comm::IsConnOpen(srv
->readPipe
) && !fd_table
[srv
->readPipe
->fd
].closing()) {
1127 int spaceSize
= srv
->rbuf_sz
- srv
->roffset
- 1;
1128 assert(spaceSize
>= 0);
1130 AsyncCall::Pointer call
= commCbCall(5,4, "helperHandleRead",
1131 CommIoCbPtrFun(helperHandleRead
, srv
));
1132 comm_read(srv
->readPipe
, srv
->rbuf
+ srv
->roffset
, spaceSize
, call
);
1137 helperStatefulHandleRead(const Comm::ConnectionPointer
&conn
, char *, size_t len
, Comm::Flag flag
, int, void *data
)
1140 helper_stateful_server
*srv
= (helper_stateful_server
*)data
;
1141 const auto hlp
= srv
->parent
;
1142 assert(cbdataReferenceValid(data
));
1144 /* Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us */
1146 if (flag
== Comm::ERR_CLOSING
) {
1150 assert(conn
->fd
== srv
->readPipe
->fd
);
1152 debugs(84, 5, "helperStatefulHandleRead: " << len
<< " bytes from " <<
1153 hlp
->id_name
<< " #" << srv
->index
);
1155 if (flag
!= Comm::OK
|| len
== 0) {
1156 srv
->closePipesSafely(hlp
->id_name
);
1160 srv
->roffset
+= len
;
1161 srv
->rbuf
[srv
->roffset
] = '\0';
1162 Helper::Xaction
*r
= srv
->requests
.front();
1163 debugs(84, DBG_DATA
, Raw("accumulated", srv
->rbuf
, srv
->roffset
));
1166 /* someone spoke without being spoken to */
1167 debugs(84, DBG_IMPORTANT
, "ERROR: helperStatefulHandleRead: unexpected read from " <<
1168 hlp
->id_name
<< " #" << srv
->index
<< ", " << (int)len
<<
1169 " bytes '" << srv
->rbuf
<< "'");
1174 if ((t
= strchr(srv
->rbuf
, hlp
->eom
))) {
1175 debugs(84, 3, "helperStatefulHandleRead: end of reply found");
1177 if (t
> srv
->rbuf
&& t
[-1] == '\r' && hlp
->eom
== '\n') {
1179 // rewind to the \r octet which is the real terminal now
1186 if (r
&& !r
->reply
.accumulate(srv
->rbuf
, t
? (t
- srv
->rbuf
) : srv
->roffset
)) {
1187 debugs(84, DBG_IMPORTANT
, "ERROR: Disconnecting from a " <<
1188 "helper that overflowed " << srv
->rbuf_sz
<< "-byte " <<
1189 "Squid input buffer: " << hlp
->id_name
<< " #" << srv
->index
);
1190 srv
->closePipesSafely(hlp
->id_name
);
1194 * BUG: the below assumes that only one response per read() was received and discards any octets remaining.
1195 * Doing this prohibits concurrency support with multiple replies per read().
1196 * TODO: check that read() setup on these buffers pays attention to roffest!=0
1197 * TODO: check that replies bigger than the buffer are discarded and do not to affect future replies
1202 /* end of reply found */
1203 srv
->requests
.pop_front(); // we already have it in 'r'
1206 if (r
&& cbdataReferenceValid(r
->request
.data
)) {
1207 r
->reply
.finalize();
1208 r
->reply
.reservationId
= srv
->reservationId
;
1209 r
->request
.callback(r
->request
.data
, r
->reply
);
1211 debugs(84, DBG_IMPORTANT
, "StatefulHandleRead: no callback data registered");
1217 -- srv
->stats
.pending
;
1218 ++ srv
->stats
.replies
;
1220 ++ hlp
->stats
.replies
;
1221 srv
->answer_time
= current_time
;
1222 hlp
->stats
.avg_svc_time
=
1223 Math::intAverage(hlp
->stats
.avg_svc_time
,
1224 tvSubMsec(srv
->dispatch_time
, current_time
),
1225 hlp
->stats
.replies
, REDIRECT_AV_FACTOR
);
1228 helperStatefulServerDone(srv
);
1230 hlp
->cancelReservation(srv
->reservationId
);
1233 if (Comm::IsConnOpen(srv
->readPipe
) && !fd_table
[srv
->readPipe
->fd
].closing()) {
1234 int spaceSize
= srv
->rbuf_sz
- 1;
1236 AsyncCall::Pointer call
= commCbCall(5,4, "helperStatefulHandleRead",
1237 CommIoCbPtrFun(helperStatefulHandleRead
, srv
));
1238 comm_read(srv
->readPipe
, srv
->rbuf
, spaceSize
, call
);
1242 /// Handles a request when all running helpers, if any, are busy.
1244 Enqueue(helper
* hlp
, Helper::Xaction
* r
)
1247 ++ hlp
->stats
.queue_size
;
1249 /* do this first so idle=N has a chance to grow the child pool before it hits critical. */
1250 if (hlp
->childs
.needNew() > 0) {
1251 debugs(84, DBG_CRITICAL
, "Starting new " << hlp
->id_name
<< " helpers...");
1252 helperOpenServers(hlp
);
1256 if (hlp
->stats
.queue_size
< (int)hlp
->childs
.queue_size
)
1259 if (squid_curtime
- hlp
->last_queue_warn
< 600)
1262 if (shutting_down
|| reconfiguring
)
1265 hlp
->last_queue_warn
= squid_curtime
;
1267 debugs(84, DBG_CRITICAL
, "WARNING: All " << hlp
->childs
.n_active
<< "/" << hlp
->childs
.n_max
<< " " << hlp
->id_name
<< " processes are busy.");
1268 debugs(84, DBG_CRITICAL
, "WARNING: " << hlp
->stats
.queue_size
<< " pending requests queued");
1269 debugs(84, DBG_CRITICAL
, "WARNING: Consider increasing the number of " << hlp
->id_name
<< " processes in your config file.");
1273 StatefulEnqueue(statefulhelper
* hlp
, Helper::Xaction
* r
)
1276 ++ hlp
->stats
.queue_size
;
1278 /* do this first so idle=N has a chance to grow the child pool before it hits critical. */
1279 if (hlp
->childs
.needNew() > 0) {
1280 debugs(84, DBG_CRITICAL
, "Starting new " << hlp
->id_name
<< " helpers...");
1281 helperStatefulOpenServers(hlp
);
1285 if (hlp
->stats
.queue_size
< (int)hlp
->childs
.queue_size
)
1288 if (squid_curtime
- hlp
->last_queue_warn
< 600)
1291 if (shutting_down
|| reconfiguring
)
1294 hlp
->last_queue_warn
= squid_curtime
;
1296 debugs(84, DBG_CRITICAL
, "WARNING: All " << hlp
->childs
.n_active
<< "/" << hlp
->childs
.n_max
<< " " << hlp
->id_name
<< " processes are busy.");
1297 debugs(84, DBG_CRITICAL
, "WARNING: " << hlp
->stats
.queue_size
<< " pending requests queued");
1298 debugs(84, DBG_CRITICAL
, "WARNING: Consider increasing the number of " << hlp
->id_name
<< " processes in your config file.");
1302 helper::nextRequest()
1307 auto *r
= queue
.front();
1313 static helper_server
*
1314 GetFirstAvailable(const helper::Pointer
&hlp
)
1318 helper_server
*selected
= nullptr;
1319 debugs(84, 5, "GetFirstAvailable: Running servers " << hlp
->childs
.n_running
);
1321 if (hlp
->childs
.n_running
== 0)
1324 /* Find "least" loaded helper (approx) */
1325 for (n
= hlp
->servers
.head
; n
!= nullptr; n
= n
->next
) {
1326 srv
= (helper_server
*)n
->data
;
1328 if (selected
&& selected
->stats
.pending
<= srv
->stats
.pending
)
1331 if (srv
->flags
.shutdown
)
1334 if (!srv
->stats
.pending
)
1346 debugs(84, 5, "GetFirstAvailable: None available.");
1350 if (selected
->stats
.pending
>= (hlp
->childs
.concurrency
? hlp
->childs
.concurrency
: 1)) {
1351 debugs(84, 3, "GetFirstAvailable: Least-loaded helper is fully loaded!");
1355 debugs(84, 5, "GetFirstAvailable: returning srv-" << selected
->index
);
1359 static helper_stateful_server
*
1360 StatefulGetFirstAvailable(const statefulhelper::Pointer
&hlp
)
1363 helper_stateful_server
*srv
= nullptr;
1364 helper_stateful_server
*oldestReservedServer
= nullptr;
1365 debugs(84, 5, "StatefulGetFirstAvailable: Running servers " << hlp
->childs
.n_running
);
1367 if (hlp
->childs
.n_running
== 0)
1370 for (n
= hlp
->servers
.head
; n
!= nullptr; n
= n
->next
) {
1371 srv
= (helper_stateful_server
*)n
->data
;
1373 if (srv
->stats
.pending
)
1376 if (srv
->reserved()) {
1377 if ((squid_curtime
- srv
->reservationStart
) > hlp
->childs
.reservationTimeout
) {
1378 if (!oldestReservedServer
)
1379 oldestReservedServer
= srv
;
1380 else if (oldestReservedServer
->reservationStart
< srv
->reservationStart
)
1381 oldestReservedServer
= srv
;
1382 debugs(84, 5, "the earlier reserved server is the srv-" << oldestReservedServer
->index
);
1387 if (srv
->flags
.shutdown
)
1390 debugs(84, 5, "StatefulGetFirstAvailable: returning srv-" << srv
->index
);
1394 if (oldestReservedServer
) {
1395 debugs(84, 5, "expired reservation " << oldestReservedServer
->reservationId
<< " for srv-" << oldestReservedServer
->index
);
1396 return oldestReservedServer
;
1399 debugs(84, 5, "StatefulGetFirstAvailable: None available.");
1404 helperDispatchWriteDone(const Comm::ConnectionPointer
&, char *, size_t, Comm::Flag flag
, int, void *data
)
1406 helper_server
*srv
= (helper_server
*)data
;
1408 srv
->writebuf
->clean();
1409 delete srv
->writebuf
;
1410 srv
->writebuf
= nullptr;
1411 srv
->flags
.writing
= false;
1413 if (flag
!= Comm::OK
) {
1414 /* Helper server has crashed */
1415 debugs(84, DBG_CRITICAL
, "helperDispatch: Helper " << srv
->parent
->id_name
<< " #" << srv
->index
<< " has crashed");
1419 if (!srv
->wqueue
->isNull()) {
1420 srv
->writebuf
= srv
->wqueue
;
1421 srv
->wqueue
= new MemBuf
;
1422 srv
->flags
.writing
= true;
1423 AsyncCall::Pointer call
= commCbCall(5,5, "helperDispatchWriteDone",
1424 CommIoCbPtrFun(helperDispatchWriteDone
, srv
));
1425 Comm::Write(srv
->writePipe
, srv
->writebuf
->content(), srv
->writebuf
->contentSize(), call
, nullptr);
1430 helperDispatch(helper_server
* srv
, Helper::Xaction
* r
)
1432 const auto hlp
= srv
->parent
;
1433 const uint64_t reqId
= ++srv
->nextRequestId
;
1435 if (!cbdataReferenceValid(r
->request
.data
)) {
1436 debugs(84, DBG_IMPORTANT
, "ERROR: helperDispatch: invalid callback data");
1441 r
->request
.Id
= reqId
;
1442 helper_server::Requests::iterator it
= srv
->requests
.insert(srv
->requests
.end(), r
);
1443 r
->request
.dispatch_time
= current_time
;
1445 if (srv
->wqueue
->isNull())
1446 srv
->wqueue
->init();
1448 if (hlp
->childs
.concurrency
) {
1449 srv
->requestsIndex
.insert(helper_server::RequestIndex::value_type(reqId
, it
));
1450 assert(srv
->requestsIndex
.size() == srv
->requests
.size());
1451 srv
->wqueue
->appendf("%" PRIu64
" %s", reqId
, r
->request
.buf
);
1453 srv
->wqueue
->append(r
->request
.buf
, strlen(r
->request
.buf
));
1455 if (!srv
->flags
.writing
) {
1456 assert(nullptr == srv
->writebuf
);
1457 srv
->writebuf
= srv
->wqueue
;
1458 srv
->wqueue
= new MemBuf
;
1459 srv
->flags
.writing
= true;
1460 AsyncCall::Pointer call
= commCbCall(5,5, "helperDispatchWriteDone",
1461 CommIoCbPtrFun(helperDispatchWriteDone
, srv
));
1462 Comm::Write(srv
->writePipe
, srv
->writebuf
->content(), srv
->writebuf
->contentSize(), call
, nullptr);
1465 debugs(84, 5, "helperDispatch: Request sent to " << hlp
->id_name
<< " #" << srv
->index
<< ", " << strlen(r
->request
.buf
) << " bytes");
1468 ++ srv
->stats
.pending
;
1469 ++ hlp
->stats
.requests
;
1473 helperStatefulDispatchWriteDone(const Comm::ConnectionPointer
&, char *, size_t, Comm::Flag
, int, void *)
1477 helperStatefulDispatch(helper_stateful_server
* srv
, Helper::Xaction
* r
)
1479 const auto hlp
= srv
->parent
;
1481 if (!cbdataReferenceValid(r
->request
.data
)) {
1482 debugs(84, DBG_IMPORTANT
, "ERROR: helperStatefulDispatch: invalid callback data");
1484 hlp
->cancelReservation(srv
->reservationId
);
1488 debugs(84, 9, "helperStatefulDispatch busying helper " << hlp
->id_name
<< " #" << srv
->index
);
1490 assert(srv
->reservationId
);
1491 r
->reply
.reservationId
= srv
->reservationId
;
1493 if (r
->request
.placeholder
== 1) {
1494 /* a callback is needed before this request can _use_ a helper. */
1495 /* we don't care about releasing this helper. The request NEVER
1496 * gets to the helper. So we throw away the return code */
1497 r
->reply
.result
= Helper::Unknown
;
1498 r
->request
.callback(r
->request
.data
, r
->reply
);
1499 /* throw away the placeholder */
1501 /* and push the queue. Note that the callback may have submitted a new
1502 * request to the helper which is why we test for the request */
1504 if (!srv
->requests
.size())
1505 helperStatefulServerDone(srv
);
1510 srv
->requests
.push_back(r
);
1511 srv
->dispatch_time
= current_time
;
1512 AsyncCall::Pointer call
= commCbCall(5,5, "helperStatefulDispatchWriteDone",
1513 CommIoCbPtrFun(helperStatefulDispatchWriteDone
, srv
));
1514 Comm::Write(srv
->writePipe
, r
->request
.buf
, strlen(r
->request
.buf
), call
, nullptr);
1515 debugs(84, 5, "helperStatefulDispatch: Request sent to " <<
1516 hlp
->id_name
<< " #" << srv
->index
<< ", " <<
1517 (int) strlen(r
->request
.buf
) << " bytes");
1520 ++ srv
->stats
.pending
;
1521 ++ hlp
->stats
.requests
;
1525 helperKickQueue(const helper::Pointer
&hlp
)
1530 while ((srv
= GetFirstAvailable(hlp
)) && (r
= hlp
->nextRequest()))
1531 helperDispatch(srv
, r
);
1535 helperStatefulKickQueue(const statefulhelper::Pointer
&hlp
)
1538 helper_stateful_server
*srv
;
1539 while ((srv
= StatefulGetFirstAvailable(hlp
)) && (r
= hlp
->nextRequest())) {
1540 debugs(84, 5, "found srv-" << srv
->index
);
1541 hlp
->reserveServer(srv
);
1542 helperStatefulDispatch(srv
, r
);
1547 helperStatefulServerDone(helper_stateful_server
* srv
)
1549 if (!srv
->flags
.shutdown
) {
1550 helperStatefulKickQueue(srv
->parent
);
1551 } else if (!srv
->flags
.closing
&& !srv
->reserved() && !srv
->stats
.pending
) {
1552 srv
->closeWritePipeSafely(srv
->parent
->id_name
);
1558 helper_server::checkForTimedOutRequests(bool const retry
)
1560 assert(parent
->childs
.concurrency
);
1561 while(!requests
.empty() && requests
.front()->request
.timedOut(parent
->timeout
)) {
1562 Helper::Xaction
*r
= requests
.front();
1563 RequestIndex::iterator it
;
1564 it
= requestsIndex
.find(r
->request
.Id
);
1565 assert(it
!= requestsIndex
.end());
1566 requestsIndex
.erase(it
);
1567 requests
.pop_front();
1568 debugs(84, 2, "Request " << r
->request
.Id
<< " timed-out, remove it from queue");
1570 bool retried
= false;
1571 if (retry
&& r
->request
.retries
< MAX_RETRIES
&& cbdataReferenceValid(r
->request
.data
)) {
1572 debugs(84, 2, "Retry request " << r
->request
.Id
);
1573 ++r
->request
.retries
;
1574 parent
->submitRequest(r
);
1576 } else if (cbdataReferenceValidDone(r
->request
.data
, &cbdata
)) {
1577 if (!parent
->onTimedOutResponse
.isEmpty()) {
1578 if (r
->reply
.accumulate(parent
->onTimedOutResponse
.rawContent(), parent
->onTimedOutResponse
.length()))
1579 r
->reply
.finalize();
1581 r
->reply
.result
= Helper::TimedOut
;
1582 r
->request
.callback(cbdata
, r
->reply
);
1584 r
->reply
.result
= Helper::TimedOut
;
1585 r
->request
.callback(cbdata
, r
->reply
);
1590 ++parent
->stats
.timedout
;
1597 helper_server::requestTimeout(const CommTimeoutCbParams
&io
)
1599 debugs(26, 3, io
.conn
);
1600 helper_server
*srv
= static_cast<helper_server
*>(io
.data
);
1602 srv
->checkForTimedOutRequests(srv
->parent
->retryTimedOut
);
1604 debugs(84, 3, io
.conn
<< " establish new helper_server::requestTimeout");
1605 AsyncCall::Pointer timeoutCall
= commCbCall(84, 4, "helper_server::requestTimeout",
1606 CommTimeoutCbPtrFun(helper_server::requestTimeout
, srv
));
1608 const int timeSpent
= srv
->requests
.empty() ? 0 : (squid_curtime
- srv
->requests
.front()->request
.dispatch_time
.tv_sec
);
1609 const int timeLeft
= max(1, (static_cast<int>(srv
->parent
->timeout
) - timeSpent
));
1611 commSetConnTimeout(io
.conn
, timeLeft
, timeoutCall
);