ovs-dpctl: Make specifying datapath optional for some commands.
[sliver-openvswitch.git] / utilities / ovs-dpctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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 <assert.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <sys/socket.h>
24 #include <net/if.h>
25 #include <netinet/in.h>
26 #include <signal.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33
34 #include "command-line.h"
35 #include "compiler.h"
36 #include "dirs.h"
37 #include "dpif.h"
38 #include "dynamic-string.h"
39 #include "flow.h"
40 #include "netdev.h"
41 #include "netlink.h"
42 #include "odp-util.h"
43 #include "ofpbuf.h"
44 #include "packets.h"
45 #include "shash.h"
46 #include "simap.h"
47 #include "smap.h"
48 #include "sset.h"
49 #include "timeval.h"
50 #include "util.h"
51 #include "vlog.h"
52
53 VLOG_DEFINE_THIS_MODULE(dpctl);
54
55 /* -s, --statistics: Print port statistics? */
56 static bool print_statistics;
57
58 /* -m, --more: Output verbosity.
59  *
60  * So far only undocumented commands honor this option, so we don't document
61  * the option itself. */
62 static int verbosity;
63
64 static const struct command all_commands[];
65
66 static void usage(void) NO_RETURN;
67 static void parse_options(int argc, char *argv[]);
68
69 int
70 main(int argc, char *argv[])
71 {
72     set_program_name(argv[0]);
73     parse_options(argc, argv);
74     signal(SIGPIPE, SIG_IGN);
75     run_command(argc - optind, argv + optind, all_commands);
76     return 0;
77 }
78
79 static void
80 parse_options(int argc, char *argv[])
81 {
82     enum {
83         OPT_DUMMY = UCHAR_MAX + 1,
84         VLOG_OPTION_ENUMS
85     };
86     static struct option long_options[] = {
87         {"statistics", no_argument, NULL, 's'},
88         {"more", no_argument, NULL, 'm'},
89         {"timeout", required_argument, NULL, 't'},
90         {"help", no_argument, NULL, 'h'},
91         {"version", no_argument, NULL, 'V'},
92         VLOG_LONG_OPTIONS,
93         {NULL, 0, NULL, 0},
94     };
95     char *short_options = long_options_to_short_options(long_options);
96
97     for (;;) {
98         unsigned long int timeout;
99         int c;
100
101         c = getopt_long(argc, argv, short_options, long_options, NULL);
102         if (c == -1) {
103             break;
104         }
105
106         switch (c) {
107         case 's':
108             print_statistics = true;
109             break;
110
111         case 'm':
112             verbosity++;
113             break;
114
115         case 't':
116             timeout = strtoul(optarg, NULL, 10);
117             if (timeout <= 0) {
118                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
119                           optarg);
120             } else {
121                 time_alarm(timeout);
122             }
123             break;
124
125         case 'h':
126             usage();
127
128         case 'V':
129             ovs_print_version(0, 0);
130             exit(EXIT_SUCCESS);
131
132         VLOG_OPTION_HANDLERS
133
134         case '?':
135             exit(EXIT_FAILURE);
136
137         default:
138             abort();
139         }
140     }
141     free(short_options);
142 }
143
144 static void
145 usage(void)
146 {
147     printf("%s: Open vSwitch datapath management utility\n"
148            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
149            "  add-dp DP [IFACE...]     add new datapath DP (with IFACEs)\n"
150            "  del-dp DP                delete local datapath DP\n"
151            "  add-if DP IFACE...       add each IFACE as a port on DP\n"
152            "  set-if DP IFACE...       reconfigure each IFACE within DP\n"
153            "  del-if DP IFACE...       delete each IFACE from DP\n"
154            "  dump-dps                 display names of all datapaths\n"
155            "  show                     show basic info on all datapaths\n"
156            "  show DP...               show basic info on each DP\n"
157            "  dump-flows DP            display flows in DP\n"
158            "  del-flows DP             delete all flows from DP\n"
159            "Each IFACE on add-dp, add-if, and set-if may be followed by\n"
160            "comma-separated options.  See ovs-dpctl(8) for syntax, or the\n"
161            "Interface table in ovs-vswitchd.conf.db(5) for an options list.\n",
162            program_name, program_name);
163     vlog_usage();
164     printf("\nOther options:\n"
165            "  -t, --timeout=SECS          give up after SECS seconds\n"
166            "  -h, --help                  display this help message\n"
167            "  -V, --version               display version information\n");
168     exit(EXIT_SUCCESS);
169 }
170
171 static void run(int retval, const char *message, ...)
172     PRINTF_FORMAT(2, 3);
173
174 static void run(int retval, const char *message, ...)
175 {
176     if (retval) {
177         va_list args;
178
179         va_start(args, message);
180         ovs_fatal_valist(retval, message, args);
181     }
182 }
183 \f
184 static void dpctl_add_if(int argc, char *argv[]);
185
186 static int if_up(const char *netdev_name)
187 {
188     struct netdev *netdev;
189     int retval;
190
191     retval = netdev_open(netdev_name, "system", &netdev);
192     if (!retval) {
193         retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
194         netdev_close(netdev);
195     }
196     return retval;
197 }
198
199 /* Retrieve the name of the datapath if exactly one exists.  The caller
200  * is responsible for freeing the returned string.  If there is not one
201  * datapath, aborts with an error message. */
202 static char *
203 get_one_dp(void)
204 {
205     struct sset types;
206     const char *type;
207     char *dp_name = NULL;
208     size_t count = 0;
209
210     sset_init(&types);
211     dp_enumerate_types(&types);
212     SSET_FOR_EACH (type, &types) {
213         struct sset names;
214
215         sset_init(&names);
216         if (!dp_enumerate_names(type, &names)) {
217             count += sset_count(&names);
218             if (!dp_name && count == 1) {
219                 dp_name = xasprintf("%s@%s", type, SSET_FIRST(&names));
220             }
221         }
222         sset_destroy(&names);
223     }
224     sset_destroy(&types);
225
226     if (!count) {
227         ovs_fatal(0, "no datapaths exist");
228     } else if (count > 1) {
229         ovs_fatal(0, "multiple datapaths, specify one");
230     }
231
232     return dp_name;
233 }
234
235 static int
236 parsed_dpif_open(const char *arg_, bool create, struct dpif **dpifp)
237 {
238     int result;
239     char *name, *type;
240
241     dp_parse_name(arg_, &name, &type);
242
243     if (create) {
244         result = dpif_create(name, type, dpifp);
245     } else {
246         result = dpif_open(name, type, dpifp);
247     }
248
249     free(name);
250     free(type);
251     return result;
252 }
253
254 static void
255 dpctl_add_dp(int argc OVS_UNUSED, char *argv[])
256 {
257     struct dpif *dpif;
258     run(parsed_dpif_open(argv[1], true, &dpif), "add_dp");
259     dpif_close(dpif);
260     if (argc > 2) {
261         dpctl_add_if(argc, argv);
262     }
263 }
264
265 static void
266 dpctl_del_dp(int argc OVS_UNUSED, char *argv[])
267 {
268     struct dpif *dpif;
269     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
270     run(dpif_delete(dpif), "del_dp");
271     dpif_close(dpif);
272 }
273
274 static void
275 dpctl_add_if(int argc OVS_UNUSED, char *argv[])
276 {
277     bool failure = false;
278     struct dpif *dpif;
279     int i;
280
281     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
282     for (i = 2; i < argc; i++) {
283         const char *name, *type;
284         char *save_ptr = NULL;
285         struct netdev *netdev = NULL;
286         struct smap args;
287         uint32_t port_no = UINT32_MAX;
288         char *option;
289         int error;
290
291         name = strtok_r(argv[i], ",", &save_ptr);
292         type = "system";
293
294         if (!name) {
295             ovs_error(0, "%s is not a valid network device name", argv[i]);
296             failure = true;
297             continue;
298         }
299
300         smap_init(&args);
301         while ((option = strtok_r(NULL, ",", &save_ptr)) != NULL) {
302             char *save_ptr_2 = NULL;
303             char *key, *value;
304
305             key = strtok_r(option, "=", &save_ptr_2);
306             value = strtok_r(NULL, "", &save_ptr_2);
307             if (!value) {
308                 value = "";
309             }
310
311             if (!strcmp(key, "type")) {
312                 type = value;
313             } else if (!strcmp(key, "port_no")) {
314                 port_no = atoi(value);
315             } else if (!smap_add_once(&args, key, value)) {
316                 ovs_error(0, "duplicate \"%s\" option", key);
317             }
318         }
319
320         error = netdev_open(name, type, &netdev);
321         if (error) {
322             ovs_error(error, "%s: failed to open network device", name);
323             goto next;
324         }
325
326         error = netdev_set_config(netdev, &args);
327         if (error) {
328             ovs_error(error, "%s: failed to configure network device", name);
329             goto next;
330         }
331
332         error = dpif_port_add(dpif, netdev, &port_no);
333         if (error) {
334             ovs_error(error, "adding %s to %s failed", name, argv[1]);
335             goto next;
336         }
337
338         error = if_up(name);
339
340 next:
341         netdev_close(netdev);
342         if (error) {
343             failure = true;
344         }
345     }
346     dpif_close(dpif);
347     if (failure) {
348         exit(EXIT_FAILURE);
349     }
350 }
351
352 static void
353 dpctl_set_if(int argc, char *argv[])
354 {
355     bool failure = false;
356     struct dpif *dpif;
357     int i;
358
359     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
360     for (i = 2; i < argc; i++) {
361         struct netdev *netdev = NULL;
362         struct dpif_port dpif_port;
363         char *save_ptr = NULL;
364         char *type = NULL;
365         const char *name;
366         struct smap args;
367         uint32_t port_no;
368         char *option;
369         int error;
370
371         name = strtok_r(argv[i], ",", &save_ptr);
372         if (!name) {
373             ovs_error(0, "%s is not a valid network device name", argv[i]);
374             failure = true;
375             continue;
376         }
377
378         /* Get the port's type from the datapath. */
379         error = dpif_port_query_by_name(dpif, name, &dpif_port);
380         if (error) {
381             ovs_error(error, "%s: failed to query port in %s", name, argv[1]);
382             goto next;
383         }
384         type = xstrdup(dpif_port.type);
385         port_no = dpif_port.port_no;
386         dpif_port_destroy(&dpif_port);
387
388         /* Retrieve its existing configuration. */
389         error = netdev_open(name, type, &netdev);
390         if (error) {
391             ovs_error(error, "%s: failed to open network device", name);
392             goto next;
393         }
394
395         smap_init(&args);
396         error = netdev_get_config(netdev, &args);
397         if (error) {
398             ovs_error(error, "%s: failed to fetch configuration", name);
399             goto next;
400         }
401
402         /* Parse changes to configuration. */
403         while ((option = strtok_r(NULL, ",", &save_ptr)) != NULL) {
404             char *save_ptr_2 = NULL;
405             char *key, *value;
406
407             key = strtok_r(option, "=", &save_ptr_2);
408             value = strtok_r(NULL, "", &save_ptr_2);
409             if (!value) {
410                 value = "";
411             }
412
413             if (!strcmp(key, "type")) {
414                 if (strcmp(value, type)) {
415                     ovs_error(0, "%s: can't change type from %s to %s",
416                               name, type, value);
417                     failure = true;
418                 }
419             } else if (!strcmp(key, "port_no")) {
420                 if (port_no != atoi(value)) {
421                     ovs_error(0, "%s: can't change port number from "
422                               "%"PRIu32" to %d",
423                               name, port_no, atoi(value));
424                     failure = true;
425                 }
426             } else if (value[0] == '\0') {
427                 smap_remove(&args, key);
428             } else {
429                 smap_replace(&args, key, value);
430             }
431         }
432
433         /* Update configuration. */
434         error = netdev_set_config(netdev, &args);
435         smap_destroy(&args);
436         if (error) {
437             ovs_error(error, "%s: failed to configure network device", name);
438             goto next;
439         }
440
441 next:
442         free(type);
443         netdev_close(netdev);
444         if (error) {
445             failure = true;
446         }
447     }
448     dpif_close(dpif);
449     if (failure) {
450         exit(EXIT_FAILURE);
451     }
452 }
453
454 static bool
455 get_port_number(struct dpif *dpif, const char *name, uint32_t *port)
456 {
457     struct dpif_port dpif_port;
458
459     if (!dpif_port_query_by_name(dpif, name, &dpif_port)) {
460         *port = dpif_port.port_no;
461         dpif_port_destroy(&dpif_port);
462         return true;
463     } else {
464         ovs_error(0, "no port named %s", name);
465         return false;
466     }
467 }
468
469 static void
470 dpctl_del_if(int argc OVS_UNUSED, char *argv[])
471 {
472     bool failure = false;
473     struct dpif *dpif;
474     int i;
475
476     run(parsed_dpif_open(argv[1], false, &dpif), "opening datapath");
477     for (i = 2; i < argc; i++) {
478         const char *name = argv[i];
479         uint32_t port;
480         int error;
481
482         if (!name[strspn(name, "0123456789")]) {
483             port = atoi(name);
484         } else if (!get_port_number(dpif, name, &port)) {
485             failure = true;
486             continue;
487         }
488
489         error = dpif_port_del(dpif, port);
490         if (error) {
491             ovs_error(error, "deleting port %s from %s failed", name, argv[1]);
492             failure = true;
493         }
494     }
495     dpif_close(dpif);
496     if (failure) {
497         exit(EXIT_FAILURE);
498     }
499 }
500
501 static void
502 print_stat(const char *leader, uint64_t value)
503 {
504     fputs(leader, stdout);
505     if (value != UINT64_MAX) {
506         printf("%"PRIu64, value);
507     } else {
508         putchar('?');
509     }
510 }
511
512 static void
513 print_human_size(uint64_t value)
514 {
515     if (value == UINT64_MAX) {
516         /* Nothing to do. */
517     } else if (value >= 1024ULL * 1024 * 1024 * 1024) {
518         printf(" (%.1f TiB)", value / (1024.0 * 1024 * 1024 * 1024));
519     } else if (value >= 1024ULL * 1024 * 1024) {
520         printf(" (%.1f GiB)", value / (1024.0 * 1024 * 1024));
521     } else if (value >= 1024ULL * 1024) {
522         printf(" (%.1f MiB)", value / (1024.0 * 1024));
523     } else if (value >= 1024) {
524         printf(" (%.1f KiB)", value / 1024.0);
525     }
526 }
527
528 static void
529 show_dpif(struct dpif *dpif)
530 {
531     struct dpif_port_dump dump;
532     struct dpif_port dpif_port;
533     struct dpif_dp_stats stats;
534     struct netdev *netdev;
535
536     printf("%s:\n", dpif_name(dpif));
537     if (!dpif_get_dp_stats(dpif, &stats)) {
538         printf("\tlookups: hit:%"PRIu64" missed:%"PRIu64" lost:%"PRIu64"\n"
539                "\tflows: %"PRIu64"\n",
540                stats.n_hit, stats.n_missed, stats.n_lost, stats.n_flows);
541     }
542     DPIF_PORT_FOR_EACH (&dpif_port, &dump, dpif) {
543         printf("\tport %u: %s", dpif_port.port_no, dpif_port.name);
544
545         if (strcmp(dpif_port.type, "system")) {
546             int error;
547
548             printf (" (%s", dpif_port.type);
549
550             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
551             if (!error) {
552                 struct smap config;
553
554                 smap_init(&config);
555                 error = netdev_get_config(netdev, &config);
556                 if (!error) {
557                     const struct smap_node **nodes;
558                     size_t i;
559
560                     nodes = smap_sort(&config);
561                     for (i = 0; i < smap_count(&config); i++) {
562                         const struct smap_node *node = nodes[i];
563                         printf("%c %s=%s", i ? ',' : ':', node->key,
564                                node->value);
565                     }
566                     free(nodes);
567                 } else {
568                     printf(", could not retrieve configuration (%s)",
569                            strerror(error));
570                 }
571                 smap_destroy(&config);
572
573                 netdev_close(netdev);
574             } else {
575                 printf(": open failed (%s)", strerror(error));
576             }
577             putchar(')');
578         }
579         putchar('\n');
580
581         if (print_statistics) {
582             struct netdev_stats s;
583             int error;
584
585             error = netdev_open(dpif_port.name, dpif_port.type, &netdev);
586             if (error) {
587                 printf(", open failed (%s)", strerror(error));
588                 continue;
589             }
590             error = netdev_get_stats(netdev, &s);
591             if (error) {
592                 printf(", could not retrieve stats (%s)", strerror(error));
593                 continue;
594             }
595
596             netdev_close(netdev);
597             print_stat("\t\tRX packets:", s.rx_packets);
598             print_stat(" errors:", s.rx_errors);
599             print_stat(" dropped:", s.rx_dropped);
600             print_stat(" overruns:", s.rx_over_errors);
601             print_stat(" frame:", s.rx_frame_errors);
602             printf("\n");
603
604             print_stat("\t\tTX packets:", s.tx_packets);
605             print_stat(" errors:", s.tx_errors);
606             print_stat(" dropped:", s.tx_dropped);
607             print_stat(" aborted:", s.tx_aborted_errors);
608             print_stat(" carrier:", s.tx_carrier_errors);
609             printf("\n");
610
611             print_stat("\t\tcollisions:", s.collisions);
612             printf("\n");
613
614             print_stat("\t\tRX bytes:", s.rx_bytes);
615             print_human_size(s.rx_bytes);
616             print_stat("  TX bytes:", s.tx_bytes);
617             print_human_size(s.tx_bytes);
618             printf("\n");
619         }
620     }
621     dpif_close(dpif);
622 }
623
624 static void
625 dpctl_show(int argc, char *argv[])
626 {
627     bool failure = false;
628     if (argc > 1) {
629         int i;
630         for (i = 1; i < argc; i++) {
631             const char *name = argv[i];
632             struct dpif *dpif;
633             int error;
634
635             error = parsed_dpif_open(name, false, &dpif);
636             if (!error) {
637                 show_dpif(dpif);
638             } else {
639                 ovs_error(error, "opening datapath %s failed", name);
640                 failure = true;
641             }
642         }
643     } else {
644         struct sset types;
645         const char *type;
646
647         sset_init(&types);
648         dp_enumerate_types(&types);
649         SSET_FOR_EACH (type, &types) {
650             struct sset names;
651             const char *name;
652
653             sset_init(&names);
654             if (dp_enumerate_names(type, &names)) {
655                 failure = true;
656                 continue;
657             }
658             SSET_FOR_EACH (name, &names) {
659                 struct dpif *dpif;
660                 int error;
661
662                 error = dpif_open(name, type, &dpif);
663                 if (!error) {
664                     show_dpif(dpif);
665                 } else {
666                     ovs_error(error, "opening datapath %s failed", name);
667                     failure = true;
668                 }
669             }
670             sset_destroy(&names);
671         }
672         sset_destroy(&types);
673     }
674     if (failure) {
675         exit(EXIT_FAILURE);
676     }
677 }
678
679 static void
680 dpctl_dump_dps(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
681 {
682     struct sset dpif_names, dpif_types;
683     const char *type;
684     int error = 0;
685
686     sset_init(&dpif_names);
687     sset_init(&dpif_types);
688     dp_enumerate_types(&dpif_types);
689
690     SSET_FOR_EACH (type, &dpif_types) {
691         const char *name;
692         int retval;
693
694         retval = dp_enumerate_names(type, &dpif_names);
695         if (retval) {
696             error = retval;
697         }
698
699         SSET_FOR_EACH (name, &dpif_names) {
700             struct dpif *dpif;
701             if (!dpif_open(name, type, &dpif)) {
702                 printf("%s\n", dpif_name(dpif));
703                 dpif_close(dpif);
704             }
705         }
706     }
707
708     sset_destroy(&dpif_names);
709     sset_destroy(&dpif_types);
710     if (error) {
711         exit(EXIT_FAILURE);
712     }
713 }
714
715 static void
716 dpctl_dump_flows(int argc, char *argv[])
717 {
718     const struct dpif_flow_stats *stats;
719     const struct nlattr *actions;
720     struct dpif_flow_dump dump;
721     const struct nlattr *key;
722     size_t actions_len;
723     struct dpif *dpif;
724     size_t key_len;
725     struct ds ds;
726     char *name;
727
728     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
729     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
730     free(name);
731
732     ds_init(&ds);
733     dpif_flow_dump_start(&dump, dpif);
734     while (dpif_flow_dump_next(&dump, &key, &key_len,
735                                &actions, &actions_len, &stats)) {
736         ds_clear(&ds);
737         odp_flow_key_format(key, key_len, &ds);
738         ds_put_cstr(&ds, ", ");
739         dpif_flow_stats_format(stats, &ds);
740         ds_put_cstr(&ds, ", actions:");
741         format_odp_actions(&ds, actions, actions_len);
742         printf("%s\n", ds_cstr(&ds));
743     }
744     dpif_flow_dump_done(&dump);
745     ds_destroy(&ds);
746     dpif_close(dpif);
747 }
748
749 static void
750 dpctl_del_flows(int argc, char *argv[])
751 {
752     struct dpif *dpif;
753     char *name;
754
755     name = (argc == 2) ? xstrdup(argv[1]) : get_one_dp();
756     run(parsed_dpif_open(name, false, &dpif), "opening datapath");
757     free(name);
758
759     run(dpif_flow_flush(dpif), "deleting all flows");
760     dpif_close(dpif);
761 }
762
763 static void
764 dpctl_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
765 {
766     usage();
767 }
768 \f
769 /* Undocumented commands for unit testing. */
770
771 static void
772 dpctl_parse_actions(int argc, char *argv[])
773 {
774     int i;
775
776     for (i = 1; i < argc; i++) {
777         struct ofpbuf actions;
778         struct ds s;
779
780         ofpbuf_init(&actions, 0);
781         run(odp_actions_from_string(argv[i], NULL, &actions),
782             "odp_actions_from_string");
783
784         ds_init(&s);
785         format_odp_actions(&s, actions.data, actions.size);
786         puts(ds_cstr(&s));
787         ds_destroy(&s);
788
789         ofpbuf_uninit(&actions);
790     }
791 }
792
793 struct actions_for_flow {
794     struct hmap_node hmap_node;
795     struct flow flow;
796     struct ofpbuf actions;
797 };
798
799 static struct actions_for_flow *
800 get_actions_for_flow(struct hmap *actions_per_flow, const struct flow *flow)
801 {
802     uint32_t hash = flow_hash(flow, 0);
803     struct actions_for_flow *af;
804
805     HMAP_FOR_EACH_WITH_HASH (af, hmap_node, hash, actions_per_flow) {
806         if (flow_equal(&af->flow, flow)) {
807             return af;
808         }
809     }
810
811     af = xmalloc(sizeof *af);
812     af->flow = *flow;
813     ofpbuf_init(&af->actions, 0);
814     hmap_insert(actions_per_flow, &af->hmap_node, hash);
815     return af;
816 }
817
818 static int
819 compare_actions_for_flow(const void *a_, const void *b_)
820 {
821     struct actions_for_flow *const *a = a_;
822     struct actions_for_flow *const *b = b_;
823
824     return flow_compare_3way(&(*a)->flow, &(*b)->flow);
825 }
826
827 static int
828 compare_output_actions(const void *a_, const void *b_)
829 {
830     const struct nlattr *a = a_;
831     const struct nlattr *b = b_;
832     uint32_t a_port = nl_attr_get_u32(a);
833     uint32_t b_port = nl_attr_get_u32(b);
834
835     return a_port < b_port ? -1 : a_port > b_port;
836 }
837
838 static void
839 sort_output_actions__(struct nlattr *first, struct nlattr *end)
840 {
841     size_t bytes = (uint8_t *) end - (uint8_t *) first;
842     size_t n = bytes / NL_A_U32_SIZE;
843
844     assert(bytes % NL_A_U32_SIZE == 0);
845     qsort(first, n, NL_A_U32_SIZE, compare_output_actions);
846 }
847
848 static void
849 sort_output_actions(struct nlattr *actions, size_t length)
850 {
851     struct nlattr *first_output = NULL;
852     struct nlattr *a;
853     int left;
854
855     NL_ATTR_FOR_EACH (a, left, actions, length) {
856         if (nl_attr_type(a) == OVS_ACTION_ATTR_OUTPUT) {
857             if (!first_output) {
858                 first_output = a;
859             }
860         } else {
861             if (first_output) {
862                 sort_output_actions__(first_output, a);
863                 first_output = NULL;
864             }
865         }
866     }
867     if (first_output) {
868         uint8_t *end = (uint8_t *) actions + length;
869         sort_output_actions__(first_output, (struct nlattr *) end);
870     }
871 }
872
873 /* usage: "ovs-dpctl normalize-actions FLOW ACTIONS" where FLOW and ACTIONS
874  * have the syntax used by "ovs-dpctl dump-flows".
875  *
876  * This command prints ACTIONS in a format that shows what happens for each
877  * VLAN, independent of the order of the ACTIONS.  For example, there is more
878  * than one way to output a packet on VLANs 9 and 11, but this command will
879  * print the same output for any form.
880  *
881  * The idea here generalizes beyond VLANs (e.g. to setting other fields) but
882  * so far the implementation only covers VLANs. */
883 static void
884 dpctl_normalize_actions(int argc, char *argv[])
885 {
886     struct simap port_names;
887     struct ofpbuf keybuf;
888     struct flow flow;
889     struct ofpbuf odp_actions;
890     struct hmap actions_per_flow;
891     struct actions_for_flow **afs;
892     struct actions_for_flow *af;
893     struct nlattr *a;
894     size_t n_afs;
895     struct ds s;
896     int left;
897     int i;
898
899     ds_init(&s);
900
901     simap_init(&port_names);
902     for (i = 3; i < argc; i++) {
903         char name[16];
904         int number;
905         int n = -1;
906
907         if (sscanf(argv[i], "%15[^=]=%d%n", name, &number, &n) > 0 && n > 0) {
908             uintptr_t n = number;
909             simap_put(&port_names, name, n);
910         } else {
911             ovs_fatal(0, "%s: expected NAME=NUMBER", argv[i]);
912         }
913     }
914
915     /* Parse flow key. */
916     ofpbuf_init(&keybuf, 0);
917     run(odp_flow_key_from_string(argv[1], &port_names, &keybuf),
918         "odp_flow_key_from_string");
919
920     ds_clear(&s);
921     odp_flow_key_format(keybuf.data, keybuf.size, &s);
922     printf("input flow: %s\n", ds_cstr(&s));
923
924     run(odp_flow_key_to_flow(keybuf.data, keybuf.size, &flow),
925         "odp_flow_key_to_flow");
926     ofpbuf_uninit(&keybuf);
927
928     /* Parse actions. */
929     ofpbuf_init(&odp_actions, 0);
930     run(odp_actions_from_string(argv[2], &port_names, &odp_actions),
931         "odp_actions_from_string");
932
933     if (verbosity) {
934         ds_clear(&s);
935         format_odp_actions(&s, odp_actions.data, odp_actions.size);
936         printf("input actions: %s\n", ds_cstr(&s));
937     }
938
939     hmap_init(&actions_per_flow);
940     NL_ATTR_FOR_EACH (a, left, odp_actions.data, odp_actions.size) {
941         if (nl_attr_type(a) == OVS_ACTION_ATTR_POP_VLAN) {
942             flow.vlan_tci = htons(0);
943             continue;
944         }
945
946         if (nl_attr_type(a) == OVS_ACTION_ATTR_PUSH_VLAN) {
947             const struct ovs_action_push_vlan *push;
948
949             push = nl_attr_get_unspec(a, sizeof *push);
950             flow.vlan_tci = push->vlan_tci;
951             continue;
952         }
953
954         af = get_actions_for_flow(&actions_per_flow, &flow);
955         nl_msg_put_unspec(&af->actions, nl_attr_type(a),
956                           nl_attr_get(a), nl_attr_get_size(a));
957     }
958
959     n_afs = hmap_count(&actions_per_flow);
960     afs = xmalloc(n_afs * sizeof *afs);
961     i = 0;
962     HMAP_FOR_EACH (af, hmap_node, &actions_per_flow) {
963         afs[i++] = af;
964     }
965     assert(i == n_afs);
966
967     qsort(afs, n_afs, sizeof *afs, compare_actions_for_flow);
968
969     for (i = 0; i < n_afs; i++) {
970         const struct actions_for_flow *af = afs[i];
971
972         sort_output_actions(af->actions.data, af->actions.size);
973
974         if (af->flow.vlan_tci != htons(0)) {
975             printf("vlan(vid=%"PRIu16",pcp=%d): ",
976                    vlan_tci_to_vid(af->flow.vlan_tci),
977                    vlan_tci_to_pcp(af->flow.vlan_tci));
978         } else {
979             printf("no vlan: ");
980         }
981
982         ds_clear(&s);
983         format_odp_actions(&s, af->actions.data, af->actions.size);
984         puts(ds_cstr(&s));
985     }
986     ds_destroy(&s);
987 }
988
989 static const struct command all_commands[] = {
990     { "add-dp", 1, INT_MAX, dpctl_add_dp },
991     { "del-dp", 1, 1, dpctl_del_dp },
992     { "add-if", 2, INT_MAX, dpctl_add_if },
993     { "del-if", 2, INT_MAX, dpctl_del_if },
994     { "set-if", 2, INT_MAX, dpctl_set_if },
995     { "dump-dps", 0, 0, dpctl_dump_dps },
996     { "show", 0, INT_MAX, dpctl_show },
997     { "dump-flows", 0, 1, dpctl_dump_flows },
998     { "del-flows", 0, 1, dpctl_del_flows },
999     { "help", 0, INT_MAX, dpctl_help },
1000
1001     /* Undocumented commands for testing. */
1002     { "parse-actions", 1, INT_MAX, dpctl_parse_actions },
1003     { "normalize-actions", 2, INT_MAX, dpctl_normalize_actions },
1004
1005     { NULL, 0, 0, NULL },
1006 };