2 * Copyright (C) 1996-2016 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"
15 #include "comm/Connection.h"
16 #include "comm/Read.h"
17 #include "comm/Write.h"
20 #include "format/Quoting.h"
22 #include "helper/Reply.h"
23 #include "helper/Request.h"
25 #include "SquidConfig.h"
27 #include "SquidMath.h"
28 #include "SquidTime.h"
32 // helper_stateful_server::data uses explicit alloc()/freeOne() */
35 #define HELPER_MAX_ARGS 64
37 /// The maximum allowed request retries.
40 /** Initial Squid input buffer size. Helper responses may exceed this, and
41 * Squid will grow the input buffer as needed, up to ReadBufMaxSize.
43 const size_t ReadBufMinSize(4*1024);
45 /** Maximum safe size of a helper-to-Squid response message plus one.
46 * Squid will warn and close the stream if a helper sends a too-big response.
47 * ssl_crtd helper is known to produce responses of at least 10KB in size.
48 * Some undocumented helpers are known to produce responses exceeding 8KB.
50 const size_t ReadBufMaxSize(32*1024);
52 static IOCB helperHandleRead
;
53 static IOCB helperStatefulHandleRead
;
54 static void helperServerFree(helper_server
*srv
);
55 static void helperStatefulServerFree(helper_stateful_server
*srv
);
56 static void Enqueue(helper
* hlp
, Helper::Request
*);
57 static helper_server
*GetFirstAvailable(helper
* hlp
);
58 static helper_stateful_server
*StatefulGetFirstAvailable(statefulhelper
* hlp
);
59 static void helperDispatch(helper_server
* srv
, Helper::Request
* r
);
60 static void helperStatefulDispatch(helper_stateful_server
* srv
, Helper::Request
* r
);
61 static void helperKickQueue(helper
* hlp
);
62 static void helperStatefulKickQueue(statefulhelper
* hlp
);
63 static void helperStatefulServerDone(helper_stateful_server
* srv
);
64 static void StatefulEnqueue(statefulhelper
* hlp
, Helper::Request
* r
);
66 CBDATA_CLASS_INIT(helper
);
67 CBDATA_CLASS_INIT(helper_server
);
68 CBDATA_CLASS_INIT(statefulhelper
);
69 CBDATA_CLASS_INIT(helper_stateful_server
);
71 InstanceIdDefinitions(HelperServerBase
, "Hlpr");
74 HelperServerBase::initStats()
84 HelperServerBase::closePipesSafely(const char *id_name
)
87 shutdown(writePipe
->fd
, SD_BOTH
);
91 if (readPipe
->fd
== writePipe
->fd
)
99 if (WaitForSingleObject(hIpc
, 5000) != WAIT_OBJECT_0
) {
101 debugs(84, DBG_IMPORTANT
, "WARNING: " << id_name
<<
102 " #" << index
<< " (PID " << (long int)pid
<< ") didn't exit in 5 seconds");
110 HelperServerBase::closeWritePipeSafely(const char *id_name
)
113 shutdown(writePipe
->fd
, (readPipe
->fd
== writePipe
->fd
? SD_BOTH
: SD_SEND
));
116 flags
.closing
= true;
117 if (readPipe
->fd
== writePipe
->fd
)
123 if (WaitForSingleObject(hIpc
, 5000) != WAIT_OBJECT_0
) {
125 debugs(84, DBG_IMPORTANT
, "WARNING: " << id_name
<<
126 " #" << index
<< " (PID " << (long int)pid
<< ") didn't exit in 5 seconds");
134 helperOpenServers(helper
* hlp
)
140 const char *args
[HELPER_MAX_ARGS
+1]; // save space for a NULL terminator
141 char fd_note_buf
[FD_DESC_SZ
];
151 if (hlp
->cmdline
== NULL
)
154 progname
= hlp
->cmdline
->key
;
156 if ((s
= strrchr(progname
, '/')))
157 shortname
= xstrdup(s
+ 1);
159 shortname
= xstrdup(progname
);
161 /* figure out how many new child are actually needed. */
162 int need_new
= hlp
->childs
.needNew();
164 debugs(84, DBG_IMPORTANT
, "helperOpenServers: Starting " << need_new
<< "/" << hlp
->childs
.n_max
<< " '" << shortname
<< "' processes");
167 debugs(84, DBG_IMPORTANT
, "helperOpenServers: No '" << shortname
<< "' processes needed.");
170 procname
= (char *)xmalloc(strlen(shortname
) + 3);
172 snprintf(procname
, strlen(shortname
) + 3, "(%s)", shortname
);
174 args
[nargs
] = procname
;
177 for (w
= hlp
->cmdline
->next
; w
&& nargs
< HELPER_MAX_ARGS
; w
= w
->next
) {
178 args
[nargs
] = w
->key
;
185 assert(nargs
<= HELPER_MAX_ARGS
);
187 for (k
= 0; k
< need_new
; ++k
) {
190 pid
= ipcCreate(hlp
->ipc_type
,
200 debugs(84, DBG_IMPORTANT
, "WARNING: Cannot run '" << progname
<< "' process.");
204 ++ hlp
->childs
.n_running
;
205 ++ hlp
->childs
.n_active
;
206 srv
= new helper_server
;
210 srv
->addr
= hlp
->addr
;
211 srv
->readPipe
= new Comm::Connection
;
212 srv
->readPipe
->fd
= rfd
;
213 srv
->writePipe
= new Comm::Connection
;
214 srv
->writePipe
->fd
= wfd
;
215 srv
->rbuf
= (char *)memAllocBuf(ReadBufMinSize
, &srv
->rbuf_sz
);
216 srv
->wqueue
= new MemBuf
;
218 srv
->nextRequestId
= 0;
219 srv
->parent
= cbdataReference(hlp
);
220 dlinkAddTail(srv
, &srv
->link
, &hlp
->servers
);
223 snprintf(fd_note_buf
, FD_DESC_SZ
, "%s #%d", shortname
, k
+ 1);
224 fd_note(rfd
, fd_note_buf
);
226 snprintf(fd_note_buf
, FD_DESC_SZ
, "reading %s #%d", shortname
, k
+ 1);
227 fd_note(rfd
, fd_note_buf
);
228 snprintf(fd_note_buf
, FD_DESC_SZ
, "writing %s #%d", shortname
, k
+ 1);
229 fd_note(wfd
, fd_note_buf
);
232 commSetNonBlocking(rfd
);
235 commSetNonBlocking(wfd
);
237 AsyncCall::Pointer closeCall
= asyncCall(5,4, "helperServerFree", cbdataDialer(helperServerFree
, srv
));
238 comm_add_close_handler(rfd
, closeCall
);
240 if (hlp
->timeout
&& hlp
->childs
.concurrency
) {
241 AsyncCall::Pointer timeoutCall
= commCbCall(84, 4, "helper_server::requestTimeout",
242 CommTimeoutCbPtrFun(helper_server::requestTimeout
, srv
));
243 commSetConnTimeout(srv
->readPipe
, hlp
->timeout
, timeoutCall
);
246 AsyncCall::Pointer call
= commCbCall(5,4, "helperHandleRead",
247 CommIoCbPtrFun(helperHandleRead
, srv
));
248 comm_read(srv
->readPipe
, srv
->rbuf
, srv
->rbuf_sz
- 1, call
);
251 hlp
->last_restart
= squid_curtime
;
252 safe_free(shortname
);
254 helperKickQueue(hlp
);
260 * helperStatefulOpenServers: create the stateful child helper processes
263 helperStatefulOpenServers(statefulhelper
* hlp
)
266 const char *args
[HELPER_MAX_ARGS
+1]; // save space for a NULL terminator
267 char fd_note_buf
[FD_DESC_SZ
];
270 if (hlp
->cmdline
== NULL
)
273 if (hlp
->childs
.concurrency
)
274 debugs(84, DBG_CRITICAL
, "ERROR: concurrency= is not yet supported for stateful helpers ('" << hlp
->cmdline
<< "')");
276 char *progname
= hlp
->cmdline
->key
;
279 if ((s
= strrchr(progname
, '/')))
280 shortname
= xstrdup(s
+ 1);
282 shortname
= xstrdup(progname
);
284 /* figure out haw mant new helpers are needed. */
285 int need_new
= hlp
->childs
.needNew();
287 debugs(84, DBG_IMPORTANT
, "helperOpenServers: Starting " << need_new
<< "/" << hlp
->childs
.n_max
<< " '" << shortname
<< "' processes");
290 debugs(84, DBG_IMPORTANT
, "helperStatefulOpenServers: No '" << shortname
<< "' processes needed.");
293 char *procname
= (char *)xmalloc(strlen(shortname
) + 3);
295 snprintf(procname
, strlen(shortname
) + 3, "(%s)", shortname
);
297 args
[nargs
] = procname
;
300 for (wordlist
*w
= hlp
->cmdline
->next
; w
&& nargs
< HELPER_MAX_ARGS
; w
= w
->next
) {
301 args
[nargs
] = w
->key
;
308 assert(nargs
<= HELPER_MAX_ARGS
);
310 for (int k
= 0; k
< need_new
; ++k
) {
315 pid_t pid
= ipcCreate(hlp
->ipc_type
,
325 debugs(84, DBG_IMPORTANT
, "WARNING: Cannot run '" << progname
<< "' process.");
329 ++ hlp
->childs
.n_running
;
330 ++ hlp
->childs
.n_active
;
331 helper_stateful_server
*srv
= new helper_stateful_server
;
334 srv
->flags
.reserved
= false;
336 srv
->addr
= hlp
->addr
;
337 srv
->readPipe
= new Comm::Connection
;
338 srv
->readPipe
->fd
= rfd
;
339 srv
->writePipe
= new Comm::Connection
;
340 srv
->writePipe
->fd
= wfd
;
341 srv
->rbuf
= (char *)memAllocBuf(ReadBufMinSize
, &srv
->rbuf_sz
);
343 srv
->parent
= cbdataReference(hlp
);
345 if (hlp
->datapool
!= NULL
)
346 srv
->data
= hlp
->datapool
->alloc();
348 dlinkAddTail(srv
, &srv
->link
, &hlp
->servers
);
351 snprintf(fd_note_buf
, FD_DESC_SZ
, "%s #%d", shortname
, k
+ 1);
352 fd_note(rfd
, fd_note_buf
);
354 snprintf(fd_note_buf
, FD_DESC_SZ
, "reading %s #%d", shortname
, k
+ 1);
355 fd_note(rfd
, fd_note_buf
);
356 snprintf(fd_note_buf
, FD_DESC_SZ
, "writing %s #%d", shortname
, k
+ 1);
357 fd_note(wfd
, fd_note_buf
);
360 commSetNonBlocking(rfd
);
363 commSetNonBlocking(wfd
);
365 AsyncCall::Pointer closeCall
= asyncCall(5,4, "helperStatefulServerFree", cbdataDialer(helperStatefulServerFree
, srv
));
366 comm_add_close_handler(rfd
, closeCall
);
368 AsyncCall::Pointer call
= commCbCall(5,4, "helperStatefulHandleRead",
369 CommIoCbPtrFun(helperStatefulHandleRead
, srv
));
370 comm_read(srv
->readPipe
, srv
->rbuf
, srv
->rbuf_sz
- 1, call
);
373 hlp
->last_restart
= squid_curtime
;
374 safe_free(shortname
);
376 helperStatefulKickQueue(hlp
);
380 helper::submitRequest(Helper::Request
*r
)
384 if ((srv
= GetFirstAvailable(this)))
385 helperDispatch(srv
, r
);
391 } else if (!full_time
) {
392 debugs(84, 3, id_name
<< " queue became full");
393 full_time
= squid_curtime
;
398 helperSubmit(helper
* hlp
, const char *buf
, HLPCB
* callback
, void *data
)
401 debugs(84, 3, "helperSubmit: hlp == NULL");
402 Helper::Reply nilReply
;
403 callback(data
, nilReply
);
407 hlp
->submit(buf
, callback
, data
);
411 helper::queueFull() const {
412 return stats
.queue_size
> static_cast<int>(childs
.queue_size
);
415 /// prepares the helper for request submission via trySubmit() or helperSubmit()
416 /// currently maintains full_time and kills Squid if the helper remains full for too long
422 else if (!full_time
) // may happen here if reconfigure decreases capacity
423 full_time
= squid_curtime
;
424 else if (squid_curtime
- full_time
> 180)
425 fatalf("Too many queued %s requests", id_name
);
429 helper::trySubmit(const char *buf
, HLPCB
* callback
, void *data
)
434 debugs(84, DBG_IMPORTANT
, id_name
<< " drops request due to a full queue");
435 return false; // request was ignored
438 submit(buf
, callback
, data
); // will send or queue
439 return true; // request submitted or queued
442 /// dispatches or enqueues a helper requests; does not enforce queue limits
444 helper::submit(const char *buf
, HLPCB
* callback
, void *data
)
446 Helper::Request
*r
= new Helper::Request(callback
, data
, buf
);
448 debugs(84, DBG_DATA
, Raw("buf", buf
, strlen(buf
)));
451 /// lastserver = "server last used as part of a reserved request sequence"
453 helperStatefulSubmit(statefulhelper
* hlp
, const char *buf
, HLPCB
* callback
, void *data
, helper_stateful_server
* lastserver
)
456 debugs(84, 3, "helperStatefulSubmit: hlp == NULL");
457 Helper::Reply nilReply
;
458 callback(data
, nilReply
);
462 hlp
->submit(buf
, callback
, data
, lastserver
);
465 void statefulhelper::submit(const char *buf
, HLPCB
* callback
, void *data
, helper_stateful_server
* lastserver
)
467 Helper::Request
*r
= new Helper::Request(callback
, data
, buf
);
469 if ((buf
!= NULL
) && lastserver
) {
470 debugs(84, 5, "StatefulSubmit with lastserver " << lastserver
);
471 assert(lastserver
->flags
.reserved
);
472 assert(!lastserver
->requests
.size());
474 debugs(84, 5, "StatefulSubmit dispatching");
475 helperStatefulDispatch(lastserver
, r
);
477 helper_stateful_server
*srv
;
478 if ((srv
= StatefulGetFirstAvailable(this))) {
479 helperStatefulDispatch(srv
, r
);
481 StatefulEnqueue(this, r
);
484 debugs(84, DBG_DATA
, "placeholder: '" << r
->placeholder
<<
485 "', " << Raw("buf", buf
, (!buf
?0:strlen(buf
))));
489 } else if (!full_time
) {
490 debugs(84, 3, id_name
<< " queue became full");
491 full_time
= squid_curtime
;
498 * helperStatefulReleaseServer tells the helper that whoever was
499 * using it no longer needs its services.
502 helperStatefulReleaseServer(helper_stateful_server
* srv
)
504 debugs(84, 3, HERE
<< "srv-" << srv
->index
<< " flags.reserved = " << srv
->flags
.reserved
);
505 if (!srv
->flags
.reserved
)
508 ++ srv
->stats
.releases
;
510 srv
->flags
.reserved
= false;
512 helperStatefulServerDone(srv
);
515 /** return a pointer to the stateful routines data area */
517 helperStatefulServerGetData(helper_stateful_server
* srv
)
523 helper::packStatsInto(Packable
*p
, const char *label
) const
526 p
->appendf("%s:\n", label
);
528 p
->appendf(" program: %s\n", cmdline
->key
);
529 p
->appendf(" number active: %d of %d (%d shutting down)\n", childs
.n_active
, childs
.n_max
, (childs
.n_running
- childs
.n_active
));
530 p
->appendf(" requests sent: %d\n", stats
.requests
);
531 p
->appendf(" replies received: %d\n", stats
.replies
);
532 p
->appendf(" requests timedout: %d\n", stats
.timedout
);
533 p
->appendf(" queue length: %d\n", stats
.queue_size
);
534 p
->appendf(" avg service time: %d msec\n", stats
.avg_svc_time
);
536 p
->appendf("%7s\t%7s\t%7s\t%11s\t%11s\t%11s\t%6s\t%7s\t%7s\t%7s\n",
548 for (dlink_node
*link
= servers
.head
; link
; link
= link
->next
) {
549 HelperServerBase
*srv
= static_cast<HelperServerBase
*>(link
->data
);
551 Helper::Request
*request
= srv
->requests
.empty() ? NULL
: srv
->requests
.front();
552 double tt
= 0.001 * (request
? tvSubMsec(request
->dispatch_time
, current_time
) : tvSubMsec(srv
->dispatch_time
, srv
->answer_time
));
553 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",
560 srv
->stats
.pending
? 'B' : ' ',
561 srv
->flags
.writing
? 'W' : ' ',
562 srv
->flags
.closing
? 'C' : ' ',
563 srv
->flags
.reserved
? 'R' : ' ',
564 srv
->flags
.shutdown
? 'S' : ' ',
565 request
&& request
->placeholder
? 'P' : ' ',
568 request
? Format::QuoteMimeBlob(request
->buf
) : "(none)");
571 p
->append("\nFlags key:\n"
576 " S\tSHUTDOWN PENDING\n"
577 " P\tPLACEHOLDER\n", 101);
581 helperShutdown(helper
* hlp
)
583 dlink_node
*link
= hlp
->servers
.head
;
587 srv
= (helper_server
*)link
->data
;
590 if (srv
->flags
.shutdown
) {
591 debugs(84, 3, "helperShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " has already SHUT DOWN.");
595 assert(hlp
->childs
.n_active
> 0);
596 -- hlp
->childs
.n_active
;
597 srv
->flags
.shutdown
= true; /* request it to shut itself down */
599 if (srv
->flags
.closing
) {
600 debugs(84, 3, "helperShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is CLOSING.");
604 if (srv
->stats
.pending
) {
605 debugs(84, 3, "helperShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is BUSY.");
609 debugs(84, 3, "helperShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " shutting down.");
610 /* the rest of the details is dealt with in the helperServerFree
613 srv
->closePipesSafely(hlp
->id_name
);
618 helperStatefulShutdown(statefulhelper
* hlp
)
620 dlink_node
*link
= hlp
->servers
.head
;
621 helper_stateful_server
*srv
;
624 srv
= (helper_stateful_server
*)link
->data
;
627 if (srv
->flags
.shutdown
) {
628 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " has already SHUT DOWN.");
632 assert(hlp
->childs
.n_active
> 0);
633 -- hlp
->childs
.n_active
;
634 srv
->flags
.shutdown
= true; /* request it to shut itself down */
636 if (srv
->stats
.pending
) {
637 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is BUSY.");
641 if (srv
->flags
.closing
) {
642 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is CLOSING.");
646 if (srv
->flags
.reserved
) {
648 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is RESERVED. Closing anyway.");
650 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " is RESERVED. Not Shutting Down Yet.");
655 debugs(84, 3, "helperStatefulShutdown: " << hlp
->id_name
<< " #" << srv
->index
<< " shutting down.");
657 /* the rest of the details is dealt with in the helperStatefulServerFree
660 srv
->closePipesSafely(hlp
->id_name
);
666 /* note, don't free id_name, it probably points to static memory */
668 // TODO: if the queue is not empty it will leak Helper::Request's
670 debugs(84, DBG_CRITICAL
, "WARNING: freeing " << id_name
<< " helper with " << stats
.queue_size
<< " requests queued");
673 /* ====================================================================== */
674 /* LOCAL FUNCTIONS */
675 /* ====================================================================== */
678 helperServerFree(helper_server
*srv
)
680 helper
*hlp
= srv
->parent
;
681 int concurrency
= hlp
->childs
.concurrency
;
687 memFreeBuf(srv
->rbuf_sz
, srv
->rbuf
);
691 srv
->wqueue
->clean();
695 srv
->writebuf
->clean();
696 delete srv
->writebuf
;
697 srv
->writebuf
= NULL
;
700 if (Comm::IsConnOpen(srv
->writePipe
))
701 srv
->closeWritePipeSafely(hlp
->id_name
);
703 dlinkDelete(&srv
->link
, &hlp
->servers
);
705 assert(hlp
->childs
.n_running
> 0);
706 -- hlp
->childs
.n_running
;
708 if (!srv
->flags
.shutdown
) {
709 assert(hlp
->childs
.n_active
> 0);
710 -- hlp
->childs
.n_active
;
711 debugs(84, DBG_CRITICAL
, "WARNING: " << hlp
->id_name
<< " #" << srv
->index
<< " exited");
713 if (hlp
->childs
.needNew() > 0) {
714 debugs(80, DBG_IMPORTANT
, "Too few " << hlp
->id_name
<< " processes are running (need " << hlp
->childs
.needNew() << "/" << hlp
->childs
.n_max
<< ")");
716 if (hlp
->childs
.n_active
< hlp
->childs
.n_startup
&& hlp
->last_restart
> squid_curtime
- 30) {
717 if (srv
->stats
.replies
< 1)
718 fatalf("The %s helpers are crashing too rapidly, need help!\n", hlp
->id_name
);
720 debugs(80, DBG_CRITICAL
, "ERROR: The " << hlp
->id_name
<< " helpers are crashing too rapidly, need help!");
723 debugs(80, DBG_IMPORTANT
, "Starting new helpers");
724 helperOpenServers(hlp
);
728 while (!srv
->requests
.empty()) {
729 // XXX: re-schedule these on another helper?
730 Helper::Request
*r
= srv
->requests
.front();
731 srv
->requests
.pop_front();
734 if (cbdataReferenceValidDone(r
->data
, &cbdata
)) {
735 Helper::Reply nilReply
;
736 r
->callback(cbdata
, nilReply
);
741 srv
->requestsIndex
.clear();
743 cbdataReferenceDone(srv
->parent
);
748 helperStatefulServerFree(helper_stateful_server
*srv
)
750 statefulhelper
*hlp
= srv
->parent
;
753 memFreeBuf(srv
->rbuf_sz
, srv
->rbuf
);
758 srv
->wqueue
->clean();
764 /* TODO: walk the local queue of requests and carry them all out */
765 if (Comm::IsConnOpen(srv
->writePipe
))
766 srv
->closeWritePipeSafely(hlp
->id_name
);
768 dlinkDelete(&srv
->link
, &hlp
->servers
);
770 assert(hlp
->childs
.n_running
> 0);
771 -- hlp
->childs
.n_running
;
773 if (!srv
->flags
.shutdown
) {
774 assert( hlp
->childs
.n_active
> 0);
775 -- hlp
->childs
.n_active
;
776 debugs(84, DBG_CRITICAL
, "WARNING: " << hlp
->id_name
<< " #" << srv
->index
<< " exited");
778 if (hlp
->childs
.needNew() > 0) {
779 debugs(80, DBG_IMPORTANT
, "Too few " << hlp
->id_name
<< " processes are running (need " << hlp
->childs
.needNew() << "/" << hlp
->childs
.n_max
<< ")");
781 if (hlp
->childs
.n_active
< hlp
->childs
.n_startup
&& hlp
->last_restart
> squid_curtime
- 30) {
782 if (srv
->stats
.replies
< 1)
783 fatalf("The %s helpers are crashing too rapidly, need help!\n", hlp
->id_name
);
785 debugs(80, DBG_CRITICAL
, "ERROR: The " << hlp
->id_name
<< " helpers are crashing too rapidly, need help!");
788 debugs(80, DBG_IMPORTANT
, "Starting new helpers");
789 helperStatefulOpenServers(hlp
);
793 while (!srv
->requests
.empty()) {
794 // XXX: re-schedule these on another helper?
795 Helper::Request
*r
= srv
->requests
.front();
796 srv
->requests
.pop_front();
799 if (cbdataReferenceValidDone(r
->data
, &cbdata
)) {
800 Helper::Reply nilReply
;
801 r
->callback(cbdata
, nilReply
);
807 if (srv
->data
!= NULL
)
808 hlp
->datapool
->freeOne(srv
->data
);
810 cbdataReferenceDone(srv
->parent
);
815 /// Calls back with a pointer to the buffer with the helper output
817 helperReturnBuffer(int request_number
, helper_server
* srv
, helper
* hlp
, char * msg
, char * msg_end
)
819 Helper::Request
*r
= NULL
;
820 helper_server::RequestIndex::iterator it
;
821 if (hlp
->childs
.concurrency
) {
822 // If concurency supported retrieve request from ID
823 it
= srv
->requestsIndex
.find(request_number
);
824 if (it
!= srv
->requestsIndex
.end()) {
826 srv
->requests
.erase(it
->second
);
827 srv
->requestsIndex
.erase(it
);
829 } else if(!srv
->requests
.empty()) {
830 // Else get the first request from queue, if any
831 r
= srv
->requests
.front();
832 srv
->requests
.pop_front();
836 HLPCB
*callback
= r
->callback
;
841 if (cbdataReferenceValidDone(r
->data
, &cbdata
)) {
842 Helper::Reply
response(msg
, (msg_end
-msg
));
843 if (response
.result
== Helper::BrokenHelper
&& r
->retries
< MAX_RETRIES
) {
844 debugs(84, DBG_IMPORTANT
, "ERROR: helper: " << response
<< ", attempt #" << (r
->retries
+ 1) << " of 2");
847 callback(cbdata
, response
);
850 -- srv
->stats
.pending
;
851 ++ srv
->stats
.replies
;
853 ++ hlp
->stats
.replies
;
855 srv
->answer_time
= current_time
;
857 srv
->dispatch_time
= r
->dispatch_time
;
859 hlp
->stats
.avg_svc_time
=
860 Math::intAverage(hlp
->stats
.avg_svc_time
,
861 tvSubMsec(r
->dispatch_time
, current_time
),
862 hlp
->stats
.replies
, REDIRECT_AV_FACTOR
);
866 hlp
->submitRequest(r
);
869 } else if (srv
->stats
.timedout
) {
870 debugs(84, 3, "Timedout reply received for request-ID: " << request_number
<< " , ignore");
872 debugs(84, DBG_IMPORTANT
, "helperHandleRead: unexpected reply on channel " <<
873 request_number
<< " from " << hlp
->id_name
<< " #" << srv
->index
<<
874 " '" << srv
->rbuf
<< "'");
877 if (hlp
->timeout
&& hlp
->childs
.concurrency
)
878 srv
->checkForTimedOutRequests(hlp
->retryTimedOut
);
880 if (!srv
->flags
.shutdown
) {
881 helperKickQueue(hlp
);
882 } else if (!srv
->flags
.closing
&& !srv
->stats
.pending
) {
883 srv
->flags
.closing
=true;
884 srv
->writePipe
->close();
889 helperHandleRead(const Comm::ConnectionPointer
&conn
, char *, size_t len
, Comm::Flag flag
, int, void *data
)
892 helper_server
*srv
= (helper_server
*)data
;
893 helper
*hlp
= srv
->parent
;
894 assert(cbdataReferenceValid(data
));
896 /* Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us */
898 if (flag
== Comm::ERR_CLOSING
) {
902 assert(conn
->fd
== srv
->readPipe
->fd
);
904 debugs(84, 5, "helperHandleRead: " << len
<< " bytes from " << hlp
->id_name
<< " #" << srv
->index
);
906 if (flag
!= Comm::OK
|| len
== 0) {
907 srv
->closePipesSafely(hlp
->id_name
);
912 srv
->rbuf
[srv
->roffset
] = '\0';
913 debugs(84, DBG_DATA
, Raw("accumulated", srv
->rbuf
, srv
->roffset
));
915 if (!srv
->stats
.pending
&& !srv
->stats
.timedout
) {
916 /* someone spoke without being spoken to */
917 debugs(84, DBG_IMPORTANT
, "helperHandleRead: unexpected read from " <<
918 hlp
->id_name
<< " #" << srv
->index
<< ", " << (int)len
<<
919 " bytes '" << srv
->rbuf
<< "'");
925 while ((t
= strchr(srv
->rbuf
, hlp
->eom
))) {
926 /* end of reply found */
927 char *msg
= srv
->rbuf
;
930 debugs(84, 3, "helperHandleRead: end of reply found");
932 if (t
> srv
->rbuf
&& t
[-1] == '\r' && hlp
->eom
== '\n') {
934 // rewind to the \r octet which is the real terminal now
935 // and remember that we have to skip forward 2 places now.
942 if (hlp
->childs
.concurrency
) {
943 i
= strtol(msg
, &msg
, 10);
945 while (*msg
&& xisspace(*msg
))
949 helperReturnBuffer(i
, srv
, hlp
, msg
, t
);
950 srv
->roffset
-= (t
- srv
->rbuf
) + skip
;
951 memmove(srv
->rbuf
, t
+ skip
, srv
->roffset
);
952 srv
->rbuf
[srv
->roffset
] = '\0';
955 if (Comm::IsConnOpen(srv
->readPipe
) && !fd_table
[srv
->readPipe
->fd
].closing()) {
956 int spaceSize
= srv
->rbuf_sz
- srv
->roffset
- 1;
957 assert(spaceSize
>= 0);
959 // grow the input buffer if needed and possible
960 if (!spaceSize
&& srv
->rbuf_sz
+ 4096 <= ReadBufMaxSize
) {
961 srv
->rbuf
= (char *)memReallocBuf(srv
->rbuf
, srv
->rbuf_sz
+ 4096, &srv
->rbuf_sz
);
962 debugs(84, 3, HERE
<< "Grew read buffer to " << srv
->rbuf_sz
);
963 spaceSize
= srv
->rbuf_sz
- srv
->roffset
- 1;
964 assert(spaceSize
>= 0);
967 // quit reading if there is no space left
969 debugs(84, DBG_IMPORTANT
, "ERROR: Disconnecting from a " <<
970 "helper that overflowed " << srv
->rbuf_sz
<< "-byte " <<
971 "Squid input buffer: " << hlp
->id_name
<< " #" << srv
->index
);
972 srv
->closePipesSafely(hlp
->id_name
);
976 AsyncCall::Pointer call
= commCbCall(5,4, "helperHandleRead",
977 CommIoCbPtrFun(helperHandleRead
, srv
));
978 comm_read(srv
->readPipe
, srv
->rbuf
+ srv
->roffset
, spaceSize
, call
);
983 helperStatefulHandleRead(const Comm::ConnectionPointer
&conn
, char *, size_t len
, Comm::Flag flag
, int, void *data
)
986 helper_stateful_server
*srv
= (helper_stateful_server
*)data
;
987 statefulhelper
*hlp
= srv
->parent
;
988 assert(cbdataReferenceValid(data
));
990 /* Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us */
992 if (flag
== Comm::ERR_CLOSING
) {
996 assert(conn
->fd
== srv
->readPipe
->fd
);
998 debugs(84, 5, "helperStatefulHandleRead: " << len
<< " bytes from " <<
999 hlp
->id_name
<< " #" << srv
->index
);
1001 if (flag
!= Comm::OK
|| len
== 0) {
1002 srv
->closePipesSafely(hlp
->id_name
);
1006 srv
->roffset
+= len
;
1007 srv
->rbuf
[srv
->roffset
] = '\0';
1008 Helper::Request
*r
= srv
->requests
.front();
1009 debugs(84, DBG_DATA
, Raw("accumulated", srv
->rbuf
, srv
->roffset
));
1012 /* someone spoke without being spoken to */
1013 debugs(84, DBG_IMPORTANT
, "helperStatefulHandleRead: unexpected read from " <<
1014 hlp
->id_name
<< " #" << srv
->index
<< ", " << (int)len
<<
1015 " bytes '" << srv
->rbuf
<< "'");
1020 if ((t
= strchr(srv
->rbuf
, hlp
->eom
))) {
1021 /* end of reply found */
1022 srv
->requests
.pop_front(); // we already have it in 'r'
1025 debugs(84, 3, "helperStatefulHandleRead: end of reply found");
1027 if (t
> srv
->rbuf
&& t
[-1] == '\r' && hlp
->eom
== '\n') {
1029 // rewind to the \r octet which is the real terminal now
1030 // and remember that we have to skip forward 2 places now.
1037 if (r
&& cbdataReferenceValid(r
->data
)) {
1038 Helper::Reply
res(srv
->rbuf
, (t
- srv
->rbuf
));
1039 res
.whichServer
= srv
;
1040 r
->callback(r
->data
, res
);
1042 debugs(84, DBG_IMPORTANT
, "StatefulHandleRead: no callback data registered");
1045 // only skip off the \0's _after_ passing its location in Helper::Reply above
1049 * BUG: the below assumes that only one response per read() was received and discards any octets remaining.
1050 * Doing this prohibits concurrency support with multiple replies per read().
1051 * TODO: check that read() setup on these buffers pays attention to roffest!=0
1052 * TODO: check that replies bigger than the buffer are discarded and do not to affect future replies
1057 -- srv
->stats
.pending
;
1058 ++ srv
->stats
.replies
;
1060 ++ hlp
->stats
.replies
;
1061 srv
->answer_time
= current_time
;
1062 hlp
->stats
.avg_svc_time
=
1063 Math::intAverage(hlp
->stats
.avg_svc_time
,
1064 tvSubMsec(srv
->dispatch_time
, current_time
),
1065 hlp
->stats
.replies
, REDIRECT_AV_FACTOR
);
1068 helperStatefulServerDone(srv
);
1070 helperStatefulReleaseServer(srv
);
1073 if (Comm::IsConnOpen(srv
->readPipe
) && !fd_table
[srv
->readPipe
->fd
].closing()) {
1074 int spaceSize
= srv
->rbuf_sz
- srv
->roffset
- 1;
1075 assert(spaceSize
>= 0);
1077 // grow the input buffer if needed and possible
1078 if (!spaceSize
&& srv
->rbuf_sz
+ 4096 <= ReadBufMaxSize
) {
1079 srv
->rbuf
= (char *)memReallocBuf(srv
->rbuf
, srv
->rbuf_sz
+ 4096, &srv
->rbuf_sz
);
1080 debugs(84, 3, HERE
<< "Grew read buffer to " << srv
->rbuf_sz
);
1081 spaceSize
= srv
->rbuf_sz
- srv
->roffset
- 1;
1082 assert(spaceSize
>= 0);
1085 // quit reading if there is no space left
1087 debugs(84, DBG_IMPORTANT
, "ERROR: Disconnecting from a " <<
1088 "helper that overflowed " << srv
->rbuf_sz
<< "-byte " <<
1089 "Squid input buffer: " << hlp
->id_name
<< " #" << srv
->index
);
1090 srv
->closePipesSafely(hlp
->id_name
);
1094 AsyncCall::Pointer call
= commCbCall(5,4, "helperStatefulHandleRead",
1095 CommIoCbPtrFun(helperStatefulHandleRead
, srv
));
1096 comm_read(srv
->readPipe
, srv
->rbuf
+ srv
->roffset
, spaceSize
, call
);
1100 /// Handles a request when all running helpers, if any, are busy.
1102 Enqueue(helper
* hlp
, Helper::Request
* r
)
1105 ++ hlp
->stats
.queue_size
;
1107 /* do this first so idle=N has a chance to grow the child pool before it hits critical. */
1108 if (hlp
->childs
.needNew() > 0) {
1109 debugs(84, DBG_CRITICAL
, "Starting new " << hlp
->id_name
<< " helpers...");
1110 helperOpenServers(hlp
);
1114 if (hlp
->stats
.queue_size
< (int)hlp
->childs
.queue_size
)
1117 if (squid_curtime
- hlp
->last_queue_warn
< 600)
1120 if (shutting_down
|| reconfiguring
)
1123 hlp
->last_queue_warn
= squid_curtime
;
1125 debugs(84, DBG_CRITICAL
, "WARNING: All " << hlp
->childs
.n_active
<< "/" << hlp
->childs
.n_max
<< " " << hlp
->id_name
<< " processes are busy.");
1126 debugs(84, DBG_CRITICAL
, "WARNING: " << hlp
->stats
.queue_size
<< " pending requests queued");
1127 debugs(84, DBG_CRITICAL
, "WARNING: Consider increasing the number of " << hlp
->id_name
<< " processes in your config file.");
1131 StatefulEnqueue(statefulhelper
* hlp
, Helper::Request
* r
)
1134 ++ hlp
->stats
.queue_size
;
1136 /* do this first so idle=N has a chance to grow the child pool before it hits critical. */
1137 if (hlp
->childs
.needNew() > 0) {
1138 debugs(84, DBG_CRITICAL
, "Starting new " << hlp
->id_name
<< " helpers...");
1139 helperStatefulOpenServers(hlp
);
1143 if (hlp
->stats
.queue_size
< (int)hlp
->childs
.queue_size
)
1146 if (squid_curtime
- hlp
->last_queue_warn
< 600)
1149 if (shutting_down
|| reconfiguring
)
1152 hlp
->last_queue_warn
= squid_curtime
;
1154 debugs(84, DBG_CRITICAL
, "WARNING: All " << hlp
->childs
.n_active
<< "/" << hlp
->childs
.n_max
<< " " << hlp
->id_name
<< " processes are busy.");
1155 debugs(84, DBG_CRITICAL
, "WARNING: " << hlp
->stats
.queue_size
<< " pending requests queued");
1156 debugs(84, DBG_CRITICAL
, "WARNING: Consider increasing the number of " << hlp
->id_name
<< " processes in your config file.");
1160 helper::nextRequest()
1165 auto *r
= queue
.front();
1171 static helper_server
*
1172 GetFirstAvailable(helper
* hlp
)
1176 helper_server
*selected
= NULL
;
1177 debugs(84, 5, "GetFirstAvailable: Running servers " << hlp
->childs
.n_running
);
1179 if (hlp
->childs
.n_running
== 0)
1182 /* Find "least" loaded helper (approx) */
1183 for (n
= hlp
->servers
.head
; n
!= NULL
; n
= n
->next
) {
1184 srv
= (helper_server
*)n
->data
;
1186 if (selected
&& selected
->stats
.pending
<= srv
->stats
.pending
)
1189 if (srv
->flags
.shutdown
)
1192 if (!srv
->stats
.pending
)
1203 /* Check for overload */
1205 debugs(84, 5, "GetFirstAvailable: None available.");
1209 if (selected
->stats
.pending
>= (hlp
->childs
.concurrency
? hlp
->childs
.concurrency
: 1)) {
1210 debugs(84, 3, "GetFirstAvailable: Least-loaded helper is overloaded!");
1214 debugs(84, 5, "GetFirstAvailable: returning srv-" << selected
->index
);
1218 static helper_stateful_server
*
1219 StatefulGetFirstAvailable(statefulhelper
* hlp
)
1222 helper_stateful_server
*srv
= NULL
;
1223 debugs(84, 5, "StatefulGetFirstAvailable: Running servers " << hlp
->childs
.n_running
);
1225 if (hlp
->childs
.n_running
== 0)
1228 for (n
= hlp
->servers
.head
; n
!= NULL
; n
= n
->next
) {
1229 srv
= (helper_stateful_server
*)n
->data
;
1231 if (srv
->stats
.pending
)
1234 if (srv
->flags
.reserved
)
1237 if (srv
->flags
.shutdown
)
1240 debugs(84, 5, "StatefulGetFirstAvailable: returning srv-" << srv
->index
);
1244 debugs(84, 5, "StatefulGetFirstAvailable: None available.");
1249 helperDispatchWriteDone(const Comm::ConnectionPointer
&, char *, size_t, Comm::Flag flag
, int, void *data
)
1251 helper_server
*srv
= (helper_server
*)data
;
1253 srv
->writebuf
->clean();
1254 delete srv
->writebuf
;
1255 srv
->writebuf
= NULL
;
1256 srv
->flags
.writing
= false;
1258 if (flag
!= Comm::OK
) {
1259 /* Helper server has crashed */
1260 debugs(84, DBG_CRITICAL
, "helperDispatch: Helper " << srv
->parent
->id_name
<< " #" << srv
->index
<< " has crashed");
1264 if (!srv
->wqueue
->isNull()) {
1265 srv
->writebuf
= srv
->wqueue
;
1266 srv
->wqueue
= new MemBuf
;
1267 srv
->flags
.writing
= true;
1268 AsyncCall::Pointer call
= commCbCall(5,5, "helperDispatchWriteDone",
1269 CommIoCbPtrFun(helperDispatchWriteDone
, srv
));
1270 Comm::Write(srv
->writePipe
, srv
->writebuf
->content(), srv
->writebuf
->contentSize(), call
, NULL
);
1275 helperDispatch(helper_server
* srv
, Helper::Request
* r
)
1277 helper
*hlp
= srv
->parent
;
1278 const uint64_t reqId
= ++srv
->nextRequestId
;
1280 if (!cbdataReferenceValid(r
->data
)) {
1281 debugs(84, DBG_IMPORTANT
, "helperDispatch: invalid callback data");
1287 helper_server::Requests::iterator it
= srv
->requests
.insert(srv
->requests
.end(), r
);
1288 r
->dispatch_time
= current_time
;
1290 if (srv
->wqueue
->isNull())
1291 srv
->wqueue
->init();
1293 if (hlp
->childs
.concurrency
) {
1294 srv
->requestsIndex
.insert(helper_server::RequestIndex::value_type(reqId
, it
));
1295 assert(srv
->requestsIndex
.size() == srv
->requests
.size());
1296 srv
->wqueue
->appendf("%" PRIu64
" %s", reqId
, r
->buf
);
1298 srv
->wqueue
->append(r
->buf
, strlen(r
->buf
));
1300 if (!srv
->flags
.writing
) {
1301 assert(NULL
== srv
->writebuf
);
1302 srv
->writebuf
= srv
->wqueue
;
1303 srv
->wqueue
= new MemBuf
;
1304 srv
->flags
.writing
= true;
1305 AsyncCall::Pointer call
= commCbCall(5,5, "helperDispatchWriteDone",
1306 CommIoCbPtrFun(helperDispatchWriteDone
, srv
));
1307 Comm::Write(srv
->writePipe
, srv
->writebuf
->content(), srv
->writebuf
->contentSize(), call
, NULL
);
1310 debugs(84, 5, "helperDispatch: Request sent to " << hlp
->id_name
<< " #" << srv
->index
<< ", " << strlen(r
->buf
) << " bytes");
1313 ++ srv
->stats
.pending
;
1314 ++ hlp
->stats
.requests
;
1318 helperStatefulDispatchWriteDone(const Comm::ConnectionPointer
&, char *, size_t, Comm::Flag
, int, void *)
1322 helperStatefulDispatch(helper_stateful_server
* srv
, Helper::Request
* r
)
1324 statefulhelper
*hlp
= srv
->parent
;
1326 if (!cbdataReferenceValid(r
->data
)) {
1327 debugs(84, DBG_IMPORTANT
, "helperStatefulDispatch: invalid callback data");
1329 helperStatefulReleaseServer(srv
);
1333 debugs(84, 9, "helperStatefulDispatch busying helper " << hlp
->id_name
<< " #" << srv
->index
);
1335 if (r
->placeholder
== 1) {
1336 /* a callback is needed before this request can _use_ a helper. */
1337 /* we don't care about releasing this helper. The request NEVER
1338 * gets to the helper. So we throw away the return code */
1339 Helper::Reply nilReply
;
1340 nilReply
.whichServer
= srv
;
1341 r
->callback(r
->data
, nilReply
);
1342 /* throw away the placeholder */
1344 /* and push the queue. Note that the callback may have submitted a new
1345 * request to the helper which is why we test for the request */
1347 if (!srv
->requests
.size())
1348 helperStatefulServerDone(srv
);
1353 srv
->flags
.reserved
= true;
1354 srv
->requests
.push_back(r
);
1355 srv
->dispatch_time
= current_time
;
1356 AsyncCall::Pointer call
= commCbCall(5,5, "helperStatefulDispatchWriteDone",
1357 CommIoCbPtrFun(helperStatefulDispatchWriteDone
, hlp
));
1358 Comm::Write(srv
->writePipe
, r
->buf
, strlen(r
->buf
), call
, NULL
);
1359 debugs(84, 5, "helperStatefulDispatch: Request sent to " <<
1360 hlp
->id_name
<< " #" << srv
->index
<< ", " <<
1361 (int) strlen(r
->buf
) << " bytes");
1364 ++ srv
->stats
.pending
;
1365 ++ hlp
->stats
.requests
;
1369 helperKickQueue(helper
* hlp
)
1374 while ((srv
= GetFirstAvailable(hlp
)) && (r
= hlp
->nextRequest()))
1375 helperDispatch(srv
, r
);
1379 helperStatefulKickQueue(statefulhelper
* hlp
)
1382 helper_stateful_server
*srv
;
1384 while ((srv
= StatefulGetFirstAvailable(hlp
)) && (r
= hlp
->nextRequest()))
1385 helperStatefulDispatch(srv
, r
);
1389 helperStatefulServerDone(helper_stateful_server
* srv
)
1391 if (!srv
->flags
.shutdown
) {
1392 helperStatefulKickQueue(srv
->parent
);
1393 } else if (!srv
->flags
.closing
&& !srv
->flags
.reserved
&& !srv
->stats
.pending
) {
1394 srv
->closeWritePipeSafely(srv
->parent
->id_name
);
1400 helper_server::checkForTimedOutRequests(bool const retry
)
1402 assert(parent
->childs
.concurrency
);
1403 while(!requests
.empty() && requests
.front()->timedOut(parent
->timeout
)) {
1404 Helper::Request
*r
= requests
.front();
1405 RequestIndex::iterator it
;
1406 it
= requestsIndex
.find(r
->Id
);
1407 assert(it
!= requestsIndex
.end());
1408 requestsIndex
.erase(it
);
1409 requests
.pop_front();
1410 debugs(84, 2, "Request " << r
->Id
<< " timed-out, remove it from queue");
1412 bool retried
= false;
1413 if (retry
&& r
->retries
< MAX_RETRIES
&& cbdataReferenceValid(r
->data
)) {
1414 debugs(84, 2, "Retry request " << r
->Id
);
1416 parent
->submitRequest(r
);
1418 } else if (cbdataReferenceValidDone(r
->data
, &cbdata
)) {
1419 if (!parent
->onTimedOutResponse
.isEmpty()) {
1420 // Helper::Reply needs a non const buffer
1421 char *replyMsg
= xstrdup(parent
->onTimedOutResponse
.c_str());
1422 r
->callback(cbdata
, Helper::Reply(replyMsg
, strlen(replyMsg
)));
1425 r
->callback(cbdata
, Helper::Reply(Helper::TimedOut
));
1429 ++parent
->stats
.timedout
;
1436 helper_server::requestTimeout(const CommTimeoutCbParams
&io
)
1438 debugs(26, 3, HERE
<< io
.conn
);
1439 helper_server
*srv
= static_cast<helper_server
*>(io
.data
);
1441 if (!cbdataReferenceValid(srv
))
1444 srv
->checkForTimedOutRequests(srv
->parent
->retryTimedOut
);
1446 debugs(84, 3, HERE
<< io
.conn
<< " establish new helper_server::requestTimeout");
1447 AsyncCall::Pointer timeoutCall
= commCbCall(84, 4, "helper_server::requestTimeout",
1448 CommTimeoutCbPtrFun(helper_server::requestTimeout
, srv
));
1450 const int timeSpent
= srv
->requests
.empty() ? 0 : (squid_curtime
- srv
->requests
.front()->dispatch_time
.tv_sec
);
1451 const int timeLeft
= max(1, (static_cast<int>(srv
->parent
->timeout
) - timeSpent
));
1453 commSetConnTimeout(io
.conn
, timeLeft
, timeoutCall
);