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 /* In S_ACTIVE and S_IDLE, probably_admitted reports whether we believe
96 * that the peer has made a (positive) admission control decision on our
97 * connection. If we have not yet been (probably) admitted, then the
98 * connection does not reset the timer used for deciding whether the switch
99 * should go into fail-open mode.
101 * last_admitted reports the last time we believe such a positive admission
102 * control decision was made. */
103 bool probably_admitted;
104 time_t last_admitted;
106 /* These values are simply for statistics reporting, not used directly by
107 * anything internal to the rconn (or the secchan for that matter). */
108 unsigned int packets_received;
109 unsigned int n_attempted_connections, n_successful_connections;
110 time_t creation_time;
111 unsigned long int total_time_connected;
113 /* If we can't connect to the peer, it could be for any number of reasons.
114 * Usually, one would assume it is because the peer is not running or
115 * because the network is partitioned. But it could also be because the
116 * network topology has changed, in which case the upper layer will need to
117 * reassess it (in particular, obtain a new IP address via DHCP and find
118 * the new location of the controller). We set this flag when we suspect
119 * that this could be the case. */
120 bool questionable_connectivity;
121 time_t last_questioned;
123 /* Throughout this file, "probe" is shorthand for "inactivity probe".
124 * When nothing has been received from the peer for a while, we send out
125 * an echo request as an inactivity probe packet. We should receive back
127 int probe_interval; /* Secs of inactivity before sending probe. */
129 /* Messages sent or received are copied to the monitor connections. */
130 #define MAX_MONITORS 8
131 struct vconn *monitors[8];
135 static unsigned int elapsed_in_this_state(const struct rconn *);
136 static unsigned int timeout(const struct rconn *);
137 static bool timed_out(const struct rconn *);
138 static void state_transition(struct rconn *, enum state);
139 static int try_send(struct rconn *);
140 static int reconnect(struct rconn *);
141 static void disconnect(struct rconn *, int error);
142 static void flush_queue(struct rconn *);
143 static void question_connectivity(struct rconn *);
144 static void copy_to_monitor(struct rconn *, const struct ofpbuf *);
145 static bool is_connected_state(enum state);
146 static bool is_admitted_msg(const struct ofpbuf *);
148 /* Creates a new rconn, connects it (reliably) to 'name', and returns it. */
150 rconn_new(const char *name, int inactivity_probe_interval, int max_backoff)
152 struct rconn *rc = rconn_create(inactivity_probe_interval, max_backoff);
153 rconn_connect(rc, name);
157 /* Creates a new rconn, connects it (unreliably) to 'vconn', and returns it. */
159 rconn_new_from_vconn(const char *name, struct vconn *vconn)
161 struct rconn *rc = rconn_create(60, 0);
162 rconn_connect_unreliably(rc, name, vconn);
166 /* Creates and returns a new rconn.
168 * 'probe_interval' is a number of seconds. If the interval passes once
169 * without an OpenFlow message being received from the peer, the rconn sends
170 * out an "echo request" message. If the interval passes again without a
171 * message being received, the rconn disconnects and re-connects to the peer.
172 * Setting 'probe_interval' to 0 disables this behavior.
174 * 'max_backoff' is the maximum number of seconds between attempts to connect
175 * to the peer. The actual interval starts at 1 second and doubles on each
176 * failure until it reaches 'max_backoff'. If 0 is specified, the default of
177 * 60 seconds is used. */
179 rconn_create(int probe_interval, int max_backoff)
181 struct rconn *rc = xcalloc(1, sizeof *rc);
184 rc->state_entered = time_now();
187 rc->name = xstrdup("void");
188 rc->reliable = false;
190 queue_init(&rc->txq);
193 rc->max_backoff = max_backoff ? max_backoff : 60;
194 rc->backoff_deadline = TIME_MIN;
195 rc->last_received = time_now();
196 rc->last_connected = time_now();
198 rc->packets_sent = 0;
200 rc->probably_admitted = false;
201 rc->last_admitted = time_now();
203 rc->packets_received = 0;
204 rc->n_attempted_connections = 0;
205 rc->n_successful_connections = 0;
206 rc->creation_time = time_now();
207 rc->total_time_connected = 0;
209 rc->questionable_connectivity = false;
210 rc->last_questioned = time_now();
212 rc->probe_interval = probe_interval ? MAX(5, probe_interval) : 0;
220 rconn_connect(struct rconn *rc, const char *name)
222 rconn_disconnect(rc);
224 rc->name = xstrdup(name);
226 return reconnect(rc);
230 rconn_connect_unreliably(struct rconn *rc,
231 const char *name, struct vconn *vconn)
233 assert(vconn != NULL);
234 rconn_disconnect(rc);
236 rc->name = xstrdup(name);
237 rc->reliable = false;
239 rc->last_connected = time_now();
240 state_transition(rc, S_ACTIVE);
244 rconn_disconnect(struct rconn *rc)
246 if (rc->state != S_VOID) {
248 vconn_close(rc->vconn);
252 rc->name = xstrdup("void");
253 rc->reliable = false;
256 rc->backoff_deadline = TIME_MIN;
258 state_transition(rc, S_VOID);
262 /* Disconnects 'rc' and frees the underlying storage. */
264 rconn_destroy(struct rconn *rc)
268 vconn_close(rc->vconn);
270 queue_destroy(&rc->txq);
276 timeout_VOID(const struct rconn *rc)
282 run_VOID(struct rconn *rc)
288 reconnect(struct rconn *rc)
292 VLOG_WARN("%s: connecting...", rc->name);
293 rc->n_attempted_connections++;
294 retval = vconn_open(rc->name, OFP_VERSION, &rc->vconn);
296 rc->backoff_deadline = time_now() + rc->backoff;
297 state_transition(rc, S_CONNECTING);
299 VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
300 rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
307 timeout_BACKOFF(const struct rconn *rc)
313 run_BACKOFF(struct rconn *rc)
321 timeout_CONNECTING(const struct rconn *rc)
323 return MAX(1, rc->backoff);
327 run_CONNECTING(struct rconn *rc)
329 int retval = vconn_connect(rc->vconn);
331 VLOG_WARN("%s: connected", rc->name);
332 rc->n_successful_connections++;
333 state_transition(rc, S_ACTIVE);
334 rc->last_connected = rc->state_entered;
335 } else if (retval != EAGAIN) {
336 VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
337 disconnect(rc, retval);
338 } else if (timed_out(rc)) {
339 VLOG_WARN("%s: connection timed out", rc->name);
340 rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
346 do_tx_work(struct rconn *rc)
351 while (rc->txq.n > 0) {
352 int error = try_send(rc);
358 poll_immediate_wake();
363 timeout_ACTIVE(const struct rconn *rc)
365 if (rc->probe_interval) {
366 unsigned int base = MAX(rc->last_received, rc->state_entered);
367 unsigned int arg = base + rc->probe_interval - rc->state_entered;
374 run_ACTIVE(struct rconn *rc)
377 unsigned int base = MAX(rc->last_received, rc->state_entered);
378 rconn_send(rc, make_echo_request(), NULL);
379 VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
380 rc->name, (unsigned int) (time_now() - base));
381 state_transition(rc, S_IDLE);
389 timeout_IDLE(const struct rconn *rc)
391 return rc->probe_interval;
395 run_IDLE(struct rconn *rc)
398 question_connectivity(rc);
399 VLOG_ERR("%s: no response to inactivity probe after %u "
400 "seconds, disconnecting",
401 rc->name, elapsed_in_this_state(rc));
408 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
409 * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
410 * connected, attempts to send packets in the send queue, if any. */
412 rconn_run(struct rconn *rc)
416 old_state = rc->state;
418 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
424 } while (rc->state != old_state);
427 /* Causes the next call to poll_block() to wake up when rconn_run() should be
430 rconn_run_wait(struct rconn *rc)
432 unsigned int timeo = timeout(rc);
433 if (timeo != UINT_MAX) {
434 unsigned int expires = sat_add(rc->state_entered, timeo);
435 unsigned int remaining = sat_sub(expires, time_now());
436 poll_timer_wait(sat_mul(remaining, 1000));
439 if ((rc->state & (S_ACTIVE | S_IDLE)) && rc->txq.n) {
440 vconn_wait(rc->vconn, WAIT_SEND);
444 /* Attempts to receive a packet from 'rc'. If successful, returns the packet;
445 * otherwise, returns a null pointer. The caller is responsible for freeing
446 * the packet (with ofpbuf_delete()). */
448 rconn_recv(struct rconn *rc)
450 if (rc->state & (S_ACTIVE | S_IDLE)) {
451 struct ofpbuf *buffer;
452 int error = vconn_recv(rc->vconn, &buffer);
454 copy_to_monitor(rc, buffer);
455 if (is_admitted_msg(buffer)
456 || time_now() - rc->last_connected >= 30) {
457 rc->probably_admitted = true;
458 rc->last_admitted = time_now();
460 rc->last_received = time_now();
461 rc->packets_received++;
462 if (rc->state == S_IDLE) {
463 state_transition(rc, S_ACTIVE);
466 } else if (error != EAGAIN) {
467 disconnect(rc, error);
473 /* Causes the next call to poll_block() to wake up when a packet may be ready
474 * to be received by vconn_recv() on 'rc'. */
476 rconn_recv_wait(struct rconn *rc)
479 vconn_wait(rc->vconn, WAIT_RECV);
483 /* Sends 'b' on 'rc'. Returns 0 if successful (in which case 'b' is
484 * destroyed), or ENOTCONN if 'rc' is not currently connected (in which case
485 * the caller retains ownership of 'b').
487 * If 'n_queued' is non-null, then '*n_queued' will be incremented while the
488 * packet is in flight, then decremented when it has been sent (or discarded
489 * due to disconnection). Because 'b' may be sent (or discarded) before this
490 * function returns, the caller may not be able to observe any change in
493 * There is no rconn_send_wait() function: an rconn has a send queue that it
494 * takes care of sending if you call rconn_run(), which will have the side
495 * effect of waking up poll_block(). */
497 rconn_send(struct rconn *rc, struct ofpbuf *b, int *n_queued)
499 if (rconn_is_connected(rc)) {
500 copy_to_monitor(rc, b);
501 b->private = n_queued;
505 queue_push_tail(&rc->txq, b);
506 if (rc->txq.n == 1) {
515 /* Sends 'b' on 'rc'. Increments '*n_queued' while the packet is in flight; it
516 * will be decremented when it has been sent (or discarded due to
517 * disconnection). Returns 0 if successful, EAGAIN if '*n_queued' is already
518 * at least as large as 'queue_limit', or ENOTCONN if 'rc' is not currently
519 * connected. Regardless of return value, 'b' is destroyed.
521 * Because 'b' may be sent (or discarded) before this function returns, the
522 * caller may not be able to observe any change in '*n_queued'.
524 * There is no rconn_send_wait() function: an rconn has a send queue that it
525 * takes care of sending if you call rconn_run(), which will have the side
526 * effect of waking up poll_block(). */
528 rconn_send_with_limit(struct rconn *rc, struct ofpbuf *b,
529 int *n_queued, int queue_limit)
532 retval = *n_queued >= queue_limit ? EAGAIN : rconn_send(rc, b, n_queued);
539 /* Returns the total number of packets successfully sent on the underlying
540 * vconn. A packet is not counted as sent while it is still queued in the
541 * rconn, only when it has been successfuly passed to the vconn. */
543 rconn_packets_sent(const struct rconn *rc)
545 return rc->packets_sent;
548 /* Adds 'vconn' to 'rc' as a monitoring connection, to which all messages sent
549 * and received on 'rconn' will be copied. 'rc' takes ownership of 'vconn'. */
551 rconn_add_monitor(struct rconn *rc, struct vconn *vconn)
553 if (rc->n_monitors < ARRAY_SIZE(rc->monitors)) {
554 VLOG_WARN("new monitor connection from %s", vconn_get_name(vconn));
555 rc->monitors[rc->n_monitors++] = vconn;
557 VLOG_DBG("too many monitor connections, discarding %s",
558 vconn_get_name(vconn));
563 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
565 rconn_get_name(const struct rconn *rc)
570 /* Returns true if 'rconn' is connected or in the process of reconnecting,
571 * false if 'rconn' is disconnected and will not reconnect on its own. */
573 rconn_is_alive(const struct rconn *rconn)
575 return rconn->state != S_VOID;
578 /* Returns true if 'rconn' is connected, false otherwise. */
580 rconn_is_connected(const struct rconn *rconn)
582 return is_connected_state(rconn->state);
585 /* Returns 0 if 'rconn' is connected and the connection is believed to have
586 * been accepted by the controller. Otherwise, if 'rconn' is in a "failure
587 * mode" (that is, it is not connected or if it has recently connected and the
588 * controller is not yet believed to have made an admission control decision
589 * for this switch), returns the number of seconds that it has been in failure
592 rconn_failure_duration(const struct rconn *rconn)
594 return (rconn_is_connected(rconn) && rconn->probably_admitted
596 : time_now() - rconn->last_admitted);
599 /* Returns the IP address of the peer, or 0 if the peer is not connected over
600 * an IP-based protocol or if its IP address is not known. */
602 rconn_get_ip(const struct rconn *rconn)
604 return rconn->vconn ? vconn_get_ip(rconn->vconn) : 0;
607 /* If 'rconn' can't connect to the peer, it could be for any number of reasons.
608 * Usually, one would assume it is because the peer is not running or because
609 * the network is partitioned. But it could also be because the network
610 * topology has changed, in which case the upper layer will need to reassess it
611 * (in particular, obtain a new IP address via DHCP and find the new location
612 * of the controller). When this appears that this might be the case, this
613 * function returns true. It also clears the questionability flag and prevents
614 * it from being set again for some time. */
616 rconn_is_connectivity_questionable(struct rconn *rconn)
618 bool questionable = rconn->questionable_connectivity;
619 rconn->questionable_connectivity = false;
623 /* Returns the total number of packets successfully received by the underlying
626 rconn_packets_received(const struct rconn *rc)
628 return rc->packets_received;
631 /* Returns a string representing the internal state of 'rc'. The caller must
632 * not modify or free the string. */
634 rconn_get_state(const struct rconn *rc)
636 return state_name(rc->state);
639 /* Returns the number of connection attempts made by 'rc', including any
640 * ongoing attempt that has not yet succeeded or failed. */
642 rconn_get_attempted_connections(const struct rconn *rc)
644 return rc->n_attempted_connections;
647 /* Returns the number of successful connection attempts made by 'rc'. */
649 rconn_get_successful_connections(const struct rconn *rc)
651 return rc->n_successful_connections;
654 /* Returns the time at which the last successful connection was made by
657 rconn_get_last_connection(const struct rconn *rc)
659 return rc->last_connected;
662 /* Returns the time at which 'rc' was created. */
664 rconn_get_creation_time(const struct rconn *rc)
666 return rc->creation_time;
669 /* Returns the approximate number of seconds that 'rc' has been connected. */
671 rconn_get_total_time_connected(const struct rconn *rc)
673 return (rc->total_time_connected
674 + (rconn_is_connected(rc) ? elapsed_in_this_state(rc) : 0));
677 /* Returns the current amount of backoff, in seconds. This is the amount of
678 * time after which the rconn will transition from BACKOFF to CONNECTING. */
680 rconn_get_backoff(const struct rconn *rc)
685 /* Returns the number of seconds spent in this state so far. */
687 rconn_get_state_elapsed(const struct rconn *rc)
689 return elapsed_in_this_state(rc);
692 /* Tries to send a packet from 'rc''s send buffer. Returns 0 if successful,
693 * otherwise a positive errno value. */
695 try_send(struct rconn *rc)
698 struct ofpbuf *next = rc->txq.head->next;
699 int *n_queued = rc->txq.head->private;
700 retval = vconn_send(rc->vconn, rc->txq.head);
702 if (retval != EAGAIN) {
703 disconnect(rc, retval);
711 queue_advance_head(&rc->txq, next);
715 /* Disconnects 'rc'. 'error' is used only for logging purposes. If it is
716 * nonzero, then it should be EOF to indicate the connection was closed by the
717 * peer in a normal fashion or a positive errno value. */
719 disconnect(struct rconn *rc, int error)
722 time_t now = time_now();
724 if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
726 VLOG_WARN("%s: connection dropped (%s)",
727 rc->name, strerror(error));
728 } else if (error == EOF) {
730 VLOG_WARN("%s: connection closed", rc->name);
733 VLOG_WARN("%s: connection dropped", rc->name);
735 vconn_close(rc->vconn);
740 if (now >= rc->backoff_deadline) {
743 rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
744 VLOG_WARN("%s: waiting %d seconds before reconnect\n",
745 rc->name, rc->backoff);
747 rc->backoff_deadline = now + rc->backoff;
748 state_transition(rc, S_BACKOFF);
749 if (now - rc->last_connected > 60) {
750 question_connectivity(rc);
753 rconn_disconnect(rc);
757 /* Drops all the packets from 'rc''s send queue and decrements their queue
760 flush_queue(struct rconn *rc)
765 while (rc->txq.n > 0) {
766 struct ofpbuf *b = queue_pop_head(&rc->txq);
767 int *n_queued = b->private;
773 poll_immediate_wake();
777 elapsed_in_this_state(const struct rconn *rc)
779 return time_now() - rc->state_entered;
783 timeout(const struct rconn *rc)
786 #define STATE(NAME, VALUE) case S_##NAME: return timeout_##NAME(rc);
795 timed_out(const struct rconn *rc)
797 return time_now() >= sat_add(rc->state_entered, timeout(rc));
801 state_transition(struct rconn *rc, enum state state)
803 if (is_connected_state(state) && !is_connected_state(rc->state)) {
804 rc->probably_admitted = false;
806 if (rconn_is_connected(rc)) {
807 rc->total_time_connected += elapsed_in_this_state(rc);
809 VLOG_DBG("%s: entering %s", rc->name, state_name(state));
811 rc->state_entered = time_now();
815 question_connectivity(struct rconn *rc)
817 time_t now = time_now();
818 if (now - rc->last_questioned > 60) {
819 rc->questionable_connectivity = true;
820 rc->last_questioned = now;
825 copy_to_monitor(struct rconn *rc, const struct ofpbuf *b)
827 struct ofpbuf *clone = NULL;
831 for (i = 0; i < rc->n_monitors; ) {
832 struct vconn *vconn = rc->monitors[i];
835 clone = ofpbuf_clone(b);
837 retval = vconn_send(vconn, clone);
840 } else if (retval != EAGAIN) {
841 VLOG_DBG("%s: closing monitor connection to %s: %s",
842 rconn_get_name(rc), vconn_get_name(vconn),
844 rc->monitors[i] = rc->monitors[--rc->n_monitors];
849 ofpbuf_delete(clone);
853 is_connected_state(enum state state)
855 return (state & (S_ACTIVE | S_IDLE)) != 0;
859 is_admitted_msg(const struct ofpbuf *b)
861 struct ofp_header *oh = b->data;
862 uint8_t type = oh->type;
864 && (1u << type) & ((1u << OFPT_HELLO) |
866 (1u << OFPT_ECHO_REQUEST) |
867 (1u << OFPT_ECHO_REPLY) |
868 (1u << OFPT_VENDOR) |
869 (1u << OFPT_FEATURES_REQUEST) |
870 (1u << OFPT_FEATURES_REPLY) |
871 (1u << OFPT_GET_CONFIG_REQUEST) |
872 (1u << OFPT_GET_CONFIG_REPLY) |
873 (1u << OFPT_SET_CONFIG)));