rconn: Rewrite to use explicit state machine.
[sliver-openvswitch.git] / lib / rconn.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  *
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  *
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include "rconn.h"
35 #include <assert.h>
36 #include <errno.h>
37 #include <limits.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include "buffer.h"
41 #include "poll-loop.h"
42 #include "ofp-print.h"
43 #include "timeval.h"
44 #include "util.h"
45 #include "vconn.h"
46
47 #define THIS_MODULE VLM_rconn
48 #include "vlog.h"
49
50 #define STATES                                  \
51     STATE(VOID, 1 << 0)                         \
52     STATE(BACKOFF, 1 << 1)                      \
53     STATE(CONNECTING, 1 << 2)                   \
54     STATE(ACTIVE, 1 << 3)                       \
55     STATE(IDLE, 1 << 4)
56 enum state {
57 #define STATE(NAME, VALUE) S_##NAME = VALUE,
58     STATES
59 #undef STATE
60 };
61
62 static const char *
63 state_name(enum state state)
64 {
65     switch (state) {
66 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
67         STATES
68 #undef STATE
69     }
70     return "***ERROR***";
71 }
72
73 /* A reliable connection to an OpenFlow switch or controller.
74  *
75  * See the large comment in rconn.h for more information. */
76 struct rconn {
77     enum state state;
78     time_t state_entered;
79     unsigned int min_timeout;
80
81     struct vconn *vconn;
82     char *name;
83     bool reliable;
84
85     struct queue txq;
86     int txq_limit;
87
88     int backoff;
89     int max_backoff;
90     time_t backoff_deadline;
91     time_t last_received;
92     time_t last_connected;
93
94     unsigned int packets_sent;
95
96     /* Throughout this file, "probe" is shorthand for "inactivity probe".
97      * When nothing has been received from the peer for a while, we send out
98      * an echo request as an inactivity probe packet.  We should receive back
99      * a response. */
100     int probe_interval;         /* Secs of inactivity before sending probe. */
101 };
102
103 static unsigned int sat_add(unsigned int x, unsigned int y);
104 static unsigned int sat_mul(unsigned int x, unsigned int y);
105 static unsigned int elapsed_in_this_state(const struct rconn *);
106 static bool timeout(struct rconn *, unsigned int secs);
107 static void state_transition(struct rconn *, enum state);
108 static int try_send(struct rconn *);
109 static void reconnect(struct rconn *);
110 static void disconnect(struct rconn *, int error);
111
112 /* Creates a new rconn, connects it (reliably) to 'name', and returns it. */
113 struct rconn *
114 rconn_new(const char *name, int txq_limit, int inactivity_probe_interval,
115           int max_backoff) 
116 {
117     struct rconn *rc = rconn_create(txq_limit, inactivity_probe_interval,
118                                     max_backoff);
119     rconn_connect(rc, name);
120     return rc;
121 }
122
123 /* Creates a new rconn, connects it (unreliably) to 'vconn', and returns it. */
124 struct rconn *
125 rconn_new_from_vconn(const char *name, int txq_limit, struct vconn *vconn) 
126 {
127     struct rconn *rc = rconn_create(txq_limit, 60, 0);
128     rconn_connect_unreliably(rc, name, vconn);
129     return rc;
130 }
131
132 /* Creates and returns a new rconn.
133  *
134  * 'txq_limit' is the maximum length of the send queue, in packets.
135  *
136  * 'probe_interval' is a number of seconds.  If the interval passes once
137  * without an OpenFlow message being received from the peer, the rconn sends
138  * out an "echo request" message.  If the interval passes again without a
139  * message being received, the rconn disconnects and re-connects to the peer.
140  * Setting 'probe_interval' to 0 disables this behavior.
141  *
142  * 'max_backoff' is the maximum number of seconds between attempts to connect
143  * to the peer.  The actual interval starts at 1 second and doubles on each
144  * failure until it reaches 'max_backoff'.  If 0 is specified, the default of
145  * 60 seconds is used. */
146 struct rconn *
147 rconn_create(int txq_limit, int probe_interval, int max_backoff)
148 {
149     struct rconn *rc = xcalloc(1, sizeof *rc);
150
151     rc->state = S_VOID;
152     rc->state_entered = time(0);
153     rc->min_timeout = 0;
154
155     rc->vconn = NULL;
156     rc->name = xstrdup("void");
157     rc->reliable = false;
158
159     queue_init(&rc->txq);
160     assert(txq_limit > 0);
161     rc->txq_limit = txq_limit;
162
163     rc->backoff = 0;
164     rc->max_backoff = max_backoff ? max_backoff : 60;
165     rc->backoff_deadline = TIME_MIN;
166     rc->last_received = time(0);
167     rc->last_connected = time(0);
168
169     rc->packets_sent = 0;
170
171     rc->probe_interval = probe_interval ? MAX(5, probe_interval) : 0;
172
173     return rc;
174 }
175
176 void
177 rconn_connect(struct rconn *rc, const char *name)
178 {
179     rconn_disconnect(rc);
180     free(rc->name);
181     rc->name = xstrdup(name);
182     rc->reliable = true;
183     reconnect(rc);
184 }
185
186 void
187 rconn_connect_unreliably(struct rconn *rc,
188                          const char *name, struct vconn *vconn)
189 {
190     assert(vconn != NULL);
191     rconn_disconnect(rc);
192     free(rc->name);
193     rc->name = xstrdup(name);
194     rc->reliable = false;
195     rc->vconn = vconn;
196     rc->last_connected = time(0);
197     state_transition(rc, S_ACTIVE);
198 }
199
200 void
201 rconn_disconnect(struct rconn *rc)
202 {
203     if (rc->vconn) {
204         vconn_close(rc->vconn);
205         rc->vconn = NULL;
206     }
207     free(rc->name);
208     rc->name = xstrdup("void");
209     rc->reliable = false;
210
211     rc->backoff = 0;
212     rc->backoff_deadline = TIME_MIN;
213
214     state_transition(rc, S_VOID);
215 }
216
217 /* Disconnects 'rc' and frees the underlying storage. */
218 void
219 rconn_destroy(struct rconn *rc)
220 {
221     if (rc) {
222         free(rc->name);
223         vconn_close(rc->vconn);
224         queue_destroy(&rc->txq);
225         free(rc);
226     }
227 }
228
229 static void
230 run_VOID(struct rconn *rc)
231 {
232     /* Nothing to do. */
233 }
234
235 static void
236 reconnect(struct rconn *rc)
237 {
238     int retval;
239
240     VLOG_WARN("%s: connecting...", rc->name);
241     retval = vconn_open(rc->name, &rc->vconn);
242     if (!retval) {
243         rc->backoff_deadline = time(0) + rc->backoff;
244         state_transition(rc, S_CONNECTING);
245     } else {
246         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
247         disconnect(rc, 0);
248     }
249 }
250
251 static void
252 run_BACKOFF(struct rconn *rc)
253 {
254     if (timeout(rc, rc->backoff)) {
255         reconnect(rc);
256     }
257 }
258
259 static void
260 run_CONNECTING(struct rconn *rc)
261 {
262     int error = vconn_connect(rc->vconn);
263     if (!error) {
264         VLOG_WARN("%s: connected", rc->name);
265         if (vconn_is_passive(rc->vconn)) {
266             fatal(0, "%s: passive vconn not supported in switch",
267                   rc->name);
268         }
269         state_transition(rc, S_ACTIVE);
270         rc->last_connected = rc->state_entered;
271     } else if (error != EAGAIN) {
272         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(error));
273         disconnect(rc, error);
274     } else if (timeout(rc, MAX(1, rc->backoff))) {
275         VLOG_WARN("%s: connection timed out", rc->name);
276         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
277         disconnect(rc, 0);
278     }
279 }
280
281 static void
282 do_tx_work(struct rconn *rc)
283 {
284     while (rc->txq.n > 0) {
285         int error = try_send(rc);
286         if (error) {
287             break;
288         }
289     }
290 }
291
292 static void
293 run_ACTIVE(struct rconn *rc)
294 {
295     if (rc->probe_interval) {
296         unsigned int base = MAX(rc->last_received, rc->state_entered);
297         unsigned int arg = base + rc->probe_interval - rc->state_entered;
298         if (timeout(rc, arg)) {
299             queue_push_tail(&rc->txq, make_echo_request());
300             VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
301                      rc->name, (unsigned int) (time(0) - base));
302             state_transition(rc, S_IDLE);
303             return;
304         }
305     }
306
307     do_tx_work(rc);
308 }
309
310 static void
311 run_IDLE(struct rconn *rc)
312 {
313     if (timeout(rc, rc->probe_interval)) {
314         VLOG_ERR("%s: no response to inactivity probe after %u "
315                  "seconds, disconnecting",
316                  rc->name, elapsed_in_this_state(rc));
317         disconnect(rc, 0);
318     } else {
319         do_tx_work(rc);
320     }
321 }
322
323 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
324  * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
325  * connected, attempts to send packets in the send queue, if any. */
326 void
327 rconn_run(struct rconn *rc)
328 {
329     int old_state;
330     do {
331         old_state = rc->state;
332         rc->min_timeout = UINT_MAX;
333         switch (rc->state) {
334 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
335             STATES
336 #undef STATE
337         default:
338             NOT_REACHED();
339         }
340     } while (rc->state != old_state);
341 }
342
343 /* Causes the next call to poll_block() to wake up when rconn_run() should be
344  * called on 'rc'. */
345 void
346 rconn_run_wait(struct rconn *rc)
347 {
348     if (rc->min_timeout != UINT_MAX) {
349         poll_timer_wait(sat_mul(rc->min_timeout, 1000));
350     }
351     /* Reset timeout to 1 second.  This will have no effect ordinarily, because
352      * rconn_run() will typically set it back to a higher value.  If, however,
353      * the caller fails to call rconn_run() before its next call to
354      * rconn_wait() we won't potentially block forever. */
355     rc->min_timeout = 1;
356
357     if ((rc->state & (S_ACTIVE | S_IDLE)) && rc->txq.n) {
358         vconn_wait(rc->vconn, WAIT_SEND);
359     }
360 }
361
362 /* Attempts to receive a packet from 'rc'.  If successful, returns the packet;
363  * otherwise, returns a null pointer.  The caller is responsible for freeing
364  * the packet (with buffer_delete()). */
365 struct buffer *
366 rconn_recv(struct rconn *rc)
367 {
368     if (rc->state & (S_ACTIVE | S_IDLE)) {
369         struct buffer *buffer;
370         int error = vconn_recv(rc->vconn, &buffer);
371         if (!error) {
372             rc->last_received = time(0);
373             if (rc->state == S_IDLE) {
374                 state_transition(rc, S_ACTIVE);
375             }
376             return buffer;
377         } else if (error != EAGAIN) {
378             disconnect(rc, error);
379         }
380     }
381     return NULL;
382 }
383
384 /* Causes the next call to poll_block() to wake up when a packet may be ready
385  * to be received by vconn_recv() on 'rc'.  */
386 void
387 rconn_recv_wait(struct rconn *rc)
388 {
389     if (rc->vconn) {
390         vconn_wait(rc->vconn, WAIT_RECV);
391     }
392 }
393
394 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if at least 'txq_limit'
395  * packets are already queued, otherwise a positive errno value. */
396 int
397 do_send(struct rconn *rc, struct buffer *b, int txq_limit)
398 {
399     if (rc->vconn) {
400         if (rc->txq.n < txq_limit) {
401             queue_push_tail(&rc->txq, b);
402             if (rc->txq.n == 1) {
403                 try_send(rc);
404             }
405             return 0;
406         } else {
407             return EAGAIN;
408         }
409     } else {
410         return ENOTCONN;
411     }
412 }
413
414 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if the send queue is
415  * full, or ENOTCONN if 'rc' is not currently connected.
416  *
417  * There is no rconn_send_wait() function: an rconn has a send queue that it
418  * takes care of sending if you call rconn_run(), which will have the side
419  * effect of waking up poll_block(). */
420 int
421 rconn_send(struct rconn *rc, struct buffer *b)
422 {
423     return do_send(rc, b, rc->txq_limit);
424 }
425
426 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if the send queue is
427  * full, otherwise a positive errno value.
428  *
429  * Compared to rconn_send(), this function relaxes the queue limit, allowing
430  * more packets than usual to be queued. */
431 int
432 rconn_force_send(struct rconn *rc, struct buffer *b)
433 {
434     return do_send(rc, b, 2 * rc->txq_limit);
435 }
436
437 /* Returns true if 'rc''s send buffer is full,
438  * false if it has room for at least one more packet. */
439 bool
440 rconn_is_full(const struct rconn *rc)
441 {
442     return rc->txq.n >= rc->txq_limit;
443 }
444
445 /* Returns the total number of packets successfully sent on the underlying
446  * vconn.  A packet is not counted as sent while it is still queued in the
447  * rconn, only when it has been successfuly passed to the vconn.  */
448 unsigned int
449 rconn_packets_sent(const struct rconn *rc)
450 {
451     return rc->packets_sent;
452 }
453
454 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
455 const char *
456 rconn_get_name(const struct rconn *rc)
457 {
458     return rc->name;
459 }
460
461 /* Returns true if 'rconn' is connected or in the process of reconnecting,
462  * false if 'rconn' is disconnected and will not reconnect on its own. */
463 bool
464 rconn_is_alive(const struct rconn *rconn)
465 {
466     return rconn->reliable || rconn->vconn;
467 }
468
469 /* Returns true if 'rconn' is connected, false otherwise. */
470 bool
471 rconn_is_connected(const struct rconn *rconn)
472 {
473     return rconn->state & (S_ACTIVE | S_IDLE);
474 }
475
476 /* Returns 0 if 'rconn' is connected, otherwise the number of seconds that it
477  * has been disconnected. */
478 int
479 rconn_disconnected_duration(const struct rconn *rconn)
480 {
481     return rconn_is_connected(rconn) ? 0 : time(0) - rconn->last_connected;
482 }
483
484 /* Returns the IP address of the peer, or 0 if the peer is not connected over
485  * an IP-based protocol or if its IP address is not known. */
486 uint32_t
487 rconn_get_ip(const struct rconn *rconn) 
488 {
489     return rconn->vconn ? vconn_get_ip(rconn->vconn) : 0;
490 }
491 \f
492 /* Tries to send a packet from 'rc''s send buffer.  Returns 0 if successful,
493  * otherwise a positive errno value. */
494 static int
495 try_send(struct rconn *rc)
496 {
497     int retval = 0;
498     struct buffer *next = rc->txq.head->next;
499     retval = vconn_send(rc->vconn, rc->txq.head);
500     if (retval) {
501         if (retval != EAGAIN) {
502             disconnect(rc, retval);
503         }
504         return retval;
505     }
506     rc->packets_sent++;
507     queue_advance_head(&rc->txq, next);
508     return 0;
509 }
510
511 /* Disconnects 'rc'.  'error' is used only for logging purposes.  If it is
512  * nonzero, then it should be EOF to indicate the connection was closed by the
513  * peer in a normal fashion or a positive errno value. */
514 static void
515 disconnect(struct rconn *rc, int error)
516 {
517     if (rc->reliable) {
518         time_t now = time(0);
519
520         if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
521             if (error > 0) {
522                 VLOG_WARN("%s: connection dropped (%s)",
523                           rc->name, strerror(error));
524             } else if (error == EOF) {
525                 if (rc->reliable) {
526                     VLOG_WARN("%s: connection closed", rc->name);
527                 }
528             } else {
529                 VLOG_WARN("%s: connection dropped", rc->name);
530             }
531             vconn_close(rc->vconn);
532             rc->vconn = NULL;
533             queue_clear(&rc->txq);
534         }
535
536         if (now >= rc->backoff_deadline) {
537             rc->backoff = 1;
538         } else {
539             rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
540             VLOG_WARN("%s: waiting %d seconds before reconnect\n",
541                       rc->name, rc->backoff);
542         }
543         rc->backoff_deadline = now + rc->backoff;
544         state_transition(rc, S_BACKOFF);
545     } else {
546         rconn_disconnect(rc);
547     }
548 }
549
550 static unsigned int
551 elapsed_in_this_state(const struct rconn *rc)
552 {
553     return time(0) - rc->state_entered;
554 }
555
556 static bool
557 timeout(struct rconn *rc, unsigned int secs)
558 {
559     rc->min_timeout = MIN(rc->min_timeout, secs);
560     return time(0) >= sat_add(rc->state_entered, secs);
561 }
562
563 static void
564 state_transition(struct rconn *rc, enum state state)
565 {
566     VLOG_DBG("%s: entering %s", rc->name, state_name(state));
567     rc->state = state;
568     rc->state_entered = time(0);
569 }
570
571 static unsigned int
572 sat_add(unsigned int x, unsigned int y)
573 {
574     return x + y >= x ? x + y : UINT_MAX;
575 }
576
577 static unsigned int
578 sat_mul(unsigned int x, unsigned int y)
579 {
580     assert(y);
581     return x <= UINT_MAX / y ? x * y : UINT_MAX;
582 }