1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
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:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
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
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.
43 #include "poll-loop.h"
49 #define THIS_MODULE VLM_rconn
54 STATE(BACKOFF, 1 << 1) \
55 STATE(CONNECTING, 1 << 2) \
56 STATE(ACTIVE, 1 << 3) \
59 #define STATE(NAME, VALUE) S_##NAME = VALUE,
65 state_name(enum state state)
68 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
75 /* A reliable connection to an OpenFlow switch or controller.
77 * See the large comment in rconn.h for more information. */
90 time_t backoff_deadline;
92 time_t last_connected;
93 unsigned int packets_sent;
95 /* These values are simply for statistics reporting, not used directly by
96 * anything internal to the rconn (or the secchan for that matter). */
97 unsigned int packets_received;
98 unsigned int n_attempted_connections, n_successful_connections;
100 unsigned long int total_time_connected;
102 /* If we can't connect to the peer, it could be for any number of reasons.
103 * Usually, one would assume it is because the peer is not running or
104 * because the network is partitioned. But it could also be because the
105 * network topology has changed, in which case the upper layer will need to
106 * reassess it (in particular, obtain a new IP address via DHCP and find
107 * the new location of the controller). We set this flag when we suspect
108 * that this could be the case. */
109 bool questionable_connectivity;
110 time_t last_questioned;
112 /* Throughout this file, "probe" is shorthand for "inactivity probe".
113 * When nothing has been received from the peer for a while, we send out
114 * an echo request as an inactivity probe packet. We should receive back
116 int probe_interval; /* Secs of inactivity before sending probe. */
118 /* Messages sent or received are copied to the monitor connections. */
119 #define MAX_MONITORS 8
120 struct vconn *monitors[8];
124 static unsigned int elapsed_in_this_state(const struct rconn *);
125 static unsigned int timeout(const struct rconn *);
126 static bool timed_out(const struct rconn *);
127 static void state_transition(struct rconn *, enum state);
128 static int try_send(struct rconn *);
129 static int reconnect(struct rconn *);
130 static void disconnect(struct rconn *, int error);
131 static void flush_queue(struct rconn *);
132 static void question_connectivity(struct rconn *);
133 static void copy_to_monitor(struct rconn *, const struct ofpbuf *);
135 /* Creates a new rconn, connects it (reliably) to 'name', and returns it. */
137 rconn_new(const char *name, int inactivity_probe_interval, int max_backoff)
139 struct rconn *rc = rconn_create(inactivity_probe_interval, max_backoff);
140 rconn_connect(rc, name);
144 /* Creates a new rconn, connects it (unreliably) to 'vconn', and returns it. */
146 rconn_new_from_vconn(const char *name, struct vconn *vconn)
148 struct rconn *rc = rconn_create(60, 0);
149 rconn_connect_unreliably(rc, name, vconn);
153 /* Creates and returns a new rconn.
155 * 'probe_interval' is a number of seconds. If the interval passes once
156 * without an OpenFlow message being received from the peer, the rconn sends
157 * out an "echo request" message. If the interval passes again without a
158 * message being received, the rconn disconnects and re-connects to the peer.
159 * Setting 'probe_interval' to 0 disables this behavior.
161 * 'max_backoff' is the maximum number of seconds between attempts to connect
162 * to the peer. The actual interval starts at 1 second and doubles on each
163 * failure until it reaches 'max_backoff'. If 0 is specified, the default of
164 * 60 seconds is used. */
166 rconn_create(int probe_interval, int max_backoff)
168 struct rconn *rc = xcalloc(1, sizeof *rc);
171 rc->state_entered = time_now();
174 rc->name = xstrdup("void");
175 rc->reliable = false;
177 queue_init(&rc->txq);
180 rc->max_backoff = max_backoff ? max_backoff : 60;
181 rc->backoff_deadline = TIME_MIN;
182 rc->last_received = time_now();
183 rc->last_connected = time_now();
185 rc->packets_sent = 0;
187 rc->packets_received = 0;
188 rc->n_attempted_connections = 0;
189 rc->n_successful_connections = 0;
190 rc->creation_time = time_now();
191 rc->total_time_connected = 0;
193 rc->questionable_connectivity = false;
194 rc->last_questioned = time_now();
196 rc->probe_interval = probe_interval ? MAX(5, probe_interval) : 0;
204 rconn_connect(struct rconn *rc, const char *name)
206 rconn_disconnect(rc);
208 rc->name = xstrdup(name);
210 return reconnect(rc);
214 rconn_connect_unreliably(struct rconn *rc,
215 const char *name, struct vconn *vconn)
217 assert(vconn != NULL);
218 rconn_disconnect(rc);
220 rc->name = xstrdup(name);
221 rc->reliable = false;
223 rc->last_connected = time_now();
224 state_transition(rc, S_ACTIVE);
228 rconn_disconnect(struct rconn *rc)
231 vconn_close(rc->vconn);
235 rc->name = xstrdup("void");
236 rc->reliable = false;
239 rc->backoff_deadline = TIME_MIN;
241 state_transition(rc, S_VOID);
244 /* Disconnects 'rc' and frees the underlying storage. */
246 rconn_destroy(struct rconn *rc)
250 vconn_close(rc->vconn);
252 queue_destroy(&rc->txq);
258 timeout_VOID(const struct rconn *rc)
264 run_VOID(struct rconn *rc)
270 reconnect(struct rconn *rc)
274 VLOG_WARN("%s: connecting...", rc->name);
275 rc->n_attempted_connections++;
276 retval = vconn_open(rc->name, OFP_VERSION, &rc->vconn);
278 rc->backoff_deadline = time_now() + rc->backoff;
279 state_transition(rc, S_CONNECTING);
281 VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
282 rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
289 timeout_BACKOFF(const struct rconn *rc)
295 run_BACKOFF(struct rconn *rc)
303 timeout_CONNECTING(const struct rconn *rc)
305 return MAX(1, rc->backoff);
309 run_CONNECTING(struct rconn *rc)
311 int retval = vconn_connect(rc->vconn);
313 VLOG_WARN("%s: connected", rc->name);
314 rc->n_successful_connections++;
315 state_transition(rc, S_ACTIVE);
316 rc->last_connected = rc->state_entered;
317 } else if (retval != EAGAIN) {
318 VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
319 disconnect(rc, retval);
320 } else if (timed_out(rc)) {
321 VLOG_WARN("%s: connection timed out", rc->name);
322 rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
328 do_tx_work(struct rconn *rc)
333 while (rc->txq.n > 0) {
334 int error = try_send(rc);
340 poll_immediate_wake();
345 timeout_ACTIVE(const struct rconn *rc)
347 if (rc->probe_interval) {
348 unsigned int base = MAX(rc->last_received, rc->state_entered);
349 unsigned int arg = base + rc->probe_interval - rc->state_entered;
356 run_ACTIVE(struct rconn *rc)
359 unsigned int base = MAX(rc->last_received, rc->state_entered);
360 rconn_send(rc, make_echo_request(), NULL);
361 VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
362 rc->name, (unsigned int) (time_now() - base));
363 state_transition(rc, S_IDLE);
371 timeout_IDLE(const struct rconn *rc)
373 return rc->probe_interval;
377 run_IDLE(struct rconn *rc)
380 question_connectivity(rc);
381 VLOG_ERR("%s: no response to inactivity probe after %u "
382 "seconds, disconnecting",
383 rc->name, elapsed_in_this_state(rc));
390 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
391 * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
392 * connected, attempts to send packets in the send queue, if any. */
394 rconn_run(struct rconn *rc)
398 old_state = rc->state;
400 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
406 } while (rc->state != old_state);
409 /* Causes the next call to poll_block() to wake up when rconn_run() should be
412 rconn_run_wait(struct rconn *rc)
414 unsigned int timeo = timeout(rc);
415 if (timeo != UINT_MAX) {
416 unsigned int expires = sat_add(rc->state_entered, timeo);
417 unsigned int remaining = sat_sub(expires, time_now());
418 poll_timer_wait(sat_mul(remaining, 1000));
421 if ((rc->state & (S_ACTIVE | S_IDLE)) && rc->txq.n) {
422 vconn_wait(rc->vconn, WAIT_SEND);
426 /* Attempts to receive a packet from 'rc'. If successful, returns the packet;
427 * otherwise, returns a null pointer. The caller is responsible for freeing
428 * the packet (with ofpbuf_delete()). */
430 rconn_recv(struct rconn *rc)
432 if (rc->state & (S_ACTIVE | S_IDLE)) {
433 struct ofpbuf *buffer;
434 int error = vconn_recv(rc->vconn, &buffer);
436 copy_to_monitor(rc, buffer);
437 rc->last_received = time_now();
438 rc->packets_received++;
439 if (rc->state == S_IDLE) {
440 state_transition(rc, S_ACTIVE);
443 } else if (error != EAGAIN) {
444 disconnect(rc, error);
450 /* Causes the next call to poll_block() to wake up when a packet may be ready
451 * to be received by vconn_recv() on 'rc'. */
453 rconn_recv_wait(struct rconn *rc)
456 vconn_wait(rc->vconn, WAIT_RECV);
460 /* Sends 'b' on 'rc'. Returns 0 if successful (in which case 'b' is
461 * destroyed), or ENOTCONN if 'rc' is not currently connected (in which case
462 * the caller retains ownership of 'b').
464 * If 'n_queued' is non-null, then '*n_queued' will be incremented while the
465 * packet is in flight, then decremented when it has been sent (or discarded
466 * due to disconnection). Because 'b' may be sent (or discarded) before this
467 * function returns, the caller may not be able to observe any change in
470 * There is no rconn_send_wait() function: an rconn has a send queue that it
471 * takes care of sending if you call rconn_run(), which will have the side
472 * effect of waking up poll_block(). */
474 rconn_send(struct rconn *rc, struct ofpbuf *b, int *n_queued)
476 if (rconn_is_connected(rc)) {
477 copy_to_monitor(rc, b);
478 b->private = n_queued;
482 queue_push_tail(&rc->txq, b);
483 if (rc->txq.n == 1) {
492 /* Sends 'b' on 'rc'. Increments '*n_queued' while the packet is in flight; it
493 * will be decremented when it has been sent (or discarded due to
494 * disconnection). Returns 0 if successful, EAGAIN if '*n_queued' is already
495 * at least as large as 'queue_limit', or ENOTCONN if 'rc' is not currently
496 * connected. Regardless of return value, 'b' is destroyed.
498 * Because 'b' may be sent (or discarded) before this function returns, the
499 * caller may not be able to observe any change in '*n_queued'.
501 * There is no rconn_send_wait() function: an rconn has a send queue that it
502 * takes care of sending if you call rconn_run(), which will have the side
503 * effect of waking up poll_block(). */
505 rconn_send_with_limit(struct rconn *rc, struct ofpbuf *b,
506 int *n_queued, int queue_limit)
509 retval = *n_queued >= queue_limit ? EAGAIN : rconn_send(rc, b, n_queued);
516 /* Returns the total number of packets successfully sent on the underlying
517 * vconn. A packet is not counted as sent while it is still queued in the
518 * rconn, only when it has been successfuly passed to the vconn. */
520 rconn_packets_sent(const struct rconn *rc)
522 return rc->packets_sent;
525 /* Adds 'vconn' to 'rc' as a monitoring connection, to which all messages sent
526 * and received on 'rconn' will be copied. 'rc' takes ownership of 'vconn'. */
528 rconn_add_monitor(struct rconn *rc, struct vconn *vconn)
530 if (rc->n_monitors < ARRAY_SIZE(rc->monitors)) {
531 VLOG_WARN("new monitor connection from %s", vconn_get_name(vconn));
532 rc->monitors[rc->n_monitors++] = vconn;
534 VLOG_DBG("too many monitor connections, discarding %s",
535 vconn_get_name(vconn));
540 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
542 rconn_get_name(const struct rconn *rc)
547 /* Returns true if 'rconn' is connected or in the process of reconnecting,
548 * false if 'rconn' is disconnected and will not reconnect on its own. */
550 rconn_is_alive(const struct rconn *rconn)
552 return rconn->state != S_VOID;
555 /* Returns true if 'rconn' is connected, false otherwise. */
557 rconn_is_connected(const struct rconn *rconn)
559 return rconn->state & (S_ACTIVE | S_IDLE);
562 /* Returns 0 if 'rconn' is connected, otherwise the number of seconds that it
563 * has been disconnected. */
565 rconn_disconnected_duration(const struct rconn *rconn)
567 return rconn_is_connected(rconn) ? 0 : time_now() - rconn->last_received;
570 /* Returns the IP address of the peer, or 0 if the peer is not connected over
571 * an IP-based protocol or if its IP address is not known. */
573 rconn_get_ip(const struct rconn *rconn)
575 return rconn->vconn ? vconn_get_ip(rconn->vconn) : 0;
578 /* If 'rconn' can't connect to the peer, it could be for any number of reasons.
579 * Usually, one would assume it is because the peer is not running or because
580 * the network is partitioned. But it could also be because the network
581 * topology has changed, in which case the upper layer will need to reassess it
582 * (in particular, obtain a new IP address via DHCP and find the new location
583 * of the controller). When this appears that this might be the case, this
584 * function returns true. It also clears the questionability flag and prevents
585 * it from being set again for some time. */
587 rconn_is_connectivity_questionable(struct rconn *rconn)
589 bool questionable = rconn->questionable_connectivity;
590 rconn->questionable_connectivity = false;
594 /* Returns the total number of packets successfully received by the underlying
597 rconn_packets_received(const struct rconn *rc)
599 return rc->packets_received;
602 /* Returns a string representing the internal state of 'rc'. The caller must
603 * not modify or free the string. */
605 rconn_get_state(const struct rconn *rc)
607 return state_name(rc->state);
610 /* Returns the number of connection attempts made by 'rc', including any
611 * ongoing attempt that has not yet succeeded or failed. */
613 rconn_get_attempted_connections(const struct rconn *rc)
615 return rc->n_attempted_connections;
618 /* Returns the number of successful connection attempts made by 'rc'. */
620 rconn_get_successful_connections(const struct rconn *rc)
622 return rc->n_successful_connections;
625 /* Returns the time at which the last successful connection was made by
628 rconn_get_last_connection(const struct rconn *rc)
630 return rc->last_connected;
633 /* Returns the time at which 'rc' was created. */
635 rconn_get_creation_time(const struct rconn *rc)
637 return rc->creation_time;
640 /* Returns the approximate number of seconds that 'rc' has been connected. */
642 rconn_get_total_time_connected(const struct rconn *rc)
644 return (rc->total_time_connected
645 + (rconn_is_connected(rc) ? elapsed_in_this_state(rc) : 0));
648 /* Returns the current amount of backoff, in seconds. This is the amount of
649 * time after which the rconn will transition from BACKOFF to CONNECTING. */
651 rconn_get_backoff(const struct rconn *rc)
656 /* Returns the number of seconds spent in this state so far. */
658 rconn_get_state_elapsed(const struct rconn *rc)
660 return elapsed_in_this_state(rc);
663 /* Tries to send a packet from 'rc''s send buffer. Returns 0 if successful,
664 * otherwise a positive errno value. */
666 try_send(struct rconn *rc)
669 struct ofpbuf *next = rc->txq.head->next;
670 int *n_queued = rc->txq.head->private;
671 retval = vconn_send(rc->vconn, rc->txq.head);
673 if (retval != EAGAIN) {
674 disconnect(rc, retval);
682 queue_advance_head(&rc->txq, next);
686 /* Disconnects 'rc'. 'error' is used only for logging purposes. If it is
687 * nonzero, then it should be EOF to indicate the connection was closed by the
688 * peer in a normal fashion or a positive errno value. */
690 disconnect(struct rconn *rc, int error)
693 time_t now = time_now();
695 if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
697 VLOG_WARN("%s: connection dropped (%s)",
698 rc->name, strerror(error));
699 } else if (error == EOF) {
701 VLOG_WARN("%s: connection closed", rc->name);
704 VLOG_WARN("%s: connection dropped", rc->name);
706 vconn_close(rc->vconn);
711 if (now >= rc->backoff_deadline) {
714 rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
715 VLOG_WARN("%s: waiting %d seconds before reconnect\n",
716 rc->name, rc->backoff);
718 rc->backoff_deadline = now + rc->backoff;
719 state_transition(rc, S_BACKOFF);
720 if (now - rc->last_connected > 60) {
721 question_connectivity(rc);
724 rconn_disconnect(rc);
728 /* Drops all the packets from 'rc''s send queue and decrements their queue
731 flush_queue(struct rconn *rc)
736 while (rc->txq.n > 0) {
737 struct ofpbuf *b = queue_pop_head(&rc->txq);
738 int *n_queued = b->private;
744 poll_immediate_wake();
748 elapsed_in_this_state(const struct rconn *rc)
750 return time_now() - rc->state_entered;
754 timeout(const struct rconn *rc)
757 #define STATE(NAME, VALUE) case S_##NAME: return timeout_##NAME(rc);
766 timed_out(const struct rconn *rc)
768 return time_now() >= sat_add(rc->state_entered, timeout(rc));
772 state_transition(struct rconn *rc, enum state state)
774 if (rconn_is_connected(rc)) {
775 rc->total_time_connected += elapsed_in_this_state(rc);
777 VLOG_DBG("%s: entering %s", rc->name, state_name(state));
779 rc->state_entered = time_now();
783 question_connectivity(struct rconn *rc)
785 time_t now = time_now();
786 if (now - rc->last_questioned > 60) {
787 rc->questionable_connectivity = true;
788 rc->last_questioned = now;
793 copy_to_monitor(struct rconn *rc, const struct ofpbuf *b)
795 struct ofpbuf *clone = NULL;
799 for (i = 0; i < rc->n_monitors; ) {
800 struct vconn *vconn = rc->monitors[i];
803 clone = ofpbuf_clone(b);
805 retval = vconn_send(vconn, clone);
808 } else if (retval != EAGAIN) {
809 VLOG_DBG("%s: closing monitor connection to %s: %s",
810 rconn_get_name(rc), vconn_get_name(vconn),
812 rc->monitors[i] = rc->monitors[--rc->n_monitors];
817 ofpbuf_delete(clone);