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"
39 #include "openflow/nicira-ext.h"
40 #include "openflow/openflow.h"
42 #include "poll-loop.h"
46 #include "socket-util.h"
53 #define THIS_MODULE VLM_switchui
56 static void parse_options(int argc, char *argv[]);
57 static void usage(void);
59 static void initialize_terminal(void);
60 static void restore_terminal(void *aux);
71 static void emit(struct message **, enum priority, const char *, ...)
73 static void emit_function(struct message **, enum priority,
74 void (*function)(void *aux), void *aux);
75 static int shown(struct message **);
76 static void clear_messages(void);
77 static bool empty_message(const struct message *);
78 static struct message *best_message(void);
79 static struct message *next_message(struct message *);
80 static struct message *prev_message(struct message *);
81 static void put_message(const struct message *);
82 static void message_shown(struct message *);
83 static void age_messages(void);
95 static void dict_init(struct dict *);
96 static void dict_add(struct dict *, const char *name, const char *value);
97 static void dict_add_nocopy(struct dict *, char *name, char *value);
98 static void dict_delete(struct dict *, const char *name);
99 static void dict_parse(struct dict *, const char *data, size_t nbytes);
100 static void dict_free(struct dict *);
101 static bool dict_lookup(const struct dict *,
102 const char *name, const char **value);
103 static int dict_get_int(const struct dict *, const char *name, int def);
104 static bool dict_get_bool(const struct dict *, const char *name, bool def);
105 static const char *dict_get_string(const struct dict *,
106 const char *name, const char *def);
107 static uint32_t dict_get_ip(const struct dict *, const char *name);
109 static void addf(const char *format, ...) PRINTF_FORMAT(1, 2);
111 static void fetch_status(struct rconn *, struct dict *, long long int timeout);
112 static bool parse_reply(void *, struct dict *, uint32_t xid);
113 static void compose_messages(const struct dict *, struct rconn *rconn);
115 static void show_flows(struct rconn *);
116 static void show_dpid_ip(struct rconn *, const struct dict *);
117 static void show_ofproto_state(const struct dict *);
118 static void show_fail_open_state(const struct dict *);
119 static void show_discovery_state(const struct dict *);
120 static void show_remote_state(const struct dict *);
121 static void show_data_rates(struct rconn *, const struct dict *);
123 static void init_reboot_notifier(void);
124 static bool show_reboot_state(void);
126 static void show_string(const char *string);
127 static void block_until(long long timeout);
128 static void menu(const struct dict *);
129 static void drain_keyboard_buffer(void);
131 static const char *progress(void);
134 main(int argc, char *argv[])
142 /* Tracking keystroke repeat counts. */
144 long long int last_key_time = 0;
145 int repeat_count = 0;
147 proctitle_init(argc, argv);
148 set_program_name(argv[0]);
151 parse_options(argc, argv);
152 signal(SIGPIPE, SIG_IGN);
153 vlog_set_levels(VLM_ANY_MODULE, VLF_CONSOLE, VLL_EMER);
154 init_reboot_notifier();
159 ovs_fatal(0, "exactly one non-option argument required; "
160 "use --help for help");
163 rconn = rconn_create(5, 5);
164 rconn_connect(rconn, argv[0], NULL);
166 die_if_already_running();
169 initialize_terminal();
170 fatal_signal_add_hook(restore_terminal, NULL, NULL, true);
174 user_selected = false;
178 long long timeout = time_msec() + 1000;
183 fetch_status(rconn, &dict, timeout);
184 dict_add(&dict, "debug", debug_mode ? "true" : "false");
185 compose_messages(&dict, rconn);
188 if (!empty_message(msg)) {
191 msg = user_selected ? next_message(msg) : best_message();
195 msg = best_message();
197 user_selected = false;
199 if (!user_selected) {
210 if (c != last_key || time_msec() > last_key_time + 250) {
214 last_key_time = time_msec();
217 if (c == KEY_DOWN || c == KEY_UP) {
218 msg = (c == KEY_DOWN ? next_message(msg)
219 : prev_message(msg));
221 user_selected = true;
222 } else if (c == '\r' || c == '\n') {
224 user_selected = true;
225 if (repeat_count >= 20) {
226 debug_mode = !debug_mode;
227 show_string(debug_mode
228 ? "Debug Mode\nEnabled"
229 : "Debug Mode\nDisabled");
231 } else if (c == '\b' || c == '\x7f' ||
232 c == '\x1b' || c == KEY_BACKSPACE || c == KEY_DC) {
234 drain_keyboard_buffer();
245 poll_fd_wait(STDIN_FILENO, POLLIN);
246 poll_timer_wait_until(timeout);
248 } while (time_msec() < timeout);
257 compose_messages(const struct dict *dict, struct rconn *rconn)
259 if (!show_reboot_state()) {
261 show_dpid_ip(rconn, dict);
262 show_ofproto_state(dict);
263 show_fail_open_state(dict);
264 show_discovery_state(dict);
265 show_remote_state(dict);
266 show_data_rates(rconn, dict);
270 struct put_flows_data {
278 parse_flow_reply(void *data, struct put_flows_data *pfd)
280 struct ofp_header *oh;
281 struct ofp_stats_reply *rpy;
282 struct ofp_aggregate_stats_reply *asr;
283 const size_t min_size = sizeof *rpy + sizeof *asr;
286 if (ntohs(oh->length) < min_size) {
287 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
290 if (oh->xid != pfd->xid) {
291 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
295 if (oh->type != OFPT_STATS_REPLY) {
296 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
301 if (rpy->type != htons(OFPST_AGGREGATE)) {
302 VLOG_WARN("reply has wrong stat type ID %08"PRIx16, rpy->type);
306 asr = (struct ofp_aggregate_stats_reply *) rpy->body;
307 pfd->flow_count = ntohl(asr->flow_count);
308 pfd->got_reply = true;
314 const char *dico = tigetstr("dico");
315 return dico && dico != (const char *) -1;
319 set_icon(int num, int r0, int r1, int r2, int r3, int r4, int r5, int r6,
323 putp(tparm(tigetstr("dico"), num, r0, r1, r2, r3, r4, r5, r6, r7));
328 set_repeated_icon(int num, int row)
330 set_icon(num, row, row, row, row, row, row, row, row);
335 set_brick_icon(int num, int n_solid)
337 const static int rows[6] = {_____, X____, XX___, XXX__, XXXX_, XXXXX};
338 set_repeated_icon(num, rows[n_solid < 0 ? 0
345 icon_char(int num, int alternate)
347 return have_icons() ? 0x80 | num | A_ALTCHARSET : alternate;
351 put_icon(int num, char alternate)
353 addch(icon_char(num, alternate));
358 bar_graph(int n_chars, int n_pixels)
364 } else if (n_pixels > n_chars * 5) {
365 n_pixels = n_chars * 5;
369 set_brick_icon(0, 5);
370 for (i = 0; i < n_pixels / 5; i++) {
375 set_brick_icon(1, n_pixels % 5);
382 put_flows(void *pfd_)
384 struct put_flows_data *pfd = pfd_;
385 static struct rconn_packet_counter *counter;
389 counter = rconn_packet_counter_create();
393 struct ofp_stats_request *rq;
394 struct ofp_aggregate_stats_request *asr;
397 pfd->xid = random_uint32();
398 rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
400 rq->type = htons(OFPST_AGGREGATE);
401 rq->flags = htons(0);
402 asr = ofpbuf_put_uninit(b, sizeof *asr);
403 memset(asr, 0, sizeof *asr);
404 asr->match.wildcards = htonl(OFPFW_ALL);
405 asr->table_id = 0xff;
406 asr->out_port = htons(OFPP_NONE);
407 update_openflow_length(b);
408 rconn_send_with_limit(pfd->rconn, b, counter, 10);
411 if (!pfd->got_reply) {
414 rconn_run(pfd->rconn);
415 for (i = 0; i < 50; i++) {
418 b = rconn_recv(pfd->rconn);
423 parse_flow_reply(b->data, pfd);
425 if (pfd->got_reply) {
431 gethostname(host, sizeof host);
432 host[sizeof host - 1] = '\0';
433 if (strlen(host) + 6 <= 16) {
434 addf("Host: %s\n", host);
438 if (pfd->got_reply) {
439 addf("Flows: %"PRIu32, pfd->flow_count);
442 if (!pfd->got_reply) {
443 rconn_run_wait(pfd->rconn);
444 rconn_recv_wait(pfd->rconn);
449 show_flows(struct rconn *rconn)
451 static struct message *m;
452 static struct put_flows_data pfd;
454 memset(&pfd, 0, sizeof pfd);
456 emit_function(&m, P_STATUS, put_flows, &pfd);
460 struct put_dpid_ip_data {
469 parse_dp_reply(void *data, struct put_dpid_ip_data *pdid)
471 struct ofp_switch_features *osf;
472 struct ofp_header *oh;
475 if (ntohs(oh->length) < sizeof *osf) {
476 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
479 if (oh->xid != pdid->xid) {
480 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
484 if (oh->type != OFPT_FEATURES_REPLY) {
485 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
490 pdid->dpid = ntohll(osf->datapath_id);
491 pdid->got_reply = true;
495 put_dpid_id(void *pdid_)
497 struct put_dpid_ip_data *pdid = pdid_;
498 static struct rconn_packet_counter *counter;
501 counter = rconn_packet_counter_create();
505 struct ofp_header *oh;
508 pdid->xid = random_uint32();
509 oh = make_openflow_xid(sizeof *oh, OFPT_FEATURES_REQUEST,
511 rconn_send_with_limit(pdid->rconn, b, counter, 10);
514 if (!pdid->got_reply) {
517 rconn_run(pdid->rconn);
518 for (i = 0; i < 50; i++) {
521 b = rconn_recv(pdid->rconn);
526 parse_dp_reply(b->data, pdid);
528 if (pdid->got_reply) {
535 if (pdid->got_reply) {
536 addf("%012"PRIx64, pdid->dpid);
538 addf("\nIP: %s", pdid->ip);
540 if (!pdid->got_reply) {
541 rconn_run_wait(pdid->rconn);
542 rconn_recv_wait(pdid->rconn);
547 show_dpid_ip(struct rconn *rconn, const struct dict *dict)
549 static struct message *m;
550 static struct put_dpid_ip_data pdid;
551 const char *is_connected, *local_ip;
553 dict_lookup(dict, "local.is-connected", &is_connected);
554 dict_lookup(dict, "remote.local-ip", &local_ip);
555 if (!is_connected && !local_ip) {
556 /* If we're not connected to the datapath and don't have a local IP,
557 * then we won't have anything useful to show anyhow. */
561 memset(&pdid, 0, sizeof pdid);
563 ovs_strlcpy(pdid.ip, local_ip ? local_ip : "", sizeof pdid.ip);
564 emit_function(&m, P_STATUS, put_dpid_id, &pdid);
568 dict_find(const struct dict *dict, const char *name)
572 for (i = 0; i < dict->n; i++) {
573 const struct pair *p = &dict->pairs[i];
574 if (!strcmp(p->name, name)) {
583 dict_lookup(const struct dict *dict, const char *name, const char **value)
585 size_t idx = dict_find(dict, name);
586 if (idx != SIZE_MAX) {
587 *value = dict->pairs[idx].value;
596 dict_get(const struct dict *dict, const char *name)
599 return dict_lookup(dict, name, &value) ? value : NULL;
603 dict_get_int(const struct dict *dict, const char *name, int def)
606 return dict_lookup(dict, name, &value) ? atoi(value) : def;
610 dict_get_bool(const struct dict *dict, const char *name, bool def)
613 if (dict_lookup(dict, name, &value)) {
614 if (!strcmp(value, "true")) {
617 if (!strcmp(value, "false")) {
625 dict_get_string(const struct dict *dict, const char *name, const char *def)
628 return dict_lookup(dict, name, &value) ? value : def;
632 dict_get_ip(const struct dict *dict, const char *name)
635 return (inet_aton(dict_get_string(dict, name, ""), &in) ? in.s_addr
640 addf(const char *format, ...)
645 va_start(args, format);
646 vsnprintf(buf, sizeof buf, format, args);
653 show_ofproto_state(const struct dict *dict)
655 static struct message *msg;
656 const char *is_connected;
658 if (!dict_lookup(dict, "remote.is-connected", &is_connected)) {
659 /* Secchan not running or not responding. */
660 emit(&msg, P_ERROR, "Switch disabled");
665 discovery_state_label(const char *name)
667 static struct dict *states;
669 states = xmalloc(sizeof *states);
671 dict_add(states, "INIT", "Init");
672 dict_add(states, "INIT_REBOOT", "Init");
673 dict_add(states, "REBOOTING", "Init");
674 dict_add(states, "SELECTING", "Searching");
675 dict_add(states, "REQUESTING", "Requesting");
676 dict_add(states, "BOUND", "Got");
677 dict_add(states, "RENEWING", "Renewing");
678 dict_add(states, "REBINDING", "Rebinding");
679 dict_add(states, "RELEASED", "Released");
681 return dict_get_string(states, name, "Error");
685 show_discovery_state(const struct dict *dict)
687 static struct message *m_bound, *m_other;
689 const char *state, *ip;
690 enum priority priority;
693 state = dict_get_string(dict, "discovery.state", NULL);
697 ip = dict_get_string(dict, "discovery.ip", NULL);
698 state_elapsed = dict_get_int(dict, "discovery.state-elapsed", 0);
700 if (!strcmp(state, "BOUND")) {
705 priority = P_PROGRESS;
707 emit(m, priority, "Discovery %s\n%s",
708 progress(), discovery_state_label(state));
710 emit(m, priority, " %s", ip);
715 human_time(int seconds, char *buf, size_t size)
717 const char *sign = "";
720 seconds = seconds == INT_MIN ? INT_MAX : -seconds;
724 snprintf(buf, size, "%s%d s", sign, seconds);
725 } else if (seconds <= 60 * 60) {
726 snprintf(buf, size, "%s%d min", sign, seconds / 60);
727 } else if (seconds <= 60 * 60 * 24 * 2) {
728 snprintf(buf, size, "%s%d h", sign, seconds / 60 / 60);
730 snprintf(buf, size, "%s%d days", sign, seconds / 60 / 60 / 24);
735 show_fail_open_state(const struct dict *dict)
737 static struct message *m;
738 int cur_duration, trigger_duration;
740 if (!dict_get_bool(dict, "fail-open.triggered", false)) {
743 trigger_duration = dict_get_int(dict, "fail-open.trigger-duration", 0);
744 cur_duration = dict_get_int(dict, "fail-open.current-duration", 0);
746 emit(&m, P_WARNING, "Failed open %s\nafter %d secs",
747 progress(), trigger_duration);
750 human_time(cur_duration - trigger_duration, buf, sizeof buf);
751 emit(&m, P_WARNING, "In fail open for\n%s now %s", buf, progress());
758 return "..." + (3 - (unsigned int) time_now() % 4);
762 show_remote_state(const struct dict *dict)
764 bool debug_mode = dict_get_bool(dict, "debug", false);
765 const char *state, *is_connected;
767 state = dict_get_string(dict, "remote.state", NULL);
771 is_connected = dict_get_string(dict, "remote.is-connected", "false");
772 if (!strcmp(is_connected, "true")) {
774 static struct message *m_connected;
776 human_time(dict_get_int(dict, "remote.last-connection", 0),
778 emit(&m_connected, P_STATUS,
779 "Connected for\nlast %s %s", buf, progress());
782 if (!strcmp(state, "IDLE")) {
783 static struct message *m_idle;
784 emit(&m_idle, P_PROGRESS, "Sent idle probe");
788 const char *name = dict_get_string(dict, "remote.name", NULL);
790 static struct message *m_name;
791 emit(&m_name, P_STATUS, "Connected to\n%s", name);
795 int elapsed, backoff;
796 const char *name, *error;
798 elapsed = dict_get_int(dict, "remote.state-elapsed", 0);
799 backoff = dict_get_int(dict, "remote.backoff", 0);
800 name = dict_get_string(dict, "remote.name", "unknown");
801 state = dict_get_string(dict, "remote.state", "VOID");
802 error = dict_get_string(dict, "remote.last-connect-error", NULL);
803 if (!strcmp(state, "VOID")) {
804 static struct message *m;
805 emit(&m, P_PROGRESS, "Controller not\nfound");
806 } else if (!strcmp(state, "BACKOFF")) {
807 static struct message *m[3];
811 emit(&m[0], P_PROGRESS, "Connect failed:\n%s", error);
813 emit(&m[2], P_STATUS, "Last connected\n%s ago", buf);
814 emit(&m[1], P_PROGRESS,
815 "Disconnected\nReconnect in %d", backoff - elapsed);
816 human_time(dict_get_int(dict, "remote.last-connection", 0),
818 } else if (!strcmp(state, "CONNECTING")) {
819 static struct message *m;
820 emit(&m, P_PROGRESS, "Connecting %s\n%s", progress(), name);
826 fetch_status(struct rconn *rconn, struct dict *dict, long long timeout)
828 static struct rconn_packet_counter *counter;
830 struct nicira_header *rq;
835 counter = rconn_packet_counter_create();
838 xid = random_uint32();
841 rq = make_openflow_xid(sizeof *rq, OFPT_VENDOR, ++xid, &b);
842 rq->vendor = htonl(NX_VENDOR_ID);
843 rq->subtype = htonl(NXT_STATUS_REQUEST);
844 retval = rconn_send_with_limit(rconn, b, counter, 10);
846 /* continue into the loop so that we pause for a while */
849 while (time_msec() < timeout) {
854 for (i = 0; i < 50; i++) {
858 b = rconn_recv(rconn);
863 got_reply = parse_reply(b->data, dict, xid);
870 rconn_run_wait(rconn);
871 rconn_recv_wait(rconn);
872 poll_timer_wait_until(timeout);
878 parse_reply(void *data, struct dict *dict, uint32_t xid)
880 struct ofp_header *oh;
881 struct nicira_header *rpy;
884 if (ntohs(oh->length) < sizeof *rpy) {
885 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
888 if (oh->xid != xid) {
889 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32, oh->xid, xid);
892 if (oh->type != OFPT_VENDOR) {
893 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
898 if (rpy->vendor != htonl(NX_VENDOR_ID)) {
899 VLOG_WARN("reply has wrong vendor ID %08"PRIx32, rpy->vendor);
902 if (rpy->subtype != htonl(NXT_STATUS_REPLY)) {
903 VLOG_WARN("reply has wrong subtype %08"PRIx32, rpy->subtype);
907 dict_parse(dict, (const char *) (rpy + 1),
908 ntohs(oh->length) - sizeof *rpy);
913 dict_parse(struct dict *dict, const char *data, size_t nbytes)
915 char *save_ptr = NULL;
918 copy = xmemdup0(data, nbytes);
919 for (name = strtok_r(copy, "=", &save_ptr); name;
920 name = strtok_r(NULL, "=", &save_ptr))
922 char *value = strtok_r(NULL, "\n", &save_ptr);
926 dict_add(dict, name, value);
932 dict_init(struct dict *dict)
936 dict->pairs = xmalloc(sizeof *dict->pairs * dict->max);
940 dict_add(struct dict *dict, const char *name, const char *value)
942 dict_add_nocopy(dict, xstrdup(name), xstrdup(value));
946 dict_add_nocopy(struct dict *dict, char *name, char *value)
950 if (dict->n >= dict->max) {
952 dict->pairs = xrealloc(dict->pairs, sizeof *dict->pairs * dict->max);
954 p = &dict->pairs[dict->n++];
960 dict_delete(struct dict *dict, const char *name)
963 while ((idx = dict_find(dict, name)) != SIZE_MAX) {
964 struct pair *pair = &dict->pairs[idx];
967 dict->pairs[idx] = dict->pairs[--dict->n];
972 dict_free(struct dict *dict)
977 for (i = 0; i < dict->n; i++) {
978 free(dict->pairs[i].name);
979 free(dict->pairs[i].value);
986 initialize_terminal(void)
992 intrflush(stdscr, FALSE);
993 keypad(stdscr, TRUE);
994 nodelay(stdscr, TRUE);
996 scrollok(stdscr, TRUE);
1000 restore_terminal(void *aux OVS_UNUSED)
1010 struct show_rates_data {
1011 struct rconn *rconn;
1013 struct byte_count prev, now;
1018 parse_port_reply(void *data, struct show_rates_data *rates)
1020 struct ofp_header *oh;
1021 struct ofp_stats_reply *rpy;
1022 struct ofp_port_stats *ops;
1027 if (ntohs(oh->length) < sizeof *rpy) {
1028 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
1031 if (oh->xid != rates->xid) {
1032 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
1033 oh->xid, rates->xid);
1036 if (oh->type != OFPT_STATS_REPLY) {
1037 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
1042 if (rpy->type != htons(OFPST_PORT)) {
1043 VLOG_WARN("reply has wrong stat type ID %08"PRIx16, rpy->type);
1047 n_ports = ((ntohs(oh->length) - offsetof(struct ofp_stats_reply, body))
1049 ops = (struct ofp_port_stats *) rpy->body;
1050 rates->prev = rates->now;
1051 rates->now.when = time_msec();
1052 rates->now.tx_bytes = UINT64_MAX;
1053 for (i = 0; i < n_ports; i++, ops++) {
1054 if (ops->tx_bytes != htonll(UINT64_MAX)) {
1055 if (rates->now.tx_bytes == UINT64_MAX) {
1056 rates->now.tx_bytes = 0;
1058 rates->now.tx_bytes += ntohll(ops->tx_bytes);
1061 rates->got_reply = true;
1065 dump_graph(const bool graph[80])
1067 signed char icons[32];
1071 memset(icons, -1, sizeof icons);
1072 for (i = 0; i < 16; i++) {
1077 for (j = 0; j < 5; j++) {
1078 row = (row << 1) | graph[i * 5 + j];
1085 if (icons[row] < 0) {
1090 set_repeated_icon(n_icons, row);
1091 icons[row] = n_icons++;
1093 put_icon(icons[row], row == 0x1f ? '#' : ' ');
1098 do_show_data_rates(void *rates_)
1100 struct show_rates_data *rates = rates_;
1101 static struct rconn_packet_counter *counter;
1105 counter = rconn_packet_counter_create();
1108 struct ofp_stats_request *rq;
1109 struct ofp_port_stats_request *psr;
1112 rates->xid = random_uint32();
1113 rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
1115 rq->type = htons(OFPST_PORT);
1116 rq->flags = htons(0);
1117 psr = ofpbuf_put_uninit(b, sizeof *psr);
1118 memset(psr, 0, sizeof *psr);
1119 psr->port_no = htons(OFPP_NONE);
1120 update_openflow_length(b);
1121 rconn_send_with_limit(rates->rconn, b, counter, 10);
1124 if (!rates->got_reply) {
1127 rconn_run(rates->rconn);
1128 for (i = 0; i < 50; i++) {
1131 b = rconn_recv(rates->rconn);
1136 parse_port_reply(b->data, rates);
1138 if (rates->got_reply) {
1172 memset(graph, 0, sizeof graph);
1185 if (rates->now.tx_bytes != UINT64_MAX
1186 && rates->prev.tx_bytes != UINT64_MAX
1187 && rates->now.when - rates->prev.when > 500
1188 && time_msec() - rates->now.when < 2000)
1190 uint64_t bits = (rates->now.tx_bytes - rates->prev.tx_bytes) * 8;
1191 uint64_t msecs = rates->now.when - rates->prev.when;
1192 double bps = (double) bits * 1000.0 / msecs;
1193 int pixels = bps > 0 ? log(bps) / log(10.0) * 8 + .5 : 0;
1196 } else if (pixels > 80) {
1199 memset(graph, 1, pixels);
1204 if (!rates->got_reply) {
1205 rconn_run_wait(rates->rconn);
1206 rconn_recv_wait(rates->rconn);
1211 show_data_rates(struct rconn *rconn, const struct dict *dict)
1213 static struct message *m;
1214 static struct show_rates_data rates;
1215 const char *is_connected, *local_ip;
1216 static bool inited = false;
1218 dict_lookup(dict, "local.is-connected", &is_connected);
1219 dict_lookup(dict, "remote.local-ip", &local_ip);
1220 if (!is_connected && !local_ip) {
1221 /* If we're not connected to the datapath and don't have a local IP,
1222 * then we won't have anything useful to show anyhow. */
1226 rates.rconn = rconn;
1228 rates.got_reply = false;
1230 rates.now.tx_bytes = UINT64_MAX;
1231 rates.prev.tx_bytes = UINT64_MAX;
1234 emit_function(&m, P_STATUS, do_show_data_rates, &rates);
1239 void (*function)(void *aux);
1244 enum priority priority;
1249 static struct message **messages;
1250 static size_t n_messages, allocated_messages;
1252 static struct message *
1253 allocate_message(struct message **msgp)
1256 /* Allocate and initialize message. */
1257 *msgp = xzalloc(sizeof **msgp);
1258 (*msgp)->index = n_messages;
1260 /* Add to list of messages. */
1261 if (n_messages >= allocated_messages) {
1262 allocated_messages = 2 * allocated_messages + 1;
1263 messages = xrealloc(messages,
1264 sizeof *messages * allocated_messages);
1266 messages[n_messages++] = *msgp;
1272 emit(struct message **msgp, enum priority priority, const char *format, ...)
1274 struct message *msg = allocate_message(msgp);
1278 msg->priority = priority;
1280 va_start(args, format);
1281 length = strlen(msg->string);
1282 vsnprintf(msg->string + length, sizeof msg->string - length, format, args);
1287 emit_function(struct message **msgp, enum priority priority,
1288 void (*function)(void *aux), void *aux)
1290 struct message *msg = allocate_message(msgp);
1291 msg->priority = priority;
1292 msg->function = function;
1297 shown(struct message **msgp)
1299 struct message *msg = allocate_message(msgp);
1304 clear_messages(void)
1308 for (i = 0; i < n_messages; i++) {
1309 struct message *msg = messages[i];
1310 msg->string[0] = '\0';
1311 msg->function = NULL;
1315 static struct message *
1318 struct message *best_msg;
1322 best_score = INT_MIN;
1324 for (i = 0; i < n_messages; i++) {
1325 struct message *msg = messages[i];
1328 if (empty_message(msg)) {
1332 score = msg->priority;
1336 score -= msg->shown;
1338 if (score > best_score) {
1347 message_shown(struct message *msg)
1349 if (msg && msg->shown++ > 3600) {
1355 empty_message(const struct message *msg)
1357 return !msg || (!msg->string[0] && !msg->function);
1360 static struct message *get_message(size_t index)
1362 assert(index <= n_messages || index == SIZE_MAX);
1363 return (index < n_messages ? messages[index]
1364 : index == SIZE_MAX ? messages[n_messages - 1]
1368 static struct message *
1369 next_message(struct message *msg)
1373 for (p = get_message(msg->index + 1); p != msg;
1374 p = get_message(p->index + 1)) {
1375 if (!empty_message(p)) {
1382 static struct message *
1383 prev_message(struct message *msg)
1387 for (p = get_message(msg->index - 1); p != msg;
1388 p = get_message(p->index - 1)) {
1389 if (!empty_message(p)) {
1397 put_message(const struct message *m)
1401 } else if (m->function) {
1402 m->function(m->aux);
1413 for (i = 0; i < n_messages; i++) {
1414 struct message *msg = messages[i];
1415 if (!empty_message(msg)) {
1420 for (i = 0; i < n_messages; i++) {
1421 struct message *msg = messages[i];
1422 if (empty_message(msg)) {
1423 msg->age = msg->shown = 0;
1425 if (msg->age && msg->age % 60 == 0) {
1426 msg->shown -= MAX(0, 5 - (load + 6) / 12);
1427 if (msg->shown < 0) {
1431 if (msg->age++ > 3600) {
1438 /* Set by SIGUSR1 handler. */
1439 static volatile sig_atomic_t sigusr1_triggered;
1441 /* The time after which we stop indicating that the switch is rebooting.
1442 * (This is just in case the reboot fails.) */
1443 static time_t reboot_deadline = TIME_MIN;
1445 static void sigusr1_handler(int);
1448 init_reboot_notifier(void)
1450 signal(SIGUSR1, sigusr1_handler);
1454 sigusr1_handler(int signr OVS_UNUSED)
1456 sigusr1_triggered = true;
1460 show_reboot_state(void)
1462 if (sigusr1_triggered) {
1463 reboot_deadline = time_now() + 30;
1464 sigusr1_triggered = false;
1466 if (time_now() < reboot_deadline) {
1467 static struct message *msg;
1468 emit(&msg, P_FATAL, "Rebooting");
1476 void (*f)(const struct dict *);
1483 struct menu_item **items;
1484 size_t n_items, allocated_items;
1487 static void menu_init(struct menu *);
1488 static void menu_free(struct menu *);
1489 static struct menu_item *menu_add_item(struct menu *, const char *text, ...)
1490 PRINTF_FORMAT(2, 3);
1491 static int menu_show(const struct menu *, int start, bool select);
1493 static void cmd_shell(const struct dict *);
1494 static void cmd_show_version(const struct dict *);
1495 static void cmd_configure(const struct dict *);
1496 static void cmd_set_up_pki(const struct dict *);
1497 static void cmd_browse_status(const struct dict *);
1498 static void cmd_show_motto(const struct dict *);
1501 menu_init(struct menu *menu)
1503 memset(menu, 0, sizeof *menu);
1507 menu_free(struct menu *menu)
1511 for (i = 0; i < menu->n_items; i++) {
1512 struct menu_item *item = menu->items[i];
1519 static struct menu_item *
1520 menu_add_item(struct menu *menu, const char *text, ...)
1522 struct menu_item *item;
1525 if (menu->n_items >= menu->allocated_items) {
1526 menu->allocated_items = 2 * menu->allocated_items + 1;
1527 menu->items = xrealloc(menu->items,
1528 sizeof *menu->items * menu->allocated_items);
1530 item = menu->items[menu->n_items++] = xmalloc(sizeof *item);
1531 va_start(args, text);
1532 item->text = xvasprintf(text, args);
1536 item->enabled = true;
1542 menu(const struct dict *dict)
1544 bool debug_mode = dict_get_bool(dict, "debug", false);
1549 menu_add_item(&menu, "Exit");
1550 menu_add_item(&menu, "Show Version")->f = cmd_show_version;
1551 menu_add_item(&menu, "Configure")->f = cmd_configure;
1552 menu_add_item(&menu, "Set up PKI")->f = cmd_set_up_pki;
1554 menu_add_item(&menu, "Browse Status")->f = cmd_browse_status;
1555 menu_add_item(&menu, "Shell")->f = cmd_shell;
1556 menu_add_item(&menu, "Show Motto")->f = cmd_show_motto;
1559 choice = menu_show(&menu, 0, true);
1561 void (*f)(const struct dict *) = menu.items[choice]->f;
1571 menu_show(const struct menu *menu, int start, bool select)
1573 long long int adjust = LLONG_MAX;
1574 int min = 0, max = MAX(menu->n_items - 2, 0);
1603 if (menu->n_items) {
1604 pos = MIN(menu->n_items - 1, MAX(0, start));
1613 while ((key = getch()) != ERR) {
1616 if (select && selection > 0) {
1618 if (selection >= pos) {
1628 if (select && selection < menu->n_items - 1) {
1630 if (selection <= pos + 1) {
1639 case '\r': case '\n':
1640 if (select && selection >= 0 && selection < menu->n_items) {
1641 struct menu_item *item = menu->items[selection];
1642 if (!item->enabled) {
1643 show_string("Item disabled");
1645 } else if (item->toggle >= 0) {
1646 item->toggle = !item->toggle;
1652 case '\b': case '\x7f': case '\x1b':
1653 case KEY_BACKSPACE: case KEY_DC:
1656 adjust = time_msec() + 1000;
1658 if (time_msec() >= adjust && menu->n_items > 1) {
1661 } else if (pos > max) {
1669 if (!menu->n_items) {
1673 for (idx = pos; idx < pos + 2; idx++) {
1678 if (selection == idx) {
1687 } else if (idx >= menu->n_items) {
1690 const struct menu_item *item = menu->items[idx];
1691 size_t length = strlen(item->text);
1692 if (!item->enabled) {
1696 if (item->toggle >= 0) {
1698 addch(icon_char(item->toggle ? 2 : 1, 0));
1701 addstr(item->toggle ? "[X]" : "[ ]");
1705 addnstr(item->text, MIN(width, length));
1706 if (!item->enabled) {
1717 if (pos < min || pos > max) {
1718 poll_timer_wait_until(adjust);
1720 poll_fd_wait(STDIN_FILENO, POLLIN);
1726 menu_show2(const struct menu *menu, int start, bool select)
1729 if (menu->n_items) {
1730 pos = MIN(menu->n_items - 1, MAX(0, start));
1755 while ((key = getch()) != ERR) {
1764 if (menu->n_items > 0 && pos < menu->n_items - 1) {
1769 case '\r': case '\n':
1770 if (select && !menu->items[pos]->enabled) {
1771 show_string("Item disabled");
1776 case '\b': case '\x7f': case '\x1b':
1777 case KEY_BACKSPACE: case KEY_DC:
1788 const struct menu_item *item = menu->items[pos];
1789 const char *line1 = item->text;
1790 size_t len1 = strcspn(line1, "\n");
1791 const char *line2 = line1[len1] ? &line1[len1 + 1] : "";
1792 size_t len2 = strcspn(line2, "\n");
1793 size_t width = 39 - 2 * !item->enabled;
1796 addch(pos > 0 ? icon_char(0, '^') : ' ');
1797 if (!item->enabled && len1) {
1800 addnstr(line1, MIN(len1, width));
1801 if (!item->enabled && len1) {
1807 addch(pos < menu->n_items - 1 ? icon_char(1, 'V') : ' ');
1808 if (!item->enabled && len2) {
1811 addnstr(line2, MIN(len2, width));
1812 if (!item->enabled && len2) {
1818 poll_fd_wait(STDIN_FILENO, POLLIN);
1824 yesno(const char *title, bool def)
1841 while ((key = getch()) != ERR) {
1858 case '\r': case '\n':
1869 addch(answer ? icon_char(0, '>') : ' ');
1873 addch(!answer ? icon_char(0, '>') : ' ');
1878 poll_fd_wait(STDIN_FILENO, POLLIN);
1884 cmd_show_version(const struct dict *dict OVS_UNUSED)
1886 show_string(VERSION BUILDNR);
1890 cmd_browse_status(const struct dict *dict)
1896 for (i = 0; i < dict->n; i++) {
1897 const struct pair *p = &dict->pairs[i];
1898 menu_add_item(&menu, "%s = %s", p->name, p->value);
1900 menu_show(&menu, 0, false);
1905 cmd_shell(const struct dict *dict OVS_UNUSED)
1913 printf("Type ^D to exit\n");
1920 home = getenv("HOME");
1925 initialize_terminal();
1929 cmd_show_motto(const struct dict *dict OVS_UNUSED)
1931 show_string("\"Just Add Ice\"");
1935 show_string(const char *string)
1937 VLOG_INFO("%s", string);
1943 block_until(time_msec() + 5000);
1947 block_until(long long timeout)
1949 while (timeout > time_msec()) {
1950 poll_timer_wait_until(timeout);
1953 drain_keyboard_buffer();
1957 drain_keyboard_buffer(void)
1959 while (getch() != ERR) {
1965 read_vars(const char *cmd, struct dict *dict)
1971 stream = popen(cmd, "r");
1973 VLOG_ERR("popen(\"%s\") failed: %s", cmd, strerror(errno));
1979 while (!ds_get_line(&ds, stream)) {
1980 const char *s = ds_cstr(&ds);
1981 const char *equals = strchr(s, '=');
1983 dict_add_nocopy(dict,
1984 xmemdup0(s, equals - s), xstrdup(equals + 1));
1987 status = pclose(stream);
1989 char *msg = process_status_msg(status);
1990 VLOG_ERR("pclose(\"%s\") reported subprocess failure: %s",
2000 run_and_report_failure(char **argv, const char *title)
2002 int null_fds[3] = {0, 1, 2};
2007 s = process_escape_args(argv);
2008 VLOG_INFO("starting subprocess: %s", s);
2011 retval = process_run(argv, NULL, 0, null_fds, 3, &status);
2013 char *s = xasprintf("%s:\n%s", title, strerror(retval));
2017 } else if (status) {
2018 char *msg = process_status_msg(status);
2019 char *s = xasprintf("%s:\n%s", title, msg);
2025 VLOG_INFO("subprocess exited with status 0");
2031 do_load_config(const char *file_name, struct dict *dict)
2033 struct dict auto_vars;
2038 /* Get the list of the variables that the shell sets automatically. */
2039 retval = read_vars("set -a && env", &auto_vars);
2044 /* Get the variables from 'file_name'. */
2045 cmd = xasprintf("set -a && . '%s' && env", file_name);
2046 retval = read_vars(cmd, dict);
2049 dict_free(&auto_vars);
2054 for (i = 0; i < auto_vars.n; i++) {
2055 dict_delete(dict, auto_vars.pairs[i].name);
2057 dict_free(&auto_vars);
2062 load_config(struct dict *dict)
2064 static const char default_file[] = "/etc/default/openflow-switch";
2065 int retval = do_load_config(default_file, dict);
2069 char *s = xasprintf("Cfg load failed:\n%s", strerror(retval));
2077 save_config(const struct svec *settings)
2083 VLOG_INFO("Saving configuration:");
2084 for (i = 0; i < settings->n; i++) {
2085 VLOG_INFO("%s", settings->names[i]);
2089 svec_add(&argv, "/usr/share/openvswitch-switchui/reconfigure");
2090 svec_append(&argv, settings);
2091 svec_terminate(&argv);
2092 ok = run_and_report_failure(argv.names, "Save failed");
2094 long long int timeout = time_msec() + 5000;
2099 addstr("Saved.\nRestarting...");
2103 svec_add(&argv, "/bin/sh");
2104 svec_add(&argv, "-c");
2106 "/etc/init.d/openflow-switch restart >/dev/null 2>&1");
2107 svec_terminate(&argv);
2109 ok = run_and_report_failure(argv.names, "Restart failed");
2111 block_until(timeout);
2114 svec_destroy(&argv);
2117 VLOG_INFO("Save completed successfully");
2119 VLOG_WARN("Save failed");
2125 match(pcre *re, const char *string, int length)
2130 retval = pcre_exec(re, NULL, string, length, 0, PCRE_PARTIAL,
2131 ovec, ARRAY_SIZE(ovec));
2133 if (ovec[0] >= 0 && ovec[1] >= length) {
2134 /* 're' matched all of 'string'. */
2137 /* 're' matched the initial part of 'string' but not all of it. */
2138 return PCRE_ERROR_NOMATCH;
2146 figure_choices(pcre *re, struct ds *s, int pos, struct ds *choices)
2154 /* See whether the current string is a complete match. */
2155 if (!match(re, s->string, pos)) {
2156 ds_put_char(choices, '\n');
2159 /* Then try all the other possibilities. */
2161 ds_put_buffer(&tmp, s->string, pos);
2162 for (c = 0x20; c < 0x7f; c++) {
2163 ds_put_char(&tmp, c);
2164 retval = match(re, tmp.string, pos + 1);
2165 if (retval == PCRE_ERROR_PARTIAL || !retval) {
2166 ds_put_char(choices, c);
2172 if (!choices->length) {
2173 ds_put_char(choices, '\n');
2178 figure_completion(pcre *re, struct ds *s)
2184 /* See whether the current string is a complete match. */
2185 if (!match(re, s->string, s->length)) {
2188 for (c = 0x20; c < 0x7f; c++) {
2192 retval = match(re, s->string, s->length);
2195 if (retval == PCRE_ERROR_PARTIAL || !retval) {
2205 ds_put_char(s, found);
2209 #define OCTET_RE "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
2210 #define IP_RE "("OCTET_RE"\\."OCTET_RE"\\."OCTET_RE"\\."OCTET_RE")"
2214 "[1-9][0-9][0-9]|" \
2215 "[1-9][0-9][0-9][0-9]|" \
2216 "[1-5][0-9][0-9][0-9][0-9]|" \
2217 "6[1-4][0-9][0-9][0-9]|" \
2218 "65[1-4][0-9][0-9]|" \
2221 #define XOCTET_RE "[0-9A-F][0-9A-F]"
2223 XOCTET_RE":"XOCTET_RE":"XOCTET_RE":"\
2224 XOCTET_RE":"XOCTET_RE":"XOCTET_RE
2225 #define NUM100_TO_99999_RE \
2226 "([1-9][0-9][0-9]|" \
2227 "[1-9][0-9][0-9][0-9]|" \
2228 "[1-9][0-9][0-9][0-9][0-9])"
2229 #define NUM5_TO_99999_RE \
2232 "[1-9][0-9][0-9]|" \
2233 "[1-9][0-9][0-9][0-9]|" \
2234 "[1-9][0-9][0-9][0-9][0-9])"
2235 #define NUM1_TO_99999_RE \
2238 "[1-9][0-9][0-9]|" \
2239 "[1-9][0-9][0-9][0-9]|" \
2240 "[1-9][0-9][0-9][0-9][0-9])"
2243 prompt(const char *prompt, const char *initial, const char *pattern)
2265 re = pcre_compile(pattern, PCRE_ANCHORED, &error, &erroffset, NULL);
2267 VLOG_ERR("PCRE error for pattern \"%s\" at offset %d: %s",
2268 pattern, erroffset, error);
2269 return xstrdup(initial);
2272 retval = pcre_fullinfo(re, NULL, PCRE_INFO_OKPARTIAL, &okpartial);
2278 ds_put_cstr(&ds, initial);
2280 figure_choices(re, &ds, pos, &choices);
2281 p = memchr(choices.string, initial[0], choices.length);
2282 chidx = p ? p - choices.string : 0;
2286 while ((key = getch()) != ERR) {
2289 if (choices.length > 1) {
2290 if (++chidx >= choices.length) {
2293 ds.string[pos] = choices.string[chidx];
2294 ds_truncate(&ds, pos + 1);
2295 figure_completion(re, &ds);
2300 if (choices.length > 1) {
2302 chidx = choices.length - 1;
2304 ds.string[pos] = choices.string[chidx];
2305 ds_truncate(&ds, pos + 1);
2306 figure_completion(re, &ds);
2310 case '\r': case '\n':
2311 if (choices.string[chidx] == '\n') {
2312 ds_truncate(&ds, pos);
2313 return ds_cstr(&ds);
2315 if (pos >= ds.length) {
2317 ds_put_char(&ds, choices.string[chidx]);
2318 figure_choices(re, &ds, pos, &choices);
2320 figure_completion(re, &ds);
2323 figure_choices(re, &ds, pos, &choices);
2325 figure_completion(re, &ds);
2331 ds_truncate(&ds, pos + 1);
2332 figure_choices(re, &ds, pos, &choices);
2336 case '\b': case '\x7f': case '\x1b':
2337 case KEY_BACKSPACE: case KEY_DC:
2341 return xstrdup(initial);
2343 figure_choices(re, &ds, pos, &choices);
2345 if (pos < ds.length) {
2346 p = memchr(choices.string, ds.string[pos],
2349 chidx = p - choices.string;
2355 if (key >= 0x20 && key < 0x7f) {
2356 /* Check whether 'key' is valid and toggle case if
2358 if (!memchr(choices.string, key, choices.length)) {
2359 if (memchr(choices.string, toupper(key),
2362 } else if (memchr(choices.string, tolower(key),
2370 /* Insert 'key' and advance the position. */
2371 if (pos >= ds.length) {
2372 ds_put_char(&ds, key);
2374 ds.string[pos] = key;
2378 if (choices.string[chidx] != key) {
2379 ds_truncate(&ds, pos);
2381 figure_choices(re, &ds, pos, &choices);
2383 if (pos < ds.length) {
2384 p = memchr(choices.string, ds.string[pos],
2387 chidx = p - choices.string;
2390 figure_completion(re, &ds);
2398 addnstr(prompt, MIN(40, strlen(prompt)));
2400 c = choices.string[chidx];
2402 addstr(ds_cstr(&ds));
2412 poll_fd_wait(STDIN_FILENO, POLLIN);
2418 prompt_ip(const char *title, uint32_t *ip)
2420 char *in = xasprintf(IP_FMT, IP_ARGS(ip));
2421 char *out = prompt(title, in, "^"IP_RE"$");
2422 *ip = inet_addr(out);
2428 abbreviate_netdevs(const struct svec *netdevs, struct ds *abbrev)
2433 for (i = 0; i < netdevs->n; ) {
2434 size_t i_len = strlen(netdevs->names[i]);
2437 for (j = i + 1; j < netdevs->n; j++) {
2438 size_t j_len = strlen(netdevs->names[j]);
2439 if (!i_len || !j_len || i_len != j_len
2440 || memcmp(netdevs->names[i], netdevs->names[j], i_len - 1)) {
2445 if (abbrev->length) {
2446 ds_put_char(abbrev, ' ');
2449 ds_put_cstr(abbrev, netdevs->names[i]);
2453 ds_put_buffer(abbrev, netdevs->names[i], i_len - 1);
2454 ds_put_char(abbrev, '[');
2455 for (k = i; k < j; k++) {
2456 ds_put_char(abbrev, netdevs->names[k][i_len - 1]);
2458 ds_put_char(abbrev, ']');
2465 choose_netdevs(struct svec *choices)
2467 struct svec netdevs = SVEC_EMPTY_INITIALIZER;
2471 netdev_enumerate(&netdevs);
2472 svec_sort(&netdevs);
2475 menu_add_item(&menu, "Exit");
2476 for (i = 0; i < netdevs.n; i++) {
2477 const char *name = netdevs.names[i];
2478 struct menu_item *item;
2479 struct netdev *netdev;
2482 if (!strncmp(name, "wmaster", strlen("wmaster"))
2483 || !strncmp(name, "of", strlen("of"))
2484 || !strcmp(name, "lo")) {
2488 retval = netdev_open_default(name, &netdev);
2490 bool exclude = netdev_get_in4(netdev, NULL, NULL) == 0;
2491 netdev_close(netdev);
2497 item = menu_add_item(&menu, "%s", name);
2498 item->toggle = svec_contains(choices, name);
2500 if (menu.n_items > 1) {
2501 menu_show(&menu, 0, true);
2503 show_string("No available\nbridge ports");
2506 svec_clear(choices);
2507 for (i = 0; i < menu.n_items; i++) {
2508 struct menu_item *item = menu.items[i];
2509 if (item->toggle > 0) {
2510 svec_add(choices, item->text);
2518 is_datapath_id_in_dmi(void)
2524 dmidecode = popen("dmidecode -s system-uuid", "r");
2528 is_in_dmi = fgets(line, sizeof line, dmidecode) && strstr(line, "-002320");
2533 struct switch_config {
2534 struct svec netdevs;
2535 enum { DISCOVERY, IN_BAND } mode;
2537 uint32_t switch_mask;
2539 enum { FAIL_DROP, FAIL_SWITCH } disconnected;
2542 int inactivity_probe;
2544 char *controller_vconn;
2549 disconnected_string(int value)
2551 #define FAIL_SWITCH_STRING "Switch packets"
2552 #define FAIL_DROP_STRING "Drop packets"
2553 return value == FAIL_SWITCH ? FAIL_SWITCH_STRING : FAIL_DROP_STRING;
2557 cmd_configure(const struct dict *dict OVS_UNUSED)
2559 bool debug_mode = dict_get_bool(dict, "debug", false);
2560 struct dict config_dict;
2561 struct switch_config config;
2564 if (!load_config(&config_dict)) {
2567 svec_init(&config.netdevs);
2568 svec_parse_words(&config.netdevs,
2569 dict_get_string(&config_dict, "NETDEVS", ""));
2570 config.mode = (!strcmp(dict_get_string(&config_dict, "MODE", "discovery"),
2571 "in-band") ? IN_BAND : DISCOVERY);
2572 config.switch_ip = dict_get_ip(&config_dict, "SWITCH_IP");
2573 config.switch_mask = dict_get_ip(&config_dict, "SWITCH_NETMASK");
2574 config.switch_gw = dict_get_ip(&config_dict, "SWITCH_GATEWAY");
2575 config.controller_vconn = xstrdup(dict_get_string(&config_dict,
2577 config.disconnected = (!strcmp(dict_get_string(&config_dict,
2578 "DISCONNECTED_MODE", ""),
2580 ? FAIL_SWITCH : FAIL_DROP);
2581 config.stp = !strcmp(dict_get_string(&config_dict, "stp", ""), "yes");
2582 config.rate_limit = dict_get_int(&config_dict, "RATE_LIMIT", -1);
2583 config.inactivity_probe = dict_get_int(&config_dict, "INACTIVITY_PROBE",
2585 config.max_backoff = dict_get_int(&config_dict, "MAX_BACKOFF", -1);
2586 if (is_datapath_id_in_dmi()) {
2587 config.datapath_id = xstrdup("DMI");
2589 const char *dpid = dict_get(&config_dict, "DATAPATH_ID");
2591 struct ds ds = DS_EMPTY_INITIALIZER;
2593 for (cp = dpid; *cp != '\0'; cp++) {
2595 ds_put_char(&ds, toupper((unsigned char) *cp));
2598 config.datapath_id = ds_cstr(&ds);
2600 config.datapath_id = xstrdup("Random");
2603 dict_free(&config_dict);
2606 while (start != -1) {
2615 MENU_DISCONNECTED_MODE,
2619 MENU_INACTIVITY_PROBE,
2624 struct menu_item *item;
2632 item = menu_add_item(&menu, "Exit");
2633 item->id = MENU_EXIT;
2636 abbreviate_netdevs(&config.netdevs, &ports);
2637 item = menu_add_item(&menu, "Bridge Ports:\n%s", ds_cstr(&ports));
2638 item->id = MENU_NETDEVS;
2642 item = menu_add_item(&menu, "Mode:\n%s",
2643 (config.mode == DISCOVERY
2644 ? "Discovery" : "In-Band"));
2645 item->id = MENU_MODE;
2648 if (config.switch_ip == htonl(0)) {
2649 item = menu_add_item(&menu, "Switch IP Addr:\nDHCP");
2651 item = menu_add_item(&menu, "Switch IP Addr:\n"IP_FMT,
2652 IP_ARGS(&config.switch_ip));
2655 item->enabled = config.mode == IN_BAND;
2658 item = menu_add_item(&menu, "Switch Netmask:\n"IP_FMT,
2659 IP_ARGS(&config.switch_mask));
2660 item->id = MENU_NETMASK;
2661 item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2664 item = menu_add_item(&menu, "Switch Gateway:\n"IP_FMT,
2665 IP_ARGS(&config.switch_gw));
2666 item->id = MENU_GATEWAY;
2667 item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2670 item = menu_add_item(&menu, "Controller:\n%s",
2671 config.controller_vconn);
2672 item->id = MENU_CONTROLLER;
2673 item->enabled = config.mode == IN_BAND;
2675 /* Disconnected mode. */
2676 item = menu_add_item(&menu, "If disconnected:\n%s\n",
2677 disconnected_string(config.disconnected));
2678 item->id = MENU_DISCONNECTED_MODE;
2681 item = menu_add_item(&menu, "Datapath ID:\n%s", config.datapath_id);
2682 item->id = MENU_DATAPATH_ID;
2683 item->enabled = strcmp(config.datapath_id, "DMI");
2685 /* Spanning tree protocol. */
2687 item = menu_add_item(&menu, "802.1D-1998 STP:\n%s",
2688 config.stp ? "Enabled" : "Disabled");
2689 item->id = MENU_STP;
2692 /* Rate-limiting. */
2694 if (config.rate_limit < 0) {
2695 item = menu_add_item(&menu, "Ctlr rate limit:\nDisabled");
2697 item = menu_add_item(&menu, "Ctlr rate limit:\n%d/s",
2700 item->id = MENU_RATE_LIMIT;
2703 /* Inactivity probe. */
2705 if (config.inactivity_probe < 0) {
2706 item = menu_add_item(&menu, "Activity probe:\nDefault");
2708 item = menu_add_item(&menu, "Activity probe:\n%d s",
2709 config.inactivity_probe);
2711 item->id = MENU_INACTIVITY_PROBE;
2716 if (config.max_backoff < 0) {
2717 item = menu_add_item(&menu, "Max backoff:\nDefault");
2719 item = menu_add_item(&menu, "Max backoff:\n%d s",
2720 config.max_backoff);
2722 item->id = MENU_MAX_BACKOFF;
2725 start = menu_show2(&menu, start, true);
2735 choose_netdevs(&config.netdevs);
2739 out = prompt("Mode:",
2740 config.mode == DISCOVERY ? "Discovery" : "In-Band",
2741 "^(Discovery|In-Band)$");
2742 config.mode = !strcmp(out, "Discovery") ? DISCOVERY : IN_BAND;
2747 in = (config.switch_ip == htonl(0) ? xstrdup("DHCP")
2748 : xasprintf(IP_FMT, IP_ARGS(&config.switch_ip)));
2749 out = prompt("Switch IP:", in, "^(DHCP|"IP_RE")$");
2750 ip = strcmp(out, "DHCP") ? inet_addr(out) : htonl(0);
2753 if (ip != config.switch_ip) {
2754 config.switch_ip = ip;
2755 if (ip != htonl(0)) {
2756 uint32_t mask = guess_netmask(ip);
2758 config.switch_mask = mask;
2759 config.switch_gw = (ip & mask) | htonl(1);
2766 prompt_ip("Switch Netmask:", &config.switch_mask);
2770 prompt_ip("Switch Gateway:", &config.switch_gw);
2773 case MENU_CONTROLLER:
2774 out = prompt("Controller:", config.controller_vconn,
2775 "^(tcp|ssl):"IP_RE"(:"PORT_RE")?$");
2776 free(config.controller_vconn);
2777 config.controller_vconn = out;
2780 case MENU_DISCONNECTED_MODE:
2781 out = prompt("If disconnected",
2782 disconnected_string(config.disconnected),
2783 "^("FAIL_DROP_STRING"|"FAIL_SWITCH_STRING")$");
2784 config.disconnected = (!strcmp(out, FAIL_DROP_STRING)
2785 ? FAIL_DROP : FAIL_SWITCH);
2789 case MENU_DATAPATH_ID:
2790 out = prompt("Datapath ID:", config.datapath_id,
2791 "^Random|"MAC_RE"$");
2792 free(config.datapath_id);
2793 config.datapath_id = out;
2797 out = prompt("802.1D-1998 STP:",
2798 config.stp ? "Enabled" : "Disabled",
2799 "^(Enabled|Disabled)$");
2800 config.stp = !strcmp(out, "Enabled");
2804 case MENU_RATE_LIMIT:
2805 in = (config.rate_limit < 0
2806 ? xstrdup("Disabled")
2807 : xasprintf("%d/s", config.rate_limit));
2808 out = prompt("Ctlr rate limit:", in,
2809 "^(Disabled|("NUM100_TO_99999_RE")/s)$");
2812 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2816 case MENU_INACTIVITY_PROBE:
2817 in = (config.inactivity_probe < 0
2818 ? xstrdup("Default")
2819 : xasprintf("%d s", config.inactivity_probe));
2820 out = prompt("Activity probe:", in,
2821 "^(Default|("NUM5_TO_99999_RE") s)$");
2823 config.inactivity_probe
2824 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2828 case MENU_MAX_BACKOFF:
2829 in = (config.max_backoff < 0
2830 ? xstrdup("Default")
2831 : xasprintf("%d s", config.max_backoff));
2832 out = prompt("Max backoff:", in,
2833 "^(Default|("NUM1_TO_99999_RE") s)$");
2836 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2842 if (yesno("Save\nChanges?", false)) {
2847 netdevs = svec_join(&config.netdevs, " ", "");
2848 svec_add_nocopy(&set, xasprintf("NETDEVS=%s", netdevs));
2851 config.mode == IN_BAND ? "MODE=in-band" : "MODE=discovery");
2852 if (config.mode == IN_BAND) {
2853 if (config.switch_ip == htonl(0)) {
2854 svec_add(&set, "SWITCH_IP=dhcp");
2856 svec_add_nocopy(&set, xasprintf("SWITCH_IP="IP_FMT,
2857 IP_ARGS(&config.switch_ip)));
2858 svec_add_nocopy(&set,
2859 xasprintf("SWITCH_NETMASK="IP_FMT,
2860 IP_ARGS(&config.switch_mask)));
2861 svec_add_nocopy(&set, xasprintf("SWITCH_GATEWAY="IP_FMT,
2862 IP_ARGS(&config.switch_gw)));
2863 svec_add_nocopy(&set, xasprintf("CONTROLLER=%s",
2864 config.controller_vconn));
2867 svec_add(&set, (config.disconnected == FAIL_DROP
2868 ? "DISCONNECTED_MODE=drop"
2869 : "DISCONNECTED_MODE=switch"));
2870 svec_add_nocopy(&set, xasprintf("STP=%s", config.stp ? "yes" : "no"));
2871 if (config.rate_limit < 0) {
2872 svec_add(&set, "RATE_LIMIT=");
2874 svec_add_nocopy(&set,
2875 xasprintf("RATE_LIMIT=%d", config.rate_limit));
2877 if (config.inactivity_probe < 0) {
2878 svec_add(&set, "INACTIVITY_PROBE=");
2880 svec_add_nocopy(&set, xasprintf("INACTIVITY_PROBE=%d",
2881 config.inactivity_probe));
2883 if (config.max_backoff < 0) {
2884 svec_add(&set, "MAX_BACKOFF=");
2886 svec_add_nocopy(&set, xasprintf("MAX_BACKOFF=%d",
2887 config.max_backoff));
2893 svec_destroy(&config.netdevs);
2894 free(config.controller_vconn);
2895 free(config.datapath_id);
2899 cmd_set_up_pki(const struct dict *dict OVS_UNUSED)
2901 static const char def_privkey_file[]
2902 = "/etc/openflow-switch/of0-privkey.pem";
2903 static const char def_cert_file[] = "/etc/openflow-switch/of0-cert.pem";
2904 static const char def_cacert_file[] = "/etc/openflow-switch/cacert.pem";
2905 struct dict config_dict;
2906 const char *privkey_file, *cert_file, *cacert_file;
2912 if (!load_config(&config_dict)) {
2915 privkey_file = dict_get_string(&config_dict, "PRIVKEY", def_privkey_file);
2916 cert_file = dict_get_string(&config_dict, "CERT", def_cert_file);
2917 cacert_file = dict_get_string(&config_dict, "CACERT", def_cacert_file);
2918 bootstrap = !strcmp(dict_get_string(&config_dict, "CACERT_MODE", "secure"),
2921 has_keys = !stat(privkey_file, &s) && !stat(cert_file, &s);
2923 ? yesno("Generate\nkeys?", true)
2924 : yesno("Generate\nnew keys?", false)) {
2928 privkey_file = def_privkey_file;
2929 cert_file = def_cert_file;
2932 svec_parse_words(&argv, "sh -c 'cd /etc/openflow-switch "
2933 "&& ovs-pki --force req of0"
2934 "&& ovs-pki --force self-sign of0'");
2935 svec_terminate(&argv);
2936 ok = run_and_report_failure(argv.names, "Key gen failed");
2937 svec_destroy(&argv);
2947 if (stat(cacert_file, &s) && errno == ENOENT) {
2948 bootstrap = yesno("Bootstrap\nCA cert?", bootstrap);
2949 } else if (yesno("Replace\nCA cert?", false)) {
2950 unlink(cacert_file);
2955 svec_add_nocopy(&set, xasprintf("PRIVKEY=%s", privkey_file));
2956 svec_add_nocopy(&set, xasprintf("CERT=%s", cert_file));
2957 svec_add_nocopy(&set, xasprintf("CACERT=%s", cacert_file));
2958 svec_add_nocopy(&set, xasprintf("CACERT_MODE=%s",
2959 bootstrap ? "bootstrap" : "secure"));
2965 parse_options(int argc, char *argv[])
2968 OPT_DUMMY = UCHAR_MAX + 1,
2971 static struct option long_options[] = {
2972 {"verbose", optional_argument, 0, 'v'},
2973 {"help", no_argument, 0, 'h'},
2974 {"version", no_argument, 0, 'V'},
2975 DAEMON_LONG_OPTIONS,
2979 char *short_options = long_options_to_short_options(long_options);
2984 c = getopt_long(argc, argv, short_options, long_options, NULL);
2994 OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
2997 VLOG_OPTION_HANDLERS
2998 DAEMON_OPTION_HANDLERS
3007 free(short_options);
3013 printf("%s: OpenFlow switch monitoring user interface\n"
3014 "usage: %s [OPTIONS] SWITCH\n"
3015 "where SWITCH is an active OpenFlow connection method.\n",
3016 program_name, program_name);
3017 vconn_usage(true, false, false);
3018 printf("\nOptions:\n"
3019 " -v, --verbose=MODULE:FACILITY:LEVEL configure logging levels\n"
3020 " -v, --verbose set maximum verbosity level\n"
3021 " -h, --help display this help message\n"
3022 " -V, --version display version information\n");