Add the ability to connect to a vconn asynchronously.
[sliver-openvswitch.git] / controller / controller.c
1 /* Copyright (C) 2007 Board of Trustees, Leland Stanford Jr. University.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to
5  * deal in the Software without restriction, including without limitation the
6  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7  * sell copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19  * IN THE SOFTWARE.
20  */
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <getopt.h>
25 #include <inttypes.h>
26 #include <netinet/in.h>
27 #include <poll.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #include "buffer.h"
33 #include "command-line.h"
34 #include "compiler.h"
35 #include "fault.h"
36 #include "flow.h"
37 #include "hash.h"
38 #include "list.h"
39 #include "mac.h"
40 #include "ofp-print.h"
41 #include "openflow.h"
42 #include "poll-loop.h"
43 #include "time.h"
44 #include "util.h"
45 #include "vconn-ssl.h"
46 #include "vconn.h"
47 #include "vlog-socket.h"
48 #include "xtoxll.h"
49
50 #include "vlog.h"
51 #define THIS_MODULE VLM_controller
52
53 #define MAX_SWITCHES 16
54 #define MAX_TXQ 128
55
56 struct switch_ {
57     char *name;
58     struct vconn *vconn;
59
60     uint64_t datapath_id;
61     time_t last_control_hello;
62
63     int n_txq;
64     struct buffer *txq, *tx_tail;
65 };
66
67 /* -H, --hub: Use dumb hub instead of learning switch? */
68 static bool hub = false;
69
70 /* -n, --noflow: Pass traffic, but don't setup flows in switch */
71 static bool noflow = false;
72
73 static void parse_options(int argc, char *argv[]);
74 static void usage(void) NO_RETURN;
75
76 static struct switch_ *connect_switch(const char *name);
77 static struct switch_ *new_switch(const char *name, struct vconn *);
78 static void close_switch(struct switch_ *);
79
80 static void queue_tx(struct switch_ *, struct buffer *);
81
82 static void send_control_hello(struct switch_ *);
83
84 static int do_switch_recv(struct switch_ *this);
85 static int do_switch_send(struct switch_ *this);
86
87 static void process_packet(struct switch_ *, struct buffer *);
88 static void process_hub(struct switch_ *, struct ofp_packet_in *);
89 static void process_noflow(struct switch_ *, struct ofp_packet_in *);
90
91 static void switch_init(void);
92 static void process_switch(struct switch_ *, struct ofp_packet_in *);
93
94 int
95 main(int argc, char *argv[])
96 {
97     struct switch_ *switches[MAX_SWITCHES];
98     int n_switches;
99     int retval;
100     int i;
101
102     set_program_name(argv[0]);
103     register_fault_handlers();
104     vlog_init();
105     parse_options(argc, argv);
106
107     if (!hub && !noflow) {
108         switch_init();
109     }
110
111     if (argc - optind < 1) {
112         fatal(0, "at least one vconn argument required; use --help for usage");
113     }
114
115     retval = vlog_server_listen(NULL, NULL);
116     if (retval) {
117         fatal(retval, "Could not listen for vlog connections");
118     }
119
120     n_switches = 0;
121     for (i = 0; i < argc - optind; i++) {
122         struct switch_ *this = connect_switch(argv[optind + i]);
123         if (this) {
124             if (n_switches >= MAX_SWITCHES) {
125                 fatal(0, "max %d switch connections", n_switches);
126             }
127             switches[n_switches++] = this;
128         }
129     }
130     if (n_switches == 0) {
131         fatal(0, "could not connect to any switches");
132     }
133
134     while (n_switches > 0) {
135         /* Do some work.  Limit the number of iterations so that callbacks
136          * registered with the poll loop don't starve. */
137         int iteration;
138         int i;
139         for (iteration = 0; iteration < 50; iteration++) {
140             bool progress = false;
141             for (i = 0; i < n_switches; ) {
142                 struct switch_ *this = switches[i];
143                 int retval;
144
145                 if (vconn_is_passive(this->vconn)) {
146                     retval = 0;
147                     while (n_switches < MAX_SWITCHES) {
148                         struct vconn *new_vconn;
149                         retval = vconn_accept(this->vconn, &new_vconn);
150                         if (retval) {
151                             break;
152                         }
153                         switches[n_switches++] = new_switch("tcp", new_vconn);
154                     }
155                 } else {
156                     retval = do_switch_recv(this);
157                     if (!retval || retval == EAGAIN) {
158                         do {
159                             retval = do_switch_send(this);
160                             if (!retval) {
161                                 progress = true;
162                             }
163                         } while (!retval);
164                     }
165                 }
166
167                 if (retval && retval != EAGAIN) {
168                     close_switch(this);
169                     switches[i] = switches[--n_switches];
170                 } else {
171                     i++;
172                 }
173             }
174             if (!progress) {
175                 break;
176             }
177         }
178
179         /* Wait for something to happen. */
180         for (i = 0; i < n_switches; i++) {
181             struct switch_ *this = switches[i];
182             if (vconn_is_passive(this->vconn)) {
183                 if (n_switches < MAX_SWITCHES) {
184                     vconn_accept_wait(this->vconn);
185                 }
186             } else {
187                 vconn_recv_wait(this->vconn);
188                 if (this->n_txq) {
189                     vconn_send_wait(this->vconn);
190                 }
191             }
192         }
193         poll_block();
194     }
195
196     return 0;
197 }
198
199 static int
200 do_switch_recv(struct switch_ *this) 
201 {
202     struct buffer *msg;
203     int retval;
204
205     retval = vconn_recv(this->vconn, &msg);
206     if (!retval) {
207         process_packet(this, msg);
208         buffer_delete(msg);
209     }
210     return retval;
211 }
212
213 static int
214 do_switch_send(struct switch_ *this) 
215 {
216     int retval = 0;
217     if (this->n_txq) {
218         struct buffer *next = this->txq->next;
219
220         retval = vconn_send(this->vconn, this->txq);
221         if (retval) {
222             return retval;
223         }
224
225         this->txq = next;
226         if (this->txq == NULL) {
227             this->tx_tail = NULL;
228         }
229         this->n_txq--;
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     this->n_txq = 0;
258     this->txq = NULL;
259     this->tx_tail = NULL;
260     this->last_control_hello = 0;
261     if (!vconn_is_passive(vconn)) {
262         send_control_hello(this);
263     }
264     return this;
265 }
266
267 static void
268 close_switch(struct switch_ *this) 
269 {
270     if (this) {
271         struct buffer *cur, *next;
272
273         free(this->name);
274         vconn_close(this->vconn);
275         for (cur = this->txq; cur != NULL; cur = next) {
276             next = cur->next;
277             buffer_delete(cur);
278         }
279         free(this);
280     }
281 }
282
283 static void
284 send_control_hello(struct switch_ *this)
285 {
286     time_t now = time(0);
287     if (now >= this->last_control_hello + 1) {
288         struct buffer *b;
289         struct ofp_control_hello *och;
290
291         b = buffer_new(0);
292         och = buffer_put_uninit(b, sizeof *och);
293         memset(och, 0, sizeof *och);
294         och->header.version = OFP_VERSION;
295         och->header.length = htons(sizeof *och);
296
297         och->version = htonl(OFP_VERSION);
298         och->flags = htons(OFP_CHELLO_SEND_FLOW_EXP);
299         och->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
300         queue_tx(this, b);
301
302         this->last_control_hello = now;
303     }
304 }
305
306 static void
307 check_txq(struct switch_ *this UNUSED)
308 {
309 #if 0
310     struct buffer *iter;
311     size_t n;
312
313     assert(this->n_txq == 0
314            ? this->txq == NULL && this->tx_tail == NULL
315            : this->txq != NULL && this->tx_tail != NULL);
316
317     n = 0;
318     for (iter = this->txq; iter != NULL; iter = iter->next) {
319         n++;
320         assert((iter->next != NULL) == (iter != this->tx_tail));
321     }
322     assert(n == this->n_txq);
323 #endif
324 }
325
326 static void
327 queue_tx(struct switch_ *this, struct buffer *b) 
328 {
329     check_txq(this);
330
331     b->next = NULL;
332     if (this->n_txq++) {
333         this->tx_tail->next = b;
334     } else {
335         this->txq = b;
336     }
337     this->tx_tail = b;
338
339     check_txq(this);
340 }
341
342 static void
343 process_packet(struct switch_ *sw, struct buffer *msg) 
344 {
345     static const size_t min_size[UINT8_MAX + 1] = {
346         [0 ... UINT8_MAX] = SIZE_MAX,
347         [OFPT_CONTROL_HELLO] = sizeof (struct ofp_control_hello),
348         [OFPT_DATA_HELLO] = sizeof (struct ofp_data_hello),
349         [OFPT_PACKET_IN] = offsetof (struct ofp_packet_in, data),
350         [OFPT_PACKET_OUT] = sizeof (struct ofp_packet_out),
351         [OFPT_FLOW_MOD] = sizeof (struct ofp_flow_mod),
352         [OFPT_FLOW_EXPIRED] = sizeof (struct ofp_flow_expired),
353         [OFPT_TABLE] = sizeof (struct ofp_table),
354         [OFPT_PORT_MOD] = sizeof (struct ofp_port_mod),
355         [OFPT_PORT_STATUS] = sizeof (struct ofp_port_status),
356         [OFPT_FLOW_STAT_REQUEST] = sizeof (struct ofp_flow_stat_request),
357         [OFPT_FLOW_STAT_REPLY] = sizeof (struct ofp_flow_stat_reply),
358     };
359     struct ofp_header *oh;
360
361     oh = msg->data;
362     if (msg->size < min_size[oh->type]) {
363         VLOG_WARN("%s: too short (%zu bytes) for type %"PRIu8" (min %zu)",
364                   sw->name, msg->size, oh->type, min_size[oh->type]);
365         return;
366     }
367
368     if (oh->type == OFPT_DATA_HELLO) {
369         struct ofp_data_hello *odh = msg->data;
370         sw->datapath_id = odh->datapath_id;
371     } else if (sw->datapath_id == 0) {
372         send_control_hello(sw);
373         return;
374     }
375
376     if (oh->type == OFPT_PACKET_IN) {
377         if (sw->n_txq >= MAX_TXQ) {
378             VLOG_WARN("%s: tx queue overflow", sw->name);
379         } else if (noflow) {
380             process_noflow(sw, msg->data);
381         } else if (hub) {
382             process_hub(sw, msg->data);
383         } else {
384             process_switch(sw, msg->data);
385         }
386         return;
387     }
388
389     ofp_print(stdout, msg->data, msg->size, 2);
390 }
391
392 static void
393 process_hub(struct switch_ *sw, struct ofp_packet_in *opi)
394 {
395     size_t pkt_ofs, pkt_len;
396     struct buffer pkt;
397     struct flow flow;
398
399     /* Extract flow data from 'opi' into 'flow'. */
400     pkt_ofs = offsetof(struct ofp_packet_in, data);
401     pkt_len = ntohs(opi->header.length) - pkt_ofs;
402     pkt.data = opi->data;
403     pkt.size = pkt_len;
404     flow_extract(&pkt, ntohs(opi->in_port), &flow);
405
406     /* Add new flow. */
407     queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
408                                       OFPP_FLOOD));
409
410     /* If the switch didn't buffer the packet, we need to send a copy. */
411     if (ntohl(opi->buffer_id) == UINT32_MAX) {
412         queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(flow.in_port),
413                                                 OFPP_FLOOD));
414     }
415 }
416
417 static void
418 process_noflow(struct switch_ *sw, struct ofp_packet_in *opi)
419 {
420     /* If the switch didn't buffer the packet, we need to send a copy. */
421     if (ntohl(opi->buffer_id) == UINT32_MAX) {
422         size_t pkt_ofs, pkt_len;
423         struct buffer pkt;
424
425         /* Extract flow data from 'opi' into 'flow'. */
426         pkt_ofs = offsetof(struct ofp_packet_in, data);
427         pkt_len = ntohs(opi->header.length) - pkt_ofs;
428         pkt.data = opi->data;
429         pkt.size = pkt_len;
430
431         queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(opi->in_port),
432                     OFPP_FLOOD));
433     } else {
434         queue_tx(sw, make_buffered_packet_out(ntohl(opi->buffer_id), 
435                     ntohs(opi->in_port), OFPP_FLOOD));
436     }
437 }
438
439
440 #define MAC_HASH_BITS 10
441 #define MAC_HASH_MASK (MAC_HASH_SIZE - 1)
442 #define MAC_HASH_SIZE (1u << MAC_HASH_BITS)
443
444 #define MAC_MAX 1024
445
446 struct mac_source {
447     struct list hash_list;
448     struct list lru_list;
449     uint64_t datapath_id;
450     uint8_t mac[ETH_ADDR_LEN];
451     uint16_t port;
452 };
453
454 static struct list mac_table[MAC_HASH_SIZE];
455 static struct list lrus;
456 static size_t mac_count;
457
458 static void
459 switch_init(void)
460 {
461     int i;
462
463     list_init(&lrus);
464     for (i = 0; i < MAC_HASH_SIZE; i++) {
465         list_init(&mac_table[i]);
466     }
467 }
468
469 static struct list *
470 mac_table_bucket(uint64_t datapath_id, const uint8_t mac[ETH_ADDR_LEN]) 
471 {
472     uint32_t hash;
473     hash = hash_fnv(&datapath_id, sizeof datapath_id, HASH_FNV_BASIS);
474     hash = hash_fnv(mac, ETH_ADDR_LEN, hash);
475     return &mac_table[hash & MAC_HASH_BITS];
476 }
477
478 static void
479 process_switch(struct switch_ *sw, struct ofp_packet_in *opi)
480 {
481     size_t pkt_ofs, pkt_len;
482     struct buffer pkt;
483     struct flow flow;
484
485     uint16_t out_port;
486
487     /* Extract flow data from 'opi' into 'flow'. */
488     pkt_ofs = offsetof(struct ofp_packet_in, data);
489     pkt_len = ntohs(opi->header.length) - pkt_ofs;
490     pkt.data = opi->data;
491     pkt.size = pkt_len;
492     flow_extract(&pkt, ntohs(opi->in_port), &flow);
493
494     /* Learn the source. */
495     if (!mac_is_multicast(flow.dl_src)) {
496         struct mac_source *src;
497         struct list *bucket;
498         bool found;
499
500         bucket = mac_table_bucket(sw->datapath_id, flow.dl_src);
501         found = false;
502         LIST_FOR_EACH (src, struct mac_source, hash_list, bucket) {
503             if (src->datapath_id == sw->datapath_id
504                 && mac_equals(src->mac, flow.dl_src)) {
505                 found = true;
506                 break;
507             }
508         }
509
510         if (!found) {
511             /* Learn a new address. */
512
513             if (mac_count >= MAC_MAX) {
514                 /* Drop the least recently used mac source. */
515                 struct mac_source *lru;
516                 lru = CONTAINER_OF(lrus.next, struct mac_source, lru_list);
517                 list_remove(&lru->hash_list);
518                 list_remove(&lru->lru_list);
519                 free(lru);
520             } else {
521                 mac_count++;
522             }
523
524             /* Create new mac source */
525             src = xmalloc(sizeof *src);
526             src->datapath_id = sw->datapath_id;
527             memcpy(src->mac, flow.dl_src, ETH_ADDR_LEN);
528             src->port = -1;
529             list_push_front(bucket, &src->hash_list);
530             list_push_back(&lrus, &src->lru_list);
531         } else {
532             /* Make 'src' most-recently-used.  */
533             list_remove(&src->lru_list);
534             list_push_back(&lrus, &src->lru_list);
535         }
536
537         if (ntohs(flow.in_port) != src->port) {
538             src->port = ntohs(flow.in_port);
539             VLOG_DBG("learned that "MAC_FMT" is on datapath %"PRIx64" port %d",
540                      MAC_ARGS(src->mac), ntohll(src->datapath_id),
541                      src->port);
542         }
543     } else {
544         VLOG_DBG("multicast packet source "MAC_FMT, MAC_ARGS(flow.dl_src));
545     }
546
547     /* Figure out the destination. */
548     out_port = OFPP_FLOOD;
549     if (!mac_is_multicast(flow.dl_dst)) {
550         struct mac_source *dst;
551         struct list *bucket;
552
553         bucket = mac_table_bucket(sw->datapath_id, flow.dl_dst);
554         LIST_FOR_EACH (dst, struct mac_source, hash_list, bucket) {
555             if (dst->datapath_id == sw->datapath_id
556                 && mac_equals(dst->mac, flow.dl_dst)) {
557                 out_port = dst->port;
558                 break;
559             }
560         }
561     }
562
563     if (out_port != OFPP_FLOOD) {
564         /* The output port is known, so add a new flow. */
565         queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id), 
566                     out_port));
567
568         /* If the switch didn't buffer the packet, we need to send a copy. */
569         if (ntohl(opi->buffer_id) == UINT32_MAX) {
570             queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(flow.in_port),
571                                                     out_port));
572         }
573     } else {
574         /* We don't know that MAC.  Flood the packet. */
575         struct buffer *b;
576         if (ntohl(opi->buffer_id) == UINT32_MAX) {
577             b = make_unbuffered_packet_out(&pkt, ntohs(flow.in_port), out_port);
578         } else {
579             b = make_buffered_packet_out(ntohl(opi->buffer_id), 
580                         ntohs(flow.in_port), out_port);
581         }
582         queue_tx(sw, b);
583     }
584 }
585
586 static void
587 parse_options(int argc, char *argv[])
588 {
589     static struct option long_options[] = {
590         {"hub",         no_argument, 0, 'H'},
591         {"noflow",      no_argument, 0, 'n'},
592         {"verbose",     optional_argument, 0, 'v'},
593         {"help",        no_argument, 0, 'h'},
594         {"version",     no_argument, 0, 'V'},
595 #ifdef HAVE_OPENSSL
596         {"private-key", required_argument, 0, 'p'},
597         {"certificate", required_argument, 0, 'c'},
598         {"ca-cert",     required_argument, 0, 'C'},
599 #endif
600         {0, 0, 0, 0},
601     };
602     char *short_options = long_options_to_short_options(long_options);
603
604     for (;;) {
605         int indexptr;
606         int c;
607
608         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
609         if (c == -1) {
610             break;
611         }
612
613         switch (c) {
614         case 'H':
615             hub = true;
616             break;
617
618         case 'n':
619             noflow = true;
620             break;
621
622         case 'h':
623             usage();
624
625         case 'V':
626             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
627             exit(EXIT_SUCCESS);
628
629         case 'v':
630             vlog_set_verbosity(optarg);
631             break;
632
633 #ifdef HAVE_OPENSSL
634         case 'p':
635             vconn_ssl_set_private_key_file(optarg);
636             break;
637
638         case 'c':
639             vconn_ssl_set_certificate_file(optarg);
640             break;
641
642         case 'C':
643             vconn_ssl_set_ca_cert_file(optarg);
644             break;
645 #endif
646
647         case '?':
648             exit(EXIT_FAILURE);
649
650         default:
651             abort();
652         }
653     }
654     free(short_options);
655 }
656
657 static void
658 usage(void)
659 {
660     printf("%s: OpenFlow controller\n"
661            "usage: %s [OPTIONS] VCONN\n"
662            "where VCONN is one of the following:\n"
663            "  ptcp:[PORT]             listen to TCP PORT (default: %d)\n",
664            program_name, program_name, OFP_TCP_PORT);
665 #ifdef HAVE_NETLINK
666     printf("  nl:DP_IDX               via netlink to local datapath DP_IDX\n");
667 #endif
668 #ifdef HAVE_OPENSSL
669     printf("  pssl:[PORT]             listen for SSL on PORT (default: %d)\n"
670            "\nPKI configuration (required to use SSL):\n"
671            "  -p, --private-key=FILE  file with private key\n"
672            "  -c, --certificate=FILE  file with certificate for private key\n"
673            "  -C, --ca-cert=FILE      file with peer CA certificate\n",
674            OFP_SSL_PORT);
675 #endif
676     printf("\nOther options:\n"
677            "  -H, --hub               act as hub instead of learning switch\n"
678            "  -n, --noflow            pass traffic, but don't add flows\n"
679            "  -v, --verbose           set maximum verbosity level\n"
680            "  -h, --help              display this help message\n"
681            "  -V, --version           display version information\n");
682     exit(EXIT_SUCCESS);
683 }