Simplified sanity checks
[freeradius.git] / src / main / connection.c
1 /*
2  *   This program is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License as published by
4  *   the Free Software Foundation; either version 2 of the License, or
5  *   (at your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /**
18  * @file connection.c
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.
22  *
23  * @copyright 2012  The FreeRADIUS server project
24  * @copyright 2012  Alan DeKok <aland@deployingradius.com>
25  */
26 RCSID("$Id$")
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/rad_assert.h>
30
31 typedef struct fr_connection fr_connection_t;
32
33 static int fr_connection_pool_check(fr_connection_pool_t *pool);
34
35 extern bool check_config;
36
37 #ifndef NDEBUG
38 #ifdef HAVE_PTHREAD_H
39 #define PTHREAD_DEBUG (1)
40 #endif
41 #endif
42
43 /** An individual connection within the connection pool
44  *
45  * Defines connection counters, timestamps, and holds a pointer to the
46  * connection handle itself.
47  *
48  * @see fr_connection_pool_t
49  */
50 struct fr_connection {
51         fr_connection_t *prev;          //!< Previous connection in list.
52         fr_connection_t *next;          //!< Next connection in list.
53
54         time_t          created;        //!< Time connection was created.
55         time_t          last_used;      //!< Last time the connection was
56                                         //!< reserved.
57
58         uint64_t        num_uses;       //!< Number of times the connection
59                                         //!< has been reserved.
60         int             in_use;         //!< Whether the connection is currently
61                                         //!< reserved.
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.
68 #ifdef PTHREAD_DEBUG
69         pthread_t       pthread_id;     //!< When 'in_use == true'
70 #endif
71 };
72
73 /** A connection pool
74  *
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.
79  *
80  * @see fr_connection
81  */
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.
94                                           //!< (0 is infinite).
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
102                                         //!< from there.
103         uint64_t        max_uses;       //!< Maximum number of times a
104                                         //!< connection can be used before being
105                                         //!< closed.
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.
111
112         bool            trigger;        //!< If true execute connection triggers
113                                         //!< associated with the connection
114                                         //!< pool.
115
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.
120
121         time_t          last_checked;   //!< Last time we pruned the connection
122                                         //!< pool.
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.
134
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
139                                         //!< connections.
140
141         fr_connection_t *head;          //!< Start of the connection list.
142         fr_connection_t *tail;          //!< End of the connection list.
143
144         bool            spawning;       //!< Whether we are currently attempting
145                                         //!< to spawn a new connection.
146
147 #ifdef HAVE_PTHREAD_H
148         pthread_mutex_t mutex;          //!< Mutex used to keep consistent state
149                                         //!< when making modifications in
150                                         //!< threaded mode.
151 #endif
152
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.
158
159         char            *log_prefix;    //!< Log prefix to prepend to all log
160                                         //!< messages created by the connection
161                                         //!< pool code.
162
163         fr_connection_create_t  create; //!< Function used to create new
164                                         //!< connections.
165         fr_connection_alive_t   alive;  //!< Function used to check status
166                                         //!< of connections.
167         fr_connection_delete_t  delete; //!< Function used to close existing
168                                         //!< connections.
169 };
170
171 #define LOG_PREFIX "rlm_%s (%s)"
172 #ifndef HAVE_PTHREAD_H
173 #define pthread_mutex_lock(_x)
174 #define pthread_mutex_unlock(_x)
175 #endif
176
177 static const CONF_PARSER connection_config[] = {
178         { "start",    PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, start),
179           0, "5" },
180         { "min",      PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, min),
181           0, "5" },
182         { "max",      PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, max),
183           0, "10" },
184         { "spare",    PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, spare),
185           0, "3" },
186         { "uses",     PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, max_uses),
187           0, "0" },
188         { "lifetime", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, lifetime),
189           0, "0" },
190         { "cleanup_delay", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, cleanup_interval),
191           0, NULL},
192         { "cleanup_interval", PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, cleanup_interval),
193           0, "30" },
194         { "idle_timeout",  PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, idle_timeout),
195           0, "60" },
196         { "retry_delay",  PW_TYPE_INTEGER, offsetof(fr_connection_pool_t, retry_delay),
197           0, "1" },
198         { "spread", PW_TYPE_BOOLEAN, offsetof(fr_connection_pool_t, spread),
199           0, "no" },
200         { NULL, -1, 0, NULL, NULL }
201 };
202
203 /** Removes a connection from the connection list
204  *
205  * @note Must be called with the mutex held.
206  *
207  * @param[in,out] pool to modify.
208  * @param[in] this Connection to delete.
209  */
210 static void fr_connection_unlink(fr_connection_pool_t *pool,
211                                  fr_connection_t *this)
212 {
213         if (this->prev) {
214                 rad_assert(pool->head != this);
215                 this->prev->next = this->next;
216         } else {
217                 rad_assert(pool->head == this);
218                 pool->head = this->next;
219         }
220         if (this->next) {
221                 rad_assert(pool->tail != this);
222                 this->next->prev = this->prev;
223         } else {
224                 rad_assert(pool->tail == this);
225                 pool->tail = this->prev;
226         }
227
228         this->prev = this->next = NULL;
229 }
230
231 /** Adds a connection to the head of the connection list
232  *
233  * @note Must be called with the mutex held.
234  *
235  * @param[in,out] pool to modify.
236  * @param[in] this Connection to add.
237  */
238 static void fr_connection_link_head(fr_connection_pool_t *pool,
239                                     fr_connection_t *this)
240 {
241         rad_assert(pool != NULL);
242         rad_assert(this != NULL);
243         rad_assert(pool->head != this);
244         rad_assert(pool->tail != this);
245
246         if (pool->head) {
247                 pool->head->prev = this;
248         }
249
250         this->next = pool->head;
251         this->prev = NULL;
252         pool->head = this;
253         if (!pool->tail) {
254                 rad_assert(this->next == NULL);
255                 pool->tail = this;
256         } else {
257                 rad_assert(this->next != NULL);
258         }
259 }
260
261 /** Adds a connection to the tail of the connection list
262  *
263  * @note Must be called with the mutex held.
264  *
265  * @param[in,out] pool to modify.
266  * @param[in] this Connection to add.
267  */
268 static void fr_connection_link_tail(fr_connection_pool_t *pool,
269                                     fr_connection_t *this)
270 {
271         rad_assert(pool != NULL);
272         rad_assert(this != NULL);
273         rad_assert(pool->head != this);
274         rad_assert(pool->tail != this);
275
276         if (pool->tail) {
277                 pool->tail->next = this;
278         }
279         this->prev = pool->tail;
280         this->next = NULL;
281         pool->tail = this;
282         if (!pool->head) {
283                 rad_assert(this->prev == NULL);
284                 pool->head = this;
285         } else {
286                 rad_assert(this->prev != NULL);
287         }
288 }
289
290
291 /** Spawns a new connection
292  *
293  * Spawns a new connection using the create callback, and returns it for
294  * adding to the connection list.
295  *
296  * @note Will call the 'open' trigger.
297  * @note Must be called with the mutex free.
298  *
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.
303  */
304 static fr_connection_t *fr_connection_spawn(fr_connection_pool_t *pool,
305                                             time_t now, bool in_use)
306 {
307         fr_connection_t *this;
308         void *conn;
309
310         rad_assert(pool != NULL);
311
312         /*
313          *      Prevent all threads from blocking if the resource
314          *      were managing connections for appears to be unavailable.
315          */
316         if ((pool->num == 0) && pool->spawning) {
317                 return NULL;
318         }
319
320         pthread_mutex_lock(&pool->mutex);
321         rad_assert(pool->num <= pool->max);
322
323         /*
324          *      Don't spawn multiple connections at the same time.
325          */
326         if (pool->spawning) {
327                 pthread_mutex_unlock(&pool->mutex);
328
329                 ERROR("%s: Cannot open new connection, "
330                       "connection spawning already in "
331                       "progress", pool->log_prefix);
332                 return NULL;
333         }
334
335         /*
336          *      If the last attempt failed, wait a bit before
337          *      retrying.
338          */
339         if (pool->last_failed && ((pool->last_failed + pool->retry_delay) > now)) {
340                 bool complain = false;
341
342                 if (pool->last_throttled != now) {
343                         complain = true;
344
345                         pool->last_throttled = now;
346                 }
347
348                 pthread_mutex_unlock(&pool->mutex);
349
350                 if (complain) {
351                         ERROR("%s: Last connection attempt failed, "
352                               "waiting %d seconds before retrying",
353                               pool->log_prefix, pool->retry_delay);
354                 }
355
356                 return NULL;
357         }
358
359         pool->spawning = true;
360
361         /*
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
366          *      to be used.
367          */
368         pthread_mutex_unlock(&pool->mutex);
369
370         INFO("%s: Opening additional connection (%" PRIu64 ")", pool->log_prefix, pool->count);
371
372         /*
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.
377          */
378         conn = pool->create(pool->ctx);
379         if (!conn) {
380                 ERROR("%s: Opening connection failed (%" PRIu64 ")", pool->log_prefix, pool->count);
381
382                 pool->last_failed = now;
383                 pool->spawning = false; /* atomic, so no lock is needed */
384                 return NULL;
385         }
386
387         this = rad_malloc(sizeof(*this));
388         memset(this, 0, sizeof(*this));
389
390         this->created = now;
391         this->connection = conn;
392         this->in_use = in_use;
393
394         /*
395          *      And lock the mutex again while we link the new
396          *      connection back into the pool.
397          */
398         pthread_mutex_lock(&pool->mutex);
399
400         this->number = pool->count++;
401         this->last_used = now;
402         fr_connection_link_head(pool, this);
403         pool->num++;
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;
409
410         pthread_mutex_unlock(&pool->mutex);
411
412         if (pool->trigger) exec_trigger(NULL, pool->cs, "open", true);
413
414         return this;
415 }
416
417 /** Close an existing connection.
418  *
419  * Removes the connection from the list, calls the delete callback to close
420  * the connection, then frees memory allocated to the connection.
421  *
422  * @note Will call the 'close' trigger.
423  * @note Must be called with the mutex held.
424  *
425  * @param[in,out] pool to modify.
426  * @param[in,out] this Connection to delete.
427
428  */
429 static void fr_connection_close(fr_connection_pool_t *pool,
430                                 fr_connection_t *this)
431 {
432         /*
433          *      If it's in use, release it.
434          */
435         if (this->in_use) {
436 #ifdef PTHREAD_DEBUG
437                 pthread_t pthread_id = pthread_self();
438                 rad_assert(pthread_equal(this->pthread_id, pthread_id) != 0);
439 #endif
440                 this->in_use = false;
441
442                 rad_assert(pool->active > 0);
443                 pool->active--;
444         }
445
446         if (pool->trigger) exec_trigger(NULL, pool->cs, "close", true);
447
448         fr_connection_unlink(pool, this);
449         pool->delete(pool->ctx, this->connection);
450         rad_assert(pool->num > 0);
451         pool->num--;
452         free(this);
453 }
454
455 /** Find a connection handle in the connection list
456  *
457  * Walks over the list of connections searching for a specified connection
458  * handle and returns the first connection that contains that pointer.
459  *
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.
463  *
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
467  * found.
468  */
469 static fr_connection_t *fr_connection_find(fr_connection_pool_t *pool, void *conn)
470 {
471         fr_connection_t *this;
472
473         if (!pool || !conn) return NULL;
474
475         pthread_mutex_lock(&pool->mutex);
476
477         /*
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.
481          */
482         for (this = pool->head; this != NULL; this = this->next) {
483                 if (this->connection == conn) {
484 #ifdef PTHREAD_DEBUG
485                         pthread_t pthread_id;
486
487                         pthread_id = pthread_self();
488                         rad_assert(pthread_equal(this->pthread_id, pthread_id) != 0);
489 #endif
490
491                         rad_assert(this->in_use == true);
492                         return this;
493                 }
494         }
495
496         pthread_mutex_unlock(&pool->mutex);
497         return NULL;
498 }
499
500 /** Delete a connection from the connection pool.
501  *
502  * Resolves the connection handle to a connection, then (if found)
503  * closes, unlinks and frees that connection.
504  *
505  * @note Must be called with the mutex free.
506  *
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.
510  */
511 int fr_connection_del(fr_connection_pool_t *pool, void *conn)
512 {
513         fr_connection_t *this;
514
515         this = fr_connection_find(pool, conn);
516         if (!this) return 0;
517
518         INFO("%s: Deleting connection (%" PRIu64 ")", pool->log_prefix, this->number);
519
520         fr_connection_close(pool, this);
521         fr_connection_pool_check(pool);
522         return 1;
523 }
524
525 /** Delete a connection pool
526  *
527  * Closes, unlinks and frees all connections in the connection pool, then frees
528  * all memory used by the connection pool.
529  *
530  * @note Will call the 'stop' trigger.
531  * @note Must be called with the mutex free.
532  *
533  * @param[in,out] pool to delete.
534  */
535 void fr_connection_pool_delete(fr_connection_pool_t *pool)
536 {
537         fr_connection_t *this, *next;
538
539         if (!pool) return;
540
541         DEBUG("%s: Removing connection pool", pool->log_prefix);
542
543         pthread_mutex_lock(&pool->mutex);
544
545         for (this = pool->head; this != NULL; this = next) {
546                 next = this->next;
547
548                 INFO("%s: Closing connection (%" PRIu64 ")", pool->log_prefix, this->number);
549
550                 fr_connection_close(pool, this);
551         }
552
553         if (pool->trigger) exec_trigger(NULL, pool->cs, "stop", true);
554
555         rad_assert(pool->head == NULL);
556         rad_assert(pool->tail == NULL);
557         rad_assert(pool->num == 0);
558
559         free(pool->log_prefix);
560         free(pool);
561 }
562
563 /** Create a new connection pool
564  *
565  * Allocates structures used by the connection pool, initialises the various
566  * configuration options and counters, and sets the callback functions.
567  *
568  * Will also spawn the number of connections specified by the 'start'
569  * configuration options.
570  *
571  * @note Will call the 'start' trigger.
572  *
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.
581  */
582 fr_connection_pool_t *fr_connection_pool_init(CONF_SECTION *parent,
583                                               void *ctx,
584                                               fr_connection_create_t c,
585                                               fr_connection_alive_t a,
586                                               fr_connection_delete_t d,
587                                               char *prefix)
588 {
589         int i, lp_len;
590         fr_connection_pool_t *pool;
591         fr_connection_t *this;
592         CONF_SECTION *modules;
593         CONF_SECTION *cs;
594         char const *cs_name1, *cs_name2;
595         time_t now = time(NULL);
596
597         if (!parent || !ctx || !c || !d) return NULL;
598
599         cs = cf_section_sub_find(parent, "pool");
600         if (!cs) cs = cf_section_sub_find(parent, "limit");
601
602         pool = rad_malloc(sizeof(*pool));
603         memset(pool, 0, sizeof(*pool));
604
605         pool->cs = cs;
606         pool->ctx = ctx;
607         pool->create = c;
608         pool->alive = a;
609         pool->delete = d;
610
611         pool->head = pool->tail = NULL;
612
613 #ifdef HAVE_PTHREAD_H
614         pthread_mutex_init(&pool->mutex, NULL);
615 #endif
616
617         if (!prefix) {
618                 modules = cf_item_parent(cf_sectiontoitem(parent));
619                 if (modules) {
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);
624                                 if (!cs_name2) {
625                                         cs_name2 = cs_name1;
626                                 }
627
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,
631                                          cs_name2);
632                         }
633                 } else {                /* not a module configuration */
634                         cs_name1 = cf_section_name1(parent);
635
636                         pool->log_prefix = strdup(cs_name1);
637                 }
638         } else {
639                 pool->log_prefix = strdup(prefix);
640         }
641
642         DEBUG("%s: Initialising connection pool", pool->log_prefix);
643
644         if (cs) {
645                 if (cf_section_parse(cs, pool, connection_config) < 0) {
646                         goto error;
647                 }
648
649                 if (cf_section_sub_find(cs, "trigger")) pool->trigger = true;
650         } else {
651                 pool->start = 5;
652                 pool->min = 5;
653                 pool->max = 10;
654                 pool->spare = 3;
655                 pool->cleanup_interval = 30;
656                 pool->idle_timeout = 60;
657         }
658
659         /*
660          *      Some simple limits
661          */
662         if (pool->max == 0) {
663                 cf_log_err_cs(cs, "Cannot set 'max' to zero");
664                 goto error;
665         }
666         if (pool->min > pool->max) {
667                 cf_log_err_cs(cs, "Cannot set 'min' to more than 'max'");
668                 goto error;
669         }
670
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;
675         }
676         if ((pool->lifetime > 0) && (pool->idle_timeout > pool->lifetime)) {
677                 pool->idle_timeout = 0;
678         }
679
680         if (pool->cleanup_interval < 0) {
681                 pool->cleanup_interval = 30;
682         }
683
684         if ((pool->idle_timeout > 0) && (pool->cleanup_interval > pool->idle_timeout)) {
685                 pool->cleanup_interval = pool->idle_timeout;
686         }
687
688         /*
689          *      Don't open any connections.  Instead, force the limits
690          *      to only 1 connection.
691          *
692          */
693         if (check_config) {
694                 pool->start = pool->min = pool->max = 1;
695                 return pool;
696         }
697
698         /*
699          *      Create all of the connections, unless the admin says
700          *      not to.
701          */
702         for (i = 0; i < pool->start; i++) {
703                 this = fr_connection_spawn(pool, now, false);
704                 if (!this) {
705                 error:
706                         fr_connection_pool_delete(pool);
707                         return NULL;
708                 }
709         }
710
711         if (pool->trigger) exec_trigger(NULL, pool->cs, "start", true);
712
713         return pool;
714 }
715
716
717 /** Check whether a connection needs to be removed from the pool
718  *
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.
721  *
722  * @note Will only close connections not in use.
723  * @note Must be called with the mutex held.
724  *
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.
729  */
730 static int fr_connection_manage(fr_connection_pool_t *pool,
731                                 fr_connection_t *this,
732                                 time_t now)
733 {
734         rad_assert(pool != NULL);
735         rad_assert(this != NULL);
736
737         /*
738          *      Don't terminated in-use connections
739          */
740         if (this->in_use) return 1;
741
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,
745                       this->number);
746         do_delete:
747                 if ((pool->num <= pool->min) &&
748                     (pool->last_complained < now)) {
749                         WARN("%s: You probably need to lower \"min\"", pool->log_prefix);
750
751                         pool->last_complained = now;
752                 }
753                 fr_connection_close(pool, this);
754                 return 0;
755         }
756
757         if ((pool->lifetime > 0) &&
758             ((this->created + pool->lifetime) < now)) {
759                 DEBUG("%s: Closing expired connection (%" PRIu64 ")", pool->log_prefix, this->number);
760                 goto do_delete;
761         }
762
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));
767                 goto do_delete;
768         }
769
770         return 1;
771 }
772
773
774 /** Check whether any connections needs to be removed from the pool
775  *
776  * Maintains the number of connections in the pool as per the configuration
777  * parameters for the connection pool.
778  *
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
783  * returning.
784  *
785  * @param[in,out] pool to manage.
786  * @return 1
787  */
788 static int fr_connection_pool_check(fr_connection_pool_t *pool)
789 {
790         int spawn, idle, extra;
791         time_t now = time(NULL);
792         fr_connection_t *this, *next;
793
794         if (pool->last_checked == now) {
795                 pthread_mutex_unlock(&pool->mutex);
796                 return 1;
797         }
798
799         /*
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.
803          */
804         idle = pool->num - pool->active;
805         if (idle <= pool->spare) {
806                 extra = 0;
807         } else {
808                 extra = idle - pool->spare;
809         }
810
811         /*
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".
815          */
816         if (pool->num <= pool->min) {
817                 if (pool->spawning) {
818                         spawn = 0;
819                 } else {
820                         spawn = pool->min - pool->num;
821                 }
822                 extra = 0;
823
824         } else if (pool->num >= pool->max) {
825                 /*
826                  *      Ensure we don't spawn more connections.  If
827                  *      there are extra idle connections, we can
828                  *      delete all of them.
829                  */
830                 spawn = 0;
831                 /* leave extra alone from above */
832
833         } else if (idle <= pool->spare) {
834                 /*
835                  *      Not enough spare connections.  Spawn a few.
836                  *      But cap the pool size at "max"
837                  */
838                 spawn = pool->spare - idle;
839                 extra = 0;
840
841                 if ((pool->num + spawn) > pool->max) {
842                         spawn = pool->max - pool->num;
843                 }
844
845         } else if ((pool->min + extra) >= pool->num) {
846                 /*
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".
851                  */
852                 spawn = 0;
853                 extra = pool->num - pool->min;
854
855         } else {
856                 /*
857                  *      Closing the "extra" connections won't take us
858                  *      below "min".  It's therefore safe to close
859                  *      them all.
860                  */
861                 spawn = 0;
862                 /* leave extra alone from above */
863         }
864
865         if (spawn) {
866                 pthread_mutex_unlock(&pool->mutex);
867                 fr_connection_spawn(pool, now, false); /* ignore return code */
868                 pthread_mutex_lock(&pool->mutex);
869         }
870
871         /*
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.
875          */
876         if (extra && (now >= (pool->last_spawned + pool->delay_interval))) {
877                 fr_connection_t *found;
878
879                 found = NULL;
880                 for (this = pool->tail; this != NULL; this = this->prev) {
881                         if (this->in_use) continue;
882
883                         if (!found ||
884                            (this->last_used < found->last_used)) {
885                                 found = this;
886                         }
887                 }
888
889                 rad_assert(found != NULL);
890
891                 INFO("%s: Closing connection (%" PRIu64 "), from %d unused connections", pool->log_prefix,
892                      found->number, extra);
893                 fr_connection_close(pool, found);
894
895                 /*
896                  *      Decrease the delay for the next time we clean
897                  *      up.
898                  */
899                 pool->next_delay >>= 1;
900                 if (pool->next_delay == 0) pool->next_delay = 1;
901                 pool->delay_interval += pool->next_delay;
902         }
903
904         /*
905          *      Pass over all of the connections in the pool, limiting
906          *      lifetime, idle time, max requests, etc.
907          */
908         for (this = pool->head; this != NULL; this = next) {
909                 next = this->next;
910                 fr_connection_manage(pool, this, now);
911         }
912
913         pool->last_checked = now;
914         pthread_mutex_unlock(&pool->mutex);
915
916         return 1;
917 }
918
919 /** Get a connection from the connection pool
920  *
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.
924  */
925 static void *fr_connection_get_internal(fr_connection_pool_t *pool, int spawn)
926 {
927         time_t now;
928         fr_connection_t *this, *next;
929
930         if (!pool) return NULL;
931
932         pthread_mutex_lock(&pool->mutex);
933
934         now = time(NULL);
935         for (this = pool->head; this != NULL; this = next) {
936                 next = this->next;
937
938                 if (!this->in_use) goto do_return;
939         }
940
941         if (pool->num == pool->max) {
942                 bool complain = false;
943
944                 /*
945                  *      Rate-limit complaints.
946                  */
947                 if (pool->last_at_max != now) {
948                         complain = true;
949                         pool->last_at_max = now;
950                 }
951
952                 pthread_mutex_unlock(&pool->mutex);
953
954                 if (complain) {
955                         ERROR("%s: No connections available and at max connection limit", pool->log_prefix);
956                 }
957
958                 return NULL;
959         }
960
961         pthread_mutex_unlock(&pool->mutex);
962
963         if (!spawn) return NULL;
964
965         this = fr_connection_spawn(pool, now, true); /* MY connection! */
966         if (!this) return NULL;
967         pthread_mutex_lock(&pool->mutex);
968
969 do_return:
970         pool->active++;
971         this->num_uses++;
972         this->last_used = now;
973         this->in_use = true;
974
975 #ifdef PTHREAD_DEBUG
976         this->pthread_id = pthread_self();
977 #endif
978         pthread_mutex_unlock(&pool->mutex);
979
980         DEBUG("%s: Reserved connection (%" PRIu64 ")", pool->log_prefix, this->number);
981
982         return this->connection;
983 }
984
985
986 /** Reserve a connection in the connection pool
987  *
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.
991  *
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.
995  *
996  * @note fr_connection_release must be called once the caller has finished
997  * using the connection.
998  *
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.
1002  */
1003 void *fr_connection_get(fr_connection_pool_t *pool)
1004 {
1005         return fr_connection_get_internal(pool, true);
1006 }
1007
1008
1009 /** Release a connection
1010  *
1011  * Will mark a connection as unused and decrement the number of active
1012  * connections.
1013  *
1014  * @see fr_connection_get
1015  * @param[in,out] pool to release the connection in.
1016  * @param[in,out] conn to release.
1017  */
1018 void fr_connection_release(fr_connection_pool_t *pool, void *conn)
1019 {
1020         fr_connection_t *this;
1021
1022         this = fr_connection_find(pool, conn);
1023         if (!this) return;
1024
1025         this->in_use = false;
1026
1027         /*
1028          *      Determines whether the last used connection gets
1029          *      re-used first.
1030          */
1031         if (pool->spread) {
1032                 /*
1033                  *      Put it at the tail of the list, so
1034                  *      that it will get re-used last.
1035                  */
1036                 if (this != pool->tail) {
1037                         fr_connection_unlink(pool, this);
1038                         fr_connection_link_tail(pool, this);
1039                 }
1040         } else {
1041                 /*
1042                  *      Put it at the head of the list, so
1043                  *      that it will get re-used quickly.
1044                  */
1045                 if (this != pool->head) {
1046                         fr_connection_unlink(pool, this);
1047                         fr_connection_link_head(pool, this);
1048                 }
1049         }
1050
1051         rad_assert(pool->active > 0);
1052         pool->active--;
1053
1054         DEBUG("%s: Released connection (%" PRIu64 ")", pool->log_prefix, this->number);
1055
1056         /*
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.
1060          */
1061         fr_connection_pool_check(pool);
1062 }
1063
1064 /** Reconnect a suspected inviable connection
1065  *
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).
1068  *
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
1071  * pool connection.
1072  *
1073  * If this is not successful, the connection will be removed from the pool.
1074  *
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.
1081  *
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.
1084  *
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.
1089  */
1090 void *fr_connection_reconnect(fr_connection_pool_t *pool, void *conn)
1091 {
1092         void *new_conn;
1093         fr_connection_t *this;
1094         uint64_t conn_number;
1095
1096         if (!pool || !conn) return NULL;
1097
1098         this = fr_connection_find(pool, conn);
1099         if (!this) return NULL;
1100
1101         /*
1102          *      The pool is now locked.
1103          */
1104         conn_number = this->number;
1105
1106         DEBUG("%s: Reconnecting (%" PRIu64 ")", pool->log_prefix, conn_number);
1107
1108         new_conn = pool->create(pool->ctx);
1109         if (!new_conn) {
1110                 time_t now = time(NULL);
1111
1112                 if (pool->last_complained == now) {
1113                         now = 0;
1114                 } else {
1115                         pool->last_complained = now;
1116                 }
1117
1118                 /*
1119                  *      We can't create a new connection, so close
1120                  *      this one.
1121                  */
1122                 fr_connection_close(pool, this);
1123
1124                 /*
1125                  *      Maybe there's a connection which is unused and
1126                  *      available.  If so, return it.
1127                  */
1128                 pthread_mutex_unlock(&pool->mutex);
1129                 new_conn = fr_connection_get_internal(pool, false);
1130                 if (new_conn) return new_conn;
1131
1132                 if (!now) return NULL;
1133
1134                 ERROR("%s: Failed to reconnect (%" PRIu64 "), no free connections are available", pool->log_prefix,
1135                       conn_number);
1136
1137                 return NULL;
1138         }
1139
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);
1144         return new_conn;
1145 }