3a29043df729df269917ae950d1194f6338dfd4e
[sliver-openvswitch.git] / controller / controller.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 <assert.h>
35 #include <errno.h>
36 #include <getopt.h>
37 #include <inttypes.h>
38 #include <netinet/in.h>
39 #include <poll.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43
44 #include "buffer.h"
45 #include "command-line.h"
46 #include "compiler.h"
47 #include "fault.h"
48 #include "flow.h"
49 #include "hash.h"
50 #include "list.h"
51 #include "ofp-print.h"
52 #include "mac-learning.h"
53 #include "openflow.h"
54 #include "packets.h"
55 #include "poll-loop.h"
56 #include "queue.h"
57 #include "time.h"
58 #include "util.h"
59 #include "vconn-ssl.h"
60 #include "vconn.h"
61 #include "vlog-socket.h"
62 #include "xtoxll.h"
63
64 #include "vlog.h"
65 #define THIS_MODULE VLM_controller
66
67 #define MAX_SWITCHES 16
68 #define MAX_TXQ 128
69
70 struct switch_ {
71     char *name;
72     struct vconn *vconn;
73
74     uint64_t datapath_id;
75     time_t last_features_request;
76
77     struct queue txq;
78     struct mac_learning *ml;
79 };
80
81 /* Learn the ports on which MAC addresses appear? */
82 static bool learn_macs = true;
83
84 /* Set up flows?  (If not, every packet is processed at the controller.) */
85 static bool setup_flows = true;
86
87 static void parse_options(int argc, char *argv[]);
88 static void usage(void) NO_RETURN;
89
90 static struct switch_ *connect_switch(const char *name);
91 static struct switch_ *new_switch(const char *name, struct vconn *);
92 static void close_switch(struct switch_ *);
93
94 static void queue_tx(struct switch_ *, struct buffer *);
95
96 static void send_features_request(struct switch_ *);
97
98 static int do_switch_recv(struct switch_ *this);
99 static int do_switch_send(struct switch_ *this);
100
101 static void process_packet(struct switch_ *, struct buffer *);
102 static void process_packet_in(struct switch_ *, struct ofp_packet_in *);
103
104 int
105 main(int argc, char *argv[])
106 {
107     struct switch_ *switches[MAX_SWITCHES];
108     int n_switches;
109     int retval;
110     int i;
111
112     set_program_name(argv[0]);
113     register_fault_handlers();
114     vlog_init();
115     parse_options(argc, argv);
116
117     if (argc - optind < 1) {
118         fatal(0, "at least one vconn argument required; use --help for usage");
119     }
120
121     retval = vlog_server_listen(NULL, NULL);
122     if (retval) {
123         fatal(retval, "Could not listen for vlog connections");
124     }
125
126     n_switches = 0;
127     for (i = 0; i < argc - optind; i++) {
128         struct switch_ *this = connect_switch(argv[optind + i]);
129         if (this) {
130             if (n_switches >= MAX_SWITCHES) {
131                 fatal(0, "max %d switch connections", n_switches);
132             }
133             switches[n_switches++] = this;
134         }
135     }
136     if (n_switches == 0) {
137         fatal(0, "could not connect to any switches");
138     }
139
140     while (n_switches > 0) {
141         /* Do some work.  Limit the number of iterations so that callbacks
142          * registered with the poll loop don't starve. */
143         int iteration;
144         int i;
145         for (iteration = 0; iteration < 50; iteration++) {
146             bool progress = false;
147             for (i = 0; i < n_switches; ) {
148                 struct switch_ *this = switches[i];
149                 int retval;
150
151                 if (vconn_is_passive(this->vconn)) {
152                     retval = 0;
153                     while (n_switches < MAX_SWITCHES) {
154                         struct vconn *new_vconn;
155                         retval = vconn_accept(this->vconn, &new_vconn);
156                         if (retval) {
157                             break;
158                         }
159                         switches[n_switches++] = new_switch("tcp", new_vconn);
160                     }
161                 } else {
162                     retval = do_switch_recv(this);
163                     if (!retval || retval == EAGAIN) {
164                         do {
165                             retval = do_switch_send(this);
166                             if (!retval) {
167                                 progress = true;
168                             }
169                         } while (!retval);
170                     }
171                 }
172
173                 if (retval && retval != EAGAIN) {
174                     close_switch(this);
175                     switches[i] = switches[--n_switches];
176                 } else {
177                     i++;
178                 }
179             }
180             if (!progress) {
181                 break;
182             }
183         }
184
185         /* Wait for something to happen. */
186         for (i = 0; i < n_switches; i++) {
187             struct switch_ *this = switches[i];
188             if (vconn_is_passive(this->vconn)) {
189                 if (n_switches < MAX_SWITCHES) {
190                     vconn_accept_wait(this->vconn);
191                 }
192             } else {
193                 vconn_recv_wait(this->vconn);
194                 if (this->txq.n) {
195                     vconn_send_wait(this->vconn);
196                 }
197             }
198         }
199         poll_block();
200     }
201
202     return 0;
203 }
204
205 static int
206 do_switch_recv(struct switch_ *this) 
207 {
208     struct buffer *msg;
209     int retval;
210
211     retval = vconn_recv(this->vconn, &msg);
212     if (!retval) {
213         process_packet(this, msg);
214         buffer_delete(msg);
215     }
216     return retval;
217 }
218
219 static int
220 do_switch_send(struct switch_ *this) 
221 {
222     int retval = 0;
223     if (this->txq.n) {
224         struct buffer *next = this->txq.head->next;
225         retval = vconn_send(this->vconn, this->txq.head);
226         if (retval) {
227             return retval;
228         }
229         queue_advance_head(&this->txq, next);
230         return 0;
231     }
232     return EAGAIN;
233 }
234
235 struct switch_ *
236 connect_switch(const char *name) 
237 {
238     struct vconn *vconn;
239     int retval;
240
241     retval = vconn_open(name, &vconn);
242     if (retval) {
243         VLOG_ERR("%s: connect: %s", name, strerror(retval));
244         return NULL;
245     }
246
247     return new_switch(name, vconn);
248 }
249
250 static struct switch_ *
251 new_switch(const char *name, struct vconn *vconn) 
252 {
253     struct switch_ *this = xmalloc(sizeof *this);
254     memset(this, 0, sizeof *this);
255     this->name = xstrdup(name);
256     this->vconn = vconn;
257     queue_init(&this->txq);
258     this->last_features_request = 0;
259     if (!vconn_is_passive(vconn)) {
260         send_features_request(this);
261     }
262     if (learn_macs) {
263         this->ml = mac_learning_create(); 
264     }
265     return this;
266 }
267
268 static void
269 close_switch(struct switch_ *this) 
270 {
271     if (this) {
272         free(this->name);
273         vconn_close(this->vconn);
274         queue_destroy(&this->txq);
275         mac_learning_destroy(this->ml);
276         free(this);
277     }
278 }
279
280 static void
281 send_features_request(struct switch_ *this)
282 {
283     time_t now = time(0);
284     if (now >= this->last_features_request + 1) {
285         struct buffer *b;
286         struct ofp_header *ofr;
287         struct ofp_switch_config *osc;
288
289         /* Send OFPT_FEATURES_REQUEST. */
290         b = buffer_new(0);
291         ofr = buffer_put_uninit(b, sizeof *ofr);
292         memset(ofr, 0, sizeof *ofr);
293         ofr->type = OFPT_FEATURES_REQUEST;
294         ofr->version = OFP_VERSION;
295         ofr->length = htons(sizeof *ofr);
296         queue_tx(this, b);
297
298         /* Send OFPT_SET_CONFIG. */
299         b = buffer_new(0);
300         osc = buffer_put_uninit(b, sizeof *osc);
301         memset(osc, 0, sizeof *osc);
302         osc->header.type = OFPT_SET_CONFIG;
303         osc->header.version = OFP_VERSION;
304         osc->header.length = htons(sizeof *osc);
305         osc->flags = htons(OFPC_SEND_FLOW_EXP);
306         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
307         queue_tx(this, b);
308
309         this->last_features_request = now;
310     }
311 }
312
313 static void
314 queue_tx(struct switch_ *this, struct buffer *b) 
315 {
316     queue_push_tail(&this->txq, b);
317 }
318
319 static void
320 process_packet(struct switch_ *sw, struct buffer *msg) 
321 {
322     static const size_t min_size[UINT8_MAX + 1] = {
323         [0 ... UINT8_MAX] = sizeof (struct ofp_header),
324         [OFPT_FEATURES_REPLY] = sizeof (struct ofp_switch_features),
325         [OFPT_PACKET_IN] = offsetof (struct ofp_packet_in, data),
326     };
327     struct ofp_header *oh;
328
329     oh = msg->data;
330     if (msg->size < min_size[oh->type]) {
331         VLOG_WARN("%s: too short (%zu bytes) for type %"PRIu8" (min %zu)",
332                   sw->name, msg->size, oh->type, min_size[oh->type]);
333         return;
334     }
335
336     if (oh->type == OFPT_FEATURES_REPLY) {
337         struct ofp_switch_features *osf = msg->data;
338         sw->datapath_id = osf->datapath_id;
339     } else if (sw->datapath_id == 0) {
340         send_features_request(sw);
341     } else if (oh->type == OFPT_PACKET_IN) {
342         struct ofp_packet_in *opi = msg->data;
343         if (sw->txq.n >= MAX_TXQ) {
344             /* FIXME: ratelimit. */
345             VLOG_WARN("%s: tx queue overflow", sw->name);
346         } else {
347             process_packet_in(sw, opi);
348         }
349     } else {
350         if (VLOG_IS_DBG_ENABLED()) {
351             char *p = ofp_to_string(msg->data, msg->size, 2);
352             VLOG_DBG("OpenFlow packet ignored: %s", p);
353             free(p);
354         }
355     }
356 }
357
358 static void
359 process_packet_in(struct switch_ *sw, struct ofp_packet_in *opi) 
360 {
361     uint16_t in_port = ntohs(opi->in_port);
362     uint16_t out_port = OFPP_FLOOD;
363
364     size_t pkt_ofs, pkt_len;
365     struct buffer pkt;
366     struct flow flow;
367
368     /* Extract flow data from 'opi' into 'flow'. */
369     pkt_ofs = offsetof(struct ofp_packet_in, data);
370     pkt_len = ntohs(opi->header.length) - pkt_ofs;
371     pkt.data = opi->data;
372     pkt.size = pkt_len;
373     flow_extract(&pkt, in_port, &flow);
374
375     if (learn_macs) {
376         if (mac_learning_learn(sw->ml, flow.dl_src, in_port)) {
377             VLOG_DBG("learned that "ETH_ADDR_FMT" is on datapath %"
378                      PRIx64" port %"PRIu16, ETH_ADDR_ARGS(flow.dl_src),
379                      ntohll(sw->datapath_id), in_port);
380         }
381         out_port = mac_learning_lookup(sw->ml, flow.dl_dst);
382     }
383
384     if (setup_flows && (!learn_macs || out_port != OFPP_FLOOD)) {
385         /* The output port is known, or we always flood everything, so add a
386          * new flow. */
387         queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
388                                           out_port));
389
390         /* If the switch didn't buffer the packet, we need to send a copy. */
391         if (ntohl(opi->buffer_id) == UINT32_MAX) {
392             queue_tx(sw, make_unbuffered_packet_out(&pkt, in_port, out_port));
393         }
394     } else {
395         /* We don't know that MAC, or we don't set up flows.  Send along the
396          * packet without setting up a flow. */
397         struct buffer *b;
398         if (ntohl(opi->buffer_id) == UINT32_MAX) {
399             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
400         } else {
401             b = make_buffered_packet_out(ntohl(opi->buffer_id),
402                                          in_port, out_port);
403         }
404         queue_tx(sw, b);
405     }
406 }
407
408 static void
409 parse_options(int argc, char *argv[])
410 {
411     static struct option long_options[] = {
412         {"hub",         no_argument, 0, 'H'},
413         {"noflow",      no_argument, 0, 'n'},
414         {"verbose",     optional_argument, 0, 'v'},
415         {"help",        no_argument, 0, 'h'},
416         {"version",     no_argument, 0, 'V'},
417         VCONN_SSL_LONG_OPTIONS
418         {0, 0, 0, 0},
419     };
420     char *short_options = long_options_to_short_options(long_options);
421
422     for (;;) {
423         int indexptr;
424         int c;
425
426         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
427         if (c == -1) {
428             break;
429         }
430
431         switch (c) {
432         case 'H':
433             learn_macs = false;
434             break;
435
436         case 'n':
437             setup_flows = false;
438             break;
439
440         case 'h':
441             usage();
442
443         case 'V':
444             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
445             exit(EXIT_SUCCESS);
446
447         case 'v':
448             vlog_set_verbosity(optarg);
449             break;
450
451         VCONN_SSL_OPTION_HANDLERS
452
453         case '?':
454             exit(EXIT_FAILURE);
455
456         default:
457             abort();
458         }
459     }
460     free(short_options);
461 }
462
463 static void
464 usage(void)
465 {
466     printf("%s: OpenFlow controller\n"
467            "usage: %s [OPTIONS] METHOD\n"
468            "where METHOD is any OpenFlow connection method.\n",
469            program_name, program_name);
470     vconn_usage(true, true);
471     printf("\nOther options:\n"
472            "  -H, --hub               act as hub instead of learning switch\n"
473            "  -n, --noflow            pass traffic, but don't add flows\n"
474            "  -v, --verbose           set maximum verbosity level\n"
475            "  -h, --help              display this help message\n"
476            "  -V, --version           display version information\n");
477     exit(EXIT_SUCCESS);
478 }