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