netdev: Decouple creating and configuring network devices.
[openvswitch] / utilities / ovs-dpctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <arpa/inet.h>
19 #include <errno.h>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <sys/socket.h>
23 #include <net/if.h>
24 #include <netinet/in.h>
25 #include <signal.h>
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <sys/stat.h>
31 #include <sys/time.h>
32
33 #include "command-line.h"
34 #include "compiler.h"
35 #include "dirs.h"
36 #include "dpif.h"
37 #include "dynamic-string.h"
38 #include "netdev.h"
39 #include "odp-util.h"
40 #include "shash.h"
41 #include "sset.h"
42 #include "timeval.h"
43 #include "util.h"
44 #include "vlog.h"
45
46 VLOG_DEFINE_THIS_MODULE(dpctl);
47
48 /* -s, --statistics: Print port statistics? */
49 static bool print_statistics;
50
51 static const struct command all_commands[];
52
53 static void usage(void) NO_RETURN;
54 static void parse_options(int argc, char *argv[]);
55
56 int
57 main(int argc, char *argv[])
58 {
59     set_program_name(argv[0]);
60     parse_options(argc, argv);
61     signal(SIGPIPE, SIG_IGN);
62     run_command(argc - optind, argv + optind, all_commands);
63     return 0;
64 }
65
66 static void
67 parse_options(int argc, char *argv[])
68 {
69     enum {
70         OPT_DUMMY = UCHAR_MAX + 1,
71         VLOG_OPTION_ENUMS
72     };
73     static struct option long_options[] = {
74         {"statistics", no_argument, NULL, 's'},
75         {"timeout", required_argument, NULL, 't'},
76         {"help", no_argument, NULL, 'h'},
77         {"version", no_argument, NULL, 'V'},
78         VLOG_LONG_OPTIONS,
79         {NULL, 0, NULL, 0},
80     };
81     char *short_options = long_options_to_short_options(long_options);
82
83     for (;;) {
84         unsigned long int timeout;
85         int c;
86
87         c = getopt_long(argc, argv, short_options, long_options, NULL);
88         if (c == -1) {
89             break;
90         }
91
92         switch (c) {
93         case 's':
94             print_statistics = true;
95             break;
96
97         case 't':
98             timeout = strtoul(optarg, NULL, 10);
99             if (timeout <= 0) {
100                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
101                           optarg);
102             } else {
103                 time_alarm(timeout);
104             }
105             break;
106
107         case 'h':
108             usage();
109
110         case 'V':
111             ovs_print_version(0, 0);
112             exit(EXIT_SUCCESS);
113
114         VLOG_OPTION_HANDLERS
115
116         case '?':
117             exit(EXIT_FAILURE);
118
119         default:
120             abort();
121         }
122     }
123     free(short_options);
124 }
125
126 static void
127 usage(void)
128 {
129     printf("%s: Open vSwitch datapath management utility\n"
130            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
131            "  add-dp DP [IFACE...]     add new datapath DP (with IFACEs)\n"
132            "  del-dp DP                delete local datapath DP\n"
133            "  add-if DP IFACE...       add each IFACE as a port on DP\n"
134            "  del-if DP IFACE...       delete each IFACE from DP\n"
135            "  dump-dps                 display names of all datapaths\n"
136            "  show                     show basic info on all datapaths\n"
137            "  show DP...               show basic info on each DP\n"
138            "  dump-flows DP            display flows in DP\n"
139            "  del-flows DP             delete all flows from DP\n",
140            program_name, program_name);
141     vlog_usage();
142     printf("\nOther options:\n"
143            "  -t, --timeout=SECS          give up after SECS seconds\n"
144            "  -h, --help                  display this help message\n"
145            "  -V, --version               display version information\n");
146     exit(EXIT_SUCCESS);
147 }
148
149 static void run(int retval, const char *message, ...)
150     PRINTF_FORMAT(2, 3);
151
152 static void run(int retval, const char *message, ...)
153 {
154     if (retval) {
155         va_list args;
156
157         va_start(args, message);
158         ovs_fatal_valist(retval, message, args);
159     }
160 }
161 \f
162 static void do_add_if(int argc, char *argv[]);
163
164 static int if_up(const char *netdev_name)
165 {
166     struct netdev *netdev;
167     int retval;
168
169     retval = netdev_open_default(netdev_name, &netdev);
170     if (!retval) {
171         retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
172         netdev_close(netdev);
173     }
174     return retval;
175 }
176
177 static int
178 parsed_dpif_open(const char *arg_, bool create, struct dpif **dpifp)
179 {
180     int result;
181     char *name, *type;
182
183     dp_parse_name(arg_, &name, &type);
184
185     if (create) {
186         result = dpif_create(name, type, dpifp);
187     } else {
188         result = dpif_open(name, type, dpifp);
189     }
190
191     free(name);
192     free(type);
193     return result;
194 }
195
196 static void
197 do_add_dp(int argc OVS_UNUSED, char *argv[])
198 {
199     struct dpif *dpif;
200     run(parsed_dpif_open(argv[1], true, &dpif), "add_dp");
201     dpif_close(dpif);
202     if (argc > 2) {
203         do_add_if(argc, argv);
204     }
205 }
206
207 static void
208 do_del_dp(int argc OVS_UNUSED, char *argv[])
209 {
210     struct dpif *dpif;
211     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
212     run(dpif_delete(dpif), "del_dp");
213     dpif_close(dpif);
214 }
215
216 static void
217 do_add_if(int argc OVS_UNUSED, char *argv[])
218 {
219     bool failure = false;
220     struct dpif *dpif;
221     int i;
222
223     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
224     for (i = 2; i < argc; i++) {
225         char *save_ptr = NULL;
226         struct netdev_options options;
227         struct netdev *netdev = NULL;
228         struct shash args;
229         char *option;
230         int error;
231
232         options.name = strtok_r(argv[i], ",", &save_ptr);
233         options.type = "system";
234
235         if (!options.name) {
236             ovs_error(0, "%s is not a valid network device name", argv[i]);
237             continue;
238         }
239
240         shash_init(&args);
241         while ((option = strtok_r(NULL, ",", &save_ptr)) != NULL) {
242             char *save_ptr_2 = NULL;
243             char *key, *value;
244
245             key = strtok_r(option, "=", &save_ptr_2);
246             value = strtok_r(NULL, "", &save_ptr_2);
247             if (!value) {
248                 value = "";
249             }
250
251             if (!strcmp(key, "type")) {
252                 options.type = value;
253             } else if (!shash_add_once(&args, key, value)) {
254                 ovs_error(0, "duplicate \"%s\" option", key);
255             }
256         }
257
258         error = netdev_open(&options, &netdev);
259         if (error) {
260             ovs_error(error, "%s: failed to open network device",
261                       options.name);
262             goto next;
263         }
264
265         error = netdev_set_config(netdev, &args);
266         if (error) {
267             ovs_error(error, "%s: failed to configure network device",
268                       options.name);
269             goto next;
270         }
271
272         error = dpif_port_add(dpif, netdev, NULL);
273         if (error) {
274             ovs_error(error, "adding %s to %s failed", options.name, argv[1]);
275             goto next;
276         }
277
278         error = if_up(options.name);
279
280 next:
281         netdev_close(netdev);
282         if (error) {
283             failure = true;
284         }
285     }
286     dpif_close(dpif);
287     if (failure) {
288         exit(EXIT_FAILURE);
289     }
290 }
291
292 static bool
293 get_port_number(struct dpif *dpif, const char *name, uint16_t *port)
294 {
295     struct dpif_port dpif_port;
296
297     if (!dpif_port_query_by_name(dpif, name, &dpif_port)) {
298         *port = dpif_port.port_no;
299         dpif_port_destroy(&dpif_port);
300         return true;
301     } else {
302         ovs_error(0, "no port named %s", name);
303         return false;
304     }
305 }
306
307 static void
308 do_del_if(int argc OVS_UNUSED, char *argv[])
309 {
310     bool failure = false;
311     struct dpif *dpif;
312     int i;
313
314     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
315     for (i = 2; i < argc; i++) {
316         const char *name = argv[i];
317         uint16_t port;
318         int error;
319
320         if (!name[strspn(name, "0123456789")]) {
321             port = atoi(name);
322         } else if (!get_port_number(dpif, name, &port)) {
323             failure = true;
324             continue;
325         }
326
327         error = dpif_port_del(dpif, port);
328         if (error) {
329             ovs_error(error, "deleting port %s from %s failed", name, argv[1]);
330             failure = true;
331         }
332     }
333     dpif_close(dpif);
334     if (failure) {
335         exit(EXIT_FAILURE);
336     }
337 }
338
339 static void
340 print_stat(const char *leader, uint64_t value)
341 {
342     fputs(leader, stdout);
343     if (value != UINT64_MAX) {
344         printf("%"PRIu64, value);
345     } else {
346         putchar('?');
347     }
348 }
349
350 static void
351 print_human_size(uint64_t value)
352 {
353     if (value == UINT64_MAX) {
354         /* Nothing to do. */
355     } else if (value >= 1024ULL * 1024 * 1024 * 1024) {
356         printf(" (%.1f TiB)", value / (1024.0 * 1024 * 1024 * 1024));
357     } else if (value >= 1024ULL * 1024 * 1024) {
358         printf(" (%.1f GiB)", value / (1024.0 * 1024 * 1024));
359     } else if (value >= 1024ULL * 1024) {
360         printf(" (%.1f MiB)", value / (1024.0 * 1024));
361     } else if (value >= 1024) {
362         printf(" (%.1f KiB)", value / 1024.0);
363     }
364 }
365
366 static void
367 show_dpif(struct dpif *dpif)
368 {
369     struct dpif_port_dump dump;
370     struct dpif_port dpif_port;
371     struct odp_stats stats;
372
373     printf("%s:\n", dpif_name(dpif));
374     if (!dpif_get_dp_stats(dpif, &stats)) {
375         printf("\tlookups: frags:%llu, hit:%llu, missed:%llu, lost:%llu\n",
376                (unsigned long long int) stats.n_frags,
377                (unsigned long long int) stats.n_hit,
378                (unsigned long long int) stats.n_missed,
379                (unsigned long long int) stats.n_lost);
380         printf("\tflows: %llu\n", (unsigned long long int)stats.n_flows);
381     }
382     DPIF_PORT_FOR_EACH (&dpif_port, &dump, dpif) {
383         printf("\tport %u: %s", dpif_port.port_no, dpif_port.name);
384
385         if (strcmp(dpif_port.type, "system")) {
386             struct netdev_options netdev_options;
387             struct netdev *netdev;
388             int error;
389
390             printf (" (%s", dpif_port.type);
391
392             netdev_options.name = dpif_port.name;
393             netdev_options.type = dpif_port.type;
394             error = netdev_open(&netdev_options, &netdev);
395             if (!error) {
396                 struct shash config;
397
398                 shash_init(&config);
399                 error = netdev_get_config(netdev, &config);
400                 if (!error) {
401                     const struct shash_node **nodes;
402                     size_t i;
403
404                     nodes = shash_sort(&config);
405                     for (i = 0; i < shash_count(&config); i++) {
406                         const struct shash_node *node = nodes[i];
407                         printf("%c %s=%s", i ? ',' : ':',
408                                node->name, (char *) node->data);
409                     }
410                     free(nodes);
411                 } else {
412                     printf(", could not retrieve configuration (%s)",
413                            strerror(error));
414                 }
415                 shash_destroy_free_data(&config);
416
417                 netdev_close(netdev);
418             } else {
419                 printf(": open failed (%s)", strerror(error));
420             }
421             putchar(')');
422         }
423         putchar('\n');
424
425         if (print_statistics) {
426             const struct netdev_stats *s = &dpif_port.stats;
427
428             print_stat("\t\tRX packets:", s->rx_packets);
429             print_stat(" errors:", s->rx_errors);
430             print_stat(" dropped:", s->rx_dropped);
431             print_stat(" overruns:", s->rx_over_errors);
432             print_stat(" frame:", s->rx_frame_errors);
433             printf("\n");
434
435             print_stat("\t\tTX packets:", s->tx_packets);
436             print_stat(" errors:", s->tx_errors);
437             print_stat(" dropped:", s->tx_dropped);
438             print_stat(" aborted:", s->tx_aborted_errors);
439             print_stat(" carrier:", s->tx_carrier_errors);
440             printf("\n");
441
442             print_stat("\t\tcollisions:", s->collisions);
443             printf("\n");
444
445             print_stat("\t\tRX bytes:", s->rx_bytes);
446             print_human_size(s->rx_bytes);
447             print_stat("  TX bytes:", s->tx_bytes);
448             print_human_size(s->tx_bytes);
449             printf("\n");
450         }
451     }
452     dpif_close(dpif);
453 }
454
455 static void
456 do_show(int argc, char *argv[])
457 {
458     bool failure = false;
459     if (argc > 1) {
460         int i;
461         for (i = 1; i < argc; i++) {
462             const char *name = argv[i];
463             struct dpif *dpif;
464             int error;
465
466             error = parsed_dpif_open(name, false, &dpif);
467             if (!error) {
468                 show_dpif(dpif);
469             } else {
470                 ovs_error(error, "opening datapath %s failed", name);
471                 failure = true;
472             }
473         }
474     } else {
475         struct sset types;
476         const char *type;
477
478         sset_init(&types);
479         dp_enumerate_types(&types);
480         SSET_FOR_EACH (type, &types) {
481             struct sset names;
482             const char *name;
483
484             sset_init(&names);
485             if (dp_enumerate_names(type, &names)) {
486                 failure = true;
487                 continue;
488             }
489             SSET_FOR_EACH (name, &names) {
490                 struct dpif *dpif;
491                 int error;
492
493                 error = dpif_open(name, type, &dpif);
494                 if (!error) {
495                     show_dpif(dpif);
496                 } else {
497                     ovs_error(error, "opening datapath %s failed", name);
498                     failure = true;
499                 }
500             }
501             sset_destroy(&names);
502         }
503         sset_destroy(&types);
504     }
505     if (failure) {
506         exit(EXIT_FAILURE);
507     }
508 }
509
510 static void
511 do_dump_dps(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
512 {
513     struct sset dpif_names, dpif_types;
514     const char *type;
515     int error = 0;
516
517     sset_init(&dpif_names);
518     sset_init(&dpif_types);
519     dp_enumerate_types(&dpif_types);
520
521     SSET_FOR_EACH (type, &dpif_types) {
522         const char *name;
523         int retval;
524
525         retval = dp_enumerate_names(type, &dpif_names);
526         if (retval) {
527             error = retval;
528         }
529
530         SSET_FOR_EACH (name, &dpif_names) {
531             struct dpif *dpif;
532             if (!dpif_open(name, type, &dpif)) {
533                 printf("%s\n", dpif_name(dpif));
534                 dpif_close(dpif);
535             }
536         }
537     }
538
539     sset_destroy(&dpif_names);
540     sset_destroy(&dpif_types);
541     if (error) {
542         exit(EXIT_FAILURE);
543     }
544 }
545
546 static void
547 do_dump_flows(int argc OVS_UNUSED, char *argv[])
548 {
549     const struct dpif_flow_stats *stats;
550     const struct nlattr *actions;
551     struct dpif_flow_dump dump;
552     const struct nlattr *key;
553     size_t actions_len;
554     struct dpif *dpif;
555     size_t key_len;
556     struct ds ds;
557
558     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
559
560     ds_init(&ds);
561     dpif_flow_dump_start(&dump, dpif);
562     while (dpif_flow_dump_next(&dump, &key, &key_len,
563                                &actions, &actions_len, &stats)) {
564         ds_clear(&ds);
565         odp_flow_key_format(key, key_len, &ds);
566         ds_put_cstr(&ds, ", ");
567         dpif_flow_stats_format(stats, &ds);
568         ds_put_cstr(&ds, ", actions:");
569         format_odp_actions(&ds, actions, actions_len);
570         printf("%s\n", ds_cstr(&ds));
571     }
572     dpif_flow_dump_done(&dump);
573     ds_destroy(&ds);
574     dpif_close(dpif);
575 }
576
577 static void
578 do_del_flows(int argc OVS_UNUSED, char *argv[])
579 {
580     struct dpif *dpif;
581
582     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
583     run(dpif_flow_flush(dpif), "deleting all flows");
584     dpif_close(dpif);
585 }
586
587 static void
588 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
589 {
590     usage();
591 }
592
593 static const struct command all_commands[] = {
594     { "add-dp", 1, INT_MAX, do_add_dp },
595     { "del-dp", 1, 1, do_del_dp },
596     { "add-if", 2, INT_MAX, do_add_if },
597     { "del-if", 2, INT_MAX, do_del_if },
598     { "dump-dps", 0, 0, do_dump_dps },
599     { "show", 0, INT_MAX, do_show },
600     { "dump-flows", 1, 1, do_dump_flows },
601     { "del-flows", 1, 1, do_del_flows },
602     { "help", 0, INT_MAX, do_help },
603     { NULL, 0, 0, NULL },
604 };