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