reconnect: Implement "passive mode".
[cascardo/ovs.git] / lib / reconnect.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
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:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <config.h>
18 #include "reconnect.h"
19
20 #include <assert.h>
21 #include <stdlib.h>
22
23 #include "poll-loop.h"
24
25 #define THIS_MODULE VLM_reconnect
26 #include "vlog.h"
27
28 #define STATES                                  \
29     STATE(VOID, 1 << 0)                         \
30     STATE(BACKOFF, 1 << 1)                      \
31     STATE(CONNECT_IN_PROGRESS, 1 << 3)          \
32     STATE(ACTIVE, 1 << 4)                       \
33     STATE(IDLE, 1 << 5)                         \
34     STATE(RECONNECT, 1 << 6)                    \
35     STATE(LISTENING, 1 << 7)
36 enum state {
37 #define STATE(NAME, VALUE) S_##NAME = VALUE,
38     STATES
39 #undef STATE
40 };
41
42 static bool
43 is_connected_state(enum state state)
44 {
45     return (state & (S_ACTIVE | S_IDLE)) != 0;
46 }
47
48 struct reconnect {
49     /* Configuration. */
50     char *name;
51     int min_backoff;
52     int max_backoff;
53     int probe_interval;
54     bool passive;
55
56     /* State. */
57     enum state state;
58     long long int state_entered;
59     int backoff;
60     long long int last_received;
61     long long int last_connected;
62     unsigned int max_tries;
63
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;
69     unsigned int seqno;
70 };
71
72 static void reconnect_transition__(struct reconnect *, long long int now,
73                                    enum state state);
74 static long long int reconnect_deadline__(const struct reconnect *);
75 static bool reconnect_may_retry(struct reconnect *);
76
77 static const char *
78 reconnect_state_name__(enum state state)
79 {
80     switch (state) {
81 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
82         STATES
83 #undef STATE
84     }
85     return "***ERROR***";
86 }
87
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. */
91 struct reconnect *
92 reconnect_create(long long int now)
93 {
94     struct reconnect *fsm = xzalloc(sizeof *fsm);
95
96     fsm->name = xstrdup("void");
97     fsm->min_backoff = 1000;
98     fsm->max_backoff = 8000;
99     fsm->probe_interval = 5000;
100     fsm->passive = false;
101
102     fsm->state = S_VOID;
103     fsm->state_entered = now;
104     fsm->backoff = 0;
105     fsm->last_received = now;
106     fsm->last_connected = now;
107     fsm->max_tries = UINT_MAX;
108     fsm->creation_time = now;
109
110     return fsm;
111 }
112
113 /* Frees 'fsm'. */
114 void
115 reconnect_destroy(struct reconnect *fsm)
116 {
117     if (fsm) {
118         free(fsm->name);
119         free(fsm);
120     }
121 }
122
123 /* Returns 'fsm''s name. */
124 const char *
125 reconnect_get_name(const struct reconnect *fsm)
126 {
127     return fsm->name;
128 }
129
130 /* Sets 'fsm''s name to 'name'.  If 'name' is null, then "void" is used
131  * instead.
132  *
133  * The name set for 'fsm' is used in log messages. */
134 void
135 reconnect_set_name(struct reconnect *fsm, const char *name)
136 {
137     free(fsm->name);
138     fsm->name = xstrdup(name ? name : "void");
139 }
140
141 /* Return the minimum number of milliseconds to back off between consecutive
142  * connection attempts.  The default is 1000 ms. */
143 int
144 reconnect_get_min_backoff(const struct reconnect *fsm)
145 {
146     return fsm->min_backoff;
147 }
148
149 /* Return the maximum number of milliseconds to back off between consecutive
150  * connection attempts.  The default is 8000 ms. */
151 int
152 reconnect_get_max_backoff(const struct reconnect *fsm)
153 {
154     return fsm->max_backoff;
155 }
156
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'. */
163 int
164 reconnect_get_probe_interval(const struct reconnect *fsm)
165 {
166     return fsm->probe_interval;
167 }
168
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
171  * of tries.
172  *
173  * After the number of tries has expired, the 'fsm' will disable itself
174  * instead of backing off and retrying. */
175 void
176 reconnect_set_max_tries(struct reconnect *fsm, unsigned int max_tries)
177 {
178     fsm->max_tries = max_tries;
179 }
180
181 /* Returns the current remaining number of connection attempts, UINT_MAX if
182  * the number is unlimited.  */
183 unsigned int
184 reconnect_get_max_tries(struct reconnect *fsm)
185 {
186     return fsm->max_tries;
187 }
188
189 /* Configures the backoff parameters for 'fsm'.  'min_backoff' is the minimum
190  * number of milliseconds, and 'max_backoff' is the maximum, between connection
191  * attempts.
192  *
193  * 'min_backoff' must be at least 1000, and 'max_backoff' must be greater than
194  * or equal to 'min_backoff'. */
195 void
196 reconnect_set_backoff(struct reconnect *fsm, int min_backoff, int max_backoff)
197 {
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;
202     }
203
204     if (fsm->state == S_BACKOFF && fsm->backoff > max_backoff) {
205         fsm->backoff = max_backoff;
206     }
207 }
208
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'.
215  *
216  * If 'probe_interval' is nonzero, then it will be forced to a value of at
217  * least 1000 ms. */
218 void
219 reconnect_set_probe_interval(struct reconnect *fsm, int probe_interval)
220 {
221     fsm->probe_interval = probe_interval ? MAX(1000, probe_interval) : 0;
222 }
223
224 /* Returns true if 'fsm' is in passive mode, false if 'fsm' is in active mode
225  * (the default). */
226 bool
227 reconnect_is_passive(const struct reconnect *fsm)
228 {
229     return fsm->passive;
230 }
231
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. */
235 void
236 reconnect_set_passive(struct reconnect *fsm, bool passive, long long int now)
237 {
238     if (fsm->passive != passive) {
239         fsm->passive = passive;
240
241         if (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);
245             fsm->backoff = 0;
246         }
247     }
248 }
249
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. */
254 bool
255 reconnect_is_enabled(const struct reconnect *fsm)
256 {
257     return fsm->state != S_VOID;
258 }
259
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
262  * RECONNECT_CONNECT.
263  *
264  * If 'fsm' is not disabled, this function has no effect. */
265 void
266 reconnect_enable(struct reconnect *fsm, long long int now)
267 {
268     if (fsm->state == S_VOID && reconnect_may_retry(fsm)) {
269         reconnect_transition__(fsm, now, S_BACKOFF);
270         fsm->backoff = 0;
271     }
272 }
273
274 /* Disables 'fsm'.  Until 'fsm' is enabled again, reconnect_run() will always
275  * return 0. */
276 void
277 reconnect_disable(struct reconnect *fsm, long long int now)
278 {
279     if (fsm->state != S_VOID) {
280         reconnect_transition__(fsm, now, S_VOID);
281     }
282 }
283
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. */
288 void
289 reconnect_force_reconnect(struct reconnect *fsm, long long int now)
290 {
291     if (fsm->state & (S_CONNECT_IN_PROGRESS | S_ACTIVE | S_IDLE)) {
292         reconnect_transition__(fsm, now, S_RECONNECT);
293     }
294 }
295
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.
300  *
301  * The FSM will back off, then reconnect. */
302 void
303 reconnect_disconnected(struct reconnect *fsm, long long int now, int error)
304 {
305     if (!(fsm->state & (S_BACKOFF | S_VOID))) {
306         /* Report what happened. */
307         if (fsm->state & (S_ACTIVE | S_IDLE)) {
308             if (error > 0) {
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);
313             } else {
314                 VLOG_INFO("%s: connection dropped", fsm->name);
315             }
316         } else if (fsm->state == S_LISTENING) {
317             if (error > 0) {
318                 VLOG_WARN("%s: error listening for connections (%s)",
319                           fsm->name, strerror(error));
320             } else {
321                 VLOG_INFO("%s: error listening for connections", fsm->name);
322             }
323         } else {
324             const char *type = fsm->passive ? "listen" : "connection";
325             if (error > 0) {
326                 VLOG_WARN("%s: %s attempt failed (%s)",
327                           fsm->name, type, strerror(error));
328             } else {
329                 VLOG_INFO("%s: %s attempt timed out", fsm->name, type);
330             }
331         }
332
333         /* Back off. */
334         if (fsm->state & (S_ACTIVE | S_IDLE)
335              && (fsm->last_received - fsm->last_connected >= fsm->backoff
336                  || fsm->passive)) {
337             fsm->backoff = fsm->passive ? 0 : fsm->min_backoff;
338         } else {
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;
343             } else {
344                 fsm->backoff *= 2;
345             }
346             if (fsm->passive) {
347                 VLOG_INFO("%s: waiting %.3g seconds before trying to "
348                           "listen again", fsm->name, fsm->backoff / 1000.0);
349             } else {
350                 VLOG_INFO("%s: waiting %.3g seconds before reconnect",
351                           fsm->name, fsm->backoff / 1000.0);
352             }
353         }
354
355         reconnect_transition__(fsm, now,
356                                reconnect_may_retry(fsm) ? S_BACKOFF : S_VOID);
357     }
358 }
359
360 /* Tell 'fsm' that a connection or listening attempt is in progress.
361  *
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()).  */
364 void
365 reconnect_connecting(struct reconnect *fsm, long long int now)
366 {
367     if (fsm->state != S_CONNECT_IN_PROGRESS) {
368         if (fsm->passive) {
369             VLOG_INFO("%s: listening...", fsm->name);
370         } else {
371             VLOG_INFO("%s: connecting...", fsm->name);
372         }
373         reconnect_transition__(fsm, now, S_CONNECT_IN_PROGRESS);
374     }
375 }
376
377 /* Tell 'fsm' that the client is listening for connection attempts.  This state
378  * last indefinitely until the client reports some change.
379  *
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().
383  *
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. */
388 void
389 reconnect_listening(struct reconnect *fsm, long long int now)
390 {
391     if (fsm->state != S_LISTENING) {
392         VLOG_INFO("%s: listening...", fsm->name);
393         reconnect_transition__(fsm, now, S_LISTENING);
394     }
395 }
396
397 /* Tell 'fsm' that the client's attempt to accept a connection failed
398  * (e.g. accept() returned an unexpected error such as ENOMEM).
399  *
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. */
404 void
405 reconnect_listen_error(struct reconnect *fsm, long long int now, int error)
406 {
407     if (fsm->state == S_LISTENING) {
408         reconnect_disconnected(fsm, now, error);
409     }
410 }
411
412 /* Tell 'fsm' that the connection was successful.
413  *
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()). */
419 void
420 reconnect_connected(struct reconnect *fsm, long long int now)
421 {
422     if (!is_connected_state(fsm->state)) {
423         reconnect_connecting(fsm, now);
424
425         VLOG_INFO("%s: connected", fsm->name);
426         reconnect_transition__(fsm, now, S_ACTIVE);
427         fsm->last_connected = now;
428     }
429 }
430
431 /* Tell 'fsm' that the connection attempt failed.
432  *
433  * The FSM will back off and attempt to reconnect. */
434 void
435 reconnect_connect_failed(struct reconnect *fsm, long long int now, int error)
436 {
437     reconnect_connecting(fsm, now);
438     reconnect_disconnected(fsm, now, error);
439 }
440
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. */
443 void
444 reconnect_received(struct reconnect *fsm, long long int now)
445 {
446     if (fsm->state != S_ACTIVE) {
447         reconnect_transition__(fsm, now, S_ACTIVE);
448     }
449     fsm->last_received = now;
450 }
451
452 static void
453 reconnect_transition__(struct reconnect *fsm, long long int now,
454                        enum state state)
455 {
456     if (fsm->state == S_CONNECT_IN_PROGRESS) {
457         fsm->n_attempted_connections++;
458         if (state == S_ACTIVE) {
459             fsm->n_successful_connections++;
460         }
461     }
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;
465         }
466         fsm->seqno++;
467     }
468
469     VLOG_DBG("%s: entering %s", fsm->name, reconnect_state_name__(state));
470     fsm->state = state;
471     fsm->state_entered = now;
472 }
473
474 static long long int
475 reconnect_deadline__(const struct reconnect *fsm)
476 {
477     assert(fsm->state_entered != LLONG_MIN);
478     switch (fsm->state) {
479     case S_VOID:
480     case S_LISTENING:
481         return LLONG_MAX;
482
483     case S_BACKOFF:
484         return fsm->state_entered + fsm->backoff;
485
486     case S_CONNECT_IN_PROGRESS:
487         return fsm->state_entered + MAX(1000, fsm->backoff);
488
489     case S_ACTIVE:
490         if (fsm->probe_interval) {
491             long long int base = MAX(fsm->last_received, fsm->state_entered);
492             return base + fsm->probe_interval;
493         }
494         return LLONG_MAX;
495
496     case S_IDLE:
497         return fsm->state_entered + fsm->probe_interval;
498
499     case S_RECONNECT:
500         return fsm->state_entered;
501     }
502
503     NOT_REACHED();
504 }
505
506 /* Assesses whether any action should be taken on 'fsm'.  The return value is
507  * one of:
508  *
509  *     - 0: The client need not take any action.
510  *
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().
516  *
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).
522  *
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.
528  *
529  *       A listening passive client should constantly attempt to accept a new
530  *       connection and report an accepted connection with
531  *       reconnect_connected().
532  *
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.
536  *
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()).
541  */
542 enum reconnect_action
543 reconnect_run(struct reconnect *fsm, long long int now)
544 {
545     if (now >= reconnect_deadline__(fsm)) {
546         switch (fsm->state) {
547         case S_VOID:
548             return 0;
549
550         case S_BACKOFF:
551             return RECONNECT_CONNECT;
552
553         case S_CONNECT_IN_PROGRESS:
554             return RECONNECT_DISCONNECT;
555
556         case S_ACTIVE:
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;
561
562         case S_IDLE:
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;
567
568         case S_RECONNECT:
569             return RECONNECT_DISCONNECT;
570
571         case S_LISTENING:
572             return 0;
573         }
574
575         NOT_REACHED();
576     } else {
577         return 0;
578     }
579 }
580
581 /* Causes the next call to poll_block() to wake up when reconnect_run() should
582  * be called on 'fsm'. */
583 void
584 reconnect_wait(struct reconnect *fsm, long long int now)
585 {
586     int timeout = reconnect_timeout(fsm, now);
587     if (timeout >= 0) {
588         poll_timer_wait(timeout);
589     }
590 }
591
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. */
595 int
596 reconnect_timeout(struct reconnect *fsm, long long int now)
597 {
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));
602     }
603     return -1;
604 }
605
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.  */
610 bool
611 reconnect_is_connected(const struct reconnect *fsm)
612 {
613     return is_connected_state(fsm->state);
614 }
615
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.) */
618 unsigned int
619 reconnect_get_connection_duration(const struct reconnect *fsm,
620                                   long long int now)
621 {
622     return reconnect_is_connected(fsm) ? now - fsm->last_connected : 0;
623 }
624
625 /* Copies various statistics for 'fsm' into '*stats'. */
626 void
627 reconnect_get_stats(const struct reconnect *fsm, long long int now,
628                     struct reconnect_stats *stats)
629 {
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;
644 }
645
646 static bool
647 reconnect_may_retry(struct reconnect *fsm)
648 {
649     bool may_retry = fsm->max_tries > 0;
650     if (may_retry && fsm->max_tries != UINT_MAX) {
651         fsm->max_tries--;
652     }
653     return may_retry;
654 }