Merge "master" into "next".
[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(START_CONNECT, 1 << 2)                \
32     STATE(CONNECT_IN_PROGRESS, 1 << 3)          \
33     STATE(ACTIVE, 1 << 4)                       \
34     STATE(IDLE, 1 << 5)                         \
35     STATE(RECONNECT, 1 << 6)
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
55     /* State. */
56     enum state state;
57     long long int state_entered;
58     int backoff;
59     long long int last_received;
60     long long int last_connected;
61     unsigned int max_tries;
62
63     /* These values are simply for statistics reporting, not otherwise used
64      * directly by anything internal. */
65     long long int creation_time;
66     unsigned int n_attempted_connections, n_successful_connections;
67     unsigned int total_connected_duration;
68     unsigned int seqno;
69 };
70
71 static void reconnect_transition__(struct reconnect *, long long int now,
72                                    enum state state);
73 static long long int reconnect_deadline__(const struct reconnect *);
74 static bool reconnect_may_retry(struct reconnect *);
75
76 static const char *
77 reconnect_state_name__(enum state state)
78 {
79     switch (state) {
80 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
81         STATES
82 #undef STATE
83     }
84     return "***ERROR***";
85 }
86
87 /* Creates and returns a new reconnect FSM with default settings.  The FSM is
88  * initially disabled.  The caller will likely want to call reconnect_enable()
89  * and reconnect_set_name() on the returned object. */
90 struct reconnect *
91 reconnect_create(long long int now)
92 {
93     struct reconnect *fsm = xzalloc(sizeof *fsm);
94
95     fsm->name = xstrdup("void");
96     fsm->min_backoff = 1000;
97     fsm->max_backoff = 8000;
98     fsm->probe_interval = 5000;
99
100     fsm->state = S_VOID;
101     fsm->state_entered = now;
102     fsm->backoff = 0;
103     fsm->last_received = now;
104     fsm->last_connected = now;
105     fsm->max_tries = UINT_MAX;
106     fsm->creation_time = now;
107
108     return fsm;
109 }
110
111 /* Frees 'fsm'. */
112 void
113 reconnect_destroy(struct reconnect *fsm)
114 {
115     if (fsm) {
116         free(fsm->name);
117         free(fsm);
118     }
119 }
120
121 /* Returns 'fsm''s name. */
122 const char *
123 reconnect_get_name(const struct reconnect *fsm)
124 {
125     return fsm->name;
126 }
127
128 /* Sets 'fsm''s name to 'name'.  If 'name' is null, then "void" is used
129  * instead.
130  *
131  * The name set for 'fsm' is used in log messages. */
132 void
133 reconnect_set_name(struct reconnect *fsm, const char *name)
134 {
135     free(fsm->name);
136     fsm->name = xstrdup(name ? name : "void");
137 }
138
139 /* Return the minimum number of milliseconds to back off between consecutive
140  * connection attempts.  The default is 1000 ms. */
141 int
142 reconnect_get_min_backoff(const struct reconnect *fsm)
143 {
144     return fsm->min_backoff;
145 }
146
147 /* Return the maximum number of milliseconds to back off between consecutive
148  * connection attempts.  The default is 8000 ms. */
149 int
150 reconnect_get_max_backoff(const struct reconnect *fsm)
151 {
152     return fsm->max_backoff;
153 }
154
155 /* Returns the "probe interval" for 'fsm' in milliseconds.  If this is zero, it
156  * disables the connection keepalive feature.  If it is nonzero, then if the
157  * interval passes while 'fsm' is connected and without reconnect_received()
158  * being called for 'fsm', reconnect_run() returns RECONNECT_PROBE.  If the
159  * interval passes again without reconnect_received() being called,
160  * reconnect_run() returns RECONNECT_DISCONNECT for 'fsm'. */
161 int
162 reconnect_get_probe_interval(const struct reconnect *fsm)
163 {
164     return fsm->probe_interval;
165 }
166
167 /* Limits the maximum number of times that 'fsm' will ask the client to try to
168  * reconnect to 'max_tries'.  UINT_MAX (the default) means an unlimited number
169  * of tries.
170  *
171  * After the number of tries has expired, the 'fsm' will disable itself
172  * instead of backing off and retrying. */
173 void
174 reconnect_set_max_tries(struct reconnect *fsm, unsigned int max_tries)
175 {
176     fsm->max_tries = max_tries;
177 }
178
179 /* Returns the current remaining number of connection attempts, UINT_MAX if
180  * the number is unlimited.  */
181 unsigned int
182 reconnect_get_max_tries(struct reconnect *fsm)
183 {
184     return fsm->max_tries;
185 }
186
187 /* Configures the backoff parameters for 'fsm'.  'min_backoff' is the minimum
188  * number of milliseconds, and 'max_backoff' is the maximum, between connection
189  * attempts.
190  *
191  * 'min_backoff' must be at least 1000, and 'max_backoff' must be greater than
192  * or equal to 'min_backoff'. */
193 void
194 reconnect_set_backoff(struct reconnect *fsm, int min_backoff, int max_backoff)
195 {
196     fsm->min_backoff = MAX(min_backoff, 1000);
197     fsm->max_backoff = max_backoff ? MAX(max_backoff, 1000) : 8000;
198     if (fsm->min_backoff > fsm->max_backoff) {
199         fsm->max_backoff = fsm->min_backoff;
200     }
201
202     if (fsm->state == S_BACKOFF && fsm->backoff > max_backoff) {
203         fsm->backoff = max_backoff;
204     }
205 }
206
207 /* Sets the "probe interval" for 'fsm' to 'probe_interval', in milliseconds.
208  * If this is zero, it disables the connection keepalive feature.  If it is
209  * nonzero, then if the interval passes while 'fsm' is connected and without
210  * reconnect_received() being called for 'fsm', reconnect_run() returns
211  * RECONNECT_PROBE.  If the interval passes again without reconnect_received()
212  * being called, reconnect_run() returns RECONNECT_DISCONNECT for 'fsm'.
213  *
214  * If 'probe_interval' is nonzero, then it will be forced to a value of at
215  * least 1000 ms. */
216 void
217 reconnect_set_probe_interval(struct reconnect *fsm, int probe_interval)
218 {
219     fsm->probe_interval = probe_interval ? MAX(1000, probe_interval) : 0;
220 }
221
222 /* Returns true if 'fsm' has been enabled with reconnect_enable().  Calling
223  * another function that indicates a change in connection state, such as
224  * reconnect_disconnected() or reconnect_force_reconnect(), will also enable
225  * a reconnect FSM. */
226 bool
227 reconnect_is_enabled(const struct reconnect *fsm)
228 {
229     return fsm->state != S_VOID;
230 }
231
232 /* If 'fsm' is disabled (the default for newly created FSMs), enables it, so
233  * that the next call to reconnect_run() for 'fsm' will return
234  * RECONNECT_CONNECT.
235  *
236  * If 'fsm' is not disabled, this function has no effect. */
237 void
238 reconnect_enable(struct reconnect *fsm, long long int now)
239 {
240     if (fsm->state == S_VOID && reconnect_may_retry(fsm)) {
241         reconnect_transition__(fsm, now, S_BACKOFF);
242         fsm->backoff = 0;
243     }
244 }
245
246 /* Disables 'fsm'.  Until 'fsm' is enabled again, reconnect_run() will always
247  * return 0. */
248 void
249 reconnect_disable(struct reconnect *fsm, long long int now)
250 {
251     if (fsm->state != S_VOID) {
252         reconnect_transition__(fsm, now, S_VOID);
253     }
254 }
255
256 /* If 'fsm' is enabled and currently connected (or attempting to connect),
257  * forces reconnect_run() for 'fsm' to return RECONNECT_DISCONNECT the next
258  * time it is called, which should cause the client to drop the connection (or
259  * attempt), back off, and then reconnect. */
260 void
261 reconnect_force_reconnect(struct reconnect *fsm, long long int now)
262 {
263     if (fsm->state & (S_START_CONNECT | S_CONNECT_IN_PROGRESS
264                       | S_ACTIVE | S_IDLE)) {
265         reconnect_transition__(fsm, now, S_RECONNECT);
266     }
267 }
268
269 /* Tell 'fsm' that the connection dropped or that a connection attempt failed.
270  * 'error' specifies the reason: a positive value represents an errno value,
271  * EOF indicates that the connection was closed by the peer (e.g. read()
272  * returned 0), and 0 indicates no specific error.
273  *
274  * The FSM will back off, then reconnect. */
275 void
276 reconnect_disconnected(struct reconnect *fsm, long long int now, int error)
277 {
278     if (!(fsm->state & (S_BACKOFF | S_VOID))) {
279         /* Report what happened. */
280         if (fsm->state & (S_ACTIVE | S_IDLE)) {
281             if (error > 0) {
282                 VLOG_WARN("%s: connection dropped (%s)",
283                           fsm->name, strerror(error));
284             } else if (error == EOF) {
285                 VLOG_INFO("%s: connection closed by peer", fsm->name);
286             } else {
287                 VLOG_INFO("%s: connection dropped", fsm->name);
288             }
289         } else {
290             if (error > 0) {
291                 VLOG_WARN("%s: connection attempt failed (%s)",
292                           fsm->name, strerror(error));
293             } else {
294                 VLOG_INFO("%s: connection attempt timed out", fsm->name);
295             }
296         }
297
298         /* Back off. */
299         if (fsm->state & (S_ACTIVE | S_IDLE)
300             && fsm->last_received - fsm->last_connected >= fsm->backoff) {
301             fsm->backoff = fsm->min_backoff;
302         } else {
303             if (fsm->backoff < fsm->min_backoff) {
304                 fsm->backoff = fsm->min_backoff;
305             } else if (fsm->backoff >= fsm->max_backoff / 2) {
306                 fsm->backoff = fsm->max_backoff;
307             } else {
308                 fsm->backoff *= 2;
309             }
310             VLOG_INFO("%s: waiting %.3g seconds before reconnect\n",
311                       fsm->name, fsm->backoff / 1000.0);
312         }
313
314         reconnect_transition__(fsm, now,
315                                reconnect_may_retry(fsm) ? S_BACKOFF : S_VOID);
316     }
317 }
318
319 /* Tell 'fsm' that a connection attempt is in progress.
320  *
321  * The FSM will start a timer, after which the connection attempt will be
322  * aborted (by returning RECONNECT_DISCONNECT from reconect_run()).  */
323 void
324 reconnect_connecting(struct reconnect *fsm, long long int now)
325 {
326     if (fsm->state != S_CONNECT_IN_PROGRESS) {
327         VLOG_INFO("%s: connecting...", fsm->name);
328         reconnect_transition__(fsm, now, S_CONNECT_IN_PROGRESS);
329     }
330 }
331
332 /* Tell 'fsm' that the connection was successful.
333  *
334  * The FSM will start the probe interval timer, which is reset by
335  * reconnect_received().  If the timer expires, a probe will be sent (by
336  * returning RECONNECT_PROBE from reconnect_run()).  If the timer expires
337  * again without being reset, the connection will be aborted (by returning
338  * RECONNECT_DISCONNECT from reconnect_run()). */
339 void
340 reconnect_connected(struct reconnect *fsm, long long int now)
341 {
342     if (!is_connected_state(fsm->state)) {
343         reconnect_connecting(fsm, now);
344
345         VLOG_INFO("%s: connected", fsm->name);
346         reconnect_transition__(fsm, now, S_ACTIVE);
347         fsm->last_connected = now;
348     }
349 }
350
351 /* Tell 'fsm' that the connection attempt failed.
352  *
353  * The FSM will back off and attempt to reconnect. */
354 void
355 reconnect_connect_failed(struct reconnect *fsm, long long int now, int error)
356 {
357     reconnect_connecting(fsm, now);
358     reconnect_disconnected(fsm, now, error);
359 }
360
361 /* Tell 'fsm' that some data was received.  This resets the probe interval
362  * timer, so that the connection is known not to be idle. */
363 void
364 reconnect_received(struct reconnect *fsm, long long int now)
365 {
366     if (fsm->state != S_ACTIVE) {
367         reconnect_transition__(fsm, now, S_ACTIVE);
368     }
369     fsm->last_received = now;
370 }
371
372 static void
373 reconnect_transition__(struct reconnect *fsm, long long int now,
374                        enum state state)
375 {
376     if (fsm->state == S_CONNECT_IN_PROGRESS) {
377         fsm->n_attempted_connections++;
378         if (state == S_ACTIVE) {
379             fsm->n_successful_connections++;
380         }
381     }
382     if (is_connected_state(fsm->state) != is_connected_state(state)) {
383         if (is_connected_state(fsm->state)) {
384             fsm->total_connected_duration += now - fsm->last_connected;
385         }
386         fsm->seqno++;
387     }
388
389     VLOG_DBG("%s: entering %s", fsm->name, reconnect_state_name__(state));
390     fsm->state = state;
391     fsm->state_entered = now;
392 }
393
394 static long long int
395 reconnect_deadline__(const struct reconnect *fsm)
396 {
397     assert(fsm->state_entered != LLONG_MIN);
398     switch (fsm->state) {
399     case S_VOID:
400         return LLONG_MAX;
401
402     case S_BACKOFF:
403         return fsm->state_entered + fsm->backoff;
404
405     case S_START_CONNECT:
406     case S_CONNECT_IN_PROGRESS:
407         return fsm->state_entered + MAX(1000, fsm->backoff);
408
409     case S_ACTIVE:
410         if (fsm->probe_interval) {
411             long long int base = MAX(fsm->last_received, fsm->state_entered);
412             return base + fsm->probe_interval;
413         }
414         return LLONG_MAX;
415
416     case S_IDLE:
417         return fsm->state_entered + fsm->probe_interval;
418
419     case S_RECONNECT:
420         return fsm->state_entered;
421     }
422
423     NOT_REACHED();
424 }
425
426 /* Assesses whether any action should be taken on 'fsm'.  The return value is
427  * one of:
428  *
429  *     - 0: The client need not take any action.
430  *
431  *     - RECONNECT_CONNECT: The client should start a connection attempt and
432  *       indicate this by calling reconnect_connecting().  If the connection
433  *       attempt has definitely succeeded, it should call
434  *       reconnect_connected().  If the connection attempt has definitely
435  *       failed, it should call reconnect_connect_failed().
436  *
437  *       The FSM is smart enough to back off correctly after successful
438  *       connections that quickly abort, so it is OK to call
439  *       reconnect_connected() after a low-level successful connection
440  *       (e.g. connect()) even if the connection might soon abort due to a
441  *       failure at a high-level (e.g. SSL negotiation failure).
442  *
443  *     - RECONNECT_DISCONNECT: The client should abort the current connection
444  *       or connection attempt and call reconnect_disconnected() or
445  *       reconnect_connect_failed() to indicate it.
446  *
447  *     - RECONNECT_PROBE: The client should send some kind of request to the
448  *       peer that will elicit a response, to ensure that the connection is
449  *       indeed in working order.  (This will only be returned if the "probe
450  *       interval" is nonzero--see reconnect_set_probe_interval()).
451  */
452 enum reconnect_action
453 reconnect_run(struct reconnect *fsm, long long int now)
454 {
455     if (now >= reconnect_deadline__(fsm)) {
456         switch (fsm->state) {
457         case S_VOID:
458             return 0;
459
460         case S_BACKOFF:
461             return RECONNECT_CONNECT;
462
463         case S_START_CONNECT:
464         case S_CONNECT_IN_PROGRESS:
465             return RECONNECT_DISCONNECT;
466
467         case S_ACTIVE:
468             VLOG_DBG("%s: idle %lld ms, sending inactivity probe", fsm->name,
469                      now - MAX(fsm->last_received, fsm->state_entered));
470             reconnect_transition__(fsm, now, S_IDLE);
471             return RECONNECT_PROBE;
472
473         case S_IDLE:
474             VLOG_ERR("%s: no response to inactivity probe after %.3g "
475                      "seconds, disconnecting",
476                      fsm->name, (now - fsm->state_entered) / 1000.0);
477             return RECONNECT_DISCONNECT;
478
479         case S_RECONNECT:
480             return RECONNECT_DISCONNECT;
481         }
482
483         NOT_REACHED();
484     } else {
485         return fsm->state == S_START_CONNECT ? RECONNECT_CONNECT : 0;
486     }
487 }
488
489 /* Causes the next call to poll_block() to wake up when reconnect_run() should
490  * be called on 'fsm'. */
491 void
492 reconnect_wait(struct reconnect *fsm, long long int now)
493 {
494     int timeout = reconnect_timeout(fsm, now);
495     if (timeout >= 0) {
496         poll_timer_wait(timeout);
497     }
498 }
499
500 /* Returns the number of milliseconds after which reconnect_run() should be
501  * called on 'fsm' if nothing else notable happens in the meantime, or a
502  * negative number if this is currently unnecessary. */
503 int
504 reconnect_timeout(struct reconnect *fsm, long long int now)
505 {
506     long long int deadline = reconnect_deadline__(fsm);
507     if (deadline != LLONG_MAX) {
508         long long int remaining = deadline - now;
509         return MAX(0, MIN(INT_MAX, remaining));
510     }
511     return -1;
512 }
513
514 /* Returns true if 'fsm' is currently believed to be connected, that is, if
515  * reconnect_connected() was called more recently than any call to
516  * reconnect_connect_failed() or reconnect_disconnected() or
517  * reconnect_disable(), and false otherwise.  */
518 bool
519 reconnect_is_connected(const struct reconnect *fsm)
520 {
521     return is_connected_state(fsm->state);
522 }
523
524 /* Returns the number of milliseconds for which 'fsm' has been continuously
525  * connected to its peer.  (If 'fsm' is not currently connected, this is 0.) */
526 unsigned int
527 reconnect_get_connection_duration(const struct reconnect *fsm,
528                                   long long int now)
529 {
530     return reconnect_is_connected(fsm) ? now - fsm->last_connected : 0;
531 }
532
533 /* Copies various statistics for 'fsm' into '*stats'. */
534 void
535 reconnect_get_stats(const struct reconnect *fsm, long long int now,
536                     struct reconnect_stats *stats)
537 {
538     stats->creation_time = fsm->creation_time;
539     stats->last_received = fsm->last_received;
540     stats->last_connected = fsm->last_connected;
541     stats->backoff = fsm->backoff;
542     stats->seqno = fsm->seqno;
543     stats->is_connected = reconnect_is_connected(fsm);
544     stats->current_connection_duration
545         = reconnect_get_connection_duration(fsm, now);
546     stats->total_connected_duration = (stats->current_connection_duration
547                                        + fsm->total_connected_duration);
548     stats->n_attempted_connections = fsm->n_attempted_connections;
549     stats->n_successful_connections = fsm->n_successful_connections;
550     stats->state = reconnect_state_name__(fsm->state);
551     stats->state_elapsed = now - fsm->state_entered;
552 }
553
554 static bool
555 reconnect_may_retry(struct reconnect *fsm)
556 {
557     bool may_retry = fsm->max_tries > 0;
558     if (may_retry && fsm->max_tries != UINT_MAX) {
559         fsm->max_tries--;
560     }
561     return may_retry;
562 }