2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "reconnect.h"
23 #include "poll-loop.h"
26 VLOG_DEFINE_THIS_MODULE(reconnect);
30 STATE(BACKOFF, 1 << 1) \
31 STATE(CONNECT_IN_PROGRESS, 1 << 3) \
32 STATE(ACTIVE, 1 << 4) \
34 STATE(RECONNECT, 1 << 6) \
35 STATE(LISTENING, 1 << 7)
37 #define STATE(NAME, VALUE) S_##NAME = VALUE,
43 is_connected_state(enum state state)
45 return (state & (S_ACTIVE | S_IDLE)) != 0;
55 enum vlog_level info; /* Used for informational messages. */
59 long long int state_entered;
61 long long int last_received;
62 long long int last_connected;
63 unsigned int max_tries;
65 /* These values are simply for statistics reporting, not otherwise used
66 * directly by anything internal. */
67 long long int creation_time;
68 unsigned int n_attempted_connections, n_successful_connections;
69 unsigned int total_connected_duration;
73 static void reconnect_transition__(struct reconnect *, long long int now,
75 static long long int reconnect_deadline__(const struct reconnect *);
76 static bool reconnect_may_retry(struct reconnect *);
79 reconnect_state_name__(enum state state)
82 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
89 /* Creates and returns a new reconnect FSM with default settings. The FSM is
90 * initially disabled. The caller will likely want to call reconnect_enable()
91 * and reconnect_set_name() on the returned object. */
93 reconnect_create(long long int now)
95 struct reconnect *fsm = xzalloc(sizeof *fsm);
97 fsm->name = xstrdup("void");
98 fsm->min_backoff = RECONNECT_DEFAULT_MIN_BACKOFF;
99 fsm->max_backoff = RECONNECT_DEFAULT_MAX_BACKOFF;
100 fsm->probe_interval = RECONNECT_DEFAULT_PROBE_INTERVAL;
101 fsm->passive = false;
102 fsm->info = VLL_INFO;
105 fsm->state_entered = now;
107 fsm->last_received = now;
108 fsm->last_connected = now;
109 fsm->max_tries = UINT_MAX;
110 fsm->creation_time = now;
117 reconnect_destroy(struct reconnect *fsm)
125 /* If 'quiet' is true, 'fsm' will log informational messages at level VLL_DBG,
126 * by default keeping them out of log files. This is appropriate if the
127 * connection is one that is expected to be short-lived, so that the log
128 * messages are merely distracting.
130 * If 'quiet' is false, 'fsm' logs informational messages at level VLL_INFO.
131 * This is the default.
133 * This setting has no effect on the log level of debugging, warning, or error
136 reconnect_set_quiet(struct reconnect *fsm, bool quiet)
138 fsm->info = quiet ? VLL_DBG : VLL_INFO;
141 /* Returns 'fsm''s name. */
143 reconnect_get_name(const struct reconnect *fsm)
148 /* Sets 'fsm''s name to 'name'. If 'name' is null, then "void" is used
151 * The name set for 'fsm' is used in log messages. */
153 reconnect_set_name(struct reconnect *fsm, const char *name)
156 fsm->name = xstrdup(name ? name : "void");
159 /* Return the minimum number of milliseconds to back off between consecutive
160 * connection attempts. The default is RECONNECT_DEFAULT_MIN_BACKOFF. */
162 reconnect_get_min_backoff(const struct reconnect *fsm)
164 return fsm->min_backoff;
167 /* Return the maximum number of milliseconds to back off between consecutive
168 * connection attempts. The default is RECONNECT_DEFAULT_MAX_BACKOFF. */
170 reconnect_get_max_backoff(const struct reconnect *fsm)
172 return fsm->max_backoff;
175 /* Returns the "probe interval" for 'fsm' in milliseconds. If this is zero, it
176 * disables the connection keepalive feature. If it is nonzero, then if the
177 * interval passes while 'fsm' is connected and without reconnect_received()
178 * being called for 'fsm', reconnect_run() returns RECONNECT_PROBE. If the
179 * interval passes again without reconnect_received() being called,
180 * reconnect_run() returns RECONNECT_DISCONNECT for 'fsm'. */
182 reconnect_get_probe_interval(const struct reconnect *fsm)
184 return fsm->probe_interval;
187 /* Limits the maximum number of times that 'fsm' will ask the client to try to
188 * reconnect to 'max_tries'. UINT_MAX (the default) means an unlimited number
191 * After the number of tries has expired, the 'fsm' will disable itself
192 * instead of backing off and retrying. */
194 reconnect_set_max_tries(struct reconnect *fsm, unsigned int max_tries)
196 fsm->max_tries = max_tries;
199 /* Returns the current remaining number of connection attempts, UINT_MAX if
200 * the number is unlimited. */
202 reconnect_get_max_tries(struct reconnect *fsm)
204 return fsm->max_tries;
207 /* Configures the backoff parameters for 'fsm'. 'min_backoff' is the minimum
208 * number of milliseconds, and 'max_backoff' is the maximum, between connection
211 * 'min_backoff' must be at least 1000, and 'max_backoff' must be greater than
212 * or equal to 'min_backoff'.
214 * Pass 0 for 'min_backoff' or 'max_backoff' or both to use the defaults. */
216 reconnect_set_backoff(struct reconnect *fsm, int min_backoff, int max_backoff)
218 fsm->min_backoff = MAX(min_backoff, 1000);
219 fsm->max_backoff = (max_backoff
220 ? MAX(max_backoff, 1000)
221 : RECONNECT_DEFAULT_MAX_BACKOFF);
222 if (fsm->min_backoff > fsm->max_backoff) {
223 fsm->max_backoff = fsm->min_backoff;
226 if (fsm->state == S_BACKOFF && fsm->backoff > max_backoff) {
227 fsm->backoff = max_backoff;
231 /* Sets the "probe interval" for 'fsm' to 'probe_interval', in milliseconds.
232 * If this is zero, it disables the connection keepalive feature. If it is
233 * nonzero, then if the interval passes while 'fsm' is connected and without
234 * reconnect_received() being called for 'fsm', reconnect_run() returns
235 * RECONNECT_PROBE. If the interval passes again without reconnect_received()
236 * being called, reconnect_run() returns RECONNECT_DISCONNECT for 'fsm'.
238 * If 'probe_interval' is nonzero, then it will be forced to a value of at
241 reconnect_set_probe_interval(struct reconnect *fsm, int probe_interval)
243 fsm->probe_interval = probe_interval ? MAX(1000, probe_interval) : 0;
246 /* Returns true if 'fsm' is in passive mode, false if 'fsm' is in active mode
249 reconnect_is_passive(const struct reconnect *fsm)
254 /* Configures 'fsm' for active or passive mode. In active mode (the default),
255 * the FSM is attempting to connect to a remote host. In passive mode, the FSM
256 * is listening for connections from a remote host. */
258 reconnect_set_passive(struct reconnect *fsm, bool passive, long long int now)
260 if (fsm->passive != passive) {
261 fsm->passive = passive;
264 ? fsm->state & (S_CONNECT_IN_PROGRESS | S_RECONNECT)
265 : fsm->state == S_LISTENING && reconnect_may_retry(fsm)) {
266 reconnect_transition__(fsm, now, S_BACKOFF);
272 /* Returns true if 'fsm' has been enabled with reconnect_enable(). Calling
273 * another function that indicates a change in connection state, such as
274 * reconnect_disconnected() or reconnect_force_reconnect(), will also enable
275 * a reconnect FSM. */
277 reconnect_is_enabled(const struct reconnect *fsm)
279 return fsm->state != S_VOID;
282 /* If 'fsm' is disabled (the default for newly created FSMs), enables it, so
283 * that the next call to reconnect_run() for 'fsm' will return
286 * If 'fsm' is not disabled, this function has no effect. */
288 reconnect_enable(struct reconnect *fsm, long long int now)
290 if (fsm->state == S_VOID && reconnect_may_retry(fsm)) {
291 reconnect_transition__(fsm, now, S_BACKOFF);
296 /* Disables 'fsm'. Until 'fsm' is enabled again, reconnect_run() will always
299 reconnect_disable(struct reconnect *fsm, long long int now)
301 if (fsm->state != S_VOID) {
302 reconnect_transition__(fsm, now, S_VOID);
306 /* If 'fsm' is enabled and currently connected (or attempting to connect),
307 * forces reconnect_run() for 'fsm' to return RECONNECT_DISCONNECT the next
308 * time it is called, which should cause the client to drop the connection (or
309 * attempt), back off, and then reconnect. */
311 reconnect_force_reconnect(struct reconnect *fsm, long long int now)
313 if (fsm->state & (S_CONNECT_IN_PROGRESS | S_ACTIVE | S_IDLE)) {
314 reconnect_transition__(fsm, now, S_RECONNECT);
318 /* Tell 'fsm' that the connection dropped or that a connection attempt failed.
319 * 'error' specifies the reason: a positive value represents an errno value,
320 * EOF indicates that the connection was closed by the peer (e.g. read()
321 * returned 0), and 0 indicates no specific error.
323 * The FSM will back off, then reconnect. */
325 reconnect_disconnected(struct reconnect *fsm, long long int now, int error)
327 if (!(fsm->state & (S_BACKOFF | S_VOID))) {
328 /* Report what happened. */
329 if (fsm->state & (S_ACTIVE | S_IDLE)) {
331 VLOG_WARN("%s: connection dropped (%s)",
332 fsm->name, strerror(error));
333 } else if (error == EOF) {
334 VLOG(fsm->info, "%s: connection closed by peer", fsm->name);
336 VLOG(fsm->info, "%s: connection dropped", fsm->name);
338 } else if (fsm->state == S_LISTENING) {
340 VLOG_WARN("%s: error listening for connections (%s)",
341 fsm->name, strerror(error));
343 VLOG(fsm->info, "%s: error listening for connections",
347 const char *type = fsm->passive ? "listen" : "connection";
349 VLOG_WARN("%s: %s attempt failed (%s)",
350 fsm->name, type, strerror(error));
352 VLOG(fsm->info, "%s: %s attempt timed out", fsm->name, type);
357 if (fsm->state & (S_ACTIVE | S_IDLE)
358 && (fsm->last_received - fsm->last_connected >= fsm->backoff
360 fsm->backoff = fsm->passive ? 0 : fsm->min_backoff;
362 if (fsm->backoff < fsm->min_backoff) {
363 fsm->backoff = fsm->min_backoff;
364 } else if (fsm->backoff >= fsm->max_backoff / 2) {
365 fsm->backoff = fsm->max_backoff;
370 VLOG(fsm->info, "%s: waiting %.3g seconds before trying to "
371 "listen again", fsm->name, fsm->backoff / 1000.0);
373 VLOG(fsm->info, "%s: waiting %.3g seconds before reconnect",
374 fsm->name, fsm->backoff / 1000.0);
378 reconnect_transition__(fsm, now,
379 reconnect_may_retry(fsm) ? S_BACKOFF : S_VOID);
383 /* Tell 'fsm' that a connection or listening attempt is in progress.
385 * The FSM will start a timer, after which the connection or listening attempt
386 * will be aborted (by returning RECONNECT_DISCONNECT from
387 * reconnect_run()). */
389 reconnect_connecting(struct reconnect *fsm, long long int now)
391 if (fsm->state != S_CONNECT_IN_PROGRESS) {
393 VLOG(fsm->info, "%s: listening...", fsm->name);
395 VLOG(fsm->info, "%s: connecting...", fsm->name);
397 reconnect_transition__(fsm, now, S_CONNECT_IN_PROGRESS);
401 /* Tell 'fsm' that the client is listening for connection attempts. This state
402 * last indefinitely until the client reports some change.
404 * The natural progression from this state is for the client to report that a
405 * connection has been accepted or is in progress of being accepted, by calling
406 * reconnect_connecting() or reconnect_connected().
408 * The client may also report that listening failed (e.g. accept() returned an
409 * unexpected error such as ENOMEM) by calling reconnect_listen_error(), in
410 * which case the FSM will back off and eventually return RECONNECT_CONNECT
411 * from reconnect_run() to tell the client to try listening again. */
413 reconnect_listening(struct reconnect *fsm, long long int now)
415 if (fsm->state != S_LISTENING) {
416 VLOG(fsm->info, "%s: listening...", fsm->name);
417 reconnect_transition__(fsm, now, S_LISTENING);
421 /* Tell 'fsm' that the client's attempt to accept a connection failed
422 * (e.g. accept() returned an unexpected error such as ENOMEM).
424 * If the FSM is currently listening (reconnect_listening() was called), it
425 * will back off and eventually return RECONNECT_CONNECT from reconnect_run()
426 * to tell the client to try listening again. If there is an active
427 * connection, this will be delayed until that connection drops. */
429 reconnect_listen_error(struct reconnect *fsm, long long int now, int error)
431 if (fsm->state == S_LISTENING) {
432 reconnect_disconnected(fsm, now, error);
436 /* Tell 'fsm' that the connection was successful.
438 * The FSM will start the probe interval timer, which is reset by
439 * reconnect_received(). If the timer expires, a probe will be sent (by
440 * returning RECONNECT_PROBE from reconnect_run()). If the timer expires
441 * again without being reset, the connection will be aborted (by returning
442 * RECONNECT_DISCONNECT from reconnect_run()). */
444 reconnect_connected(struct reconnect *fsm, long long int now)
446 if (!is_connected_state(fsm->state)) {
447 reconnect_connecting(fsm, now);
449 VLOG(fsm->info, "%s: connected", fsm->name);
450 reconnect_transition__(fsm, now, S_ACTIVE);
451 fsm->last_connected = now;
455 /* Tell 'fsm' that the connection attempt failed.
457 * The FSM will back off and attempt to reconnect. */
459 reconnect_connect_failed(struct reconnect *fsm, long long int now, int error)
461 reconnect_connecting(fsm, now);
462 reconnect_disconnected(fsm, now, error);
465 /* Tell 'fsm' that some data was received. This resets the probe interval
466 * timer, so that the connection is known not to be idle. */
468 reconnect_received(struct reconnect *fsm, long long int now)
470 if (fsm->state != S_ACTIVE) {
471 reconnect_transition__(fsm, now, S_ACTIVE);
473 fsm->last_received = now;
477 reconnect_transition__(struct reconnect *fsm, long long int now,
480 if (fsm->state == S_CONNECT_IN_PROGRESS) {
481 fsm->n_attempted_connections++;
482 if (state == S_ACTIVE) {
483 fsm->n_successful_connections++;
486 if (is_connected_state(fsm->state) != is_connected_state(state)) {
487 if (is_connected_state(fsm->state)) {
488 fsm->total_connected_duration += now - fsm->last_connected;
493 VLOG_DBG("%s: entering %s", fsm->name, reconnect_state_name__(state));
495 fsm->state_entered = now;
499 reconnect_deadline__(const struct reconnect *fsm)
501 assert(fsm->state_entered != LLONG_MIN);
502 switch (fsm->state) {
508 return fsm->state_entered + fsm->backoff;
510 case S_CONNECT_IN_PROGRESS:
511 return fsm->state_entered + MAX(1000, fsm->backoff);
514 if (fsm->probe_interval) {
515 long long int base = MAX(fsm->last_received, fsm->state_entered);
516 return base + fsm->probe_interval;
521 return fsm->state_entered + fsm->probe_interval;
524 return fsm->state_entered;
530 /* Assesses whether any action should be taken on 'fsm'. The return value is
533 * - 0: The client need not take any action.
535 * - Active client, RECONNECT_CONNECT: The client should start a connection
536 * attempt and indicate this by calling reconnect_connecting(). If the
537 * connection attempt has definitely succeeded, it should call
538 * reconnect_connected(). If the connection attempt has definitely
539 * failed, it should call reconnect_connect_failed().
541 * The FSM is smart enough to back off correctly after successful
542 * connections that quickly abort, so it is OK to call
543 * reconnect_connected() after a low-level successful connection
544 * (e.g. connect()) even if the connection might soon abort due to a
545 * failure at a high-level (e.g. SSL negotiation failure).
547 * - Passive client, RECONNECT_CONNECT: The client should try to listen for
548 * a connection, if it is not already listening. It should call
549 * reconnect_listening() if successful, otherwise reconnect_connecting()
550 * or reconnected_connect_failed() if the attempt is in progress or
551 * definitely failed, respectively.
553 * A listening passive client should constantly attempt to accept a new
554 * connection and report an accepted connection with
555 * reconnect_connected().
557 * - RECONNECT_DISCONNECT: The client should abort the current connection
558 * or connection attempt or listen attempt and call
559 * reconnect_disconnected() or reconnect_connect_failed() to indicate it.
561 * - RECONNECT_PROBE: The client should send some kind of request to the
562 * peer that will elicit a response, to ensure that the connection is
563 * indeed in working order. (This will only be returned if the "probe
564 * interval" is nonzero--see reconnect_set_probe_interval()).
566 enum reconnect_action
567 reconnect_run(struct reconnect *fsm, long long int now)
569 if (now >= reconnect_deadline__(fsm)) {
570 switch (fsm->state) {
575 return RECONNECT_CONNECT;
577 case S_CONNECT_IN_PROGRESS:
578 return RECONNECT_DISCONNECT;
581 VLOG_DBG("%s: idle %lld ms, sending inactivity probe", fsm->name,
582 now - MAX(fsm->last_received, fsm->state_entered));
583 reconnect_transition__(fsm, now, S_IDLE);
584 return RECONNECT_PROBE;
587 VLOG_ERR("%s: no response to inactivity probe after %.3g "
588 "seconds, disconnecting",
589 fsm->name, (now - fsm->state_entered) / 1000.0);
590 return RECONNECT_DISCONNECT;
593 return RECONNECT_DISCONNECT;
605 /* Causes the next call to poll_block() to wake up when reconnect_run() should
606 * be called on 'fsm'. */
608 reconnect_wait(struct reconnect *fsm, long long int now)
610 int timeout = reconnect_timeout(fsm, now);
612 poll_timer_wait(timeout);
616 /* Returns the number of milliseconds after which reconnect_run() should be
617 * called on 'fsm' if nothing else notable happens in the meantime, or a
618 * negative number if this is currently unnecessary. */
620 reconnect_timeout(struct reconnect *fsm, long long int now)
622 long long int deadline = reconnect_deadline__(fsm);
623 if (deadline != LLONG_MAX) {
624 long long int remaining = deadline - now;
625 return MAX(0, MIN(INT_MAX, remaining));
630 /* Returns true if 'fsm' is currently believed to be connected, that is, if
631 * reconnect_connected() was called more recently than any call to
632 * reconnect_connect_failed() or reconnect_disconnected() or
633 * reconnect_disable(), and false otherwise. */
635 reconnect_is_connected(const struct reconnect *fsm)
637 return is_connected_state(fsm->state);
640 /* Returns the number of milliseconds for which 'fsm' has been continuously
641 * connected to its peer. (If 'fsm' is not currently connected, this is 0.) */
643 reconnect_get_connection_duration(const struct reconnect *fsm,
646 return reconnect_is_connected(fsm) ? now - fsm->last_connected : 0;
649 /* Copies various statistics for 'fsm' into '*stats'. */
651 reconnect_get_stats(const struct reconnect *fsm, long long int now,
652 struct reconnect_stats *stats)
654 stats->creation_time = fsm->creation_time;
655 stats->last_received = fsm->last_received;
656 stats->last_connected = fsm->last_connected;
657 stats->backoff = fsm->backoff;
658 stats->seqno = fsm->seqno;
659 stats->is_connected = reconnect_is_connected(fsm);
660 stats->current_connection_duration
661 = reconnect_get_connection_duration(fsm, now);
662 stats->total_connected_duration = (stats->current_connection_duration
663 + fsm->total_connected_duration);
664 stats->n_attempted_connections = fsm->n_attempted_connections;
665 stats->n_successful_connections = fsm->n_successful_connections;
666 stats->state = reconnect_state_name__(fsm->state);
667 stats->state_elapsed = now - fsm->state_entered;
671 reconnect_may_retry(struct reconnect *fsm)
673 bool may_retry = fsm->max_tries > 0;
674 if (may_retry && fsm->max_tries != UINT_MAX) {