The FreeRADIUS server $Id: a4e7f8c94e8038b7627bcf52356b7ed15955c1d7 $
Loading...
Searching...
No Matches
trunk.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 (at
5 * 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: 375f9ef2e8e9a779002747d4ebf4cea410147860 $
19 *
20 * @file src/lib/server/trunk.c
21 * @brief A management API for bonding multiple connections together.
22 *
23 * @copyright 2019-2020 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
24 * @copyright 2019-2020 The FreeRADIUS server project
25 */
26
27#define LOG_PREFIX trunk->log_prefix
28
29#ifdef NDEBUG
30# define TALLOC_GET_TYPE_ABORT_NOOP 1
31#endif
32
35typedef struct trunk_s trunk_t;
36#define _TRUNK_PRIVATE 1
37#include <freeradius-devel/server/trunk.h>
38
39#include <freeradius-devel/server/trigger.h>
40#include <freeradius-devel/util/debug.h>
41#include <freeradius-devel/util/misc.h>
42#include <freeradius-devel/util/syserror.h>
43#include <freeradius-devel/util/minmax_heap.h>
44
45#ifdef HAVE_STDATOMIC_H
46# include <stdatomic.h>
47# ifndef ATOMIC_VAR_INIT
48# define ATOMIC_VAR_INIT(_x) (_x)
49# endif
50#else
51# include <freeradius-devel/util/stdatomic.h>
52#endif
53
54static atomic_uint_fast64_t request_counter = ATOMIC_VAR_INIT(1);
55
56#ifdef TESTING_TRUNK
58
59static fr_time_t test_time(void)
60{
61 return test_time_base;
62}
63
64#define fr_time test_time
65#endif
66
67#ifndef NDEBUG
68/** The maximum number of state logs to record per request
69 *
70 */
71#define TRUNK_REQUEST_STATE_LOG_MAX 20
72
73/** Trace state machine changes for a particular request
74 *
75 */
76typedef struct {
77 fr_dlist_head_t *log_head; //!< To allow the log entry to remove itself on free.
78 fr_dlist_t entry; //!< Entry in the linked list.
79 trunk_request_state_t from; //!< What state we transitioned from.
80 trunk_request_state_t to; //!< What state we transitioned to.
81
82 trunk_connection_t *tconn; //!< The request was associated with.
83 ///< Pointer may now be invalid, do no de-reference.
84
85 uint64_t tconn_id; //!< If the treq was associated with a connection
86 ///< the connection ID.
87 trunk_connection_state_t tconn_state; //!< If the treq was associated with a connection
88 ///< the connection state at the time of the
89 ///< state transition.
90
91 char const *function; //!< State change occurred in.
92 int line; //!< Line change occurred on.
94#endif
95
96/** Wraps a normal request
97 *
98 */
100 struct trunk_request_pub_s pub; //!< Public fields in the trunk request.
101 ///< This *MUST* be the first field in this
102 ///< structure.
103
104 uint64_t id; //!< Trunk request ID.
105
106 fr_heap_index_t heap_id; //!< Used to track the request conn->pending heap.
107
108 fr_dlist_t entry; //!< Used to track the trunk request in the conn->sent
109 ///< or trunk->backlog request.
110
111 trunk_cancel_reason_t cancel_reason; //!< Why this request was cancelled.
112
113 fr_time_t last_freed; //!< Last time this request was freed.
114
115 bool bound_to_conn; //!< Fail the request if there's an attempt to
116 ///< re-enqueue it.
117
118 bool sent; //!< Trunk request has been sent at least once.
119 ///< Used so that re-queueing doesn't increase trunk
120 ///< `sent` count.
121
122 bool blocking; //!< The request will block the connection until it is
123 ///< completed, so no more requests should be enqueued
124 ///< on this connection until the treq is completed.
125
126#ifndef NDEBUG
127 fr_dlist_head_t log; //!< State change log.
128#endif
129};
130
131
132/** Associates request queues with a connection
133 *
134 * @dotfile src/lib/server/trunk_conn.gv "Trunk connection state machine"
135 * @dotfile src/lib/server/trunk_req.gv "Trunk request state machine"
136 */
138 struct trunk_connection_pub_s pub; //!< Public fields in the trunk connection.
139 ///< This *MUST* be the first field in this
140 ///< structure.
141
142 fr_heap_index_t heap_id; //!< Used to track the connection in the connected
143 ///< heap.
144
145 fr_dlist_t entry; //!< Used to track the connection in the connecting,
146 ///< full and failed lists.
147
148 /** @name State
149 * @{
150 */
151 trunk_connection_event_t events; //!< The current events we expect to be notified on.
152 /** @} */
153
154 /** @name Request lists
155 * @{
156 */
157 fr_heap_t *pending; //!< Requests waiting to be sent.
158
159 trunk_request_t *partial; //!< Partially written request.
160
161 fr_dlist_head_t sent; //!< Sent request.
162
163 fr_dlist_head_t reapable; //!< Idle request.
164
165 fr_dlist_head_t cancel; //!< Requests in the cancel state.
166
167 trunk_request_t *cancel_partial; //!< Partially written cancellation request.
168
169 fr_dlist_head_t cancel_sent; //!< Sent cancellation request.
170 /** @} */
171
172 /** @name Statistics
173 * @{
174 */
175 uint64_t sent_count; //!< The number of requests that have been sent using
176 ///< this connection.
177 /** @} */
178
179 /** @name Timers
180 * @{
181 */
182 fr_timer_t *lifetime_ev; //!< Maximum time this connection can be open.
183 /** @} */
184};
185
186/** An entry in a trunk watch function list
187 *
188 */
189typedef struct trunk_watch_entry_s {
190 fr_dlist_t entry; //!< List entry.
191 trunk_watch_t func; //!< Function to call when a trunk enters
192 ///< the state this list belongs to
193 bool oneshot; //!< Remove the function after it's called once.
194 bool enabled; //!< Whether the watch entry is enabled.
195 void *uctx; //!< User data to pass to the function.
197
198/** Map connection states to trigger names
199 *
200 * Must stay in the same order as #trunk_connection_state_t
201 */
203 { L("pool.connection_halted"), TRUNK_CONN_HALTED }, /* 0x0000 - bit 0 */
204 { L("pool.connection_init"), TRUNK_CONN_INIT }, /* 0x0001 - bit 1 */
205 { L("pool.connection_connecting"), TRUNK_CONN_CONNECTING }, /* 0x0002 - bit 2 */
206 { L("pool.connection_active"), TRUNK_CONN_ACTIVE }, /* 0x0004 - bit 3 */
207 { L("pool.connection_closed"), TRUNK_CONN_CLOSED }, /* 0x0008 - bit 4 */
208 { L("pool.connection_full"), TRUNK_CONN_FULL }, /* 0x0010 - bit 5 */
209 { L("pool.connection_inactive"), TRUNK_CONN_INACTIVE }, /* 0x0020 - bit 6 */
210 { L("pool.connection_inactive_draining"), TRUNK_CONN_INACTIVE_DRAINING }, /* 0x0040 - bit 7 */
211 { L("pool.connection_draining"), TRUNK_CONN_DRAINING }, /* 0x0080 - bit 8 */
212 { L("pool.connection_draining_to_free"), TRUNK_CONN_DRAINING_TO_FREE } /* 0x0100 - bit 9 */
213};
215
216/** Main trunk management handle
217 *
218 */
219struct trunk_s {
220 struct trunk_pub_s pub; //!< Public fields in the trunk connection.
221 ///< This *MUST* be the first field in this
222 ///< structure.
223
224 char const *log_prefix; //!< What to prepend to messages.
225
226 fr_event_list_t *el; //!< Event list used by this trunk and the connection.
227
228 trunk_conf_t conf; //!< Trunk common configuration.
229
230 fr_dlist_head_t free_requests; //!< Requests in the unassigned state. Waiting to be
231 ///< enqueued.
232
233 fr_heap_t *backlog; //!< The request backlog. Requests we couldn't
234 ///< immediately assign to a connection.
235
236 /** @name Connection lists
237 *
238 * A connection must always be in exactly one of these lists
239 * or trees.
240 *
241 * @{
242 */
243 fr_dlist_head_t init; //!< Connections which have not yet started
244 ///< connecting.
245
246 fr_dlist_head_t connecting; //!< Connections which are not yet in the open state.
247
248 fr_minmax_heap_t *active; //!< Connections which can service requests.
249
250 fr_dlist_head_t full; //!< Connections which have too many outstanding
251 ///< requests.
252
253 fr_dlist_head_t inactive; //!< Connections which have been signalled to be
254 ///< inactive by the API client.
255
256 fr_dlist_head_t inactive_draining; //!< Connections which have been signalled to be
257 ///< inactive by the API client, which the trunk
258 ///< manager is draining to close.
259
260 fr_dlist_head_t failed; //!< Connections that'll be reconnected shortly.
261
262 fr_dlist_head_t closed; //!< Connections that have closed. Either due to
263 ///< shutdown, reconnection or failure.
264
265 fr_dlist_head_t draining; //!< Connections that will be freed once all their
266 ///< requests are complete, but can be reactivated.
267
268 fr_dlist_head_t draining_to_free; //!< Connections that will be freed once all their
269 ///< requests are complete.
270
271 fr_dlist_head_t to_free; //!< Connections we're done with and will free on
272 //!< the next call to trunk_manage.
273 //!< This prevents connections from being freed
274 //!< whilst we're inside callbacks.
275 /** @} */
276
277 /** @name Callbacks
278 * @{
279 */
280 trunk_io_funcs_t funcs; //!< I/O functions.
281
282 void *in_handler; //!< Which handler we're inside.
283
284 void *uctx; //!< Uctx data to pass to alloc.
285
286 fr_dlist_head_t watch[TRUNK_STATE_MAX]; //!< To be called when trunk changes state.
287
288 trunk_watch_entry_t *next_watcher; //!< Watcher about to be run. Used to prevent nested watchers.
289 /** @} */
290
291 /** @name Timers
292 * @{
293 */
294 fr_timer_t *manage_ev; //!< Periodic connection management event.
295 /** @} */
296
297 /** @name Log rate limiting entries
298 * @{
299 */
300 fr_rate_limit_t limit_max_requests_alloc_log; //!< Rate limit on "Refusing to alloc requests - Limit of * requests reached"
301
302 fr_rate_limit_t limit_last_failure_log; //!< Rate limit on "Refusing to enqueue requests - No active conns"
303 /** @} */
304
305 /** @name State
306 * @{
307 */
308 bool freeing; //!< Trunk is being freed, don't spawn new
309 ///< connections or re-enqueue.
310
311 bool started; //!< Has the trunk been started.
312
313 bool managing_connections; //!< Whether the trunk is allowed to manage
314 ///< (open/close) connections.
315
316 uint64_t last_req_per_conn; //!< The last request to connection ratio we calculated.
317 /** @} */
318
319 fr_pair_list_t *trigger_args; //!< Passed to trigger
320
321 bool trigger_undef[NUM_ELEMENTS(trunk_conn_trigger_names)]; //!< Record that a specific trigger is undefined.
322
324};
325
326int trunk_trigger_cf_parse(TALLOC_CTX *ctx, void *out, void *parent, CONF_ITEM *ci, conf_parser_t const *rule);
327
329 { FR_CONF_OFFSET("per_connection_max", trunk_conf_t, max_req_per_conn), .dflt = "2000" },
330 { FR_CONF_OFFSET("per_connection_target", trunk_conf_t, target_req_per_conn), .dflt = "1000" },
331 { FR_CONF_OFFSET("free_delay", trunk_conf_t, req_cleanup_delay), .dflt = "10.0" },
332 { FR_CONF_OFFSET("triggers", trunk_conf_t, req_triggers), .func = trunk_trigger_cf_parse },
333
335};
336
338 { FR_CONF_OFFSET("connect_timeout", connection_conf_t, connection_timeout), .dflt = "3.0", .func = cf_parse_time_delta_bounded, .uctx = &cf_time_delta_bounds_int_msec },
339 { FR_CONF_OFFSET("reconnect_delay", connection_conf_t, reconnection_delay), .dflt = "1" },
340
342};
343
344#ifndef TRUNK_TESTS
346 { L("queue"), TRUNK_SORT_QUEUE },
347 { L("mru"), TRUNK_SORT_MRU },
348 { L("lru"), TRUNK_SORT_LRU },
349};
351
353 { FR_CONF_OFFSET("start", trunk_conf_t, start), .dflt = "1" },
354 { FR_CONF_OFFSET("min", trunk_conf_t, min), .dflt = "1" },
355 { FR_CONF_OFFSET("max", trunk_conf_t, max), .dflt = "5" },
356 { FR_CONF_OFFSET("connecting", trunk_conf_t, connecting), .dflt = "2" },
357 { FR_CONF_OFFSET("uses", trunk_conf_t, max_uses), .dflt = "0" },
358 { FR_CONF_OFFSET("lifetime", trunk_conf_t, lifetime), .dflt = "0" },
359 { FR_CONF_OFFSET("idle_timeout", trunk_conf_t, idle_timeout), .dflt = "0" },
360
361 { FR_CONF_OFFSET("open_delay", trunk_conf_t, open_delay), .dflt = "0.2" },
362 { FR_CONF_OFFSET("close_delay", trunk_conf_t, close_delay), .dflt = "10.0" },
363
364 { FR_CONF_OFFSET("manage_interval", trunk_conf_t, manage_interval), .dflt = "0.2" },
365
368 .uctx = &(cf_table_parse_ctx_t){
369 .table = trunk_sort_table,
371 },
372 .dflt = "mru" },
373
374 { FR_CONF_OFFSET("time_window", trunk_conf_t, time_window), .dflt = "0.1" },
375
376 { FR_CONF_OFFSET("max_backlog", trunk_conf_t, max_backlog), .dflt = "1000" },
377
378 { FR_CONF_OFFSET("backlog_on_failed_conn", trunk_conf_t, backlog_on_failed_conn), },
379
380 { FR_CONF_OFFSET("triggers", trunk_conf_t, conn_triggers), .func = trunk_trigger_cf_parse },
381
382 { FR_CONF_OFFSET_SUBSECTION("connection", 0, trunk_conf_t, conn_conf, trunk_config_connection), .subcs_size = sizeof(trunk_config_connection) },
383 { FR_CONF_POINTER("request", 0, CONF_FLAG_SUBSECTION, NULL), .subcs = (void const *) trunk_config_request },
384
386};
387#endif
388
389#ifndef NDEBUG
390/** Map request states to trigger names
391 *
392 * Must stay in the same order as #trunk_connection_state_t
393 */
395 { L("pool.request_init"), TRUNK_REQUEST_STATE_INIT }, /* 0x0000 - bit 0 */
396 { L("pool.request_unassigned"), TRUNK_REQUEST_STATE_UNASSIGNED }, /* 0x0001 - bit 1 */
397 { L("pool.request_backlog"), TRUNK_REQUEST_STATE_BACKLOG }, /* 0x0002 - bit 2 */
398 { L("pool.request_pending"), TRUNK_REQUEST_STATE_PENDING }, /* 0x0004 - bit 3 */
399 { L("pool.request_partial"), TRUNK_REQUEST_STATE_PARTIAL }, /* 0x0008 - bit 4 */
400 { L("pool.request_sent"), TRUNK_REQUEST_STATE_SENT }, /* 0x0010 - bit 5 */
401 { L("pool.request_state_reapable"), TRUNK_REQUEST_STATE_REAPABLE }, /* 0x0020 - bit 6 */
402 { L("pool.request_complete"), TRUNK_REQUEST_STATE_COMPLETE }, /* 0x0040 - bit 7 */
403 { L("pool.request_state_failed"), TRUNK_REQUEST_STATE_FAILED }, /* 0x0080 - bit 8 */
404 { L("pool.request_state_cancel"), TRUNK_REQUEST_STATE_CANCEL }, /* 0x0100 - bit 9 */
405 { L("pool.request_state_cancel_sent"), TRUNK_REQUEST_STATE_CANCEL_SENT }, /* 0x0200 - bit 10 */
406 { L("pool.request_state_cancel_partial"), TRUNK_REQUEST_STATE_CANCEL_PARTIAL }, /* 0x0400 - bit 11 */
407 { L("pool.request_state_cancel_complete"), TRUNK_REQUEST_STATE_CANCEL_COMPLETE }, /* 0x0800 - bit 12 */
408};
410#endif
411
413 { L("INIT"), TRUNK_REQUEST_STATE_INIT },
414 { L("UNASSIGNED"), TRUNK_REQUEST_STATE_UNASSIGNED },
415 { L("BACKLOG"), TRUNK_REQUEST_STATE_BACKLOG },
416 { L("PENDING"), TRUNK_REQUEST_STATE_PENDING },
417 { L("PARTIAL"), TRUNK_REQUEST_STATE_PARTIAL },
418 { L("SENT"), TRUNK_REQUEST_STATE_SENT },
419 { L("REAPABLE"), TRUNK_REQUEST_STATE_REAPABLE },
420 { L("COMPLETE"), TRUNK_REQUEST_STATE_COMPLETE },
421 { L("FAILED"), TRUNK_REQUEST_STATE_FAILED },
422 { L("CANCEL"), TRUNK_REQUEST_STATE_CANCEL },
423 { L("CANCEL-SENT"), TRUNK_REQUEST_STATE_CANCEL_SENT },
424 { L("CANCEL-PARTIAL"), TRUNK_REQUEST_STATE_CANCEL_PARTIAL },
425 { L("CANCEL-COMPLETE"), TRUNK_REQUEST_STATE_CANCEL_COMPLETE }
426};
428
430 { L("IDLE"), TRUNK_STATE_IDLE },
431 { L("ACTIVE"), TRUNK_STATE_ACTIVE },
432 { L("PENDING"), TRUNK_STATE_PENDING },
433 { L("FULL"), TRUNK_STATE_FULL },
434 { L("FAILED"), TRUNK_STATE_FAILED }
435};
437
439 { L("INIT"), TRUNK_CONN_INIT },
440 { L("HALTED"), TRUNK_CONN_HALTED },
441 { L("CONNECTING"), TRUNK_CONN_CONNECTING },
442 { L("ACTIVE"), TRUNK_CONN_ACTIVE },
443 { L("CLOSED"), TRUNK_CONN_CLOSED },
444 { L("FULL"), TRUNK_CONN_FULL },
445 { L("INACTIVE"), TRUNK_CONN_INACTIVE },
446 { L("INACTIVE-DRAINING"), TRUNK_CONN_INACTIVE_DRAINING },
447 { L("DRAINING"), TRUNK_CONN_DRAINING },
448 { L("DRAINING-TO-FREE"), TRUNK_CONN_DRAINING_TO_FREE }
449};
451
453 { L("TRUNK_CANCEL_REASON_NONE"), TRUNK_CANCEL_REASON_NONE },
454 { L("TRUNK_CANCEL_REASON_SIGNAL"), TRUNK_CANCEL_REASON_SIGNAL },
455 { L("TRUNK_CANCEL_REASON_MOVE"), TRUNK_CANCEL_REASON_MOVE },
456 { L("TRUNK_CANCEL_REASON_REQUEUE"), TRUNK_CANCEL_REASON_REQUEUE }
457};
459
461 { L("TRUNK_CONN_EVENT_NONE"), TRUNK_CONN_EVENT_NONE },
462 { L("TRUNK_CONN_EVENT_READ"), TRUNK_CONN_EVENT_READ },
463 { L("TRUNK_CONN_EVENT_WRITE"), TRUNK_CONN_EVENT_WRITE },
464 { L("TRUNK_CONN_EVENT_BOTH"), TRUNK_CONN_EVENT_BOTH },
465};
467
468#define CONN_TRIGGER(_state) do { \
469 uint8_t idx = fr_high_bit_pos(_state); \
470 if (trunk->conf.conn_triggers && !trunk->trigger_undef[idx]) { \
471 if (trigger(unlang_interpret_get_thread_default(), trunk->conf.conn_trigger_cs, \
472 &trunk->trigger_cp[idx], \
473 fr_table_str_by_value(trunk_conn_trigger_names, _state, \
474 "<INVALID>"), true, trunk->trigger_args, trunk) == -1) { \
475 trunk->trigger_undef[idx] = true; \
476 } \
477 } \
478} while (0)
479
480#define CONN_STATE_TRANSITION(_new, _log) \
481do { \
482 _log("[%" PRIu64 "] Trunk connection changed state %s -> %s", \
483 tconn->pub.conn->id, \
484 fr_table_str_by_value(trunk_connection_states, tconn->pub.state, "<INVALID>"), \
485 fr_table_str_by_value(trunk_connection_states, _new, "<INVALID>")); \
486 tconn->pub.state = _new; \
487 CONN_TRIGGER(_new); \
488 trunk_requests_per_connection(NULL, NULL, trunk, fr_time(), false); \
489} while (0)
490
491#define CONN_BAD_STATE_TRANSITION(_new) \
492do { \
493 if (!fr_cond_assert_msg(0, "[%" PRIu64 "] Trunk connection invalid transition %s -> %s", \
494 tconn->pub.conn->id, \
495 fr_table_str_by_value(trunk_connection_states, tconn->pub.state, "<INVALID>"), \
496 fr_table_str_by_value(trunk_connection_states, _new, "<INVALID>"))) return; \
497} while (0)
498
499#ifndef NDEBUG
500void trunk_request_state_log_entry_add(char const *function, int line,
501 trunk_request_t *treq, trunk_request_state_t new) CC_HINT(nonnull);
502
503#define REQUEST_TRIGGER(_state) do { \
504 if (trunk->conf.req_triggers) { \
505 trigger(unlang_interpret_get_thread_default(), \
506 trunk->conf.req_trigger_cs, NULL, fr_table_str_by_value(trunk_req_trigger_names, _state, \
507 "<INVALID>"), true, trunk->trigger_args, trunk); \
508 } \
509} while (0)
510
511/** Record a request state transition and log appropriate output
512 *
513 */
514#define REQUEST_STATE_TRANSITION(_new) \
515do { \
516 request_t *request = treq->pub.request; \
517 ROPTIONAL(RDEBUG3, DEBUG3, "Trunk request %" PRIu64 " changed state %s -> %s", \
518 treq->id, \
519 fr_table_str_by_value(trunk_request_states, treq->pub.state, "<INVALID>"), \
520 fr_table_str_by_value(trunk_request_states, _new, "<INVALID>")); \
521 trunk_request_state_log_entry_add(__FUNCTION__, __LINE__, treq, _new); \
522 treq->pub.state = _new; \
523 REQUEST_TRIGGER(_new); \
524} while (0)
525#define REQUEST_BAD_STATE_TRANSITION(_new) \
526do { \
527 trunk_request_state_log(&default_log, L_ERR, __FILE__, __LINE__, treq); \
528 if (!fr_cond_assert_msg(0, "Trunk request %" PRIu64 " invalid transition %s -> %s", \
529 treq->id, \
530 fr_table_str_by_value(trunk_request_states, treq->pub.state, "<INVALID>"), \
531 fr_table_str_by_value(trunk_request_states, _new, "<INVALID>"))) return; \
532} while (0)
533#else
534/** Record a request state transition
535 *
536 */
537#define REQUEST_STATE_TRANSITION(_new) \
538do { \
539 request_t *request = treq->pub.request; \
540 ROPTIONAL(RDEBUG3, DEBUG3, "Trunk request %" PRIu64 " changed state %s -> %s", \
541 treq->id, \
542 fr_table_str_by_value(trunk_request_states, treq->pub.state, "<INVALID>"), \
543 fr_table_str_by_value(trunk_request_states, _new, "<INVALID>")); \
544 treq->pub.state = _new; \
545} while (0)
546#define REQUEST_BAD_STATE_TRANSITION(_new) \
547do { \
548 if (!fr_cond_assert_msg(0, "Trunk request %" PRIu64 " invalid transition %s -> %s", \
549 treq->id, \
550 fr_table_str_by_value(trunk_request_states, treq->pub.state, "<INVALID>"), \
551 fr_table_str_by_value(trunk_request_states, _new, "<INVALID>"))) return; \
552} while (0)
553#endif
554
555
556/** Call the cancel callback if set
557 *
558 */
559#define DO_REQUEST_CANCEL(_treq, _reason) \
560do { \
561 if ((_treq)->pub.trunk->funcs.request_cancel) { \
562 request_t *request = (_treq)->pub.request; \
563 void *_prev = (_treq)->pub.trunk->in_handler; \
564 (_treq)->pub.trunk->in_handler = (void *)(_treq)->pub.trunk->funcs.request_cancel; \
565 ROPTIONAL(RDEBUG3, DEBUG3, "Calling request_cancel(conn=%p, preq=%p, reason=%s, uctx=%p)", \
566 (_treq)->pub.tconn->pub.conn, \
567 (_treq)->pub.preq, \
568 fr_table_str_by_value(trunk_cancellation_reasons, \
569 (_reason), \
570 "<INVALID>"), \
571 (_treq)->pub.trunk->uctx); \
572 (_treq)->pub.trunk->funcs.request_cancel((_treq)->pub.tconn->pub.conn, (_treq)->pub.preq, (_reason), (_treq)->pub.trunk->uctx); \
573 (_treq)->pub.trunk->in_handler = _prev; \
574 } \
575} while(0)
576
577/** Call the "conn_release" callback (if set)
578 *
579 */
580#define DO_REQUEST_CONN_RELEASE(_treq) \
581do { \
582 if ((_treq)->pub.trunk->funcs.request_conn_release) { \
583 request_t *request = (_treq)->pub.request; \
584 void *_prev = (_treq)->pub.trunk->in_handler; \
585 (_treq)->pub.trunk->in_handler = (void *)(_treq)->pub.trunk->funcs.request_conn_release; \
586 ROPTIONAL(RDEBUG3, DEBUG3, "Calling request_conn_release(conn=%p, preq=%p, uctx=%p)", \
587 (_treq)->pub.tconn->pub.conn, \
588 (_treq)->pub.preq, \
589 (_treq)->pub.trunk->uctx); \
590 (_treq)->pub.trunk->funcs.request_conn_release((_treq)->pub.tconn->pub.conn, (_treq)->pub.preq, (_treq)->pub.trunk->uctx); \
591 (_treq)->pub.trunk->in_handler = _prev; \
592 } \
593} while(0)
594
595/** Call the complete callback (if set)
596 *
597 */
598#define DO_REQUEST_COMPLETE(_treq) \
599do { \
600 if ((_treq)->pub.trunk->funcs.request_complete) { \
601 request_t *request = (_treq)->pub.request; \
602 void *_prev = (_treq)->pub.trunk->in_handler; \
603 ROPTIONAL(RDEBUG3, DEBUG3, "Calling request_complete(request=%p, preq=%p, rctx=%p, uctx=%p)", \
604 (_treq)->pub.request, \
605 (_treq)->pub.preq, \
606 (_treq)->pub.rctx, \
607 (_treq)->pub.trunk->uctx); \
608 (_treq)->pub.trunk->in_handler = (void *)(_treq)->pub.trunk->funcs.request_complete; \
609 (_treq)->pub.trunk->funcs.request_complete((_treq)->pub.request, (_treq)->pub.preq, (_treq)->pub.rctx, (_treq)->pub.trunk->uctx); \
610 (_treq)->pub.trunk->in_handler = _prev; \
611 } \
612} while(0)
613
614/** Call the fail callback (if set)
615 *
616 */
617#define DO_REQUEST_FAIL(_treq, _prev_state) \
618do { \
619 if ((_treq)->pub.trunk->funcs.request_fail) { \
620 request_t *request = (_treq)->pub.request; \
621 void *_prev = (_treq)->pub.trunk->in_handler; \
622 ROPTIONAL(RDEBUG3, DEBUG3, "Calling request_fail(request=%p, preq=%p, rctx=%p, state=%s uctx=%p)", \
623 (_treq)->pub.request, \
624 (_treq)->pub.preq, \
625 (_treq)->pub.rctx, \
626 fr_table_str_by_value(trunk_request_states, (_prev_state), "<INVALID>"), \
627 (_treq)->pub.trunk->uctx); \
628 (_treq)->pub.trunk->in_handler = (void *)(_treq)->pub.trunk->funcs.request_fail; \
629 (_treq)->pub.trunk->funcs.request_fail((_treq)->pub.request, (_treq)->pub.preq, (_treq)->pub.rctx, _prev_state, (_treq)->pub.trunk->uctx); \
630 (_treq)->pub.trunk->in_handler = _prev; \
631 } \
632} while(0)
633
634/** Call the free callback (if set)
635 *
636 */
637#define DO_REQUEST_FREE(_treq) \
638do { \
639 if ((_treq)->pub.trunk->funcs.request_free) { \
640 request_t *request = (_treq)->pub.request; \
641 void *_prev = (_treq)->pub.trunk->in_handler; \
642 ROPTIONAL(RDEBUG3, DEBUG3, "Calling request_free(request=%p, preq=%p, uctx=%p)", \
643 (_treq)->pub.request, \
644 (_treq)->pub.preq, \
645 (_treq)->pub.trunk->uctx); \
646 (_treq)->pub.trunk->in_handler = (void *)(_treq)->pub.trunk->funcs.request_free; \
647 (_treq)->pub.trunk->funcs.request_free((_treq)->pub.request, (_treq)->pub.preq, (_treq)->pub.trunk->uctx); \
648 (_treq)->pub.trunk->in_handler = _prev; \
649 } \
650} while(0)
651
652/** Write one or more requests to a connection
653 *
654 */
655#define DO_REQUEST_MUX(_tconn) \
656do { \
657 void *_prev = (_tconn)->pub.trunk->in_handler; \
658 DEBUG3("[%" PRIu64 "] Calling request_mux(el=%p, tconn=%p, conn=%p, uctx=%p)", \
659 (_tconn)->pub.conn->id, \
660 (_tconn)->pub.trunk->el, \
661 (_tconn), \
662 (_tconn)->pub.conn, \
663 (_tconn)->pub.trunk->uctx); \
664 (_tconn)->pub.trunk->in_handler = (void *)(_tconn)->pub.trunk->funcs.request_mux; \
665 (_tconn)->pub.trunk->funcs.request_mux((_tconn)->pub.trunk->el, (_tconn), (_tconn)->pub.conn, (_tconn)->pub.trunk->uctx); \
666 (_tconn)->pub.trunk->in_handler = _prev; \
667} while(0)
668
669/** Read one or more requests from a connection
670 *
671 */
672#define DO_REQUEST_DEMUX(_tconn) \
673do { \
674 void *_prev = (_tconn)->pub.trunk->in_handler; \
675 DEBUG3("[%" PRIu64 "] Calling request_demux(tconn=%p, conn=%p, uctx=%p)", \
676 (_tconn)->pub.conn->id, \
677 (_tconn), \
678 (_tconn)->pub.conn, \
679 (_tconn)->pub.trunk->uctx); \
680 (_tconn)->pub.trunk->in_handler = (void *)(_tconn)->pub.trunk->funcs.request_demux; \
681 (_tconn)->pub.trunk->funcs.request_demux((_tconn)->pub.trunk->el, (_tconn), (_tconn)->pub.conn, (_tconn)->pub.trunk->uctx); \
682 (_tconn)->pub.trunk->in_handler = _prev; \
683} while(0)
684
685/** Write one or more cancellation requests to a connection
686 *
687 */
688#define DO_REQUEST_CANCEL_MUX(_tconn) \
689do { \
690 if ((_tconn)->pub.trunk->funcs.request_cancel_mux) { \
691 void *_prev = (_tconn)->pub.trunk->in_handler; \
692 DEBUG3("[%" PRIu64 "] Calling request_cancel_mux(tconn=%p, conn=%p, uctx=%p)", \
693 (_tconn)->pub.conn->id, \
694 (_tconn), \
695 (_tconn)->pub.conn, \
696 (_tconn)->pub.trunk->uctx); \
697 (_tconn)->pub.trunk->in_handler = (void *)(_tconn)->pub.trunk->funcs.request_cancel_mux; \
698 (_tconn)->pub.trunk->funcs.request_cancel_mux((_tconn)->pub.trunk->el, (_tconn), (_tconn)->pub.conn, (_tconn)->pub.trunk->uctx); \
699 (_tconn)->pub.trunk->in_handler = _prev; \
700 } \
701} while(0)
702
703/** Allocate a new connection
704 *
705 */
706#define DO_CONNECTION_ALLOC(_tconn) \
707do { \
708 void *_prev = trunk->in_handler; \
709 DEBUG3("Calling connection_alloc(tconn=%p, el=%p, conf=%p, log_prefix=\"%s\", uctx=%p)", \
710 (_tconn), \
711 (_tconn)->pub.trunk->el, \
712 (_tconn)->pub.trunk->conf.conn_conf, \
713 trunk->log_prefix, \
714 (_tconn)->pub.trunk->uctx); \
715 (_tconn)->pub.trunk->in_handler = (void *) (_tconn)->pub.trunk->funcs.connection_alloc; \
716 (_tconn)->pub.conn = trunk->funcs.connection_alloc((_tconn), (_tconn)->pub.trunk->el, (_tconn)->pub.trunk->conf.conn_conf, (_tconn)->pub.trunk->log_prefix, trunk->uctx); \
717 (_tconn)->pub.trunk->in_handler = _prev; \
718 if (!(_tconn)->pub.conn) { \
719 ERROR("Failed creating new connection"); \
720 talloc_free(tconn); \
721 return -1; \
722 } \
723} while(0)
724
725/** Change what events the connection should be notified about
726 *
727 */
728#define DO_CONNECTION_NOTIFY(_tconn, _events) \
729do { \
730 if ((_tconn)->pub.trunk->funcs.connection_notify) { \
731 void *_prev = (_tconn)->pub.trunk->in_handler; \
732 DEBUG3("[%" PRIu64 "] Calling connection_notify(tconn=%p, conn=%p, el=%p, events=%s, uctx=%p)", \
733 (_tconn)->pub.conn->id, \
734 (_tconn), \
735 (_tconn)->pub.conn, \
736 (_tconn)->pub.trunk->el, \
737 fr_table_str_by_value(trunk_connection_events, (_events), "<INVALID>"), \
738 (_tconn)->pub.trunk->uctx); \
739 (_tconn)->pub.trunk->in_handler = (void *)(_tconn)->pub.trunk->funcs.connection_notify; \
740 (_tconn)->pub.trunk->funcs.connection_notify((_tconn), (_tconn)->pub.conn, (_tconn)->pub.trunk->el, (_events), (_tconn)->pub.trunk->uctx); \
741 (_tconn)->pub.trunk->in_handler = _prev; \
742 } \
743} while(0)
744
745#define IN_HANDLER(_trunk) (((_trunk)->in_handler) != NULL)
746#define IN_REQUEST_MUX(_trunk) (((_trunk)->funcs.request_mux) && ((_trunk)->in_handler == (void *)(_trunk)->funcs.request_mux))
747#define IN_REQUEST_DEMUX(_trunk) (((_trunk)->funcs.request_demux) && ((_trunk)->in_handler == (void *)(_trunk)->funcs.request_demux))
748#define IN_REQUEST_CANCEL_MUX(_trunk) (((_trunk)->funcs.request_cancel_mux) && ((_trunk)->in_handler == (void *)(_trunk)->funcs.request_cancel_mux))
749
750#define IS_SERVICEABLE(_tconn) ((_tconn)->pub.state & TRUNK_CONN_SERVICEABLE)
751#define IS_PROCESSING(_tconn) ((_tconn)->pub.state & TRUNK_CONN_PROCESSING)
752
753/** Remove the current request from the backlog
754 *
755 */
756#define REQUEST_EXTRACT_BACKLOG(_treq) \
757do { \
758 int _ret; \
759 _ret = fr_heap_extract(&(_treq)->pub.trunk->backlog, _treq); \
760 if (!fr_cond_assert_msg(_ret == 0, "Failed extracting conn from backlog heap: %s", fr_strerror())) break; \
761} while (0)
762
763/** Remove the current request from the pending list
764 *
765 */
766#define REQUEST_EXTRACT_PENDING(_treq) \
767do { \
768 int _ret; \
769 _ret = fr_heap_extract(&(_treq)->pub.tconn->pending, _treq); \
770 if (!fr_cond_assert_msg(_ret == 0, "Failed extracting conn from pending heap: %s", fr_strerror())) break; \
771} while (0)
772
773/** Remove the current request from the partial slot
774 *
775 */
776#define REQUEST_EXTRACT_PARTIAL(_treq) \
777do { \
778 fr_assert((_treq)->pub.tconn->partial == treq); \
779 tconn->partial = NULL; \
780} while (0)
781
782/** Remove the current request from the sent list
783 *
784 */
785#define REQUEST_EXTRACT_SENT(_treq) fr_dlist_remove(&tconn->sent, treq)
786
787/** Remove the current request from the reapable list
788 *
789 */
790#define REQUEST_EXTRACT_REAPABLE(_treq) fr_dlist_remove(&tconn->reapable, treq)
791
792/** Remove the current request from the cancel list
793 *
794 */
795#define REQUEST_EXTRACT_CANCEL(_treq) fr_dlist_remove(&tconn->cancel, treq)
796
797/** Remove the current request from the cancel_partial slot
798 *
799 */
800#define REQUEST_EXTRACT_CANCEL_PARTIAL(_treq) \
801do { \
802 fr_assert((_treq)->pub.tconn->cancel_partial == treq); \
803 tconn->cancel_partial = NULL; \
804} while (0)
805
806/** Remove the current request from the cancel sent list
807 *
808 */
809#define REQUEST_EXTRACT_CANCEL_SENT(_treq) fr_dlist_remove(&tconn->cancel_sent, treq)
810
811/** Reorder the connections in the active heap
812 *
813 * fr_heap_extract will also error out if heap_id is bad - no need for assert
814 */
815#define CONN_REORDER(_tconn) \
816do { \
817 int _ret; \
818 if ((fr_minmax_heap_num_elements((_tconn)->pub.trunk->active) == 1)) break; \
819 if (!fr_cond_assert((_tconn)->pub.state == TRUNK_CONN_ACTIVE)) break; \
820 _ret = fr_minmax_heap_extract((_tconn)->pub.trunk->active, (_tconn)); \
821 if (!fr_cond_assert_msg(_ret == 0, "Failed extracting conn from active heap: %s", fr_strerror())) break; \
822 fr_minmax_heap_insert((_tconn)->pub.trunk->active, (_tconn)); \
823} while (0)
824
825/** Reorder an active connection after a request moves to the `sent` or `reapable` state
826 *
827 * The `lru` ordering reads the number of requests in the `pending` and `partial` states, and
828 * `last_write_success`. This number changes when a request moves to the `sent` or `reapable` state, or when
829 * `last_write_success` changes. We therefore need to re-order the connection on writes.
830 *
831 * The function does nothing the connection is inactive, or for ordering which is not `TRUNK_SORT_LRU`.
832 *
833 * @param[in] tconn connection which wrote the request.
834 */
836{
837 if (tconn->pub.trunk->conf.sort != TRUNK_SORT_LRU) return;
838
839 /*
840 * Only connections in the active state are in the active heap. A write can change the
841 * connection state, for example when the connection reaches `max_uses`.
842 */
843 if (tconn->pub.state != TRUNK_CONN_ACTIVE) return;
844
845 CONN_REORDER(tconn);
846}
847
848DIAG_OFF(unused-function)
849
850#define FR_TRUNK_LIST_FUNC(_list,_type) \
851static inline CC_HINT(nonnull, always_inline) void trunk_list_ ## _list ## _add(trunk_t *trunk, _type *arg) \
852{ \
853 fr_dlist_insert_head(&trunk->_list, arg); \
854} \
855static inline CC_HINT(nonnull, always_inline) _type *trunk_list_ ## _list ##_peek(trunk_t *trunk) \
856{ \
857 return fr_dlist_tail(&trunk->_list); \
858} \
859static inline CC_HINT(nonnull, always_inline) _type *trunk_list_ ## _list ##_pop(trunk_t *trunk) \
860{ \
861 return fr_dlist_pop_head(&trunk->_list); \
862} \
863static inline CC_HINT(nonnull, always_inline) void trunk_list_ ## _list ##_remove(trunk_t *trunk, _type *arg) \
864{ \
865 fr_dlist_remove(&trunk->_list, arg); \
866}
867
871FR_TRUNK_LIST_FUNC(inactive_draining, trunk_connection_t)
873
874DIAG_ON(unused-function)
875
876/** Call a list of watch functions associated with a state
877 *
878 */
880{
881 /*
882 * Nested watcher calls are not allowed
883 * and shouldn't be possible because of
884 * deferred signal processing.
885 */
886 fr_assert(trunk->next_watcher == NULL);
887
888 while ((trunk->next_watcher = fr_dlist_next(list, trunk->next_watcher))) {
889 trunk_watch_entry_t *entry = trunk->next_watcher;
890 bool oneshot = entry->oneshot; /* Watcher could be freed, so store now */
891
892 if (!entry->enabled) continue;
893 if (oneshot) trunk->next_watcher = fr_dlist_remove(list, entry);
894
895 entry->func(trunk, trunk->pub.state, state, entry->uctx);
896
897 if (oneshot) talloc_free(entry);
898 }
899 trunk->next_watcher = NULL;
900}
901
902/** Call the state change watch functions
903 *
904 */
905#define CALL_WATCHERS(_trunk, _state) \
906do { \
907 if (fr_dlist_empty(&(_trunk)->watch[_state])) break; \
908 trunk_watch_call((_trunk), &(_trunk)->watch[_state], _state); \
909} while(0)
910
911/** Remove a watch function from a trunk state list
912 *
913 * @param[in] trunk The trunk to remove the watcher from.
914 * @param[in] state to remove the watch from.
915 * @param[in] watch Function to remove.
916 * @return
917 * - 0 if the function was removed successfully.
918 * - -1 if the function wasn't present in the watch list.
919 * - -2 if an invalid state was passed.
920 */
922{
923 trunk_watch_entry_t *entry = NULL;
924 fr_dlist_head_t *list;
925
926 if (state >= TRUNK_STATE_MAX) return -2;
927
928 list = &trunk->watch[state];
929 while ((entry = fr_dlist_next(list, entry))) {
930 if (entry->func == watch) {
931 if (trunk->next_watcher == entry) {
932 trunk->next_watcher = fr_dlist_remove(list, entry);
933 } else {
934 fr_dlist_remove(list, entry);
935 }
936 talloc_free(entry);
937 return 0;
938 }
939 }
940
941 return -1;
942}
943
944/** Add a watch entry to the trunk state list
945 *
946 * @param[in] trunk The trunk to add the watcher to.
947 * @param[in] state to watch for.
948 * @param[in] watch Function to add.
949 * @param[in] oneshot Should this watcher only be run once.
950 * @param[in] uctx Context to pass to function.
951 * @return
952 * - NULL if an invalid state is passed.
953 * - A new watch entry handle on success.
954 */
956 trunk_watch_t watch, bool oneshot, void const *uctx)
957{
958 trunk_watch_entry_t *entry;
959 fr_dlist_head_t *list;
960
961 if (state >= TRUNK_STATE_MAX) return NULL;
962
963 list = &trunk->watch[state];
964 MEM(entry = talloc_zero(trunk, trunk_watch_entry_t));
965
966 entry->func = watch;
967 entry->oneshot = oneshot;
968 entry->enabled = true;
969 memcpy(&entry->uctx, &uctx, sizeof(entry->uctx));
970 fr_dlist_insert_tail(list, entry);
971
972 return entry;
973}
974
975#define TRUNK_STATE_TRANSITION(_new) \
976do { \
977 DEBUG3("Trunk changed state %s -> %s", \
978 fr_table_str_by_value(trunk_states, trunk->pub.state, "<INVALID>"), \
979 fr_table_str_by_value(trunk_states, _new, "<INVALID>")); \
980 CALL_WATCHERS(trunk, _new); \
981 trunk->pub.state = _new; \
982} while (0)
983
984static void trunk_request_enter_backlog(trunk_request_t *treq, bool new);
985static void trunk_request_enter_pending(trunk_request_t *treq, trunk_connection_t *tconn, bool new);
994
995static uint64_t trunk_requests_per_connection(uint16_t *conn_count_out, uint32_t *req_conn_out,
996 trunk_t *trunk, fr_time_t now, NDEBUG_UNUSED bool verify);
997
998static int trunk_connection_spawn(trunk_t *trunk, fr_time_t now);
999static inline void trunk_connection_auto_full(trunk_connection_t *tconn);
1000static inline void trunk_connection_auto_unfull(trunk_connection_t *tconn);
1001static inline void trunk_connection_readable(trunk_connection_t *tconn);
1002static inline void trunk_connection_writable(trunk_connection_t *tconn);
1010
1011static void trunk_rebalance(trunk_t *trunk);
1012static void trunk_manage(trunk_t *trunk, fr_time_t now);
1013static void _trunk_timer(fr_timer_list_t *tl, fr_time_t now, void *uctx);
1014static void trunk_backlog_drain(trunk_t *trunk);
1015
1016/** Compare two protocol requests
1017 *
1018 * Allows protocol requests to be prioritised with a function
1019 * specified by the API client. Defaults to by pointer address
1020 * if no function is specified.
1021 *
1022 * @param[in] a treq to compare to b.
1023 * @param[in] b treq to compare to a.
1024 * @return
1025 * - +1 if a > b.
1026 * - 0 if a == b.
1027 * - -1 if a < b.
1028 */
1029static fr_cmp_ret_t _trunk_request_prioritise(void const *a, void const *b)
1030{
1033
1034 fr_assert(treq_a->pub.trunk == treq_b->pub.trunk);
1035
1036 return treq_a->pub.trunk->funcs.request_prioritise(treq_a->pub.preq, treq_b->pub.preq);
1037}
1038
1039/** Remove a request from all connection lists
1040 *
1041 * A common function used by init, fail, complete state functions to disassociate
1042 * a request from a connection in preparation for freeing or reassignment.
1043 *
1044 * Despite its unassuming name, this function is *the* place to put calls to
1045 * functions which need to be called when the number of requests associated with
1046 * a connection changes.
1047 *
1048 * Trunk requests will always be passed to this function before they're removed
1049 * from a connection, even if the requests are being freed.
1050 *
1051 * @param[in] treq to trigger a state change for.
1052 */
1054{
1055 trunk_connection_t *tconn = treq->pub.tconn;
1056 trunk_t *trunk = treq->pub.trunk;
1057
1058 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1059
1060 switch (treq->pub.state) {
1062 return; /* Not associated with connection */
1063
1066 break;
1067
1070 break;
1071
1074 break;
1075
1078 break;
1079
1082 break;
1083
1086 break;
1087
1090 break;
1091
1092 default:
1093 fr_assert(0);
1094 break;
1095 }
1096
1097 /*
1098 * If the request wasn't associated with a
1099 * connection, then there's nothing more
1100 * to do.
1101 */
1102 if (!tconn) return;
1103
1104 {
1105 request_t *request = treq->pub.request;
1106
1107 ROPTIONAL(RDEBUG3, DEBUG3, "%s Trunk connection released request %" PRIu64,
1108 tconn->pub.conn->name, treq->id);
1109 }
1110 /*
1111 * Release any connection specific resources the
1112 * treq holds.
1113 */
1115
1116 switch (tconn->pub.state){
1117 case TRUNK_CONN_FULL:
1118 trunk_connection_auto_unfull(tconn); /* Check if we can switch back to active */
1119 if (tconn->pub.state == TRUNK_CONN_FULL) break; /* Only fallthrough if conn is now active */
1121
1122 case TRUNK_CONN_ACTIVE:
1123 CONN_REORDER(tconn);
1124 break;
1125
1127 /*
1128 * If the trunk request set the connection inactive, mark it active again.
1129 */
1130 if (treq->blocking) trunk_connection_signal_active(tconn);
1131 break;
1132
1133 default:
1134 break;
1135 }
1136
1137 treq->pub.tconn = NULL;
1138
1139 /*
1140 * Request removed from the connection
1141 * see if we need up deregister I/O events.
1142 */
1144}
1145
1146/** Transition a request to the unassigned state, in preparation for re-assignment
1147 *
1148 * @note treq->tconn may be inviable after calling
1149 * if treq->conn and connection_signals_pause are not used.
1150 * This is due to call to trunk_request_remove_from_conn.
1151 *
1152 * @param[in] treq to trigger a state change for.
1153 */
1155{
1156 trunk_t *trunk = treq->pub.trunk;
1157
1158 switch (treq->pub.state) {
1160 return;
1161
1164 break;
1165
1171 break;
1172
1173 default:
1175 }
1176
1178}
1179
1180/** Transition a request to the backlog state, adding it to the backlog of the trunk
1181 *
1182 * @note treq->tconn and treq may be inviable after calling
1183 * if treq->conn and connection_signals_pause are not used.
1184 * This is due to call to trunk_manage.
1185 *
1186 * @param[in] treq to trigger a state change for.
1187 * @param[in] new Whether this is a new request.
1188 */
1190{
1191 trunk_connection_t *tconn = treq->pub.tconn;
1192 trunk_t *trunk = treq->pub.trunk;
1193
1194 switch (treq->pub.state) {
1197 break;
1198
1201 break;
1202
1205 break;
1206
1207 default:
1209 }
1210
1212 fr_heap_insert(&trunk->backlog, treq); /* Insert into the backlog heap */
1213
1214 /*
1215 * A new request has entered the trunk.
1216 * Re-calculate request/connection ratios.
1217 */
1218 if (new) trunk_requests_per_connection(NULL, NULL, trunk, fr_time(), false);
1219
1220 /*
1221 * To reduce latency, if there's no connections
1222 * in the connecting state, call the trunk manage
1223 * function immediately.
1224 *
1225 * Likewise, if there's draining connections
1226 * which could be moved back to active call
1227 * the trunk manage function.
1228 *
1229 * Remember requests only enter the backlog if
1230 * there's no connections which can service them.
1231 */
1235 }
1236}
1237
1238/** Transition a request to the pending state, adding it to the backlog of an active connection
1239 *
1240 * All trunk requests being added to a connection get passed to this function.
1241 * All trunk requests being removed from a connection get passed to #trunk_request_remove_from_conn.
1242 *
1243 * @note treq->tconn and treq may be inviable after calling
1244 * if treq->conn and connection_signals_pause is not used.
1245 * This is due to call to trunk_connection_event_update.
1246 *
1247 * @param[in] treq to trigger a state change for.
1248 * @param[in] tconn to enqueue the request on.
1249 * @param[in] new Whether this is a new request.
1250 */
1252{
1253 trunk_t *trunk = treq->pub.trunk;
1254
1255 fr_assert(tconn->pub.trunk == trunk);
1256 fr_assert(IS_PROCESSING(tconn));
1257
1258 switch (treq->pub.state) {
1261 fr_assert(!treq->pub.tconn);
1262 break;
1263
1265 fr_assert(!treq->pub.tconn);
1267 break;
1268
1269 case TRUNK_REQUEST_STATE_CANCEL: /* Moved from another connection */
1271 break;
1272
1273 default:
1275 }
1276
1277 /*
1278 * Assign the new connection first this first so
1279 * it appears in the state log.
1280 */
1281 treq->pub.tconn = tconn;
1282
1283 /*
1284 * The request being handled is a blocking one, mark the
1285 * assigned connection as inactive.
1286 */
1288
1290
1291 {
1292 request_t *request = treq->pub.request;
1293
1294 ROPTIONAL(RDEBUG, DEBUG3, "%s Trunk connection assigned request %"PRIu64,
1295 tconn->pub.conn->name, treq->id);
1296 }
1297 fr_heap_insert(&tconn->pending, treq);
1298
1299 /*
1300 * A new request has entered the trunk.
1301 * Re-calculate request/connection ratios.
1302 */
1303 if (new) trunk_requests_per_connection(NULL, NULL, trunk, fr_time(), false);
1304
1305 /*
1306 * Check if we need to automatically transition the
1307 * connection to full.
1308 */
1310
1311 /*
1312 * Reorder the connection in the heap now it has an
1313 * additional request.
1314 */
1315 if (tconn->pub.state == TRUNK_CONN_ACTIVE) CONN_REORDER(tconn);
1316
1317 /*
1318 * We have a new request, see if we need to register
1319 * for I/O events.
1320 */
1322}
1323
1324/** Transition a request to the partial state, indicating that is has been partially sent
1325 *
1326 * @param[in] treq to trigger a state change for.
1327 */
1329{
1330 trunk_connection_t *tconn = treq->pub.tconn;
1331 trunk_t *trunk = treq->pub.trunk;
1332
1333 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1334
1335 switch (treq->pub.state) {
1336 case TRUNK_REQUEST_STATE_PENDING: /* All requests go through pending, even requeued ones */
1338 break;
1339
1340 default:
1342 }
1343
1344 fr_assert(!tconn->partial);
1345 tconn->partial = treq;
1346
1348}
1349
1350/** Transition a request to the sent state, indicating that it's been sent in its entirety
1351 *
1352 * @note treq->tconn and treq may be inviable after calling
1353 * if treq->conn and connection_signals_pause is not used.
1354 * This is due to call to trunk_connection_event_update.
1355 *
1356 * @param[in] treq to trigger a state change for.
1357 */
1359{
1360 trunk_connection_t *tconn = treq->pub.tconn;
1361 trunk_t *trunk = treq->pub.trunk;
1362
1363 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1364
1365 switch (treq->pub.state) {
1368 break;
1369
1372 break;
1373
1374 default:
1376 }
1377
1379 fr_dlist_insert_tail(&tconn->sent, treq);
1380
1381 /*
1382 * Update the connection's sent stats if this is the
1383 * first time this request is being sent.
1384 */
1385 if (!treq->sent) {
1386 trunk->pub.last_write_success = fr_time();
1387
1389 tconn->sent_count++;
1390 treq->sent = true;
1391
1392 /*
1393 * Enforces max_uses
1394 */
1395 if ((trunk->conf.max_uses > 0) && (tconn->sent_count >= trunk->conf.max_uses)) {
1396 DEBUG3("Trunk hit max uses %" PRIu64 " at %d", trunk->conf.max_uses, __LINE__);
1398 }
1399 }
1400
1402
1403 /*
1404 * We just sent a request, we probably need
1405 * to tell the event loop we want to be
1406 * notified if there's data available.
1407 */
1409}
1410
1411/** Transition a request to the reapable state, indicating that it's been sent in its entirety, but no response is expected
1412 *
1413 * @note Largely a replica of trunk_request_enter_sent.
1414 *
1415 * @param[in] treq to trigger a state change for.
1416 */
1418{
1419 trunk_connection_t *tconn = treq->pub.tconn;
1420 trunk_t *trunk = treq->pub.trunk;
1421
1422 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1423
1424 switch (treq->pub.state) {
1427 break;
1428
1431 break;
1432
1433 default:
1435 }
1436
1438 fr_dlist_insert_tail(&tconn->reapable, treq);
1439
1440 if (!treq->sent) {
1441 trunk->pub.last_write_success = fr_time();
1442
1444 tconn->sent_count++;
1445 treq->sent = true;
1446
1447 if ((trunk->conf.max_uses > 0) && (tconn->sent_count >= trunk->conf.max_uses)) {
1448 DEBUG3("Trunk hit max uses %" PRIu64 " at %d", trunk->conf.max_uses, __LINE__);
1450 }
1451 }
1452
1454
1456}
1457
1458/** Transition a request to the cancel state, placing it in a connection's cancellation list
1459 *
1460 * If a request_cancel_send callback is provided, that callback will
1461 * be called periodically for requests which were cancelled due to
1462 * a signal.
1463 *
1464 * The request_cancel_send callback will dequeue cancelled requests
1465 * and inform a remote server that the result is no longer required.
1466 *
1467 * A request must enter this state before being added to the backlog
1468 * of another connection if it's been sent or partially sent.
1469 *
1470 * @note treq->tconn and treq may be inviable after calling
1471 * if treq->conn and connection_signals_pause is not used.
1472 * This is due to call to trunk_connection_event_update.
1473 *
1474 * @param[in] treq to trigger a state change for.
1475 * @param[in] reason Why the request was cancelled.
1476 * Should be one of:
1477 * - TRUNK_CANCEL_REASON_SIGNAL request cancelled
1478 * because of a signal from the interpreter.
1479 * - TRUNK_CANCEL_REASON_MOVE request cancelled
1480 * because the connection failed and it needs
1481 * to be assigned to a new connection.
1482 * - TRUNK_CANCEL_REASON_REQUEUE request cancelled
1483 * as it needs to be resent on the same connection.
1484 */
1486{
1487 trunk_connection_t *tconn = treq->pub.tconn;
1488 trunk_t *trunk = treq->pub.trunk;
1489
1490 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1491
1492 switch (treq->pub.state) {
1495 break;
1496
1499 break;
1500
1503 break;
1504
1505 default:
1507 }
1508
1510 fr_dlist_insert_tail(&tconn->cancel, treq);
1511 treq->cancel_reason = reason;
1512
1513 DO_REQUEST_CANCEL(treq, reason);
1514
1515 /*
1516 * Our treq is no longer bound to an actual
1517 * request_t *, as we can't guarantee the
1518 * lifetime of the original request_t *.
1519 */
1520 if (treq->cancel_reason == TRUNK_CANCEL_REASON_SIGNAL) treq->pub.request = NULL;
1521
1522 /*
1523 * Register for I/O write events if we need to.
1524 */
1526}
1527
1528/** Transition a request to the cancel_partial state, placing it in a connection's cancel_partial slot
1529 *
1530 * The request_demux function is then responsible for signalling
1531 * that the cancel request is complete when the remote server
1532 * acknowledges the cancellation request.
1533 *
1534 * @param[in] treq to trigger a state change for.
1535 */
1537{
1538 trunk_connection_t *tconn = treq->pub.tconn;
1539 trunk_t *trunk = treq->pub.trunk;
1540
1541 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1544
1545 switch (treq->pub.state) {
1546 case TRUNK_REQUEST_STATE_CANCEL: /* The only valid state cancel_sent can be reached from */
1548 break;
1549
1550 default:
1552 }
1553
1555 fr_assert(!tconn->cancel_partial);
1556 tconn->cancel_partial = treq;
1557}
1558
1559/** Transition a request to the cancel_sent state, placing it in a connection's cancel_sent list
1560 *
1561 * The request_demux function is then responsible for signalling
1562 * that the cancel request is complete when the remote server
1563 * acknowledges the cancellation request.
1564 *
1565 * @note treq->tconn and treq may be inviable after calling
1566 * if treq->conn and connection_signals_pause is not used.
1567 * This is due to call to trunk_connection_event_update.
1568 *
1569 * @param[in] treq to trigger a state change for.
1570 */
1572{
1573 trunk_connection_t *tconn = treq->pub.tconn;
1574 trunk_t *trunk = treq->pub.trunk;
1575
1576 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1579
1580 switch (treq->pub.state) {
1583 break;
1584
1587 break;
1588
1589 default:
1591 }
1592
1594 fr_dlist_insert_tail(&tconn->cancel_sent, treq);
1595
1596 /*
1597 * De-register for I/O write events
1598 * and register the read events
1599 * to drain the cancel ACKs.
1600 */
1602}
1603
1604/** Cancellation was acked, the request is complete, free it
1605 *
1606 * The API client will not be informed, as the original request_t *
1607 * will likely have been freed by this point.
1608 *
1609 * @note treq will be inviable after a call to this function.
1610 * treq->tconn may be inviable after calling
1611 * if treq->conn and connection_signals_pause is not used.
1612 * This is due to call to trunk_request_remove_from_conn.
1613 *
1614 * @param[in] treq to mark as complete.
1615 */
1617{
1618 trunk_connection_t *tconn = treq->pub.tconn;
1619 trunk_t *trunk = treq->pub.trunk;
1620
1621 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1622 if (!fr_cond_assert(!treq->pub.request)) return; /* Only a valid state for request_t * which have been cancelled */
1623
1624 switch (treq->pub.state) {
1627 break;
1628
1629 default:
1631 }
1632
1634
1636 trunk_request_free(&treq); /* Free the request */
1637}
1638
1639/** Request completed successfully, inform the API client and free the request
1640 *
1641 * @note treq will be inviable after a call to this function.
1642 * treq->tconn may also be inviable due to call to
1643 * trunk_request_remove_from_conn.
1644 *
1645 * @param[in] treq to mark as complete.
1646 */
1648{
1649 trunk_connection_t *tconn = treq->pub.tconn;
1650 trunk_t *trunk = treq->pub.trunk;
1651
1652 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1653
1654 switch (treq->pub.state) {
1659 break;
1660
1661 default:
1663 }
1664
1666 DO_REQUEST_COMPLETE(treq);
1667 trunk_request_free(&treq); /* Free the request */
1668}
1669
1670/** Request failed, inform the API client and free the request
1671 *
1672 * @note treq will be inviable after a call to this function.
1673 * treq->tconn may also be inviable due to call to
1674 * trunk_request_remove_from_conn.
1675 *
1676 * @param[in] treq to mark as failed.
1677 */
1679{
1680 trunk_connection_t *tconn = treq->pub.tconn;
1681 trunk_t *trunk = treq->pub.trunk;
1682 trunk_request_state_t prev = treq->pub.state;
1683
1684 if (!fr_cond_assert(!tconn || (tconn->pub.trunk == trunk))) return;
1685
1686 switch (treq->pub.state) {
1689 break;
1690
1691 default:
1693 break;
1694 }
1695
1697 DO_REQUEST_FAIL(treq, prev);
1698 trunk_request_free(&treq); /* Free the request */
1699}
1700
1701/** Check to see if a trunk request can be enqueued
1702 *
1703 * @param[out] tconn_out Connection the request may be enqueued on.
1704 * @param[in] trunk To enqueue requests on.
1705 * @param[in] request associated with the treq (if any).
1706 * @return
1707 * - TRUNK_ENQUEUE_OK caller should enqueue request on provided tconn.
1708 * - TRUNK_ENQUEUE_IN_BACKLOG Request should be queued in the backlog.
1709 * - TRUNK_ENQUEUE_NO_CAPACITY Unable to enqueue request as we have no spare
1710 * connections or backlog space.
1711 * - TRUNK_ENQUEUE_DST_UNAVAILABLE Can't enqueue because the destination is
1712 * unreachable.
1713 */
1716{
1717 trunk_connection_t *tconn;
1718 /*
1719 * If we have an active connection then
1720 * return that.
1721 */
1722 tconn = fr_minmax_heap_min_peek(trunk->active);
1723 if (tconn) {
1724 *tconn_out = tconn;
1725 return TRUNK_ENQUEUE_OK;
1726 }
1727
1728 /*
1729 * Unlike the connection pool, we don't need
1730 * to drive any internal processes by feeding
1731 * it requests.
1732 *
1733 * If the last event to occur was a failure
1734 * we refuse to enqueue new requests until
1735 * one or more connections comes online.
1736 */
1737 if (!trunk->conf.backlog_on_failed_conn &&
1738 fr_time_gt(trunk->pub.last_failed, fr_time_wrap(0)) &&
1739 fr_time_lt(trunk->pub.last_connected, trunk->pub.last_failed)) {
1741 RWARN, WARN, "Refusing to enqueue requests - "
1742 "No active connections and last event was a connection failure");
1743
1745 }
1746
1747
1748 /*
1749 * Only enforce if we're limiting maximum
1750 * number of connections, and maximum
1751 * number of requests per connection.
1752 */
1753 if (trunk->conf.max_req_per_conn && trunk->conf.max) {
1754 uint64_t limit;
1755
1756 limit = trunk->conf.max * (uint64_t)trunk->conf.max_req_per_conn;
1757 if (limit > 0) {
1758 uint64_t total_reqs;
1759
1760 total_reqs = trunk_request_count_by_state(trunk, TRUNK_CONN_ALL,
1762 if (total_reqs >= (limit + trunk->conf.max_backlog)) {
1764 RWARN, WARN, "Refusing to alloc requests - "
1765 "Limit of %"PRIu64" (max = %u * per_connection_max = %u) "
1766 "plus %u backlog requests reached",
1767 limit, trunk->conf.max, trunk->conf.max_req_per_conn,
1768 trunk->conf.max_backlog);
1770 }
1771 }
1772 }
1773
1775}
1776
1777/** Enqueue a request which has never been assigned to a connection or was previously cancelled
1778 *
1779 * @param[in] treq to re enqueue. Must have been removed
1780 * from its existing connection with
1781 * #trunk_connection_requests_dequeue.
1782 * @return
1783 * - TRUNK_ENQUEUE_OK Request was re-enqueued.
1784 * - TRUNK_ENQUEUE_NO_CAPACITY Request enqueueing failed because we're at capacity.
1785 * - TRUNK_ENQUEUE_DST_UNAVAILABLE Enqueuing failed for some reason.
1786 * Usually because the connection to the resource is down.
1787 */
1789{
1790 trunk_t *trunk = treq->pub.trunk;
1791 trunk_connection_t *tconn = NULL;
1792 trunk_enqueue_t ret;
1793
1794 /*
1795 * Must *NOT* still be assigned to another connection
1796 */
1797 fr_assert(!treq->pub.tconn);
1798
1799 ret = trunk_request_check_enqueue(&tconn, trunk, treq->pub.request);
1800 switch (ret) {
1801 case TRUNK_ENQUEUE_OK:
1802 if (trunk->conf.always_writable) {
1804 trunk_request_enter_pending(treq, tconn, false);
1807 } else {
1808 trunk_request_enter_pending(treq, tconn, false);
1809 }
1810 break;
1811
1813 /*
1814 * No more connections and request
1815 * is already in the backlog.
1816 *
1817 * Signal our caller it should stop
1818 * trying to drain the backlog.
1819 */
1821 trunk_request_enter_backlog(treq, false);
1822 break;
1823
1824 default:
1825 break;
1826 }
1827
1828 return ret;
1829}
1830
1831/** Shift requests in the specified states onto new connections
1832 *
1833 * This function will blindly dequeue any requests in the specified state and get
1834 * them back to the unassigned state, cancelling any sent or partially sent requests.
1835 *
1836 * This function does not check that dequeuing a request in a particular state is a
1837 * sane or sensible thing to do, that's up to the caller!
1838 *
1839 * @param[out] out A list to insert the newly dequeued and unassigned
1840 * requests into.
1841 * @param[in] tconn to dequeue requests from.
1842 * @param[in] states Dequeue request in these states.
1843 * @param[in] max The maximum number of requests to dequeue. 0 for unlimited.
1844 */
1846 int states, uint64_t max)
1847{
1848 trunk_request_t *treq;
1849 uint64_t count = 0;
1850
1851 if (max == 0) max = UINT64_MAX;
1852
1853#define OVER_MAX_CHECK if (++count > max) return (count - 1)
1854
1855#define DEQUEUE_ALL(_src_list, _state) do { \
1856 while ((treq = fr_dlist_head(_src_list))) { \
1857 OVER_MAX_CHECK; \
1858 fr_assert(treq->pub.state == (_state)); \
1859 trunk_request_enter_unassigned(treq); \
1860 fr_dlist_insert_tail(out, treq); \
1861 } } while (0)
1862
1863 /*
1864 * Don't need to do anything with
1865 * cancellation requests.
1866 */
1867 if (states & TRUNK_REQUEST_STATE_CANCEL) DEQUEUE_ALL(&tconn->cancel,
1869
1870 /*
1871 * ...same with cancel inform
1872 */
1875
1876 /*
1877 * ....same with cancel partial
1878 */
1881 treq = tconn->cancel_partial;
1882 if (treq) {
1886 }
1887 }
1888
1889 /*
1890 * ...and pending.
1891 */
1892 if (states & TRUNK_REQUEST_STATE_PENDING) {
1893 while ((treq = fr_heap_peek(tconn->pending))) {
1898 }
1899 }
1900
1901 /*
1902 * Cancel partially sent requests
1903 */
1904 if (states & TRUNK_REQUEST_STATE_PARTIAL) {
1906 treq = tconn->partial;
1907 if (treq) {
1909
1910 /*
1911 * Don't allow the connection to change state whilst
1912 * we're draining requests from it.
1913 */
1919 }
1920 }
1921
1922 /*
1923 * Cancel sent requests
1924 */
1925 if (states & TRUNK_REQUEST_STATE_SENT) {
1926 /*
1927 * Don't allow the connection to change state whilst
1928 * we're draining requests from it.
1929 */
1931 while ((count < max) && (treq = fr_dlist_head(&tconn->sent))) {
1933
1937 count++;
1938 }
1940 }
1941
1942 return count;
1943}
1944
1945/** Remove requests in specified states from a connection, attempting to distribute them to new connections
1946 *
1947 * @param[in] tconn To remove requests from.
1948 * @param[in] states One or more states or'd together.
1949 * @param[in] max The maximum number of requests to dequeue.
1950 * 0 for unlimited.
1951 * @param[in] fail_bound If true causes any requests bound to the connection to fail.
1952 * If false bound requests will not be moved.
1953 *
1954 * @return the number of requests re-queued.
1955 */
1956static uint64_t trunk_connection_requests_requeue_priv(trunk_connection_t *tconn, int states, uint64_t max, bool fail_bound)
1957{
1958 trunk_t *trunk = tconn->pub.trunk;
1959 fr_dlist_head_t to_process;
1960 trunk_request_t *treq = NULL;
1961 uint64_t moved = 0;
1962
1963 if (max == 0) max = UINT64_MAX;
1964
1965 fr_dlist_talloc_init(&to_process, trunk_request_t, entry);
1966
1967 /*
1968 * Prevent the connection changing state whilst we're
1969 * working with it.
1970 *
1971 * There's a user callback that can be called by
1972 * trunk_request_enqueue_existing which can reconnect
1973 * the connection.
1974 */
1976
1977 /*
1978 * Remove non-cancelled requests from the connection
1979 */
1980 moved += trunk_connection_requests_dequeue(&to_process, tconn, states & ~TRUNK_REQUEST_STATE_CANCEL_ALL, max);
1981
1982 /*
1983 * Prevent requests being requeued on the same trunk
1984 * connection, which would break rebalancing.
1985 *
1986 * This is a bit of a hack, but nothing should test
1987 * for connection/list consistency in this code,
1988 * and if something is added later, it'll be flagged
1989 * by the tests.
1990 */
1991 if (tconn->pub.state == TRUNK_CONN_ACTIVE) {
1992 int ret;
1993
1994 ret = fr_minmax_heap_extract(trunk->active, tconn);
1995 if (!fr_cond_assert_msg(ret == 0,
1996 "Failed extracting conn from active heap: %s", fr_strerror())) goto done;
1997
1998 }
1999
2000 /*
2001 * Loop over all the requests we gathered and
2002 * redistribute them to new connections.
2003 */
2004 while ((treq = fr_dlist_next(&to_process, treq))) {
2005 trunk_request_t *prev;
2006
2007 prev = fr_dlist_remove(&to_process, treq);
2008
2009 /*
2010 * Attempts to re-queue a request
2011 * that's bound to a connection
2012 * results in a failure.
2013 */
2014 if (treq->bound_to_conn) {
2015 if (fail_bound || !IS_SERVICEABLE(tconn)) {
2017 } else {
2018 trunk_request_enter_pending(treq, tconn, false);
2019 }
2020 goto next;
2021 }
2022
2023 switch (trunk_request_enqueue_existing(treq)) {
2024 case TRUNK_ENQUEUE_OK:
2025 break;
2026
2027 /*
2028 * A connection failed, and
2029 * there's no other connections
2030 * available to deal with the
2031 * load, it's been placed back
2032 * in the backlog.
2033 */
2035 break;
2036
2037 /*
2038 * If we fail to re-enqueue then
2039 * there's nothing to do except
2040 * fail the request.
2041 */
2044 case TRUNK_ENQUEUE_FAIL:
2046 break;
2047 }
2048 next:
2049 treq = prev;
2050 }
2051
2052 /*
2053 * Add the connection back into the active list
2054 */
2055 if (tconn->pub.state == TRUNK_CONN_ACTIVE) {
2056 int ret;
2057
2058 ret = fr_minmax_heap_insert(trunk->active, tconn);
2059 if (!fr_cond_assert_msg(ret == 0,
2060 "Failed re-inserting conn into active heap: %s", fr_strerror())) goto done;
2061 }
2062 if (moved >= max) goto done;
2063
2064 /*
2065 * Deal with the cancelled requests specially we can't
2066 * queue them up again as they were only valid on that
2067 * specific connection.
2068 *
2069 * We just need to run them to completion which, as
2070 * they should already be in the unassigned state,
2071 * just means freeing them.
2072 */
2073 moved += trunk_connection_requests_dequeue(&to_process, tconn,
2074 states & TRUNK_REQUEST_STATE_CANCEL_ALL, max - moved);
2075 while ((treq = fr_dlist_next(&to_process, treq))) {
2076 trunk_request_t *prev;
2077
2078 prev = fr_dlist_remove(&to_process, treq);
2079 trunk_request_free(&treq);
2080 treq = prev;
2081 }
2082
2083done:
2084
2085 /*
2086 * Always re-calculate the request/connection
2087 * ratio at the end.
2088 *
2089 * This avoids having the state transition
2090 * functions do it.
2091 *
2092 * The ratio would be wrong when they calculated
2093 * it anyway, because a bunch of requests are
2094 * dequeued from the connection and temporarily
2095 * cease to exist from the perspective of the
2096 * trunk_requests_per_connection code.
2097 */
2098 trunk_requests_per_connection(NULL, NULL, trunk, fr_time(), false);
2099
2101 return moved;
2102}
2103
2104/** Move requests off of a connection and requeue elsewhere
2105 *
2106 * @note We don't re-queue on draining or draining to free, as requests should have already been
2107 * moved off of the connection. It's also dangerous as the trunk management code main
2108 * clean up a connection in this state when it's run on re-queue, and then the caller
2109 * may try and access a now freed connection.
2110 *
2111 * @param[in] tconn to move requests off of.
2112 * @param[in] states Only move requests in this state.
2113 * @param[in] max The maximum number of requests to dequeue. 0 for unlimited.
2114 * @param[in] fail_bound If true causes any requests bound to the connection to fail.
2115 * If false bound requests will not be moved.
2116 * @return The number of requests requeued.
2117 */
2118uint64_t trunk_connection_requests_requeue(trunk_connection_t *tconn, int states, uint64_t max, bool fail_bound)
2119{
2120 switch (tconn->pub.state) {
2121 case TRUNK_CONN_ACTIVE:
2122 case TRUNK_CONN_FULL:
2124 return trunk_connection_requests_requeue_priv(tconn, states, max, fail_bound);
2125
2126 default:
2127 return 0;
2128 }
2129}
2130
2131/** Signal a partial write
2132 *
2133 * Where there's high load, and the outbound write buffer is full
2134 *
2135 * @param[in] treq to signal state change for.
2136 */
2138{
2139 if (!fr_cond_assert_msg(treq->pub.trunk, "treq not associated with trunk")) return;
2140
2142 "%s can only be called from within request_mux handler", __FUNCTION__)) return;
2143
2144 switch (treq->pub.state) {
2147 break;
2148
2149 default:
2150 return;
2151 }
2152}
2153
2154/** Signal that the request was written to a connection successfully
2155 *
2156 * @param[in] treq to signal state change for.
2157 */
2159{
2160 if (!fr_cond_assert_msg(treq->pub.trunk, "treq not associated with trunk")) return;
2161
2163 "%s can only be called from within request_mux handler", __FUNCTION__)) return;
2164
2165 switch (treq->pub.state) {
2169 break;
2170
2171 default:
2172 return;
2173 }
2174}
2175
2176/** Signal that the request was written to a connection successfully, but no response is expected
2177 *
2178 * @param[in] treq to signal state change for.
2179 */
2181{
2182 if (!fr_cond_assert_msg(treq->pub.trunk, "treq not associated with trunk")) return;
2183
2185 "%s can only be called from within request_mux handler", __FUNCTION__)) return;
2186
2187 switch (treq->pub.state) {
2191 break;
2192
2193 default:
2194 return;
2195 }
2196}
2197
2198/** Signal that a trunk request is complete
2199 *
2200 * The API client will be informed that the request is now complete.
2201 */
2203{
2204 trunk_t *trunk = treq->pub.trunk;
2205
2206 if (!fr_cond_assert_msg(trunk, "treq not associated with trunk")) return;
2207
2208 /*
2209 * We assume that if the request is being signalled
2210 * as complete from the demux function, that it was
2211 * a successful read.
2212 *
2213 * If this assumption turns out to be incorrect
2214 * then we need to add an argument to signal_complete
2215 * to indicate if this is a successful read.
2216 */
2217 if (IN_REQUEST_DEMUX(trunk)) {
2218 trunk_connection_t *tconn = treq->pub.tconn;
2219
2220 trunk->pub.last_read_success = fr_time();
2222 }
2223
2224 switch (treq->pub.state) {
2226 case TRUNK_REQUEST_STATE_PENDING: /* Got immediate response, i.e. cached */
2229 break;
2230
2231 default:
2232 return;
2233 }
2234}
2235
2236/** Signal that a trunk request failed
2237 *
2238 * The API client will be informed that the request has failed.
2239 */
2241{
2242 if (!fr_cond_assert_msg(treq->pub.trunk, "treq not associated with trunk")) return;
2243
2245}
2246
2247/** Cancel a trunk request
2248 *
2249 * treq can be in any state, but requests to cancel if the treq is not in
2250 * the TRUNK_REQUEST_STATE_PARTIAL or TRUNK_REQUEST_STATE_SENT state will be ignored.
2251 *
2252 * The complete or failed callbacks will not be called here, as it's assumed the request_t *
2253 * is now inviable as it's being cancelled.
2254 *
2255 * The free function however, is called, and that should be used to perform necessary
2256 * cleanup.
2257 *
2258 * @param[in] treq to signal state change for.
2259 */
2261{
2262 trunk_t *trunk;
2263
2264 /*
2265 * Ensure treq hasn't been freed
2266 */
2267 (void)talloc_get_type_abort(treq, trunk_request_t);
2268
2269 if (!fr_cond_assert_msg(treq->pub.trunk, "treq not associated with trunk")) return;
2270
2272 "%s cannot be called within a handler", __FUNCTION__)) return;
2273
2274 trunk = treq->pub.trunk;
2275
2276 switch (treq->pub.state) {
2277 /*
2278 * We don't call the complete or failed callbacks
2279 * as the request and rctx are no longer viable.
2280 */
2283 {
2284 trunk_connection_t *tconn = treq->pub.tconn;
2285
2286 /*
2287 * Don't allow connection state changes
2288 */
2292 "Bad state %s after cancellation",
2293 fr_table_str_by_value(trunk_request_states, treq->pub.state, "<INVALID>"))) {
2295 return;
2296 }
2297 /*
2298 * No cancel muxer. We're done.
2299 *
2300 * If we do have a cancel mux function,
2301 * the next time this connection becomes
2302 * writable, we'll call the cancel mux
2303 * function.
2304 *
2305 * We don't run the complete or failed
2306 * callbacks here as the request is
2307 * being cancelled.
2308 */
2309 if (!trunk->funcs.request_cancel_mux) {
2311 trunk_request_free(&treq);
2312 }
2314 }
2315 break;
2316
2317 /*
2318 * We're already in the process of cancelling a
2319 * request, so ignore duplicate signals.
2320 */
2325 break;
2326
2327 /*
2328 * For any other state, we just release the request
2329 * from its current connection and free it.
2330 */
2331 default:
2333 trunk_request_free(&treq);
2334 break;
2335 }
2336}
2337
2338/** Signal a partial cancel write
2339 *
2340 * Where there's high load, and the outbound write buffer is full
2341 *
2342 * @param[in] treq to signal state change for.
2343 */
2345{
2346 if (!fr_cond_assert_msg(treq->pub.trunk, "treq not associated with trunk")) return;
2347
2349 "%s can only be called from within request_cancel_mux handler", __FUNCTION__)) return;
2350
2351 switch (treq->pub.state) {
2354 break;
2355
2356 default:
2357 return;
2358 }
2359}
2360
2361/** Signal that a remote server has been notified of the cancellation
2362 *
2363 * Called from request_cancel_mux to indicate that the datastore has been informed
2364 * that the response is no longer needed.
2365 *
2366 * @param[in] treq to signal state change for.
2367 */
2369{
2370 if (!fr_cond_assert_msg(treq->pub.trunk, "treq not associated with trunk")) return;
2371
2373 "%s can only be called from within request_cancel_mux handler", __FUNCTION__)) return;
2374
2375 switch (treq->pub.state) {
2379 break;
2380
2381 default:
2382 break;
2383 }
2384}
2385
2386/** Signal that a remote server acked our cancellation
2387 *
2388 * Called from request_demux to indicate that it got an ack for the cancellation.
2389 *
2390 * @param[in] treq to signal state change for.
2391 */
2393{
2394 if (!fr_cond_assert_msg(treq->pub.trunk, "treq not associated with trunk")) return;
2395
2397 "%s can only be called from within request_demux or request_cancel_mux handlers",
2398 __FUNCTION__)) return;
2399
2400 switch (treq->pub.state) {
2402 /*
2403 * This is allowed, as we may not need to wait
2404 * for the database to ACK our cancellation
2405 * request.
2406 *
2407 * Note: TRUNK_REQUEST_STATE_CANCEL_PARTIAL
2408 * is not allowed here, as that'd mean we'd half
2409 * written the cancellation request out to the
2410 * socket, and then decided to abandon it.
2411 *
2412 * That'd leave the socket in an unusable state.
2413 */
2416 break;
2417
2418 default:
2419 break;
2420 }
2421}
2422
2423/** If the trunk request is freed then update the target requests
2424 *
2425 * gperftools showed calling the request free function directly was slightly faster
2426 * than using talloc_free.
2427 *
2428 * @param[in] treq_to_free request.
2429 */
2431{
2432 trunk_request_t *treq = *treq_to_free;
2433 trunk_t *trunk;
2434
2435 if (unlikely(!treq)) return;
2436
2437 trunk = treq->pub.trunk;
2438
2439 /*
2440 * The only valid states a trunk request can be
2441 * freed from.
2442 */
2443 switch (treq->pub.state) {
2449 break;
2450
2451 default:
2452 if (!fr_cond_assert(0)) return;
2453 }
2454
2455 /*
2456 * Zero out the pointer to prevent double frees
2457 */
2458 *treq_to_free = NULL;
2459
2460 /*
2461 * Call the API client callback to free
2462 * any associated memory.
2463 */
2464 DO_REQUEST_FREE(treq);
2465
2466 /*
2467 * Update the last above/below target stats
2468 * We only do this when we alloc or free
2469 * connections, or on connection
2470 * state changes.
2471 */
2472 trunk_requests_per_connection(NULL, NULL, treq->pub.trunk, fr_time(), false);
2473
2474 /*
2475 * This tracks the total number of requests
2476 * allocated and not freed or returned to
2477 * the free list.
2478 */
2479 if (fr_cond_assert(trunk->pub.req_alloc > 0)) trunk->pub.req_alloc--;
2480
2481 /*
2482 * No cleanup delay, means cleanup immediately
2483 */
2486
2487#ifndef NDEBUG
2488 /*
2489 * Ensure anything parented off the treq
2490 * is freed. We do this to trigger
2491 * the destructors for the log entries.
2492 */
2493 talloc_free_children(treq);
2494
2495 /*
2496 * State log should now be empty as entries
2497 * remove themselves from the dlist
2498 * on free.
2499 */
2501 "Should have 0 remaining log entries, have %u", fr_dlist_num_elements(&treq->log));
2502#endif
2503
2504 talloc_free(treq);
2505 return;
2506 }
2507
2508 /*
2509 * Ensure anything parented off the treq
2510 * is freed.
2511 */
2512 talloc_free_children(treq);
2513
2514#ifndef NDEBUG
2515 /*
2516 * State log should now be empty as entries
2517 * remove themselves from the dlist
2518 * on free.
2519 */
2521 "Should have 0 remaining log entries, have %u", fr_dlist_num_elements(&treq->log));
2522#endif
2523
2524 /*
2525 *
2526 * Return the trunk request back to the init state.
2527 */
2528 *treq = (trunk_request_t){
2529 .pub = {
2531 .trunk = treq->pub.trunk,
2532 },
2533 .cancel_reason = TRUNK_CANCEL_REASON_NONE,
2534 .last_freed = fr_time(),
2535#ifndef NDEBUG
2536 .log = treq->log /* Keep the list head, to save reinitialisation */
2537#endif
2538 };
2539
2540
2541 /*
2542 * Insert at the head, so that we can free
2543 * requests that have been unused for N
2544 * seconds from the tail.
2545 */
2546 trunk_list_free_requests_add(trunk, treq);
2547
2548}
2549
2550/** Actually free the trunk request
2551 *
2552 */
2554{
2555 trunk_t *trunk = treq->pub.trunk;
2556
2557 switch (treq->pub.state) {
2560 break;
2561
2562 default:
2563 fr_assert(0);
2564 break;
2565 }
2566
2567 trunk_list_free_requests_remove(trunk, treq);
2568
2569 return 0;
2570}
2571
2572/** (Pre-)Allocate a new trunk request
2573 *
2574 * If trunk->conf.req_pool_headers or trunk->conf.req_pool_size are not zero then the
2575 * request will be a talloc pool, which can be used to hold the preq.
2576 *
2577 * @note Do not use MEM to check the result of this allocated as it may fail for
2578 * non-fatal reasons.
2579 *
2580 * @param[in] trunk to add request to.
2581 * @param[in] request to wrap in a trunk request (treq).
2582 * @return
2583 * - A newly allocated request.
2584 * - NULL if too many requests are allocated.
2585 */
2587{
2588 trunk_request_t *treq;
2589
2590 /*
2591 * The number of treqs currently allocated
2592 * exceeds the maximum number allowed.
2593 */
2594 if (trunk->conf.max_req_per_conn && trunk->conf.max) {
2595 uint64_t limit;
2596
2597 limit = (uint64_t) trunk->conf.max_req_per_conn * trunk->conf.max;
2598 if (trunk->pub.req_alloc >= (limit + trunk->conf.max_backlog)) {
2600 RWARN, WARN, "Refusing to alloc requests - "
2601 "Limit of %"PRIu64" (max = %u * per_connection_max = %u) "
2602 "plus %u backlog requests reached",
2603 limit, trunk->conf.max, trunk->conf.max_req_per_conn,
2604 trunk->conf.max_backlog);
2605 return NULL;
2606 }
2607 }
2608
2609 /*
2610 * Re-use a recently freed request, which might have some
2611 * better cache locality than getting a request from the tail.
2612 *
2613 * If we can't do that, just allocate a new one.
2614 */
2615 treq = trunk_list_free_requests_pop(trunk);
2616 if (treq) {
2618 fr_assert(treq->pub.trunk == trunk);
2619 fr_assert(treq->pub.tconn == NULL);
2622 trunk->pub.req_alloc_reused++;
2623 } else {
2625 trunk->conf.req_pool_headers, trunk->conf.req_pool_size));
2626 talloc_set_destructor(treq, _trunk_request_free);
2627
2628 *treq = (trunk_request_t){
2629 .pub = {
2631 .trunk = trunk
2632 },
2633 .cancel_reason = TRUNK_CANCEL_REASON_NONE
2634 };
2635 trunk->pub.req_alloc_new++;
2636#ifndef NDEBUG
2638#endif
2639 }
2640
2641 trunk->pub.req_alloc++;
2643 /* heap_id - initialised when treq inserted into pending */
2644 /* list - empty */
2645 /* preq - populated later */
2646 /* rctx - populated later */
2647 treq->pub.request = request;
2648
2649 return treq;
2650}
2651
2652/** Enqueue a request that needs data written to the trunk
2653 *
2654 * When a request_t * needs to make an asynchronous request to an external datastore
2655 * it should call this function, specifying a preq (protocol request) containing
2656 * the data necessary to request information from the external datastore, and an
2657 * rctx (resume ctx) used to hold the decoded response and/or any error codes.
2658 *
2659 * After a treq is successfully enqueued it will either be assigned immediately
2660 * to the pending queue of a connection, or if no connections are available,
2661 * (depending on the trunk configuration) the treq will be placed in the trunk's
2662 * global backlog.
2663 *
2664 * After receiving a positive return code from this function the caller should
2665 * immediately yield, to allow the various timers and I/O handlers that drive tconn
2666 * (trunk connection) and treq state changes to be called.
2667 *
2668 * When a tconn becomes writable (or the trunk is configured to be always writable)
2669 * the #trunk_request_mux_t callback will be called to dequeue, encode and
2670 * send any pending requests for that tconn. The #trunk_request_mux_t callback
2671 * is also responsible for tracking the outbound requests to allow the
2672 * #trunk_request_demux_t callback to match inbound responses with the original
2673 * treq. Once the #trunk_request_mux_t callback is done processing the treq
2674 * it signals what state the treq should enter next using one of the
2675 * trunk_request_signal_* functions.
2676 *
2677 * When a tconn becomes readable the user specified #trunk_request_demux_t
2678 * callback is called to process any responses, match them with the original treq.
2679 * and signal what state they should enter next using one of the
2680 * trunk_request_signal_* functions.
2681 *
2682 * @param[in,out] treq_out A trunk request handle. If the memory pointed to
2683 * is NULL, a new treq will be allocated.
2684 * Otherwise treq should point to memory allocated
2685 * with trunk_request_alloc.
2686 * @param[in] trunk to enqueue request on.
2687 * @param[in] request to enqueue.
2688 * @param[in] preq Protocol request to write out. Will be freed when
2689 * treq is freed. Should ideally be parented by the
2690 * treq if possible.
2691 * Use #trunk_request_alloc for pre-allocation of
2692 * the treq.
2693 * @param[in] rctx The resume context to write any result to.
2694 * @return
2695 * - TRUNK_ENQUEUE_OK.
2696 * - TRUNK_ENQUEUE_IN_BACKLOG.
2697 * - TRUNK_ENQUEUE_NO_CAPACITY.
2698 * - TRUNK_ENQUEUE_DST_UNAVAILABLE
2699 * - TRUNK_ENQUEUE_FAIL
2700 */
2702 request_t *request, void *preq, void *rctx)
2703{
2704 trunk_connection_t *tconn = NULL;
2705 trunk_request_t *treq;
2706 trunk_enqueue_t ret;
2707
2708 if (!fr_cond_assert_msg(!IN_HANDLER(trunk),
2709 "%s cannot be called within a handler", __FUNCTION__)) return TRUNK_ENQUEUE_FAIL;
2710
2711 if (!fr_cond_assert_msg(!*treq_out || ((*treq_out)->pub.state == TRUNK_REQUEST_STATE_INIT),
2712 "%s requests must be in \"init\" state", __FUNCTION__)) return TRUNK_ENQUEUE_FAIL;
2713
2714 /*
2715 * If delay_start was set, we may need
2716 * to insert the timer for the connection manager.
2717 */
2718 if (unlikely(!trunk->started)) {
2719 if (trunk_start(trunk) < 0) return TRUNK_ENQUEUE_FAIL;
2720 }
2721
2722 ret = trunk_request_check_enqueue(&tconn, trunk, request);
2723 switch (ret) {
2724 case TRUNK_ENQUEUE_OK:
2725 if (*treq_out) {
2726 treq = *treq_out;
2727 } else {
2728 *treq_out = treq = trunk_request_alloc(trunk, request);
2729 if (!treq) return TRUNK_ENQUEUE_NO_CAPACITY;
2730 }
2731 treq->pub.preq = preq;
2732 treq->pub.rctx = rctx;
2733 if (trunk->conf.always_writable) {
2735 trunk_request_enter_pending(treq, tconn, true);
2738 } else {
2739 trunk_request_enter_pending(treq, tconn, true);
2740 }
2741 break;
2742
2744 if (*treq_out) {
2745 treq = *treq_out;
2746 } else {
2747 *treq_out = treq = trunk_request_alloc(trunk, request);
2748 if (!treq) return TRUNK_ENQUEUE_NO_CAPACITY;
2749 }
2750 treq->pub.preq = preq;
2751 treq->pub.rctx = rctx;
2752 trunk_request_enter_backlog(treq, true);
2753 break;
2754
2755 default:
2756 /*
2757 * If a trunk request was provided
2758 * populate the preq and rctx fields
2759 * so that if it's freed with
2760 * trunk_request_free, the free
2761 * function works as intended.
2762 */
2763 if (*treq_out) {
2764 treq = *treq_out;
2765 treq->pub.preq = preq;
2766 treq->pub.rctx = rctx;
2767 }
2768 return ret;
2769 }
2770
2771 return ret;
2772}
2773
2774/** Re-enqueue a request on the same connection
2775 *
2776 * If the treq has been sent, we assume that we're being signalled to requeue
2777 * because something outside of the trunk API has determined that a retransmission
2778 * is required. The easiest way to perform that retransmission is to clean up
2779 * any tracking information for the request, and the requeue it for transmission.
2780 *
2781 * IF re-queueing fails, the request will enter the fail state. It should not be
2782 * accessed if this occurs.
2783 *
2784 * @param[in] treq to requeue (retransmit).
2785 * @return
2786 * - TRUNK_ENQUEUE_OK.
2787 * - TRUNK_ENQUEUE_DST_UNAVAILABLE - Connection cannot service requests.
2788 * - TRUNK_ENQUEUE_FAIL - Request isn't in a valid state to be reassigned.
2789 */
2791{
2792 trunk_connection_t *tconn = treq->pub.tconn; /* Existing conn */
2793
2794 if (!tconn) return TRUNK_ENQUEUE_FAIL;
2795
2796 if (!IS_PROCESSING(tconn)) {
2799 }
2800
2801 switch (treq->pub.state) {
2807 trunk_request_enter_pending(treq, tconn, false);
2808 if (treq->pub.trunk->conf.always_writable) {
2810 }
2812 break;
2813
2814 case TRUNK_REQUEST_STATE_BACKLOG: /* Do nothing.... */
2815 case TRUNK_REQUEST_STATE_PENDING: /* Do nothing.... */
2816 break;
2817
2818 default:
2820 return TRUNK_ENQUEUE_FAIL;
2821 }
2822
2823 return TRUNK_ENQUEUE_OK;
2824}
2825
2826/** Enqueue additional requests on a specific connection
2827 *
2828 * This may be used to create a series of requests on a single connection, or to generate
2829 * in-band status checks.
2830 *
2831 * @note If conf->always_writable, then the muxer will be called immediately. The caller
2832 * must be able to handle multiple calls to its muxer gracefully.
2833 *
2834 * @param[in,out] treq_out A trunk request handle. If the memory pointed to
2835 * is NULL, a new treq will be allocated.
2836 * Otherwise treq should point to memory allocated
2837 * with trunk_request_alloc.
2838 * @param[in] tconn to enqueue request on.
2839 * @param[in] request to enqueue.
2840 * @param[in] preq Protocol request to write out. Will be freed when
2841 * treq is freed. Should ideally be parented by the
2842 * treq if possible.
2843 * Use #trunk_request_alloc for pre-allocation of
2844 * the treq.
2845 * @param[in] rctx The resume context to write any result to.
2846 * @param[in] ignore_limits Ignore max_req_per_conn. Useful to force status
2847 * checks through even if the connection is at capacity.
2848 * Will also allow enqueuing on "inactive", "draining",
2849 * "draining-to-free" connections.
2850 * @return
2851 * - TRUNK_ENQUEUE_OK.
2852 * - TRUNK_ENQUEUE_NO_CAPACITY - At max_req_per_conn_limit
2853 * - TRUNK_ENQUEUE_DST_UNAVAILABLE - Connection cannot service requests.
2854 */
2856 request_t *request, void *preq, void *rctx,
2857 bool ignore_limits)
2858{
2859 trunk_request_t *treq;
2860 trunk_t *trunk = tconn->pub.trunk;
2861
2862 if (!fr_cond_assert_msg(!*treq_out || ((*treq_out)->pub.state == TRUNK_REQUEST_STATE_INIT),
2863 "%s requests must be in \"init\" state", __FUNCTION__)) return TRUNK_ENQUEUE_FAIL;
2864
2866
2867 /*
2868 * Limits check
2869 */
2870 if (!ignore_limits) {
2871 if (trunk->conf.max_req_per_conn &&
2874
2876 }
2877
2878 if (*treq_out) {
2879 treq = *treq_out;
2880 } else {
2881 *treq_out = treq = trunk_request_alloc(trunk, request);
2882 if (!treq) return TRUNK_ENQUEUE_NO_CAPACITY;
2883 }
2884
2885 treq->pub.preq = preq;
2886 treq->pub.rctx = rctx;
2887 treq->bound_to_conn = true; /* Don't let the request be transferred */
2888
2889 if (trunk->conf.always_writable) {
2891 trunk_request_enter_pending(treq, tconn, true);
2894 } else {
2895 trunk_request_enter_pending(treq, tconn, true);
2896 }
2897
2898 return TRUNK_ENQUEUE_OK;
2899}
2900
2901/** Mark a trunk request as one which will block the connection until it is completed
2902 */
2904{
2905 treq->blocking = true;
2906 if (!treq->pub.tconn) return;
2907
2908 /*
2909 * Prevent additional requests being enqueued on this connection
2910 */
2912}
2913
2914#ifndef NDEBUG
2915/** Used for sanity checks to ensure all log entries have been freed
2916 *
2917 */
2919{
2920 fr_dlist_remove(slog->log_head, slog);
2921
2922 return 0;
2923}
2924
2925void trunk_request_state_log_entry_add(char const *function, int line,
2927{
2928 trunk_request_state_log_t *slog = NULL;
2929
2931 slog = fr_dlist_head(&treq->log);
2932 fr_assert_msg(slog, "slog list head NULL but element counter was %u",
2933 fr_dlist_num_elements(&treq->log));
2934 (void)fr_dlist_remove(&treq->log, slog); /* Returns NULL when removing the list head */
2935 memset(slog, 0, sizeof(*slog));
2936 } else {
2937 MEM(slog = talloc_zero(treq, trunk_request_state_log_t));
2938 talloc_set_destructor(slog, _state_log_entry_free);
2939 }
2940
2941 slog->log_head = &treq->log;
2942 slog->from = treq->pub.state;
2943 slog->to = new;
2944 slog->function = function;
2945 slog->line = line;
2946 if (treq->pub.tconn) {
2947 slog->tconn = treq->pub.tconn;
2948 slog->tconn_id = treq->pub.tconn->pub.conn->id;
2949 slog->tconn_state = treq->pub.tconn->pub.state;
2950 }
2951
2952 fr_dlist_insert_tail(&treq->log, slog);
2953
2954}
2955
2956void trunk_request_state_log(fr_log_t const *log, fr_log_type_t log_type, char const *file, int line,
2957 trunk_request_t const *treq)
2958{
2959 trunk_request_state_log_t *slog = NULL;
2960
2961 unsigned int i;
2962
2963 for (slog = fr_dlist_head(&treq->log), i = 0;
2964 slog;
2965 slog = fr_dlist_next(&treq->log, slog), i++) {
2966 fr_log(log, log_type, file, line, "[%u] %s:%i - in conn %"PRIu64" in state %s - %s -> %s",
2967 i, slog->function, slog->line,
2968 slog->tconn_id,
2970 slog->tconn_state, "<INVALID>") : "none",
2971 fr_table_str_by_value(trunk_request_states, slog->from, "<INVALID>"),
2972 fr_table_str_by_value(trunk_request_states, slog->to, "<INVALID>"));
2973 }
2974}
2975#endif
2976
2977/** Return the count number of connections in the specified states
2978 *
2979 * @param[in] trunk to retrieve counts for.
2980 * @param[in] conn_state One or more #trunk_connection_state_t states or'd together.
2981 * @return The number of connections in the specified states.
2982 */
2984{
2985 uint16_t count = 0;
2986
2987 if (conn_state & TRUNK_CONN_INIT) count += fr_dlist_num_elements(&trunk->init);
2988 if (conn_state & TRUNK_CONN_CONNECTING) count += fr_dlist_num_elements(&trunk->connecting);
2989 if (conn_state & TRUNK_CONN_ACTIVE) count += fr_minmax_heap_num_elements(trunk->active);
2990 if (conn_state & TRUNK_CONN_FULL) count += fr_dlist_num_elements(&trunk->full);
2991 if (conn_state & TRUNK_CONN_INACTIVE) count += fr_dlist_num_elements(&trunk->inactive);
2993 if (conn_state & TRUNK_CONN_CLOSED) count += fr_dlist_num_elements(&trunk->closed);
2994 if (conn_state & TRUNK_CONN_DRAINING) count += fr_dlist_num_elements(&trunk->draining);
2996
2997 return count;
2998}
2999
3000/** Return the count number of requests associated with a trunk connection
3001 *
3002 * @param[in] tconn to return request count for.
3003 * @param[in] req_state One or more request states or'd together.
3004 *
3005 * @return The number of requests in the specified states, associated with a tconn.
3006 */
3008{
3009 uint32_t count = 0;
3010
3012 if (req_state & TRUNK_REQUEST_STATE_PARTIAL) count += tconn->partial ? 1 : 0;
3013 if (req_state & TRUNK_REQUEST_STATE_SENT) count += fr_dlist_num_elements(&tconn->sent);
3015 if (req_state & TRUNK_REQUEST_STATE_CANCEL) count += fr_dlist_num_elements(&tconn->cancel);
3016 if (req_state & TRUNK_REQUEST_STATE_CANCEL_PARTIAL) count += tconn->cancel_partial ? 1 : 0;
3018
3019 return count;
3020}
3021
3022/** Automatically mark a connection as full
3023 *
3024 * @param[in] tconn to potentially mark as full.
3025 */
3027{
3028 trunk_t *trunk = tconn->pub.trunk;
3030
3031 if (tconn->pub.state != TRUNK_CONN_ACTIVE) return;
3032
3033 /*
3034 * Enforces max_req_per_conn
3035 */
3036 if (trunk->conf.max_req_per_conn > 0) {
3039 }
3040}
3041
3042/** Return whether a trunk connection should currently be considered full
3043 *
3044 * @param[in] tconn to check.
3045 * @return
3046 * - true if the connection is full.
3047 * - false if the connection is not full.
3048 */
3050{
3051 trunk_t *trunk = tconn->pub.trunk;
3053
3054 /*
3055 * Enforces max_req_per_conn
3056 */
3058 if ((trunk->conf.max_req_per_conn == 0) || (count < trunk->conf.max_req_per_conn)) return false;
3059
3060 return true;
3061}
3062
3063/** Automatically mark a connection as active or reconnect it
3064 *
3065 * @param[in] tconn to potentially mark as active or reconnect.
3066 */
3068{
3069 if (tconn->pub.state != TRUNK_CONN_FULL) return;
3070
3071 /*
3072 * Enforces max_req_per_conn
3073 */
3075}
3076
3077/** A connection is readable. Call the request_demux function to read pending requests
3078 *
3079 */
3081{
3082 trunk_t *trunk = tconn->pub.trunk;
3083 fr_time_t last_reply = tconn->pub.last_read_success;
3084
3085 DO_REQUEST_DEMUX(tconn);
3086
3087 /*
3088 * The `mru` connection ordering reads `last_read_success`. `trunk_request_signal_complete()`
3089 * sets `last_read_success` when the application completes a request from the demux function.
3090 * Because the heap does not reorder a connection by itself, the trunk reorders the connection
3091 * here, after the demux function returns.
3092 *
3093 * Because the trunk defers freeing a connection while the trunk runs a handler, `tconn` is
3094 * still valid after the demux function returns.
3095 */
3096 if (!fr_time_eq(last_reply, tconn->pub.last_read_success) && (tconn->pub.state == TRUNK_CONN_ACTIVE)) {
3097 CONN_REORDER(tconn);
3098 }
3099}
3100
3101/** A connection is writable. Call the request_mux function to write pending requests
3102 *
3103 */
3105{
3106 trunk_t *trunk = tconn->pub.trunk;
3107
3108 /*
3109 * Call the cancel_sent function (if we have one)
3110 * to inform a backend datastore we no longer
3111 * care about the result
3112 */
3116 DO_REQUEST_CANCEL_MUX(tconn);
3117 }
3121 DO_REQUEST_MUX(tconn);
3122}
3123
3124/** Update the registrations for I/O events we're interested in
3125 *
3126 */
3128{
3129 trunk_t *trunk = tconn->pub.trunk;
3131
3132 switch (tconn->pub.state) {
3133 /*
3134 * We only register I/O events if the trunk connection is
3135 * in one of these states.
3136 *
3137 * For the other states the trunk shouldn't be processing
3138 * requests.
3139 */
3140 case TRUNK_CONN_ACTIVE:
3141 case TRUNK_CONN_FULL:
3146 /*
3147 * If the connection is always writable,
3148 * then we don't care about write events.
3149 */
3150 if (!trunk->conf.always_writable &&
3154 (trunk->funcs.request_cancel_mux ?
3158 }
3159
3162 (trunk->funcs.request_cancel_mux ?
3165 }
3166 break;
3167
3168 default:
3169 break;
3170 }
3171
3172 if (tconn->events != events) {
3173 /*
3174 * There may be a fatal error which results
3175 * in the connection being freed.
3176 *
3177 * Stop that from happening until after
3178 * we're done using it.
3179 */
3182 tconn->events = events;
3184 }
3185}
3186
3187/** Remove a trunk connection from whichever list it's currently in
3188 *
3189 * @param[in] tconn to remove.
3190 */
3192{
3193 trunk_t *trunk = tconn->pub.trunk;
3194
3195 switch (tconn->pub.state) {
3196 case TRUNK_CONN_ACTIVE:
3197 {
3198 int ret;
3199
3200 ret = fr_minmax_heap_extract(trunk->active, tconn);
3201 if (!fr_cond_assert_msg(ret == 0, "Failed extracting conn from active heap: %s", fr_strerror())) return;
3202 }
3203 return;
3204
3205 case TRUNK_CONN_INIT:
3206 fr_dlist_remove(&trunk->init, tconn);
3207 break;
3208
3210 fr_dlist_remove(&trunk->connecting, tconn);
3211 return;
3212
3213 case TRUNK_CONN_CLOSED:
3214 fr_dlist_remove(&trunk->closed, tconn);
3215 return;
3216
3217 case TRUNK_CONN_FULL:
3218 trunk_list_full_remove(trunk, tconn);
3219 return;
3220
3222 trunk_list_inactive_remove(trunk, tconn);
3223 return;
3224
3226 trunk_list_inactive_draining_remove(trunk, tconn);
3227 return;
3228
3230 trunk_list_draining_remove(trunk, tconn);
3231 return;
3232
3234 fr_dlist_remove(&trunk->draining_to_free, tconn);
3235 return;
3236
3237 case TRUNK_CONN_HALTED:
3238 return;
3239 }
3240}
3241
3242/** Transition a connection to the full state
3243 *
3244 * Called whenever a trunk connection is at the maximum number of requests.
3245 * Removes the connection from the connected heap, and places it in the full list.
3246 */
3248{
3249 trunk_t *trunk = tconn->pub.trunk;
3250
3251 switch (tconn->pub.state) {
3252 case TRUNK_CONN_ACTIVE:
3254 break;
3255
3256 default:
3258 }
3259
3260 trunk_list_full_add(trunk, tconn);
3262}
3263
3264/** Transition a connection to the inactive state
3265 *
3266 * Called whenever the API client wants to stop new requests being enqueued
3267 * on a trunk connection.
3268 */
3270{
3271 trunk_t *trunk = tconn->pub.trunk;
3272
3273 switch (tconn->pub.state) {
3274 case TRUNK_CONN_ACTIVE:
3275 case TRUNK_CONN_FULL:
3277 break;
3278
3279 default:
3281 }
3282
3283 trunk_list_inactive_add(trunk, tconn);
3285}
3286
3287/** Transition a connection to the inactive-draining state
3288 *
3289 * Called whenever the trunk manager wants to drain an inactive connection
3290 * of its requests.
3291 */
3293{
3294 trunk_t *trunk = tconn->pub.trunk;
3295
3296 switch (tconn->pub.state) {
3300 break;
3301
3302 default:
3304 }
3305
3306 trunk_list_inactive_draining_add(trunk, tconn);
3308
3309 /*
3310 * Immediately re-enqueue all pending
3311 * requests, so the connection is drained
3312 * quicker.
3313 */
3315}
3316
3317/** Transition a connection to the draining state
3318 *
3319 * Removes the connection from the active heap so it won't be assigned any new
3320 * connections.
3321 */
3323{
3324 trunk_t *trunk = tconn->pub.trunk;
3325
3326 switch (tconn->pub.state) {
3327 case TRUNK_CONN_ACTIVE:
3328 case TRUNK_CONN_FULL:
3332 break;
3333
3334 default:
3336 }
3337
3338 trunk_list_draining_add(trunk, tconn);
3340
3341 /*
3342 * Immediately re-enqueue all pending
3343 * requests, so the connection is drained
3344 * quicker.
3345 */
3347}
3348
3349/** Transition a connection to the draining-to-reconnect state
3350 *
3351 * Removes the connection from the active heap so it won't be assigned any new
3352 * connections.
3353 */
3355{
3356 trunk_t *trunk = tconn->pub.trunk;
3357
3359
3360 switch (tconn->pub.state) {
3361 case TRUNK_CONN_ACTIVE:
3362 case TRUNK_CONN_FULL:
3367 break;
3368
3369 default:
3371 }
3372
3373 fr_dlist_insert_head(&trunk->draining_to_free, tconn);
3375
3376 /*
3377 * Immediately re-enqueue all pending
3378 * requests, so the connection is drained
3379 * quicker.
3380 */
3382}
3383
3384
3385/** Transition a connection back to the active state
3386 *
3387 * This should only be called on a connection which is in the full state,
3388 * inactive state, draining state or connecting state.
3389 */
3391{
3392 trunk_t *trunk = tconn->pub.trunk;
3393 int ret;
3394
3395 switch (tconn->pub.state) {
3396 case TRUNK_CONN_FULL:
3401 break;
3402
3403 case TRUNK_CONN_INIT:
3407 break;
3408
3409 default:
3411 }
3412
3413 ret = fr_minmax_heap_insert(trunk->active, tconn); /* re-insert into the active heap*/
3414 if (!fr_cond_assert_msg(ret == 0, "Failed inserting connection into active heap: %s", fr_strerror())) {
3416 return;
3417 }
3418
3420
3421 /*
3422 * Reorder the connections
3423 */
3424 CONN_REORDER(tconn);
3425
3426 /*
3427 * Rebalance requests
3428 */
3429 trunk_rebalance(trunk);
3430
3431 /*
3432 * We place requests into the backlog
3433 * because there were no connections
3434 * available to handle them.
3435 *
3436 * If a connection has become active
3437 * chances are those backlogged requests
3438 * can now be enqueued, so try and do
3439 * that now.
3440 *
3441 * If there's requests sitting in the
3442 * backlog indefinitely, it's because
3443 * they were inserted there erroneously
3444 * when there were active connections
3445 * which could have handled them.
3446 */
3447 trunk_backlog_drain(trunk);
3448}
3449
3450/** Connection transitioned to the init state
3451 *
3452 * Reflect the connection state change in the lists we use to track connections.
3453 *
3454 * @note This function is only called from the connection API as a watcher.
3455 *
3456 * @param[in] conn The connection which changes state.
3457 * @param[in] prev The connection is was in.
3458 * @param[in] state The connection is now in.
3459 * @param[in] uctx The trunk_connection_t wrapping the connection.
3460 */
3464 void *uctx)
3465{
3466 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
3467 trunk_t *trunk = tconn->pub.trunk;
3468
3469 switch (tconn->pub.state) {
3470 case TRUNK_CONN_HALTED:
3471 break;
3472
3473 case TRUNK_CONN_CLOSED:
3475 break;
3476
3477 default:
3479 }
3480
3481 fr_dlist_insert_head(&trunk->init, tconn);
3483}
3484
3485/** Connection transitioned to the connecting state
3486 *
3487 * Reflect the connection state change in the lists we use to track connections.
3488 *
3489 * @note This function is only called from the connection API as a watcher.
3490 *
3491 * @param[in] conn The connection which changes state.
3492 * @param[in] prev The connection is was in.
3493 * @param[in] state The connection is now in.
3494 * @param[in] uctx The trunk_connection_t wrapping the connection.
3495 */
3499 void *uctx)
3500{
3501 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
3502 trunk_t *trunk = tconn->pub.trunk;
3503
3504 switch (tconn->pub.state) {
3505 case TRUNK_CONN_INIT:
3506 case TRUNK_CONN_CLOSED:
3508 break;
3509
3510 default:
3512 }
3513
3514 /*
3515 * If a connection just entered the
3516 * connecting state, it should have
3517 * no requests associated with it.
3518 */
3520
3521 fr_dlist_insert_head(&trunk->connecting, tconn); /* MUST remain a head insertion for reconnect logic */
3523}
3524
3525/** Connection transitioned to the shutdown state
3526 *
3527 * If we're not already in the draining-to-free state, transition there now.
3528 *
3529 * The idea is that if something signalled the connection to shutdown, we need
3530 * to reflect that by dequeuing any pending requests, not accepting new ones,
3531 * and waiting for the existing requests to complete.
3532 *
3533 * @note This function is only called from the connection API as a watcher.
3534 *
3535 * @param[in] conn The connection which changes state.
3536 * @param[in] prev The connection is was in.
3537 * @param[in] state The connection is now in.
3538 * @param[in] uctx The trunk_connection_t wrapping the connection.
3539 */
3543 void *uctx)
3544{
3545 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
3546
3547 switch (tconn->pub.state) {
3549 /*
3550 * Shutdown from draining-to-free means no outstanding requests.
3551 * Now signal to halt.
3552 */
3554 return;
3555
3556 case TRUNK_CONN_ACTIVE: /* Transition to draining-to-free */
3557 case TRUNK_CONN_FULL:
3561 break;
3562
3563 case TRUNK_CONN_INIT:
3565 case TRUNK_CONN_CLOSED:
3566 case TRUNK_CONN_HALTED:
3568 }
3569
3571}
3572
3573/** Trigger a reconnection of the trunk connection
3574 *
3575 * @param[in] tl timer list the timer was inserted into.
3576 * @param[in] now Current time.
3577 * @param[in] uctx The tconn.
3578 */
3580{
3581 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
3582
3584}
3585
3586/** Connection transitioned to the connected state
3587 *
3588 * Reflect the connection state change in the lists we use to track connections.
3589 *
3590 * @note This function is only called from the connection API as a watcher.
3591 *
3592 * @param[in] conn The connection which changes state.
3593 * @param[in] prev The connection is was in.
3594 * @param[in] state The connection is now in.
3595 * @param[in] uctx The trunk_connection_t wrapping the connection.
3596 */
3600 void *uctx)
3601{
3602 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
3603 trunk_t *trunk = tconn->pub.trunk;
3604
3605 /*
3606 * If a connection was just connected, it should only
3607 * have a pending list of requests. This state is found
3608 * in the rlm_radius module, which starts a new trunk,
3609 * and then immediately enqueues a request onto it. The
3610 * alternative for rlm_radius is to keep it's own queue
3611 * of pending requests before the trunk is fully
3612 * initialized. And then enqueue them onto the trunk
3613 * when the trunk is connected.
3614 *
3615 * It's instead easier (and makes more sense) to allow
3616 * the trunk to accept packets into its queue. If there
3617 * are no connections within a period of time, then the
3618 * requests will retry, or will time out.
3619 */
3621
3622 /*
3623 * Set here, as the active state can
3624 * be transitioned to from full and
3625 * draining too.
3626 */
3627 trunk->pub.last_connected = fr_time();
3628
3629 /*
3630 * Set last_write_success so that idle timeout checks will run
3631 * from when the connection has connected if they fire before
3632 * any requests are written, rather than from server start time.
3633 */
3634 tconn->pub.last_write_success = fr_time();
3635
3636 /*
3637 * Insert a timer to reconnect the
3638 * connection periodically.
3639 */
3640 if (fr_time_delta_ispos(trunk->conf.lifetime)) {
3641 if (fr_timer_in(tconn, trunk->el->tl, &tconn->lifetime_ev,
3642 trunk->conf.lifetime, false, _trunk_connection_lifetime_expire, tconn) < 0) {
3643 PERROR("Failed inserting connection reconnection timer event, halting connection");
3645 return;
3646 }
3647 }
3648
3650}
3651
3652/** Connection failed after it was connected
3653 *
3654 * Reflect the connection state change in the lists we use to track connections.
3655 *
3656 * @note This function is only called from the connection API as a watcher.
3657 *
3658 * @param[in] conn The connection which changes state.
3659 * @param[in] prev The connection is was in.
3660 * @param[in] state The connection is now in.
3661 * @param[in] uctx The trunk_connection_t wrapping the connection.
3662 */
3666 void *uctx)
3667{
3668 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
3669 trunk_t *trunk = tconn->pub.trunk;
3670 bool need_requeue = false;
3671
3672 switch (tconn->pub.state) {
3673 case TRUNK_CONN_ACTIVE:
3674 case TRUNK_CONN_FULL:
3679 need_requeue = true;
3681 break;
3682
3683 case TRUNK_CONN_INIT: /* Initialisation failed */
3687 break;
3688
3689 case TRUNK_CONN_CLOSED:
3690 case TRUNK_CONN_HALTED: /* Can't move backwards? */
3692 }
3693
3694 fr_dlist_insert_head(&trunk->closed, tconn); /* MUST remain a head insertion for reconnect logic */
3696
3697 /*
3698 * Now *AFTER* the connection has been
3699 * removed from the active, pool
3700 * re-enqueue the requests.
3701 */
3702 if (need_requeue) trunk_connection_requests_requeue_priv(tconn, TRUNK_REQUEST_STATE_ALL, 0, true);
3703
3704 /*
3705 * There should be no requests left on this
3706 * connection. They should have all been
3707 * moved off or failed.
3708 */
3710
3711 /*
3712 * Clear statistics and flags
3713 */
3714 tconn->sent_count = 0;
3715
3716 /*
3717 * Remove the reconnect event
3718 */
3720
3721 /*
3722 * Remove the I/O events
3723 */
3725}
3726
3727/** Connection failed
3728 *
3729 * @param[in] conn The connection which changes state.
3730 * @param[in] prev The connection is was in.
3731 * @param[in] state The connection is now in.
3732 * @param[in] uctx The trunk_connection_t wrapping the connection.
3733 */
3735 connection_state_t prev,
3737 void *uctx)
3738{
3739 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
3740 trunk_t *trunk = tconn->pub.trunk;
3741
3742 /*
3743 * Need to set this first as it
3744 * determines whether requests are
3745 * re-queued or fail outright.
3746 */
3747 trunk->pub.last_failed = fr_time();
3748
3749 /*
3750 * Failed in the init state, transition the
3751 * connection to closed, else we get an
3752 * INIT -> INIT transition which triggers
3753 * an assert.
3754 */
3755 if (prev == CONNECTION_STATE_INIT) _trunk_connection_on_closed(conn, prev, state, uctx);
3756
3757 /*
3758 * See what the state of the trunk is
3759 * if there are no connections that could
3760 * potentially accept requests in the near
3761 * future, then fail all the requests in the
3762 * trunk backlog.
3763 */
3764 if ((prev == CONNECTION_STATE_CONNECTED) &&
3769}
3770
3771/** Connection transitioned to the halted state
3772 *
3773 * Remove the connection remove all lists, as it's likely about to be freed.
3774 *
3775 * Setting the trunk back to the init state ensures that if the code is ever
3776 * refactored and #connection_signal_reconnect is used after a connection
3777 * is halted, then everything is maintained in a valid state.
3778 *
3779 * @note This function is only called from the connection API as a watcher.
3780 *
3781 * @param[in] conn The connection which changes state.
3782 * @param[in] prev The connection is was in.
3783 * @param[in] state The connection is now in.
3784 * @param[in] uctx The trunk_connection_t wrapping the connection.
3785 */
3789 void *uctx)
3790{
3791 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
3792 trunk_t *trunk = tconn->pub.trunk;
3793
3794 switch (tconn->pub.state) {
3795 case TRUNK_CONN_INIT:
3796 case TRUNK_CONN_CLOSED:
3798 break;
3799
3800 default:
3802 }
3803
3804 /*
3805 * It began life in the halted state,
3806 * and will end life in the halted state.
3807 */
3809
3810 /*
3811 * There should be no requests left on this
3812 * connection. They should have all been
3813 * moved off or failed.
3814 */
3816
3817 /*
3818 * And free the connection...
3819 */
3820 if (trunk->in_handler) {
3821 /*
3822 * ...later.
3823 */
3824 fr_dlist_insert_tail(&trunk->to_free, tconn);
3825 return;
3826 }
3827 talloc_free(tconn);
3828}
3829
3830/** Free a connection
3831 *
3832 * Enforces orderly free order of children of the tconn
3833 */
3835{
3837 fr_assert(!fr_dlist_entry_in_list(&tconn->entry)); /* Should not be in a list */
3838
3839 /*
3840 * Loop over all the requests we gathered
3841 * and transition them to the failed state,
3842 * freeing them.
3843 *
3844 * Usually, requests will be re-queued when
3845 * a connection enters the closed state,
3846 * but in this case because the whole trunk
3847 * is being freed, we don't bother, and
3848 * just signal to the API client that the
3849 * requests failed.
3850 */
3851 if (tconn->pub.trunk->freeing) {
3852 fr_dlist_head_t to_fail;
3853 trunk_request_t *treq = NULL;
3854
3855 fr_dlist_talloc_init(&to_fail, trunk_request_t, entry);
3856
3857 /*
3858 * Remove requests from this connection
3859 */
3861 while ((treq = fr_dlist_next(&to_fail, treq))) {
3862 trunk_request_t *prev;
3863
3864 prev = fr_dlist_remove(&to_fail, treq);
3866 treq = prev;
3867 }
3868 }
3869
3870 /*
3871 * Ensure we're not signalled by the connection
3872 * as it processes its backlog of state changes,
3873 * as we are about to be freed.
3874 */
3882
3883 /*
3884 * This may return -1, indicating the free was deferred
3885 * this is fine. It just means the conn will be freed
3886 * after all the handlers have exited.
3887 */
3888 (void)talloc_free(tconn->pub.conn);
3889 tconn->pub.conn = NULL;
3890
3891 return 0;
3892}
3893
3894/** Attempt to spawn a new connection
3895 *
3896 * Calls the API client's alloc() callback to create a new connection_t,
3897 * then inserts the connection into the 'connecting' list.
3898 *
3899 * @param[in] trunk to spawn connection in.
3900 * @param[in] now The current time.
3901 */
3903{
3904 trunk_connection_t *tconn;
3905
3906
3907 /*
3908 * Call the API client's callback to create
3909 * a new connection_t.
3910 */
3911 MEM(tconn = talloc_zero(trunk, trunk_connection_t));
3912 tconn->pub.trunk = trunk;
3913 tconn->pub.state = TRUNK_CONN_HALTED; /* All connections start in the halted state */
3914
3915 /*
3916 * Allocate a new connection_t or fail.
3917 */
3918 DO_CONNECTION_ALLOC(tconn);
3919
3921 fr_dlist_talloc_init(&tconn->sent, trunk_request_t, entry);
3925
3926 /*
3927 * OK, we have the connection, now setup watch
3928 * points so we know when it changes state.
3929 *
3930 * This lets us automatically move the tconn
3931 * between the different lists in the trunk
3932 * with minimum extra code.
3933 */
3935 _trunk_connection_on_init, false, tconn); /* Before init() has been called */
3936
3938 _trunk_connection_on_connecting, false, tconn); /* After init() has been called */
3939
3941 _trunk_connection_on_connected, false, tconn); /* After open() has been called */
3942
3944 _trunk_connection_on_closed, false, tconn); /* Before close() has been called */
3945
3947 _trunk_connection_on_failed, false, tconn); /* Before failed() has been called */
3948
3950 _trunk_connection_on_shutdown, false, tconn); /* After shutdown() has been called */
3951
3953 _trunk_connection_on_halted, false, tconn); /* About to be freed */
3954
3955 talloc_set_destructor(tconn, _trunk_connection_free);
3956
3957 connection_signal_init(tconn->pub.conn); /* annnnd GO! */
3958
3959 trunk->pub.last_open = now;
3960
3961 return 0;
3962}
3963
3964/** Pop a cancellation request off a connection's cancellation queue
3965 *
3966 * The request we return is advanced by the request moving out of the
3967 * cancel state and into the cancel_sent or cancel_complete state.
3968 *
3969 * One of these signalling functions must be called after the request
3970 * has been popped:
3971 *
3972 * - #trunk_request_signal_cancel_sent
3973 * The remote datastore has been informed, but we need to wait for acknowledgement.
3974 * The #trunk_request_demux_t callback must handle the acks calling
3975 * #trunk_request_signal_cancel_complete when an ack is received.
3976 *
3977 * - #trunk_request_signal_cancel_complete
3978 * The request was cancelled and we don't need to wait, clean it up immediately.
3979 *
3980 * @param[out] treq_out to process
3981 * @param[in] tconn Connection to drain cancellation request from.
3982 * @return
3983 * - 1 if no more requests.
3984 * - 0 if a new request was written to treq_out.
3985 * - -1 if the connection was previously freed. Caller *MUST NOT* touch any
3986 * memory or requests associated with the connection.
3987 * - -2 if called outside of the cancel muxer.
3988 */
3990{
3991 if (unlikely(tconn->pub.state == TRUNK_CONN_HALTED)) return -1;
3992
3994 "%s can only be called from within request_cancel_mux handler",
3995 __FUNCTION__)) return -2;
3996
3997 *treq_out = tconn->cancel_partial ? tconn->cancel_partial : fr_dlist_head(&tconn->cancel);
3998 if (!*treq_out) return 1;
3999
4000 return 0;
4001}
4002
4003/** Pop a request off a connection's pending queue
4004 *
4005 * The request we return is advanced by the request moving out of the partial or
4006 * pending states, when the mux function signals us.
4007 *
4008 * If the same request is returned again and again, it means the muxer isn't actually
4009 * doing anything with the request we returned, and it's and error in the muxer code.
4010 *
4011 * One of these signalling functions must be used after the request has been popped:
4012 *
4013 * - #trunk_request_signal_complete
4014 * The request was completed. Either we got a synchronous response, or we knew the
4015 * response without contacting an external server (cache).
4016 *
4017 * - #trunk_request_signal_fail
4018 * Failed muxing the request due to a permanent issue, i.e. an invalid request.
4019 *
4020 * - #trunk_request_signal_partial
4021 * Wrote part of a request. This request will be returned on the next call to this
4022 * function so that the request_mux function can finish writing it. Only useful
4023 * for stream type connections. Datagram type connections cannot have partial
4024 * writes.
4025 *
4026 * - #trunk_request_signal_sent Successfully sent a request.
4027 *
4028 * @param[out] treq_out to process
4029 * @param[in] tconn to pop a request from.
4030 * @return
4031 * - 1 if no more requests.
4032 * - 0 if a new request was written to treq_out.
4033 * - -1 if the connection was previously freed. Caller *MUST NOT* touch any
4034 * memory or requests associated with the connection.
4035 * - -2 if called outside of the muxer.
4036 */
4038{
4039 if (unlikely(tconn->pub.state == TRUNK_CONN_HALTED)) return -1;
4040
4042 "%s can only be called from within request_mux handler",
4043 __FUNCTION__)) return -2;
4044
4045 *treq_out = tconn->partial ? tconn->partial : fr_heap_peek(tconn->pending);
4046 if (!*treq_out) return 1;
4047
4048 return 0;
4049}
4050
4051/** Signal that a trunk connection is writable
4052 *
4053 * Should be called from the 'write' I/O handler to signal that requests can be enqueued.
4054 *
4055 * @param[in] tconn to signal.
4056 */
4058{
4059 trunk_t *trunk = tconn->pub.trunk;
4060
4061 if (!fr_cond_assert_msg(!IN_HANDLER(tconn->pub.trunk),
4062 "%s cannot be called within a handler", __FUNCTION__)) return;
4063
4064 DEBUG3("[%" PRIu64 "] Signalled writable", tconn->pub.conn->id);
4065
4067}
4068
4069/** Signal that a trunk connection is readable
4070 *
4071 * Should be called from the 'read' I/O handler to signal that requests should be dequeued.
4072 *
4073 * @param[in] tconn to signal.
4074 */
4076{
4077 trunk_t *trunk = tconn->pub.trunk;
4078
4079 if (!fr_cond_assert_msg(!IN_HANDLER(tconn->pub.trunk),
4080 "%s cannot be called within a handler", __FUNCTION__)) return;
4081
4082 DEBUG3("[%" PRIu64 "] Signalled readable", tconn->pub.conn->id);
4083
4085}
4086
4087/** Signal a trunk connection cannot accept more requests
4088 *
4089 * @param[in] tconn to signal.
4090 */
4092{
4093 /* Can be called anywhere */
4094
4095 switch (tconn->pub.state) {
4096 case TRUNK_CONN_ACTIVE:
4097 case TRUNK_CONN_FULL:
4099 break;
4100
4103 break;
4104
4105 default:
4106 return;
4107 }
4108}
4109
4110/** Signal a trunk connection is no longer full
4111 *
4112 * @param[in] tconn to signal.
4113 */
4115{
4116 switch (tconn->pub.state) {
4117 case TRUNK_CONN_FULL:
4118 trunk_connection_auto_unfull(tconn); /* Mark as active if it should be active */
4119 break;
4120
4122 /*
4123 * Do the appropriate state transition based on
4124 * how many requests the trunk connection is
4125 * currently servicing.
4126 */
4127 if (trunk_connection_is_full(tconn)) {
4129 break;
4130 }
4132 break;
4133
4134 /*
4135 * Unsetting the active flag just moves
4136 * the connection back to the normal
4137 * draining state.
4138 */
4139 case TRUNK_CONN_INACTIVE_DRAINING: /* Only an external signal can trigger this transition */
4141 break;
4142
4143 default:
4144 return;
4145 }
4146}
4147
4148/** Signal a trunk connection is no longer viable
4149 *
4150 * @param[in] tconn to signal.
4151 * @param[in] reason the connection is being reconnected.
4152 */
4157
4158/** Standard I/O read function
4159 *
4160 * Underlying FD in now readable, so call the trunk to read any pending requests
4161 * from this connection.
4162 *
4163 * @param[in] el The event list signalling.
4164 * @param[in] fd that's now readable.
4165 * @param[in] flags describing the read event.
4166 * @param[in] uctx The trunk connection handle (tconn).
4167 */
4169{
4170 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
4171
4173}
4174
4175/** Standard I/O write function
4176 *
4177 * Underlying FD is now writable, so call the trunk to write any pending requests
4178 * to this connection.
4179 *
4180 * @param[in] el The event list signalling.
4181 * @param[in] fd that's now writable.
4182 * @param[in] flags describing the write event.
4183 * @param[in] uctx The trunk connection handle (tcon).
4184 */
4186{
4187 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
4188
4190}
4191
4192
4193/** Returns true if the trunk connection is in one of the specified states
4194 *
4195 * @param[in] tconn To check state for.
4196 * @param[in] state to check
4197 * @return
4198 * - True if trunk connection is in a particular state.
4199 * - False if trunk connection is not in a particular state.
4200 */
4202{
4203 return (bool)(tconn->pub.state & state);
4204}
4205
4206/** Close connections in a particular connection list if they have no requests associated with them
4207 *
4208 * @param[in] trunk containing connections we want to close.
4209 * @param[in] head of list of connections to examine.
4210 */
4212{
4213 trunk_connection_t *tconn = NULL, *last = NULL;
4214
4215 while ((tconn = fr_dlist_next(head, tconn))) {
4216 trunk_connection_t *prev;
4217
4218 /*
4219 * The watch callback which fires after shutdown removes
4220 * the connection from the list being inspected, however
4221 * in single threaded mode, if this requires an event to
4222 * fire before the connection shutdown is complete then
4223 * that won't happen within this loop, so if `next` gives
4224 * the same connection twice, just move on.
4225 */
4226 if (last == tconn) continue;
4227 last = tconn;
4228
4230
4231 prev = fr_dlist_prev(head, tconn);
4232
4233 DEBUG3("Closing %s connection with no requests",
4235 /*
4236 * Close the connection as gracefully
4237 * as possible by signalling it should
4238 * shutdown.
4239 *
4240 * The connection, should, if serviced
4241 * correctly by the underlying library,
4242 * automatically transition to halted after
4243 * all pending reads/writes are
4244 * complete at which point we'll be informed
4245 * and free our tconn wrapper.
4246 */
4248 tconn = prev;
4249 }
4250}
4251
4252/** Rebalance connections across active trunk members when a new connection becomes active
4253 *
4254 * We don't have any visibility into the connection prioritisation algorithm
4255 * it's essentially a black box.
4256 *
4257 * We can however determine when the correct level of requests per connection
4258 * has been reached, by dequeuing and requeing requests up until the point
4259 * where the connection that just had a request dequeued, receives the same
4260 * request back.
4261 *
4262 * @param[in] trunk The trunk to rebalance.
4263 */
4264static void trunk_rebalance(trunk_t *trunk)
4265{
4267 trunk_connection_t *tail;
4268
4270 fr_minmax_heap_max_peek((void **)&tail, trunk->active);
4271
4272 /*
4273 * Only rebalance if the top and bottom of
4274 * the heap are not equal.
4275 */
4276 if (trunk->funcs.connection_prioritise(tail, head) == 0) return;
4277
4278 DEBUG3("Rebalancing requests");
4279
4280 /*
4281 * Keep requeuing requests from the connection
4282 * at the bottom of the heap until the
4283 * connection at the top is shifted from that
4284 * position.
4285 */
4286 while (fr_minmax_heap_min_peek(trunk->active) == head) {
4287 fr_minmax_heap_max_peek((void **)&tail, trunk->active);
4289 }
4290}
4291
4292/** Recalculate the trunk's aggregate state from its connection counts
4293 *
4294 * Derives the global #trunk_state_t from the number of connections in each
4295 * connection state, and fires any registered state-change watchers (via
4296 * #TRUNK_STATE_TRANSITION) if the aggregate state has changed.
4297 *
4298 * @param[in] trunk to update.
4299 */
4300static void trunk_state_update(trunk_t *trunk)
4301{
4302 trunk_state_t new_state;
4303
4304 /*
4305 * Don't churn the state or fire watchers while the trunk is
4306 * being torn down.
4307 */
4308 if (trunk->freeing) return;
4309
4311 /*
4312 * One or more connections are active and operational. The trunk is ACTIVE.
4313 */
4314 new_state = TRUNK_STATE_ACTIVE;
4315
4317 /*
4318 * Connections are being opened, but none are usable yet.
4319 *
4320 * This is checked before FULL. If a connection is CONNECTING, then the trunk is by
4321 * definition not full.
4322 */
4323 new_state = TRUNK_STATE_PENDING;
4324
4325 } else if (trunk->conf.max &&
4327 /*
4328 * No active or connecting connections, and every one of the maximum permitted
4329 * connections is connected and full. The backend is reachable, but the trunk has no
4330 * spare capacity, and can accept no more traffic.
4331 */
4332 new_state = TRUNK_STATE_FULL;
4333
4335 /*
4336 * Connections exist, but they have all failed and are
4337 * closed / in reconnect backoff. The backend is
4338 * currently unreachable.
4339 */
4340 new_state = TRUNK_STATE_FAILED;
4341
4342 } else {
4343 new_state = TRUNK_STATE_IDLE;
4344 }
4345
4346 if (new_state == trunk->pub.state) return;
4347
4348 /*
4349 * This can be reached from within a state-change watcher. A watcher may enqueue a request or
4350 * reconnect a connection, which changes a connection's state and calls
4351 * trunk_requests_per_connection() -> trunk_state_update().
4352 *
4353 * Nested watcher calls are not allowed (see trunk_watch_call()). If we're already inside one,
4354 * leave the state unchanged and let the next non-nested update, or the periodic trunk_manage(),
4355 * reconcile it.
4356 */
4357 if (trunk->next_watcher != NULL) return;
4358
4359 TRUNK_STATE_TRANSITION(new_state);
4360}
4361
4362/** Implements the algorithm we use to manage requests per connection levels
4363 *
4364 * This is executed periodically using a timer event, and opens/closes
4365 * connections.
4366 *
4367 * The aim is to try and keep the request per connection level in a sweet spot,
4368 * where there's enough outstanding work for the connection/pipelining to work
4369 * efficiently, but not so much so that we encounter increased latency.
4370 *
4371 * In the request enqueue and dequeue functions we record every time the
4372 * average number of requests per connection goes above the target count
4373 * and record every time the average number of requests per connection goes
4374 * below the target count.
4375 *
4376 * This may sound expensive, but in all cases we're just summing counters.
4377 * CPU time required does not increase with additional requests, only with
4378 * large numbers of connections.
4379 *
4380 * If we do encounter scaling issues, we can always maintain the counters
4381 * as aggregates as an optimisation later.
4382 *
4383 * If when the management function runs, the trunk was above the target
4384 * most recently, we:
4385 * - Return if we've been in this state for a shorter period than 'open_delay'.
4386 * - Return if we're at max.
4387 * - Return if opening a new connection will take us below the load target.
4388 * - Return if we last opened a connection within 'open_delay'.
4389 * - Otherwise we attempt to open a new connection.
4390 *
4391 * If the trunk we below the target most recently, we:
4392 * - Return if we've been in this state for a shorter period than 'close_delay'.
4393 * - Return if we're at min.
4394 * - Return if we have no connections.
4395 * - Close a connection if min is 0, and we have no outstanding
4396 * requests. Then return.
4397 * - Return if closing a new connection will take us above the load target.
4398 * - Return if we last closed a connection within 'closed_delay'.
4399 * - Otherwise we move a connection to draining state.
4400 */
4401static void trunk_manage(trunk_t *trunk, fr_time_t now)
4402{
4403 trunk_connection_t *tconn = NULL;
4404 trunk_request_t *treq;
4405 uint32_t average = 0;
4406 uint32_t req_count;
4407 uint16_t conn_count;
4408
4409 DEBUG4("Managing trunk");
4410
4411 /*
4412 * Cleanup requests in our request cache which
4413 * have been reapable for too long.
4414 */
4415 while ((treq = trunk_list_free_requests_peek(trunk)) &&
4417
4418 /*
4419 * If we have idle connections, then close them, maintaining "min" connections.
4420 */
4422 (fr_minmax_heap_num_elements(trunk->active) > trunk->conf.min)) {
4424 fr_time_t idle_cutoff = fr_time_sub(now, trunk->conf.idle_timeout);
4425
4426 for (tconn = fr_minmax_heap_iter_init(trunk->active, &iter);
4427 tconn;
4428 tconn = fr_minmax_heap_iter_next(trunk->active, &iter)) {
4429 /*
4430 * The connection has outstanding requests without replies, don't do anything.
4431 */
4432 if (fr_heap_num_elements(tconn->pending) > 0) continue;
4433
4434 /*
4435 * The connection was last active after the idle cutoff time, don't do anything.
4436 */
4437 if (fr_time_gt(tconn->pub.last_write_success, idle_cutoff)) continue;
4438
4439 /*
4440 * This connection has been inactive since before the idle timeout. Drain it,
4441 * and free it.
4442 *
4443 * This also extracts the connection from the minmax heap, which invalidates the
4444 * iterator, so we stop iterating over it.
4445 */
4447 break;
4448 }
4449 }
4450
4451 /*
4452 * Free any connections which have drained
4453 * and we didn't reactivate during the last
4454 * round of management.
4455 */
4459
4460 /*
4461 * Process deferred connection freeing
4462 */
4463 if (!trunk->in_handler) fr_dlist_talloc_free(&trunk->to_free);
4464
4465 /*
4466 * Update the state of the trunk
4467 */
4468 trunk_state_update(trunk);
4469
4470 /*
4471 * A trunk can be signalled to not proactively
4472 * manage connections if a destination is known
4473 * to be unreachable, and doing so would result
4474 * in spurious connections still being opened.
4475 *
4476 * We still run other connection management
4477 * functions and just short circuit the function
4478 * here.
4479 */
4480 if (!trunk->managing_connections) return;
4481
4482 /*
4483 * We're above the target requests per connection
4484 * spawn more connections!
4485 */
4487 /*
4488 * If connecting is provided, check we
4489 * wouldn't have too many connections in
4490 * the connecting state.
4491 *
4492 * This is a throttle in the case of transitory
4493 * load spikes, or a backend becoming
4494 * unavailable.
4495 */
4496 if ((trunk->conf.connecting > 0) &&
4498 trunk->conf.connecting)) {
4499 DEBUG4("Not opening connection - Too many (%u) connections in the connecting state",
4500 trunk->conf.connecting);
4501 return;
4502 }
4503
4504 trunk_requests_per_connection(&conn_count, &req_count, trunk, now, true);
4505
4506 /*
4507 * Only apply hysteresis if we have at least
4508 * one available connection.
4509 */
4510 if (conn_count && fr_time_gt(fr_time_add(trunk->pub.last_above_target, trunk->conf.open_delay), now)) {
4511 DEBUG4("Not opening connection - Need to be above target for %pVs. It's been %pVs",
4514 return; /* too soon */
4515 }
4516
4517 /*
4518 * We don't consider 'draining' connections
4519 * in the max calculation, as if we do
4520 * determine that we need to spawn a new
4521 * request, then we'd move all 'draining'
4522 * connections to active before spawning
4523 * any new connections.
4524 */
4525 if ((trunk->conf.max > 0) && (conn_count >= trunk->conf.max)) {
4526 DEBUG4("Not opening connection - Have %u connections, need %u or below",
4527 conn_count, trunk->conf.max);
4528 return;
4529 }
4530
4531 /*
4532 * We consider requests pending on all connections
4533 * and the trunk's backlog as that's the current count
4534 * load.
4535 */
4536 if (!req_count) {
4537 DEBUG4("Not opening connection - No outstanding requests");
4538 return;
4539 }
4540
4541 /*
4542 * Do the n+1 check, i.e. if we open one connection
4543 * will that take us below our target threshold.
4544 */
4545 if (conn_count > 0) {
4546 average = ROUND_UP_DIV(req_count, (conn_count + 1));
4547 if (average < trunk->conf.target_req_per_conn) {
4548 DEBUG4("Not opening connection - Would leave us below our target requests "
4549 "per connection (now %u, after open %u)",
4550 ROUND_UP_DIV(req_count, conn_count), average);
4551 return;
4552 }
4553 } else {
4554 (void)trunk_connection_spawn(trunk, now);
4555 return;
4556 }
4557
4558 /*
4559 * If we've got a connection in the draining list
4560 * move it back into the active list if we've
4561 * been requested to add a connection back in.
4562 */
4563 tconn = fr_dlist_head(&trunk->draining);
4564 if (tconn) {
4565 if (trunk_connection_is_full(tconn)) {
4567 } else {
4569 }
4570 return;
4571 }
4572
4573 /*
4574 * Implement delay if there's no connections that
4575 * could be immediately re-activated.
4576 */
4577 if (fr_time_gt(fr_time_add(trunk->pub.last_open, trunk->conf.open_delay), now)) {
4578 DEBUG4("Not opening connection - Need to wait %pVs before opening another connection. "
4579 "It's been %pVs",
4582 return;
4583 }
4584
4585 DEBUG4("Opening connection - Above target requests per connection (now %u, target %u)",
4586 ROUND_UP_DIV(req_count, conn_count), trunk->conf.target_req_per_conn);
4587 /* last_open set by trunk_connection_spawn */
4588 (void)trunk_connection_spawn(trunk, now);
4589 }
4590
4591 /*
4592 * We're below the target requests per connection.
4593 * Free some connections...
4594 */
4595 else if (fr_time_gt(trunk->pub.last_below_target, trunk->pub.last_above_target)) {
4596 if (fr_time_gt(fr_time_add(trunk->pub.last_below_target, trunk->conf.close_delay), now)) {
4597 DEBUG4("Not closing connection - Need to be below target for %pVs. It's been %pVs",
4600 return; /* too soon */
4601 }
4602
4603 trunk_requests_per_connection(&conn_count, &req_count, trunk, now, true);
4604
4605 if (!conn_count) {
4606 DEBUG4("Not closing connection - No connections to close!");
4607 return;
4608 }
4609
4610 if ((trunk->conf.min > 0) && ((conn_count - 1) < trunk->conf.min)) {
4611 DEBUG4("Not closing connection - Have %u connections, need %u or above",
4612 conn_count, trunk->conf.min);
4613 return;
4614 }
4615
4616 if (!req_count) {
4617 DEBUG4("Closing connection - No outstanding requests");
4618 goto close;
4619 }
4620
4621 /*
4622 * The minimum number of connections must be set
4623 * to zero for this to work.
4624 * min == 0, no requests, close all the connections.
4625 * This is useful for backup databases, when
4626 * maintaining the connection would lead to lots of
4627 * log file churn.
4628 */
4629 if (conn_count == 1) {
4630 DEBUG4("Not closing connection - Would leave connections "
4631 "and there are still %u outstanding requests", req_count);
4632 return;
4633 }
4634
4635 /*
4636 * Do the n-1 check, i.e. if we close one connection
4637 * will that take us above our target threshold.
4638 */
4639 average = ROUND_UP_DIV(req_count, (conn_count - 1));
4640 if (average > trunk->conf.target_req_per_conn) {
4641 DEBUG4("Not closing connection - Would leave us above our target requests per connection "
4642 "(now %u, after close %u)", ROUND_UP_DIV(req_count, conn_count), average);
4643 return;
4644 }
4645
4646 DEBUG4("Closing connection - Below target requests per connection (now %u, target %u)",
4647 ROUND_UP_DIV(req_count, conn_count), trunk->conf.target_req_per_conn);
4648
4649 close:
4650 if (fr_time_gt(fr_time_add(trunk->pub.last_closed, trunk->conf.close_delay), now)) {
4651 DEBUG4("Not closing connection - Need to wait %pVs before closing another connection. "
4652 "It's been %pVs",
4655 return;
4656 }
4657
4658 /*
4659 * If the last event on the trunk was a connection failure and
4660 * there is only one connection, this may well be a reconnect
4661 * attempt after a failure - and needs to persist otherwise
4662 * the last event will be a failure and no new connection will
4663 * be made, leading to no new requests being enqueued.
4664 */
4665 if (fr_time_gt(trunk->pub.last_failed, fr_time_wrap(0)) &&
4666 fr_time_lt(trunk->pub.last_connected, trunk->pub.last_failed) && (conn_count == 1)) {
4667 DEBUG4("Not closing remaining connection - last event was a failure");
4668 return;
4669 }
4670
4671 /*
4672 * Inactive connections get counted in the
4673 * set of viable connections, but are likely
4674 * to be congested or dead, so we drain
4675 * (and possibly eventually free) those first.
4676 */
4677 if ((tconn = trunk_list_inactive_peek(trunk))) {
4678 /*
4679 * If the connection has no requests associated
4680 * with it then immediately free.
4681 */
4683 connection_signal_halt(tconn->pub.conn); /* Also frees the tconn */
4684 } else {
4686 }
4687 /*
4688 * It is possible to have too may connecting
4689 * connections when the connections are
4690 * taking a while to open and the number
4691 * of requests decreases.
4692 */
4693 } else if ((tconn = fr_dlist_tail(&trunk->connecting))) {
4694 connection_signal_halt(tconn->pub.conn); /* Also frees the tconn */
4695
4696 /*
4697 * Finally if there are no "connecting"
4698 * connections to close, and no "inactive"
4699 * connections, start draining "active"
4700 * connections.
4701 */
4702 } else if ((fr_minmax_heap_max_peek((void **)&tconn, trunk->active) == 0) && tconn) {
4703 /*
4704 * If the connection has no requests associated
4705 * with it then immediately free.
4706 */
4708 connection_signal_halt(tconn->pub.conn); /* Also frees the tconn */
4709 } else {
4711 }
4712 }
4713
4714 trunk->pub.last_closed = now;
4715
4716 return;
4717 }
4718}
4719
4720/** Event to periodically call the connection management function
4721 *
4722 * @param[in] tl this event belongs to.
4723 * @param[in] now current time.
4724 * @param[in] uctx The trunk.
4725 */
4726static void _trunk_timer(fr_timer_list_t *tl, fr_time_t now, void *uctx)
4727{
4728 trunk_t *trunk = talloc_get_type_abort(uctx, trunk_t);
4729
4730 trunk_manage(trunk, now);
4731
4733 if (fr_timer_in(trunk, tl, &trunk->manage_ev, trunk->conf.manage_interval,
4734 false, _trunk_timer, trunk) < 0) {
4735 PERROR("Failed inserting trunk management event");
4736 /* Not much we can do, hopefully the trunk will be freed soon */
4737 }
4738 }
4739}
4740
4741/** Return a count of requests on a connection in a specific state
4742 *
4743 * @param[in] trunk to retrieve counts for.
4744 * @param[in] conn_state One or more connection states or'd together.
4745 * @param[in] req_state One or more request states or'd together.
4746 * @return The number of requests in a particular state, on connection in a particular state.
4747 */
4748uint64_t trunk_request_count_by_state(trunk_t *trunk, int conn_state, int req_state)
4749{
4750 uint64_t count = 0;
4751 trunk_connection_t *tconn = NULL;
4753
4754#define COUNT_BY_STATE(_state, _list) \
4755do { \
4756 if (conn_state & (_state)) { \
4757 tconn = NULL; \
4758 while ((tconn = fr_dlist_next(&trunk->_list, tconn))) { \
4759 count += trunk_request_count_by_connection(tconn, req_state); \
4760 } \
4761 } \
4762} while (0)
4763
4764 if (conn_state & TRUNK_CONN_ACTIVE) {
4765 for (tconn = fr_minmax_heap_iter_init(trunk->active, &iter);
4766 tconn;
4767 tconn = fr_minmax_heap_iter_next(trunk->active, &iter)) {
4768 count += trunk_request_count_by_connection(tconn, req_state);
4769 }
4770 }
4771
4774 COUNT_BY_STATE(TRUNK_CONN_INACTIVE_DRAINING, inactive_draining);
4777
4779
4780 return count;
4781}
4782
4783/** Update timestamps for when we last had a transition from above target to below target or vice versa
4784 *
4785 * Should be called on every time a connection or request is allocated or freed.
4786 *
4787 * @param[out] conn_count_out How many connections we considered.
4788 * @param[out] req_count_out How many requests we considered.
4789 * @param[in] trunk to operate on.
4790 * @param[in] now The current time.
4791 * @param[in] verify if true (and this is a debug build), then assert if req_per_conn
4792 * has changed.
4793 * @return
4794 * - 0 if the average couldn't be calculated (no requests or no connections).
4795 * - The average number of requests per connection.
4796 */
4797static uint64_t trunk_requests_per_connection(uint16_t *conn_count_out, uint32_t *req_count_out,
4798 trunk_t *trunk, fr_time_t now,
4799 NDEBUG_UNUSED bool verify)
4800{
4801 uint32_t req_count = 0;
4802 uint16_t conn_count = 0;
4803 uint64_t req_per_conn = 0;
4804
4806
4807 /*
4808 * Recompute the trunk's aggregate state (and fire any state
4809 * watchers) now that a connection's state may have changed.
4810 * This is the authoritative, prompt trigger for the trunk
4811 * entering / leaving states such as ACTIVE, FULL and FAILED.
4812 * trunk_state_update() no-ops if the trunk is being freed.
4813 */
4814 trunk_state_update(trunk);
4815
4816 /*
4817 * No need to update these as the trunk is being freed
4818 */
4819 if (trunk->freeing) goto done;
4820
4821 /*
4822 * Count all connections except draining and draining to free.
4823 *
4824 * Omitting these connection states artificially raises the
4825 * request to connection ratio, so that we can preemptively spawn
4826 * new connections.
4827 *
4828 * In the case of TRUNK_CONN_DRAINING | TRUNK_CONN_INACTIVE_DRAINING
4829 * the trunk management code has enough hysteresis to not
4830 * immediately reactivate the connection.
4831 *
4832 * In the case of TRUNK_CONN_DRAINING_TO_FREE the trunk
4833 * management code should spawn a new connection to takes its place.
4834 *
4835 * Connections placed in the DRAINING_TO_FREE state are being
4836 * closed preemptively to deal with bugs on the server we're
4837 * talking to, or misconfigured firewalls which are trashing
4838 * TCP/UDP connection states.
4839 */
4844
4845 /*
4846 * Requests on all connections
4847 */
4848 req_count = (uint32_t) trunk_request_count_by_state(trunk,
4851
4852 /*
4853 * No connections, but we do have requests
4854 */
4855 if (conn_count == 0) {
4856 if ((req_count > 0) && (trunk->conf.target_req_per_conn > 0)) goto above_target;
4857 goto done;
4858 }
4859
4860 if (req_count == 0) {
4861 if (trunk->conf.target_req_per_conn > 0) goto below_target;
4862 goto done;
4863 }
4864
4865 /*
4866 * Calculate the req_per_conn
4867 */
4868 req_per_conn = ROUND_UP_DIV(req_count, conn_count);
4869 if (req_per_conn > trunk->conf.target_req_per_conn) {
4870 above_target:
4871 /*
4872 * Edge - Below target to above target (too many requests per conn - spawn more)
4873 *
4874 * The equality check is correct here as both values start at 0.
4875 */
4877 } else if (req_per_conn < trunk->conf.target_req_per_conn) {
4878 below_target:
4879 /*
4880 * Edge - Above target to below target (too few requests per conn - close some)
4881 *
4882 * The equality check is correct here as both values start at 0.
4883 */
4885 }
4886
4887done:
4888 if (conn_count_out) *conn_count_out = conn_count;
4889 if (req_count_out) *req_count_out = req_count;
4890
4891 /*
4892 * Check we haven't missed a call to trunk_requests_per_connection
4893 */
4894 fr_assert(!verify || (trunk->last_req_per_conn == 0) || (req_per_conn == trunk->last_req_per_conn));
4895
4896 trunk->last_req_per_conn = req_per_conn;
4897
4898 return req_per_conn;
4899}
4900
4901/** Drain the backlog of as many requests as possible
4902 *
4903 * @param[in] trunk To drain backlog requests for.
4904 */
4905static void trunk_backlog_drain(trunk_t *trunk)
4906{
4907 trunk_request_t *treq;
4908
4909 if (fr_heap_num_elements(trunk->backlog) == 0) return;
4910
4911 /*
4912 * If it's always writable, this isn't
4913 * really a noteworthy event.
4914 */
4915 if (!trunk->conf.always_writable) DEBUG3("Draining backlog of requests");
4916
4917 /*
4918 * Do *NOT* add an artificial limit
4919 * here. We rely on all available
4920 * connections entering the full
4921 * state and transitioning back to
4922 * active in order to drain the
4923 * backlog.
4924 */
4925 while ((treq = fr_heap_peek(trunk->backlog))) {
4926 switch (trunk_request_enqueue_existing(treq)) {
4927 case TRUNK_ENQUEUE_OK:
4928 continue;
4929
4930 /*
4931 * Signal to stop
4932 */
4934 break;
4935
4936 /*
4937 * Failed enqueueing the request,
4938 * have it enter the failed state
4939 * which will free it and
4940 * re-enliven the yielded request.
4941 */
4943 case TRUNK_ENQUEUE_FAIL:
4945 continue;
4946
4949 return;
4950 }
4951 }
4952}
4953
4954/** Force the trunk to re-establish its connections
4955 *
4956 * @param[in] trunk to signal.
4957 * @param[in] states One or more states or'd together.
4958 * @param[in] reason Why the connections are being signalled to reconnect.
4959 */
4960void trunk_reconnect(trunk_t *trunk, int states, connection_reason_t reason)
4961{
4962
4963#define RECONNECT_BY_STATE(_state, _list) \
4964do { \
4965 if (states & (_state)) { \
4966 size_t i; \
4967 for (i = fr_dlist_num_elements(&trunk->_list); i > 0; i--) { \
4968 connection_signal_reconnect(((trunk_connection_t *)fr_dlist_tail(&trunk->_list))->pub.conn, reason); \
4969 } \
4970 } \
4971} while (0)
4972
4973 /*
4974 * Connections in the 'connecting' state
4975 * may re-enter that state, so we need to
4976 * be careful not to enter an infinite
4977 * loop, as we iterate over the list
4978 * again and again.
4979 */
4981
4982 if (states & TRUNK_CONN_ACTIVE) {
4983 trunk_connection_t *tconn;
4984 while ((tconn = fr_minmax_heap_min_peek(trunk->active))) connection_signal_reconnect(tconn->pub.conn, reason);
4985 }
4986
4994}
4995
4996/** Start the trunk running
4997 *
4998 */
5000{
5001 uint16_t i;
5002
5003 if (unlikely(trunk->started)) return 0;
5004
5005 /*
5006 * Spawn the initial set of connections
5007 */
5008 for (i = 0; i < trunk->conf.start; i++) {
5009 DEBUG("[%i] Starting initial connection", i);
5010 if (trunk_connection_spawn(trunk, fr_time()) != 0) return -1;
5011 }
5012
5013 /*
5014 * If the idle timeout is set, AND there's no management interval, OR the management interval is
5015 * less than the idle timeout, update the management interval.
5016 */
5020 trunk->conf.manage_interval = trunk->conf.idle_timeout;
5021 }
5022
5024 /*
5025 * Insert the event timer to manage
5026 * the interval between managing connections.
5027 */
5028 if (fr_timer_in(trunk, trunk->el->tl, &trunk->manage_ev, trunk->conf.manage_interval,
5029 false, _trunk_timer, trunk) < 0) {
5030 PERROR("Failed inserting trunk management event");
5031 return -1;
5032 }
5033 }
5034 trunk->started = true;
5035 trunk->managing_connections = true;
5036
5037 return 0;
5038}
5039
5040/** Allow the trunk to open and close connections in response to load
5041 *
5042 */
5044{
5045 if (!trunk->started || trunk->managing_connections) return;
5046
5047 DEBUG3("Connection management enabled");
5048 trunk->managing_connections = true;
5049}
5050
5051/** Stop the trunk from opening and closing connections in response to load
5052 *
5053 */
5055{
5056 if (!trunk->started || !trunk->managing_connections) return;
5057
5058 DEBUG3("Connection management disabled");
5059 trunk->managing_connections = false;
5060}
5061
5062/** Schedule a trunk management event for the next time the event loop is executed
5063 */
5065{
5066 if (!trunk->started || !trunk->managing_connections) return 0;
5067
5068 if (fr_timer_in(trunk, trunk->el->tl, &trunk->manage_ev, fr_time_delta_wrap(0),
5069 false, _trunk_timer, trunk) < 0) {
5070 PERROR("Failed inserting trunk management event");
5071 return -1;
5072 }
5073
5074 return 0;
5075}
5076
5077/** Order connections by queue depth
5078 *
5079 * `trunk_alloc()` uses this function when `conf->sort` is `TRUNK_SORT_QUEUE` and the application
5080 * does not set `connection_prioritise`. The function is also the tie-break of the MRU ordering.
5081 *
5082 * @param[in] one first connection.
5083 * @param[in] two second connection.
5084 * @return
5085 * - <0 if `one` has at least two fewer requests than `two`.
5086 * - 0 if the request counts of `one` and `two` differ by one or less.
5087 * - >0 if `one` has at least two more requests than `two`.
5088 */
5089static fr_cmp_ret_t _trunk_connection_order_by_shortest_queue(void const *one, void const *two)
5090{
5093
5096
5097 /*
5098 * Add a fudge factor of 1 to reduce spurious rebalancing
5099 */
5100 return (fr_cmp_ret_t)(((a_count > b_count) && ((a_count - b_count) > 1)) - ((b_count > a_count) && ((b_count - a_count) > 1)));
5101}
5102
5103/** Order connections by the time of the last successful reply (MRU), and then by queue depth
5104 *
5105 * A connection which is replying will be preferred to a connection which has replies farther in the past.
5106 *
5107 * Replies which are less than `time_window` apart are treated as equal. An exact comparison would send every
5108 * new request to the connection which had the most recent reply. Treating replies which are less than
5109 * `time_window` apart as equal balances the load between the connections which reply.
5110 *
5111 * If the two connections have replied recently, then sort by queue depth.
5112 *
5113 * @param[in] one first connection.
5114 * @param[in] two second connection.
5115 * @return
5116 * - <0 if `one` sorts before `two`.
5117 * - 0 if `one` and `two` sort equally.
5118 * - >0 if `one` sorts after `two`.
5119 */
5120static fr_cmp_ret_t _trunk_connection_order_by_last_reply(void const *one, void const *two)
5121{
5124 fr_time_delta_t time_window = a->pub.trunk->conf.time_window;
5125 fr_cmp_ret_t ret;
5126
5127 /*
5128 * Pass `b` before `a`, to prefer the larger time (the more recent reply).
5129 */
5131 if (ret != 0) {
5132 fr_time_delta_t delta;
5133
5134 delta = (ret > 0) ? fr_time_sub(b->pub.last_read_success, a->pub.last_read_success) :
5136
5137 /*
5138 * Replies which are more than `time_window` apart are sorted by last_read_success.
5139 */
5140 if (fr_time_delta_cmp(delta, time_window) > 0) return ret;
5141 }
5142
5143 /*
5144 * Otherwise sort the connections by queue depth.
5145 */
5147}
5148
5149/** Order connections by the number of requests waiting to be written, and then by the time of the last write
5150 *
5151 * The comparisons, in this order:
5152 *
5153 * 1. Choose a connection with fewer requests in the `pending` and `partial` states. The trunk assigns a
5154 * request to a connection before the application writes the request. The trunk sets `last_write_success`
5155 * only when the application writes the request. Without comparison 1, every request in a burst would
5156 * select the connection with the oldest `last_write_success`. A connection which is not writable would
5157 * also keep the oldest time, and would be sent every new request.
5158 *
5159 * 2. Choose a connection with the older `last_write_success`. A new connection has `last_write_success` set
5160 * to when the connection became writable. Connections which are less than `time_window` apart go to 3.
5161 *
5162 * 3. Choose the connection by shortest queue.
5163 *
5164 * @param[in] one first connection.
5165 * @param[in] two second connection.
5166 * @return
5167 * - <0 if `one` sorts before `two`.
5168 * - 0 if `one` and `two` sort equally.
5169 * - >0 if `one` sorts after `two`.
5170 */
5171static fr_cmp_ret_t _trunk_connection_order_by_last_write(void const *one, void const *two)
5172{
5175 fr_time_delta_t time_window = a->pub.trunk->conf.time_window;
5176 uint32_t a_waiting, b_waiting;
5177 fr_cmp_ret_t ret;
5178
5181
5182 /*
5183 * A connection with fewer requests in the `pending` and `partial` states sorts first.
5184 */
5185 ret = CMP(a_waiting, b_waiting);
5186 if (ret != 0) return ret;
5187
5188 /*
5189 * Choose the connection with the older `last_write_success`.
5190 */
5192 if (ret != 0) {
5193 fr_time_delta_t delta;
5194
5195 delta = (ret > 0) ? fr_time_sub(a->pub.last_write_success, b->pub.last_write_success) :
5197
5198 /*
5199 * Requests which are more than `time_window` apart are sorted by last_write_success.
5200 */
5201 if (fr_time_delta_cmp(delta, time_window) > 0) return ret;
5202 }
5203
5204 /*
5205 * Otherwise sort the connections by queue depth.
5206 */
5208}
5209
5210/** Free a trunk, gracefully closing all connections.
5211 *
5212 */
5213static int _trunk_free(trunk_t *trunk)
5214{
5215 trunk_connection_t *tconn;
5216 trunk_request_t *treq;
5217 trunk_watch_entry_t *watch;
5218 size_t i;
5219
5220 DEBUG4("Trunk free %p", trunk);
5221
5222 trunk->freeing = true; /* Prevent re-enqueuing */
5223
5224 /*
5225 * We really don't want this firing after
5226 * we've freed everything.
5227 */
5229
5230 /*
5231 * Now free the connections in each of the lists.
5232 *
5233 * Each time a connection is freed it removes itself from the list
5234 * its in, which means the head should keep advancing automatically.
5235 */
5236 while ((tconn = fr_minmax_heap_min_peek(trunk->active))) connection_signal_halt(tconn->pub.conn);
5237 while ((tconn = fr_dlist_head(&trunk->init))) connection_signal_halt(tconn->pub.conn);
5238 while ((tconn = fr_dlist_head(&trunk->connecting))) connection_signal_halt(tconn->pub.conn);
5239 while ((tconn = fr_dlist_head(&trunk->full))) connection_signal_halt(tconn->pub.conn);
5240 while ((tconn = fr_dlist_head(&trunk->inactive))) connection_signal_halt(tconn->pub.conn);
5241 while ((tconn = fr_dlist_head(&trunk->inactive_draining))) connection_signal_halt(tconn->pub.conn);
5242 while ((tconn = fr_dlist_head(&trunk->closed))) connection_signal_halt(tconn->pub.conn);
5243 while ((tconn = fr_dlist_head(&trunk->draining))) connection_signal_halt(tconn->pub.conn);
5244 while ((tconn = fr_dlist_head(&trunk->draining_to_free))) connection_signal_halt(tconn->pub.conn);
5245
5246 /*
5247 * Process any deferred connection frees
5248 */
5250
5251 /*
5252 * Free any requests left in the backlog
5253 */
5254 while ((treq = fr_heap_peek(trunk->backlog))) trunk_request_enter_failed(treq);
5255
5256 /*
5257 * Free any requests in our request cache
5258 */
5259 while ((treq = trunk_list_free_requests_peek(trunk))) talloc_free(treq);
5260
5261 /*
5262 * Free any entries in the watch lists
5263 */
5264 for (i = 0; i < NUM_ELEMENTS(trunk->watch); i++) {
5265 while ((watch = fr_dlist_pop_head(&trunk->watch[i]))) talloc_free(watch);
5266 }
5267
5268 return 0;
5269}
5270
5271/** Allocate a new collection of connections
5272 *
5273 * This function should be called first to allocate a new trunk connection.
5274 *
5275 * After the trunk has been allocated, #trunk_request_alloc and
5276 * #trunk_request_enqueue should be used to allocate memory for trunk
5277 * requests, and pass a preq (protocol request) to the trunk for
5278 * processing.
5279 *
5280 * The trunk will then asynchronously process the request, writing the result
5281 * to a specified rctx. See #trunk_request_enqueue for more details.
5282 *
5283 * @note Trunks may not be shared between multiple threads under any circumstances.
5284 *
5285 * @param[in] ctx To use for any memory allocations. Must be thread local.
5286 * @param[in] el to use for I/O and timer events.
5287 * @param[in] funcs Callback functions.
5288 * @param[in] conf Common user configurable parameters.
5289 * @param[in] log_prefix To prepend to global messages.
5290 * @param[in] uctx User data to pass to the alloc function.
5291 * @param[in] delay_start If true, then we will not spawn any connections
5292 * until the first request is enqueued.
5293 * @param[in] trigger_args Pairs to pass to trigger requests, if triggers are enabled.
5294 * @return
5295 * - New trunk handle on success.
5296 * - NULL on error.
5297 */
5299 trunk_io_funcs_t const *funcs, trunk_conf_t const *conf,
5300 char const *log_prefix, void const *uctx, bool delay_start, fr_pair_list_t *trigger_args)
5301{
5302 trunk_t *trunk;
5303 size_t i;
5304
5305 /*
5306 * Check we have the functions we need
5307 */
5308 if (!fr_cond_assert(funcs->connection_alloc)) return NULL;
5309
5310 MEM(trunk = talloc_zero(ctx, trunk_t));
5311 trunk->el = el;
5312 trunk->log_prefix = talloc_strdup(trunk, log_prefix);
5313 trunk->trigger_args = trigger_args;
5314
5315 memcpy(&trunk->funcs, funcs, sizeof(trunk->funcs));
5316 if (!trunk->funcs.connection_prioritise) {
5317 switch (conf->sort) {
5318 case TRUNK_SORT_QUEUE:
5319 default:
5321 break;
5322
5323 case TRUNK_SORT_MRU:
5325 break;
5326
5327 case TRUNK_SORT_LRU:
5329 break;
5330 }
5331 }
5333
5334 memcpy(&trunk->conf, conf, sizeof(trunk->conf));
5335
5336 memcpy(&trunk->uctx, &uctx, sizeof(trunk->uctx));
5337 talloc_set_destructor(trunk, _trunk_free);
5338
5339 /*
5340 * Free request list...
5341 */
5343
5344 /*
5345 * Request backlog queue
5346 */
5348 trunk_request_t, heap_id, 0));
5349
5350 /*
5351 * Connection queues and trees
5352 */
5354 trunk_connection_t, heap_id, 0));
5364
5365 /*
5366 * Watch lists
5367 */
5368 for (i = 0; i < NUM_ELEMENTS(trunk->watch); i++) {
5370 }
5371
5372 DEBUG4("Trunk allocated %p", trunk);
5373
5374 if (!delay_start) {
5375 if (trunk_start(trunk) < 0) {
5376 talloc_free(trunk);
5377 return NULL;
5378 }
5379 }
5380
5381 return trunk;
5382}
5383
5384/** Check for a module trigger section when parsing the `triggers` option.
5385 *
5386 */
5387int trunk_trigger_cf_parse(TALLOC_CTX *ctx, void *out, void *parent, CONF_ITEM *ci, conf_parser_t const *rule)
5388{
5391
5392 if (cf_pair_parse_value(ctx, out, parent, ci, rule)< 0) return -1;
5393
5394 /*
5395 * If the parent section of the `triggers` option contains a trigger
5396 * section then store it as the module CONF SECTION for the appropriate
5397 * trigger group.
5398 */
5399 if (cf_section_find(cs, "trigger", NULL)) {
5400 if (strcmp(cf_section_name(cs), "request") == 0) {
5401 conf->req_trigger_cs = cs;
5402 } else {
5403 conf->conn_trigger_cs = cs;
5404 }
5405 }
5406
5407 return 0;
5408}
5409
5410#ifndef TALLOC_GET_TYPE_ABORT_NOOP
5411/** Verify a trunk
5412 *
5413 * A trunk has some number of connections, which each have some number of requests. The connections and
5414 * requests are in differing kinds of containers depending on their state and how they are used, and may
5415 * have fields that can only be validated by comparison with a parent. We had planned on passing a "context"
5416 * down with the ancestral values, but that breaks the foo_verify() API. Each foo_verify() will only verify the
5417 * foo's children.
5418 */
5419void trunk_verify(char const *file, int line, trunk_t *trunk)
5420{
5421 fr_fatal_assert_msg(trunk, "CONSISTENCY CHECK FAILED %s[%i]: trunk_t pointer was NULL", file, line);
5422 (void) talloc_get_type_abort(trunk, trunk_t);
5423
5424 for (size_t i = 0; i < NUM_ELEMENTS(trunk->watch); i++) {
5425 _fr_dlist_verify(file, line, &trunk->watch[i]);
5426 }
5427
5428#define IO_FUNC_VERIFY(_func) \
5429 fr_fatal_assert_msg(trunk->funcs._func, "CONSISTENCY_CHECK_FAILED %s[%i}: " #_func " was NULL", file, line)
5430
5431 /*
5432 * Only a few of the function pointers *must* be non-NULL..
5433 */
5435 IO_FUNC_VERIFY(connection_prioritise);
5437
5438#define TRUNK_TCONN_CHECKS(_tconn, _state) \
5439do { \
5440 fr_fatal_assert_msg(trunk == _tconn->pub.trunk, \
5441 "CONSISTENCY_CHECK_FAILED %s[%i}: connection-trunk mismatch", file, line); \
5442 fr_fatal_assert_msg(_state == _tconn->pub.state, \
5443 "CONSISTENCY_CHECK_FAILED %s[%i}: connection-state mismatch", file, line); \
5444} while (0)
5445
5446#define TCONN_DLIST_VERIFY(_dlist, _state) \
5447do { \
5448 _fr_dlist_verify(file, line, &(trunk->_dlist)); \
5449 fr_dlist_foreach(&(trunk->_dlist), trunk_connection_t, tconn) { \
5450 trunk_connection_verify(file, line, tconn); \
5451 TRUNK_TCONN_CHECKS(tconn, _state); \
5452 } \
5453} while (0)
5454
5455#define TCONN_MINMAX_HEAP_VERIFY(_heap, _state) \
5456do {\
5457 fr_minmax_heap_verify(file, line, trunk->_heap); \
5458 fr_minmax_heap_foreach(trunk->_heap, trunk_connection_t, tconn) { \
5459 trunk_connection_verify(file, line, tconn); \
5460 TRUNK_TCONN_CHECKS(tconn, _state); \
5461 }} \
5462} while (0)
5463
5464 fr_dlist_verify(&(trunk->free_requests));
5465 FR_HEAP_VERIFY(trunk->backlog);
5466
5473 /* TCONN_DLIST_VERIFY(failed, ???); */
5478}
5479
5480void trunk_connection_verify(char const *file, int line, trunk_connection_t *tconn)
5481{
5482 fr_fatal_assert_msg(tconn, "CONSISTENCY CHECK FAILED %s[%i]: trunk_connection_t pointer was NULL", file, line);
5483 (void) talloc_get_type_abort(tconn, trunk_connection_t);
5484
5485 (void) talloc_get_type_abort(tconn->pub.trunk, trunk_t);
5486
5487 /*
5488 * shouldn't be both in heap and on list--but it doesn't look like moves
5489 * to active heap wipe the dlist pointers.
5490 */
5491
5492#define TCONN_TREQ_CHECKS(_treq, _state) \
5493do { \
5494 fr_fatal_assert_msg(tconn == _treq->pub.tconn, \
5495 "CONSISTENCY_CHECK_FAILED %s[%i}: trunk request-tconn mismatch", file, line); \
5496 fr_fatal_assert_msg(tconn->pub.trunk == _treq->pub.trunk, \
5497 "CONSISTENCY_CHECK_FAILED %s[%i}: trunk request-trunk mismatch", file, line); \
5498 fr_fatal_assert_msg(_state == _treq->pub.state, \
5499 "CONSISTENCY_CHECK_FAILED %s[%i}: trunk request-state mismatch", file, line); \
5500} while (0)
5501
5502#define TREQ_DLIST_VERIFY(_dlist, _state) \
5503do { \
5504 _fr_dlist_verify(file, line, &(tconn->_dlist)); \
5505 fr_dlist_foreach(&(tconn->_dlist), trunk_request_t, treq) { \
5506 trunk_request_verify(file, line, treq); \
5507 TCONN_TREQ_CHECKS(treq, _state); \
5508 } \
5509} while (0)
5510
5511#define TREQ_HEAP_VERIFY(_heap, _state) \
5512do { \
5513 fr_heap_iter_t _iter; \
5514 fr_heap_verify(file, line, tconn->_heap); \
5515 for (trunk_request_t *treq = fr_heap_iter_init(tconn->_heap, &_iter); \
5516 treq; \
5517 treq = fr_heap_iter_next(tconn->_heap, &_iter)) { \
5518 trunk_request_verify(file, line, treq); \
5519 TCONN_TREQ_CHECKS(treq, _state); \
5520 } \
5521} while (0)
5522
5523#define TREQ_OPTION_VERIFY(_option, _state) \
5524do { \
5525 if (tconn->_option) { \
5526 trunk_request_verify(file, line, tconn->_option); \
5527 TCONN_TREQ_CHECKS(tconn->_option, _state); \
5528 } \
5529} while (0)
5530
5531 /* verify associated requests */
5538}
5539
5540void trunk_request_verify(char const *file, int line, trunk_request_t *treq)
5541{
5542 fr_fatal_assert_msg(treq, "CONSISTENCY CHECK FAILED %s[%i]: trunk_request_t pointer was NULL", file, line);
5543 (void) talloc_get_type_abort(treq, trunk_request_t);
5544
5545#ifdef WITH_VERIFY_PTR
5546 if (treq->pub.request) request_verify(file, line, treq->pub.request);
5547#endif
5548}
5549
5550
5551bool trunk_search(trunk_t *trunk, void *ptr)
5552{
5553#define TCONN_DLIST_SEARCH(_dlist) \
5554do { \
5555 fr_dlist_foreach(&(trunk->_dlist), trunk_connection_t, tconn) { \
5556 if (ptr == tconn) { \
5557 fr_fprintf(stderr, "trunk_search: tconn %p on " #_dlist "\n", ptr); \
5558 return true; \
5559 } \
5560 if (trunk_connection_search(tconn, ptr)) { \
5561 fr_fprintf(stderr, " in tconn %p on " #_dlist "\n", tconn); \
5562 return true; \
5563 } \
5564 } \
5565} while (0)
5566
5567#define TCONN_MINMAX_HEAP_SEARCH(_heap) \
5568do { \
5569 fr_minmax_heap_foreach(trunk->_heap, trunk_connection_t, tconn) { \
5570 if (ptr == tconn) { \
5571 fr_fprintf(stderr, "trunk_search: tconn %p on " #_heap "\n", ptr); \
5572 return true; \
5573 } \
5574 if (trunk_connection_search(tconn, ptr)) { \
5575 fr_fprintf(stderr, " on tconn %p on " #_heap "\n", tconn); \
5576 return true; \
5577 } \
5578 }}\
5579} while (0)
5580
5582 TCONN_DLIST_SEARCH(connecting);
5584 TCONN_DLIST_SEARCH(full);
5585 TCONN_DLIST_SEARCH(inactive);
5586 TCONN_DLIST_SEARCH(inactive_draining);
5587 TCONN_DLIST_SEARCH(failed);
5588 TCONN_DLIST_SEARCH(closed);
5589 TCONN_DLIST_SEARCH(draining);
5590 TCONN_DLIST_SEARCH(draining_to_free);
5591 TCONN_DLIST_SEARCH(to_free);
5592
5593 return false;
5594}
5595
5597{
5598#define TREQ_DLIST_SEARCH(_dlist) \
5599do { \
5600 fr_dlist_foreach(&(tconn->_dlist), trunk_request_t, treq) { \
5601 if (ptr == treq) { \
5602 fr_fprintf(stderr, "trunk_search: treq %p on " #_dlist "\n", ptr); \
5603 return true; \
5604 } \
5605 if (trunk_request_search(treq, ptr)) { \
5606 fr_fprintf(stderr, "trunk_search: preq %p found on " #_dlist, ptr); \
5607 return true; \
5608 } \
5609 } \
5610} while (0)
5611
5612#define TREQ_HEAP_SEARCH(_heap) \
5613do { \
5614 fr_heap_iter_t _iter; \
5615 for (trunk_request_t *treq = fr_heap_iter_init(tconn->_heap, &_iter); \
5616 treq; \
5617 treq = fr_heap_iter_next(tconn->_heap, &_iter)) { \
5618 if (ptr == treq) { \
5619 fr_fprintf(stderr, "trunk_search: treq %p in " #_heap "\n", ptr); \
5620 return true; \
5621 } \
5622 if (trunk_request_search(treq, ptr)) { \
5623 fr_fprintf(stderr, "trunk_search: preq %p found in " #_heap, ptr); \
5624 return true; \
5625 } \
5626 } \
5627} while (0)
5628
5629#define TREQ_OPTION_SEARCH(_option) \
5630do { \
5631 if (tconn->_option) { \
5632 if (ptr == tconn->_option) { \
5633 fr_fprintf(stderr, "trunk_search: treq %p is " #_option "\n", ptr); \
5634 return true; \
5635 } \
5636 if (trunk_request_search(tconn->_option, ptr)) { \
5637 fr_fprintf(stderr, "trunk_search: preq %p found in " #_option, ptr); \
5638 return true; \
5639 } \
5640 } \
5641} while (0)
5642
5643 /* search associated requests */
5644 TREQ_HEAP_SEARCH(pending);
5645 TREQ_DLIST_SEARCH(sent);
5646 TREQ_DLIST_SEARCH(cancel);
5647 TREQ_DLIST_SEARCH(cancel_sent);
5648 TREQ_OPTION_SEARCH(partial);
5649 TREQ_OPTION_SEARCH(cancel_partial);
5650
5651 return false;
5652}
5653
5655{
5656 return treq->pub.preq == ptr;
5657}
5658#endif
int const char * file
Definition acutest.h:855
void int line
Definition acutest.h:810
void request_verify(UNUSED char const *file, UNUSED int line, UNUSED request_t *request)
static uint8_t request[4]
#define L(_str)
Helper for initialising arrays of string literals.
Definition build.h:245
#define NDEBUG_UNUSED
Definition build.h:426
#define FALL_THROUGH
clang 10 doesn't recognised the FALL-THROUGH comment anymore
Definition build.h:422
#define DIAG_ON(_x)
Definition build.h:576
#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:130
#define unlikely(_x)
Definition build.h:486
#define UNUSED
Definition build.h:415
#define NUM_ELEMENTS(_t)
Definition build.h:437
#define DIAG_OFF(_x)
Definition build.h:575
fr_cmp_ret_t
Result of an ordering comparison.
Definition build.h:113
int cf_pair_parse_value(TALLOC_CTX *ctx, void *out, UNUSED void *base, CONF_ITEM *ci, conf_parser_t const *rule)
Parses a CONF_PAIR into a C data type.
Definition cf_parse.c:252
cf_time_delta_bounds_t const cf_time_delta_bounds_int_msec
Bounds which keep a time delta within an int of milliseconds, for libraries which take one.
Definition cf_parse.c:1927
int cf_parse_time_delta_bounded(TALLOC_CTX *ctx, void *out, void *parent, CONF_ITEM *ci, conf_parser_t const *rule)
Parse a time delta, and force it within the bounds passed as the rule's uctx.
Definition cf_parse.c:1951
#define CONF_PARSER_TERMINATOR
Definition cf_parse.h:722
cf_parse_t func
Override default parsing behaviour for the specified type with a custom parsing function.
Definition cf_parse.h:666
#define FR_CONF_OFFSET(_name, _struct, _field)
conf_parser_t which parses a single CONF_PAIR, writing the result to a field in a struct
Definition cf_parse.h:280
@ CONF_FLAG_SUBSECTION
Instead of putting the information into a configuration structure, the configuration file routines MA...
Definition cf_parse.h:460
int cf_table_parse_uint8(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent, CONF_ITEM *ci, conf_parser_t const *rule)
#define FR_CONF_POINTER(_name, _type, _flags, _res_p)
conf_parser_t which parses a single CONF_PAIR producing a single global result
Definition cf_parse.h:350
#define FR_CONF_OFFSET_SUBSECTION(_name, _flags, _struct, _field, _subcs)
conf_parser_t which populates a sub-struct using a CONF_SECTION
Definition cf_parse.h:309
#define FR_CONF_OFFSET_TYPE_FLAGS(_name, _type, _flags, _struct, _field)
conf_parser_t which parses a single CONF_PAIR, writing the result to a field in a struct
Definition cf_parse.h:238
Defines a CONF_PAIR to C data type mapping.
Definition cf_parse.h:649
Common header for all CONF_* types.
Definition cf_priv.h:54
Configuration AVP similar to a fr_pair_t.
Definition cf_priv.h:77
A section grouping multiple CONF_PAIR.
Definition cf_priv.h:106
CONF_SECTION * cf_section_find(CONF_SECTION const *cs, char const *name1, char const *name2)
Find a CONF_SECTION with name1 and optionally name2.
Definition cf_util.c:1247
CONF_SECTION * cf_item_to_section(CONF_ITEM const *ci)
Cast a CONF_ITEM to a CONF_SECTION.
Definition cf_util.c:671
char const * cf_section_name(CONF_SECTION const *cs)
Return name2 if set, else name1.
Definition cf_util.c:1417
#define cf_parent(_cf)
Definition cf_util.h:115
static size_t min(size_t x, size_t y)
Definition dbuff.c:66
#define fr_cond_assert(_x)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:177
#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:248
#define fr_cond_assert_msg(_x, _fmt,...)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:194
#define fr_fatal_assert_msg(_x, _fmt,...)
Calls panic_action ifndef NDEBUG, else logs error and causes the server to exit immediately with code...
Definition debug.h:222
#define MEM(x)
Definition debug.h:38
#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 void * fr_dlist_remove(fr_dlist_head_t *list_head, void *ptr)
Remove an item from the list.
Definition dlist.h:620
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_talloc_free(fr_dlist_head_t *head)
Free all items in a doubly linked list (with talloc)
Definition dlist.h:892
static void _fr_dlist_verify(NDEBUG_UNUSED char const *file, NDEBUG_UNUSED int line, fr_dlist_head_t const *list_head)
Check all items in the list are valid.
Definition dlist.h:717
static void * fr_dlist_prev(fr_dlist_head_t const *list_head, void const *ptr)
Get the previous item in a list.
Definition dlist.h:570
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 void * fr_dlist_tail(fr_dlist_head_t const *list_head)
Return the TAIL item of a list or NULL if the list is empty.
Definition dlist.h:513
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
#define fr_dlist_verify(_head)
Definition dlist.h:737
#define fr_dlist_talloc_init(_head, _type, _field)
Initialise the head structure of a doubly linked list.
Definition dlist.h:257
static int fr_dlist_insert_head(fr_dlist_head_t *list_head, void *ptr)
Insert an item into the head of a list.
Definition dlist.h:320
static void * fr_dlist_next(fr_dlist_head_t const *list_head, void const *ptr)
Get the next item in a list.
Definition dlist.h:537
Head of a doubly linked list.
Definition dlist.h:51
Entry in a doubly linked list.
Definition dlist.h:41
int fr_heap_insert(fr_heap_t **hp, void *data)
Insert a new element into the heap.
Definition heap.c:149
unsigned int fr_heap_index_t
Definition heap.h:82
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
#define FR_HEAP_VERIFY(_heap)
Definition heap.h:214
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)
#define PERROR(_fmt,...)
Definition log.h:233
#define DEBUG3(_fmt,...)
Definition log.h:271
#define ROPTIONAL(_l_request, _l_global, _fmt,...)
Use different logging functions depending on whether request is NULL or not.
Definition log.h:545
#define RDEBUG3(fmt,...)
Definition log.h:360
#define RWARN(fmt,...)
Definition log.h:314
#define DEBUG4(_fmt,...)
Definition log.h:272
#define RATE_LIMIT_LOCAL_ROPTIONAL(_entry, _l_request, _l_global, _fmt,...)
Rate limit messages using a local limiting entry.
Definition log.h:624
Track when a log message was last repeated.
Definition log.h:564
#define fr_time()
Definition event.c:58
Stores all information relating to an event list.
Definition event.c:375
#define fr_log(_log, _lvl, _file, _line, _fmt,...)
Definition log.h:172
fr_log_type_t
Definition log.h:51
#define ROUND_UP_DIV(_x, _y)
Get the ceiling value of integer division.
Definition math.h:214
unsigned short uint16_t
@ FR_TYPE_VOID
User data.
unsigned int uint32_t
int fr_minmax_heap_insert(fr_minmax_heap_t *hp, void *data)
void * fr_minmax_heap_iter_next(fr_minmax_heap_t *hp, fr_minmax_heap_iter_t *iter)
Get the next entry in a minmax heap.
void * fr_minmax_heap_min_peek(fr_minmax_heap_t *hp)
unsigned int fr_minmax_heap_num_elements(fr_minmax_heap_t *hp)
Return the number of elements in the minmax heap.
void * fr_minmax_heap_iter_init(fr_minmax_heap_t *hp, fr_minmax_heap_iter_t *iter)
Iterate over entries in a minmax heap.
int fr_minmax_heap_extract(fr_minmax_heap_t *hp, void *data)
int fr_minmax_heap_max_peek(void **out, fr_minmax_heap_t *hp)
unsigned int fr_minmax_heap_iter_t
Definition minmax_heap.h:39
#define fr_minmax_heap_talloc_alloc(_ctx, _cmp, _talloc_type, _field, _init)
Creates a minmax heap that verifies elements are of a specific talloc type.
Definition minmax_heap.h:87
fr_cmp_ret_t fr_pointer_cmp(void const *a, void const *b)
Compares two pointers.
Definition misc.c:449
static fr_cmp_ret_t request_prioritise(void const *one, void const *two)
Definition bio.c:1806
#define fr_assert(_expr)
Definition rad_assert.h:37
#define RDEBUG(fmt,...)
#define DEBUG2(fmt,...)
#define WARN(fmt,...)
static bool done
Definition radclient.c:80
#define INFO(fmt,...)
Definition radict.c:67
static fr_event_list_t * events
Definition radsniff.c:58
static rs_t * conf
Definition radsniff.c:52
void connection_signal_shutdown(connection_t *conn)
Shuts down a connection gracefully.
int connection_del_watch_post(connection_t *conn, connection_state_t state, connection_watch_t watch)
Remove a watch function from a post list.
Definition connection.c:457
void connection_signal_halt(connection_t *conn)
Shuts down a connection ungracefully.
void connection_signals_resume(connection_t *conn)
Resume processing of deferred signals.
Definition connection.c:304
void connection_signal_reconnect(connection_t *conn, connection_reason_t reason)
Asynchronously signal the connection should be reconnected.
void connection_signal_init(connection_t *conn)
Asynchronously signal a halted connection to start.
connection_t * connection_alloc(TALLOC_CTX *ctx, fr_event_list_t *el, connection_funcs_t const *funcs, connection_conf_t const *conf, char const *log_prefix, void const *uctx)
Allocate a new connection.
connection_watch_entry_t * connection_add_watch_pre(connection_t *conn, connection_state_t state, connection_watch_t watch, bool oneshot, void const *uctx)
Add a callback to be executed before a state function has been called.
Definition connection.c:495
connection_watch_entry_t * connection_add_watch_post(connection_t *conn, connection_state_t state, connection_watch_t watch, bool oneshot, void const *uctx)
Add a callback to be executed after a state function has been called.
Definition connection.c:517
int connection_del_watch_pre(connection_t *conn, connection_state_t state, connection_watch_t watch)
Remove a watch function from a pre list.
Definition connection.c:440
void connection_signals_pause(connection_t *conn)
Pause processing of deferred signals.
Definition connection.c:295
connection_reason_t
Definition connection.h:88
connection_state_t
Definition connection.h:47
@ CONNECTION_STATE_FAILED
Connection has failed.
Definition connection.h:56
@ CONNECTION_STATE_HALTED
The connection is in a halted stat.
Definition connection.h:48
@ CONNECTION_STATE_CLOSED
Connection has been closed.
Definition connection.h:57
@ CONNECTION_STATE_CONNECTED
File descriptor is open (ready for writing).
Definition connection.h:54
@ CONNECTION_STATE_INIT
Init state, sets up connection.
Definition connection.h:51
@ CONNECTION_STATE_CONNECTING
Waiting for connection to establish.
Definition connection.h:52
@ CONNECTION_STATE_SHUTDOWN
Connection is shutting down.
Definition connection.h:55
static fr_time_t test_time(void)
Definition slab_tests.c:43
static fr_time_t test_time_base
Definition slab_tests.c:42
return count
Definition module.c:155
init
Enter the EAP-IDENTITY state.
@ memory_order_relaxed
Definition stdatomic.h:127
#define atomic_fetch_add_explicit(object, operand, order)
Definition stdatomic.h:302
#define ATOMIC_VAR_INIT(value)
Definition stdatomic.h:88
Definition log.h:93
#define fr_table_str_by_value(_table, _number, _def)
Convert an integer to a string.
Definition table.h:804
An element in a table indexed by bit position.
Definition table.h:83
An element in an arbitrarily ordered array of name to num mappings.
Definition table.h:57
An element in a lexicographically sorted array of name to num mappings.
Definition table.h:49
#define talloc_get_type_abort_const
Definition talloc.h:117
#define talloc_pooled_object(_ctx, _type, _num_subobjects, _total_subobjects_size)
Definition talloc.h:212
#define talloc_strdup(_ctx, _str)
Definition talloc.h:149
#define fr_time_gteq(_a, _b)
Definition time.h:238
#define fr_time_delta_wrap(_time)
Definition time.h:152
#define fr_time_wrap(_time)
Definition time.h:145
#define fr_time_lteq(_a, _b)
Definition time.h:240
#define fr_time_delta_ispos(_a)
Definition time.h:290
#define fr_time_eq(_a, _b)
Definition time.h:241
static fr_cmp_ret_t fr_time_cmp(fr_time_t a, fr_time_t b)
Compare two fr_time_t values.
Definition time.h:934
#define fr_time_add(_a, _b)
Add a time/time delta together.
Definition time.h:196
static fr_cmp_ret_t fr_time_delta_cmp(fr_time_delta_t a, fr_time_delta_t b)
Compare two fr_time_delta_t values.
Definition time.h:948
#define fr_time_gt(_a, _b)
Definition time.h:237
#define fr_time_sub(_a, _b)
Subtract one time from another.
Definition time.h:229
#define fr_time_lt(_a, _b)
Definition time.h:239
#define fr_time_delta_gt(_a, _b)
Definition time.h:283
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
"server local" time.
Definition time.h:69
An event timer list.
Definition timer.c:65
A timer event.
Definition timer.c:100
#define FR_TIMER_DELETE(_ev_p)
Definition timer.h:105
#define FR_TIMER_DELETE_RETURN(_ev_p)
Definition timer.h:112
#define fr_timer_in(...)
Definition timer.h:87
#define FR_TIMER_DISARM(_ev)
Definition timer.h:91
bool trunk_search(trunk_t *trunk, void *ptr)
Definition trunk.c:5551
static atomic_uint_fast64_t request_counter
Definition trunk.c:54
CONF_PAIR * trigger_cp[NUM_ELEMENTS(trunk_conn_trigger_names)]
Cached trigger CONF_PAIRs.
Definition trunk.c:323
static void trunk_connection_enter_active(trunk_connection_t *tconn)
Transition a connection back to the active state.
Definition trunk.c:3390
#define CONN_REORDER(_tconn)
Reorder the connections in the active heap.
Definition trunk.c:815
static size_t trunk_req_trigger_names_len
Definition trunk.c:409
int trunk_connection_pop_cancellation(trunk_request_t **treq_out, trunk_connection_t *tconn)
Pop a cancellation request off a connection's cancellation queue.
Definition trunk.c:3989
fr_dlist_head_t cancel
Requests in the cancel state.
Definition trunk.c:165
int trunk_connection_manage_schedule(trunk_t *trunk)
Schedule a trunk management event for the next time the event loop is executed.
Definition trunk.c:5064
#define REQUEST_EXTRACT_SENT(_treq)
Remove the current request from the sent list.
Definition trunk.c:785
struct trunk_watch_entry_s trunk_watch_entry_t
An entry in a trunk watch function list.
fr_dlist_head_t reapable
Idle request.
Definition trunk.c:163
fr_heap_t * pending
Requests waiting to be sent.
Definition trunk.c:157
trunk_conf_t conf
Trunk common configuration.
Definition trunk.c:228
static size_t trunk_connection_states_len
Definition trunk.c:450
#define REQUEST_EXTRACT_REAPABLE(_treq)
Remove the current request from the reapable list.
Definition trunk.c:790
trunk_connection_t * tconn
The request was associated with.
Definition trunk.c:82
void trunk_connection_callback_readable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
Standard I/O read function.
Definition trunk.c:4168
fr_rate_limit_t limit_last_failure_log
Rate limit on "Refusing to enqueue requests - No active conns".
Definition trunk.c:302
void trunk_verify(char const *file, int line, trunk_t *trunk)
Verify a trunk.
Definition trunk.c:5419
fr_timer_t * manage_ev
Periodic connection management event.
Definition trunk.c:294
#define IN_HANDLER(_trunk)
Definition trunk.c:745
static fr_table_num_ordered_t const trunk_connection_states[]
Definition trunk.c:438
void trunk_reconnect(trunk_t *trunk, int states, connection_reason_t reason)
Force the trunk to re-establish its connections.
Definition trunk.c:4960
void trunk_connection_callback_writable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
Standard I/O write function.
Definition trunk.c:4185
void * uctx
User data to pass to the function.
Definition trunk.c:195
static void trunk_request_enter_pending(trunk_request_t *treq, trunk_connection_t *tconn, bool new)
Transition a request to the pending state, adding it to the backlog of an active connection.
Definition trunk.c:1251
static void trunk_request_remove_from_conn(trunk_request_t *treq)
Remove a request from all connection lists.
Definition trunk.c:1053
fr_rate_limit_t limit_max_requests_alloc_log
Rate limit on "Refusing to alloc requests - Limit of * requests reached".
Definition trunk.c:300
trunk_request_state_t to
What state we transitioned to.
Definition trunk.c:80
static void trunk_manage(trunk_t *trunk, fr_time_t now)
Implements the algorithm we use to manage requests per connection levels.
Definition trunk.c:4401
static int _trunk_connection_free(trunk_connection_t *tconn)
Free a connection.
Definition trunk.c:3834
trunk_io_funcs_t funcs
I/O functions.
Definition trunk.c:280
fr_dlist_head_t draining
Connections that will be freed once all their requests are complete, but can be reactivated.
Definition trunk.c:265
#define REQUEST_EXTRACT_CANCEL_PARTIAL(_treq)
Remove the current request from the cancel_partial slot.
Definition trunk.c:800
int trunk_trigger_cf_parse(TALLOC_CTX *ctx, void *out, void *parent, CONF_ITEM *ci, conf_parser_t const *rule)
Check for a module trigger section when parsing the triggers option.
Definition trunk.c:5387
int trunk_start(trunk_t *trunk)
Start the trunk running.
Definition trunk.c:4999
void trunk_request_signal_partial(trunk_request_t *treq)
Signal a partial write.
Definition trunk.c:2137
void trunk_request_signal_fail(trunk_request_t *treq)
Signal that a trunk request failed.
Definition trunk.c:2240
#define TREQ_OPTION_SEARCH(_option)
static void _trunk_connection_on_shutdown(connection_t *conn, UNUSED connection_state_t prev, UNUSED connection_state_t state, void *uctx)
Connection transitioned to the shutdown state.
Definition trunk.c:3540
void trunk_request_signal_cancel_sent(trunk_request_t *treq)
Signal that a remote server has been notified of the cancellation.
Definition trunk.c:2368
static void trunk_connection_enter_draining_to_free(trunk_connection_t *tconn)
Transition a connection to the draining-to-reconnect state.
Definition trunk.c:3354
trunk_watch_t func
Function to call when a trunk enters the state this list belongs to.
Definition trunk.c:191
void trunk_connection_signal_readable(trunk_connection_t *tconn)
Signal that a trunk connection is readable.
Definition trunk.c:4075
static fr_cmp_ret_t _trunk_connection_order_by_last_reply(void const *one, void const *two)
Order connections by the time of the last successful reply (MRU), and then by queue depth.
Definition trunk.c:5120
#define DO_REQUEST_FREE(_treq)
Call the free callback (if set)
Definition trunk.c:637
trunk_request_t * trunk_request_alloc(trunk_t *trunk, request_t *request)
(Pre-)Allocate a new trunk request
Definition trunk.c:2586
static void _trunk_connection_on_halted(UNUSED connection_t *conn, UNUSED connection_state_t prev, UNUSED connection_state_t state, void *uctx)
Connection transitioned to the halted state.
Definition trunk.c:3786
#define REQUEST_EXTRACT_BACKLOG(_treq)
Remove the current request from the backlog.
Definition trunk.c:756
fr_heap_index_t heap_id
Used to track the connection in the connected heap.
Definition trunk.c:142
fr_dlist_head_t closed
Connections that have closed.
Definition trunk.c:262
fr_dlist_head_t watch[TRUNK_STATE_MAX]
To be called when trunk changes state.
Definition trunk.c:286
static void trunk_watch_call(trunk_t *trunk, fr_dlist_head_t *list, trunk_state_t state)
Call a list of watch functions associated with a state.
Definition trunk.c:879
static void trunk_request_enter_cancel_complete(trunk_request_t *treq)
Cancellation was acked, the request is complete, free it.
Definition trunk.c:1616
int line
Line change occurred on.
Definition trunk.c:92
static void trunk_connection_enter_inactive_draining(trunk_connection_t *tconn)
Transition a connection to the inactive-draining state.
Definition trunk.c:3292
#define CONN_STATE_TRANSITION(_new, _log)
Definition trunk.c:480
static uint64_t trunk_requests_per_connection(uint16_t *conn_count_out, uint32_t *req_conn_out, trunk_t *trunk, fr_time_t now, NDEBUG_UNUSED bool verify)
Update timestamps for when we last had a transition from above target to below target or vice versa.
Definition trunk.c:4797
static size_t trunk_connection_events_len
Definition trunk.c:466
static void _trunk_connection_on_failed(connection_t *conn, connection_state_t prev, connection_state_t state, void *uctx)
Connection failed.
Definition trunk.c:3734
bool oneshot
Remove the function after it's called once.
Definition trunk.c:193
static fr_cmp_ret_t _trunk_connection_order_by_last_write(void const *one, void const *two)
Order connections by the number of requests waiting to be written, and then by the time of the last w...
Definition trunk.c:5171
bool started
Has the trunk been started.
Definition trunk.c:311
static size_t trunk_states_len
Definition trunk.c:436
#define TCONN_DLIST_VERIFY(_dlist, _state)
#define IO_FUNC_VERIFY(_func)
uint32_t trunk_request_count_by_connection(trunk_connection_t const *tconn, int req_state)
Return the count number of requests associated with a trunk connection.
Definition trunk.c:3007
uint64_t last_req_per_conn
The last request to connection ratio we calculated.
Definition trunk.c:316
#define DO_REQUEST_COMPLETE(_treq)
Call the complete callback (if set)
Definition trunk.c:598
static void trunk_connection_auto_full(trunk_connection_t *tconn)
Automatically mark a connection as full.
Definition trunk.c:3026
static void trunk_connection_remove(trunk_connection_t *tconn)
Remove a trunk connection from whichever list it's currently in.
Definition trunk.c:3191
#define TRUNK_REQUEST_STATE_LOG_MAX
The maximum number of state logs to record per request.
Definition trunk.c:71
static void trunk_connection_writable(trunk_connection_t *tconn)
A connection is writable.
Definition trunk.c:3104
#define OVER_MAX_CHECK
trunk_connection_event_t events
The current events we expect to be notified on.
Definition trunk.c:151
trunk_watch_entry_t * trunk_add_watch(trunk_t *trunk, trunk_state_t state, trunk_watch_t watch, bool oneshot, void const *uctx)
Add a watch entry to the trunk state list.
Definition trunk.c:955
static int _trunk_free(trunk_t *trunk)
Free a trunk, gracefully closing all connections.
Definition trunk.c:5213
fr_dlist_head_t failed
Connections that'll be reconnected shortly.
Definition trunk.c:260
static void trunk_rebalance(trunk_t *trunk)
Rebalance connections across active trunk members when a new connection becomes active.
Definition trunk.c:4264
static void trunk_backlog_drain(trunk_t *trunk)
Drain the backlog of as many requests as possible.
Definition trunk.c:4905
#define DO_REQUEST_CANCEL(_treq, _reason)
Call the cancel callback if set.
Definition trunk.c:559
#define FR_TRUNK_LIST_FUNC(_list, _type)
Definition trunk.c:850
struct trunk_request_pub_s pub
Public fields in the trunk request.
Definition trunk.c:100
static fr_table_num_sorted_t const trunk_sort_table[]
Definition trunk.c:345
#define TCONN_MINMAX_HEAP_VERIFY(_heap, _state)
trunk_request_t * cancel_partial
Partially written cancellation request.
Definition trunk.c:167
#define TCONN_MINMAX_HEAP_SEARCH(_heap)
uint64_t trunk_connection_requests_requeue(trunk_connection_t *tconn, int states, uint64_t max, bool fail_bound)
Move requests off of a connection and requeue elsewhere.
Definition trunk.c:2118
bool enabled
Whether the watch entry is enabled.
Definition trunk.c:194
fr_time_t last_freed
Last time this request was freed.
Definition trunk.c:113
#define DO_REQUEST_CONN_RELEASE(_treq)
Call the "conn_release" callback (if set)
Definition trunk.c:580
#define TREQ_DLIST_SEARCH(_dlist)
#define REQUEST_EXTRACT_CANCEL(_treq)
Remove the current request from the cancel list.
Definition trunk.c:795
static bool trunk_connection_is_full(trunk_connection_t *tconn)
Return whether a trunk connection should currently be considered full.
Definition trunk.c:3049
struct trunk_pub_s pub
Public fields in the trunk connection.
Definition trunk.c:220
trunk_cancel_reason_t cancel_reason
Why this request was cancelled.
Definition trunk.c:111
#define REQUEST_BAD_STATE_TRANSITION(_new)
Definition trunk.c:525
trunk_enqueue_t trunk_request_enqueue_on_conn(trunk_request_t **treq_out, trunk_connection_t *tconn, request_t *request, void *preq, void *rctx, bool ignore_limits)
Enqueue additional requests on a specific connection.
Definition trunk.c:2855
static void _trunk_connection_on_closed(UNUSED connection_t *conn, UNUSED connection_state_t prev, UNUSED connection_state_t state, void *uctx)
Connection failed after it was connected.
Definition trunk.c:3663
static fr_table_num_ordered_t const trunk_connection_events[]
Definition trunk.c:460
trunk_enqueue_t trunk_request_enqueue(trunk_request_t **treq_out, trunk_t *trunk, request_t *request, void *preq, void *rctx)
Enqueue a request that needs data written to the trunk.
Definition trunk.c:2701
#define TCONN_DLIST_SEARCH(_dlist)
static void trunk_request_enter_unassigned(trunk_request_t *treq)
Transition a request to the unassigned state, in preparation for re-assignment.
Definition trunk.c:1154
struct trunk_request_s trunk_request_t
Definition trunk.c:33
void * in_handler
Which handler we're inside.
Definition trunk.c:282
bool freeing
Trunk is being freed, don't spawn new connections or re-enqueue.
Definition trunk.c:308
static fr_table_num_ordered_t const trunk_states[]
Definition trunk.c:429
static void trunk_connection_readable(trunk_connection_t *tconn)
A connection is readable.
Definition trunk.c:3080
#define IS_SERVICEABLE(_tconn)
Definition trunk.c:750
trunk_enqueue_t trunk_request_requeue(trunk_request_t *treq)
Re-enqueue a request on the same connection.
Definition trunk.c:2790
#define IS_PROCESSING(_tconn)
Definition trunk.c:751
#define RECONNECT_BY_STATE(_state, _list)
static void trunk_connection_enter_draining(trunk_connection_t *tconn)
Transition a connection to the draining state.
Definition trunk.c:3322
static fr_table_num_indexed_bit_pos_t const trunk_req_trigger_names[]
Map request states to trigger names.
Definition trunk.c:394
fr_dlist_t entry
Used to track the trunk request in the conn->sent or trunk->backlog request.
Definition trunk.c:108
static void trunk_connection_close_if_empty(trunk_t *trunk, fr_dlist_head_t *head)
Close connections in a particular connection list if they have no requests associated with them.
Definition trunk.c:4211
void trunk_request_signal_cancel_complete(trunk_request_t *treq)
Signal that a remote server acked our cancellation.
Definition trunk.c:2392
static trunk_enqueue_t trunk_request_check_enqueue(trunk_connection_t **tconn_out, trunk_t *trunk, request_t *request)
Check to see if a trunk request can be enqueued.
Definition trunk.c:1714
#define DO_REQUEST_MUX(_tconn)
Write one or more requests to a connection.
Definition trunk.c:655
#define REQUEST_EXTRACT_PARTIAL(_treq)
Remove the current request from the partial slot.
Definition trunk.c:776
fr_dlist_head_t sent
Sent request.
Definition trunk.c:161
static void trunk_request_enter_partial(trunk_request_t *treq)
Transition a request to the partial state, indicating that is has been partially sent.
Definition trunk.c:1328
fr_timer_t * lifetime_ev
Maximum time this connection can be open.
Definition trunk.c:182
int trunk_connection_pop_request(trunk_request_t **treq_out, trunk_connection_t *tconn)
Pop a request off a connection's pending queue.
Definition trunk.c:4037
fr_dlist_head_t connecting
Connections which are not yet in the open state.
Definition trunk.c:246
static size_t trunk_sort_table_len
Definition trunk.c:350
#define TRUNK_STATE_TRANSITION(_new)
Definition trunk.c:975
void trunk_request_signal_cancel(trunk_request_t *treq)
Cancel a trunk request.
Definition trunk.c:2260
void trunk_request_state_log_entry_add(char const *function, int line, trunk_request_t *treq, trunk_request_state_t new)
Definition trunk.c:2925
static int trunk_connection_spawn(trunk_t *trunk, fr_time_t now)
Attempt to spawn a new connection.
Definition trunk.c:3902
int trunk_del_watch(trunk_t *trunk, trunk_state_t state, trunk_watch_t watch)
Remove a watch function from a trunk state list.
Definition trunk.c:921
static void trunk_state_update(trunk_t *trunk)
Recalculate the trunk's aggregate state from its connection counts.
Definition trunk.c:4300
static void _trunk_timer(fr_timer_list_t *tl, fr_time_t now, void *uctx)
Event to periodically call the connection management function.
Definition trunk.c:4726
struct trunk_connection_pub_s pub
Public fields in the trunk connection.
Definition trunk.c:138
static void trunk_request_enter_reapable(trunk_request_t *treq)
Transition a request to the reapable state, indicating that it's been sent in its entirety,...
Definition trunk.c:1417
uint16_t trunk_connection_count_by_state(trunk_t *trunk, int conn_state)
Return the count number of connections in the specified states.
Definition trunk.c:2983
#define IN_REQUEST_DEMUX(_trunk)
Definition trunk.c:747
#define DO_REQUEST_FAIL(_treq, _prev_state)
Call the fail callback (if set)
Definition trunk.c:617
static void trunk_request_enter_cancel(trunk_request_t *treq, trunk_cancel_reason_t reason)
Transition a request to the cancel state, placing it in a connection's cancellation list.
Definition trunk.c:1485
static trunk_enqueue_t trunk_request_enqueue_existing(trunk_request_t *treq)
Enqueue a request which has never been assigned to a connection or was previously cancelled.
Definition trunk.c:1788
bool managing_connections
Whether the trunk is allowed to manage (open/close) connections.
Definition trunk.c:313
#define DO_CONNECTION_ALLOC(_tconn)
Allocate a new connection.
Definition trunk.c:706
static fr_cmp_ret_t _trunk_request_prioritise(void const *a, void const *b)
Compare two protocol requests.
Definition trunk.c:1029
char const * function
State change occurred in.
Definition trunk.c:91
static size_t trunk_request_states_len
Definition trunk.c:427
fr_dlist_head_t init
Connections which have not yet started connecting.
Definition trunk.c:243
fr_dlist_head_t * log_head
To allow the log entry to remove itself on free.
Definition trunk.c:77
static void trunk_request_enter_cancel_partial(trunk_request_t *treq)
Transition a request to the cancel_partial state, placing it in a connection's cancel_partial slot.
Definition trunk.c:1536
static void _trunk_connection_on_connected(UNUSED connection_t *conn, UNUSED connection_state_t prev, UNUSED connection_state_t state, void *uctx)
Connection transitioned to the connected state.
Definition trunk.c:3597
trunk_t * trunk_alloc(TALLOC_CTX *ctx, fr_event_list_t *el, trunk_io_funcs_t const *funcs, trunk_conf_t const *conf, char const *log_prefix, void const *uctx, bool delay_start, fr_pair_list_t *trigger_args)
Allocate a new collection of connections.
Definition trunk.c:5298
fr_dlist_head_t to_free
Connections we're done with and will free on the next call to trunk_manage.
Definition trunk.c:271
trunk_request_t * partial
Partially written request.
Definition trunk.c:159
static void trunk_request_enter_failed(trunk_request_t *treq)
Request failed, inform the API client and free the request.
Definition trunk.c:1678
fr_minmax_heap_t * active
Connections which can service requests.
Definition trunk.c:248
conf_parser_t const trunk_config[]
Config parser definitions to populate a trunk_conf_t.
Definition trunk.c:352
static void trunk_request_enter_complete(trunk_request_t *treq)
Request completed successfully, inform the API client and free the request.
Definition trunk.c:1647
static void trunk_request_enter_sent(trunk_request_t *treq)
Transition a request to the sent state, indicating that it's been sent in its entirety.
Definition trunk.c:1358
#define DO_REQUEST_CANCEL_MUX(_tconn)
Write one or more cancellation requests to a connection.
Definition trunk.c:688
static void trunk_connection_enter_full(trunk_connection_t *tconn)
Transition a connection to the full state.
Definition trunk.c:3247
void trunk_request_free(trunk_request_t **treq_to_free)
If the trunk request is freed then update the target requests.
Definition trunk.c:2430
#define DO_REQUEST_DEMUX(_tconn)
Read one or more requests from a connection.
Definition trunk.c:672
static uint64_t trunk_connection_requests_dequeue(fr_dlist_head_t *out, trunk_connection_t *tconn, int states, uint64_t max)
Shift requests in the specified states onto new connections.
Definition trunk.c:1845
static int _trunk_request_free(trunk_request_t *treq)
Actually free the trunk request.
Definition trunk.c:2553
char const * log_prefix
What to prepend to messages.
Definition trunk.c:224
#define REQUEST_EXTRACT_PENDING(_treq)
Remove the current request from the pending list.
Definition trunk.c:766
static void _trunk_connection_lifetime_expire(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t now, void *uctx)
Trigger a reconnection of the trunk connection.
Definition trunk.c:3579
static fr_cmp_ret_t _trunk_connection_order_by_shortest_queue(void const *one, void const *two)
Order connections by queue depth.
Definition trunk.c:5089
static void trunk_connection_event_update(trunk_connection_t *tconn)
Update the registrations for I/O events we're interested in.
Definition trunk.c:3127
static conf_parser_t const trunk_config_request[]
Definition trunk.c:328
fr_dlist_head_t full
Connections which have too many outstanding requests.
Definition trunk.c:250
#define DEQUEUE_ALL(_src_list, _state)
static void trunk_request_enter_backlog(trunk_request_t *treq, bool new)
Transition a request to the backlog state, adding it to the backlog of the trunk.
Definition trunk.c:1189
static fr_table_num_ordered_t const trunk_request_states[]
Definition trunk.c:412
static void _trunk_connection_on_connecting(UNUSED connection_t *conn, UNUSED connection_state_t prev, UNUSED connection_state_t state, void *uctx)
Connection transitioned to the connecting state.
Definition trunk.c:3496
static fr_table_num_indexed_bit_pos_t const trunk_conn_trigger_names[]
Map connection states to trigger names.
Definition trunk.c:202
fr_dlist_head_t draining_to_free
Connections that will be freed once all their requests are complete.
Definition trunk.c:268
uint64_t id
Trunk request ID.
Definition trunk.c:104
bool blocking
The request will block the connection until it is completed, so no more requests should be enqueued o...
Definition trunk.c:122
uint64_t sent_count
The number of requests that have been sent using this connection.
Definition trunk.c:175
static void _trunk_connection_on_init(UNUSED connection_t *conn, UNUSED connection_state_t prev, UNUSED connection_state_t state, void *uctx)
Connection transitioned to the init state.
Definition trunk.c:3461
#define DO_CONNECTION_NOTIFY(_tconn, _events)
Change what events the connection should be notified about.
Definition trunk.c:728
#define TREQ_DLIST_VERIFY(_dlist, _state)
fr_dlist_head_t inactive
Connections which have been signalled to be inactive by the API client.
Definition trunk.c:253
bool trigger_undef[NUM_ELEMENTS(trunk_conn_trigger_names)]
Record that a specific trigger is undefined.
Definition trunk.c:321
void trunk_connection_manage_stop(trunk_t *trunk)
Stop the trunk from opening and closing connections in response to load.
Definition trunk.c:5054
#define TREQ_HEAP_VERIFY(_heap, _state)
void trunk_connection_signal_active(trunk_connection_t *tconn)
Signal a trunk connection is no longer full.
Definition trunk.c:4114
fr_dlist_head_t log
State change log.
Definition trunk.c:127
uint64_t tconn_id
If the treq was associated with a connection the connection ID.
Definition trunk.c:85
fr_dlist_t entry
Used to track the connection in the connecting, full and failed lists.
Definition trunk.c:145
static void trunk_request_enter_cancel_sent(trunk_request_t *treq)
Transition a request to the cancel_sent state, placing it in a connection's cancel_sent list.
Definition trunk.c:1571
static void trunk_connection_reorder_after_write(trunk_connection_t *tconn)
Reorder an active connection after a request moves to the sent or reapable state.
Definition trunk.c:835
static void trunk_connection_enter_inactive(trunk_connection_t *tconn)
Transition a connection to the inactive state.
Definition trunk.c:3269
trunk_request_state_t from
What state we transitioned from.
Definition trunk.c:79
fr_pair_list_t * trigger_args
Passed to trigger.
Definition trunk.c:319
fr_dlist_head_t cancel_sent
Sent cancellation request.
Definition trunk.c:169
void trunk_connection_manage_start(trunk_t *trunk)
Allow the trunk to open and close connections in response to load.
Definition trunk.c:5043
fr_dlist_head_t inactive_draining
Connections which have been signalled to be inactive by the API client, which the trunk manager is dr...
Definition trunk.c:256
void trunk_connection_signal_inactive(trunk_connection_t *tconn)
Signal a trunk connection cannot accept more requests.
Definition trunk.c:4091
static int _state_log_entry_free(trunk_request_state_log_t *slog)
Used for sanity checks to ensure all log entries have been freed.
Definition trunk.c:2918
void trunk_connection_verify(char const *file, int line, trunk_connection_t *tconn)
Definition trunk.c:5480
fr_heap_t * backlog
The request backlog.
Definition trunk.c:233
#define IN_REQUEST_CANCEL_MUX(_trunk)
Definition trunk.c:748
void trunk_request_verify(char const *file, int line, trunk_request_t *treq)
Definition trunk.c:5540
uint64_t trunk_request_count_by_state(trunk_t *trunk, int conn_state, int req_state)
Return a count of requests on a connection in a specific state.
Definition trunk.c:4748
void trunk_request_mark_blocking(trunk_request_t *treq)
Mark a trunk request as one which will block the connection until it is completed.
Definition trunk.c:2903
void trunk_request_signal_cancel_partial(trunk_request_t *treq)
Signal a partial cancel write.
Definition trunk.c:2344
void trunk_request_signal_sent(trunk_request_t *treq)
Signal that the request was written to a connection successfully.
Definition trunk.c:2158
#define COUNT_BY_STATE(_state, _list)
void * uctx
Uctx data to pass to alloc.
Definition trunk.c:284
#define TREQ_OPTION_VERIFY(_option, _state)
bool trunk_connection_search(trunk_connection_t *tconn, void *ptr)
Definition trunk.c:5596
#define CONN_BAD_STATE_TRANSITION(_new)
Definition trunk.c:491
fr_heap_index_t heap_id
Used to track the request conn->pending heap.
Definition trunk.c:106
#define REQUEST_STATE_TRANSITION(_new)
Record a request state transition and log appropriate output.
Definition trunk.c:514
trunk_watch_entry_t * next_watcher
Watcher about to be run. Used to prevent nested watchers.
Definition trunk.c:288
static uint64_t trunk_connection_requests_requeue_priv(trunk_connection_t *tconn, int states, uint64_t max, bool fail_bound)
Remove requests in specified states from a connection, attempting to distribute them to new connectio...
Definition trunk.c:1956
bool sent
Trunk request has been sent at least once.
Definition trunk.c:118
void trunk_request_signal_complete(trunk_request_t *treq)
Signal that a trunk request is complete.
Definition trunk.c:2202
static void trunk_connection_auto_unfull(trunk_connection_t *tconn)
Automatically mark a connection as active or reconnect it.
Definition trunk.c:3067
void trunk_connection_signal_reconnect(trunk_connection_t *tconn, connection_reason_t reason)
Signal a trunk connection is no longer viable.
Definition trunk.c:4153
void trunk_connection_signal_writable(trunk_connection_t *tconn)
Signal that a trunk connection is writable.
Definition trunk.c:4057
bool trunk_request_search(trunk_request_t *treq, void *ptr)
Definition trunk.c:5654
fr_dlist_t entry
List entry.
Definition trunk.c:190
static conf_parser_t const trunk_config_connection[]
Definition trunk.c:337
trunk_connection_state_t tconn_state
If the treq was associated with a connection the connection state at the time of the state transition...
Definition trunk.c:87
bool bound_to_conn
Fail the request if there's an attempt to re-enqueue it.
Definition trunk.c:115
static size_t trunk_cancellation_reasons_len
Definition trunk.c:458
static fr_table_num_ordered_t const trunk_cancellation_reasons[]
Definition trunk.c:452
static size_t trunk_conn_trigger_names_len
Definition trunk.c:214
fr_event_list_t * el
Event list used by this trunk and the connection.
Definition trunk.c:226
void trunk_request_state_log(fr_log_t const *log, fr_log_type_t log_type, char const *file, int line, trunk_request_t const *treq)
Definition trunk.c:2956
#define IN_REQUEST_MUX(_trunk)
Definition trunk.c:746
fr_dlist_head_t free_requests
Requests in the unassigned state.
Definition trunk.c:230
bool trunk_connection_in_state(trunk_connection_t *tconn, int state)
Returns true if the trunk connection is in one of the specified states.
Definition trunk.c:4201
#define TREQ_HEAP_SEARCH(_heap)
#define REQUEST_EXTRACT_CANCEL_SENT(_treq)
Remove the current request from the cancel sent list.
Definition trunk.c:809
fr_dlist_t entry
Entry in the linked list.
Definition trunk.c:78
void trunk_request_signal_reapable(trunk_request_t *treq)
Signal that the request was written to a connection successfully, but no response is expected.
Definition trunk.c:2180
Associates request queues with a connection.
Definition trunk.c:137
Wraps a normal request.
Definition trunk.c:99
Trace state machine changes for a particular request.
Definition trunk.c:76
Main trunk management handle.
Definition trunk.c:219
An entry in a trunk watch function list.
Definition trunk.c:189
uint16_t max
Maximum number of connections in the trunk.
Definition trunk.h:254
uint32_t max_req_per_conn
Maximum requests per connection.
Definition trunk.h:263
fr_time_t _CONST last_write_success
Last time we wrote to the connection.
Definition trunk.h:349
trunk_t *_CONST trunk
Trunk this request belongs to.
Definition trunk.h:380
bool backlog_on_failed_conn
Assign requests to the backlog when there are no available connections and the last connection event ...
Definition trunk.h:310
uint16_t min
Shouldn't let connections drop below this number.
Definition trunk.h:252
trunk_connection_event_t
What type of I/O events the trunk connection is currently interested in receiving.
Definition trunk.h:81
@ TRUNK_CONN_EVENT_BOTH
Trunk should be notified if a connection is readable or writable.
Definition trunk.h:88
@ TRUNK_CONN_EVENT_WRITE
Trunk should be notified if a connection is writable.
Definition trunk.h:86
@ TRUNK_CONN_EVENT_NONE
Don't notify the trunk on connection state changes.
Definition trunk.h:82
@ TRUNK_CONN_EVENT_READ
Trunk should be notified if a connection is readable.
Definition trunk.h:84
#define TRUNK_REQUEST_STATE_ALL
All request states.
Definition trunk.h:218
void *_CONST rctx
Resume ctx of the module.
Definition trunk.h:386
trunk_t *_CONST trunk
Trunk this connection belongs to.
Definition trunk.h:408
fr_heap_cmp_t connection_prioritise
Ordering function for connections.
Definition trunk.h:770
unsigned req_pool_headers
How many chunk headers the talloc pool allocated with the treq should contain.
Definition trunk.h:295
request_t *_CONST request
The request that we're writing the data on behalf of.
Definition trunk.h:388
fr_time_t _CONST last_open
Last time the connection management function opened a connection.
Definition trunk.h:339
fr_time_delta_t idle_timeout
how long a connection can remain idle for
Definition trunk.h:273
trunk_connection_state_t _CONST state
What state the connection is in.
Definition trunk.h:400
trunk_connection_state_t
Used for sanity checks and to track which list the connection is in.
Definition trunk.h:96
@ TRUNK_CONN_FULL
Connection is full and can't accept any more requests.
Definition trunk.h:104
@ TRUNK_CONN_CONNECTING
Connection is connecting.
Definition trunk.h:99
@ TRUNK_CONN_DRAINING
Connection will be closed once it has no more outstanding requests, if it's not reactivated.
Definition trunk.h:110
@ TRUNK_CONN_INACTIVE_DRAINING
Connection is inactive, can't accept any more requests, and will be closed once it has no more outsta...
Definition trunk.h:106
@ TRUNK_CONN_INACTIVE
Connection is inactive and can't accept any more requests.
Definition trunk.h:105
@ TRUNK_CONN_HALTED
Halted, ready to be freed.
Definition trunk.h:97
@ TRUNK_CONN_CLOSED
Connection was closed, either explicitly or due to failure.
Definition trunk.h:103
@ TRUNK_CONN_INIT
In the initial state.
Definition trunk.h:98
@ TRUNK_CONN_DRAINING_TO_FREE
Connection will be closed once it has no more outstanding requests.
Definition trunk.h:112
@ TRUNK_CONN_ACTIVE
Connection is connected and ready to service requests.
Definition trunk.h:100
trunk_state_t
Definition trunk.h:62
@ TRUNK_STATE_MAX
Definition trunk.h:75
@ TRUNK_STATE_PENDING
Trunk has connections, but none are usable yet; connections are being opened (INIT / CONNECTING).
Definition trunk.h:66
@ TRUNK_STATE_FAILED
Trunk has connections, but they have all failed and are closed / in reconnect backoff.
Definition trunk.h:72
@ TRUNK_STATE_ACTIVE
Trunk has at least one active connection which can service requests.
Definition trunk.h:64
@ TRUNK_STATE_FULL
Trunk has no active connections, but has one or more connected connections which are all full (at cap...
Definition trunk.h:68
@ TRUNK_STATE_IDLE
Trunk has no connections.
Definition trunk.h:63
size_t req_pool_size
The size of the talloc pool allocated with the treq.
Definition trunk.h:298
uint64_t max_uses
The maximum time a connection can be used.
Definition trunk.h:269
fr_time_delta_t lifetime
Time between reconnects.
Definition trunk.h:271
uint16_t connecting
Maximum number of connections that can be in the connecting state.
Definition trunk.h:256
@ TRUNK_SORT_QUEUE
Order by queue depth only.
Definition trunk.h:163
@ TRUNK_SORT_MRU
Most Recently Used (MRU): order by the time of the last successful reply, then by queue depth.
Definition trunk.h:164
@ TRUNK_SORT_LRU
Least Recently Used (LRU): order by fewer requests in the pending and partial states,...
Definition trunk.h:166
uint64_t _CONST req_alloc_reused
How many requests were reused.
Definition trunk.h:363
uint32_t max_backlog
Maximum number of requests that can be in the backlog.
Definition trunk.h:267
fr_time_t _CONST last_failed
Last time a connection failed.
Definition trunk.h:347
trunk_request_state_t _CONST state
Which list the request is now located in.
Definition trunk.h:378
fr_time_t _CONST last_write_success
Last time we wrote to the connection.
Definition trunk.h:404
trunk_connection_t *_CONST tconn
Connection this request belongs to.
Definition trunk.h:382
trunk_connection_alloc_t connection_alloc
Allocate a new connection_t.
Definition trunk.h:766
fr_time_t _CONST last_read_success
Last time we read a response.
Definition trunk.h:351
fr_time_t _CONST last_below_target
Last time average utilisation went below the target value.
Definition trunk.h:336
fr_time_t _CONST last_read_success
Last time we read from the connection.
Definition trunk.h:406
fr_time_delta_t close_delay
How long we must be below target utilisation to close an existing connection.
Definition trunk.h:278
uint16_t start
How many connections to start.
Definition trunk.h:250
fr_time_delta_t req_cleanup_delay
How long must a request in the unassigned (free) list not have been used for before it's cleaned up a...
Definition trunk.h:282
#define TRUNK_REQUEST_STATE_CANCEL_ALL
All requests in various cancellation states.
Definition trunk.h:236
bool always_writable
Set to true if our ability to write requests to a connection handle is not dependent on the state of ...
Definition trunk.h:300
trunk_enqueue_t
Definition trunk.h:171
@ TRUNK_ENQUEUE_DST_UNAVAILABLE
Destination is down.
Definition trunk.h:176
@ TRUNK_ENQUEUE_FAIL
General internal sanity check failure.
Definition trunk.h:177
@ TRUNK_ENQUEUE_OK
Operation was successful.
Definition trunk.h:173
@ TRUNK_ENQUEUE_NO_CAPACITY
At maximum number of connections, and no connection has capacity.
Definition trunk.h:174
@ TRUNK_ENQUEUE_IN_BACKLOG
Request should be enqueued in backlog.
Definition trunk.h:172
#define TRUNK_CONN_ALL
All connection states.
Definition trunk.h:120
fr_heap_cmp_t request_prioritise
Ordering function for requests.
Definition trunk.h:772
uint64_t _CONST req_alloc
The number of requests currently allocated that have not been freed or returned to the free list.
Definition trunk.h:357
uint64_t _CONST req_alloc_new
How many requests we've allocated.
Definition trunk.h:361
fr_time_delta_t open_delay
How long we must be above target utilisation to spawn a new connection.
Definition trunk.h:275
connection_t *_CONST conn
The underlying connection.
Definition trunk.h:402
fr_time_t _CONST last_closed
Last time the connection management function closed a connection.
Definition trunk.h:342
void(* trunk_watch_t)(trunk_t *trunk, trunk_state_t prev, trunk_state_t state, void *uctx)
Receive a notification when a trunk enters a particular state.
Definition trunk.h:757
fr_time_delta_t manage_interval
How often we run the management algorithm to open/close connections.
Definition trunk.h:286
void *_CONST preq
Data for the muxer to write to the connection.
Definition trunk.h:384
trunk_request_state_t
Used for sanity checks and to simplify freeing.
Definition trunk.h:184
@ TRUNK_REQUEST_STATE_PARTIAL
Some of the request was written to the socket, more of it should be written later.
Definition trunk.h:193
@ TRUNK_REQUEST_STATE_REAPABLE
Request has been written, needs to persist, but we are not currently waiting for any response.
Definition trunk.h:196
@ TRUNK_REQUEST_STATE_UNASSIGNED
Transition state - Request currently not assigned to any connection.
Definition trunk.h:188
@ TRUNK_REQUEST_STATE_INIT
Initial state.
Definition trunk.h:185
@ TRUNK_REQUEST_STATE_CANCEL_SENT
We've informed the remote server that the request has been cancelled.
Definition trunk.h:208
@ TRUNK_REQUEST_STATE_COMPLETE
The request is complete.
Definition trunk.h:205
@ TRUNK_REQUEST_STATE_FAILED
The request failed.
Definition trunk.h:206
@ TRUNK_REQUEST_STATE_CANCEL
A request on a particular socket was cancel.
Definition trunk.h:207
@ TRUNK_REQUEST_STATE_CANCEL_PARTIAL
We partially wrote a cancellation request.
Definition trunk.h:210
@ TRUNK_REQUEST_STATE_BACKLOG
In the backlog.
Definition trunk.h:190
@ TRUNK_REQUEST_STATE_CANCEL_COMPLETE
Remote server has acknowledged our cancellation.
Definition trunk.h:211
@ TRUNK_REQUEST_STATE_PENDING
In the queue of a connection and is pending writing.
Definition trunk.h:191
@ TRUNK_REQUEST_STATE_SENT
Was written to a socket. Waiting for a response.
Definition trunk.h:195
uint32_t target_req_per_conn
How many pending requests should ideally be running on each connection.
Definition trunk.h:259
fr_time_t _CONST last_connected
Last time a connection connected.
Definition trunk.h:345
trunk_request_cancel_mux_t request_cancel_mux
!< Read one or more requests from a connection.
Definition trunk.h:779
trunk_cancel_reason_t
Reasons for a request being cancelled.
Definition trunk.h:55
@ TRUNK_CANCEL_REASON_NONE
Request has not been cancelled.
Definition trunk.h:56
@ TRUNK_CANCEL_REASON_SIGNAL
Request cancelled due to a signal.
Definition trunk.h:57
@ TRUNK_CANCEL_REASON_REQUEUE
A previously sent request is being requeued.
Definition trunk.h:59
@ TRUNK_CANCEL_REASON_MOVE
Request cancelled because it's being moved.
Definition trunk.h:58
trunk_state_t _CONST state
Current state of the trunk.
Definition trunk.h:366
fr_time_t _CONST last_above_target
Last time average utilisation went above the target value.
Definition trunk.h:333
Common configuration parameters for a trunk.
Definition trunk.h:247
Public fields for the trunk connection.
Definition trunk.h:399
I/O functions to pass to trunk_alloc.
Definition trunk.h:765
Public fields for the trunk.
Definition trunk.h:329
Public fields for the trunk request.
Definition trunk.h:377
static fr_event_list_t * el
static fr_slen_t head
Definition xlat.h:410
static fr_slen_t parent
Definition pair.h:864
char const * fr_strerror(void)
Get the last library error.
Definition strerror.c:558
static fr_sbuff_err_t char size_t fr_sbuff_t size_t max
Definition value.h:1061
static fr_sbuff_err_t char ** out
Definition value.h:1061
#define fr_box_time_delta(_val)
Definition value.h:397
int nonnull(2, 5))