rconn: Time out connection attempts when the backoff deadline passes.
[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 "rconn.h"
35 #include <assert.h>
36 #include <errno.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include "buffer.h"
40 #include "poll-loop.h"
41 #include "ofp-print.h"
42 #include "timeval.h"
43 #include "util.h"
44 #include "vconn.h"
45
46 #define THIS_MODULE VLM_rconn
47 #include "vlog.h"
48
49 /* A reliable connection to an OpenFlow switch or controller.
50  *
51  * See the large comment in rconn.h for more information. */
52 struct rconn {
53     bool reliable;
54     char *name;
55     struct vconn *vconn;
56     bool connected;
57     struct queue txq;
58     int txq_limit;
59     time_t backoff_deadline;
60     int backoff;
61     int max_backoff;
62     time_t last_connected;
63     unsigned int packets_sent;
64
65     /* Throughout this file, "probe" is shorthand for "inactivity probe".
66      * When nothing has been received from the peer for a while, we send out
67      * an echo request as an inactivity probe packet.  We should receive back
68      * a response. */
69     int probe_interval;         /* Secs of inactivity before sending probe. */
70     time_t probe_sent;          /* Time at which last probe sent, or 0 if none
71                                  * has been sent since 'last_connected'. */
72 };
73
74 static struct rconn *create_rconn(const char *name, int txq_limit,
75                                   int probe_interval, int max_backoff,
76                                   struct vconn *);
77 static int try_send(struct rconn *);
78 static void disconnect(struct rconn *, int error);
79 static time_t probe_deadline(const struct rconn *);
80
81 /* Creates and returns a new rconn that connects (and re-connects as necessary)
82  * to the vconn named 'name'.
83  *
84  * 'txq_limit' is the maximum length of the send queue, in packets.
85  *
86  * 'probe_interval' is a number of seconds.  If the interval passes once
87  * without an OpenFlow message being received from the peer, the rconn sends
88  * out an "echo request" message.  If the interval passes again without a
89  * message being received, the rconn disconnects and re-connects to the peer.
90  * Setting 'probe_interval' to 0 disables this behavior.
91  *
92  * 'max_backoff' is the maximum number of seconds between attempts to connect
93  * to the peer.  The actual interval starts at 1 second and doubles on each
94  * failure until it reaches 'max_backoff'.  If 0 is specified, the default of
95  * 60 seconds is used. */
96 struct rconn *
97 rconn_new(const char *name, int txq_limit, int probe_interval, int max_backoff)
98 {
99     return create_rconn(name, txq_limit, probe_interval, max_backoff, NULL);
100 }
101
102 /* Creates and returns a new rconn that is initially connected to 'vconn' and
103  * has the given 'name'.  The rconn will not re-connect after the connection
104  * drops.
105  *
106  * 'txq_limit' is the maximum length of the send queue, in packets. */
107 struct rconn *
108 rconn_new_from_vconn(const char *name, int txq_limit, struct vconn *vconn)
109 {
110     assert(vconn != NULL);
111     return create_rconn(name, txq_limit, 0, 0, vconn);
112 }
113
114 /* Disconnects 'rc' and frees the underlying storage. */
115 void
116 rconn_destroy(struct rconn *rc)
117 {
118     if (rc) {
119         free(rc->name);
120         vconn_close(rc->vconn);
121         queue_destroy(&rc->txq);
122         free(rc);
123     }
124 }
125
126 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
127  * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
128  * connected, attempts to send packets in the send queue, if any. */
129 void
130 rconn_run(struct rconn *rc)
131 {
132     if (!rc->vconn) {
133         if (rc->reliable && time(0) >= rc->backoff_deadline) {
134             int retval;
135
136             VLOG_WARN("%s: connecting...", rc->name);
137             retval = vconn_open(rc->name, &rc->vconn);
138             if (!retval) {
139                 rc->backoff_deadline = time(0) + rc->backoff;
140                 rc->connected = false;
141             } else {
142                 VLOG_WARN("%s: connection failed (%s)",
143                           rc->name, strerror(retval)); 
144                 disconnect(rc, 0);
145             }
146         }
147     } else if (!rc->connected) {
148         int error = vconn_connect(rc->vconn);
149         if (!error) {
150             VLOG_WARN("%s: connected", rc->name);
151             if (vconn_is_passive(rc->vconn)) {
152                 fatal(0, "%s: passive vconn not supported in switch",
153                       rc->name);
154             }
155             rc->connected = true;
156         } else if (error != EAGAIN) {
157             VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(error));
158             disconnect(rc, 0);
159         } else if (time(0) >= rc->backoff_deadline) {
160             VLOG_WARN("%s: connection timed out", rc->name);
161             rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
162             disconnect(rc, 0);
163         }
164     } else {
165         if (rc->probe_interval) {
166             time_t now = time(0);
167             if (now >= probe_deadline(rc)) {
168                 if (!rc->probe_sent) {
169                     queue_push_tail(&rc->txq, make_echo_request());
170                     rc->probe_sent = now;
171                     VLOG_DBG("%s: idle %d seconds, sending inactivity probe",
172                              rc->name, (int) (now - rc->last_connected)); 
173                 } else {
174                     VLOG_ERR("%s: no response to inactivity probe after %d "
175                              "seconds, disconnecting",
176                              rc->name, (int) (now - rc->probe_sent));
177                     disconnect(rc, 0);
178                 }
179             }
180         }
181         while (rc->txq.n > 0) {
182             int error = try_send(rc);
183             if (error == EAGAIN) {
184                 break;
185             } else if (error) {
186                 disconnect(rc, error);
187                 return;
188             }
189         }
190     }
191 }
192
193 /* Causes the next call to poll_block() to wake up when rconn_run() should be
194  * called on 'rc'. */
195 void
196 rconn_run_wait(struct rconn *rc)
197 {
198     if (rc->vconn) {
199         if (rc->txq.n) {
200             vconn_wait(rc->vconn, WAIT_SEND);
201         }
202         if (rc->probe_interval) {
203             poll_timer_wait((probe_deadline(rc) - time(0)) * 1000);
204         }
205     } else {
206         poll_timer_wait((rc->backoff_deadline - time(0)) * 1000);
207     }
208 }
209
210 /* Returns the time at which, should nothing be received, we should send out an
211  * inactivity probe (if none has yet been sent) or conclude that the connection
212  * is dead (if a probe has already been sent). */
213 static time_t
214 probe_deadline(const struct rconn *rc) 
215 {
216     assert(rc->probe_interval);
217     return (rc->probe_interval
218             + (rc->probe_sent ? rc->probe_sent : rc->last_connected));
219 }
220
221 /* Attempts to receive a packet from 'rc'.  If successful, returns the packet;
222  * otherwise, returns a null pointer.  The caller is responsible for freeing
223  * the packet (with buffer_delete()). */
224 struct buffer *
225 rconn_recv(struct rconn *rc)
226 {
227     if (rc->vconn && rc->connected) {
228         struct buffer *buffer;
229         int error = vconn_recv(rc->vconn, &buffer);
230         if (!error) {
231             rc->last_connected = time(0);
232             rc->probe_sent = 0;
233             return buffer;
234         } else if (error != EAGAIN) {
235             disconnect(rc, error); 
236         }
237     }
238     return NULL;
239 }
240
241 /* Causes the next call to poll_block() to wake up when a packet may be ready
242  * to be received by vconn_recv() on 'rc'.  */
243 void
244 rconn_recv_wait(struct rconn *rc) 
245 {
246     if (rc->vconn) {
247         vconn_wait(rc->vconn, WAIT_RECV);
248     }
249 }
250
251 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if at least 'txq_limit'
252  * packets are already queued, otherwise a positive errno value. */
253 int
254 do_send(struct rconn *rc, struct buffer *b, int txq_limit)
255 {
256     if (rc->vconn) {
257         if (rc->txq.n < txq_limit) {
258             queue_push_tail(&rc->txq, b);
259             if (rc->txq.n == 1) {
260                 try_send(rc);
261             }
262             return 0;
263         } else {
264             return EAGAIN;
265         }
266     } else {
267         return ENOTCONN;
268     }
269 }
270
271 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if the send queue is
272  * full, or ENOTCONN if 'rc' is not currently connected.
273  *
274  * There is no rconn_send_wait() function: an rconn has a send queue that it
275  * takes care of sending if you call rconn_run(), which will have the side
276  * effect of waking up poll_block(). */
277 int
278 rconn_send(struct rconn *rc, struct buffer *b)
279 {
280     return do_send(rc, b, rc->txq_limit);
281 }
282
283 /* Sends 'b' on 'rc'.  Returns 0 if successful, EAGAIN if the send queue is
284  * full, otherwise a positive errno value.
285  *
286  * Compared to rconn_send(), this function relaxes the queue limit, allowing
287  * more packets than usual to be queued. */
288 int
289 rconn_force_send(struct rconn *rc, struct buffer *b)
290 {
291     return do_send(rc, b, 2 * rc->txq_limit);
292 }
293
294 /* Returns true if 'rc''s send buffer is full,
295  * false if it has room for at least one more packet. */
296 bool
297 rconn_is_full(const struct rconn *rc) 
298 {
299     return rc->txq.n >= rc->txq_limit;
300 }
301
302 /* Returns the total number of packets successfully sent on the underlying
303  * vconn.  A packet is not counted as sent while it is still queued in the
304  * rconn, only when it has been successfuly passed to the vconn.  */
305 unsigned int
306 rconn_packets_sent(const struct rconn *rc) 
307 {
308     return rc->packets_sent;
309 }
310
311 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
312 const char *
313 rconn_get_name(const struct rconn *rc) 
314 {
315     return rc->name;
316 }
317
318 /* Returns true if 'rconn' is connected or in the process of reconnecting,
319  * false if 'rconn' is disconnected and will not be reconnected. */
320 bool
321 rconn_is_alive(const struct rconn *rconn) 
322 {
323     return rconn->reliable || rconn->vconn;
324 }
325
326 /* Returns true if 'rconn' is connected, false otherwise. */
327 bool
328 rconn_is_connected(const struct rconn *rconn)
329 {
330     return rconn->vconn && !vconn_connect(rconn->vconn);
331 }
332
333 /* Returns 0 if 'rconn' is connected, otherwise the number of seconds that it
334  * has been disconnected. */
335 int
336 rconn_disconnected_duration(const struct rconn *rconn) 
337 {
338     return rconn_is_connected(rconn) ? 0 : time(0) - rconn->last_connected;
339 }
340
341 /* Returns the IP address of the peer, or 0 if the peer is not connected over
342  * an IP-based protocol or if its IP address is not known. */
343 uint32_t
344 rconn_get_ip(const struct rconn *rconn) 
345 {
346     return rconn->vconn ? vconn_get_ip(rconn->vconn) : 0;
347 }
348 \f
349 static struct rconn *
350 create_rconn(const char *name, int txq_limit, int probe_interval,
351              int max_backoff, struct vconn *vconn)
352 {
353     struct rconn *rc = xmalloc(sizeof *rc);
354     assert(txq_limit > 0);
355     rc->reliable = vconn == NULL;
356     rc->connected = vconn != NULL;
357     rc->name = xstrdup(name);
358     rc->vconn = vconn;
359     queue_init(&rc->txq);
360     rc->txq_limit = txq_limit;
361     rc->backoff_deadline = time(0);
362     rc->backoff = 0;
363     rc->max_backoff = max_backoff ? max_backoff : 60;
364     rc->last_connected = time(0);
365     rc->probe_interval = (probe_interval
366                               ? MAX(5, probe_interval) : 0);
367     rc->probe_sent = 0;
368     rc->packets_sent = 0;
369     return rc;
370 }
371
372 /* Tries to send a packet from 'rc''s send buffer.  Returns 0 if successful,
373  * otherwise a positive errno value. */
374 static int
375 try_send(struct rconn *rc)
376 {
377     int retval = 0;
378     struct buffer *next = rc->txq.head->next;
379     retval = vconn_send(rc->vconn, rc->txq.head);
380     if (retval) {
381         return retval;
382     }
383     rc->packets_sent++;
384     queue_advance_head(&rc->txq, next);
385     return 0;
386 }
387
388 /* Disconnects 'rc'.  'error' is used only for logging purposes.  If it is
389  * nonzero, then it should be EOF to indicate the connection was closed by the
390  * peer in a normal fashion or a positive errno value. */
391 static void
392 disconnect(struct rconn *rc, int error) 
393 {
394     time_t now = time(0);
395     
396     if (rc->vconn) {
397         if (error > 0) {
398             VLOG_WARN("%s: connection dropped (%s)",
399                       rc->name, strerror(error)); 
400         } else if (error == EOF) {
401             if (rc->reliable) {
402                 VLOG_WARN("%s: connection closed", rc->name);
403             }
404         } else {
405             VLOG_WARN("%s: connection dropped", rc->name); 
406         }
407         vconn_close(rc->vconn);
408         rc->vconn = NULL;
409         queue_clear(&rc->txq);
410     }
411
412     if (now >= rc->backoff_deadline) {
413         rc->backoff = 1;
414     } else {
415         rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
416         VLOG_WARN("%s: waiting %d seconds before reconnect\n",
417                   rc->name, rc->backoff);
418     }
419     rc->backoff_deadline = now + rc->backoff;
420     rc->probe_sent = 0;
421 }