rconn: Wake up immediately if we drain the send queue.
[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     if (!rc->txq.n) {
314         return;
315     }
316     while (rc->txq.n > 0) {
317         int error = try_send(rc);
318         if (error) {
319             break;
320         }
321     }
322     if (!rc->txq.n) {
323         poll_immediate_wake();
324     }
325 }
326
327 static unsigned int
328 timeout_ACTIVE(const struct rconn *rc)
329 {
330     if (rc->probe_interval) {
331         unsigned int base = MAX(rc->last_received, rc->state_entered);
332         unsigned int arg = base + rc->probe_interval - rc->state_entered;
333         return arg;
334     }
335     return UINT_MAX;
336 }
337
338 static void
339 run_ACTIVE(struct rconn *rc)
340 {
341     if (timed_out(rc)) {
342         unsigned int base = MAX(rc->last_received, rc->state_entered);
343         rconn_send(rc, make_echo_request(), NULL);
344         VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
345                  rc->name, (unsigned int) (time_now() - base));
346         state_transition(rc, S_IDLE);
347         return;
348     }
349
350     do_tx_work(rc);
351 }
352
353 static unsigned int
354 timeout_IDLE(const struct rconn *rc)
355 {
356     return rc->probe_interval;
357 }
358
359 static void
360 run_IDLE(struct rconn *rc)
361 {
362     if (timed_out(rc)) {
363         question_connectivity(rc);
364         VLOG_ERR("%s: no response to inactivity probe after %u "
365                  "seconds, disconnecting",
366                  rc->name, elapsed_in_this_state(rc));
367         disconnect(rc, 0);
368     } else {
369         do_tx_work(rc);
370     }
371 }
372
373 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
374  * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
375  * connected, attempts to send packets in the send queue, if any. */
376 void
377 rconn_run(struct rconn *rc)
378 {
379     int old_state;
380     do {
381         old_state = rc->state;
382         switch (rc->state) {
383 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
384             STATES
385 #undef STATE
386         default:
387             NOT_REACHED();
388         }
389     } while (rc->state != old_state);
390 }
391
392 /* Causes the next call to poll_block() to wake up when rconn_run() should be
393  * called on 'rc'. */
394 void
395 rconn_run_wait(struct rconn *rc)
396 {
397     unsigned int timeo = timeout(rc);
398     if (timeo != UINT_MAX) {
399         poll_timer_wait(sat_mul(timeo, 1000));
400     }
401
402     if ((rc->state & (S_ACTIVE | S_IDLE)) && rc->txq.n) {
403         vconn_wait(rc->vconn, WAIT_SEND);
404     }
405 }
406
407 /* Attempts to receive a packet from 'rc'.  If successful, returns the packet;
408  * otherwise, returns a null pointer.  The caller is responsible for freeing
409  * the packet (with buffer_delete()). */
410 struct buffer *
411 rconn_recv(struct rconn *rc)
412 {
413     if (rc->state & (S_ACTIVE | S_IDLE)) {
414         struct buffer *buffer;
415         int error = vconn_recv(rc->vconn, &buffer);
416         if (!error) {
417             rc->last_received = time_now();
418             if (rc->state == S_IDLE) {
419                 state_transition(rc, S_ACTIVE);
420             }
421             return buffer;
422         } else if (error != EAGAIN) {
423             disconnect(rc, error);
424         }
425     }
426     return NULL;
427 }
428
429 /* Causes the next call to poll_block() to wake up when a packet may be ready
430  * to be received by vconn_recv() on 'rc'.  */
431 void
432 rconn_recv_wait(struct rconn *rc)
433 {
434     if (rc->vconn) {
435         vconn_wait(rc->vconn, WAIT_RECV);
436     }
437 }
438
439 /* Sends 'b' on 'rc'.  Returns 0 if successful (in which case 'b' is
440  * destroyed), or ENOTCONN if 'rc' is not currently connected (in which case
441  * the caller retains ownership of 'b').
442  *
443  * If 'n_queued' is non-null, then '*n_queued' will be incremented while the
444  * packet is in flight, then decremented when it has been sent (or discarded
445  * due to disconnection).  Because 'b' may be sent (or discarded) before this
446  * function returns, the caller may not be able to observe any change in
447  * '*n_queued'.
448  *
449  * There is no rconn_send_wait() function: an rconn has a send queue that it
450  * takes care of sending if you call rconn_run(), which will have the side
451  * effect of waking up poll_block(). */
452 int
453 rconn_send(struct rconn *rc, struct buffer *b, int *n_queued)
454 {
455     if (rconn_is_connected(rc)) {
456         b->private = n_queued;
457         if (n_queued) {
458             ++*n_queued;
459         }
460         queue_push_tail(&rc->txq, b);
461         if (rc->txq.n == 1) {
462             try_send(rc);
463         }
464         return 0;
465     } else {
466         return ENOTCONN;
467     }
468 }
469
470 /* Sends 'b' on 'rc'.  Increments '*n_queued' while the packet is in flight; it
471  * will be decremented when it has been sent (or discarded due to
472  * disconnection).  Returns 0 if successful, EAGAIN if '*n_queued' is already
473  * at least as large of 'queue_limit', or ENOTCONN if 'rc' is not currently
474  * connected.  Regardless of return value, 'b' is destroyed.
475  *
476  * Because 'b' may be sent (or discarded) before this function returns, the
477  * caller may not be able to observe any change in '*n_queued'.
478  *
479  * There is no rconn_send_wait() function: an rconn has a send queue that it
480  * takes care of sending if you call rconn_run(), which will have the side
481  * effect of waking up poll_block(). */
482 int
483 rconn_send_with_limit(struct rconn *rc, struct buffer *b,
484                       int *n_queued, int queue_limit)
485 {
486     int retval;
487     retval = *n_queued >= queue_limit ? EAGAIN : rconn_send(rc, b, n_queued);
488     if (retval) {
489         buffer_delete(b);
490     }
491     return retval;
492 }
493
494 /* Returns the total number of packets successfully sent on the underlying
495  * vconn.  A packet is not counted as sent while it is still queued in the
496  * rconn, only when it has been successfuly passed to the vconn.  */
497 unsigned int
498 rconn_packets_sent(const struct rconn *rc)
499 {
500     return rc->packets_sent;
501 }
502
503 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
504 const char *
505 rconn_get_name(const struct rconn *rc)
506 {
507     return rc->name;
508 }
509
510 /* Returns true if 'rconn' is connected or in the process of reconnecting,
511  * false if 'rconn' is disconnected and will not reconnect on its own. */
512 bool
513 rconn_is_alive(const struct rconn *rconn)
514 {
515     return rconn->state != S_VOID;
516 }
517
518 /* Returns true if 'rconn' is connected, false otherwise. */
519 bool
520 rconn_is_connected(const struct rconn *rconn)
521 {
522     return rconn->state & (S_ACTIVE | S_IDLE);
523 }
524
525 /* Returns 0 if 'rconn' is connected, otherwise the number of seconds that it
526  * has been disconnected. */
527 int
528 rconn_disconnected_duration(const struct rconn *rconn)
529 {
530     return rconn_is_connected(rconn) ? 0 : time_now() - rconn->last_received;
531 }
532
533 /* Returns the IP address of the peer, or 0 if the peer is not connected over
534  * an IP-based protocol or if its IP address is not known. */
535 uint32_t
536 rconn_get_ip(const struct rconn *rconn) 
537 {
538     return rconn->vconn ? vconn_get_ip(rconn->vconn) : 0;
539 }
540
541 /* If 'rconn' can't connect to the peer, it could be for any number of reasons.
542  * Usually, one would assume it is because the peer is not running or because
543  * the network is partitioned.  But it could also be because the network
544  * topology has changed, in which case the upper layer will need to reassess it
545  * (in particular, obtain a new IP address via DHCP and find the new location
546  * of the controller).  When this appears that this might be the case, this
547  * function returns true.  It also clears the questionability flag and prevents
548  * it from being set again for some time. */
549 bool
550 rconn_is_connectivity_questionable(struct rconn *rconn)
551 {
552     bool questionable = rconn->questionable_connectivity;
553     rconn->questionable_connectivity = false;
554     return questionable;
555 }
556 \f
557 /* Tries to send a packet from 'rc''s send buffer.  Returns 0 if successful,
558  * otherwise a positive errno value. */
559 static int
560 try_send(struct rconn *rc)
561 {
562     int retval = 0;
563     struct buffer *next = rc->txq.head->next;
564     int *n_queued = rc->txq.head->private;
565     retval = vconn_send(rc->vconn, rc->txq.head);
566     if (retval) {
567         if (retval != EAGAIN) {
568             disconnect(rc, retval);
569         }
570         return retval;
571     }
572     rc->packets_sent++;
573     if (n_queued) {
574         --*n_queued;
575     }
576     queue_advance_head(&rc->txq, next);
577     return 0;
578 }
579
580 /* Disconnects 'rc'.  'error' is used only for logging purposes.  If it is
581  * nonzero, then it should be EOF to indicate the connection was closed by the
582  * peer in a normal fashion or a positive errno value. */
583 static void
584 disconnect(struct rconn *rc, int error)
585 {
586     if (rc->reliable) {
587         time_t now = time_now();
588
589         if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
590             if (error > 0) {
591                 VLOG_WARN("%s: connection dropped (%s)",
592                           rc->name, strerror(error));
593             } else if (error == EOF) {
594                 if (rc->reliable) {
595                     VLOG_WARN("%s: connection closed", rc->name);
596                 }
597             } else {
598                 VLOG_WARN("%s: connection dropped", rc->name);
599             }
600             vconn_close(rc->vconn);
601             rc->vconn = NULL;
602             flush_queue(rc);
603         }
604
605         if (now >= rc->backoff_deadline) {
606             rc->backoff = 1;
607         } else {
608             rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
609             VLOG_WARN("%s: waiting %d seconds before reconnect\n",
610                       rc->name, rc->backoff);
611         }
612         rc->backoff_deadline = now + rc->backoff;
613         state_transition(rc, S_BACKOFF);
614         if (now - rc->last_connected > 60) {
615             question_connectivity(rc);
616         }
617     } else {
618         rconn_disconnect(rc);
619     }
620 }
621
622 /* Drops all the packets from 'rc''s send queue and decrements their queue
623  * counts. */
624 static void
625 flush_queue(struct rconn *rc)
626 {
627     if (!rc->txq.n) {
628         return;
629     }
630     while (rc->txq.n > 0) {
631         struct buffer *b = queue_pop_head(&rc->txq);
632         int *n_queued = b->private;
633         if (n_queued) {
634             --*n_queued;
635         }
636         buffer_delete(b);
637     }
638     poll_immediate_wake();
639 }
640
641 static unsigned int
642 elapsed_in_this_state(const struct rconn *rc)
643 {
644     return time_now() - rc->state_entered;
645 }
646
647 static unsigned int
648 timeout(const struct rconn *rc)
649 {
650     switch (rc->state) {
651 #define STATE(NAME, VALUE) case S_##NAME: return timeout_##NAME(rc);
652         STATES
653 #undef STATE
654     default:
655         NOT_REACHED();
656     }
657 }
658
659 static bool
660 timed_out(const struct rconn *rc)
661 {
662     return time_now() >= sat_add(rc->state_entered, timeout(rc));
663 }
664
665 static void
666 state_transition(struct rconn *rc, enum state state)
667 {
668     VLOG_DBG("%s: entering %s", rc->name, state_name(state));
669     rc->state = state;
670     rc->state_entered = time_now();
671 }
672
673 static unsigned int
674 sat_add(unsigned int x, unsigned int y)
675 {
676     return x + y >= x ? x + y : UINT_MAX;
677 }
678
679 static unsigned int
680 sat_mul(unsigned int x, unsigned int y)
681 {
682     assert(y);
683     return x <= UINT_MAX / y ? x * y : UINT_MAX;
684 }
685
686 static void
687 question_connectivity(struct rconn *rc) 
688 {
689     time_t now = time_now();
690     if (now - rc->last_questioned > 60) {
691         rc->questionable_connectivity = true;
692         rc->last_questioned = now;
693     }
694 }