Add "benchmark" command to work like "benchmark-nl" with echo requests.
[openvswitch] / utilities / dpctl.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <errno.h>
35 #include <getopt.h>
36 #include <inttypes.h>
37 #include <netinet/in.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <sys/time.h>
43
44 #include "command-line.h"
45 #include "compiler.h"
46 #include "buffer.h"
47 #include "dpif.h"
48 #ifdef HAVE_NETLINK
49 #include "netlink.h"
50 #include "openflow-netlink.h"
51 #endif
52 #include "util.h"
53 #include "socket-util.h"
54 #include "openflow.h"
55 #include "ofp-print.h"
56 #include "random.h"
57 #include "vconn.h"
58 #include "vconn-ssl.h"
59
60 #include "vlog.h"
61 #define THIS_MODULE VLM_dpctl
62
63 #define DEFAULT_MAX_IDLE 60
64 #define MAX_ADD_ACTS 5
65
66 static const char* ifconfigbin = "/sbin/ifconfig";
67
68 struct command {
69     const char *name;
70     int min_args;
71     int max_args;
72     void (*handler)(int argc, char *argv[]);
73 };
74
75 static struct command all_commands[];
76
77 static void usage(void) NO_RETURN;
78 static void parse_options(int argc, char *argv[]);
79
80 int main(int argc, char *argv[])
81 {
82     struct command *p;
83
84     set_program_name(argv[0]);
85     vlog_init();
86     parse_options(argc, argv);
87
88     argc -= optind;
89     argv += optind;
90     if (argc < 1)
91         fatal(0, "missing command name; use --help for help");
92
93     for (p = all_commands; p->name != NULL; p++) {
94         if (!strcmp(p->name, argv[0])) {
95             int n_arg = argc - 1;
96             if (n_arg < p->min_args)
97                 fatal(0, "'%s' command requires at least %d arguments",
98                       p->name, p->min_args);
99             else if (n_arg > p->max_args)
100                 fatal(0, "'%s' command takes at most %d arguments",
101                       p->name, p->max_args);
102             else {
103                 p->handler(argc, argv);
104                 exit(0);
105             }
106         }
107     }
108     fatal(0, "unknown command '%s'; use --help for help", argv[0]);
109
110     return 0;
111 }
112
113 static void
114 parse_options(int argc, char *argv[])
115 {
116     static struct option long_options[] = {
117         {"verbose", optional_argument, 0, 'v'},
118         {"help", no_argument, 0, 'h'},
119         {"version", no_argument, 0, 'V'},
120         VCONN_SSL_LONG_OPTIONS
121         {0, 0, 0, 0},
122     };
123     char *short_options = long_options_to_short_options(long_options);
124
125     for (;;) {
126         int indexptr;
127         int c;
128
129         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
130         if (c == -1) {
131             break;
132         }
133
134         switch (c) {
135         case 'h':
136             usage();
137
138         case 'V':
139             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
140             exit(EXIT_SUCCESS);
141
142         case 'v':
143             vlog_set_verbosity(optarg);
144             break;
145
146         VCONN_SSL_OPTION_HANDLERS
147
148         case '?':
149             exit(EXIT_FAILURE);
150
151         default:
152             abort();
153         }
154     }
155     free(short_options);
156 }
157
158 static void
159 usage(void)
160 {
161     printf("%s: OpenFlow switch management utility\n"
162            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
163 #ifdef HAVE_NETLINK
164            "\nCommands that apply to local datapaths only:\n"
165            "  adddp nl:DP_ID              add a new local datapath DP_ID\n"
166            "  deldp nl:DP_ID              delete local datapath DP_ID\n"
167            "  addif nl:DP_ID IFACE        add IFACE as a port on DP_ID\n"
168            "  delif nl:DP_ID IFACE        delete IFACE as a port on DP_ID\n"
169            "  monitor nl:DP_ID            print packets received\n"
170            "  benchmark-nl nl:DP_ID N SIZE   send N packets of SIZE bytes\n"
171 #endif
172            "\nCommands that apply to local datapaths and remote switches:\n"
173            "  show SWITCH                 show information\n"
174            "  dump-tables SWITCH          print table stats\n"
175            "  dump-ports SWITCH           print port statistics\n"
176            "  dump-flows SWITCH           print all flow entries\n"
177            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
178            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
179            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
180            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
181            "  add-flows SWITCH FILE       add flows from FILE\n"
182            "  del-flows SWITCH FLOW       delete matching FLOWs\n"
183            "  ping SWITCH [N]             latency of N-byte echos\n"
184            "  benchmark SWITCH N COUNT    bandwidth of COUNT N-byte echos\n"
185            "where each SWITCH is an active OpenFlow connection method.\n",
186            program_name, program_name);
187     vconn_usage(true, false);
188     printf("\nOptions:\n"
189            "  -v, --verbose=MODULE:FACILITY:LEVEL  configure logging levels\n"
190            "  -v, --verbose               set maximum verbosity level\n"
191            "  -h, --help                  display this help message\n"
192            "  -V, --version               display version information\n");
193     exit(EXIT_SUCCESS);
194 }
195
196 static void run(int retval, const char *message, ...)
197     PRINTF_FORMAT(2, 3);
198
199 static void run(int retval, const char *message, ...)
200 {
201     if (retval) {
202         va_list args;
203
204         fprintf(stderr, "%s: ", program_name);
205         va_start(args, message);
206         vfprintf(stderr, message, args);
207         va_end(args);
208         if (retval == EOF) {
209             fputs(": unexpected end of file\n", stderr);
210         } else {
211             fprintf(stderr, ": %s\n", strerror(retval));
212         }
213
214         exit(EXIT_FAILURE);
215     }
216 }
217 \f
218 #ifdef HAVE_NETLINK
219 /* Netlink-only commands. */
220
221 static int  if_up(const char* intf)
222 {
223     char command[256];
224     snprintf(command, sizeof command, "%s %s up &> /dev/null",
225             ifconfigbin, intf);
226     return system(command);
227 }
228
229 static void open_nl_vconn(const char *name, bool subscribe, struct dpif *dpif)
230 {
231     if (strncmp(name, "nl:", 3)
232         || strlen(name) < 4
233         || name[strspn(name + 3, "0123456789") + 3]) {
234         fatal(0, "%s: argument is not of the form \"nl:DP_ID\"", name);
235     }
236     run(dpif_open(atoi(name + 3), subscribe, dpif), "opening datapath");
237 }
238
239 static void do_add_dp(int argc UNUSED, char *argv[])
240 {
241     struct dpif dp;
242     open_nl_vconn(argv[1], false, &dp);
243     run(dpif_add_dp(&dp), "add_dp");
244     dpif_close(&dp);
245 }
246
247 static void do_del_dp(int argc UNUSED, char *argv[])
248 {
249     struct dpif dp;
250     open_nl_vconn(argv[1], false, &dp);
251     run(dpif_del_dp(&dp), "del_dp");
252     dpif_close(&dp);
253 }
254
255 static void do_add_port(int argc UNUSED, char *argv[])
256 {
257     struct dpif dp;
258     if_up(argv[2]);
259     open_nl_vconn(argv[1], false, &dp);
260     run(dpif_add_port(&dp, argv[2]), "add_port");
261     dpif_close(&dp);
262 }
263
264 static void do_del_port(int argc UNUSED, char *argv[])
265 {
266     struct dpif dp;
267     open_nl_vconn(argv[1], false, &dp);
268     run(dpif_del_port(&dp, argv[2]), "del_port");
269     dpif_close(&dp);
270 }
271
272 static void do_monitor(int argc UNUSED, char *argv[])
273 {
274     struct dpif dp;
275     open_nl_vconn(argv[1], true, &dp);
276     for (;;) {
277         struct buffer *b;
278         run(dpif_recv_openflow(&dp, &b, true), "dpif_recv_openflow");
279         ofp_print(stderr, b->data, b->size, 2);
280         buffer_delete(b);
281     }
282 }
283
284 #define BENCHMARK_INCR   100
285
286 static void do_benchmark_nl(int argc UNUSED, char *argv[])
287 {
288     struct dpif dp;
289     uint32_t num_packets, i, milestone;
290     struct timeval start, end;
291
292     open_nl_vconn(argv[1], false, &dp);
293     num_packets = atoi(argv[2]);
294     milestone = BENCHMARK_INCR;
295     run(dpif_benchmark_nl(&dp, num_packets, atoi(argv[3])), "benchmark_nl");
296     if (gettimeofday(&start, NULL) == -1) {
297         run(errno, "gettimeofday");
298     }
299     for (i = 0; i < num_packets;i++) {
300         struct buffer *b;
301         run(dpif_recv_openflow(&dp, &b, true), "dpif_recv_openflow");
302         if (i == milestone) {
303             gettimeofday(&end, NULL);
304             printf("%u packets received in %f ms\n",
305                    BENCHMARK_INCR,
306                    (1000*(double)(end.tv_sec - start.tv_sec))
307                    + (.001*(end.tv_usec - start.tv_usec)));
308             milestone += BENCHMARK_INCR;
309             start = end;
310         }
311         buffer_delete(b);
312     }
313     gettimeofday(&end, NULL);
314     printf("%u packets received in %f ms\n",
315            i - (milestone - BENCHMARK_INCR),
316            (1000*(double)(end.tv_sec - start.tv_sec))
317            + (.001*(end.tv_usec - start.tv_usec)));
318
319     dpif_close(&dp);
320 }
321 #endif /* HAVE_NETLINK */
322 \f
323 /* Generic commands. */
324
325 static void *
326 alloc_openflow_buffer(size_t openflow_len, uint8_t type,
327                       struct buffer **bufferp)
328 {
329         struct buffer *buffer;
330         struct ofp_header *oh;
331
332         buffer = *bufferp = buffer_new(openflow_len);
333         oh = buffer_put_uninit(buffer, openflow_len);
334     memset(oh, 0, openflow_len);
335         oh->version = OFP_VERSION;
336         oh->type = type;
337         oh->length = 0;
338         oh->xid = random_uint32();
339         return oh;
340 }
341
342 static void *
343 alloc_stats_request(size_t body_len, uint16_t type, struct buffer **bufferp)
344 {
345     struct ofp_stats_request *rq;
346     rq = alloc_openflow_buffer((offsetof(struct ofp_stats_request, body)
347                                 + body_len), OFPT_STATS_REQUEST, bufferp);
348     rq->type = htons(type);
349     rq->flags = htons(0);
350     return rq->body;
351 }
352
353 static void
354 send_openflow_buffer(struct vconn *vconn, struct buffer *buffer)
355 {
356     struct ofp_header *oh;
357
358     oh = buffer_at_assert(buffer, 0, sizeof *oh);
359     oh->length = htons(buffer->size);
360
361     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
362 }
363
364 static struct buffer *
365 transact_openflow(struct vconn *vconn, struct buffer *request)
366 {
367     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
368
369     send_openflow_buffer(vconn, request);
370     for (;;) {
371         uint32_t recv_xid;
372         struct buffer *reply;
373
374         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
375         recv_xid = ((struct ofp_header *) reply->data)->xid;
376         if (send_xid == recv_xid) {
377             return reply;
378         }
379
380         VLOG_DBG("received reply with xid %08"PRIx32" != expected %08"PRIx32,
381                  recv_xid, send_xid);
382         buffer_delete(reply);
383     }
384 }
385
386 static void
387 dump_transaction(const char *vconn_name, struct buffer *request)
388 {
389     struct vconn *vconn;
390     struct buffer *reply;
391
392     run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
393     reply = transact_openflow(vconn, request);
394     ofp_print(stdout, reply->data, reply->size, 1);
395     vconn_close(vconn);
396 }
397
398 static void
399 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
400 {
401     struct buffer *request;
402     alloc_openflow_buffer(sizeof(struct ofp_header), request_type, &request);
403     dump_transaction(vconn_name, request);
404 }
405
406 static void
407 dump_stats_transaction(const char *vconn_name, struct buffer *request)
408 {
409     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
410     struct vconn *vconn;
411     bool done = false;
412
413     run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
414     send_openflow_buffer(vconn, request);
415     while (!done) {
416         uint32_t recv_xid;
417         struct buffer *reply;
418
419         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
420         recv_xid = ((struct ofp_header *) reply->data)->xid;
421         if (send_xid == recv_xid) {
422             struct ofp_stats_reply *osr;
423
424             ofp_print(stdout, reply->data, reply->size, 1);
425
426             osr = buffer_at(reply, 0, sizeof *osr);
427             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
428         } else {
429             VLOG_DBG("received reply with xid %08"PRIx32" "
430                      "!= expected %08"PRIx32, recv_xid, send_xid);
431         }
432         buffer_delete(reply);
433     }
434     vconn_close(vconn);
435 }
436
437 static void
438 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
439 {
440     struct buffer *request;
441     alloc_stats_request(0, stats_type, &request);
442     dump_stats_transaction(vconn_name, request);
443 }
444
445 static void
446 do_show(int argc UNUSED, char *argv[])
447 {
448     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
449     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
450 }
451
452
453 static void
454 do_dump_tables(int argc, char *argv[])
455 {
456     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
457 }
458
459
460 static uint32_t
461 str_to_int(const char *str) 
462 {
463     uint32_t value;
464     if (sscanf(str, "%"SCNu32, &value) != 1) {
465         fatal(0, "invalid numeric format %s", str);
466     }
467     return value;
468 }
469
470 static void
471 str_to_mac(const char *str, uint8_t mac[6]) 
472 {
473     if (sscanf(str, "%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8,
474                &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
475         fatal(0, "invalid mac address %s", str);
476     }
477 }
478
479 static void
480 str_to_ip(const char *str, uint32_t *ip) 
481 {
482     struct in_addr in_addr;
483     int retval;
484
485     retval = lookup_ip(str, &in_addr);
486     if (retval) {
487         fatal(0, "%s: could not convert to IP address", str);
488     }
489     *ip = in_addr.s_addr;
490 }
491
492 static void
493 str_to_action(char *str, struct ofp_action *action, int *n_actions) 
494 {
495     uint16_t port;
496     int i;
497     int max_actions = *n_actions;
498     char *act, *arg;
499     char *saveptr = NULL;
500     
501     memset(action, 0, sizeof(*action) * max_actions);
502     for (i=0, act = strtok_r(str, ", \t\r\n", &saveptr); 
503          i<max_actions && act;
504          i++, act = strtok_r(NULL, ", \t\r\n", &saveptr)) 
505     {
506         port = OFPP_MAX;
507
508         /* Arguments are separated by colons */
509         arg = strchr(act, ':');
510         if (arg) {
511             *arg = '\0';
512             arg++;
513         } 
514
515         if (!strcasecmp(act, "mod_vlan")) {
516             action[i].type = htons(OFPAT_SET_DL_VLAN);
517
518             if (!strcasecmp(arg, "strip")) {
519                 action[i].arg.vlan_id = htons(OFP_VLAN_NONE);
520             } else {
521                 action[i].arg.vlan_id = htons(str_to_int(arg));
522             }
523         } else if (!strcasecmp(act, "output")) {
524             port = str_to_int(arg);
525         } else if (!strcasecmp(act, "TABLE")) {
526             port = OFPP_TABLE;
527         } else if (!strcasecmp(act, "NORMAL")) {
528             port = OFPP_NORMAL;
529         } else if (!strcasecmp(act, "FLOOD")) {
530             port = OFPP_FLOOD;
531         } else if (!strcasecmp(act, "ALL")) {
532             port = OFPP_ALL;
533         } else if (!strcasecmp(act, "CONTROLLER")) {
534             port = OFPP_CONTROLLER;
535             if (arg) {
536                 if (!strcasecmp(arg, "all")) {
537                     action[i].arg.output.max_len= htons(0);
538                 } else {
539                     action[i].arg.output.max_len= htons(str_to_int(arg));
540                 }
541             }
542         } else if (!strcasecmp(act, "LOCAL")) {
543             port = OFPP_LOCAL;
544         } else if (strspn(act, "0123456789") == strlen(act)) {
545             port = str_to_int(act);
546         } else {
547             fatal(0, "Unknown action: %s", act);
548         }
549
550         if (port != OFPP_MAX) {
551             action[i].type = htons(OFPAT_OUTPUT);
552             action[i].arg.output.port = htons(port);
553         }
554     }
555
556     *n_actions = i;
557 }
558
559 static void
560 str_to_flow(char *string, struct ofp_match *match, 
561         struct ofp_action *action, int *n_actions, uint8_t *table_idx, 
562         uint16_t *priority, uint16_t *max_idle)
563 {
564     struct field {
565         const char *name;
566         uint32_t wildcard;
567         enum { F_U8, F_U16, F_MAC, F_IP } type;
568         size_t offset;
569     };
570
571 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
572     static const struct field fields[] = { 
573         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port) },
574         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan) },
575         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src) },
576         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst) },
577         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type) },
578         { "nw_src", OFPFW_NW_SRC, F_IP, F_OFS(nw_src) },
579         { "nw_dst", OFPFW_NW_DST, F_IP, F_OFS(nw_dst) },
580         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto) },
581         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src) },
582         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst) },
583     };
584
585     char *name, *value;
586     uint32_t wildcards;
587     char *act_str;
588
589     if (table_idx) {
590         *table_idx = 0xff;
591     }
592     if (priority) {
593         *priority = OFP_DEFAULT_PRIORITY;
594     }
595     if (max_idle) {
596         *max_idle = DEFAULT_MAX_IDLE;
597     }
598     if (action) {
599         act_str = strstr(string, "action");
600         if (!act_str) {
601             fatal(0, "must specify an action");
602         }
603         *(act_str-1) = '\0';
604
605         act_str = strchr(act_str, '=');
606         if (!act_str) {
607             fatal(0, "must specify an action");
608         }
609
610         act_str++;
611
612         str_to_action(act_str, action, n_actions);
613     }
614     memset(match, 0, sizeof *match);
615     wildcards = OFPFW_ALL;
616     for (name = strtok(string, "="), value = strtok(NULL, ", \t\r\n");
617          name && value;
618          name = strtok(NULL, "="), value = strtok(NULL, ", \t\r\n"))
619     {
620         const struct field *f;
621         void *data;
622
623         if (table_idx && !strcmp(name, "table")) {
624             *table_idx = atoi(value);
625             continue;
626         }
627
628         if (priority && !strcmp(name, "priority")) {
629             *priority = atoi(value);
630             continue;
631         }
632
633         if (max_idle && !strcmp(name, "max_idle")) {
634             *max_idle = atoi(value);
635             continue;
636         }
637
638         for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
639             if (!strcmp(f->name, name)) {
640                 goto found;
641             }
642         }
643         fprintf(stderr, "%s: unknown field %s (fields are",
644                 program_name, name);
645         for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
646             if (f != fields) {
647                 putc(',', stderr);
648             }
649             fprintf(stderr, " %s", f->name);
650         }
651         fprintf(stderr, ")\n");
652         exit(1);
653
654     found:
655         data = (char *) match + f->offset;
656         if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
657             wildcards |= f->wildcard;
658         } else {
659             wildcards &= ~f->wildcard;
660             if (f->type == F_U8) {
661                 *(uint8_t *) data = str_to_int(value);
662             } else if (f->type == F_U16) {
663                 *(uint16_t *) data = htons(str_to_int(value));
664             } else if (f->type == F_MAC) {
665                 str_to_mac(value, data);
666             } else if (f->type == F_IP) {
667                 str_to_ip(value, data);
668             } else {
669                 NOT_REACHED();
670             }
671         }
672     }
673     if (name && !value) {
674         fatal(0, "field %s missing value", name);
675     }
676     match->wildcards = htons(wildcards);
677 }
678
679 static void do_dump_flows(int argc, char *argv[])
680 {
681     struct ofp_flow_stats_request *req;
682     struct buffer *request;
683
684     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
685     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0, 
686             &req->table_id, NULL, NULL);
687     memset(req->pad, 0, sizeof req->pad);
688
689     dump_stats_transaction(argv[1], request);
690 }
691
692 static void do_dump_aggregate(int argc, char *argv[])
693 {
694     struct ofp_aggregate_stats_request *req;
695     struct buffer *request;
696
697     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
698     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0,
699             &req->table_id, NULL, NULL);
700     memset(req->pad, 0, sizeof req->pad);
701
702     dump_stats_transaction(argv[1], request);
703 }
704
705 static void do_add_flow(int argc, char *argv[])
706 {
707     struct vconn *vconn;
708     struct buffer *buffer;
709     struct ofp_flow_mod *ofm;
710     uint16_t priority, max_idle;
711     size_t size;
712     int n_actions = MAX_ADD_ACTS;
713
714     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
715
716     /* Parse and send. */
717     size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
718     ofm = alloc_openflow_buffer(size, OFPT_FLOW_MOD, &buffer);
719     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &n_actions, 
720             NULL, &priority, &max_idle);
721     ofm->command = htons(OFPFC_ADD);
722     ofm->max_idle = htons(max_idle);
723     ofm->buffer_id = htonl(UINT32_MAX);
724     ofm->priority = htons(priority);
725     ofm->reserved = htonl(0);
726
727     /* xxx Should we use the buffer library? */
728     buffer->size -= (MAX_ADD_ACTS - n_actions) * sizeof ofm->actions[0];
729
730     send_openflow_buffer(vconn, buffer);
731     vconn_close(vconn);
732 }
733
734 static void do_add_flows(int argc, char *argv[])
735 {
736     struct vconn *vconn;
737
738     FILE *file;
739     char line[1024];
740
741     file = fopen(argv[2], "r");
742     if (file == NULL) {
743         fatal(errno, "%s: open", argv[2]);
744     }
745
746     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
747     while (fgets(line, sizeof line, file)) {
748         struct buffer *buffer;
749         struct ofp_flow_mod *ofm;
750         uint16_t priority, max_idle;
751         size_t size;
752         int n_actions = MAX_ADD_ACTS;
753
754         char *comment;
755
756         /* Delete comments. */
757         comment = strchr(line, '#');
758         if (comment) {
759             *comment = '\0';
760         }
761
762         /* Drop empty lines. */
763         if (line[strspn(line, " \t\n")] == '\0') {
764             continue;
765         }
766
767         /* Parse and send. */
768         size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
769         ofm = alloc_openflow_buffer(size, OFPT_FLOW_MOD, &buffer);
770         str_to_flow(line, &ofm->match, &ofm->actions[0], &n_actions, 
771                 NULL, &priority, &max_idle);
772         ofm->command = htons(OFPFC_ADD);
773         ofm->max_idle = htons(max_idle);
774         ofm->buffer_id = htonl(UINT32_MAX);
775         ofm->priority = htons(priority);
776         ofm->reserved = htonl(0);
777
778         /* xxx Should we use the buffer library? */
779         buffer->size -= (MAX_ADD_ACTS - n_actions) * sizeof ofm->actions[0];
780
781         send_openflow_buffer(vconn, buffer);
782     }
783     vconn_close(vconn);
784     fclose(file);
785 }
786
787 static void do_del_flows(int argc, char *argv[])
788 {
789     struct vconn *vconn;
790     uint16_t priority;
791
792     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
793     struct buffer *buffer;
794     struct ofp_flow_mod *ofm;
795     size_t size;
796
797
798     /* Parse and send. */
799     size = sizeof *ofm;
800     ofm = alloc_openflow_buffer(size, OFPT_FLOW_MOD, &buffer);
801     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, 0, NULL, 
802             &priority, NULL);
803     ofm->command = htons(OFPFC_DELETE);
804     ofm->max_idle = htons(0);
805     ofm->buffer_id = htonl(UINT32_MAX);
806     ofm->priority = htons(priority);
807     ofm->reserved = htonl(0);
808
809     send_openflow_buffer(vconn, buffer);
810
811     vconn_close(vconn);
812 }
813
814 static void
815 do_dump_ports(int argc, char *argv[])
816 {
817     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
818 }
819
820 static void
821 do_ping(int argc, char *argv[])
822 {
823     size_t max_payload = 65535 - sizeof(struct ofp_header);
824     unsigned int payload;
825     struct vconn *vconn;
826     int i;
827
828     payload = argc > 2 ? atoi(argv[2]) : 64;
829     if (payload > max_payload) {
830         fatal(0, "payload must be between 0 and %zu bytes", max_payload);
831     }
832
833     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
834     for (i = 0; i < 10; i++) {
835         struct timeval start, end;
836         struct buffer *request, *reply;
837         struct ofp_header *rq_hdr, *rpy_hdr;
838
839         rq_hdr = alloc_openflow_buffer(sizeof(struct ofp_header) + payload,
840                                     OFPT_ECHO_REQUEST, &request);
841         random_bytes(rq_hdr + 1, payload);
842
843         gettimeofday(&start, NULL);
844         reply = transact_openflow(vconn, buffer_clone(request));
845         gettimeofday(&end, NULL);
846
847         rpy_hdr = reply->data;
848         if (reply->size != request->size
849             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
850             || rpy_hdr->xid != rq_hdr->xid
851             || rpy_hdr->type != OFPT_ECHO_REPLY) {
852             printf("Reply does not match request.  Request:\n");
853             ofp_print(stdout, request, request->size, 2);
854             printf("Reply:\n");
855             ofp_print(stdout, reply, reply->size, 2);
856         }
857         printf("%d bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
858                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
859                    (1000*(double)(end.tv_sec - start.tv_sec))
860                    + (.001*(end.tv_usec - start.tv_usec)));
861         buffer_delete(request);
862         buffer_delete(reply);
863     }
864     vconn_close(vconn);
865 }
866
867 static void
868 do_benchmark(int argc, char *argv[])
869 {
870     size_t max_payload = 65535 - sizeof(struct ofp_header);
871     struct timeval start, end;
872     unsigned int payload_size, message_size;
873     struct vconn *vconn;
874     double duration;
875     int count;
876     int i;
877
878     payload_size = atoi(argv[2]);
879     if (payload_size > max_payload) {
880         fatal(0, "payload must be between 0 and %zu bytes", max_payload);
881     }
882     message_size = sizeof(struct ofp_header) + payload_size;
883
884     count = atoi(argv[3]);
885
886     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
887            count, message_size, count * message_size);
888
889     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
890     gettimeofday(&start, NULL);
891     for (i = 0; i < count; i++) {
892         struct buffer *request;
893         struct ofp_header *rq_hdr;
894
895         rq_hdr = alloc_openflow_buffer(message_size, OFPT_ECHO_REQUEST,
896                                        &request);
897         memset(rq_hdr + 1, 0, payload_size);
898         buffer_delete(transact_openflow(vconn, request));
899     }
900     gettimeofday(&end, NULL);
901     vconn_close(vconn);
902
903     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
904                 + (.001*(end.tv_usec - start.tv_usec)));
905     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
906            duration, count / (duration / 1000.0),
907            count * message_size / (duration / 1000.0));
908 }
909
910 static void do_help(int argc UNUSED, char *argv[] UNUSED)
911 {
912     usage();
913 }
914
915 static struct command all_commands[] = {
916 #ifdef HAVE_NETLINK
917     { "adddp", 1, 1, do_add_dp },
918     { "deldp", 1, 1, do_del_dp },
919     { "addif", 2, 2, do_add_port },
920     { "delif", 2, 2, do_del_port },
921     { "benchmark-nl", 3, 3, do_benchmark_nl },
922 #endif
923
924     { "show", 1, 1, do_show },
925
926     { "help", 0, INT_MAX, do_help },
927     { "monitor", 1, 1, do_monitor },
928     { "dump-tables", 1, 1, do_dump_tables },
929     { "dump-flows", 1, 2, do_dump_flows },
930     { "dump-aggregate", 1, 2, do_dump_aggregate },
931     { "add-flow", 2, 2, do_add_flow },
932     { "add-flows", 2, 2, do_add_flows },
933     { "del-flows", 1, 2, do_del_flows },
934     { "dump-ports", 1, 1, do_dump_ports },
935     { "ping", 1, 2, do_ping },
936     { "benchmark", 3, 3, do_benchmark },
937     { NULL, 0, 0, NULL },
938 };