1865c00347d6a0c72af342d2d970b809d9c910f4
[sliver-openvswitch.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 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 <errno.h>
19 #include <getopt.h>
20 #include <inttypes.h>
21 #include <net/if.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/stat.h>
27 #include <sys/time.h>
28
29 #include "byte-order.h"
30 #include "classifier.h"
31 #include "command-line.h"
32 #include "compiler.h"
33 #include "dirs.h"
34 #include "dpif.h"
35 #include "dynamic-string.h"
36 #include "netlink.h"
37 #include "nx-match.h"
38 #include "odp-util.h"
39 #include "ofp-parse.h"
40 #include "ofp-print.h"
41 #include "ofp-util.h"
42 #include "ofpbuf.h"
43 #include "openflow/nicira-ext.h"
44 #include "openflow/openflow.h"
45 #include "random.h"
46 #include "stream-ssl.h"
47 #include "timeval.h"
48 #include "util.h"
49 #include "vconn.h"
50 #include "vlog.h"
51
52 VLOG_DEFINE_THIS_MODULE(ofctl);
53
54 /* --strict: Use strict matching for flow mod commands? */
55 static bool strict;
56
57 /* -F, --flow-format: Flow format to use.  Either one of NXFF_* to force a
58  * particular flow format or -1 to let ovs-ofctl choose intelligently. */
59 static int preferred_flow_format = -1;
60
61 static const struct command all_commands[];
62
63 static void usage(void) NO_RETURN;
64 static void parse_options(int argc, char *argv[]);
65
66 int
67 main(int argc, char *argv[])
68 {
69     set_program_name(argv[0]);
70     parse_options(argc, argv);
71     signal(SIGPIPE, SIG_IGN);
72     run_command(argc - optind, argv + optind, all_commands);
73     return 0;
74 }
75
76 static void
77 parse_options(int argc, char *argv[])
78 {
79     enum {
80         OPT_STRICT = UCHAR_MAX + 1,
81         VLOG_OPTION_ENUMS
82     };
83     static struct option long_options[] = {
84         {"timeout", required_argument, 0, 't'},
85         {"strict", no_argument, 0, OPT_STRICT},
86         {"flow-format", required_argument, 0, 'F'},
87         {"help", no_argument, 0, 'h'},
88         {"version", no_argument, 0, 'V'},
89         VLOG_LONG_OPTIONS,
90         STREAM_SSL_LONG_OPTIONS
91         {0, 0, 0, 0},
92     };
93     char *short_options = long_options_to_short_options(long_options);
94
95     for (;;) {
96         unsigned long int timeout;
97         int c;
98
99         c = getopt_long(argc, argv, short_options, long_options, NULL);
100         if (c == -1) {
101             break;
102         }
103
104         switch (c) {
105         case 't':
106             timeout = strtoul(optarg, NULL, 10);
107             if (timeout <= 0) {
108                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
109                           optarg);
110             } else {
111                 time_alarm(timeout);
112             }
113             break;
114
115         case 'F':
116             preferred_flow_format = ofputil_flow_format_from_string(optarg);
117             if (preferred_flow_format < 0) {
118                 ovs_fatal(0, "unknown flow format `%s'", optarg);
119             }
120             break;
121
122         case 'h':
123             usage();
124
125         case 'V':
126             OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
127             exit(EXIT_SUCCESS);
128
129         case OPT_STRICT:
130             strict = true;
131             break;
132
133         VLOG_OPTION_HANDLERS
134         STREAM_SSL_OPTION_HANDLERS
135
136         case '?':
137             exit(EXIT_FAILURE);
138
139         default:
140             abort();
141         }
142     }
143     free(short_options);
144 }
145
146 static void
147 usage(void)
148 {
149     printf("%s: OpenFlow switch management utility\n"
150            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
151            "\nFor OpenFlow switches:\n"
152            "  show SWITCH                 show OpenFlow information\n"
153            "  status SWITCH [KEY]         report statistics (about KEY)\n"
154            "  dump-desc SWITCH            print switch description\n"
155            "  dump-tables SWITCH          print table stats\n"
156            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
157            "  dump-ports SWITCH [PORT]    print port statistics\n"
158            "  dump-flows SWITCH           print all flow entries\n"
159            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
160            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
161            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
162            "  queue-stats SWITCH [PORT [QUEUE]]  dump queue stats\n"
163            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
164            "  add-flows SWITCH FILE       add flows from FILE\n"
165            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
166            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
167            "  monitor SWITCH [MISSLEN]    print packets received from SWITCH\n"
168            "\nFor OpenFlow switches and controllers:\n"
169            "  probe VCONN                 probe whether VCONN is up\n"
170            "  ping VCONN [N]              latency of N-byte echos\n"
171            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
172            "where each SWITCH is an active OpenFlow connection method.\n",
173            program_name, program_name);
174     vconn_usage(true, false, false);
175     vlog_usage();
176     printf("\nOther options:\n"
177            "  --strict                    use strict match for flow commands\n"
178            "  -F, --flow-format=FORMAT    force particular flow format\n"
179            "  -t, --timeout=SECS          give up after SECS seconds\n"
180            "  -h, --help                  display this help message\n"
181            "  -V, --version               display version information\n");
182     exit(EXIT_SUCCESS);
183 }
184
185 static void run(int retval, const char *message, ...)
186     PRINTF_FORMAT(2, 3);
187
188 static void run(int retval, const char *message, ...)
189 {
190     if (retval) {
191         va_list args;
192
193         fprintf(stderr, "%s: ", program_name);
194         va_start(args, message);
195         vfprintf(stderr, message, args);
196         va_end(args);
197         if (retval == EOF) {
198             fputs(": unexpected end of file\n", stderr);
199         } else {
200             fprintf(stderr, ": %s\n", strerror(retval));
201         }
202
203         exit(EXIT_FAILURE);
204     }
205 }
206 \f
207 /* Generic commands. */
208
209 static void
210 open_vconn_socket(const char *name, struct vconn **vconnp)
211 {
212     char *vconn_name = xasprintf("unix:%s", name);
213     VLOG_DBG("connecting to %s", vconn_name);
214     run(vconn_open_block(vconn_name, OFP_VERSION, vconnp),
215         "connecting to %s", vconn_name);
216     free(vconn_name);
217 }
218
219 static void
220 open_vconn__(const char *name, const char *default_suffix,
221              struct vconn **vconnp)
222 {
223     struct dpif *dpif;
224     struct stat s;
225     char *bridge_path, *datapath_name, *datapath_type;
226
227     bridge_path = xasprintf("%s/%s.%s", ovs_rundir(), name, default_suffix);
228     dp_parse_name(name, &datapath_name, &datapath_type);
229
230     if (strstr(name, ":")) {
231         run(vconn_open_block(name, OFP_VERSION, vconnp),
232             "connecting to %s", name);
233     } else if (!stat(name, &s) && S_ISSOCK(s.st_mode)) {
234         open_vconn_socket(name, vconnp);
235     } else if (!stat(bridge_path, &s) && S_ISSOCK(s.st_mode)) {
236         open_vconn_socket(bridge_path, vconnp);
237     } else if (!dpif_open(datapath_name, datapath_type, &dpif)) {
238         char dpif_name[IF_NAMESIZE + 1];
239         char *socket_name;
240
241         run(dpif_port_get_name(dpif, ODPP_LOCAL, dpif_name, sizeof dpif_name),
242             "obtaining name of %s", dpif_name);
243         dpif_close(dpif);
244         if (strcmp(dpif_name, name)) {
245             VLOG_DBG("datapath %s is named %s", name, dpif_name);
246         }
247
248         socket_name = xasprintf("%s/%s.%s",
249                                 ovs_rundir(), dpif_name, default_suffix);
250         if (stat(socket_name, &s)) {
251             ovs_fatal(errno, "cannot connect to %s: stat failed on %s",
252                       name, socket_name);
253         } else if (!S_ISSOCK(s.st_mode)) {
254             ovs_fatal(0, "cannot connect to %s: %s is not a socket",
255                       name, socket_name);
256         }
257
258         open_vconn_socket(socket_name, vconnp);
259         free(socket_name);
260     } else {
261         ovs_fatal(0, "%s is not a valid connection method", name);
262     }
263
264     free(datapath_name);
265     free(datapath_type);
266     free(bridge_path);
267 }
268
269 static void
270 open_vconn(const char *name, struct vconn **vconnp)
271 {
272     return open_vconn__(name, "mgmt", vconnp);
273 }
274
275 static void *
276 alloc_stats_request(size_t body_len, uint16_t type, struct ofpbuf **bufferp)
277 {
278     struct ofp_stats_request *rq;
279     rq = make_openflow((offsetof(struct ofp_stats_request, body)
280                         + body_len), OFPT_STATS_REQUEST, bufferp);
281     rq->type = htons(type);
282     rq->flags = htons(0);
283     return rq->body;
284 }
285
286 static void
287 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
288 {
289     update_openflow_length(buffer);
290     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
291 }
292
293 static void
294 dump_transaction(const char *vconn_name, struct ofpbuf *request)
295 {
296     struct vconn *vconn;
297     struct ofpbuf *reply;
298
299     update_openflow_length(request);
300     open_vconn(vconn_name, &vconn);
301     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
302     ofp_print(stdout, reply->data, reply->size, 1);
303     vconn_close(vconn);
304 }
305
306 static void
307 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
308 {
309     struct ofpbuf *request;
310     make_openflow(sizeof(struct ofp_header), request_type, &request);
311     dump_transaction(vconn_name, request);
312 }
313
314 static void
315 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
316 {
317     ovs_be32 send_xid = ((struct ofp_header *) request->data)->xid;
318     struct vconn *vconn;
319     bool done = false;
320
321     open_vconn(vconn_name, &vconn);
322     send_openflow_buffer(vconn, request);
323     while (!done) {
324         uint32_t recv_xid;
325         struct ofpbuf *reply;
326
327         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
328         recv_xid = ((struct ofp_header *) reply->data)->xid;
329         if (send_xid == recv_xid) {
330             struct ofp_stats_reply *osr;
331
332             ofp_print(stdout, reply->data, reply->size, 1);
333
334             osr = ofpbuf_at(reply, 0, sizeof *osr);
335             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
336         } else {
337             VLOG_DBG("received reply with xid %08"PRIx32" "
338                      "!= expected %08"PRIx32, recv_xid, send_xid);
339         }
340         ofpbuf_delete(reply);
341     }
342     vconn_close(vconn);
343 }
344
345 static void
346 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
347 {
348     struct ofpbuf *request;
349     alloc_stats_request(0, stats_type, &request);
350     dump_stats_transaction(vconn_name, request);
351 }
352
353 /* Sends 'request', which should be a request that only has a reply if an error
354  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
355  * it and exits with an error. */
356 static void
357 transact_multiple_noreply(struct vconn *vconn, struct list *requests)
358 {
359     struct ofpbuf *request, *reply;
360
361     LIST_FOR_EACH (request, list_node, requests) {
362         update_openflow_length(request);
363     }
364
365     run(vconn_transact_multiple_noreply(vconn, requests, &reply),
366         "talking to %s", vconn_get_name(vconn));
367     if (reply) {
368         ofp_print(stderr, reply->data, reply->size, 2);
369         exit(1);
370     }
371     ofpbuf_delete(reply);
372 }
373
374 /* Sends 'request', which should be a request that only has a reply if an error
375  * occurs, and waits for it to succeed or fail.  If an error does occur, prints
376  * it and exits with an error. */
377 static void
378 transact_noreply(struct vconn *vconn, struct ofpbuf *request)
379 {
380     struct list requests;
381
382     list_init(&requests);
383     list_push_back(&requests, &request->list_node);
384     transact_multiple_noreply(vconn, &requests);
385 }
386
387 static void
388 do_show(int argc OVS_UNUSED, char *argv[])
389 {
390     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
391     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
392 }
393
394 static void
395 do_status(int argc, char *argv[])
396 {
397     struct nicira_header *request, *reply;
398     struct vconn *vconn;
399     struct ofpbuf *b;
400
401     request = make_nxmsg(sizeof *request, NXT_STATUS_REQUEST, &b);
402     if (argc > 2) {
403         ofpbuf_put(b, argv[2], strlen(argv[2]));
404         update_openflow_length(b);
405     }
406     open_vconn(argv[1], &vconn);
407     run(vconn_transact(vconn, b, &b), "talking to %s", argv[1]);
408     vconn_close(vconn);
409
410     if (b->size < sizeof *reply) {
411         ovs_fatal(0, "short reply (%zu bytes)", b->size);
412     }
413     reply = b->data;
414     if (reply->header.type != OFPT_VENDOR
415         || reply->vendor != ntohl(NX_VENDOR_ID)
416         || reply->subtype != ntohl(NXT_STATUS_REPLY)) {
417         ofp_print(stderr, b->data, b->size, 2);
418         ovs_fatal(0, "bad reply");
419     }
420
421     fwrite(reply + 1, b->size - sizeof *reply, 1, stdout);
422 }
423
424 static void
425 do_dump_desc(int argc OVS_UNUSED, char *argv[])
426 {
427     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
428 }
429
430 static void
431 do_dump_tables(int argc OVS_UNUSED, char *argv[])
432 {
433     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
434 }
435
436 /* Opens a connection to 'vconn_name', fetches the ofp_phy_port structure for
437  * 'port_name' (which may be a port name or number), and copies it into
438  * '*oppp'. */
439 static void
440 fetch_ofp_phy_port(const char *vconn_name, const char *port_name,
441                    struct ofp_phy_port *oppp)
442 {
443     struct ofpbuf *request, *reply;
444     struct ofp_switch_features *osf;
445     unsigned int port_no;
446     struct vconn *vconn;
447     int n_ports;
448     int port_idx;
449
450     /* Try to interpret the argument as a port number. */
451     if (!str_to_uint(port_name, 10, &port_no)) {
452         port_no = UINT_MAX;
453     }
454
455     /* Fetch the switch's ofp_switch_features. */
456     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
457     open_vconn(vconn_name, &vconn);
458     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
459
460     osf = reply->data;
461     if (reply->size < sizeof *osf) {
462         ovs_fatal(0, "%s: received too-short features reply (only %zu bytes)",
463                   vconn_name, reply->size);
464     }
465     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
466
467     for (port_idx = 0; port_idx < n_ports; port_idx++) {
468         const struct ofp_phy_port *opp = &osf->ports[port_idx];
469
470         if (port_no != UINT_MAX
471             ? htons(port_no) == opp->port_no
472             : !strncmp(opp->name, port_name, sizeof opp->name)) {
473             *oppp = *opp;
474             ofpbuf_delete(reply);
475             vconn_close(vconn);
476             return;
477         }
478     }
479     ovs_fatal(0, "%s: couldn't find port `%s'", vconn_name, port_name);
480 }
481
482 /* Returns the port number corresponding to 'port_name' (which may be a port
483  * name or number) within the switch 'vconn_name'. */
484 static uint16_t
485 str_to_port_no(const char *vconn_name, const char *port_name)
486 {
487     unsigned int port_no;
488
489     if (str_to_uint(port_name, 10, &port_no)) {
490         return port_no;
491     } else {
492         struct ofp_phy_port opp;
493
494         fetch_ofp_phy_port(vconn_name, port_name, &opp);
495         return ntohs(opp.port_no);
496     }
497 }
498
499 static bool
500 try_set_flow_format(struct vconn *vconn, enum nx_flow_format flow_format)
501 {
502     struct ofpbuf *sff, *reply;
503
504     sff = ofputil_make_set_flow_format(flow_format);
505     run(vconn_transact_noreply(vconn, sff, &reply),
506         "talking to %s", vconn_get_name(vconn));
507     if (reply) {
508         char *s = ofp_to_string(reply->data, reply->size, 2);
509         VLOG_DBG("%s: failed to set flow format %s, controller replied: %s",
510                  vconn_get_name(vconn),
511                  ofputil_flow_format_to_string(flow_format),
512                  s);
513         free(s);
514         ofpbuf_delete(reply);
515         return false;
516     }
517     return true;
518 }
519
520 static void
521 set_flow_format(struct vconn *vconn, enum nx_flow_format flow_format)
522 {
523     struct ofpbuf *sff = ofputil_make_set_flow_format(flow_format);
524     transact_noreply(vconn, sff);
525     VLOG_DBG("%s: using user-specified flow format %s",
526              vconn_get_name(vconn),
527              ofputil_flow_format_to_string(flow_format));
528 }
529
530 static enum nx_flow_format
531 negotiate_highest_flow_format(struct vconn *vconn, const struct cls_rule *rule,
532                               bool cookie_support, ovs_be64 cookie)
533 {
534     int flow_format;
535
536     if (preferred_flow_format != -1) {
537         enum nx_flow_format min_format;
538
539         min_format = ofputil_min_flow_format(rule, cookie_support, cookie);
540         if (preferred_flow_format >= min_format) {
541             set_flow_format(vconn, preferred_flow_format);
542             return preferred_flow_format;
543         }
544
545         VLOG_WARN("%s: cannot use requested flow format %s for "
546                   "specified flow", vconn_get_name(vconn),
547                   ofputil_flow_format_to_string(min_format));
548     }
549
550     if (try_set_flow_format(vconn, NXFF_NXM)) {
551         flow_format = NXFF_NXM;
552     } else if (try_set_flow_format(vconn, NXFF_TUN_ID_FROM_COOKIE)) {
553         flow_format = NXFF_TUN_ID_FROM_COOKIE;
554     } else {
555         flow_format = NXFF_OPENFLOW10;
556     }
557
558     VLOG_DBG("%s: negotiated flow format %s", vconn_get_name(vconn),
559              ofputil_flow_format_to_string(flow_format));
560     return flow_format;
561 }
562
563 static void
564 do_dump_flows__(int argc, char *argv[], bool aggregate)
565 {
566     enum nx_flow_format flow_format;
567     struct flow_stats_request fsr;
568     struct ofpbuf *request;
569     struct vconn *vconn;
570
571     parse_ofp_flow_stats_request_str(&fsr, aggregate, argc > 2 ? argv[2] : "");
572
573     open_vconn(argv[1], &vconn);
574     flow_format = negotiate_highest_flow_format(vconn, &fsr.match, false, 0);
575     request = ofputil_encode_flow_stats_request(&fsr, flow_format);
576     dump_stats_transaction(argv[1], request);
577     vconn_close(vconn);
578 }
579
580 static void
581 do_dump_flows(int argc, char *argv[])
582 {
583     return do_dump_flows__(argc, argv, false);
584 }
585
586 static void
587 do_dump_aggregate(int argc, char *argv[])
588 {
589     return do_dump_flows__(argc, argv, true);
590 }
591
592 static void
593 do_queue_stats(int argc, char *argv[])
594 {
595     struct ofp_queue_stats_request *req;
596     struct ofpbuf *request;
597
598     req = alloc_stats_request(sizeof *req, OFPST_QUEUE, &request);
599
600     if (argc > 2 && argv[2][0] && strcasecmp(argv[2], "all")) {
601         req->port_no = htons(str_to_port_no(argv[1], argv[2]));
602     } else {
603         req->port_no = htons(OFPP_ALL);
604     }
605     if (argc > 3 && argv[3][0] && strcasecmp(argv[3], "all")) {
606         req->queue_id = htonl(atoi(argv[3]));
607     } else {
608         req->queue_id = htonl(OFPQ_ALL);
609     }
610
611     memset(req->pad, 0, sizeof req->pad);
612
613     dump_stats_transaction(argv[1], request);
614 }
615
616 static void
617 do_flow_mod__(int argc OVS_UNUSED, char *argv[], uint16_t command)
618 {
619     enum nx_flow_format flow_format;
620     struct list requests;
621     struct vconn *vconn;
622
623     list_init(&requests);
624     flow_format = NXFF_OPENFLOW10;
625     parse_ofp_flow_mod_str(&requests, &flow_format, argv[2], command);
626
627     open_vconn(argv[1], &vconn);
628     transact_multiple_noreply(vconn, &requests);
629     vconn_close(vconn);
630 }
631
632 static void
633 do_add_flow(int argc, char *argv[])
634 {
635     do_flow_mod__(argc, argv, OFPFC_ADD);
636 }
637
638 static void
639 do_add_flows(int argc OVS_UNUSED, char *argv[])
640 {
641     enum nx_flow_format flow_format;
642     struct list requests;
643     struct vconn *vconn;
644     FILE *file;
645
646     file = fopen(argv[2], "r");
647     if (file == NULL) {
648         ovs_fatal(errno, "%s: open", argv[2]);
649     }
650
651     list_init(&requests);
652     flow_format = NXFF_OPENFLOW10;
653
654     open_vconn(argv[1], &vconn);
655     while (parse_ofp_add_flow_file(&requests, &flow_format, file)) {
656         transact_multiple_noreply(vconn, &requests);
657     }
658     vconn_close(vconn);
659
660     fclose(file);
661 }
662
663 static void
664 do_mod_flows(int argc, char *argv[])
665 {
666     do_flow_mod__(argc, argv, strict ? OFPFC_MODIFY_STRICT : OFPFC_MODIFY);
667 }
668
669 static void
670 do_del_flows(int argc, char *argv[])
671 {
672     do_flow_mod__(argc, argv, strict ? OFPFC_DELETE_STRICT : OFPFC_DELETE);
673 }
674
675 static void
676 monitor_vconn(struct vconn *vconn)
677 {
678     for (;;) {
679         struct ofpbuf *b;
680         run(vconn_recv_block(vconn, &b), "vconn_recv");
681         ofp_print(stderr, b->data, b->size, 2);
682         ofpbuf_delete(b);
683     }
684 }
685
686 static void
687 do_monitor(int argc, char *argv[])
688 {
689     struct vconn *vconn;
690
691     open_vconn(argv[1], &vconn);
692     if (argc > 2) {
693         int miss_send_len = atoi(argv[2]);
694         struct ofp_switch_config *osc;
695         struct ofpbuf *buf;
696
697         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &buf);
698         osc->miss_send_len = htons(miss_send_len);
699         transact_noreply(vconn, buf);
700     }
701     monitor_vconn(vconn);
702 }
703
704 static void
705 do_snoop(int argc OVS_UNUSED, char *argv[])
706 {
707     struct vconn *vconn;
708
709     open_vconn__(argv[1], "snoop", &vconn);
710     monitor_vconn(vconn);
711 }
712
713 static void
714 do_dump_ports(int argc, char *argv[])
715 {
716     struct ofp_port_stats_request *req;
717     struct ofpbuf *request;
718     uint16_t port;
719
720     req = alloc_stats_request(sizeof *req, OFPST_PORT, &request);
721     port = argc > 2 ? str_to_port_no(argv[1], argv[2]) : OFPP_NONE;
722     req->port_no = htons(port);
723     dump_stats_transaction(argv[1], request);
724 }
725
726 static void
727 do_probe(int argc OVS_UNUSED, char *argv[])
728 {
729     struct ofpbuf *request;
730     struct vconn *vconn;
731     struct ofpbuf *reply;
732
733     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
734     open_vconn(argv[1], &vconn);
735     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
736     if (reply->size != sizeof(struct ofp_header)) {
737         ovs_fatal(0, "reply does not match request");
738     }
739     ofpbuf_delete(reply);
740     vconn_close(vconn);
741 }
742
743 static void
744 do_mod_port(int argc OVS_UNUSED, char *argv[])
745 {
746     struct ofp_port_mod *opm;
747     struct ofp_phy_port opp;
748     struct ofpbuf *request;
749     struct vconn *vconn;
750
751     fetch_ofp_phy_port(argv[1], argv[2], &opp);
752
753     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
754     opm->port_no = opp.port_no;
755     memcpy(opm->hw_addr, opp.hw_addr, sizeof opm->hw_addr);
756     opm->config = htonl(0);
757     opm->mask = htonl(0);
758     opm->advertise = htonl(0);
759
760     if (!strcasecmp(argv[3], "up")) {
761         opm->mask |= htonl(OFPPC_PORT_DOWN);
762     } else if (!strcasecmp(argv[3], "down")) {
763         opm->mask |= htonl(OFPPC_PORT_DOWN);
764         opm->config |= htonl(OFPPC_PORT_DOWN);
765     } else if (!strcasecmp(argv[3], "flood")) {
766         opm->mask |= htonl(OFPPC_NO_FLOOD);
767     } else if (!strcasecmp(argv[3], "noflood")) {
768         opm->mask |= htonl(OFPPC_NO_FLOOD);
769         opm->config |= htonl(OFPPC_NO_FLOOD);
770     } else {
771         ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
772     }
773
774     open_vconn(argv[1], &vconn);
775     transact_noreply(vconn, request);
776     vconn_close(vconn);
777 }
778
779 static void
780 do_ping(int argc, char *argv[])
781 {
782     size_t max_payload = 65535 - sizeof(struct ofp_header);
783     unsigned int payload;
784     struct vconn *vconn;
785     int i;
786
787     payload = argc > 2 ? atoi(argv[2]) : 64;
788     if (payload > max_payload) {
789         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
790     }
791
792     open_vconn(argv[1], &vconn);
793     for (i = 0; i < 10; i++) {
794         struct timeval start, end;
795         struct ofpbuf *request, *reply;
796         struct ofp_header *rq_hdr, *rpy_hdr;
797
798         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
799                                OFPT_ECHO_REQUEST, &request);
800         random_bytes(rq_hdr + 1, payload);
801
802         gettimeofday(&start, NULL);
803         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
804         gettimeofday(&end, NULL);
805
806         rpy_hdr = reply->data;
807         if (reply->size != request->size
808             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
809             || rpy_hdr->xid != rq_hdr->xid
810             || rpy_hdr->type != OFPT_ECHO_REPLY) {
811             printf("Reply does not match request.  Request:\n");
812             ofp_print(stdout, request, request->size, 2);
813             printf("Reply:\n");
814             ofp_print(stdout, reply, reply->size, 2);
815         }
816         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
817                reply->size - sizeof *rpy_hdr, argv[1], ntohl(rpy_hdr->xid),
818                    (1000*(double)(end.tv_sec - start.tv_sec))
819                    + (.001*(end.tv_usec - start.tv_usec)));
820         ofpbuf_delete(request);
821         ofpbuf_delete(reply);
822     }
823     vconn_close(vconn);
824 }
825
826 static void
827 do_benchmark(int argc OVS_UNUSED, char *argv[])
828 {
829     size_t max_payload = 65535 - sizeof(struct ofp_header);
830     struct timeval start, end;
831     unsigned int payload_size, message_size;
832     struct vconn *vconn;
833     double duration;
834     int count;
835     int i;
836
837     payload_size = atoi(argv[2]);
838     if (payload_size > max_payload) {
839         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
840     }
841     message_size = sizeof(struct ofp_header) + payload_size;
842
843     count = atoi(argv[3]);
844
845     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
846            count, message_size, count * message_size);
847
848     open_vconn(argv[1], &vconn);
849     gettimeofday(&start, NULL);
850     for (i = 0; i < count; i++) {
851         struct ofpbuf *request, *reply;
852         struct ofp_header *rq_hdr;
853
854         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
855         memset(rq_hdr + 1, 0, payload_size);
856         run(vconn_transact(vconn, request, &reply), "transact");
857         ofpbuf_delete(reply);
858     }
859     gettimeofday(&end, NULL);
860     vconn_close(vconn);
861
862     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
863                 + (.001*(end.tv_usec - start.tv_usec)));
864     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
865            duration, count / (duration / 1000.0),
866            count * message_size / (duration / 1000.0));
867 }
868
869 static void
870 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
871 {
872     usage();
873 }
874 \f
875 /* Undocumented commands for unit testing. */
876
877 static void
878 do_parse_flows(int argc OVS_UNUSED, char *argv[])
879 {
880     enum nx_flow_format flow_format;
881     struct list packets;
882     FILE *file;
883
884     file = fopen(argv[1], "r");
885     if (file == NULL) {
886         ovs_fatal(errno, "%s: open", argv[2]);
887     }
888
889     list_init(&packets);
890     flow_format = NXFF_OPENFLOW10;
891     if (preferred_flow_format > 0) {
892         flow_format = preferred_flow_format;
893     }
894
895     while (parse_ofp_add_flow_file(&packets, &flow_format, file)) {
896         struct ofpbuf *packet, *next;
897
898         LIST_FOR_EACH_SAFE (packet, next, list_node, &packets) {
899             ofp_print(stdout, packet->data, packet->size, 0);
900             list_remove(&packet->list_node);
901             ofpbuf_delete(packet);
902         }
903     }
904     fclose(file);
905 }
906
907 static void
908 do_parse_nx_match(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
909 {
910     struct ds in;
911
912     ds_init(&in);
913     while (!ds_get_line(&in, stdin)) {
914         struct ofpbuf nx_match;
915         struct cls_rule rule;
916         int match_len;
917         int error;
918         char *s;
919
920         /* Delete comments, skip blank lines. */
921         s = ds_cstr(&in);
922         if (*s == '#') {
923             puts(s);
924             continue;
925         }
926         if (strchr(s, '#')) {
927             *strchr(s, '#') = '\0';
928         }
929         if (s[strspn(s, " ")] == '\0') {
930             putchar('\n');
931             continue;
932         }
933
934         /* Convert string to nx_match. */
935         ofpbuf_init(&nx_match, 0);
936         match_len = nx_match_from_string(ds_cstr(&in), &nx_match);
937
938         /* Convert nx_match to cls_rule. */
939         error = nx_pull_match(&nx_match, match_len, 0, &rule);
940         if (!error) {
941             char *out;
942
943             /* Convert cls_rule back to nx_match. */
944             ofpbuf_uninit(&nx_match);
945             ofpbuf_init(&nx_match, 0);
946             match_len = nx_put_match(&nx_match, &rule);
947
948             /* Convert nx_match to string. */
949             out = nx_match_to_string(nx_match.data, match_len);
950             puts(out);
951             free(out);
952         } else {
953             printf("nx_pull_match() returned error %x\n", error);
954         }
955
956         ofpbuf_uninit(&nx_match);
957     }
958     ds_destroy(&in);
959 }
960
961 static const struct command all_commands[] = {
962     { "show", 1, 1, do_show },
963     { "status", 1, 2, do_status },
964     { "monitor", 1, 2, do_monitor },
965     { "snoop", 1, 1, do_snoop },
966     { "dump-desc", 1, 1, do_dump_desc },
967     { "dump-tables", 1, 1, do_dump_tables },
968     { "dump-flows", 1, 2, do_dump_flows },
969     { "dump-aggregate", 1, 2, do_dump_aggregate },
970     { "queue-stats", 1, 3, do_queue_stats },
971     { "add-flow", 2, 2, do_add_flow },
972     { "add-flows", 2, 2, do_add_flows },
973     { "mod-flows", 2, 2, do_mod_flows },
974     { "del-flows", 1, 2, do_del_flows },
975     { "dump-ports", 1, 2, do_dump_ports },
976     { "mod-port", 3, 3, do_mod_port },
977     { "probe", 1, 1, do_probe },
978     { "ping", 1, 2, do_ping },
979     { "benchmark", 3, 3, do_benchmark },
980     { "help", 0, INT_MAX, do_help },
981
982     /* Undocumented commands for testing. */
983     { "parse-flows", 1, 1, do_parse_flows },
984     { "parse-nx-match", 0, 0, do_parse_nx_match },
985
986     { NULL, 0, 0, NULL },
987 };