The FreeRADIUS server $Id: f3670dba8951ca10eb4948feb3dc3db9423a334f $
Loading...
Searching...
No Matches
worker.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17 /**
18 * $Id: 0e557e7715e6891e5db2da0928d1879e13ec53db $
19 *
20 * @brief Worker thread functions.
21 * @file io/worker.c
22 *
23 * The "worker" thread is the one responsible for the bulk of the
24 * work done when processing a request. Workers are spawned by the
25 * scheduler, and create a kqueue (KQ) and control-plane
26 * Atomic Queue (AQ) for control-plane communication.
27 *
28 * When a network thread discovers that it needs more workers, it
29 * asks the scheduler for a KQ/AQ combination. The network thread
30 * then creates a channel dedicated to that worker, and sends the
31 * channel to the worker in a "new channel" message. The worker
32 * receives the channel, and sends an ACK back to the network thread.
33 *
34 * The network thread then sends the worker new packets, which the
35 * worker receives and processes.
36 *
37 * When a packet is decoded, it is put into the "runnable" heap, and
38 * also into the timeout sublist. The main loop fr_worker() then
39 * pulls new requests off of this heap and runs them. The main event
40 * loop checks the head of the timeout sublist, and forcefully terminates
41 * any requests which have been running for too long.
42 *
43 * If a request is yielded, it is placed onto the yielded list in
44 * the worker "tracking" data structure.
45 *
46 * @copyright 2016 Alan DeKok (aland@freeradius.org)
47 */
48
49RCSID("$Id: 0e557e7715e6891e5db2da0928d1879e13ec53db $")
50
51#define LOG_PREFIX worker->name
52#define LOG_DST worker->log
53
54#include <freeradius-devel/io/channel.h>
55#include <freeradius-devel/io/listen.h>
56#include <freeradius-devel/io/worker.h>
57#include <freeradius-devel/unlang/base.h>
58#include <freeradius-devel/util/minmax_heap.h>
59#include <freeradius-devel/util/timer.h>
60
61#include <stdalign.h>
62
63#ifdef WITH_VERIFY_PTR
64static void worker_verify(fr_worker_t *worker);
65#define WORKER_VERIFY worker_verify(worker)
66#else
67#define WORKER_VERIFY
68#endif
69
70static _Atomic(uint64_t) request_number = 0;
71
74
75static _Thread_local fr_ring_buffer_t *fr_worker_rb;
76
77typedef struct {
78 fr_channel_t *ch;
79
80 /*
81 * To save time, we don't care about num_elements here. Which means that we don't
82 * need to cache or lookup the fr_worker_listen_t when we free a request.
83 */
84 fr_dlist_head_t dlist;
86
87/**
88 * A worker which takes packets from a master, and processes them.
89 */
91 char const *name; //!< name of this worker
92 fr_worker_config_t config; //!< external configuration
93
94 unlang_interpret_t *intp; //!< Worker's local interpreter.
95
96 pthread_t thread_id; //!< my thread ID
97
98 fr_log_t const *log; //!< log destination
99 fr_log_lvl_t lvl; //!< log level
100
101 fr_atomic_queue_t *aq_control; //!< atomic queue for control messages sent to me
102
103 fr_control_t *control; //!< the control plane
104
105 fr_event_list_t *el; //!< our event list
106
107 int num_channels; //!< actual number of channels
108
109 fr_heap_t *runnable; //!< current runnable requests which we've spent time processing
110
111 fr_timer_list_t *timeout; //!< Track when requests timeout using a dlist.
112 fr_time_delta_t max_request_time; //!< maximum time a request can be processed
113
114 fr_rb_tree_t *dedup; //!< de-dup tree
115
116 fr_rb_tree_t *listeners; //!< so we can cancel requests when a listener goes away
117
118 fr_io_stats_t stats; //!< input / output stats
119 fr_time_elapsed_t cpu_time; //!< histogram of total CPU time per request
120 fr_time_elapsed_t wall_clock; //!< histogram of wall clock time per request
121
122 uint64_t num_naks; //!< number of messages which were nak'd
123 uint64_t num_active; //!< number of active requests
124
125 fr_time_delta_t predicted; //!< How long we predict a request will take to execute.
126 fr_time_tracking_t tracking; //!< how much time the worker has spent doing things.
127
128 bool was_sleeping; //!< used to suppress multiple sleep signals in a row
129 bool exiting; //!< are we exiting?
130
131 fr_worker_channel_t *channel; //!< list of channels
132
133 request_slab_list_t *slab; //!< slab allocator for request_t
134};
135
136typedef struct {
137 fr_listen_t const *listener; //!< incoming packets
138
139 fr_rb_node_t node; //!< in tree of listeners
140
141 /*
142 * To save time, we don't care about num_elements here. Which means that we don't
143 * need to cache or lookup the fr_worker_listen_t when we free a request.
144 */
145 fr_dlist_head_t dlist; //!< of requests associated with this listener.
147
148
149static fr_cmp_ret_t worker_listener_cmp(void const *one, void const *two)
150{
151 fr_worker_listen_t const *a = one, *b = two;
152
153 return CMP(a->listener, b->listener);
154}
155
156
157/*
158 * Explicitly cleanup the memory allocated to the ring buffer,
159 * just in case valgrind complains about it.
160 */
161static int _fr_worker_rb_free(void *arg)
162{
163 return talloc_free(arg);
164}
165
166/** Initialise thread local storage
167 *
168 * @return fr_ring_buffer_t for messages
169 */
171{
173
174 rb = fr_worker_rb;
175 if (rb) return rb;
176
178 if (!rb) {
179 fr_perror("Failed allocating memory for worker ring buffer");
180 return NULL;
181 }
182
184
185 return rb;
186}
187
188static inline bool is_worker_thread(fr_worker_t const *worker)
189{
190 return (pthread_equal(pthread_self(), worker->thread_id) != 0);
191}
192
194static void worker_send_reply(fr_worker_t *worker, request_t *request, bool do_not_respond, fr_time_t now);
195
196/** Callback which handles a message being received on the worker side.
197 *
198 * @param[in] ctx the worker
199 * @param[in] ch the channel to drain
200 * @param[in] cd the message (if any) to start with
201 */
202static void worker_recv_request(void *ctx, fr_channel_t *ch, fr_channel_data_t *cd)
203{
204 fr_worker_t *worker = ctx;
205
206 worker->stats.in++;
207 DEBUG3("Received request %" PRIu64 "", worker->stats.in);
208 cd->channel.ch = ch;
209 worker_request_bootstrap(worker, cd, fr_time());
210}
211
213{
214 request_t *request;
215
216 while ((request = fr_dlist_pop_head(&ch->dlist)) != NULL) {
218 }
219}
220
221static void worker_exit(fr_worker_t *worker)
222{
223 worker->exiting = true;
224
225 /*
226 * Don't allow the post event to run
227 * any more requests. They'll be
228 * signalled to stop before we exit.
229 *
230 * This only has an effect in single
231 * threaded mode.
232 */
233 (void)fr_event_post_delete(worker->el, fr_worker_post_event, worker);
234}
235
236/** Handle a control plane message sent to the worker via a channel
237 *
238 * @param[in] ctx the worker
239 * @param[in] data the message
240 * @param[in] data_size size of the data
241 * @param[in] now the current time
242 */
243static void worker_channel_callback(void *ctx, void const *data, size_t data_size, fr_time_t now)
244{
245 int i;
246 unsigned int num;
247 bool ok, was_sleeping;
248 fr_channel_t *ch;
251 fr_worker_t *worker = ctx;
252
253 was_sleeping = worker->was_sleeping;
254 worker->was_sleeping = false;
255
256 /*
257 * We were woken up by a signal to do something. We're
258 * not sleeping.
259 */
260 ce = fr_channel_service_message(now, &ch, data, data_size);
261 DEBUG3("Channel %s",
262 fr_table_str_by_value(channel_signals, ce, "<INVALID>"));
263 switch (ce) {
264 case FR_CHANNEL_ERROR:
265 return;
266
267 case FR_CHANNEL_EMPTY:
268 return;
269
270 case FR_CHANNEL_NOOP:
271 return;
272
274 fr_assert(0 == 1);
275 break;
276
278 fr_assert(ch != NULL);
279
280 if (!fr_channel_recv_request(ch)) {
281 worker->was_sleeping = was_sleeping;
282
283 } else while (fr_channel_recv_request(ch));
284 break;
285
286 case FR_CHANNEL_OPEN:
287 fr_assert(ch != NULL);
288
289 ok = false;
290 for (i = 0; i < worker->config.max_channels; i++) {
291 fr_assert(worker->channel[i].ch != ch);
292
293 if (worker->channel[i].ch != NULL) continue;
294
295 worker->channel[i].ch = ch;
296 fr_dlist_init(&worker->channel[i].dlist, fr_async_t, entry);
297
298 DEBUG3("Received channel %p into array entry %d", ch, i);
299
300 ms = fr_message_set_create(worker, worker->config.message_set_size,
301 sizeof(fr_channel_data_t),
302 worker->config.ring_buffer_size, false);
303 fr_assert(ms != NULL);
305
306 worker->num_channels++;
307 ok = true;
308 break;
309 }
310
311 fr_cond_assert(ok);
312 break;
313
314 case FR_CHANNEL_CLOSE:
315 fr_assert(ch != NULL);
316
317 ok = false;
318
319 /*
320 * Locate the signalling channel in the list
321 * of channels.
322 */
323 for (i = 0; i < worker->config.max_channels; i++) {
324 if (!worker->channel[i].ch) continue;
325
326 if (worker->channel[i].ch != ch) continue;
327
328 worker_requests_cancel(&worker->channel[i]);
329
331
332 fr_assert_msg(fr_dlist_num_elements(&worker->channel[i].dlist) == 0,
333 "Network added messages to channel after sending FR_CHANNEL_CLOSE");
334
335 /*
336 * Should be nothing left: the network is not supposed
337 * to enqueue anything once it has signalled the close,
338 * which is what the assert above claims. Hand back
339 * whatever we find anyway, so the messages do not
340 * strand the ring buffer they came from, and complain,
341 * because these produce no reply and so the network
342 * never decrements its outstanding count for them.
343 */
345 if (num > 0) PWARN("Discarded %u request(s) still queued at close", num);
346
348 fr_assert(ms != NULL);
350 talloc_free(ms);
351
352 worker->channel[i].ch = NULL;
353
354 fr_assert(!fr_dlist_head(&worker->channel[i].dlist)); /* we can't look at num_elements */
355 fr_assert(worker->num_channels > 0);
356
357 worker->num_channels--;
358 ok = true;
359 break;
360 }
361
362 fr_cond_assert(ok);
363
364 /*
365 * Our last input channel closed,
366 * time to die.
367 */
368 if (worker->num_channels == 0) worker_exit(worker);
369 break;
370 }
371}
372
374{
376 request_t *request;
377
378 fr_rb_find((void **)&wl, worker->listeners, &(fr_worker_listen_t) { .listener = li });
379 if (!wl) return -1;
380
381 while ((request = fr_dlist_pop_head(&wl->dlist)) != NULL) {
382 RERROR("Cancelling request due to socket being closed");
384 }
385
386 (void) fr_rb_delete(worker->listeners, wl);
387 talloc_free(wl);
388
389 return 0;
390}
391
392
393/** A socket is going away, so clean up any requests which use this socket.
394 *
395 * @param[in] ctx the worker
396 * @param[in] data the message
397 * @param[in] data_size size of the data
398 * @param[in] now the current time
399 */
400static void worker_listen_cancel_callback(void *ctx, void const *data, NDEBUG_UNUSED size_t data_size, UNUSED fr_time_t now)
401{
402 fr_listen_t const *li;
403 fr_worker_t *worker = ctx;
404
405 fr_assert(data_size == sizeof(li));
406
407 memcpy(&li, data, sizeof(li));
408
409 (void) fr_worker_listen_cancel_self(worker, li);
410}
411
412/** Send a NAK to the network thread
413 *
414 * The network thread believes that a worker is running a request until that request has been NAK'd.
415 * We typically NAK requests when they've been hanging around in the worker's backlog too long,
416 * or there was an error executing the request.
417 *
418 * @param[in] worker the worker
419 * @param[in] cd the message to NAK
420 * @param[in] now when the message is NAKd
421 */
422static void worker_nak(fr_worker_t *worker, fr_channel_data_t *cd, fr_time_t now)
423{
424 size_t size;
425 fr_channel_data_t *reply;
426 fr_channel_t *ch;
428 fr_listen_t *listen;
429
430 worker->num_naks++;
431
432 /*
433 * Cache the outbound channel. We'll need it later.
434 */
435 ch = cd->channel.ch;
436 listen = cd->listen;
437
438 /*
439 * If the channel has been closed, but we haven't
440 * been informed, that is extremely bad.
441 *
442 * Try to continue working... but we'll likely
443 * leak memory or SEGV soon.
444 */
445 if (!fr_cond_assert_msg(fr_channel_active(ch), "Wanted to send NAK but channel has been closed")) {
446 fr_message_done(&cd->m);
447 return;
448 }
449
451 fr_assert(ms != NULL);
452
453 size = listen->app_io->default_reply_size;
454 if (!size) size = listen->app_io->default_message_size;
455
456 /*
457 * Allocate a default message size.
458 */
460
461 /*
462 * Encode a NAK
463 */
464 if (listen->app_io->nak) {
465 size = listen->app_io->nak(listen, cd->packet_ctx, cd->m.data,
466 cd->m.data_size, reply->m.data, reply->m.rb_size);
467 } else {
468 size = 1; /* rely on them to figure it the heck out */
469 }
470
471 (void) fr_message_and_data_commit(ms, &reply->m, size);
472
473 /*
474 * Fill in the NAK.
475 */
476 reply->m.when = now;
477 reply->reply.cpu_time = worker->tracking.running_total;
478 reply->reply.processing_time = fr_time_delta_from_msec(1); /* @todo - set to something better? */
479 reply->reply.request_time = cd->request.recv_time;
480
481 reply->listen = cd->listen;
482 reply->packet_ctx = cd->packet_ctx;
483
484 /*
485 * Mark the original message as done.
486 */
487 fr_message_done(&cd->m);
488
489 /*
490 * Send the reply, which also polls the request queue.
491 */
492 if (fr_channel_send_reply(ch, reply) < 0) {
493 DEBUG2("Failed sending reply to channel");
494 }
495
496 worker->stats.out++;
497}
498
499/** Signal the unlang interpreter that it needs to stop running the request
500 *
501 * Signalling is a synchronous operation. Whatever I/O requests the request
502 * is currently performing are immediately cancelled, and all the frames are
503 * popped off the unlang stack.
504 *
505 * Modules and unlang keywords explicitly register signal handlers to deal
506 * with their yield points being cancelled/interrupted via this function.
507 *
508 * The caller should assume the request is no longer viable after calling
509 * this function.
510 *
511 * @param[in] request request to cancel. The request may still run to completion.
512 */
513static void worker_stop_request(request_t *request)
514{
515 /*
516 * Also marks the request as done and runs
517 * the internal/external callbacs.
518 */
520}
521
522/** Enforce max_request_time
523 *
524 * Run periodically, and tries to clean up requests which were received by the network
525 * thread more than max_request_time seconds ago. In the interest of not adding a
526 * timer for every packet, the requests are given a 1 second leeway.
527 *
528 * @param[in] tl the worker's timer list.
529 * @param[in] when the current time
530 * @param[in] uctx the request_t timing out.
531 */
533{
534 request_t *request = talloc_get_type_abort(uctx, request_t);
535
536 /*
537 * Waiting too long, delete it.
538 */
539 REDEBUG("Request has reached max_request_time - signalling it to stop");
540 worker_stop_request(request);
541
542 /*
543 * This ensures the finally section can run timeout specific policies
544 */
545 request->rcode = RLM_MODULE_TIMEOUT;
546}
547
548
549/** Start time tracking for a request, and mark it as runnable.
550 *
551 */
553{
554 /*
555 * New requests are inserted into the time order heap in
556 * strict time priority. Once they are in the list, they
557 * are only removed when the request is done / free'd.
558 */
559 fr_assert(!fr_timer_armed(request->timeout));
560
561 if (unlikely(fr_timer_in(request, worker->timeout, &request->timeout, worker->config.max_request_time,
562 true, _worker_request_timeout, request) < 0)) {
563 RERROR("Failed to set request timeout timer");
564 return -1;
565 }
566
567 /*
568 * Bootstrap the async state machine with the initial
569 * state of the request.
570 */
571 RDEBUG3("Time tracking started in yielded state");
572 fr_time_tracking_start(&worker->tracking, &request->async->tracking, now);
573 fr_time_tracking_yield(&request->async->tracking, now);
574 worker->num_active++;
575
576 fr_assert(!fr_heap_entry_inserted(request->runnable));
577 (void) fr_heap_insert(&worker->runnable, request);
578
579 return 0;
580}
581
583{
584 RDEBUG3("Time tracking ended");
585 fr_time_tracking_end(&worker->predicted, &request->async->tracking, now);
586 fr_assert(worker->num_active > 0);
587 worker->num_active--;
588
589 TALLOC_FREE(request->timeout); /* Disarm the reques timer */
590}
591
592/** Send a response packet to the network side
593 *
594 * @param[in] worker This worker.
595 * @param[in] request we're sending a reply for.
596 * @param[in] send_reply whether the network side sends a reply
597 * @param[in] now The current time
598 */
599static void worker_send_reply(fr_worker_t *worker, request_t *request, bool send_reply, fr_time_t now)
600{
601 fr_channel_data_t *reply;
602 fr_channel_t *ch;
604 size_t size = 1;
605
606 REQUEST_VERIFY(request);
607
608 /*
609 * If we're sending a reply, then it's no longer runnable.
610 */
611 fr_assert(!fr_heap_entry_inserted(request->runnable));
612
613 if (send_reply) {
614 size = request->async->listen->app_io->default_reply_size;
615 if (!size) size = request->async->listen->app_io->default_message_size;
616 }
617
618 /*
619 * Allocate and send the reply.
620 */
621 ch = request->async->channel;
622 fr_assert(ch != NULL);
623
624 /*
625 * If the channel has been closed, but we haven't
626 * been informed, that is extremely bad.
627 *
628 * Try to continue working... but we'll likely
629 * leak memory or SEGV soon.
630 */
631 if (!fr_cond_assert_msg(fr_channel_active(ch), "Wanted to send reply but channel has been closed")) {
632 return;
633 }
634
636 fr_assert(ms != NULL);
637
639 fr_assert(reply != NULL);
640
641 /*
642 * Encode it, if required.
643 */
644 if (send_reply) {
645 ssize_t slen = 0;
646 fr_listen_t const *listen = request->async->listen;
647
648 if (listen->app_io->encode) {
649 slen = listen->app_io->encode(listen->app_io_instance, request,
650 reply->m.data, reply->m.rb_size);
651 } else if (listen->app->encode) {
652 slen = listen->app->encode(listen->app_instance, request,
653 reply->m.data, reply->m.rb_size);
654 }
655 if (slen < 0) {
656 RPERROR("Failed encoding request");
657 *reply->m.data = 0;
658 slen = 1;
659 }
660
661 /*
662 * Shrink the buffer to the actual packet size.
663 *
664 * This will ALWAYS return the same message as we put in.
665 */
666 fr_assert((size_t) slen <= reply->m.rb_size);
667 (void) fr_message_and_data_commit(ms, &reply->m, slen);
668 } else {
669 (void) fr_message_and_data_commit(ms, &reply->m, 0);
670 }
671
672 /*
673 * Fill in the rest of the fields in the channel message.
674 *
675 * sequence / ack will be filled in by fr_channel_send_reply()
676 */
677 reply->m.when = now;
678 reply->reply.cpu_time = worker->tracking.running_total;
679 reply->reply.processing_time = request->async->tracking.running_total;
680 reply->reply.request_time = request->async->recv_time;
681
682 reply->listen = request->async->listen;
683 reply->packet_ctx = request->async->packet_ctx;
684
685 /*
686 * Update the various timers.
687 */
688 fr_time_elapsed_update(&worker->cpu_time, now, fr_time_add(now, reply->reply.processing_time));
689 fr_time_elapsed_update(&worker->wall_clock, reply->reply.request_time, now);
690
691 RDEBUG("Finished request");
692
693 /*
694 * Send the reply, which also polls the request queue.
695 */
696 if (fr_channel_send_reply(ch, reply) < 0) {
697 /*
698 * Should only happen if the TO_REQUESTOR
699 * channel is full, or it's not yet active.
700 *
701 * Not much we can do except complain
702 * loudly and cleanup the request.
703 */
704 RPERROR("Failed sending reply to network thread");
705 }
706
707 worker->stats.out++;
708
709 fr_assert(!fr_timer_armed(request->timeout));
710 fr_assert(!fr_heap_entry_inserted(request->runnable));
711
712 fr_dlist_entry_unlink(&request->listen_entry);
713
714#ifndef NDEBUG
715 request->async->el = NULL;
716 request->async->channel = NULL;
717 request->async->packet_ctx = NULL;
718 request->async->listen = NULL;
719#endif
720}
721
722/*
723 * talloc_typed_asprintf() is horrifically slow for printing
724 * simple numbers.
725 */
726static char *itoa_internal(TALLOC_CTX *ctx, uint64_t number)
727{
728 char buffer[32];
729 char *p;
730 char const *numbers = "0123456789";
731
732 p = buffer + 30;
733 *(p--) = '\0';
734
735 while (number > 0) {
736 *(p--) = numbers[number % 10];
737 number /= 10;
738 }
739
740 if (p[1]) return talloc_strdup(ctx, p + 1);
741
742 return talloc_strdup(ctx, "0");
743}
744
745/** Initialize various request fields needed by the worker.
746 *
747 */
748static inline CC_HINT(always_inline)
750{
751 /*
752 * For internal requests request->packet
753 * and request->reply are already populated.
754 */
755 if (!request->packet) MEM(request->packet = fr_packet_alloc(request, false));
756 if (!request->reply) MEM(request->reply = fr_packet_alloc(request, false));
757
758 request->packet->timestamp = now;
759 request->async = talloc_zero(request, fr_async_t);
760 request->async->recv_time = now;
761 request->async->el = worker->el;
762 fr_dlist_entry_init(&request->async->entry);
763}
764
765static inline CC_HINT(always_inline)
767{
768 request->number = atomic_fetch_add_explicit(&request_number, 1, memory_order_seq_cst);
769 if (request->name) talloc_const_free(request->name);
770 request->name = itoa_internal(request, request->number);
771}
772
773static inline CC_HINT(always_inline)
775{
776 return fr_timer_list_num_events(worker->timeout);
777}
778
779static int _worker_request_deinit(request_t *request, UNUSED void *uctx)
780{
781 return request_slab_deinit(request);
782}
783
785{
786 int ret = -1;
787 request_t *request;
788 fr_listen_t *listen = cd->listen;
789
790 if (worker_num_requests(worker) >= (uint32_t) worker->config.max_requests) {
791 RATE_LIMIT_GLOBAL(ERROR, "Worker at max requests");
792 goto nak;
793 }
794
795 /*
796 * Receive a message to the worker queue, and decode it
797 * to a request.
798 */
799 fr_assert(listen != NULL);
800
801 request = request_slab_reserve(worker->slab);
802 if (!request) {
803 RATE_LIMIT_GLOBAL(ERROR, "Worker failed allocating new request");
804 goto nak;
805 }
806 /*
807 * Ensures that both the deinit function runs AND
808 * the request is returned to the slab if something
809 * calls talloc_free() on it.
810 */
811 request_slab_element_set_destructor(request, _worker_request_deinit, worker);
812
813 /*
814 * Have to initialise the request manually because namspace
815 * changes based on the listener that allocated it.
816 */
817 if (request_init(request, REQUEST_TYPE_EXTERNAL, (&(request_init_args_t){ .namespace = listen->dict })) < 0) {
818 request_slab_release(request);
819 goto nak;
820 }
821
822 /*
823 * Do normal worker init that's shared between internal
824 * and external requests.
825 */
826 worker_request_init(worker, request, now);
828
829 /*
830 * Associate our interpreter with the request
831 */
832 unlang_interpret_set(request, worker->intp);
833
834 request->packet->timestamp = cd->request.recv_time; /* Legacy - Remove once everything looks at request->async */
835
836 /*
837 * Update the transport-specific fields.
838 */
839 request->async->channel = cd->channel.ch;
840
841 request->async->recv_time = cd->request.recv_time;
842
843 request->async->listen = listen;
844 request->async->packet_ctx = cd->packet_ctx;
845 request->priority = cd->priority;
846
847 /*
848 * Now that the "request" structure has been initialized, go decode the packet.
849 *
850 * Note that this also sets the "async process" function.
851 */
852 if (listen->app->decode) {
853 ret = listen->app->decode(listen->app_instance, request, cd->m.data, cd->m.data_size);
854 } else if (listen->app_io->decode) {
855 ret = listen->app_io->decode(listen->app_io_instance, request, cd->m.data, cd->m.data_size);
856 }
857
858 if (ret < 0) {
859 fail:
860 fr_assert(talloc_parent(request->stack) == request);
861 request_slab_release(request);
862
863 nak:
864 worker_nak(worker, cd, now);
865 return;
866 }
867
868 /*
869 * Set the entry point for this virtual server.
870 */
871 if (unlang_call_push(NULL, request, cd->listen->server_cs, UNLANG_TOP_FRAME) < 0) {
872 RERROR("Protocol failed to set 'process' function");
873 goto fail;
874 }
875
876 /*
877 * Look for conflicting / duplicate packets, but only if
878 * requested to do so.
879 */
880 if (request->async->listen->track_duplicates) {
881 request_t *old;
882
883 fr_rb_find((void **)&old, worker->dedup, request);
884 if (!old) {
885 goto insert_new;
886 }
887
888 fr_assert(old->async->listen == request->async->listen);
889 fr_assert(old->async->channel == request->async->channel);
890
891 /*
892 * There's a new packet. Do we keep the old one,
893 * or the new one? This decision is made by
894 * checking the recv_time, which is a
895 * nanosecond-resolution timer. If the time is
896 * identical, then the new packet is the same as
897 * the old one.
898 *
899 * If the new packet is a duplicate of the old
900 * one, then we can just discard the new one. We
901 * have to tell the channel that we've "eaten"
902 * this reply, so the sequence number should
903 * increase.
904 *
905 * @todo - fix the channel code to do queue
906 * depth, and not sequence / ack.
907 */
908 if (fr_time_eq(old->async->recv_time, request->async->recv_time)) {
909 RWARN("Discarding duplicate of request (%"PRIu64")", old->number);
910
911 fr_channel_null_reply(request->async->channel);
912 request_slab_release(request);
913
914 /*
915 * Signal there's a dup, and ignore the
916 * return code. We don't bother replying
917 * here, as an FD event or timer will
918 * wake up the request, and cause it to
919 * continue.
920 *
921 * @todo - the old request is NOT
922 * running, but is yielded. It MAY clean
923 * itself up, or do something...
924 */
926 worker->stats.dup++;
927
928 fr_message_done(&cd->m);
929 return;
930 }
931
932 /*
933 * Stop the old request, and decrement the number
934 * of active requests.
935 */
936 RWARN("Got conflicting packet for request (%" PRIu64 "), telling old request to stop", old->number);
937
939 worker->stats.dropped++;
940 (void) fr_rb_remove(NULL, worker->dedup, old); /* remove, but do NOT free it */
941
942 insert_new:
943 (void) fr_rb_insert(worker->dedup, request);
944 }
945
946 if (worker_request_time_tracking_start(worker, request, now) < 0) {
947 if (request->async->listen->track_duplicates) (void) fr_rb_remove(NULL, worker->dedup, request);
948 goto fail;
949 }
950
951 /*
952 * We're done with this message.
953 */
954 fr_message_done(&cd->m);
955
956 {
958
959 fr_rb_find((void **)&wl, worker->listeners, &(fr_worker_listen_t) { .listener = listen });
960 if (!wl) {
961 MEM(wl = talloc_zero(worker, fr_worker_listen_t));
962 fr_dlist_init(&wl->dlist, request_t, listen_entry);
963 wl->listener = listen;
964
965 (void) fr_rb_insert(worker->listeners, wl);
966 }
967
968 fr_dlist_insert_tail(&wl->dlist, request);
969 }
970}
971
972/**
973 * Track a request_t in the "runnable" heap.
974 * Higher priorities take precedence, followed by lower sequence numbers
975 */
976static fr_cmp_ret_t worker_runnable_cmp(void const *one, void const *two)
977{
978 request_t const *a = one, *b = two;
979 int ret;
980
981 /*
982 * Prefer higher priority packets.
983 */
984 ret = CMP_PREFER_LARGER(b->priority, a->priority);
985 if (ret != 0) return ret;
986
987 /*
988 * Prefer packets which are further along in their processing sequence.
989 */
990 ret = CMP_PREFER_LARGER(a->sequence, b->sequence);
991 if (ret != 0) return ret;
992
993 /*
994 * Smaller timestamp (i.e. earlier) is more important.
995 */
996 return fr_time_cmp(a->async->recv_time, b->async->recv_time);
997}
998
999/**
1000 * Track a request_t in the "dedup" tree
1001 */
1002static fr_cmp_ret_t worker_dedup_cmp(void const *one, void const *two)
1003{
1004 int ret;
1005 request_t const *a = one, *b = two;
1006
1007 ret = CMP(a->async->listen, b->async->listen);
1008 if (ret) return ret;
1009
1010 return CMP(a->async->packet_ctx, b->async->packet_ctx);
1011}
1012
1013/** Destroy a worker
1014 *
1015 * The input channels are signaled, and local messages are cleaned up.
1016 *
1017 * This should be called to _EXPLICITLY_ destroy a worker, when some fatal
1018 * error has occurred on the worker side, and we need to destroy it.
1019 *
1020 * We signal all pending requests in the backlog to stop, and tell the
1021 * network side that it should not send us any more requests.
1022 *
1023 * @param[in] worker the worker to destroy.
1024 */
1026{
1027 int i, count, ret;
1028
1029// WORKER_VERIFY;
1030
1031 /*
1032 * Stop any new requests running with this interpreter
1033 */
1035
1036 /*
1037 * Destroy all of the active requests. These are ones
1038 * which are still waiting for timers or file descriptor
1039 * events.
1040 */
1041 count = 0;
1042
1043 /*
1044 * Force the timeout event to fire for all requests that
1045 * are still running.
1046 */
1047 ret = fr_timer_list_force_run(worker->timeout);
1048 if (unlikely(ret < 0)) {
1049 fr_assert_msg(0, "Failed to force run the timeout list");
1050 } else {
1051 count += ret;
1052 }
1053
1055
1056 DEBUG("Worker is exiting - stopped %u requests", count);
1057
1058 /*
1059 * Signal the channels that we're closing.
1060 *
1061 * The other end owns the channel, and will take care of
1062 * popping messages in the TO_RESPONDER queue, and marking
1063 * them FR_MESSAGE_DONE. It will ignore the messages in
1064 * the TO_REQUESTOR queue, as we own those. They will be
1065 * automatically freed when our talloc context is freed.
1066 */
1067 for (i = 0; i < worker->config.max_channels; i++) {
1068 if (!worker->channel[i].ch) continue;
1069
1070 worker_requests_cancel(&worker->channel[i]);
1071
1072 fr_assert_msg(fr_dlist_num_elements(&worker->channel[i].dlist) == 0,
1073 "Pending messages in channel after cancelling request");
1074
1076 }
1077
1078 talloc_free(worker);
1079}
1080
1081/** Internal request (i.e. one generated by the interpreter) is now complete
1082 *
1083 */
1084static void _worker_request_internal_init(request_t *request, void *uctx)
1085{
1086 fr_worker_t *worker = talloc_get_type_abort(uctx, fr_worker_t);
1087 fr_time_t now = fr_time();
1088
1089 worker_request_init(worker, request, now);
1090
1091 /*
1092 * Requests generated by the interpreter
1093 * are always marked up as internal.
1094 */
1096 if (worker_request_time_tracking_start(worker, request, now) < 0) {
1098 }
1099}
1100
1101
1102/** External request is now complete
1103 *
1104 */
1105static void _worker_request_done_external(request_t *request, UNUSED rlm_rcode_t rcode, void *uctx)
1106{
1107 fr_worker_t *worker = talloc_get_type_abort(uctx, fr_worker_t);
1108 fr_time_t now = fr_time();
1109
1110 /*
1111 * All external requests MUST have a listener.
1112 */
1114 fr_assert(request->async->listen != NULL);
1115
1116 /*
1117 * Only real packets are in the dedup tree. And even
1118 * then, only some of the time.
1119 */
1120 if (request->async->listen->track_duplicates && fr_rb_node_inline_in_tree(&request->dedup_node)) {
1121 (void) fr_rb_delete(worker->dedup, request);
1122 }
1123
1124 /*
1125 * If we're running a real request, then the final
1126 * indentation MUST be zero. Otherwise we skipped
1127 * something!
1128 *
1129 * Also check that the request is NOT marked as
1130 * "yielded", but is in fact done.
1131 *
1132 * @todo - check that the stack is at frame 0, otherwise
1133 * more things have gone wrong.
1134 */
1135 fr_assert_msg(request_is_internal(request) || request_is_detached(request) || (request->log.indent.unlang == 0),
1136 "Request %s bad log indentation - expected 0 got %u", request->name, request->log.indent.unlang);
1138 "Request %s is marked as yielded at end of processing", request->name);
1140 "Request %s stack depth %u > 0", request->name, unlang_interpret_stack_depth(request));
1141 RDEBUG("Done request");
1142
1143 /*
1144 * The request is done. Track that.
1145 */
1146 worker_request_time_tracking_end(worker, request, now);
1147
1148 /*
1149 * Remove it from the list of requests associated with this channel.
1150 */
1151 if (fr_dlist_entry_in_list(&request->async->entry)) {
1152 fr_dlist_entry_unlink(&request->async->entry);
1153 }
1154
1155 /*
1156 * These conditions are true when the server is
1157 * exiting and we're stopping all the requests.
1158 *
1159 * This should never happen otherwise.
1160 */
1161 if (unlikely(!fr_channel_active(request->async->channel))) {
1162 fr_dlist_entry_unlink(&request->listen_entry);
1163 request_slab_release(request);
1164 return;
1165 }
1166
1167 worker_send_reply(worker, request, !unlang_request_is_cancelled(request), now);
1168 request_slab_release(request);
1169}
1170
1171/** Internal request (i.e. one generated by the interpreter) is now complete
1172 *
1173 * Whatever generated the request is now responsible for freeing it.
1174 */
1175static void _worker_request_done_internal(request_t *request, UNUSED rlm_rcode_t rcode, void *uctx)
1176{
1177 fr_worker_t *worker = talloc_get_type_abort(uctx, fr_worker_t);
1178
1179 worker_request_time_tracking_end(worker, request, fr_time());
1180
1181 fr_assert(!fr_heap_entry_inserted(request->runnable));
1182 fr_assert(!fr_timer_armed(request->timeout));
1183 fr_assert(!fr_dlist_entry_in_list(&request->async->entry));
1184}
1185
1186/** Detached request (i.e. one generated by the interpreter with no parent) is now complete
1187 *
1188 * As the request has no parent, then there's nothing to free it
1189 * so we have to.
1190 */
1191static void _worker_request_done_detached(request_t *request, UNUSED rlm_rcode_t rcode, UNUSED void *uctx)
1192{
1193 /*
1194 * No time tracking for detached requests
1195 * so we don't need to call
1196 * worker_request_time_tracking_end.
1197 */
1198 fr_assert(!fr_heap_entry_inserted(request->runnable));
1199
1200 /*
1201 * Normally worker_request_time_tracking_end
1202 * would remove the request from the time
1203 * order heap, but we need to do that for
1204 * detached requests.
1205 */
1206 TALLOC_FREE(request->timeout);
1207
1208 fr_assert(!fr_dlist_entry_in_list(&request->async->entry));
1209
1210 /*
1211 * Detached requests have to be freed by us
1212 * as nothing else can free them.
1213 *
1214 * All other requests must be freed by the
1215 * code which allocated them.
1216 */
1217 talloc_free(request);
1218}
1219
1220
1221/** Make us responsible for running the request
1222 *
1223 */
1224static void _worker_request_detach(request_t *request, void *uctx)
1225{
1226 fr_worker_t *worker = talloc_get_type_abort(uctx, fr_worker_t);
1227 fr_time_t now = fr_time();
1228
1229 RDEBUG4("%s - Request detaching", __FUNCTION__);
1230
1231 if (request_is_detachable(request)) {
1232 /*
1233 * End the time tracking... We don't track detached requests,
1234 * because they don't contribute for the time consumed by an
1235 * external request.
1236 */
1237 if (request->async->tracking.state == FR_TIME_TRACKING_YIELDED) {
1238 RDEBUG3("Forcing time tracking to running state, from yielded, for request detach");
1239 fr_time_tracking_resume(&request->async->tracking, now);
1240 }
1241 worker_request_time_tracking_end(worker, request, now);
1242
1243 if (request_detach(request) < 0) RPEDEBUG("Failed detaching request");
1244
1245 RDEBUG3("Request is detached");
1246 } else {
1247 fr_assert_msg(0, "Request is not detachable");
1248 }
1249
1250 return;
1251}
1252
1253/** Request is now runnable
1254 *
1255 */
1256static void _worker_request_runnable(request_t *request, void *uctx)
1257{
1258 fr_worker_t *worker = uctx;
1259
1260 RDEBUG4("%s - Request marked as runnable", __FUNCTION__);
1261 fr_heap_insert(&worker->runnable, request);
1262}
1263
1264/** Interpreter yielded request
1265 *
1266 */
1267static void _worker_request_yield(request_t *request, UNUSED void *uctx)
1268{
1269 RDEBUG4("%s - Request yielded", __FUNCTION__);
1270 if (likely(!request_is_detached(request))) fr_time_tracking_yield(&request->async->tracking, fr_time());
1271}
1272
1273/** Interpreter is starting to work on request again
1274 *
1275 */
1276static void _worker_request_resume(request_t *request, UNUSED void *uctx)
1277{
1278 RDEBUG4("%s - Request resuming", __FUNCTION__);
1279 if (likely(!request_is_detached(request))) fr_time_tracking_resume(&request->async->tracking, fr_time());
1280}
1281
1282/** Check if a request is scheduled
1283 *
1284 */
1285static bool _worker_request_scheduled(request_t const *request, UNUSED void *uctx)
1286{
1287 return fr_heap_entry_inserted(request->runnable);
1288}
1289
1290/** Update a request's priority
1291 *
1292 */
1293static void _worker_request_prioritise(request_t *request, void *uctx)
1294{
1295 fr_worker_t *worker = talloc_get_type_abort(uctx, fr_worker_t);
1296
1297 RDEBUG4("%s - Request priority changed", __FUNCTION__);
1298
1299 /* Extract the request from the runnable queue _if_ it's in the runnable queue */
1300 if (fr_heap_extract(&worker->runnable, request) < 0) return;
1301
1302 /* Reinsert it to re-evaluate its new priority */
1303 fr_heap_insert(&worker->runnable, request);
1304}
1305
1306/** Run a request
1307 *
1308 * Until it either yields, or is done.
1309 *
1310 * This function is also responsible for sending replies, and
1311 * cleaning up the request.
1312 *
1313 * @param[in] worker the worker
1314 * @param[in] start the current time
1315 */
1316static inline CC_HINT(always_inline) void worker_run_request(fr_worker_t *worker, fr_time_t start)
1317{
1318 request_t *request;
1319 fr_time_t now;
1320
1322
1323 now = start;
1324
1325 /*
1326 * Busy-loop running requests for 1ms. We still poll the
1327 * event loop 1000 times a second, OR when there's no
1328 * more work to do. This allows us to make progress with
1329 * ongoing requests, at the expense of sometimes ignoring
1330 * new ones.
1331 */
1332 while (fr_time_delta_lt(fr_time_sub(now, start), fr_time_delta_from_msec(1)) &&
1333 (fr_heap_pop((void **)&request, &worker->runnable) == 0) && request) {
1334
1335 REQUEST_VERIFY(request);
1336 fr_assert(!fr_heap_entry_inserted(request->runnable));
1337
1338 /*
1339 * For real requests, if the channel is gone,
1340 * just stop the request and free it.
1341 */
1342 if (request->async->channel && !fr_channel_active(request->async->channel)) {
1343 worker_stop_request(request);
1344 continue;
1345 }
1346
1348
1349 now = fr_time();
1350 }
1351}
1352
1353/** Create a worker
1354 *
1355 * @param[in] ctx the talloc context
1356 * @param[in] name the name of this worker
1357 * @param[in] el the event list
1358 * @param[in] logger the destination for all logging messages
1359 * @param[in] lvl log level
1360 * @param[in] config various configuration parameters
1361 * @return
1362 * - NULL on error
1363 * - fr_worker_t on success
1364 */
1365fr_worker_t *fr_worker_alloc(TALLOC_CTX *ctx, fr_event_list_t *el, char const *name, fr_log_t const *logger, fr_log_lvl_t lvl,
1367{
1368 fr_worker_t *worker;
1369
1370 worker = talloc_zero(ctx, fr_worker_t);
1371 if (!worker) {
1372nomem:
1373 fr_strerror_const("Failed allocating memory");
1374 return NULL;
1375 }
1376
1377 worker->name = talloc_strdup(worker, name); /* thread locality */
1378
1379 if (config) worker->config = *config;
1380
1381#define CHECK_CONFIG(_x, _min, _max) do { \
1382 if (!worker->config._x) worker->config._x = _min; \
1383 if (worker->config._x < _min) worker->config._x = _min; \
1384 if (worker->config._x > _max) worker->config._x = _max; \
1385 } while (0)
1386
1387#define CHECK_CONFIG_TIME_DELTA(_x, _min, _max) do { \
1388 if (fr_time_delta_lt(worker->config._x, _min)) worker->config._x = _min; \
1389 if (fr_time_delta_gt(worker->config._x, _max)) worker->config._x = _max; \
1390 } while (0)
1391
1392 CHECK_CONFIG(max_requests,1024,(1 << 30));
1393 CHECK_CONFIG(max_channels, 64, 1024);
1394 CHECK_CONFIG(reuse.child_pool_size, 4096, 65536);
1395 CHECK_CONFIG(message_set_size, 1024, 8192);
1396 CHECK_CONFIG(ring_buffer_size, (1 << 17), (1 << 20));
1398
1399 worker->channel = talloc_zero_array(worker, fr_worker_channel_t, worker->config.max_channels);
1400 if (!worker->channel) {
1401 talloc_free(worker);
1402 goto nomem;
1403 }
1404
1405 worker->thread_id = pthread_self();
1406 worker->el = el;
1407 worker->log = logger;
1408 worker->lvl = lvl;
1409
1410 /*
1411 * The worker thread starts now. Manually initialize it,
1412 * because we're tracking request time, not the time that
1413 * the worker thread is running.
1414 */
1415 memset(&worker->tracking, 0, sizeof(worker->tracking));
1416
1417 worker->aq_control = fr_atomic_queue_talloc(worker, 1024);
1418 if (!worker->aq_control) {
1419 fr_strerror_const("Failed creating atomic queue");
1420 fail:
1421 talloc_free(worker);
1422 return NULL;
1423 }
1424
1425 worker->control = fr_control_create(worker, el, worker->aq_control, 7);
1426 if (!worker->control) {
1427 fr_strerror_const_push("Failed creating control plane");
1428 goto fail;
1429 }
1430
1432 fr_strerror_const_push("Failed adding control channel");
1433 goto fail;
1434 }
1435
1437 fr_strerror_const_push("Failed adding callback for listeners");
1438 goto fail;
1439 }
1440
1441 if (fr_control_open(worker->control) < 0) {
1442 fr_strerror_const_push("Failed opening control plane");
1443 goto fail;
1444 }
1445
1446 worker->runnable = fr_heap_talloc_alloc(worker, worker_runnable_cmp, request_t, runnable, 0);
1447 if (!worker->runnable) {
1448 fr_strerror_const("Failed creating runnable heap");
1449 goto fail;
1450 }
1451
1452 worker->timeout = fr_timer_list_ordered_alloc(worker, el->tl);
1453 if (!worker->timeout) {
1454 fr_strerror_const("Failed creating timeouts list");
1455 goto fail;
1456 }
1457
1458 worker->dedup = fr_rb_inline_talloc_alloc(worker, request_t, dedup_node, worker_dedup_cmp, NULL);
1459 if (!worker->dedup) {
1460 fr_strerror_const("Failed creating de_dup tree");
1461 goto fail;
1462 }
1463
1465 if (!worker->listeners) {
1466 fr_strerror_const("Failed creating listener tree");
1467 goto fail;
1468 }
1469
1470 worker->intp = unlang_interpret_init(worker, el,
1472 .init_internal = _worker_request_internal_init,
1473
1474 .done_external = _worker_request_done_external,
1475 .done_internal = _worker_request_done_internal,
1476 .done_detached = _worker_request_done_detached,
1477
1478 .detach = _worker_request_detach,
1479 .yield = _worker_request_yield,
1480 .resume = _worker_request_resume,
1481 .mark_runnable = _worker_request_runnable,
1482
1483 .scheduled = _worker_request_scheduled,
1484 .prioritise = _worker_request_prioritise
1485 },
1486 worker);
1487 if (!worker->intp){
1488 fr_strerror_const("Failed initialising interpreter");
1489 goto fail;
1490 }
1491
1492 {
1495
1496 if (!(worker->slab = request_slab_list_alloc(worker, el, &worker->config.reuse, NULL, NULL,
1497 UNCONST(void *, worker), true, false))) {
1498 fr_strerror_const("Failed creating request slab list");
1499 goto fail;
1500 }
1501 }
1502
1504
1505 return worker;
1506}
1507
1508
1509/** The main loop and entry point of the stand-alone worker thread.
1510 *
1511 * Where there is only one thread, the event loop runs fr_worker_pre_event() and fr_worker_post_event()
1512 * instead, And then fr_worker_post_event() takes care of calling worker_run_request() to actually run the
1513 * request.
1514 *
1515 * @param[in] worker the worker data structure to manage
1516 */
1518{
1520
1521 while (true) {
1522 bool wait_for_event;
1523 int num_events;
1524
1526
1527 /*
1528 * There are runnable requests. We still service
1529 * the event loop, but we don't wait for events.
1530 */
1531 wait_for_event = (fr_heap_num_elements(worker->runnable) == 0);
1532 if (wait_for_event) {
1533 if (worker->exiting && (worker_num_requests(worker) == 0)) break;
1534
1535 DEBUG4("Ready to process requests");
1536 }
1537
1538 /*
1539 * Check the event list. If there's an error
1540 * (e.g. exit), we stop looping and clean up.
1541 */
1542 DEBUG4("Gathering events - %s", wait_for_event ? "will wait" : "Will not wait");
1543 num_events = fr_event_corral(worker->el, fr_time(), wait_for_event);
1544 if (num_events < 0) {
1545 if (fr_event_loop_exiting(worker->el)) {
1546 DEBUG4("Event loop exiting");
1547 break;
1548 }
1549
1550 PERROR("Failed retrieving events");
1551 break;
1552 }
1553
1554 DEBUG4("%u event(s) pending", num_events);
1555
1556 /*
1557 * Service outstanding events.
1558 */
1559 if (num_events > 0) {
1560 DEBUG4("Servicing event(s)");
1561 fr_event_service(worker->el);
1562 }
1563
1564 /*
1565 * Run any outstanding requests.
1566 */
1567 worker_run_request(worker, fr_time());
1568 }
1569}
1570
1571/** Pre-event handler
1572 *
1573 * This should be run ONLY in single-threaded mode!
1574 */
1576{
1577 fr_worker_t *worker = talloc_get_type_abort(uctx, fr_worker_t);
1578 request_t *request;
1579
1580 request = fr_heap_peek(worker->runnable);
1581 if (!request) return 0;
1582
1583 /*
1584 * There's work to do. Tell the event handler to poll
1585 * for IO / timers, but also immediately return to the
1586 * calling function, which has more work to do.
1587 */
1588 return 1;
1589}
1590
1591
1592/** Post-event handler
1593 *
1594 * This should be run ONLY in single-threaded mode!
1595 */
1597{
1598 fr_worker_t *worker = talloc_get_type_abort(uctx, fr_worker_t);
1599
1600 worker_run_request(worker, fr_time()); /* Event loop time can be too old, and trigger asserts */
1601}
1602
1603/** Print debug information about the worker structure
1604 *
1605 * @param[in] worker the worker
1606 * @param[in] fp the file where the debug output is printed.
1607 */
1608void fr_worker_debug(fr_worker_t *worker, FILE *fp)
1609{
1611
1612 fprintf(fp, "\tnum_channels = %d\n", worker->num_channels);
1613 fprintf(fp, "\tstats.in = %" PRIu64 "\n", worker->stats.in);
1614
1615 fprintf(fp, "\tcalculated (predicted) total CPU time = %" PRIu64 "\n",
1616 fr_time_delta_unwrap(worker->predicted) * worker->stats.in);
1617 if (worker->stats.in) {
1618 fprintf(fp, "\tcalculated (counted) per request time = %" PRIu64 "\n",
1620 }
1621
1622 fr_time_tracking_debug(&worker->tracking, fp);
1623
1624}
1625
1626/** Create a channel to the worker
1627 *
1628 * Called by the master (i.e. network) thread when it needs to create
1629 * a new channel to a particuler worker.
1630 *
1631 * @param[in] worker the worker
1632 * @param[in] master the control plane of the master
1633 * @param[in] ctx the context in which the channel will be created
1634 */
1636{
1637 fr_channel_t *ch;
1638 pthread_t id;
1639 bool same;
1640
1642
1643 id = pthread_self();
1644 same = (pthread_equal(id, worker->thread_id) != 0);
1645
1646 ch = fr_channel_create(ctx, master, worker->control, same);
1647 if (!ch) return NULL;
1648
1650
1651 /*
1652 * Tell the worker about the channel
1653 */
1654 if (fr_channel_signal_open(ch) < 0) {
1655 talloc_free(ch);
1656 return NULL;
1657 }
1658
1659 return ch;
1660}
1661
1663{
1664 fr_ring_buffer_t *rb;
1665
1666 /*
1667 * Skip a bunch of work if we're already in the worker thread.
1668 */
1669 if (is_worker_thread(worker)) {
1670 return fr_worker_listen_cancel_self(worker, li);
1671 }
1672
1673 rb = fr_worker_rb_init();
1674 if (!rb) return -1;
1675
1676 return fr_control_message_send(worker->control, rb, FR_CONTROL_ID_LISTEN_DEAD, &li, sizeof(li));
1677}
1678
1679#ifdef WITH_VERIFY_PTR
1680/** Verify the worker data structures.
1681 *
1682 * @param[in] worker the worker
1683 */
1684static void worker_verify(fr_worker_t *worker)
1685{
1686 int i;
1687
1688 (void) talloc_get_type_abort(worker, fr_worker_t);
1689 fr_atomic_queue_verify(worker->aq_control);
1690
1691 fr_assert(worker->control != NULL);
1692 (void) talloc_get_type_abort(worker->control, fr_control_t);
1693
1694 fr_assert(worker->el != NULL);
1695 (void) talloc_get_type_abort(worker->el, fr_event_list_t);
1696
1697 fr_assert(worker->runnable != NULL);
1698 (void) talloc_get_type_abort(worker->runnable, fr_heap_t);
1699
1700 fr_assert(worker->dedup != NULL);
1701 (void) talloc_get_type_abort(worker->dedup, fr_rb_tree_t);
1702
1703 for (i = 0; i < worker->config.max_channels; i++) {
1704 if (!worker->channel[i].ch) continue;
1705
1706 (void) talloc_get_type_abort(worker->channel[i].ch, fr_channel_t);
1707 }
1708}
1709#endif
1710
1711int fr_worker_stats(fr_worker_t const *worker, int num, uint64_t *stats)
1712{
1713 if (num < 0) return -1;
1714 if (num == 0) return 0;
1715
1716 stats[0] = worker->stats.in;
1717 if (num >= 2) stats[1] = worker->stats.out;
1718 if (num >= 3) stats[2] = worker->stats.dup;
1719 if (num >= 4) stats[3] = worker->stats.dropped;
1720 if (num >= 5) stats[4] = worker->num_naks;
1721 if (num >= 6) stats[5] = worker->num_active;
1722
1723 if (num <= 6) return num;
1724
1725 return 6;
1726}
1727
1728static int cmd_stats_worker(FILE *fp, UNUSED FILE *fp_err, void *ctx, fr_cmd_info_t const *info)
1729{
1730 fr_worker_t const *worker = ctx;
1731 fr_time_delta_t when;
1732
1733 if ((info->argc == 0) || (strcmp(info->argv[0], "count") == 0)) {
1734 fprintf(fp, "count.in\t\t\t%" PRIu64 "\n", worker->stats.in);
1735 fprintf(fp, "count.out\t\t\t%" PRIu64 "\n", worker->stats.out);
1736 fprintf(fp, "count.dup\t\t\t%" PRIu64 "\n", worker->stats.dup);
1737 fprintf(fp, "count.dropped\t\t\t%" PRIu64 "\n", worker->stats.dropped);
1738 fprintf(fp, "count.naks\t\t\t%" PRIu64 "\n", worker->num_naks);
1739 fprintf(fp, "count.active\t\t\t%" PRIu64 "\n", worker->num_active);
1740 fprintf(fp, "count.runnable\t\t\t%u\n", fr_heap_num_elements(worker->runnable));
1741 }
1742
1743 if ((info->argc == 0) || (strcmp(info->argv[0], "cpu") == 0)) {
1744 when = worker->predicted;
1745 fprintf(fp, "cpu.request_time_rtt\t\t%.9f\n", fr_time_delta_unwrap(when) / (double)NSEC);
1746
1747 when = worker->tracking.running_total;
1748 if (fr_time_delta_ispos(when) && (worker->stats.in > worker->stats.dropped)) {
1749 when = fr_time_delta_div(when, fr_time_delta_wrap(worker->stats.in - worker->stats.dropped));
1750 }
1751 fprintf(fp, "cpu.average_request_time\t%.9f\n", fr_time_delta_unwrap(when) / (double)NSEC);
1752
1753 when = worker->tracking.running_total;
1754 fprintf(fp, "cpu.used\t\t\t%.6f\n", fr_time_delta_unwrap(when) / (double)NSEC);
1755
1756 when = worker->tracking.waiting_total;
1757 fprintf(fp, "cpu.waiting\t\t\t%.3f\n", fr_time_delta_unwrap(when) / (double)NSEC);
1758
1759 fr_time_elapsed_fprint(fp, &worker->cpu_time, "cpu.requests", 4);
1760 fr_time_elapsed_fprint(fp, &worker->wall_clock, "time.requests", 4);
1761 }
1762
1763 return 0;
1764}
1765
1767 {
1768 .parent = "stats",
1769 .name = "worker",
1770 .help = "Statistics for workers threads.",
1771 .read_only = true
1772 },
1773
1774 {
1775 .parent = "stats worker",
1776 .add_name = true,
1777 .name = "self",
1778 .syntax = "[(count|cpu)]",
1779 .func = cmd_stats_worker,
1780 .help = "Show statistics for a specific worker thread.",
1781 .read_only = true
1782 },
1783
1785};
static int const char char buffer[256]
Definition acutest.h:576
fr_io_encode_t encode
Pack fr_pair_ts back into a byte array.
Definition app_io.h:55
size_t default_reply_size
same for replies
Definition app_io.h:40
size_t default_message_size
Usually maximum message size.
Definition app_io.h:39
fr_io_nak_t nak
Function to send a NAK.
Definition app_io.h:62
fr_io_decode_t decode
Translate raw bytes into fr_pair_ts and metadata.
Definition app_io.h:54
fr_io_decode_t decode
Translate raw bytes into fr_pair_ts and metadata.
Definition application.h:80
fr_io_encode_t encode
Pack fr_pair_ts back into a byte array.
Definition application.h:85
#define _Thread_local
Definition atexit.h:213
#define fr_atexit_thread_local(_name, _free, _uctx)
Definition atexit.h:224
fr_atomic_queue_t * fr_atomic_queue_talloc(TALLOC_CTX *ctx, size_t size)
Create fixed-size atomic queue.
Structure to hold the atomic queue.
#define UNCONST(_type, _ptr)
Remove const qualification from a pointer.
Definition build.h:186
#define RCSID(id)
Definition build.h:560
#define NDEBUG_UNUSED
Definition build.h:395
#define CMP_PREFER_LARGER(_a, _b)
Evaluates to -1 for a > b, and +1 for a < b.
Definition build.h:109
#define CMP(_a, _b)
Same as CMP_PREFER_SMALLER use when you don't really care about ordering, you just want an ordering.
Definition build.h:113
#define unlikely(_x)
Definition build.h:455
#define UNUSED
Definition build.h:384
unlang_action_t unlang_call_push(unlang_result_t *p_result, request_t *request, CONF_SECTION *server_cs, bool top_frame)
Push a virtual server CONF_SECTION as a call frame onto the stack.
Definition call.c:151
fr_table_num_sorted_t const channel_signals[]
Definition channel.c:151
unsigned int fr_channel_responder_discard(fr_channel_t *ch)
Discard any requests the requestor queued but we never received.
Definition channel.c:874
fr_channel_t * fr_channel_create(TALLOC_CTX *ctx, fr_control_t *requestor, fr_control_t *responder, bool same)
Create a new channel.
Definition channel.c:181
fr_channel_event_t fr_channel_service_message(fr_time_t when, fr_channel_t **p_channel, void const *data, size_t data_size)
Service a control-plane message.
Definition channel.c:687
int fr_channel_set_recv_request(fr_channel_t *ch, void *uctx, fr_channel_recv_callback_t recv_request)
Definition channel.c:977
void * fr_channel_responder_uctx_get(fr_channel_t *ch)
Get responder-specific data from a channel.
Definition channel.c:936
bool fr_channel_recv_request(fr_channel_t *ch)
Receive a request message from the channel.
Definition channel.c:470
int fr_channel_null_reply(fr_channel_t *ch)
Don't send a reply message into the channel.
Definition channel.c:626
void fr_channel_responder_uctx_add(fr_channel_t *ch, void *uctx)
Add responder-specific data to a channel.
Definition channel.c:924
int fr_channel_send_reply(fr_channel_t *ch, fr_channel_data_t *cd)
Send a reply message into the channel.
Definition channel.c:509
bool fr_channel_active(fr_channel_t *ch)
Check if a channel is active.
Definition channel.c:829
int fr_channel_responder_ack_close(fr_channel_t *ch)
Acknowledge that the channel is closing.
Definition channel.c:895
int fr_channel_signal_open(fr_channel_t *ch)
Send a channel to a responder.
Definition channel.c:991
A full channel, which consists of two ends.
Definition channel.c:142
fr_message_t m
the message header
Definition channel.h:107
fr_channel_event_t
Definition channel.h:69
@ FR_CHANNEL_NOOP
Definition channel.h:76
@ FR_CHANNEL_EMPTY
Definition channel.h:77
@ FR_CHANNEL_CLOSE
Definition channel.h:74
@ FR_CHANNEL_ERROR
Definition channel.h:70
@ FR_CHANNEL_DATA_READY_REQUESTOR
Definition channel.h:72
@ FR_CHANNEL_OPEN
Definition channel.h:73
@ FR_CHANNEL_DATA_READY_RESPONDER
Definition channel.h:71
void * packet_ctx
Packet specific context for holding client information, and other proto_* specific information that n...
Definition channel.h:144
fr_listen_t * listen
for tracking packet transport, etc.
Definition channel.h:148
#define FR_CONTROL_ID_CHANNEL
Definition channel.h:67
uint32_t priority
Priority of this packet.
Definition channel.h:142
Channel information which is added to a message.
Definition channel.h:106
int argc
current argument count
Definition command.h:39
char const * parent
e.g. "show module"
Definition command.h:52
#define CMD_TABLE_END
Definition command.h:62
char const ** argv
text version of commands
Definition command.h:42
#define FR_CONTROL_MAX_SIZE
Definition control.h:51
#define FR_CONTROL_MAX_MESSAGES
Definition control.h:50
#define fr_cond_assert(_x)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:131
#define fr_assert_msg(_x, _msg,...)
Calls panic_action ifndef NDEBUG, else logs error and causes the server to exit immediately with code...
Definition debug.h:202
#define fr_cond_assert_msg(_x, _fmt,...)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:148
#define MEM(x)
Definition debug.h:36
#define ERROR(fmt,...)
Definition dhcpclient.c:40
#define DEBUG(fmt,...)
Definition dhcpclient.c:38
#define fr_dlist_init(_head, _type, _field)
Initialise the head structure of a doubly linked list.
Definition dlist.h:242
static void * fr_dlist_head(fr_dlist_head_t const *list_head)
Return the HEAD item of a list or NULL if the list is empty.
Definition dlist.h:468
static bool fr_dlist_entry_in_list(fr_dlist_t const *entry)
Check if a list entry is part of a list.
Definition dlist.h:145
static void fr_dlist_entry_unlink(fr_dlist_t *entry)
Remove an item from the dlist when we don't have access to the head.
Definition dlist.h:128
static unsigned int fr_dlist_num_elements(fr_dlist_head_t const *head)
Return the number of elements in the dlist.
Definition dlist.h:921
static void * fr_dlist_pop_head(fr_dlist_head_t *list_head)
Remove the head item in a list.
Definition dlist.h:654
static int fr_dlist_insert_tail(fr_dlist_head_t *list_head, void *ptr)
Insert an item into the tail of a list.
Definition dlist.h:360
static void fr_dlist_entry_init(fr_dlist_t *entry)
Initialise a linked list without metadata.
Definition dlist.h:120
Head of a doubly linked list.
Definition dlist.h:51
int fr_heap_insert(fr_heap_t **hp, void *data)
Insert a new element into the heap.
Definition heap.c:149
int fr_heap_pop(void **out, fr_heap_t **hp)
Remove a node from the heap.
Definition heap.c:359
int fr_heap_extract(fr_heap_t **hp, void *data)
Remove a node from the heap.
Definition heap.c:259
static void * fr_heap_peek(fr_heap_t *h)
Return the item from the top of the heap but don't pop it.
Definition heap.h:138
static bool fr_heap_entry_inserted(fr_heap_index_t heap_idx)
Check if an entry is inserted into a heap.
Definition heap.h:126
static unsigned int fr_heap_num_elements(fr_heap_t *h)
Return the number of elements in the heap.
Definition heap.h:181
#define fr_heap_talloc_alloc(_ctx, _cmp, _talloc_type, _field, _init)
Creates a heap that verifies elements are of a specific talloc type.
Definition heap.h:117
The main heap structure.
Definition heap.h:68
talloc_free(hp)
rlm_rcode_t unlang_interpret(request_t *request, bool running)
Run the interpreter for a current request.
Definition interpret.c:1301
void unlang_interpret_set(request_t *request, unlang_interpret_t *intp)
Set a specific interpreter for a request.
Definition interpret.c:2474
int unlang_interpret_stack_depth(request_t *request)
Return the depth of the request's stack.
Definition interpret.c:1920
void unlang_interpret_set_thread_default(unlang_interpret_t *intp)
Set the default interpreter for this thread.
Definition interpret.c:2505
unlang_interpret_t * unlang_interpret_init(TALLOC_CTX *ctx, fr_event_list_t *el, unlang_request_func_t *funcs, void *uctx)
Initialize a unlang compiler / interpret.
Definition interpret.c:2433
bool unlang_request_is_cancelled(request_t const *request)
Return whether a request has been cancelled.
Definition interpret.c:1970
void unlang_interpret_signal(request_t *request, fr_signal_t action)
Send a signal (usually stop) to a request.
Definition interpret.c:1788
bool unlang_interpret_is_resumable(request_t *request)
Check if a request as resumable.
Definition interpret.c:1989
#define UNLANG_REQUEST_RESUME
Definition interpret.h:48
#define UNLANG_TOP_FRAME
Definition interpret.h:36
External functions provided by the owner of the interpret.
Definition interpret.h:116
uint64_t out
Definition base.h:43
uint64_t dup
Definition base.h:44
uint64_t dropped
Definition base.h:45
uint64_t in
Definition base.h:42
fr_control_t * fr_control_create(TALLOC_CTX *ctx, fr_event_list_t *el, fr_atomic_queue_t *aq, size_t num_callbacks)
Create a control-plane signaling path.
Definition control.c:152
int fr_control_callback_add(fr_control_t **c, uint32_t id, void *ctx, fr_control_callback_t callback)
Register a callback for an ID.
Definition control.c:444
int fr_control_open(fr_control_t *c)
Open the control-plane signalling path.
Definition control.c:176
int fr_control_message_send(fr_control_t *c, fr_ring_buffer_t *rb, uint32_t id, void *data, size_t data_size)
Send a control-plane message.
Definition control.c:355
The control structure.
Definition control.c:76
#define PERROR(_fmt,...)
Definition log.h:233
#define DEBUG3(_fmt,...)
Definition log.h:271
#define RDEBUG3(fmt,...)
Definition log.h:360
#define RWARN(fmt,...)
Definition log.h:314
#define PWARN(_fmt,...)
Definition log.h:232
#define RERROR(fmt,...)
Definition log.h:315
#define DEBUG4(_fmt,...)
Definition log.h:272
#define RPERROR(fmt,...)
Definition log.h:319
#define RPEDEBUG(fmt,...)
Definition log.h:393
#define RDEBUG4(fmt,...)
Definition log.h:361
#define RATE_LIMIT_GLOBAL(_log, _fmt,...)
Rate limit messages using a global limiting entry.
Definition log.h:658
void fr_event_service(fr_event_list_t *el)
Service any outstanding timer or file descriptor events.
Definition event.c:2204
int fr_event_corral(fr_event_list_t *el, fr_time_t now, bool wait)
Gather outstanding timer and file descriptor events.
Definition event.c:2072
int fr_event_post_delete(fr_event_list_t *el, fr_event_post_cb_t callback, void *uctx)
Delete a post-event callback from the event list.
Definition event.c:2050
#define fr_time()
Definition event.c:60
bool fr_event_loop_exiting(fr_event_list_t *el)
Check to see whether the event loop is in the process of exiting.
Definition event.c:2393
Stores all information relating to an event list.
Definition event.c:377
fr_log_lvl_t
Definition log.h:64
fr_packet_t * fr_packet_alloc(TALLOC_CTX *ctx, bool new_vector)
Allocate a new fr_packet_t.
Definition packet.c:38
void const * app_instance
Definition listen.h:39
fr_app_t const * app
Definition listen.h:38
void const * app_io_instance
I/O path configuration context.
Definition listen.h:33
CONF_SECTION * server_cs
CONF_SECTION of the server.
Definition listen.h:42
fr_dict_t const * dict
dictionary for this listener
Definition listen.h:30
fr_app_io_t const * app_io
I/O path functions.
Definition listen.h:32
Minimal data structure to use the new code.
Definition listen.h:63
unsigned int uint32_t
long int ssize_t
fr_message_set_t * fr_message_set_create(TALLOC_CTX *ctx, int num_messages, size_t message_size, size_t ring_buffer_size, bool unlimited_size)
Create a message set.
Definition message.c:127
int fr_message_done(fr_message_t *m)
Mark a message as done.
Definition message.c:195
fr_message_t * fr_message_and_data_commit(fr_message_set_t *ms, fr_message_t *m, size_t total_size)
Commit a previously reserved message, allocating exactly total_size bytes of packet data.
Definition message.c:1051
void fr_message_set_gc(fr_message_set_t *ms)
Garbage collect the message set.
Definition message.c:1321
fr_message_t * fr_message_and_data_reserve(fr_message_set_t *ms, size_t reserve_size)
Reserve a message.
Definition message.c:973
A Message set, composed of message headers and ring buffer data.
Definition message.c:94
size_t rb_size
cache-aligned size in the ring buffer
Definition message.h:51
fr_time_t when
when this message was sent
Definition message.h:47
uint8_t * data
pointer to the data in the ring buffer
Definition message.h:49
size_t data_size
size of the data in the ring buffer
Definition message.h:50
fr_cmp_ret_t
Result of an ordering comparison.
Definition misc.h:50
static const conf_parser_t config[]
Definition base.c:162
#define fr_assert(_expr)
Definition rad_assert.h:37
#define REDEBUG(fmt,...)
#define RDEBUG(fmt,...)
#define DEBUG2(fmt,...)
static void send_reply(int sockfd, fr_channel_data_t *reply)
int fr_rb_remove(void **removed, fr_rb_tree_t *tree, void const *data)
Remove an entry from the tree, without freeing the data.
Definition rb.c:718
int fr_rb_find(void **found, fr_rb_tree_t const *tree, void const *data)
Find an element in the tree, returning the data, not the node.
Definition rb.c:586
int fr_rb_delete(fr_rb_tree_t *tree, void const *data)
Remove node and free data (if a free function was specified)
Definition rb.c:767
int fr_rb_insert(fr_rb_tree_t *tree, void const *data)
Insert data into a tree.
Definition rb.c:637
#define fr_rb_inline_talloc_alloc(_ctx, _type, _field, _data_cmp, _data_free)
Allocs a red black that verifies elements are of a specific talloc type.
Definition rb.h:244
static bool fr_rb_node_inline_in_tree(fr_rb_node_t const *node)
Check to see if an item is in a tree by examining its inline fr_rb_node_t.
Definition rb.h:312
The main red black tree structure.
Definition rb.h:71
rlm_rcode_t
Return codes indicating the result of the module call.
Definition rcode.h:44
@ RLM_MODULE_TIMEOUT
Module (or section) timed out.
Definition rcode.h:56
int request_slab_deinit(request_t *request)
Callback for slabs to deinitialise the request.
Definition request.c:385
int request_detach(request_t *child)
Unlink a subrequest from its parent.
Definition request.c:544
#define REQUEST_VERIFY(_x)
Definition request.h:310
#define request_is_detached(_x)
Definition request.h:187
#define request_is_external(_x)
Definition request.h:185
#define request_is_internal(_x)
Definition request.h:186
@ REQUEST_TYPE_EXTERNAL
A request received on the wire.
Definition request.h:179
#define request_is_detachable(_x)
Definition request.h:188
#define REQUEST_POOL_NUM_OBJECTS
Definition request.h:68
#define request_init(_ctx, _type, _args)
Definition request.h:322
#define REQUEST_POOL_SIZE
Definition request.h:81
Optional arguments for initialising requests.
Definition request.h:288
fr_ring_buffer_t * fr_ring_buffer_create(TALLOC_CTX *ctx, size_t size)
Create a ring buffer.
Definition ring_buffer.c:64
static char const * name
@ FR_SIGNAL_DUP
A duplicate request was received.
Definition signal.h:44
@ FR_SIGNAL_CANCEL
Request has been cancelled.
Definition signal.h:40
#define FR_SLAB_FUNCS(_name, _type)
Define type specific wrapper functions for slabs and slab elements.
Definition slab.h:124
#define FR_SLAB_TYPES(_name, _type)
Define type specific wrapper structs for slabs and slab elements.
Definition slab.h:75
unsigned int num_children
How many child allocations are expected off each element.
Definition slab.h:48
size_t child_pool_size
Size of pool space to be allocated to each element.
Definition slab.h:49
return count
Definition module.c:155
@ memory_order_seq_cst
Definition stdatomic.h:132
#define atomic_fetch_add_explicit(object, operand, order)
Definition stdatomic.h:302
#define _Atomic(T)
Definition stdatomic.h:77
Definition log.h:93
#define fr_table_str_by_value(_table, _number, _def)
Convert an integer to a string.
Definition table.h:804
static int talloc_const_free(void const *ptr)
Free const'd memory.
Definition talloc.h:288
#define talloc_strdup(_ctx, _str)
Definition talloc.h:149
void fr_time_elapsed_update(fr_time_elapsed_t *elapsed, fr_time_t start, fr_time_t end)
Definition time.c:570
void fr_time_elapsed_fprint(FILE *fp, fr_time_elapsed_t const *elapsed, char const *prefix, int tab_offset)
Definition time.c:615
static fr_time_delta_t fr_time_delta_from_msec(int64_t msec)
Definition time.h:575
static int64_t fr_time_delta_unwrap(fr_time_delta_t time)
Definition time.h:154
#define fr_time_delta_lt(_a, _b)
Definition time.h:285
static fr_time_delta_t fr_time_delta_from_sec(int64_t sec)
Definition time.h:590
#define fr_time_delta_wrap(_time)
Definition time.h:152
#define fr_time_delta_ispos(_a)
Definition time.h:290
#define fr_time_eq(_a, _b)
Definition time.h:241
#define NSEC
Definition time.h:379
#define fr_time_add(_a, _b)
Add a time/time delta together.
Definition time.h:196
#define fr_time_sub(_a, _b)
Subtract one time from another.
Definition time.h:229
static fr_time_delta_t fr_time_delta_div(fr_time_delta_t a, fr_time_delta_t b)
Definition time.h:267
static int8_t fr_time_cmp(fr_time_t a, fr_time_t b)
Compare two fr_time_t values.
Definition time.h:916
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
"server local" time.
Definition time.h:69
@ FR_TIME_TRACKING_YIELDED
We're currently tracking time in the yielded state.
static void fr_time_tracking_yield(fr_time_tracking_t *tt, fr_time_t now)
Transition to the yielded state, recording the time we just spent running.
static void fr_time_tracking_end(fr_time_delta_t *predicted, fr_time_tracking_t *tt, fr_time_t now)
End time tracking for this entity.
fr_time_delta_t waiting_total
total time spent waiting
fr_time_delta_t running_total
total time spent running
static void fr_time_tracking_start(fr_time_tracking_t *parent, fr_time_tracking_t *tt, fr_time_t now)
Start time tracking for a tracked entity.
static void fr_time_tracking_resume(fr_time_tracking_t *tt, fr_time_t now)
Track that a request resumed.
static void fr_time_tracking_debug(fr_time_tracking_t *tt, FILE *fp)
Print debug information about the time tracking structure.
uint64_t fr_timer_list_num_events(fr_timer_list_t *tl)
Return number of pending events.
Definition timer.c:1154
fr_timer_list_t * fr_timer_list_ordered_alloc(TALLOC_CTX *ctx, fr_timer_list_t *parent)
Allocate a new sorted event timer list.
Definition timer.c:1296
int fr_timer_list_force_run(fr_timer_list_t *tl)
Forcibly run all events in an event loop.
Definition timer.c:922
An event timer list.
Definition timer.c:49
#define fr_timer_in(...)
Definition timer.h:87
static bool fr_timer_armed(fr_timer_t *ev)
Definition timer.h:120
static fr_event_list_t * el
void fr_perror(char const *fmt,...)
Print the current error to stderr with a prefix.
Definition strerror.c:737
#define fr_strerror_const_push(_msg)
Definition strerror.h:227
#define fr_strerror_const(_msg)
Definition strerror.h:223
static fr_slen_t data
Definition value.h:1340
fr_heap_t * runnable
current runnable requests which we've spent time processing
Definition worker.c:109
static void worker_request_time_tracking_end(fr_worker_t *worker, request_t *request, fr_time_t now)
Definition worker.c:582
static void _worker_request_yield(request_t *request, UNUSED void *uctx)
Interpreter yielded request.
Definition worker.c:1267
static void worker_channel_callback(void *ctx, void const *data, size_t data_size, fr_time_t now)
Handle a control plane message sent to the worker via a channel.
Definition worker.c:243
fr_event_list_t * el
our event list
Definition worker.c:105
int fr_worker_pre_event(UNUSED fr_time_t now, UNUSED fr_time_delta_t wake, void *uctx)
Pre-event handler.
Definition worker.c:1575
static void worker_send_reply(fr_worker_t *worker, request_t *request, bool do_not_respond, fr_time_t now)
Send a response packet to the network side.
Definition worker.c:599
fr_channel_t * fr_worker_channel_create(fr_worker_t *worker, TALLOC_CTX *ctx, fr_control_t *master)
Create a channel to the worker.
Definition worker.c:1635
fr_rb_tree_t * listeners
so we can cancel requests when a listener goes away
Definition worker.c:116
static void worker_run_request(fr_worker_t *worker, fr_time_t start)
Run a request.
Definition worker.c:1316
static void worker_exit(fr_worker_t *worker)
Definition worker.c:221
#define WORKER_VERIFY
Definition worker.c:67
bool was_sleeping
used to suppress multiple sleep signals in a row
Definition worker.c:128
static int cmd_stats_worker(FILE *fp, UNUSED FILE *fp_err, void *ctx, fr_cmd_info_t const *info)
Definition worker.c:1728
static void _worker_request_runnable(request_t *request, void *uctx)
Request is now runnable.
Definition worker.c:1256
static char * itoa_internal(TALLOC_CTX *ctx, uint64_t number)
Definition worker.c:726
fr_worker_t * fr_worker_alloc(TALLOC_CTX *ctx, fr_event_list_t *el, char const *name, fr_log_t const *logger, fr_log_lvl_t lvl, fr_worker_config_t *config)
Create a worker.
Definition worker.c:1365
fr_worker_channel_t * channel
list of channels
Definition worker.c:131
char const * name
name of this worker
Definition worker.c:91
uint64_t num_active
number of active requests
Definition worker.c:123
fr_cmd_table_t cmd_worker_table[]
Definition worker.c:1766
static int worker_request_time_tracking_start(fr_worker_t *worker, request_t *request, fr_time_t now)
Start time tracking for a request, and mark it as runnable.
Definition worker.c:552
int fr_worker_stats(fr_worker_t const *worker, int num, uint64_t *stats)
Definition worker.c:1711
static int _worker_request_deinit(request_t *request, UNUSED void *uctx)
Definition worker.c:779
static void _worker_request_done_detached(request_t *request, UNUSED rlm_rcode_t rcode, UNUSED void *uctx)
Detached request (i.e.
Definition worker.c:1191
static void _worker_request_resume(request_t *request, UNUSED void *uctx)
Interpreter is starting to work on request again.
Definition worker.c:1276
static fr_cmp_ret_t worker_dedup_cmp(void const *one, void const *two)
Track a request_t in the "dedup" tree.
Definition worker.c:1002
fr_rb_tree_t * dedup
de-dup tree
Definition worker.c:114
fr_atomic_queue_t * aq_control
atomic queue for control messages sent to me
Definition worker.c:101
static void worker_nak(fr_worker_t *worker, fr_channel_data_t *cd, fr_time_t now)
Send a NAK to the network thread.
Definition worker.c:422
static void worker_request_name_number(request_t *request)
Definition worker.c:766
static void _worker_request_timeout(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t when, void *uctx)
Enforce max_request_time.
Definition worker.c:532
static void worker_request_bootstrap(fr_worker_t *worker, fr_channel_data_t *cd, fr_time_t now)
Definition worker.c:784
fr_log_t const * log
log destination
Definition worker.c:98
fr_io_stats_t stats
input / output stats
Definition worker.c:118
#define CHECK_CONFIG(_x, _min, _max)
static void _worker_request_detach(request_t *request, void *uctx)
Make us responsible for running the request.
Definition worker.c:1224
static int _fr_worker_rb_free(void *arg)
Definition worker.c:161
fr_time_tracking_t tracking
how much time the worker has spent doing things.
Definition worker.c:126
static void _worker_request_done_external(request_t *request, UNUSED rlm_rcode_t rcode, void *uctx)
External request is now complete.
Definition worker.c:1105
void fr_worker_destroy(fr_worker_t *worker)
Destroy a worker.
Definition worker.c:1025
static fr_cmp_ret_t worker_runnable_cmp(void const *one, void const *two)
Track a request_t in the "runnable" heap.
Definition worker.c:976
uint64_t num_naks
number of messages which were nak'd
Definition worker.c:122
static void worker_request_init(fr_worker_t *worker, request_t *request, fr_time_t now)
Initialize various request fields needed by the worker.
Definition worker.c:749
fr_worker_config_t config
external configuration
Definition worker.c:92
fr_listen_t const * listener
incoming packets
Definition worker.c:137
unlang_interpret_t * intp
Worker's local interpreter.
Definition worker.c:94
static int fr_worker_listen_cancel_self(fr_worker_t *worker, fr_listen_t const *li)
Definition worker.c:373
static void worker_stop_request(request_t *request)
Signal the unlang interpreter that it needs to stop running the request.
Definition worker.c:513
static void _worker_request_prioritise(request_t *request, void *uctx)
Update a request's priority.
Definition worker.c:1293
bool exiting
are we exiting?
Definition worker.c:129
fr_log_lvl_t lvl
log level
Definition worker.c:99
static void worker_requests_cancel(fr_worker_channel_t *ch)
Definition worker.c:212
int num_channels
actual number of channels
Definition worker.c:107
fr_time_delta_t max_request_time
maximum time a request can be processed
Definition worker.c:112
fr_time_elapsed_t cpu_time
histogram of total CPU time per request
Definition worker.c:119
fr_rb_node_t node
in tree of listeners
Definition worker.c:139
int fr_worker_listen_cancel(fr_worker_t *worker, fr_listen_t const *li)
Definition worker.c:1662
void fr_worker_post_event(UNUSED fr_event_list_t *el, UNUSED fr_time_t now, void *uctx)
Post-event handler.
Definition worker.c:1596
fr_dlist_head_t dlist
of requests associated with this listener.
Definition worker.c:145
void fr_worker(fr_worker_t *worker)
The main loop and entry point of the stand-alone worker thread.
Definition worker.c:1517
request_slab_list_t * slab
slab allocator for request_t
Definition worker.c:133
static uint32_t worker_num_requests(fr_worker_t *worker)
Definition worker.c:774
fr_time_delta_t predicted
How long we predict a request will take to execute.
Definition worker.c:125
pthread_t thread_id
my thread ID
Definition worker.c:96
static void worker_recv_request(void *ctx, fr_channel_t *ch, fr_channel_data_t *cd)
Callback which handles a message being received on the worker side.
Definition worker.c:202
fr_time_elapsed_t wall_clock
histogram of wall clock time per request
Definition worker.c:120
static bool is_worker_thread(fr_worker_t const *worker)
Definition worker.c:188
fr_worker_channel_t
Definition worker.c:85
fr_timer_list_t * timeout
Track when requests timeout using a dlist.
Definition worker.c:111
static fr_ring_buffer_t * fr_worker_rb_init(void)
Initialise thread local storage.
Definition worker.c:170
fr_control_t * control
the control plane
Definition worker.c:103
static bool _worker_request_scheduled(request_t const *request, UNUSED void *uctx)
Check if a request is scheduled.
Definition worker.c:1285
static void _worker_request_done_internal(request_t *request, UNUSED rlm_rcode_t rcode, void *uctx)
Internal request (i.e.
Definition worker.c:1175
void fr_worker_debug(fr_worker_t *worker, FILE *fp)
Print debug information about the worker structure.
Definition worker.c:1608
static void _worker_request_internal_init(request_t *request, void *uctx)
Internal request (i.e.
Definition worker.c:1084
static fr_cmp_ret_t worker_listener_cmp(void const *one, void const *two)
Definition worker.c:149
#define CHECK_CONFIG_TIME_DELTA(_x, _min, _max)
static void worker_listen_cancel_callback(void *ctx, void const *data, NDEBUG_UNUSED size_t data_size, UNUSED fr_time_t now)
A socket is going away, so clean up any requests which use this socket.
Definition worker.c:400
A worker which takes packets from a master, and processes them.
Definition worker.c:90
int message_set_size
default start number of messages
Definition worker.h:73
#define FR_CONTROL_ID_LISTEN_DEAD
Definition worker.h:40
int max_requests
max requests this worker will handle
Definition worker.h:69
int max_channels
maximum number of channels
Definition worker.h:71
fr_slab_config_t reuse
slab allocator configuration
Definition worker.h:78
int ring_buffer_size
default start size for the ring buffers
Definition worker.h:74
fr_time_delta_t max_request_time
maximum time a request can be processed
Definition worker.h:76