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