1 /* Copyright (c) 2008, 2009, 2010 Nicira Networks, Inc.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 #include <arpa/inet.h>
32 #include "command-line.h"
34 #include "dynamic-string.h"
36 #include "fatal-signal.h"
40 #include "openflow/nicira-ext.h"
41 #include "openflow/openflow.h"
43 #include "poll-loop.h"
47 #include "socket-util.h"
54 #define THIS_MODULE VLM_switchui
57 static void parse_options(int argc, char *argv[]);
58 static void usage(void);
60 static void initialize_terminal(void);
61 static void restore_terminal(void *aux);
72 static void emit(struct message **, enum priority, const char *, ...)
74 static void emit_function(struct message **, enum priority,
75 void (*function)(void *aux), void *aux);
76 static int shown(struct message **);
77 static void clear_messages(void);
78 static bool empty_message(const struct message *);
79 static struct message *best_message(void);
80 static struct message *next_message(struct message *);
81 static struct message *prev_message(struct message *);
82 static void put_message(const struct message *);
83 static void message_shown(struct message *);
84 static void age_messages(void);
96 static void dict_init(struct dict *);
97 static void dict_add(struct dict *, const char *name, const char *value);
98 static void dict_add_nocopy(struct dict *, char *name, char *value);
99 static void dict_delete(struct dict *, const char *name);
100 static void dict_parse(struct dict *, const char *data, size_t nbytes);
101 static void dict_free(struct dict *);
102 static bool dict_lookup(const struct dict *,
103 const char *name, const char **value);
104 static int dict_get_int(const struct dict *, const char *name, int def);
105 static bool dict_get_bool(const struct dict *, const char *name, bool def);
106 static const char *dict_get_string(const struct dict *,
107 const char *name, const char *def);
108 static uint32_t dict_get_ip(const struct dict *, const char *name);
110 static void addf(const char *format, ...) PRINTF_FORMAT(1, 2);
112 static void fetch_status(struct rconn *, struct dict *, long long int timeout);
113 static bool parse_reply(void *, struct dict *, uint32_t xid);
114 static void compose_messages(const struct dict *, struct rconn *rconn);
116 static void show_flows(struct rconn *);
117 static void show_dpid_ip(struct rconn *, const struct dict *);
118 static void show_ofproto_state(const struct dict *);
119 static void show_fail_open_state(const struct dict *);
120 static void show_discovery_state(const struct dict *);
121 static void show_remote_state(const struct dict *);
122 static void show_data_rates(struct rconn *, const struct dict *);
124 static void init_reboot_notifier(void);
125 static bool show_reboot_state(void);
127 static void show_string(const char *string);
128 static void block_until(long long timeout);
129 static void menu(const struct dict *);
130 static void drain_keyboard_buffer(void);
132 static const char *progress(void);
135 main(int argc, char *argv[])
143 /* Tracking keystroke repeat counts. */
145 long long int last_key_time = 0;
146 int repeat_count = 0;
148 proctitle_init(argc, argv);
149 set_program_name(argv[0]);
152 parse_options(argc, argv);
153 signal(SIGPIPE, SIG_IGN);
154 vlog_set_levels(VLM_ANY_MODULE, VLF_CONSOLE, VLL_EMER);
155 init_reboot_notifier();
160 ovs_fatal(0, "exactly one non-option argument required; "
161 "use --help for help");
164 rconn = rconn_create(5, 5);
165 rconn_connect(rconn, argv[0], NULL);
167 die_if_already_running();
170 initialize_terminal();
171 fatal_signal_add_hook(restore_terminal, NULL, NULL, true);
175 user_selected = false;
179 long long timeout = time_msec() + 1000;
184 fetch_status(rconn, &dict, timeout);
185 dict_add(&dict, "debug", debug_mode ? "true" : "false");
186 compose_messages(&dict, rconn);
189 if (!empty_message(msg)) {
192 msg = user_selected ? next_message(msg) : best_message();
196 msg = best_message();
198 user_selected = false;
200 if (!user_selected) {
211 if (c != last_key || time_msec() > last_key_time + 250) {
215 last_key_time = time_msec();
218 if (c == KEY_DOWN || c == KEY_UP) {
219 msg = (c == KEY_DOWN ? next_message(msg)
220 : prev_message(msg));
222 user_selected = true;
223 } else if (c == '\r' || c == '\n') {
225 user_selected = true;
226 if (repeat_count >= 20) {
227 debug_mode = !debug_mode;
228 show_string(debug_mode
229 ? "Debug Mode\nEnabled"
230 : "Debug Mode\nDisabled");
232 } else if (c == '\b' || c == '\x7f' ||
233 c == '\x1b' || c == KEY_BACKSPACE || c == KEY_DC) {
235 drain_keyboard_buffer();
246 poll_fd_wait(STDIN_FILENO, POLLIN);
247 poll_timer_wait_until(timeout);
249 } while (time_msec() < timeout);
258 compose_messages(const struct dict *dict, struct rconn *rconn)
260 if (!show_reboot_state()) {
262 show_dpid_ip(rconn, dict);
263 show_ofproto_state(dict);
264 show_fail_open_state(dict);
265 show_discovery_state(dict);
266 show_remote_state(dict);
267 show_data_rates(rconn, dict);
271 struct put_flows_data {
279 parse_flow_reply(void *data, struct put_flows_data *pfd)
281 struct ofp_header *oh;
282 struct ofp_stats_reply *rpy;
283 struct ofp_aggregate_stats_reply *asr;
284 const size_t min_size = sizeof *rpy + sizeof *asr;
287 if (ntohs(oh->length) < min_size) {
288 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
291 if (oh->xid != pfd->xid) {
292 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
296 if (oh->type != OFPT_STATS_REPLY) {
297 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
302 if (rpy->type != htons(OFPST_AGGREGATE)) {
303 VLOG_WARN("reply has wrong stat type ID %08"PRIx16, rpy->type);
307 asr = (struct ofp_aggregate_stats_reply *) rpy->body;
308 pfd->flow_count = ntohl(asr->flow_count);
309 pfd->got_reply = true;
315 const char *dico = tigetstr("dico");
316 return dico && dico != (const char *) -1;
320 set_icon(int num, int r0, int r1, int r2, int r3, int r4, int r5, int r6,
324 putp(tparm(tigetstr("dico"), num, r0, r1, r2, r3, r4, r5, r6, r7));
329 set_repeated_icon(int num, int row)
331 set_icon(num, row, row, row, row, row, row, row, row);
336 set_brick_icon(int num, int n_solid)
338 const static int rows[6] = {_____, X____, XX___, XXX__, XXXX_, XXXXX};
339 set_repeated_icon(num, rows[n_solid < 0 ? 0
346 icon_char(int num, int alternate)
348 return have_icons() ? 0x80 | num | A_ALTCHARSET : alternate;
352 put_icon(int num, char alternate)
354 addch(icon_char(num, alternate));
359 bar_graph(int n_chars, int n_pixels)
365 } else if (n_pixels > n_chars * 5) {
366 n_pixels = n_chars * 5;
370 set_brick_icon(0, 5);
371 for (i = 0; i < n_pixels / 5; i++) {
376 set_brick_icon(1, n_pixels % 5);
383 put_flows(void *pfd_)
385 struct put_flows_data *pfd = pfd_;
386 static struct rconn_packet_counter *counter;
390 counter = rconn_packet_counter_create();
394 struct ofp_stats_request *rq;
395 struct ofp_aggregate_stats_request *asr;
398 pfd->xid = random_uint32();
399 rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
401 rq->type = htons(OFPST_AGGREGATE);
402 rq->flags = htons(0);
403 asr = ofpbuf_put_uninit(b, sizeof *asr);
404 memset(asr, 0, sizeof *asr);
405 asr->match.wildcards = htonl(OFPFW_ALL);
406 asr->table_id = 0xff;
407 asr->out_port = htons(OFPP_NONE);
408 update_openflow_length(b);
409 rconn_send_with_limit(pfd->rconn, b, counter, 10);
412 if (!pfd->got_reply) {
415 rconn_run(pfd->rconn);
416 for (i = 0; i < 50; i++) {
419 b = rconn_recv(pfd->rconn);
424 parse_flow_reply(b->data, pfd);
426 if (pfd->got_reply) {
432 gethostname(host, sizeof host);
433 host[sizeof host - 1] = '\0';
434 if (strlen(host) + 6 <= 16) {
435 addf("Host: %s\n", host);
439 if (pfd->got_reply) {
440 addf("Flows: %"PRIu32, pfd->flow_count);
443 if (!pfd->got_reply) {
444 rconn_run_wait(pfd->rconn);
445 rconn_recv_wait(pfd->rconn);
450 show_flows(struct rconn *rconn)
452 static struct message *m;
453 static struct put_flows_data pfd;
455 memset(&pfd, 0, sizeof pfd);
457 emit_function(&m, P_STATUS, put_flows, &pfd);
461 struct put_dpid_ip_data {
470 parse_dp_reply(void *data, struct put_dpid_ip_data *pdid)
472 struct ofp_switch_features *osf;
473 struct ofp_header *oh;
476 if (ntohs(oh->length) < sizeof *osf) {
477 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
480 if (oh->xid != pdid->xid) {
481 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
485 if (oh->type != OFPT_FEATURES_REPLY) {
486 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
491 pdid->dpid = ntohll(osf->datapath_id);
492 pdid->got_reply = true;
496 put_dpid_id(void *pdid_)
498 struct put_dpid_ip_data *pdid = pdid_;
499 static struct rconn_packet_counter *counter;
502 counter = rconn_packet_counter_create();
506 struct ofp_header *oh;
509 pdid->xid = random_uint32();
510 oh = make_openflow_xid(sizeof *oh, OFPT_FEATURES_REQUEST,
512 rconn_send_with_limit(pdid->rconn, b, counter, 10);
515 if (!pdid->got_reply) {
518 rconn_run(pdid->rconn);
519 for (i = 0; i < 50; i++) {
522 b = rconn_recv(pdid->rconn);
527 parse_dp_reply(b->data, pdid);
529 if (pdid->got_reply) {
536 if (pdid->got_reply) {
537 addf("%012"PRIx64, pdid->dpid);
539 addf("\nIP: %s", pdid->ip);
541 if (!pdid->got_reply) {
542 rconn_run_wait(pdid->rconn);
543 rconn_recv_wait(pdid->rconn);
548 show_dpid_ip(struct rconn *rconn, const struct dict *dict)
550 static struct message *m;
551 static struct put_dpid_ip_data pdid;
552 const char *is_connected, *local_ip;
554 dict_lookup(dict, "local.is-connected", &is_connected);
555 dict_lookup(dict, "remote.local-ip", &local_ip);
556 if (!is_connected && !local_ip) {
557 /* If we're not connected to the datapath and don't have a local IP,
558 * then we won't have anything useful to show anyhow. */
562 memset(&pdid, 0, sizeof pdid);
564 ovs_strlcpy(pdid.ip, local_ip ? local_ip : "", sizeof pdid.ip);
565 emit_function(&m, P_STATUS, put_dpid_id, &pdid);
569 dict_find(const struct dict *dict, const char *name)
573 for (i = 0; i < dict->n; i++) {
574 const struct pair *p = &dict->pairs[i];
575 if (!strcmp(p->name, name)) {
584 dict_lookup(const struct dict *dict, const char *name, const char **value)
586 size_t idx = dict_find(dict, name);
587 if (idx != SIZE_MAX) {
588 *value = dict->pairs[idx].value;
597 dict_get(const struct dict *dict, const char *name)
600 return dict_lookup(dict, name, &value) ? value : NULL;
604 dict_get_int(const struct dict *dict, const char *name, int def)
607 return dict_lookup(dict, name, &value) ? atoi(value) : def;
611 dict_get_bool(const struct dict *dict, const char *name, bool def)
614 if (dict_lookup(dict, name, &value)) {
615 if (!strcmp(value, "true")) {
618 if (!strcmp(value, "false")) {
626 dict_get_string(const struct dict *dict, const char *name, const char *def)
629 return dict_lookup(dict, name, &value) ? value : def;
633 dict_get_ip(const struct dict *dict, const char *name)
636 return (inet_aton(dict_get_string(dict, name, ""), &in) ? in.s_addr
641 addf(const char *format, ...)
646 va_start(args, format);
647 vsnprintf(buf, sizeof buf, format, args);
654 show_ofproto_state(const struct dict *dict)
656 static struct message *msg;
657 const char *is_connected;
659 if (!dict_lookup(dict, "remote.is-connected", &is_connected)) {
660 /* Secchan not running or not responding. */
661 emit(&msg, P_ERROR, "Switch disabled");
666 discovery_state_label(const char *name)
668 static struct dict *states;
670 states = xmalloc(sizeof *states);
672 dict_add(states, "INIT", "Init");
673 dict_add(states, "INIT_REBOOT", "Init");
674 dict_add(states, "REBOOTING", "Init");
675 dict_add(states, "SELECTING", "Searching");
676 dict_add(states, "REQUESTING", "Requesting");
677 dict_add(states, "BOUND", "Got");
678 dict_add(states, "RENEWING", "Renewing");
679 dict_add(states, "REBINDING", "Rebinding");
680 dict_add(states, "RELEASED", "Released");
682 return dict_get_string(states, name, "Error");
686 show_discovery_state(const struct dict *dict)
688 static struct message *m_bound, *m_other;
690 const char *state, *ip;
691 enum priority priority;
694 state = dict_get_string(dict, "discovery.state", NULL);
698 ip = dict_get_string(dict, "discovery.ip", NULL);
699 state_elapsed = dict_get_int(dict, "discovery.state-elapsed", 0);
701 if (!strcmp(state, "BOUND")) {
706 priority = P_PROGRESS;
708 emit(m, priority, "Discovery %s\n%s",
709 progress(), discovery_state_label(state));
711 emit(m, priority, " %s", ip);
716 human_time(int seconds, char *buf, size_t size)
718 const char *sign = "";
721 seconds = seconds == INT_MIN ? INT_MAX : -seconds;
725 snprintf(buf, size, "%s%d s", sign, seconds);
726 } else if (seconds <= 60 * 60) {
727 snprintf(buf, size, "%s%d min", sign, seconds / 60);
728 } else if (seconds <= 60 * 60 * 24 * 2) {
729 snprintf(buf, size, "%s%d h", sign, seconds / 60 / 60);
731 snprintf(buf, size, "%s%d days", sign, seconds / 60 / 60 / 24);
736 show_fail_open_state(const struct dict *dict)
738 static struct message *m;
739 int cur_duration, trigger_duration;
741 if (!dict_get_bool(dict, "fail-open.triggered", false)) {
744 trigger_duration = dict_get_int(dict, "fail-open.trigger-duration", 0);
745 cur_duration = dict_get_int(dict, "fail-open.current-duration", 0);
747 emit(&m, P_WARNING, "Failed open %s\nafter %d secs",
748 progress(), trigger_duration);
751 human_time(cur_duration - trigger_duration, buf, sizeof buf);
752 emit(&m, P_WARNING, "In fail open for\n%s now %s", buf, progress());
759 return "..." + (3 - (unsigned int) time_now() % 4);
763 show_remote_state(const struct dict *dict)
765 bool debug_mode = dict_get_bool(dict, "debug", false);
766 const char *state, *is_connected;
768 state = dict_get_string(dict, "remote.state", NULL);
772 is_connected = dict_get_string(dict, "remote.is-connected", "false");
773 if (!strcmp(is_connected, "true")) {
775 static struct message *m_connected;
777 human_time(dict_get_int(dict, "remote.last-connection", 0),
779 emit(&m_connected, P_STATUS,
780 "Connected for\nlast %s %s", buf, progress());
783 if (!strcmp(state, "IDLE")) {
784 static struct message *m_idle;
785 emit(&m_idle, P_PROGRESS, "Sent idle probe");
789 const char *name = dict_get_string(dict, "remote.name", NULL);
791 static struct message *m_name;
792 emit(&m_name, P_STATUS, "Connected to\n%s", name);
796 int elapsed, backoff;
797 const char *name, *error;
799 elapsed = dict_get_int(dict, "remote.state-elapsed", 0);
800 backoff = dict_get_int(dict, "remote.backoff", 0);
801 name = dict_get_string(dict, "remote.name", "unknown");
802 state = dict_get_string(dict, "remote.state", "VOID");
803 error = dict_get_string(dict, "remote.last-connect-error", NULL);
804 if (!strcmp(state, "VOID")) {
805 static struct message *m;
806 emit(&m, P_PROGRESS, "Controller not\nfound");
807 } else if (!strcmp(state, "BACKOFF")) {
808 static struct message *m[3];
812 emit(&m[0], P_PROGRESS, "Connect failed:\n%s", error);
814 emit(&m[2], P_STATUS, "Last connected\n%s ago", buf);
815 emit(&m[1], P_PROGRESS,
816 "Disconnected\nReconnect in %d", backoff - elapsed);
817 human_time(dict_get_int(dict, "remote.last-connection", 0),
819 } else if (!strcmp(state, "CONNECTING")) {
820 static struct message *m;
821 emit(&m, P_PROGRESS, "Connecting %s\n%s", progress(), name);
827 fetch_status(struct rconn *rconn, struct dict *dict, long long timeout)
829 static struct rconn_packet_counter *counter;
831 struct nicira_header *rq;
836 counter = rconn_packet_counter_create();
839 xid = random_uint32();
842 rq = make_openflow_xid(sizeof *rq, OFPT_VENDOR, ++xid, &b);
843 rq->vendor = htonl(NX_VENDOR_ID);
844 rq->subtype = htonl(NXT_STATUS_REQUEST);
845 retval = rconn_send_with_limit(rconn, b, counter, 10);
847 /* continue into the loop so that we pause for a while */
850 while (time_msec() < timeout) {
855 for (i = 0; i < 50; i++) {
859 b = rconn_recv(rconn);
864 got_reply = parse_reply(b->data, dict, xid);
871 rconn_run_wait(rconn);
872 rconn_recv_wait(rconn);
873 poll_timer_wait_until(timeout);
879 parse_reply(void *data, struct dict *dict, uint32_t xid)
881 struct ofp_header *oh;
882 struct nicira_header *rpy;
885 if (ntohs(oh->length) < sizeof *rpy) {
886 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
889 if (oh->xid != xid) {
890 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32, oh->xid, xid);
893 if (oh->type != OFPT_VENDOR) {
894 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
899 if (rpy->vendor != htonl(NX_VENDOR_ID)) {
900 VLOG_WARN("reply has wrong vendor ID %08"PRIx32, rpy->vendor);
903 if (rpy->subtype != htonl(NXT_STATUS_REPLY)) {
904 VLOG_WARN("reply has wrong subtype %08"PRIx32, rpy->subtype);
908 dict_parse(dict, (const char *) (rpy + 1),
909 ntohs(oh->length) - sizeof *rpy);
914 dict_parse(struct dict *dict, const char *data, size_t nbytes)
916 char *save_ptr = NULL;
919 copy = xmemdup0(data, nbytes);
920 for (name = strtok_r(copy, "=", &save_ptr); name;
921 name = strtok_r(NULL, "=", &save_ptr))
923 char *value = strtok_r(NULL, "\n", &save_ptr);
927 dict_add(dict, name, value);
933 dict_init(struct dict *dict)
937 dict->pairs = xmalloc(sizeof *dict->pairs * dict->max);
941 dict_add(struct dict *dict, const char *name, const char *value)
943 dict_add_nocopy(dict, xstrdup(name), xstrdup(value));
947 dict_add_nocopy(struct dict *dict, char *name, char *value)
951 if (dict->n >= dict->max) {
953 dict->pairs = xrealloc(dict->pairs, sizeof *dict->pairs * dict->max);
955 p = &dict->pairs[dict->n++];
961 dict_delete(struct dict *dict, const char *name)
964 while ((idx = dict_find(dict, name)) != SIZE_MAX) {
965 struct pair *pair = &dict->pairs[idx];
968 dict->pairs[idx] = dict->pairs[--dict->n];
973 dict_free(struct dict *dict)
978 for (i = 0; i < dict->n; i++) {
979 free(dict->pairs[i].name);
980 free(dict->pairs[i].value);
987 initialize_terminal(void)
993 intrflush(stdscr, FALSE);
994 keypad(stdscr, TRUE);
995 nodelay(stdscr, TRUE);
997 scrollok(stdscr, TRUE);
1001 restore_terminal(void *aux OVS_UNUSED)
1011 struct show_rates_data {
1012 struct rconn *rconn;
1014 struct byte_count prev, now;
1019 parse_port_reply(void *data, struct show_rates_data *rates)
1021 struct ofp_header *oh;
1022 struct ofp_stats_reply *rpy;
1023 struct ofp_port_stats *ops;
1028 if (ntohs(oh->length) < sizeof *rpy) {
1029 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
1032 if (oh->xid != rates->xid) {
1033 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
1034 oh->xid, rates->xid);
1037 if (oh->type != OFPT_STATS_REPLY) {
1038 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
1043 if (rpy->type != htons(OFPST_PORT)) {
1044 VLOG_WARN("reply has wrong stat type ID %08"PRIx16, rpy->type);
1048 n_ports = ((ntohs(oh->length) - offsetof(struct ofp_stats_reply, body))
1050 ops = (struct ofp_port_stats *) rpy->body;
1051 rates->prev = rates->now;
1052 rates->now.when = time_msec();
1053 rates->now.tx_bytes = UINT64_MAX;
1054 for (i = 0; i < n_ports; i++, ops++) {
1055 if (ops->tx_bytes != htonll(UINT64_MAX)) {
1056 if (rates->now.tx_bytes == UINT64_MAX) {
1057 rates->now.tx_bytes = 0;
1059 rates->now.tx_bytes += ntohll(ops->tx_bytes);
1062 rates->got_reply = true;
1066 dump_graph(const bool graph[80])
1068 signed char icons[32];
1072 memset(icons, -1, sizeof icons);
1073 for (i = 0; i < 16; i++) {
1078 for (j = 0; j < 5; j++) {
1079 row = (row << 1) | graph[i * 5 + j];
1086 if (icons[row] < 0) {
1091 set_repeated_icon(n_icons, row);
1092 icons[row] = n_icons++;
1094 put_icon(icons[row], row == 0x1f ? '#' : ' ');
1099 do_show_data_rates(void *rates_)
1101 struct show_rates_data *rates = rates_;
1102 static struct rconn_packet_counter *counter;
1106 counter = rconn_packet_counter_create();
1109 struct ofp_stats_request *rq;
1110 struct ofp_port_stats_request *psr;
1113 rates->xid = random_uint32();
1114 rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
1116 rq->type = htons(OFPST_PORT);
1117 rq->flags = htons(0);
1118 psr = ofpbuf_put_uninit(b, sizeof *psr);
1119 memset(psr, 0, sizeof *psr);
1120 psr->port_no = htons(OFPP_NONE);
1121 update_openflow_length(b);
1122 rconn_send_with_limit(rates->rconn, b, counter, 10);
1125 if (!rates->got_reply) {
1128 rconn_run(rates->rconn);
1129 for (i = 0; i < 50; i++) {
1132 b = rconn_recv(rates->rconn);
1137 parse_port_reply(b->data, rates);
1139 if (rates->got_reply) {
1173 memset(graph, 0, sizeof graph);
1186 if (rates->now.tx_bytes != UINT64_MAX
1187 && rates->prev.tx_bytes != UINT64_MAX
1188 && rates->now.when - rates->prev.when > 500
1189 && time_msec() - rates->now.when < 2000)
1191 uint64_t bits = (rates->now.tx_bytes - rates->prev.tx_bytes) * 8;
1192 uint64_t msecs = rates->now.when - rates->prev.when;
1193 double bps = (double) bits * 1000.0 / msecs;
1194 int pixels = bps > 0 ? log(bps) / log(10.0) * 8 + .5 : 0;
1197 } else if (pixels > 80) {
1200 memset(graph, 1, pixels);
1205 if (!rates->got_reply) {
1206 rconn_run_wait(rates->rconn);
1207 rconn_recv_wait(rates->rconn);
1212 show_data_rates(struct rconn *rconn, const struct dict *dict)
1214 static struct message *m;
1215 static struct show_rates_data rates;
1216 const char *is_connected, *local_ip;
1217 static bool inited = false;
1219 dict_lookup(dict, "local.is-connected", &is_connected);
1220 dict_lookup(dict, "remote.local-ip", &local_ip);
1221 if (!is_connected && !local_ip) {
1222 /* If we're not connected to the datapath and don't have a local IP,
1223 * then we won't have anything useful to show anyhow. */
1227 rates.rconn = rconn;
1229 rates.got_reply = false;
1231 rates.now.tx_bytes = UINT64_MAX;
1232 rates.prev.tx_bytes = UINT64_MAX;
1235 emit_function(&m, P_STATUS, do_show_data_rates, &rates);
1240 void (*function)(void *aux);
1245 enum priority priority;
1250 static struct message **messages;
1251 static size_t n_messages, allocated_messages;
1253 static struct message *
1254 allocate_message(struct message **msgp)
1257 /* Allocate and initialize message. */
1258 *msgp = xzalloc(sizeof **msgp);
1259 (*msgp)->index = n_messages;
1261 /* Add to list of messages. */
1262 if (n_messages >= allocated_messages) {
1263 allocated_messages = 2 * allocated_messages + 1;
1264 messages = xrealloc(messages,
1265 sizeof *messages * allocated_messages);
1267 messages[n_messages++] = *msgp;
1273 emit(struct message **msgp, enum priority priority, const char *format, ...)
1275 struct message *msg = allocate_message(msgp);
1279 msg->priority = priority;
1281 va_start(args, format);
1282 length = strlen(msg->string);
1283 vsnprintf(msg->string + length, sizeof msg->string - length, format, args);
1288 emit_function(struct message **msgp, enum priority priority,
1289 void (*function)(void *aux), void *aux)
1291 struct message *msg = allocate_message(msgp);
1292 msg->priority = priority;
1293 msg->function = function;
1298 shown(struct message **msgp)
1300 struct message *msg = allocate_message(msgp);
1305 clear_messages(void)
1309 for (i = 0; i < n_messages; i++) {
1310 struct message *msg = messages[i];
1311 msg->string[0] = '\0';
1312 msg->function = NULL;
1316 static struct message *
1319 struct message *best_msg;
1323 best_score = INT_MIN;
1325 for (i = 0; i < n_messages; i++) {
1326 struct message *msg = messages[i];
1329 if (empty_message(msg)) {
1333 score = msg->priority;
1337 score -= msg->shown;
1339 if (score > best_score) {
1348 message_shown(struct message *msg)
1350 if (msg && msg->shown++ > 3600) {
1356 empty_message(const struct message *msg)
1358 return !msg || (!msg->string[0] && !msg->function);
1361 static struct message *get_message(size_t index)
1363 assert(index <= n_messages || index == SIZE_MAX);
1364 return (index < n_messages ? messages[index]
1365 : index == SIZE_MAX ? messages[n_messages - 1]
1369 static struct message *
1370 next_message(struct message *msg)
1374 for (p = get_message(msg->index + 1); p != msg;
1375 p = get_message(p->index + 1)) {
1376 if (!empty_message(p)) {
1383 static struct message *
1384 prev_message(struct message *msg)
1388 for (p = get_message(msg->index - 1); p != msg;
1389 p = get_message(p->index - 1)) {
1390 if (!empty_message(p)) {
1398 put_message(const struct message *m)
1402 } else if (m->function) {
1403 m->function(m->aux);
1414 for (i = 0; i < n_messages; i++) {
1415 struct message *msg = messages[i];
1416 if (!empty_message(msg)) {
1421 for (i = 0; i < n_messages; i++) {
1422 struct message *msg = messages[i];
1423 if (empty_message(msg)) {
1424 msg->age = msg->shown = 0;
1426 if (msg->age && msg->age % 60 == 0) {
1427 msg->shown -= MAX(0, 5 - (load + 6) / 12);
1428 if (msg->shown < 0) {
1432 if (msg->age++ > 3600) {
1439 /* Set by SIGUSR1 handler. */
1440 static volatile sig_atomic_t sigusr1_triggered;
1442 /* The time after which we stop indicating that the switch is rebooting.
1443 * (This is just in case the reboot fails.) */
1444 static time_t reboot_deadline = TIME_MIN;
1446 static void sigusr1_handler(int);
1449 init_reboot_notifier(void)
1451 signal(SIGUSR1, sigusr1_handler);
1455 sigusr1_handler(int signr OVS_UNUSED)
1457 sigusr1_triggered = true;
1461 show_reboot_state(void)
1463 if (sigusr1_triggered) {
1464 reboot_deadline = time_now() + 30;
1465 sigusr1_triggered = false;
1467 if (time_now() < reboot_deadline) {
1468 static struct message *msg;
1469 emit(&msg, P_FATAL, "Rebooting");
1477 void (*f)(const struct dict *);
1484 struct menu_item **items;
1485 size_t n_items, allocated_items;
1488 static void menu_init(struct menu *);
1489 static void menu_free(struct menu *);
1490 static struct menu_item *menu_add_item(struct menu *, const char *text, ...)
1491 PRINTF_FORMAT(2, 3);
1492 static int menu_show(const struct menu *, int start, bool select);
1494 static void cmd_shell(const struct dict *);
1495 static void cmd_show_version(const struct dict *);
1496 static void cmd_configure(const struct dict *);
1497 static void cmd_set_up_pki(const struct dict *);
1498 static void cmd_browse_status(const struct dict *);
1499 static void cmd_show_motto(const struct dict *);
1502 menu_init(struct menu *menu)
1504 memset(menu, 0, sizeof *menu);
1508 menu_free(struct menu *menu)
1512 for (i = 0; i < menu->n_items; i++) {
1513 struct menu_item *item = menu->items[i];
1520 static struct menu_item *
1521 menu_add_item(struct menu *menu, const char *text, ...)
1523 struct menu_item *item;
1526 if (menu->n_items >= menu->allocated_items) {
1527 menu->allocated_items = 2 * menu->allocated_items + 1;
1528 menu->items = xrealloc(menu->items,
1529 sizeof *menu->items * menu->allocated_items);
1531 item = menu->items[menu->n_items++] = xmalloc(sizeof *item);
1532 va_start(args, text);
1533 item->text = xvasprintf(text, args);
1537 item->enabled = true;
1543 menu(const struct dict *dict)
1545 bool debug_mode = dict_get_bool(dict, "debug", false);
1550 menu_add_item(&menu, "Exit");
1551 menu_add_item(&menu, "Show Version")->f = cmd_show_version;
1552 menu_add_item(&menu, "Configure")->f = cmd_configure;
1553 menu_add_item(&menu, "Set up PKI")->f = cmd_set_up_pki;
1555 menu_add_item(&menu, "Browse Status")->f = cmd_browse_status;
1556 menu_add_item(&menu, "Shell")->f = cmd_shell;
1557 menu_add_item(&menu, "Show Motto")->f = cmd_show_motto;
1560 choice = menu_show(&menu, 0, true);
1562 void (*f)(const struct dict *) = menu.items[choice]->f;
1572 menu_show(const struct menu *menu, int start, bool select)
1574 long long int adjust = LLONG_MAX;
1575 int min = 0, max = MAX(menu->n_items - 2, 0);
1604 if (menu->n_items) {
1605 pos = MIN(menu->n_items - 1, MAX(0, start));
1614 while ((key = getch()) != ERR) {
1617 if (select && selection > 0) {
1619 if (selection >= pos) {
1629 if (select && selection < menu->n_items - 1) {
1631 if (selection <= pos + 1) {
1640 case '\r': case '\n':
1641 if (select && selection >= 0 && selection < menu->n_items) {
1642 struct menu_item *item = menu->items[selection];
1643 if (!item->enabled) {
1644 show_string("Item disabled");
1646 } else if (item->toggle >= 0) {
1647 item->toggle = !item->toggle;
1653 case '\b': case '\x7f': case '\x1b':
1654 case KEY_BACKSPACE: case KEY_DC:
1657 adjust = time_msec() + 1000;
1659 if (time_msec() >= adjust && menu->n_items > 1) {
1662 } else if (pos > max) {
1670 if (!menu->n_items) {
1674 for (idx = pos; idx < pos + 2; idx++) {
1679 if (selection == idx) {
1688 } else if (idx >= menu->n_items) {
1691 const struct menu_item *item = menu->items[idx];
1692 size_t length = strlen(item->text);
1693 if (!item->enabled) {
1697 if (item->toggle >= 0) {
1699 addch(icon_char(item->toggle ? 2 : 1, 0));
1702 addstr(item->toggle ? "[X]" : "[ ]");
1706 addnstr(item->text, MIN(width, length));
1707 if (!item->enabled) {
1718 if (pos < min || pos > max) {
1719 poll_timer_wait_until(adjust);
1721 poll_fd_wait(STDIN_FILENO, POLLIN);
1727 menu_show2(const struct menu *menu, int start, bool select)
1730 if (menu->n_items) {
1731 pos = MIN(menu->n_items - 1, MAX(0, start));
1756 while ((key = getch()) != ERR) {
1765 if (menu->n_items > 0 && pos < menu->n_items - 1) {
1770 case '\r': case '\n':
1771 if (select && !menu->items[pos]->enabled) {
1772 show_string("Item disabled");
1777 case '\b': case '\x7f': case '\x1b':
1778 case KEY_BACKSPACE: case KEY_DC:
1789 const struct menu_item *item = menu->items[pos];
1790 const char *line1 = item->text;
1791 size_t len1 = strcspn(line1, "\n");
1792 const char *line2 = line1[len1] ? &line1[len1 + 1] : "";
1793 size_t len2 = strcspn(line2, "\n");
1794 size_t width = 39 - 2 * !item->enabled;
1797 addch(pos > 0 ? icon_char(0, '^') : ' ');
1798 if (!item->enabled && len1) {
1801 addnstr(line1, MIN(len1, width));
1802 if (!item->enabled && len1) {
1808 addch(pos < menu->n_items - 1 ? icon_char(1, 'V') : ' ');
1809 if (!item->enabled && len2) {
1812 addnstr(line2, MIN(len2, width));
1813 if (!item->enabled && len2) {
1819 poll_fd_wait(STDIN_FILENO, POLLIN);
1825 yesno(const char *title, bool def)
1842 while ((key = getch()) != ERR) {
1859 case '\r': case '\n':
1870 addch(answer ? icon_char(0, '>') : ' ');
1874 addch(!answer ? icon_char(0, '>') : ' ');
1879 poll_fd_wait(STDIN_FILENO, POLLIN);
1885 cmd_show_version(const struct dict *dict OVS_UNUSED)
1887 show_string(VERSION BUILDNR);
1891 cmd_browse_status(const struct dict *dict)
1897 for (i = 0; i < dict->n; i++) {
1898 const struct pair *p = &dict->pairs[i];
1899 menu_add_item(&menu, "%s = %s", p->name, p->value);
1901 menu_show(&menu, 0, false);
1906 cmd_shell(const struct dict *dict OVS_UNUSED)
1914 printf("Type ^D to exit\n");
1921 home = getenv("HOME");
1926 initialize_terminal();
1930 cmd_show_motto(const struct dict *dict OVS_UNUSED)
1932 show_string("\"Just Add Ice\"");
1936 show_string(const char *string)
1938 VLOG_INFO("%s", string);
1944 block_until(time_msec() + 5000);
1948 block_until(long long timeout)
1950 while (timeout > time_msec()) {
1951 poll_timer_wait_until(timeout);
1954 drain_keyboard_buffer();
1958 drain_keyboard_buffer(void)
1960 while (getch() != ERR) {
1966 read_vars(const char *cmd, struct dict *dict)
1972 stream = popen(cmd, "r");
1974 VLOG_ERR("popen(\"%s\") failed: %s", cmd, strerror(errno));
1980 while (!ds_get_line(&ds, stream)) {
1981 const char *s = ds_cstr(&ds);
1982 const char *equals = strchr(s, '=');
1984 dict_add_nocopy(dict,
1985 xmemdup0(s, equals - s), xstrdup(equals + 1));
1988 status = pclose(stream);
1990 char *msg = process_status_msg(status);
1991 VLOG_ERR("pclose(\"%s\") reported subprocess failure: %s",
2001 run_and_report_failure(char **argv, const char *title)
2003 int null_fds[3] = {0, 1, 2};
2008 s = process_escape_args(argv);
2009 VLOG_INFO("starting subprocess: %s", s);
2012 retval = process_run(argv, NULL, 0, null_fds, 3, &status);
2014 char *s = xasprintf("%s:\n%s", title, strerror(retval));
2018 } else if (status) {
2019 char *msg = process_status_msg(status);
2020 char *s = xasprintf("%s:\n%s", title, msg);
2026 VLOG_INFO("subprocess exited with status 0");
2032 do_load_config(const char *file_name, struct dict *dict)
2034 struct dict auto_vars;
2039 /* Get the list of the variables that the shell sets automatically. */
2040 retval = read_vars("set -a && env", &auto_vars);
2045 /* Get the variables from 'file_name'. */
2046 cmd = xasprintf("set -a && . '%s' && env", file_name);
2047 retval = read_vars(cmd, dict);
2050 dict_free(&auto_vars);
2055 for (i = 0; i < auto_vars.n; i++) {
2056 dict_delete(dict, auto_vars.pairs[i].name);
2058 dict_free(&auto_vars);
2063 load_config(struct dict *dict)
2065 static const char default_file[] = "/etc/default/openflow-switch";
2066 int retval = do_load_config(default_file, dict);
2070 char *s = xasprintf("Cfg load failed:\n%s", strerror(retval));
2078 save_config(const struct svec *settings)
2084 VLOG_INFO("Saving configuration:");
2085 for (i = 0; i < settings->n; i++) {
2086 VLOG_INFO("%s", settings->names[i]);
2090 svec_add(&argv, "/usr/share/openvswitch-switchui/reconfigure");
2091 svec_append(&argv, settings);
2092 svec_terminate(&argv);
2093 ok = run_and_report_failure(argv.names, "Save failed");
2095 long long int timeout = time_msec() + 5000;
2100 addstr("Saved.\nRestarting...");
2104 svec_add(&argv, "/bin/sh");
2105 svec_add(&argv, "-c");
2107 "/etc/init.d/openflow-switch restart >/dev/null 2>&1");
2108 svec_terminate(&argv);
2110 ok = run_and_report_failure(argv.names, "Restart failed");
2112 block_until(timeout);
2115 svec_destroy(&argv);
2118 VLOG_INFO("Save completed successfully");
2120 VLOG_WARN("Save failed");
2126 match(pcre *re, const char *string, int length)
2131 retval = pcre_exec(re, NULL, string, length, 0, PCRE_PARTIAL,
2132 ovec, ARRAY_SIZE(ovec));
2134 if (ovec[0] >= 0 && ovec[1] >= length) {
2135 /* 're' matched all of 'string'. */
2138 /* 're' matched the initial part of 'string' but not all of it. */
2139 return PCRE_ERROR_NOMATCH;
2147 figure_choices(pcre *re, struct ds *s, int pos, struct ds *choices)
2155 /* See whether the current string is a complete match. */
2156 if (!match(re, s->string, pos)) {
2157 ds_put_char(choices, '\n');
2160 /* Then try all the other possibilities. */
2162 ds_put_buffer(&tmp, s->string, pos);
2163 for (c = 0x20; c < 0x7f; c++) {
2164 ds_put_char(&tmp, c);
2165 retval = match(re, tmp.string, pos + 1);
2166 if (retval == PCRE_ERROR_PARTIAL || !retval) {
2167 ds_put_char(choices, c);
2173 if (!choices->length) {
2174 ds_put_char(choices, '\n');
2179 figure_completion(pcre *re, struct ds *s)
2185 /* See whether the current string is a complete match. */
2186 if (!match(re, s->string, s->length)) {
2189 for (c = 0x20; c < 0x7f; c++) {
2193 retval = match(re, s->string, s->length);
2196 if (retval == PCRE_ERROR_PARTIAL || !retval) {
2206 ds_put_char(s, found);
2210 #define OCTET_RE "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
2211 #define IP_RE "("OCTET_RE"\\."OCTET_RE"\\."OCTET_RE"\\."OCTET_RE")"
2215 "[1-9][0-9][0-9]|" \
2216 "[1-9][0-9][0-9][0-9]|" \
2217 "[1-5][0-9][0-9][0-9][0-9]|" \
2218 "6[1-4][0-9][0-9][0-9]|" \
2219 "65[1-4][0-9][0-9]|" \
2222 #define XOCTET_RE "[0-9A-F][0-9A-F]"
2224 XOCTET_RE":"XOCTET_RE":"XOCTET_RE":"\
2225 XOCTET_RE":"XOCTET_RE":"XOCTET_RE
2226 #define NUM100_TO_99999_RE \
2227 "([1-9][0-9][0-9]|" \
2228 "[1-9][0-9][0-9][0-9]|" \
2229 "[1-9][0-9][0-9][0-9][0-9])"
2230 #define NUM5_TO_99999_RE \
2233 "[1-9][0-9][0-9]|" \
2234 "[1-9][0-9][0-9][0-9]|" \
2235 "[1-9][0-9][0-9][0-9][0-9])"
2236 #define NUM1_TO_99999_RE \
2239 "[1-9][0-9][0-9]|" \
2240 "[1-9][0-9][0-9][0-9]|" \
2241 "[1-9][0-9][0-9][0-9][0-9])"
2244 prompt(const char *prompt, const char *initial, const char *pattern)
2266 re = pcre_compile(pattern, PCRE_ANCHORED, &error, &erroffset, NULL);
2268 VLOG_ERR("PCRE error for pattern \"%s\" at offset %d: %s",
2269 pattern, erroffset, error);
2270 return xstrdup(initial);
2273 retval = pcre_fullinfo(re, NULL, PCRE_INFO_OKPARTIAL, &okpartial);
2279 ds_put_cstr(&ds, initial);
2281 figure_choices(re, &ds, pos, &choices);
2282 p = memchr(choices.string, initial[0], choices.length);
2283 chidx = p ? p - choices.string : 0;
2287 while ((key = getch()) != ERR) {
2290 if (choices.length > 1) {
2291 if (++chidx >= choices.length) {
2294 ds.string[pos] = choices.string[chidx];
2295 ds_truncate(&ds, pos + 1);
2296 figure_completion(re, &ds);
2301 if (choices.length > 1) {
2303 chidx = choices.length - 1;
2305 ds.string[pos] = choices.string[chidx];
2306 ds_truncate(&ds, pos + 1);
2307 figure_completion(re, &ds);
2311 case '\r': case '\n':
2312 if (choices.string[chidx] == '\n') {
2313 ds_truncate(&ds, pos);
2314 return ds_cstr(&ds);
2316 if (pos >= ds.length) {
2318 ds_put_char(&ds, choices.string[chidx]);
2319 figure_choices(re, &ds, pos, &choices);
2321 figure_completion(re, &ds);
2324 figure_choices(re, &ds, pos, &choices);
2326 figure_completion(re, &ds);
2332 ds_truncate(&ds, pos + 1);
2333 figure_choices(re, &ds, pos, &choices);
2337 case '\b': case '\x7f': case '\x1b':
2338 case KEY_BACKSPACE: case KEY_DC:
2342 return xstrdup(initial);
2344 figure_choices(re, &ds, pos, &choices);
2346 if (pos < ds.length) {
2347 p = memchr(choices.string, ds.string[pos],
2350 chidx = p - choices.string;
2356 if (key >= 0x20 && key < 0x7f) {
2357 /* Check whether 'key' is valid and toggle case if
2359 if (!memchr(choices.string, key, choices.length)) {
2360 if (memchr(choices.string, toupper(key),
2363 } else if (memchr(choices.string, tolower(key),
2371 /* Insert 'key' and advance the position. */
2372 if (pos >= ds.length) {
2373 ds_put_char(&ds, key);
2375 ds.string[pos] = key;
2379 if (choices.string[chidx] != key) {
2380 ds_truncate(&ds, pos);
2382 figure_choices(re, &ds, pos, &choices);
2384 if (pos < ds.length) {
2385 p = memchr(choices.string, ds.string[pos],
2388 chidx = p - choices.string;
2391 figure_completion(re, &ds);
2399 addnstr(prompt, MIN(40, strlen(prompt)));
2401 c = choices.string[chidx];
2403 addstr(ds_cstr(&ds));
2413 poll_fd_wait(STDIN_FILENO, POLLIN);
2419 prompt_ip(const char *title, uint32_t *ip)
2421 char *in = xasprintf(IP_FMT, IP_ARGS(ip));
2422 char *out = prompt(title, in, "^"IP_RE"$");
2423 *ip = inet_addr(out);
2429 abbreviate_netdevs(const struct svec *netdevs, struct ds *abbrev)
2434 for (i = 0; i < netdevs->n; ) {
2435 size_t i_len = strlen(netdevs->names[i]);
2438 for (j = i + 1; j < netdevs->n; j++) {
2439 size_t j_len = strlen(netdevs->names[j]);
2440 if (!i_len || !j_len || i_len != j_len
2441 || memcmp(netdevs->names[i], netdevs->names[j], i_len - 1)) {
2446 if (abbrev->length) {
2447 ds_put_char(abbrev, ' ');
2450 ds_put_cstr(abbrev, netdevs->names[i]);
2454 ds_put_buffer(abbrev, netdevs->names[i], i_len - 1);
2455 ds_put_char(abbrev, '[');
2456 for (k = i; k < j; k++) {
2457 ds_put_char(abbrev, netdevs->names[k][i_len - 1]);
2459 ds_put_char(abbrev, ']');
2466 choose_netdevs(struct svec *choices)
2468 struct svec netdevs = SVEC_EMPTY_INITIALIZER;
2472 netdev_enumerate(&netdevs);
2473 svec_sort(&netdevs);
2476 menu_add_item(&menu, "Exit");
2477 for (i = 0; i < netdevs.n; i++) {
2478 const char *name = netdevs.names[i];
2479 struct menu_item *item;
2480 struct netdev *netdev;
2483 if (!strncmp(name, "wmaster", strlen("wmaster"))
2484 || !strncmp(name, "of", strlen("of"))
2485 || !strcmp(name, "lo")) {
2489 retval = netdev_open_default(name, &netdev);
2491 bool exclude = netdev_get_in4(netdev, NULL, NULL) == 0;
2492 netdev_close(netdev);
2498 item = menu_add_item(&menu, "%s", name);
2499 item->toggle = svec_contains(choices, name);
2501 if (menu.n_items > 1) {
2502 menu_show(&menu, 0, true);
2504 show_string("No available\nbridge ports");
2507 svec_clear(choices);
2508 for (i = 0; i < menu.n_items; i++) {
2509 struct menu_item *item = menu.items[i];
2510 if (item->toggle > 0) {
2511 svec_add(choices, item->text);
2519 is_datapath_id_in_dmi(void)
2525 dmidecode = popen("dmidecode -s system-uuid", "r");
2529 is_in_dmi = fgets(line, sizeof line, dmidecode) && strstr(line, "-002320");
2534 struct switch_config {
2535 struct svec netdevs;
2536 enum { DISCOVERY, IN_BAND } mode;
2538 uint32_t switch_mask;
2540 enum { FAIL_DROP, FAIL_SWITCH } disconnected;
2543 int inactivity_probe;
2545 char *controller_vconn;
2550 disconnected_string(int value)
2552 #define FAIL_SWITCH_STRING "Switch packets"
2553 #define FAIL_DROP_STRING "Drop packets"
2554 return value == FAIL_SWITCH ? FAIL_SWITCH_STRING : FAIL_DROP_STRING;
2558 cmd_configure(const struct dict *dict OVS_UNUSED)
2560 bool debug_mode = dict_get_bool(dict, "debug", false);
2561 struct dict config_dict;
2562 struct switch_config config;
2565 if (!load_config(&config_dict)) {
2568 svec_init(&config.netdevs);
2569 svec_parse_words(&config.netdevs,
2570 dict_get_string(&config_dict, "NETDEVS", ""));
2571 config.mode = (!strcmp(dict_get_string(&config_dict, "MODE", "discovery"),
2572 "in-band") ? IN_BAND : DISCOVERY);
2573 config.switch_ip = dict_get_ip(&config_dict, "SWITCH_IP");
2574 config.switch_mask = dict_get_ip(&config_dict, "SWITCH_NETMASK");
2575 config.switch_gw = dict_get_ip(&config_dict, "SWITCH_GATEWAY");
2576 config.controller_vconn = xstrdup(dict_get_string(&config_dict,
2578 config.disconnected = (!strcmp(dict_get_string(&config_dict,
2579 "DISCONNECTED_MODE", ""),
2581 ? FAIL_SWITCH : FAIL_DROP);
2582 config.stp = !strcmp(dict_get_string(&config_dict, "stp", ""), "yes");
2583 config.rate_limit = dict_get_int(&config_dict, "RATE_LIMIT", -1);
2584 config.inactivity_probe = dict_get_int(&config_dict, "INACTIVITY_PROBE",
2586 config.max_backoff = dict_get_int(&config_dict, "MAX_BACKOFF", -1);
2587 if (is_datapath_id_in_dmi()) {
2588 config.datapath_id = xstrdup("DMI");
2590 const char *dpid = dict_get(&config_dict, "DATAPATH_ID");
2592 struct ds ds = DS_EMPTY_INITIALIZER;
2594 for (cp = dpid; *cp != '\0'; cp++) {
2596 ds_put_char(&ds, toupper((unsigned char) *cp));
2599 config.datapath_id = ds_cstr(&ds);
2601 config.datapath_id = xstrdup("Random");
2604 dict_free(&config_dict);
2607 while (start != -1) {
2616 MENU_DISCONNECTED_MODE,
2620 MENU_INACTIVITY_PROBE,
2625 struct menu_item *item;
2633 item = menu_add_item(&menu, "Exit");
2634 item->id = MENU_EXIT;
2637 abbreviate_netdevs(&config.netdevs, &ports);
2638 item = menu_add_item(&menu, "Bridge Ports:\n%s", ds_cstr(&ports));
2639 item->id = MENU_NETDEVS;
2643 item = menu_add_item(&menu, "Mode:\n%s",
2644 (config.mode == DISCOVERY
2645 ? "Discovery" : "In-Band"));
2646 item->id = MENU_MODE;
2649 if (config.switch_ip == htonl(0)) {
2650 item = menu_add_item(&menu, "Switch IP Addr:\nDHCP");
2652 item = menu_add_item(&menu, "Switch IP Addr:\n"IP_FMT,
2653 IP_ARGS(&config.switch_ip));
2656 item->enabled = config.mode == IN_BAND;
2659 item = menu_add_item(&menu, "Switch Netmask:\n"IP_FMT,
2660 IP_ARGS(&config.switch_mask));
2661 item->id = MENU_NETMASK;
2662 item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2665 item = menu_add_item(&menu, "Switch Gateway:\n"IP_FMT,
2666 IP_ARGS(&config.switch_gw));
2667 item->id = MENU_GATEWAY;
2668 item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2671 item = menu_add_item(&menu, "Controller:\n%s",
2672 config.controller_vconn);
2673 item->id = MENU_CONTROLLER;
2674 item->enabled = config.mode == IN_BAND;
2676 /* Disconnected mode. */
2677 item = menu_add_item(&menu, "If disconnected:\n%s\n",
2678 disconnected_string(config.disconnected));
2679 item->id = MENU_DISCONNECTED_MODE;
2682 item = menu_add_item(&menu, "Datapath ID:\n%s", config.datapath_id);
2683 item->id = MENU_DATAPATH_ID;
2684 item->enabled = strcmp(config.datapath_id, "DMI");
2686 /* Spanning tree protocol. */
2688 item = menu_add_item(&menu, "802.1D-1998 STP:\n%s",
2689 config.stp ? "Enabled" : "Disabled");
2690 item->id = MENU_STP;
2693 /* Rate-limiting. */
2695 if (config.rate_limit < 0) {
2696 item = menu_add_item(&menu, "Ctlr rate limit:\nDisabled");
2698 item = menu_add_item(&menu, "Ctlr rate limit:\n%d/s",
2701 item->id = MENU_RATE_LIMIT;
2704 /* Inactivity probe. */
2706 if (config.inactivity_probe < 0) {
2707 item = menu_add_item(&menu, "Activity probe:\nDefault");
2709 item = menu_add_item(&menu, "Activity probe:\n%d s",
2710 config.inactivity_probe);
2712 item->id = MENU_INACTIVITY_PROBE;
2717 if (config.max_backoff < 0) {
2718 item = menu_add_item(&menu, "Max backoff:\nDefault");
2720 item = menu_add_item(&menu, "Max backoff:\n%d s",
2721 config.max_backoff);
2723 item->id = MENU_MAX_BACKOFF;
2726 start = menu_show2(&menu, start, true);
2736 choose_netdevs(&config.netdevs);
2740 out = prompt("Mode:",
2741 config.mode == DISCOVERY ? "Discovery" : "In-Band",
2742 "^(Discovery|In-Band)$");
2743 config.mode = !strcmp(out, "Discovery") ? DISCOVERY : IN_BAND;
2748 in = (config.switch_ip == htonl(0) ? xstrdup("DHCP")
2749 : xasprintf(IP_FMT, IP_ARGS(&config.switch_ip)));
2750 out = prompt("Switch IP:", in, "^(DHCP|"IP_RE")$");
2751 ip = strcmp(out, "DHCP") ? inet_addr(out) : htonl(0);
2754 if (ip != config.switch_ip) {
2755 config.switch_ip = ip;
2756 if (ip != htonl(0)) {
2757 uint32_t mask = guess_netmask(ip);
2759 config.switch_mask = mask;
2760 config.switch_gw = (ip & mask) | htonl(1);
2767 prompt_ip("Switch Netmask:", &config.switch_mask);
2771 prompt_ip("Switch Gateway:", &config.switch_gw);
2774 case MENU_CONTROLLER:
2775 out = prompt("Controller:", config.controller_vconn,
2776 "^(tcp|ssl):"IP_RE"(:"PORT_RE")?$");
2777 free(config.controller_vconn);
2778 config.controller_vconn = out;
2781 case MENU_DISCONNECTED_MODE:
2782 out = prompt("If disconnected",
2783 disconnected_string(config.disconnected),
2784 "^("FAIL_DROP_STRING"|"FAIL_SWITCH_STRING")$");
2785 config.disconnected = (!strcmp(out, FAIL_DROP_STRING)
2786 ? FAIL_DROP : FAIL_SWITCH);
2790 case MENU_DATAPATH_ID:
2791 out = prompt("Datapath ID:", config.datapath_id,
2792 "^Random|"MAC_RE"$");
2793 free(config.datapath_id);
2794 config.datapath_id = out;
2798 out = prompt("802.1D-1998 STP:",
2799 config.stp ? "Enabled" : "Disabled",
2800 "^(Enabled|Disabled)$");
2801 config.stp = !strcmp(out, "Enabled");
2805 case MENU_RATE_LIMIT:
2806 in = (config.rate_limit < 0
2807 ? xstrdup("Disabled")
2808 : xasprintf("%d/s", config.rate_limit));
2809 out = prompt("Ctlr rate limit:", in,
2810 "^(Disabled|("NUM100_TO_99999_RE")/s)$");
2813 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2817 case MENU_INACTIVITY_PROBE:
2818 in = (config.inactivity_probe < 0
2819 ? xstrdup("Default")
2820 : xasprintf("%d s", config.inactivity_probe));
2821 out = prompt("Activity probe:", in,
2822 "^(Default|("NUM5_TO_99999_RE") s)$");
2824 config.inactivity_probe
2825 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2829 case MENU_MAX_BACKOFF:
2830 in = (config.max_backoff < 0
2831 ? xstrdup("Default")
2832 : xasprintf("%d s", config.max_backoff));
2833 out = prompt("Max backoff:", in,
2834 "^(Default|("NUM1_TO_99999_RE") s)$");
2837 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2843 if (yesno("Save\nChanges?", false)) {
2848 netdevs = svec_join(&config.netdevs, " ", "");
2849 svec_add_nocopy(&set, xasprintf("NETDEVS=%s", netdevs));
2852 config.mode == IN_BAND ? "MODE=in-band" : "MODE=discovery");
2853 if (config.mode == IN_BAND) {
2854 if (config.switch_ip == htonl(0)) {
2855 svec_add(&set, "SWITCH_IP=dhcp");
2857 svec_add_nocopy(&set, xasprintf("SWITCH_IP="IP_FMT,
2858 IP_ARGS(&config.switch_ip)));
2859 svec_add_nocopy(&set,
2860 xasprintf("SWITCH_NETMASK="IP_FMT,
2861 IP_ARGS(&config.switch_mask)));
2862 svec_add_nocopy(&set, xasprintf("SWITCH_GATEWAY="IP_FMT,
2863 IP_ARGS(&config.switch_gw)));
2864 svec_add_nocopy(&set, xasprintf("CONTROLLER=%s",
2865 config.controller_vconn));
2868 svec_add(&set, (config.disconnected == FAIL_DROP
2869 ? "DISCONNECTED_MODE=drop"
2870 : "DISCONNECTED_MODE=switch"));
2871 svec_add_nocopy(&set, xasprintf("STP=%s", config.stp ? "yes" : "no"));
2872 if (config.rate_limit < 0) {
2873 svec_add(&set, "RATE_LIMIT=");
2875 svec_add_nocopy(&set,
2876 xasprintf("RATE_LIMIT=%d", config.rate_limit));
2878 if (config.inactivity_probe < 0) {
2879 svec_add(&set, "INACTIVITY_PROBE=");
2881 svec_add_nocopy(&set, xasprintf("INACTIVITY_PROBE=%d",
2882 config.inactivity_probe));
2884 if (config.max_backoff < 0) {
2885 svec_add(&set, "MAX_BACKOFF=");
2887 svec_add_nocopy(&set, xasprintf("MAX_BACKOFF=%d",
2888 config.max_backoff));
2894 svec_destroy(&config.netdevs);
2895 free(config.controller_vconn);
2896 free(config.datapath_id);
2900 cmd_set_up_pki(const struct dict *dict OVS_UNUSED)
2902 static const char def_privkey_file[]
2903 = "/etc/openflow-switch/of0-privkey.pem";
2904 static const char def_cert_file[] = "/etc/openflow-switch/of0-cert.pem";
2905 static const char def_cacert_file[] = "/etc/openflow-switch/cacert.pem";
2906 struct dict config_dict;
2907 const char *privkey_file, *cert_file, *cacert_file;
2913 if (!load_config(&config_dict)) {
2916 privkey_file = dict_get_string(&config_dict, "PRIVKEY", def_privkey_file);
2917 cert_file = dict_get_string(&config_dict, "CERT", def_cert_file);
2918 cacert_file = dict_get_string(&config_dict, "CACERT", def_cacert_file);
2919 bootstrap = !strcmp(dict_get_string(&config_dict, "CACERT_MODE", "secure"),
2922 has_keys = !stat(privkey_file, &s) && !stat(cert_file, &s);
2924 ? yesno("Generate\nkeys?", true)
2925 : yesno("Generate\nnew keys?", false)) {
2929 privkey_file = def_privkey_file;
2930 cert_file = def_cert_file;
2933 svec_parse_words(&argv, "sh -c 'cd /etc/openflow-switch "
2934 "&& ovs-pki --force req of0"
2935 "&& ovs-pki --force self-sign of0'");
2936 svec_terminate(&argv);
2937 ok = run_and_report_failure(argv.names, "Key gen failed");
2938 svec_destroy(&argv);
2948 if (stat(cacert_file, &s) && errno == ENOENT) {
2949 bootstrap = yesno("Bootstrap\nCA cert?", bootstrap);
2950 } else if (yesno("Replace\nCA cert?", false)) {
2951 unlink(cacert_file);
2956 svec_add_nocopy(&set, xasprintf("PRIVKEY=%s", privkey_file));
2957 svec_add_nocopy(&set, xasprintf("CERT=%s", cert_file));
2958 svec_add_nocopy(&set, xasprintf("CACERT=%s", cacert_file));
2959 svec_add_nocopy(&set, xasprintf("CACERT_MODE=%s",
2960 bootstrap ? "bootstrap" : "secure"));
2966 parse_options(int argc, char *argv[])
2969 OPT_DUMMY = UCHAR_MAX + 1,
2972 static struct option long_options[] = {
2973 {"verbose", optional_argument, 0, 'v'},
2974 {"help", no_argument, 0, 'h'},
2975 {"version", no_argument, 0, 'V'},
2976 DAEMON_LONG_OPTIONS,
2980 char *short_options = long_options_to_short_options(long_options);
2985 c = getopt_long(argc, argv, short_options, long_options, NULL);
2995 OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
2998 VLOG_OPTION_HANDLERS
2999 DAEMON_OPTION_HANDLERS
3008 free(short_options);
3014 printf("%s: OpenFlow switch monitoring user interface\n"
3015 "usage: %s [OPTIONS] SWITCH\n"
3016 "where SWITCH is an active OpenFlow connection method.\n",
3017 program_name, program_name);
3018 vconn_usage(true, false, false);
3019 printf("\nOptions:\n"
3020 " -v, --verbose=MODULE:FACILITY:LEVEL configure logging levels\n"
3021 " -v, --verbose set maximum verbosity level\n"
3022 " -h, --help display this help message\n"
3023 " -V, --version display version information\n");