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