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"
25 #define THIS_MODULE VLM_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;
58 long long int state_entered;
60 long long int last_received;
61 long long int last_connected;
62 unsigned int max_tries;
64 /* These values are simply for statistics reporting, not otherwise used
65 * directly by anything internal. */
66 long long int creation_time;
67 unsigned int n_attempted_connections, n_successful_connections;
68 unsigned int total_connected_duration;
72 static void reconnect_transition__(struct reconnect *, long long int now,
74 static long long int reconnect_deadline__(const struct reconnect *);
75 static bool reconnect_may_retry(struct reconnect *);
78 reconnect_state_name__(enum state state)
81 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
88 /* Creates and returns a new reconnect FSM with default settings. The FSM is
89 * initially disabled. The caller will likely want to call reconnect_enable()
90 * and reconnect_set_name() on the returned object. */
92 reconnect_create(long long int now)
94 struct reconnect *fsm = xzalloc(sizeof *fsm);
96 fsm->name = xstrdup("void");
97 fsm->min_backoff = 1000;
98 fsm->max_backoff = 8000;
99 fsm->probe_interval = 5000;
100 fsm->passive = false;
103 fsm->state_entered = now;
105 fsm->last_received = now;
106 fsm->last_connected = now;
107 fsm->max_tries = UINT_MAX;
108 fsm->creation_time = now;
115 reconnect_destroy(struct reconnect *fsm)
123 /* Returns 'fsm''s name. */
125 reconnect_get_name(const struct reconnect *fsm)
130 /* Sets 'fsm''s name to 'name'. If 'name' is null, then "void" is used
133 * The name set for 'fsm' is used in log messages. */
135 reconnect_set_name(struct reconnect *fsm, const char *name)
138 fsm->name = xstrdup(name ? name : "void");
141 /* Return the minimum number of milliseconds to back off between consecutive
142 * connection attempts. The default is 1000 ms. */
144 reconnect_get_min_backoff(const struct reconnect *fsm)
146 return fsm->min_backoff;
149 /* Return the maximum number of milliseconds to back off between consecutive
150 * connection attempts. The default is 8000 ms. */
152 reconnect_get_max_backoff(const struct reconnect *fsm)
154 return fsm->max_backoff;
157 /* Returns the "probe interval" for 'fsm' in milliseconds. If this is zero, it
158 * disables the connection keepalive feature. If it is nonzero, then if the
159 * interval passes while 'fsm' is connected and without reconnect_received()
160 * being called for 'fsm', reconnect_run() returns RECONNECT_PROBE. If the
161 * interval passes again without reconnect_received() being called,
162 * reconnect_run() returns RECONNECT_DISCONNECT for 'fsm'. */
164 reconnect_get_probe_interval(const struct reconnect *fsm)
166 return fsm->probe_interval;
169 /* Limits the maximum number of times that 'fsm' will ask the client to try to
170 * reconnect to 'max_tries'. UINT_MAX (the default) means an unlimited number
173 * After the number of tries has expired, the 'fsm' will disable itself
174 * instead of backing off and retrying. */
176 reconnect_set_max_tries(struct reconnect *fsm, unsigned int max_tries)
178 fsm->max_tries = max_tries;
181 /* Returns the current remaining number of connection attempts, UINT_MAX if
182 * the number is unlimited. */
184 reconnect_get_max_tries(struct reconnect *fsm)
186 return fsm->max_tries;
189 /* Configures the backoff parameters for 'fsm'. 'min_backoff' is the minimum
190 * number of milliseconds, and 'max_backoff' is the maximum, between connection
193 * 'min_backoff' must be at least 1000, and 'max_backoff' must be greater than
194 * or equal to 'min_backoff'. */
196 reconnect_set_backoff(struct reconnect *fsm, int min_backoff, int max_backoff)
198 fsm->min_backoff = MAX(min_backoff, 1000);
199 fsm->max_backoff = max_backoff ? MAX(max_backoff, 1000) : 8000;
200 if (fsm->min_backoff > fsm->max_backoff) {
201 fsm->max_backoff = fsm->min_backoff;
204 if (fsm->state == S_BACKOFF && fsm->backoff > max_backoff) {
205 fsm->backoff = max_backoff;
209 /* Sets the "probe interval" for 'fsm' to 'probe_interval', in milliseconds.
210 * If this is zero, it disables the connection keepalive feature. If it is
211 * nonzero, then if the interval passes while 'fsm' is connected and without
212 * reconnect_received() being called for 'fsm', reconnect_run() returns
213 * RECONNECT_PROBE. If the interval passes again without reconnect_received()
214 * being called, reconnect_run() returns RECONNECT_DISCONNECT for 'fsm'.
216 * If 'probe_interval' is nonzero, then it will be forced to a value of at
219 reconnect_set_probe_interval(struct reconnect *fsm, int probe_interval)
221 fsm->probe_interval = probe_interval ? MAX(1000, probe_interval) : 0;
224 /* Returns true if 'fsm' is in passive mode, false if 'fsm' is in active mode
227 reconnect_is_passive(const struct reconnect *fsm)
232 /* Configures 'fsm' for active or passive mode. In active mode (the default),
233 * the FSM is attempting to connect to a remote host. In passive mode, the FSM
234 * is listening for connections from a remote host. */
236 reconnect_set_passive(struct reconnect *fsm, bool passive, long long int now)
238 if (fsm->passive != passive) {
239 fsm->passive = passive;
242 ? fsm->state & (S_CONNECT_IN_PROGRESS | S_RECONNECT)
243 : fsm->state == S_LISTENING && reconnect_may_retry(fsm)) {
244 reconnect_transition__(fsm, now, S_BACKOFF);
250 /* Returns true if 'fsm' has been enabled with reconnect_enable(). Calling
251 * another function that indicates a change in connection state, such as
252 * reconnect_disconnected() or reconnect_force_reconnect(), will also enable
253 * a reconnect FSM. */
255 reconnect_is_enabled(const struct reconnect *fsm)
257 return fsm->state != S_VOID;
260 /* If 'fsm' is disabled (the default for newly created FSMs), enables it, so
261 * that the next call to reconnect_run() for 'fsm' will return
264 * If 'fsm' is not disabled, this function has no effect. */
266 reconnect_enable(struct reconnect *fsm, long long int now)
268 if (fsm->state == S_VOID && reconnect_may_retry(fsm)) {
269 reconnect_transition__(fsm, now, S_BACKOFF);
274 /* Disables 'fsm'. Until 'fsm' is enabled again, reconnect_run() will always
277 reconnect_disable(struct reconnect *fsm, long long int now)
279 if (fsm->state != S_VOID) {
280 reconnect_transition__(fsm, now, S_VOID);
284 /* If 'fsm' is enabled and currently connected (or attempting to connect),
285 * forces reconnect_run() for 'fsm' to return RECONNECT_DISCONNECT the next
286 * time it is called, which should cause the client to drop the connection (or
287 * attempt), back off, and then reconnect. */
289 reconnect_force_reconnect(struct reconnect *fsm, long long int now)
291 if (fsm->state & (S_CONNECT_IN_PROGRESS | S_ACTIVE | S_IDLE)) {
292 reconnect_transition__(fsm, now, S_RECONNECT);
296 /* Tell 'fsm' that the connection dropped or that a connection attempt failed.
297 * 'error' specifies the reason: a positive value represents an errno value,
298 * EOF indicates that the connection was closed by the peer (e.g. read()
299 * returned 0), and 0 indicates no specific error.
301 * The FSM will back off, then reconnect. */
303 reconnect_disconnected(struct reconnect *fsm, long long int now, int error)
305 if (!(fsm->state & (S_BACKOFF | S_VOID))) {
306 /* Report what happened. */
307 if (fsm->state & (S_ACTIVE | S_IDLE)) {
309 VLOG_WARN("%s: connection dropped (%s)",
310 fsm->name, strerror(error));
311 } else if (error == EOF) {
312 VLOG_INFO("%s: connection closed by peer", fsm->name);
314 VLOG_INFO("%s: connection dropped", fsm->name);
316 } else if (fsm->state == S_LISTENING) {
318 VLOG_WARN("%s: error listening for connections (%s)",
319 fsm->name, strerror(error));
321 VLOG_INFO("%s: error listening for connections", fsm->name);
324 const char *type = fsm->passive ? "listen" : "connection";
326 VLOG_WARN("%s: %s attempt failed (%s)",
327 fsm->name, type, strerror(error));
329 VLOG_INFO("%s: %s attempt timed out", fsm->name, type);
334 if (fsm->state & (S_ACTIVE | S_IDLE)
335 && (fsm->last_received - fsm->last_connected >= fsm->backoff
337 fsm->backoff = fsm->passive ? 0 : fsm->min_backoff;
339 if (fsm->backoff < fsm->min_backoff) {
340 fsm->backoff = fsm->min_backoff;
341 } else if (fsm->backoff >= fsm->max_backoff / 2) {
342 fsm->backoff = fsm->max_backoff;
347 VLOG_INFO("%s: waiting %.3g seconds before trying to "
348 "listen again", fsm->name, fsm->backoff / 1000.0);
350 VLOG_INFO("%s: waiting %.3g seconds before reconnect",
351 fsm->name, fsm->backoff / 1000.0);
355 reconnect_transition__(fsm, now,
356 reconnect_may_retry(fsm) ? S_BACKOFF : S_VOID);
360 /* Tell 'fsm' that a connection or listening attempt is in progress.
362 * The FSM will start a timer, after which the connection or listening attempt
363 * will be aborted (by returning RECONNECT_DISCONNECT from reconect_run()). */
365 reconnect_connecting(struct reconnect *fsm, long long int now)
367 if (fsm->state != S_CONNECT_IN_PROGRESS) {
369 VLOG_INFO("%s: listening...", fsm->name);
371 VLOG_INFO("%s: connecting...", fsm->name);
373 reconnect_transition__(fsm, now, S_CONNECT_IN_PROGRESS);
377 /* Tell 'fsm' that the client is listening for connection attempts. This state
378 * last indefinitely until the client reports some change.
380 * The natural progression from this state is for the client to report that a
381 * connection has been accepted or is in progress of being accepted, by calling
382 * reconnect_connecting() or reconnect_connected().
384 * The client may also report that listening failed (e.g. accept() returned an
385 * unexpected error such as ENOMEM) by calling reconnect_listen_error(), in
386 * which case the FSM will back off and eventually return RECONNECT_CONNECT
387 * from reconnect_run() to tell the client to try listening again. */
389 reconnect_listening(struct reconnect *fsm, long long int now)
391 if (fsm->state != S_LISTENING) {
392 VLOG_INFO("%s: listening...", fsm->name);
393 reconnect_transition__(fsm, now, S_LISTENING);
397 /* Tell 'fsm' that the client's attempt to accept a connection failed
398 * (e.g. accept() returned an unexpected error such as ENOMEM).
400 * If the FSM is currently listening (reconnect_listening() was called), it
401 * will back off and eventually return RECONNECT_CONNECT from reconnect_run()
402 * to tell the client to try listening again. If there is an active
403 * connection, this will be delayed until that connection drops. */
405 reconnect_listen_error(struct reconnect *fsm, long long int now, int error)
407 if (fsm->state == S_LISTENING) {
408 reconnect_disconnected(fsm, now, error);
412 /* Tell 'fsm' that the connection was successful.
414 * The FSM will start the probe interval timer, which is reset by
415 * reconnect_received(). If the timer expires, a probe will be sent (by
416 * returning RECONNECT_PROBE from reconnect_run()). If the timer expires
417 * again without being reset, the connection will be aborted (by returning
418 * RECONNECT_DISCONNECT from reconnect_run()). */
420 reconnect_connected(struct reconnect *fsm, long long int now)
422 if (!is_connected_state(fsm->state)) {
423 reconnect_connecting(fsm, now);
425 VLOG_INFO("%s: connected", fsm->name);
426 reconnect_transition__(fsm, now, S_ACTIVE);
427 fsm->last_connected = now;
431 /* Tell 'fsm' that the connection attempt failed.
433 * The FSM will back off and attempt to reconnect. */
435 reconnect_connect_failed(struct reconnect *fsm, long long int now, int error)
437 reconnect_connecting(fsm, now);
438 reconnect_disconnected(fsm, now, error);
441 /* Tell 'fsm' that some data was received. This resets the probe interval
442 * timer, so that the connection is known not to be idle. */
444 reconnect_received(struct reconnect *fsm, long long int now)
446 if (fsm->state != S_ACTIVE) {
447 reconnect_transition__(fsm, now, S_ACTIVE);
449 fsm->last_received = now;
453 reconnect_transition__(struct reconnect *fsm, long long int now,
456 if (fsm->state == S_CONNECT_IN_PROGRESS) {
457 fsm->n_attempted_connections++;
458 if (state == S_ACTIVE) {
459 fsm->n_successful_connections++;
462 if (is_connected_state(fsm->state) != is_connected_state(state)) {
463 if (is_connected_state(fsm->state)) {
464 fsm->total_connected_duration += now - fsm->last_connected;
469 VLOG_DBG("%s: entering %s", fsm->name, reconnect_state_name__(state));
471 fsm->state_entered = now;
475 reconnect_deadline__(const struct reconnect *fsm)
477 assert(fsm->state_entered != LLONG_MIN);
478 switch (fsm->state) {
484 return fsm->state_entered + fsm->backoff;
486 case S_CONNECT_IN_PROGRESS:
487 return fsm->state_entered + MAX(1000, fsm->backoff);
490 if (fsm->probe_interval) {
491 long long int base = MAX(fsm->last_received, fsm->state_entered);
492 return base + fsm->probe_interval;
497 return fsm->state_entered + fsm->probe_interval;
500 return fsm->state_entered;
506 /* Assesses whether any action should be taken on 'fsm'. The return value is
509 * - 0: The client need not take any action.
511 * - Active client, RECONNECT_CONNECT: The client should start a connection
512 * attempt and indicate this by calling reconnect_connecting(). If the
513 * connection attempt has definitely succeeded, it should call
514 * reconnect_connected(). If the connection attempt has definitely
515 * failed, it should call reconnect_connect_failed().
517 * The FSM is smart enough to back off correctly after successful
518 * connections that quickly abort, so it is OK to call
519 * reconnect_connected() after a low-level successful connection
520 * (e.g. connect()) even if the connection might soon abort due to a
521 * failure at a high-level (e.g. SSL negotiation failure).
523 * - Passive client, RECONNECT_CONNECT: The client should try to listen for
524 * a connection, if it is not already listening. It should call
525 * reconnect_listening() if successful, otherwise reconnect_connecting()
526 * or reconnected_connect_failed() if the attempt is in progress or
527 * definitely failed, respectively.
529 * A listening passive client should constantly attempt to accept a new
530 * connection and report an accepted connection with
531 * reconnect_connected().
533 * - RECONNECT_DISCONNECT: The client should abort the current connection
534 * or connection attempt or listen attempt and call
535 * reconnect_disconnected() or reconnect_connect_failed() to indicate it.
537 * - RECONNECT_PROBE: The client should send some kind of request to the
538 * peer that will elicit a response, to ensure that the connection is
539 * indeed in working order. (This will only be returned if the "probe
540 * interval" is nonzero--see reconnect_set_probe_interval()).
542 enum reconnect_action
543 reconnect_run(struct reconnect *fsm, long long int now)
545 if (now >= reconnect_deadline__(fsm)) {
546 switch (fsm->state) {
551 return RECONNECT_CONNECT;
553 case S_CONNECT_IN_PROGRESS:
554 return RECONNECT_DISCONNECT;
557 VLOG_DBG("%s: idle %lld ms, sending inactivity probe", fsm->name,
558 now - MAX(fsm->last_received, fsm->state_entered));
559 reconnect_transition__(fsm, now, S_IDLE);
560 return RECONNECT_PROBE;
563 VLOG_ERR("%s: no response to inactivity probe after %.3g "
564 "seconds, disconnecting",
565 fsm->name, (now - fsm->state_entered) / 1000.0);
566 return RECONNECT_DISCONNECT;
569 return RECONNECT_DISCONNECT;
581 /* Causes the next call to poll_block() to wake up when reconnect_run() should
582 * be called on 'fsm'. */
584 reconnect_wait(struct reconnect *fsm, long long int now)
586 int timeout = reconnect_timeout(fsm, now);
588 poll_timer_wait(timeout);
592 /* Returns the number of milliseconds after which reconnect_run() should be
593 * called on 'fsm' if nothing else notable happens in the meantime, or a
594 * negative number if this is currently unnecessary. */
596 reconnect_timeout(struct reconnect *fsm, long long int now)
598 long long int deadline = reconnect_deadline__(fsm);
599 if (deadline != LLONG_MAX) {
600 long long int remaining = deadline - now;
601 return MAX(0, MIN(INT_MAX, remaining));
606 /* Returns true if 'fsm' is currently believed to be connected, that is, if
607 * reconnect_connected() was called more recently than any call to
608 * reconnect_connect_failed() or reconnect_disconnected() or
609 * reconnect_disable(), and false otherwise. */
611 reconnect_is_connected(const struct reconnect *fsm)
613 return is_connected_state(fsm->state);
616 /* Returns the number of milliseconds for which 'fsm' has been continuously
617 * connected to its peer. (If 'fsm' is not currently connected, this is 0.) */
619 reconnect_get_connection_duration(const struct reconnect *fsm,
622 return reconnect_is_connected(fsm) ? now - fsm->last_connected : 0;
625 /* Copies various statistics for 'fsm' into '*stats'. */
627 reconnect_get_stats(const struct reconnect *fsm, long long int now,
628 struct reconnect_stats *stats)
630 stats->creation_time = fsm->creation_time;
631 stats->last_received = fsm->last_received;
632 stats->last_connected = fsm->last_connected;
633 stats->backoff = fsm->backoff;
634 stats->seqno = fsm->seqno;
635 stats->is_connected = reconnect_is_connected(fsm);
636 stats->current_connection_duration
637 = reconnect_get_connection_duration(fsm, now);
638 stats->total_connected_duration = (stats->current_connection_duration
639 + fsm->total_connected_duration);
640 stats->n_attempted_connections = fsm->n_attempted_connections;
641 stats->n_successful_connections = fsm->n_successful_connections;
642 stats->state = reconnect_state_name__(fsm->state);
643 stats->state_elapsed = now - fsm->state_entered;
647 reconnect_may_retry(struct reconnect *fsm)
649 bool may_retry = fsm->max_tries > 0;
650 if (may_retry && fsm->max_tries != UINT_MAX) {