2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
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.
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
19 * @brief Handle pools of connections (threads, sockets, etc.)
20 * @note This API must be used by all modules in the public distribution that
21 * maintain pools of connections.
23 * @copyright 2012 The FreeRADIUS server project
24 * @copyright 2012 Alan DeKok <aland@deployingradius.com>
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/rad_assert.h>
31 typedef struct fr_connection fr_connection_t;
33 static int fr_connection_pool_check(fr_connection_pool_t *pool);
35 extern bool check_config;
39 #define PTHREAD_DEBUG (1)
43 /** An individual connection within the connection pool
45 * Defines connection counters, timestamps, and holds a pointer to the
46 * connection handle itself.
48 * @see fr_connection_pool_t
50 struct fr_connection {
51 fr_connection_t *prev; //!< Previous connection in list.
52 fr_connection_t *next; //!< Next connection in list.
54 time_t created; //!< Time connection was created.
55 time_t last_used; //!< Last time the connection was
58 uint64_t num_uses; //!< Number of times the connection
59 //!< has been reserved.
60 int in_use; //!< Whether the connection is currently
62 uint64_t number; //!< Unique ID assigned when the
63 //!< connection is created, these will
64 //!< monotonically increase over the
65 //!< lifetime of the connection pool.
66 void *connection; //!< Pointer to whatever the module
67 //!< uses for a connection handle.
69 pthread_t pthread_id; //!< When 'in_use == true'
75 * Defines the configuration of the connection pool, all the counters and
76 * timestamps related to the connection pool, the mutex that stops multiple
77 * threads leaving the pool in an inconsistent state, and the callbacks
78 * required to open, close and check the status of connections within the pool.
82 struct fr_connection_pool_t {
83 int start; //!< Number of initial connections
84 int min; //!< Minimum number of concurrent
85 //!< connections to keep open.
86 int max; //!< Maximum number of concurrent
87 //!< connections to allow.
88 int spare; //!< Number of spare connections to try
89 int retry_delay; //!< seconds to delay re-open
90 //!< after a failed open.
91 int cleanup_interval; //!< Initial timer for how
92 //!< often we sweep the pool
93 //!< for free connections.
95 int delay_interval; //!< When we next do a
96 //!< cleanup. Initialized to
97 //!< cleanup_interval, and increase
98 //!< from there based on the delay.
99 int next_delay; //!< The next delay time.
100 //!< cleanup. Initialized to
101 //!< cleanup_interval, and decays
103 uint64_t max_uses; //!< Maximum number of times a
104 //!< connection can be used before being
106 int lifetime; //!< How long a connection can be open
107 //!< before being closed (irrespective
108 //!< of whether it's idle or not).
109 int idle_timeout; //!< How long a connection can be idle
110 //!< before being closed.
112 bool trigger; //!< If true execute connection triggers
113 //!< associated with the connection
116 bool spread; //!< If true requests will be spread
117 //!< across all connections, instead of
118 //!< re-using the most recently used
119 //!< connections first.
121 time_t last_checked; //!< Last time we pruned the connection
123 time_t last_spawned; //!< Last time we spawned a connection.
124 time_t last_failed; //!< Last time we tried to spawn a
125 //!< a connection but failed.
126 time_t last_complained;//!< Last time we complained about
127 //!< configuration parameters.
128 time_t last_throttled; //!< Last time we refused to spawn a
129 //!< connection because the last
130 //!< connection failed, or we were
131 //!< already spawning a connection.
132 time_t last_at_max; //!< Last time we hit the maximum number
133 //!< of allowed connections.
135 uint64_t count; //!< Number of connections spawned over
136 //!< the lifetime of the pool.
137 int num; //!< Number of connections in the pool.
138 int active; //!< Number of currently reserved
141 fr_connection_t *head; //!< Start of the connection list.
142 fr_connection_t *tail; //!< End of the connection list.
144 bool spawning; //!< Whether we are currently attempting
145 //!< to spawn a new connection.
147 #ifdef HAVE_PTHREAD_H
148 pthread_mutex_t mutex; //!< Mutex used to keep consistent state
149 //!< when making modifications in
153 CONF_SECTION *cs; //!< Configuration section holding
154 //!< the section of parsed config file
155 //!< that relates to this pool.
156 void *ctx; //!< Pointer to context data that will
157 //!< be passed to callbacks.
159 char *log_prefix; //!< Log prefix to prepend to all log
160 //!< messages created by the connection
163 fr_connection_create_t create; //!< Function used to create new
165 fr_connection_alive_t alive; //!< Function used to check status
167 fr_connection_delete_t delete; //!< Function used to close existing
171 #define LOG_PREFIX "rlm_%s (%s)"
172 #ifndef HAVE_PTHREAD_H
173 #define pthread_mutex_lock(_x)
174 #define pthread_mutex_unlock(_x)
177 static const CONF_PARSER connection_config[] = {
178 { "start", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, start),
180 { "min", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, min),
182 { "max", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, max),
184 { "spare", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, spare),
186 { "uses", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, max_uses),
188 { "lifetime", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, lifetime),
190 { "cleanup_delay", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, cleanup_interval),
192 { "cleanup_interval", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, cleanup_interval),
194 { "idle_timeout", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, idle_timeout),
196 { "retry_delay", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, retry_delay),
198 { "spread", PW_TYPE_BOOLEAN, offsetof(fr_connection_pool_t, spread),
200 { NULL, -1, 0, NULL, NULL }
203 /** Removes a connection from the connection list
205 * @note Must be called with the mutex held.
207 * @param[in,out] pool to modify.
208 * @param[in] this Connection to delete.
210 static void fr_connection_unlink(fr_connection_pool_t *pool,
211 fr_connection_t *this)
214 rad_assert(pool->head != this);
215 this->prev->next = this->next;
217 rad_assert(pool->head == this);
218 pool->head = this->next;
221 rad_assert(pool->tail != this);
222 this->next->prev = this->prev;
224 rad_assert(pool->tail == this);
225 pool->tail = this->prev;
228 this->prev = this->next = NULL;
231 /** Adds a connection to the head of the connection list
233 * @note Must be called with the mutex held.
235 * @param[in,out] pool to modify.
236 * @param[in] this Connection to add.
238 static void fr_connection_link_head(fr_connection_pool_t *pool,
239 fr_connection_t *this)
241 rad_assert(pool != NULL);
242 rad_assert(this != NULL);
243 rad_assert(pool->head != this);
244 rad_assert(pool->tail != this);
247 pool->head->prev = this;
250 this->next = pool->head;
254 rad_assert(this->next == NULL);
257 rad_assert(this->next != NULL);
261 /** Adds a connection to the tail of the connection list
263 * @note Must be called with the mutex held.
265 * @param[in,out] pool to modify.
266 * @param[in] this Connection to add.
268 static void fr_connection_link_tail(fr_connection_pool_t *pool,
269 fr_connection_t *this)
271 rad_assert(pool != NULL);
272 rad_assert(this != NULL);
273 rad_assert(pool->head != this);
274 rad_assert(pool->tail != this);
277 pool->tail->next = this;
279 this->prev = pool->tail;
283 rad_assert(this->prev == NULL);
286 rad_assert(this->prev != NULL);
291 /** Spawns a new connection
293 * Spawns a new connection using the create callback, and returns it for
294 * adding to the connection list.
296 * @note Will call the 'open' trigger.
297 * @note Must be called with the mutex free.
299 * @param[in] pool to modify.
300 * @param[in] now Current time.
301 * @param[in] in_use whether the new connection should be "in_use" or not
302 * @return the new connection struct or NULL on error.
304 static fr_connection_t *fr_connection_spawn(fr_connection_pool_t *pool,
305 time_t now, bool in_use)
307 fr_connection_t *this;
310 rad_assert(pool != NULL);
313 * Prevent all threads from blocking if the resource
314 * were managing connections for appears to be unavailable.
316 if ((pool->num == 0) && pool->spawning) {
320 pthread_mutex_lock(&pool->mutex);
321 rad_assert(pool->num <= pool->max);
324 * Don't spawn multiple connections at the same time.
326 if (pool->spawning) {
327 pthread_mutex_unlock(&pool->mutex);
329 ERROR("%s: Cannot open new connection, "
330 "connection spawning already in "
331 "progress", pool->log_prefix);
336 * If the last attempt failed, wait a bit before
339 if (pool->last_failed && ((pool->last_failed + pool->retry_delay) > now)) {
340 bool complain = false;
342 if (pool->last_throttled != now) {
345 pool->last_throttled = now;
348 pthread_mutex_unlock(&pool->mutex);
351 ERROR("%s: Last connection attempt failed, "
352 "waiting %d seconds before retrying",
353 pool->log_prefix, pool->retry_delay);
359 pool->spawning = true;
362 * Unlock the mutex while we try to open a new
363 * connection. If there are issues with the back-end,
364 * opening a new connection may take a LONG time. In
365 * that case, we want the other connections to continue
368 pthread_mutex_unlock(&pool->mutex);
370 INFO("%s: Opening additional connection (%" PRIu64 ")", pool->log_prefix, pool->count);
373 * This may take a long time, which prevents other
374 * threads from releasing connections. We don't care
375 * about other threads opening new connections, as we
376 * already have no free connections.
378 conn = pool->create(pool->ctx);
380 ERROR("%s: Opening connection failed (%" PRIu64 ")", pool->log_prefix, pool->count);
382 pool->last_failed = now;
383 pool->spawning = false; /* atomic, so no lock is needed */
387 this = rad_malloc(sizeof(*this));
388 memset(this, 0, sizeof(*this));
391 this->connection = conn;
392 this->in_use = in_use;
395 * And lock the mutex again while we link the new
396 * connection back into the pool.
398 pthread_mutex_lock(&pool->mutex);
400 this->number = pool->count++;
401 this->last_used = now;
402 fr_connection_link_head(pool, this);
404 pool->spawning = false;
405 pool->last_spawned = time(NULL);
406 pool->delay_interval = pool->cleanup_interval;
407 pool->next_delay = pool->cleanup_interval;
408 pool->last_failed = 0;
410 pthread_mutex_unlock(&pool->mutex);
412 if (pool->trigger) exec_trigger(NULL, pool->cs, "open", true);
417 /** Close an existing connection.
419 * Removes the connection from the list, calls the delete callback to close
420 * the connection, then frees memory allocated to the connection.
422 * @note Will call the 'close' trigger.
423 * @note Must be called with the mutex held.
425 * @param[in,out] pool to modify.
426 * @param[in,out] this Connection to delete.
429 static void fr_connection_close(fr_connection_pool_t *pool,
430 fr_connection_t *this)
433 * If it's in use, release it.
437 pthread_t pthread_id = pthread_self();
438 rad_assert(pthread_equal(this->pthread_id, pthread_id) != 0);
440 this->in_use = false;
442 rad_assert(pool->active > 0);
446 if (pool->trigger) exec_trigger(NULL, pool->cs, "close", true);
448 fr_connection_unlink(pool, this);
449 pool->delete(pool->ctx, this->connection);
450 rad_assert(pool->num > 0);
455 /** Find a connection handle in the connection list
457 * Walks over the list of connections searching for a specified connection
458 * handle and returns the first connection that contains that pointer.
460 * @note Will lock mutex and only release mutex if connection handle
461 * is not found, so will usually return will mutex held.
462 * @note Must be called with the mutex free.
464 * @param[in] pool to search in.
465 * @param[in] conn handle to search for.
466 * @return the connection containing the specified handle, or NULL if non is
469 static fr_connection_t *fr_connection_find(fr_connection_pool_t *pool, void *conn)
471 fr_connection_t *this;
473 if (!pool || !conn) return NULL;
475 pthread_mutex_lock(&pool->mutex);
478 * FIXME: This loop could be avoided if we passed a 'void
479 * **connection' instead. We could use "offsetof" in
480 * order to find top of the parent structure.
482 for (this = pool->head; this != NULL; this = this->next) {
483 if (this->connection == conn) {
485 pthread_t pthread_id;
487 pthread_id = pthread_self();
488 rad_assert(pthread_equal(this->pthread_id, pthread_id) != 0);
491 rad_assert(this->in_use == true);
496 pthread_mutex_unlock(&pool->mutex);
500 /** Delete a connection from the connection pool.
502 * Resolves the connection handle to a connection, then (if found)
503 * closes, unlinks and frees that connection.
505 * @note Must be called with the mutex free.
507 * @param[in,out] pool Connection pool to modify.
508 * @param[in] conn to delete.
509 * @return 0 if the connection could not be found, else 1.
511 int fr_connection_del(fr_connection_pool_t *pool, void *conn)
513 fr_connection_t *this;
515 this = fr_connection_find(pool, conn);
518 INFO("%s: Deleting connection (%" PRIu64 ")", pool->log_prefix, this->number);
520 fr_connection_close(pool, this);
521 fr_connection_pool_check(pool);
525 /** Delete a connection pool
527 * Closes, unlinks and frees all connections in the connection pool, then frees
528 * all memory used by the connection pool.
530 * @note Will call the 'stop' trigger.
531 * @note Must be called with the mutex free.
533 * @param[in,out] pool to delete.
535 void fr_connection_pool_delete(fr_connection_pool_t *pool)
537 fr_connection_t *this, *next;
541 DEBUG("%s: Removing connection pool", pool->log_prefix);
543 pthread_mutex_lock(&pool->mutex);
545 for (this = pool->head; this != NULL; this = next) {
548 INFO("%s: Closing connection (%" PRIu64 ")", pool->log_prefix, this->number);
550 fr_connection_close(pool, this);
553 if (pool->trigger) exec_trigger(NULL, pool->cs, "stop", true);
555 rad_assert(pool->head == NULL);
556 rad_assert(pool->tail == NULL);
557 rad_assert(pool->num == 0);
559 free(pool->log_prefix);
563 /** Create a new connection pool
565 * Allocates structures used by the connection pool, initialises the various
566 * configuration options and counters, and sets the callback functions.
568 * Will also spawn the number of connections specified by the 'start'
569 * configuration options.
571 * @note Will call the 'start' trigger.
573 * @param[in] parent configuration section containing a 'pool' subsection.
574 * @param[in] ctx pointer to pass to callbacks.
575 * @param[in] c Callback to create new connections.
576 * @param[in] a Callback to check the status of connections.
577 * @param[in] d Callback to delete connections.
578 * @param[in] prefix to prepend to all log message, if NULL will create prefix
579 * from parent conf section names.
580 * @return A new connection pool or NULL on error.
582 fr_connection_pool_t *fr_connection_pool_init(CONF_SECTION *parent,
584 fr_connection_create_t c,
585 fr_connection_alive_t a,
586 fr_connection_delete_t d,
590 fr_connection_pool_t *pool;
591 fr_connection_t *this;
592 CONF_SECTION *modules;
594 char const *cs_name1, *cs_name2;
595 time_t now = time(NULL);
597 if (!parent || !ctx || !c || !d) return NULL;
599 cs = cf_section_sub_find(parent, "pool");
600 if (!cs) cs = cf_section_sub_find(parent, "limit");
602 pool = rad_malloc(sizeof(*pool));
603 memset(pool, 0, sizeof(*pool));
611 pool->head = pool->tail = NULL;
613 #ifdef HAVE_PTHREAD_H
614 pthread_mutex_init(&pool->mutex, NULL);
618 modules = cf_item_parent(cf_sectiontoitem(parent));
620 cs_name1 = cf_section_name1(modules);
621 if (cs_name1 && (strcmp(cs_name1, "modules") == 0)) {
622 cs_name1 = cf_section_name1(parent);
623 cs_name2 = cf_section_name2(parent);
628 lp_len = (sizeof(LOG_PREFIX) - 4) + strlen(cs_name1) + strlen(cs_name2);
629 pool->log_prefix = rad_malloc(lp_len);
630 snprintf(pool->log_prefix, lp_len, LOG_PREFIX, cs_name1,
633 } else { /* not a module configuration */
634 cs_name1 = cf_section_name1(parent);
636 pool->log_prefix = strdup(cs_name1);
639 pool->log_prefix = strdup(prefix);
642 DEBUG("%s: Initialising connection pool", pool->log_prefix);
645 if (cf_section_parse(cs, pool, connection_config) < 0) {
649 if (cf_section_sub_find(cs, "trigger")) pool->trigger = true;
655 pool->cleanup_interval = 30;
656 pool->idle_timeout = 60;
662 if (pool->max == 0) {
663 cf_log_err_cs(cs, "Cannot set 'max' to zero");
666 if (pool->min > pool->max) {
667 cf_log_err_cs(cs, "Cannot set 'min' to more than 'max'");
671 if (pool->max > 1024) pool->max = 1024;
672 if (pool->start > pool->max) pool->start = pool->max;
673 if (pool->spare > (pool->max - pool->min)) {
674 pool->spare = pool->max - pool->min;
676 if ((pool->lifetime > 0) && (pool->idle_timeout > pool->lifetime)) {
677 pool->idle_timeout = 0;
680 if (pool->cleanup_interval < 0) {
681 pool->cleanup_interval = 30;
684 if ((pool->idle_timeout > 0) && (pool->cleanup_interval > pool->idle_timeout)) {
685 pool->cleanup_interval = pool->idle_timeout;
689 * Don't open any connections. Instead, force the limits
690 * to only 1 connection.
694 pool->start = pool->min = pool->max = 1;
699 * Create all of the connections, unless the admin says
702 for (i = 0; i < pool->start; i++) {
703 this = fr_connection_spawn(pool, now, false);
706 fr_connection_pool_delete(pool);
711 if (pool->trigger) exec_trigger(NULL, pool->cs, "start", true);
717 /** Check whether a connection needs to be removed from the pool
719 * Will verify that the connection is within idle_timeout, max_uses, and
720 * lifetime values. If it is not, the connection will be closed.
722 * @note Will only close connections not in use.
723 * @note Must be called with the mutex held.
725 * @param[in,out] pool to modify.
726 * @param[in,out] this Connection to manage.
727 * @param[in] now Current time.
728 * @return 0 if the connection was closed, otherwise 1.
730 static int fr_connection_manage(fr_connection_pool_t *pool,
731 fr_connection_t *this,
734 rad_assert(pool != NULL);
735 rad_assert(this != NULL);
738 * Don't terminated in-use connections
740 if (this->in_use) return 1;
742 if ((pool->max_uses > 0) &&
743 (this->num_uses >= pool->max_uses)) {
744 DEBUG("%s: Closing expired connection (%" PRIu64 "): Hit max_uses limit", pool->log_prefix,
747 if ((pool->num <= pool->min) &&
748 (pool->last_complained < now)) {
749 WARN("%s: You probably need to lower \"min\"", pool->log_prefix);
751 pool->last_complained = now;
753 fr_connection_close(pool, this);
757 if ((pool->lifetime > 0) &&
758 ((this->created + pool->lifetime) < now)) {
759 DEBUG("%s: Closing expired connection (%" PRIu64 ")", pool->log_prefix, this->number);
763 if ((pool->idle_timeout > 0) &&
764 ((this->last_used + pool->idle_timeout) < now)) {
765 INFO("%s: Closing connection (%" PRIu64 "): Hit idle_timeout, was idle for %u seconds",
766 pool->log_prefix, this->number, (int) (now - this->last_used));
774 /** Check whether any connections needs to be removed from the pool
776 * Maintains the number of connections in the pool as per the configuration
777 * parameters for the connection pool.
779 * @note Will only run checks the first time it's called in a given second,
780 * to throttle connection spawning/closing.
781 * @note Will only close connections not in use.
782 * @note Must be called with the mutex held, will release mutex before
785 * @param[in,out] pool to manage.
788 static int fr_connection_pool_check(fr_connection_pool_t *pool)
790 int spawn, idle, extra;
791 time_t now = time(NULL);
792 fr_connection_t *this, *next;
794 if (pool->last_checked == now) {
795 pthread_mutex_unlock(&pool->mutex);
800 * Some idle connections are OK, if they're within the
801 * configured "spare" range. Any extra connections
802 * outside of that range can be closed.
804 idle = pool->num - pool->active;
805 if (idle <= pool->spare) {
808 extra = idle - pool->spare;
812 * The other end can close connections. If so, we'll
813 * have fewer than "min". When that happens, open more
814 * connections to enforce "min".
816 if (pool->num <= pool->min) {
817 if (pool->spawning) {
820 spawn = pool->min - pool->num;
824 } else if (pool->num >= pool->max) {
826 * Ensure we don't spawn more connections. If
827 * there are extra idle connections, we can
828 * delete all of them.
831 /* leave extra alone from above */
833 } else if (idle <= pool->spare) {
835 * Not enough spare connections. Spawn a few.
836 * But cap the pool size at "max"
838 spawn = pool->spare - idle;
841 if ((pool->num + spawn) > pool->max) {
842 spawn = pool->max - pool->num;
845 } else if ((pool->min + extra) >= pool->num) {
847 * If closing the extra connections would take us
848 * below "min", then don't do that. Cap the
849 * spare connections at the ones which will take
850 * us exactly to "min".
853 extra = pool->num - pool->min;
857 * Closing the "extra" connections won't take us
858 * below "min". It's therefore safe to close
862 /* leave extra alone from above */
866 pthread_mutex_unlock(&pool->mutex);
867 fr_connection_spawn(pool, now, false); /* ignore return code */
868 pthread_mutex_lock(&pool->mutex);
872 * We haven't spawned connections in a while, and there
873 * are too many spare ones. Close the one which has been
874 * unused for the longest.
876 if (extra && (now >= (pool->last_spawned + pool->delay_interval))) {
877 fr_connection_t *found;
880 for (this = pool->tail; this != NULL; this = this->prev) {
881 if (this->in_use) continue;
884 (this->last_used < found->last_used)) {
889 rad_assert(found != NULL);
891 INFO("%s: Closing connection (%" PRIu64 "), from %d unused connections", pool->log_prefix,
892 found->number, extra);
893 fr_connection_close(pool, found);
896 * Decrease the delay for the next time we clean
899 pool->next_delay >>= 1;
900 if (pool->next_delay == 0) pool->next_delay = 1;
901 pool->delay_interval += pool->next_delay;
905 * Pass over all of the connections in the pool, limiting
906 * lifetime, idle time, max requests, etc.
908 for (this = pool->head; this != NULL; this = next) {
910 fr_connection_manage(pool, this, now);
913 pool->last_checked = now;
914 pthread_mutex_unlock(&pool->mutex);
919 /** Get a connection from the connection pool
921 * @param[in,out] pool to reserve the connection from.
922 * @param[in] spawn whether to spawn a new connection
923 * @return a pointer to the connection handle, or NULL on error.
925 static void *fr_connection_get_internal(fr_connection_pool_t *pool, int spawn)
928 fr_connection_t *this, *next;
930 if (!pool) return NULL;
932 pthread_mutex_lock(&pool->mutex);
935 for (this = pool->head; this != NULL; this = next) {
938 if (!this->in_use) goto do_return;
941 if (pool->num == pool->max) {
942 bool complain = false;
945 * Rate-limit complaints.
947 if (pool->last_at_max != now) {
949 pool->last_at_max = now;
952 pthread_mutex_unlock(&pool->mutex);
955 ERROR("%s: No connections available and at max connection limit", pool->log_prefix);
961 pthread_mutex_unlock(&pool->mutex);
963 if (!spawn) return NULL;
965 this = fr_connection_spawn(pool, now, true); /* MY connection! */
966 if (!this) return NULL;
967 pthread_mutex_lock(&pool->mutex);
972 this->last_used = now;
976 this->pthread_id = pthread_self();
978 pthread_mutex_unlock(&pool->mutex);
980 DEBUG("%s: Reserved connection (%" PRIu64 ")", pool->log_prefix, this->number);
982 return this->connection;
986 /** Reserve a connection in the connection pool
988 * Will attempt to find an unused connection in the connection pool, if one is
989 * found, will mark it as in in use increment the number of active connections
990 * and return the connection handle.
992 * If no free connections are found will attempt to spawn a new one, conditional
993 * on a connection spawning not already being in progress, and not being at the
994 * 'max' connection limit.
996 * @note fr_connection_release must be called once the caller has finished
997 * using the connection.
999 * @see fr_connection_release
1000 * @param[in,out] pool to reserve the connection from.
1001 * @return a pointer to the connection handle, or NULL on error.
1003 void *fr_connection_get(fr_connection_pool_t *pool)
1005 return fr_connection_get_internal(pool, true);
1009 /** Release a connection
1011 * Will mark a connection as unused and decrement the number of active
1014 * @see fr_connection_get
1015 * @param[in,out] pool to release the connection in.
1016 * @param[in,out] conn to release.
1018 void fr_connection_release(fr_connection_pool_t *pool, void *conn)
1020 fr_connection_t *this;
1022 this = fr_connection_find(pool, conn);
1025 this->in_use = false;
1028 * Determines whether the last used connection gets
1033 * Put it at the tail of the list, so
1034 * that it will get re-used last.
1036 if (this != pool->tail) {
1037 fr_connection_unlink(pool, this);
1038 fr_connection_link_tail(pool, this);
1042 * Put it at the head of the list, so
1043 * that it will get re-used quickly.
1045 if (this != pool->head) {
1046 fr_connection_unlink(pool, this);
1047 fr_connection_link_head(pool, this);
1051 rad_assert(pool->active > 0);
1054 DEBUG("%s: Released connection (%" PRIu64 ")", pool->log_prefix, this->number);
1057 * We mirror the "spawn on get" functionality by having
1058 * "delete on release". If there are too many spare
1059 * connections, go manage the pool && clean some up.
1061 fr_connection_pool_check(pool);
1064 /** Reconnect a suspected inviable connection
1066 * This should be called by the module if it suspects that a connection is
1067 * not viable (e.g. the server has closed it).
1069 * Will attempt to create a new connection handle using the create callback,
1070 * and if this is successful the new handle will be assigned to the existing
1073 * If this is not successful, the connection will be removed from the pool.
1075 * When implementing a module that uses the connection pool API, it is advisable
1076 * to pass a pointer to the pointer to the handle (void **conn)
1077 * to all functions which may call reconnect. This is so that if a new handle
1078 * is created and returned, the handle pointer can be updated up the callstack,
1079 * and a function higher up the stack doesn't attempt to use a now invalid
1080 * connection handle.
1082 * @warning After calling reconnect the caller *MUST NOT* attempt to use
1083 * the old handle in any other operations, as its memory will have been freed.
1085 * @see fr_connection_get
1086 * @param[in,out] pool to reconnect the connection in.
1087 * @param[in,out] conn to reconnect.
1088 * @return new connection handle if successful else NULL.
1090 void *fr_connection_reconnect(fr_connection_pool_t *pool, void *conn)
1093 fr_connection_t *this;
1094 uint64_t conn_number;
1096 if (!pool || !conn) return NULL;
1098 this = fr_connection_find(pool, conn);
1099 if (!this) return NULL;
1102 * The pool is now locked.
1104 conn_number = this->number;
1106 DEBUG("%s: Reconnecting (%" PRIu64 ")", pool->log_prefix, conn_number);
1108 new_conn = pool->create(pool->ctx);
1110 time_t now = time(NULL);
1112 if (pool->last_complained == now) {
1115 pool->last_complained = now;
1119 * We can't create a new connection, so close
1122 fr_connection_close(pool, this);
1125 * Maybe there's a connection which is unused and
1126 * available. If so, return it.
1128 pthread_mutex_unlock(&pool->mutex);
1129 new_conn = fr_connection_get_internal(pool, false);
1130 if (new_conn) return new_conn;
1132 if (!now) return NULL;
1134 ERROR("%s: Failed to reconnect (%" PRIu64 "), no free connections are available", pool->log_prefix,
1140 if (pool->trigger) exec_trigger(NULL, pool->cs, "close", true);
1141 pool->delete(pool->ctx, conn);
1142 this->connection = new_conn;
1143 pthread_mutex_unlock(&pool->mutex);