Merge branch 'locking'
[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 <config.h>
35 #include "rconn.h"
36 #include <assert.h>
37 #include <errno.h>
38 #include <limits.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include "buffer.h"
42 #include "poll-loop.h"
43 #include "ofp-print.h"
44 #include "timeval.h"
45 #include "util.h"
46 #include "vconn.h"
47
48 #define THIS_MODULE VLM_rconn
49 #include "vlog.h"
50
51 #define STATES                                  \
52     STATE(VOID, 1 << 0)                         \
53     STATE(BACKOFF, 1 << 1)                      \
54     STATE(CONNECTING, 1 << 2)                   \
55     STATE(ACTIVE, 1 << 3)                       \
56     STATE(IDLE, 1 << 4)
57 enum state {
58 #define STATE(NAME, VALUE) S_##NAME = VALUE,
59     STATES
60 #undef STATE
61 };
62
63 static const char *
64 state_name(enum state state)
65 {
66     switch (state) {
67 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
68         STATES
69 #undef STATE
70     }
71     return "***ERROR***";
72 }
73
74 /* A reliable connection to an OpenFlow switch or controller.
75  *
76  * See the large comment in rconn.h for more information. */
77 struct rconn {
78     enum state state;
79     time_t state_entered;
80     unsigned int min_timeout;
81
82     struct vconn *vconn;
83     char *name;
84     bool reliable;
85
86     struct queue txq;
87     int txq_limit;
88
89     int backoff;
90     int max_backoff;
91     time_t backoff_deadline;
92     time_t last_received;
93     time_t last_connected;
94
95     unsigned int packets_sent;
96
97     /* If we can't connect to the peer, it could be for any number of reasons.
98      * Usually, one would assume it is because the peer is not running or
99      * because the network is partitioned.  But it could also be because the
100      * network topology has changed, in which case the upper layer will need to
101      * reassess it (in particular, obtain a new IP address via DHCP and find
102      * the new location of the controller).  We set this flag when we suspect
103      * that this could be the case. */
104     bool questionable_connectivity;
105     time_t last_questioned;
106
107     /* Throughout this file, "probe" is shorthand for "inactivity probe".
108      * When nothing has been received from the peer for a while, we send out
109      * an echo request as an inactivity probe packet.  We should receive back
110      * a response. */
111     int probe_interval;         /* Secs of inactivity before sending probe. */
112 };
113
114 static unsigned int sat_add(unsigned int x, unsigned int y);
115 static unsigned int sat_mul(unsigned int x, unsigned int y);
116 static unsigned int elapsed_in_this_state(const struct rconn *);
117 static bool timeout(struct rconn *, unsigned int secs);
118 static void state_transition(struct rconn *, enum state);
119 static int try_send(struct rconn *);
120 static int reconnect(struct rconn *);
121 static void disconnect(struct rconn *, int error);
122 static void question_connectivity(struct rconn *);
123
124 /* Creates a new rconn, connects it (reliably) to 'name', and returns it. */
125 struct rconn *
126 rconn_new(const char *name, int txq_limit, int inactivity_probe_interval,
127           int max_backoff) 
128 {
129     struct rconn *rc = rconn_create(txq_limit, inactivity_probe_interval,
130                                     max_backoff);
131     rconn_connect(rc, name);
132     return rc;
133 }
134
135 /* Creates a new rconn, connects it (unreliably) to 'vconn', and returns it. */
136 struct rconn *
137 rconn_new_from_vconn(const char *name, int txq_limit, struct vconn *vconn) 
138 {
139     struct rconn *rc = rconn_create(txq_limit, 60, 0);
140     rconn_connect_unreliably(rc, name, vconn);
141     return rc;
142 }
143
144 /* Creates and returns a new rconn.
145  *
146  * 'txq_limit' is the maximum length of the send queue, in packets.
147  *
148  * 'probe_interval' is a number of seconds.  If the interval passes once
149  * without an OpenFlow message being received from the peer, the rconn sends
150  * out an "echo request" message.  If the interval passes again without a
151  * message being received, the rconn disconnects and re-connects to the peer.
152  * Setting 'probe_interval' to 0 disables this behavior.
153  *
154  * 'max_backoff' is the maximum number of seconds between attempts to connect
155  * to the peer.  The actual interval starts at 1 second and doubles on each
156  * failure until it reaches 'max_backoff'.  If 0 is specified, the default of
157  * 60 seconds is used. */
158 struct rconn *
159 rconn_create(int txq_limit, int probe_interval, int max_backoff)
160 {
161     struct rconn *rc = xcalloc(1, sizeof *rc);
162
163     rc->state = S_VOID;
164     rc->state_entered = time(0);
165     rc->min_timeout = 0;
166
167     rc->vconn = NULL;
168     rc->name = xstrdup("void");
169     rc->reliable = false;
170
171     queue_init(&rc->txq);
172     assert(txq_limit > 0);
173     rc->txq_limit = txq_limit;
174
175     rc->backoff = 0;
176     rc->max_backoff = max_backoff ? max_backoff : 60;
177     rc->backoff_deadline = TIME_MIN;
178     rc->last_received = time(0);
179     rc->last_connected = time(0);
180
181     rc->packets_sent = 0;
182
183     rc->questionable_connectivity = false;
184     rc->last_questioned = time(0);
185
186     rc->probe_interval = probe_interval ? MAX(5, probe_interval) : 0;
187
188     return rc;
189 }
190
191 int
192 rconn_connect(struct rconn *rc, const char *name)
193 {
194     rconn_disconnect(rc);
195     free(rc->name);
196     rc->name = xstrdup(name);
197     rc->reliable = true;
198     return reconnect(rc);
199 }
200
201 void
202 rconn_connect_unreliably(struct rconn *rc,
203                          const char *name, struct vconn *vconn)
204 {
205     assert(vconn != NULL);
206     rconn_disconnect(rc);
207     free(rc->name);
208     rc->name = xstrdup(name);
209     rc->reliable = false;
210     rc->vconn = vconn;
211     rc->last_connected = time(0);
212     state_transition(rc, S_ACTIVE);
213 }
214
215 void
216 rconn_disconnect(struct rconn *rc)
217 {
218     if (rc->vconn) {
219         vconn_close(rc->vconn);
220         rc->vconn = NULL;
221     }
222     free(rc->name);
223     rc->name = xstrdup("void");
224     rc->reliable = false;
225
226     rc->backoff = 0;
227     rc->backoff_deadline = TIME_MIN;
228
229     state_transition(rc, S_VOID);
230 }
231
232 /* Disconnects 'rc' and frees the underlying storage. */
233 void
234 rconn_destroy(struct rconn *rc)
235 {
236     if (rc) {
237         free(rc->name);
238         vconn_close(rc->vconn);
239         queue_destroy(&rc->txq);
240         free(rc);
241     }
242 }
243
244 static void
245 run_VOID(struct rconn *rc)
246 {
247     /* Nothing to do. */
248 }
249
250 static int
251 reconnect(struct rconn *rc)
252 {
253     int retval;
254
255     VLOG_WARN("%s: connecting...", rc->name);
256     retval = vconn_open(rc->name, &rc->vconn);
257     if (!retval) {
258         rc->backoff_deadline = time(0) + rc->backoff;
259         state_transition(rc, S_CONNECTING);
260     } else {
261         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
262         disconnect(rc, 0);
263     }
264     return retval;
265 }
266
267 static void
268 run_BACKOFF(struct rconn *rc)
269 {
270     if (timeout(rc, rc->backoff)) {
271         reconnect(rc);
272     }
273 }
274
275 static void
276 run_CONNECTING(struct rconn *rc)
277 {
278     int retval = vconn_connect(rc->vconn);
279     if (!retval) {
280         VLOG_WARN("%s: connected", rc->name);
281         if (vconn_is_passive(rc->vconn)) {
282             error(0, "%s: passive vconn not supported", rc->name);
283             state_transition(rc, S_VOID);
284         } else {
285             state_transition(rc, S_ACTIVE);
286             rc->last_connected = rc->state_entered;
287         }
288     } else if (retval != EAGAIN) {
289         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
290         disconnect(rc, retval);
291     } else if (timeout(rc, MAX(1, rc->backoff))) {
292         VLOG_WARN("%s: connection timed out", rc->name);
293         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
294         disconnect(rc, 0);
295     }
296 }
297
298 static void
299 do_tx_work(struct rconn *rc)
300 {
301     while (rc->txq.n > 0) {
302         int error = try_send(rc);
303         if (error) {
304             break;
305         }
306     }
307 }
308
309 static void
310 run_ACTIVE(struct rconn *rc)
311 {
312     if (rc->probe_interval) {
313         unsigned int base = MAX(rc->last_received, rc->state_entered);
314         unsigned int arg = base + rc->probe_interval - rc->state_entered;
315         if (timeout(rc, arg)) {
316             queue_push_tail(&rc->txq, make_echo_request());
317             VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
318                      rc->name, (unsigned int) (time(0) - base));
319             state_transition(rc, S_IDLE);
320             return;
321         }
322     }
323
324     do_tx_work(rc);
325 }
326
327 static void
328 run_IDLE(struct rconn *rc)
329 {
330     if (timeout(rc, rc->probe_interval)) {
331         question_connectivity(rc);
332         VLOG_ERR("%s: no response to inactivity probe after %u "
333                  "seconds, disconnecting",
334                  rc->name, elapsed_in_this_state(rc));
335         disconnect(rc, 0);
336     } else {
337         do_tx_work(rc);
338     }
339 }
340
341 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
342  * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
343  * connected, attempts to send packets in the send queue, if any. */
344 void
345 rconn_run(struct rconn *rc)
346 {
347     int old_state;
348     do {
349         old_state = rc->state;
350         rc->min_timeout = UINT_MAX;
351         switch (rc->state) {
352 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
353             STATES
354 #undef STATE
355         default:
356             NOT_REACHED();
357         }
358     } while (rc->state != old_state);
359 }
360
361 /* Causes the next call to poll_block() to wake up when rconn_run() should be
362  * called on 'rc'. */
363 void
364 rconn_run_wait(struct rconn *rc)
365 {
366     if (rc->min_timeout != UINT_MAX) {
367         poll_timer_wait(sat_mul(rc->min_timeout, 1000));
368     }
369     /* Reset timeout to 1 second.  This will have no effect ordinarily, because
370      * rconn_run() will typically set it back to a higher value.  If, however,
371      * the caller fails to call rconn_run() before its next call to
372      * rconn_wait() we won't potentially block forever. */
373     rc->min_timeout = 1;
374
375     if ((rc->state & (S_ACTIVE | S_IDLE)) && rc->txq.n) {
376         vconn_wait(rc->vconn, WAIT_SEND);
377     }
378 }
379
380 /* Attempts to receive a packet from 'rc'.  If successful, returns the packet;
381  * otherwise, returns a null pointer.  The caller is responsible for freeing
382  * the packet (with buffer_delete()). */
383 struct buffer *
384 rconn_recv(struct rconn *rc)
385 {
386     if (rc->state & (S_ACTIVE | S_IDLE)) {
387         struct buffer *buffer;
388         int error = vconn_recv(rc->vconn, &buffer);
389         if (!error) {
390             rc->last_received = time(0);
391             if (rc->state == S_IDLE) {
392                 state_transition(rc, S_ACTIVE);
393             }
394             return buffer;
395         } else if (error != EAGAIN) {
396             disconnect(rc, error);
397         }
398     }
399     return NULL;
400 }
401
402 /* Causes the next call to poll_block() to wake up when a packet may be ready
403  * to be received by vconn_recv() on 'rc'.  */
404 void
405 rconn_recv_wait(struct rconn *rc)
406 {
407     if (rc->vconn) {
408         vconn_wait(rc->vconn, WAIT_RECV);
409     }
410 }
411
412 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if at least 'txq_limit'
413  * packets are already queued, otherwise a positive errno value. */
414 int
415 do_send(struct rconn *rc, struct buffer *b, int txq_limit)
416 {
417     if (rc->vconn) {
418         if (rc->txq.n < txq_limit) {
419             queue_push_tail(&rc->txq, b);
420             if (rc->txq.n == 1) {
421                 try_send(rc);
422             }
423             return 0;
424         } else {
425             return EAGAIN;
426         }
427     } else {
428         return ENOTCONN;
429     }
430 }
431
432 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if the send queue is
433  * full, or ENOTCONN if 'rc' is not currently connected.
434  *
435  * There is no rconn_send_wait() function: an rconn has a send queue that it
436  * takes care of sending if you call rconn_run(), which will have the side
437  * effect of waking up poll_block(). */
438 int
439 rconn_send(struct rconn *rc, struct buffer *b)
440 {
441     return do_send(rc, b, rc->txq_limit);
442 }
443
444 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if the send queue is
445  * full, otherwise a positive errno value.
446  *
447  * Compared to rconn_send(), this function relaxes the queue limit, allowing
448  * more packets than usual to be queued. */
449 int
450 rconn_force_send(struct rconn *rc, struct buffer *b)
451 {
452     return do_send(rc, b, 2 * rc->txq_limit);
453 }
454
455 /* Returns true if 'rc''s send buffer is full,
456  * false if it has room for at least one more packet. */
457 bool
458 rconn_is_full(const struct rconn *rc)
459 {
460     return rc->txq.n >= rc->txq_limit;
461 }
462
463 /* Returns the total number of packets successfully sent on the underlying
464  * vconn.  A packet is not counted as sent while it is still queued in the
465  * rconn, only when it has been successfuly passed to the vconn.  */
466 unsigned int
467 rconn_packets_sent(const struct rconn *rc)
468 {
469     return rc->packets_sent;
470 }
471
472 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
473 const char *
474 rconn_get_name(const struct rconn *rc)
475 {
476     return rc->name;
477 }
478
479 /* Returns true if 'rconn' is connected or in the process of reconnecting,
480  * false if 'rconn' is disconnected and will not reconnect on its own. */
481 bool
482 rconn_is_alive(const struct rconn *rconn)
483 {
484     return rconn->state != S_VOID;
485 }
486
487 /* Returns true if 'rconn' is connected, false otherwise. */
488 bool
489 rconn_is_connected(const struct rconn *rconn)
490 {
491     return rconn->state & (S_ACTIVE | S_IDLE);
492 }
493
494 /* Returns 0 if 'rconn' is connected, otherwise the number of seconds that it
495  * has been disconnected. */
496 int
497 rconn_disconnected_duration(const struct rconn *rconn)
498 {
499     return rconn_is_connected(rconn) ? 0 : time(0) - rconn->last_connected;
500 }
501
502 /* Returns the IP address of the peer, or 0 if the peer is not connected over
503  * an IP-based protocol or if its IP address is not known. */
504 uint32_t
505 rconn_get_ip(const struct rconn *rconn) 
506 {
507     return rconn->vconn ? vconn_get_ip(rconn->vconn) : 0;
508 }
509
510 /* If 'rconn' can't connect to the peer, it could be for any number of reasons.
511  * Usually, one would assume it is because the peer is not running or because
512  * the network is partitioned.  But it could also be because the network
513  * topology has changed, in which case the upper layer will need to reassess it
514  * (in particular, obtain a new IP address via DHCP and find the new location
515  * of the controller).  When this appears that this might be the case, this
516  * function returns true.  It also clears the questionability flag and prevents
517  * it from being set again for some time. */
518 bool
519 rconn_is_connectivity_questionable(struct rconn *rconn)
520 {
521     bool questionable = rconn->questionable_connectivity;
522     rconn->questionable_connectivity = false;
523     return questionable;
524 }
525 \f
526 /* Tries to send a packet from 'rc''s send buffer.  Returns 0 if successful,
527  * otherwise a positive errno value. */
528 static int
529 try_send(struct rconn *rc)
530 {
531     int retval = 0;
532     struct buffer *next = rc->txq.head->next;
533     retval = vconn_send(rc->vconn, rc->txq.head);
534     if (retval) {
535         if (retval != EAGAIN) {
536             disconnect(rc, retval);
537         }
538         return retval;
539     }
540     rc->packets_sent++;
541     queue_advance_head(&rc->txq, next);
542     return 0;
543 }
544
545 /* Disconnects 'rc'.  'error' is used only for logging purposes.  If it is
546  * nonzero, then it should be EOF to indicate the connection was closed by the
547  * peer in a normal fashion or a positive errno value. */
548 static void
549 disconnect(struct rconn *rc, int error)
550 {
551     if (rc->reliable) {
552         time_t now = time(0);
553
554         if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
555             if (error > 0) {
556                 VLOG_WARN("%s: connection dropped (%s)",
557                           rc->name, strerror(error));
558             } else if (error == EOF) {
559                 if (rc->reliable) {
560                     VLOG_WARN("%s: connection closed", rc->name);
561                 }
562             } else {
563                 VLOG_WARN("%s: connection dropped", rc->name);
564             }
565             vconn_close(rc->vconn);
566             rc->vconn = NULL;
567             queue_clear(&rc->txq);
568         }
569
570         if (now >= rc->backoff_deadline) {
571             rc->backoff = 1;
572         } else {
573             rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
574             VLOG_WARN("%s: waiting %d seconds before reconnect\n",
575                       rc->name, rc->backoff);
576         }
577         rc->backoff_deadline = now + rc->backoff;
578         state_transition(rc, S_BACKOFF);
579         if (now - rc->last_connected > 60) {
580             question_connectivity(rc);
581         }
582     } else {
583         rconn_disconnect(rc);
584     }
585 }
586
587 static unsigned int
588 elapsed_in_this_state(const struct rconn *rc)
589 {
590     return time(0) - rc->state_entered;
591 }
592
593 static bool
594 timeout(struct rconn *rc, unsigned int secs)
595 {
596     rc->min_timeout = MIN(rc->min_timeout, secs);
597     return time(0) >= sat_add(rc->state_entered, secs);
598 }
599
600 static void
601 state_transition(struct rconn *rc, enum state state)
602 {
603     VLOG_DBG("%s: entering %s", rc->name, state_name(state));
604     rc->state = state;
605     rc->state_entered = time(0);
606 }
607
608 static unsigned int
609 sat_add(unsigned int x, unsigned int y)
610 {
611     return x + y >= x ? x + y : UINT_MAX;
612 }
613
614 static unsigned int
615 sat_mul(unsigned int x, unsigned int y)
616 {
617     assert(y);
618     return x <= UINT_MAX / y ? x * y : UINT_MAX;
619 }
620
621 static void
622 question_connectivity(struct rconn *rc) 
623 {
624     time_t now = time(0);
625     if (now - rc->last_questioned > 60) {
626         rc->questionable_connectivity = true;
627         rc->last_questioned = now;
628     }
629 }