Use signal-based timekeeping functions throughout the source base.
[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
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 unsigned int timeout(const struct rconn *);
117 static bool timed_out(const struct rconn *);
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_now();
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_now();
178     rc->last_connected = time_now();
179
180     rc->packets_sent = 0;
181
182     rc->questionable_connectivity = false;
183     rc->last_questioned = time_now();
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_now();
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 unsigned int
244 timeout_VOID(const struct rconn *rc)
245 {
246     return UINT_MAX;
247 }
248
249 static void
250 run_VOID(struct rconn *rc)
251 {
252     /* Nothing to do. */
253 }
254
255 static int
256 reconnect(struct rconn *rc)
257 {
258     int retval;
259
260     VLOG_WARN("%s: connecting...", rc->name);
261     retval = vconn_open(rc->name, &rc->vconn);
262     if (!retval) {
263         rc->backoff_deadline = time_now() + rc->backoff;
264         state_transition(rc, S_CONNECTING);
265     } else {
266         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
267         disconnect(rc, 0);
268     }
269     return retval;
270 }
271
272 static unsigned int
273 timeout_BACKOFF(const struct rconn *rc)
274 {
275     return rc->backoff;
276 }
277
278 static void
279 run_BACKOFF(struct rconn *rc)
280 {
281     if (timed_out(rc)) {
282         reconnect(rc);
283     }
284 }
285
286 static unsigned int
287 timeout_CONNECTING(const struct rconn *rc)
288 {
289     return MAX(1, rc->backoff);
290 }
291
292 static void
293 run_CONNECTING(struct rconn *rc)
294 {
295     int retval = vconn_connect(rc->vconn);
296     if (!retval) {
297         VLOG_WARN("%s: connected", rc->name);
298         if (vconn_is_passive(rc->vconn)) {
299             error(0, "%s: passive vconn not supported", rc->name);
300             state_transition(rc, S_VOID);
301         } else {
302             state_transition(rc, S_ACTIVE);
303             rc->last_connected = rc->state_entered;
304         }
305     } else if (retval != EAGAIN) {
306         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
307         disconnect(rc, retval);
308     } else if (timed_out(rc)) {
309         VLOG_WARN("%s: connection timed out", rc->name);
310         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
311         disconnect(rc, 0);
312     }
313 }
314
315 static void
316 do_tx_work(struct rconn *rc)
317 {
318     while (rc->txq.n > 0) {
319         int error = try_send(rc);
320         if (error) {
321             break;
322         }
323     }
324 }
325
326 static unsigned int
327 timeout_ACTIVE(const struct rconn *rc)
328 {
329     if (rc->probe_interval) {
330         unsigned int base = MAX(rc->last_received, rc->state_entered);
331         unsigned int arg = base + rc->probe_interval - rc->state_entered;
332         return arg;
333     }
334     return UINT_MAX;
335 }
336
337 static void
338 run_ACTIVE(struct rconn *rc)
339 {
340     if (timed_out(rc)) {
341         unsigned int base = MAX(rc->last_received, rc->state_entered);
342         queue_push_tail(&rc->txq, make_echo_request());
343         VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
344                  rc->name, (unsigned int) (time_now() - base));
345         state_transition(rc, S_IDLE);
346         return;
347     }
348
349     do_tx_work(rc);
350 }
351
352 static unsigned int
353 timeout_IDLE(const struct rconn *rc)
354 {
355     return rc->probe_interval;
356 }
357
358 static void
359 run_IDLE(struct rconn *rc)
360 {
361     if (timed_out(rc)) {
362         question_connectivity(rc);
363         VLOG_ERR("%s: no response to inactivity probe after %u "
364                  "seconds, disconnecting",
365                  rc->name, elapsed_in_this_state(rc));
366         disconnect(rc, 0);
367     } else {
368         do_tx_work(rc);
369     }
370 }
371
372 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
373  * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
374  * connected, attempts to send packets in the send queue, if any. */
375 void
376 rconn_run(struct rconn *rc)
377 {
378     int old_state;
379     do {
380         old_state = rc->state;
381         switch (rc->state) {
382 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
383             STATES
384 #undef STATE
385         default:
386             NOT_REACHED();
387         }
388     } while (rc->state != old_state);
389 }
390
391 /* Causes the next call to poll_block() to wake up when rconn_run() should be
392  * called on 'rc'. */
393 void
394 rconn_run_wait(struct rconn *rc)
395 {
396     unsigned int timeo = timeout(rc);
397     if (timeo != UINT_MAX) {
398         poll_timer_wait(sat_mul(timeo, 1000));
399     }
400
401     if ((rc->state & (S_ACTIVE | S_IDLE)) && rc->txq.n) {
402         vconn_wait(rc->vconn, WAIT_SEND);
403     }
404 }
405
406 /* Attempts to receive a packet from 'rc'.  If successful, returns the packet;
407  * otherwise, returns a null pointer.  The caller is responsible for freeing
408  * the packet (with buffer_delete()). */
409 struct buffer *
410 rconn_recv(struct rconn *rc)
411 {
412     if (rc->state & (S_ACTIVE | S_IDLE)) {
413         struct buffer *buffer;
414         int error = vconn_recv(rc->vconn, &buffer);
415         if (!error) {
416             rc->last_received = time_now();
417             if (rc->state == S_IDLE) {
418                 state_transition(rc, S_ACTIVE);
419             }
420             return buffer;
421         } else if (error != EAGAIN) {
422             disconnect(rc, error);
423         }
424     }
425     return NULL;
426 }
427
428 /* Causes the next call to poll_block() to wake up when a packet may be ready
429  * to be received by vconn_recv() on 'rc'.  */
430 void
431 rconn_recv_wait(struct rconn *rc)
432 {
433     if (rc->vconn) {
434         vconn_wait(rc->vconn, WAIT_RECV);
435     }
436 }
437
438 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if at least 'txq_limit'
439  * packets are already queued, otherwise a positive errno value. */
440 int
441 do_send(struct rconn *rc, struct buffer *b, int txq_limit)
442 {
443     if (rc->vconn) {
444         if (rc->txq.n < txq_limit) {
445             queue_push_tail(&rc->txq, b);
446             if (rc->txq.n == 1) {
447                 try_send(rc);
448             }
449             return 0;
450         } else {
451             return EAGAIN;
452         }
453     } else {
454         return ENOTCONN;
455     }
456 }
457
458 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if the send queue is
459  * full, or ENOTCONN if 'rc' is not currently connected.
460  *
461  * There is no rconn_send_wait() function: an rconn has a send queue that it
462  * takes care of sending if you call rconn_run(), which will have the side
463  * effect of waking up poll_block(). */
464 int
465 rconn_send(struct rconn *rc, struct buffer *b)
466 {
467     return do_send(rc, b, rc->txq_limit);
468 }
469
470 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if the send queue is
471  * full, otherwise a positive errno value.
472  *
473  * Compared to rconn_send(), this function relaxes the queue limit, allowing
474  * more packets than usual to be queued. */
475 int
476 rconn_force_send(struct rconn *rc, struct buffer *b)
477 {
478     return do_send(rc, b, 2 * rc->txq_limit);
479 }
480
481 /* Returns true if 'rc''s send buffer is full,
482  * false if it has room for at least one more packet. */
483 bool
484 rconn_is_full(const struct rconn *rc)
485 {
486     return rc->txq.n >= rc->txq_limit;
487 }
488
489 /* Returns the total number of packets successfully sent on the underlying
490  * vconn.  A packet is not counted as sent while it is still queued in the
491  * rconn, only when it has been successfuly passed to the vconn.  */
492 unsigned int
493 rconn_packets_sent(const struct rconn *rc)
494 {
495     return rc->packets_sent;
496 }
497
498 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
499 const char *
500 rconn_get_name(const struct rconn *rc)
501 {
502     return rc->name;
503 }
504
505 /* Returns true if 'rconn' is connected or in the process of reconnecting,
506  * false if 'rconn' is disconnected and will not reconnect on its own. */
507 bool
508 rconn_is_alive(const struct rconn *rconn)
509 {
510     return rconn->state != S_VOID;
511 }
512
513 /* Returns true if 'rconn' is connected, false otherwise. */
514 bool
515 rconn_is_connected(const struct rconn *rconn)
516 {
517     return rconn->state & (S_ACTIVE | S_IDLE);
518 }
519
520 /* Returns 0 if 'rconn' is connected, otherwise the number of seconds that it
521  * has been disconnected. */
522 int
523 rconn_disconnected_duration(const struct rconn *rconn)
524 {
525     return rconn_is_connected(rconn) ? 0 : time_now() - rconn->last_received;
526 }
527
528 /* Returns the IP address of the peer, or 0 if the peer is not connected over
529  * an IP-based protocol or if its IP address is not known. */
530 uint32_t
531 rconn_get_ip(const struct rconn *rconn) 
532 {
533     return rconn->vconn ? vconn_get_ip(rconn->vconn) : 0;
534 }
535
536 /* If 'rconn' can't connect to the peer, it could be for any number of reasons.
537  * Usually, one would assume it is because the peer is not running or because
538  * the network is partitioned.  But it could also be because the network
539  * topology has changed, in which case the upper layer will need to reassess it
540  * (in particular, obtain a new IP address via DHCP and find the new location
541  * of the controller).  When this appears that this might be the case, this
542  * function returns true.  It also clears the questionability flag and prevents
543  * it from being set again for some time. */
544 bool
545 rconn_is_connectivity_questionable(struct rconn *rconn)
546 {
547     bool questionable = rconn->questionable_connectivity;
548     rconn->questionable_connectivity = false;
549     return questionable;
550 }
551 \f
552 /* Tries to send a packet from 'rc''s send buffer.  Returns 0 if successful,
553  * otherwise a positive errno value. */
554 static int
555 try_send(struct rconn *rc)
556 {
557     int retval = 0;
558     struct buffer *next = rc->txq.head->next;
559     retval = vconn_send(rc->vconn, rc->txq.head);
560     if (retval) {
561         if (retval != EAGAIN) {
562             disconnect(rc, retval);
563         }
564         return retval;
565     }
566     rc->packets_sent++;
567     queue_advance_head(&rc->txq, next);
568     return 0;
569 }
570
571 /* Disconnects 'rc'.  'error' is used only for logging purposes.  If it is
572  * nonzero, then it should be EOF to indicate the connection was closed by the
573  * peer in a normal fashion or a positive errno value. */
574 static void
575 disconnect(struct rconn *rc, int error)
576 {
577     if (rc->reliable) {
578         time_t now = time_now();
579
580         if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
581             if (error > 0) {
582                 VLOG_WARN("%s: connection dropped (%s)",
583                           rc->name, strerror(error));
584             } else if (error == EOF) {
585                 if (rc->reliable) {
586                     VLOG_WARN("%s: connection closed", rc->name);
587                 }
588             } else {
589                 VLOG_WARN("%s: connection dropped", rc->name);
590             }
591             vconn_close(rc->vconn);
592             rc->vconn = NULL;
593             queue_clear(&rc->txq);
594         }
595
596         if (now >= rc->backoff_deadline) {
597             rc->backoff = 1;
598         } else {
599             rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
600             VLOG_WARN("%s: waiting %d seconds before reconnect\n",
601                       rc->name, rc->backoff);
602         }
603         rc->backoff_deadline = now + rc->backoff;
604         state_transition(rc, S_BACKOFF);
605         if (now - rc->last_connected > 60) {
606             question_connectivity(rc);
607         }
608     } else {
609         rconn_disconnect(rc);
610     }
611 }
612
613 static unsigned int
614 elapsed_in_this_state(const struct rconn *rc)
615 {
616     return time_now() - rc->state_entered;
617 }
618
619 static unsigned int
620 timeout(const struct rconn *rc)
621 {
622     switch (rc->state) {
623 #define STATE(NAME, VALUE) case S_##NAME: return timeout_##NAME(rc);
624         STATES
625 #undef STATE
626     default:
627         NOT_REACHED();
628     }
629 }
630
631 static bool
632 timed_out(const struct rconn *rc)
633 {
634     return time_now() >= sat_add(rc->state_entered, timeout(rc));
635 }
636
637 static void
638 state_transition(struct rconn *rc, enum state state)
639 {
640     VLOG_DBG("%s: entering %s", rc->name, state_name(state));
641     rc->state = state;
642     rc->state_entered = time_now();
643 }
644
645 static unsigned int
646 sat_add(unsigned int x, unsigned int y)
647 {
648     return x + y >= x ? x + y : UINT_MAX;
649 }
650
651 static unsigned int
652 sat_mul(unsigned int x, unsigned int y)
653 {
654     assert(y);
655     return x <= UINT_MAX / y ? x * y : UINT_MAX;
656 }
657
658 static void
659 question_connectivity(struct rconn *rc) 
660 {
661     time_t now = time_now();
662     if (now - rc->last_questioned > 60) {
663         rc->questionable_connectivity = true;
664         rc->last_questioned = now;
665     }
666 }