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