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