1 /* Copyright (c) 2008, 2009 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_secchan_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 set_program_name(argv[0]);
150 parse_options(argc, argv);
151 signal(SIGPIPE, SIG_IGN);
152 vlog_set_levels(VLM_ANY_MODULE, VLF_CONSOLE, VLL_EMER);
153 init_reboot_notifier();
158 ovs_fatal(0, "exactly one non-option argument required; "
159 "use --help for help");
162 rconn = rconn_new(argv[0], 5, 5);
164 die_if_already_running();
167 initialize_terminal();
168 fatal_signal_add_hook(restore_terminal, NULL, true);
172 user_selected = false;
176 long long timeout = time_msec() + 1000;
181 fetch_status(rconn, &dict, timeout);
182 dict_add(&dict, "debug", debug_mode ? "true" : "false");
183 compose_messages(&dict, rconn);
186 if (!empty_message(msg)) {
189 msg = user_selected ? next_message(msg) : best_message();
193 msg = best_message();
195 user_selected = false;
197 if (!user_selected) {
208 if (c != last_key || time_msec() > last_key_time + 250) {
212 last_key_time = time_msec();
215 if (c == KEY_DOWN || c == KEY_UP) {
216 msg = (c == KEY_DOWN ? next_message(msg)
217 : prev_message(msg));
219 user_selected = true;
220 } else if (c == '\r' || c == '\n') {
222 user_selected = true;
223 if (repeat_count >= 20) {
224 debug_mode = !debug_mode;
225 show_string(debug_mode
226 ? "Debug Mode\nEnabled"
227 : "Debug Mode\nDisabled");
229 } else if (c == '\b' || c == '\x7f' ||
230 c == '\x1b' || c == KEY_BACKSPACE || c == KEY_DC) {
232 drain_keyboard_buffer();
243 poll_fd_wait(STDIN_FILENO, POLLIN);
244 poll_timer_wait(timeout - time_msec());
246 } while (time_msec() < timeout);
255 compose_messages(const struct dict *dict, struct rconn *rconn)
257 if (!show_reboot_state()) {
259 show_dpid_ip(rconn, dict);
260 show_secchan_state(dict);
261 show_fail_open_state(dict);
262 show_discovery_state(dict);
263 show_remote_state(dict);
264 show_data_rates(rconn, dict);
268 struct put_flows_data {
276 parse_flow_reply(void *data, struct put_flows_data *pfd)
278 struct ofp_header *oh;
279 struct ofp_stats_reply *rpy;
280 struct ofp_aggregate_stats_reply *asr;
281 const size_t min_size = sizeof *rpy + sizeof *asr;
284 if (ntohs(oh->length) < min_size) {
285 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
288 if (oh->xid != pfd->xid) {
289 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
293 if (oh->type != OFPT_STATS_REPLY) {
294 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
299 if (rpy->type != htons(OFPST_AGGREGATE)) {
300 VLOG_WARN("reply has wrong stat type ID %08"PRIx16, rpy->type);
304 asr = (struct ofp_aggregate_stats_reply *) rpy->body;
305 pfd->flow_count = ntohl(asr->flow_count);
306 pfd->got_reply = true;
312 const char *dico = tigetstr("dico");
313 return dico && dico != (const char *) -1;
317 set_icon(int num, int r0, int r1, int r2, int r3, int r4, int r5, int r6,
321 putp(tparm(tigetstr("dico"), num, r0, r1, r2, r3, r4, r5, r6, r7));
326 set_repeated_icon(int num, int row)
328 set_icon(num, row, row, row, row, row, row, row, row);
333 set_brick_icon(int num, int n_solid)
335 const static int rows[6] = {_____, X____, XX___, XXX__, XXXX_, XXXXX};
336 set_repeated_icon(num, rows[n_solid < 0 ? 0
343 icon_char(int num, int alternate)
345 return have_icons() ? 0x80 | num | A_ALTCHARSET : alternate;
349 put_icon(int num, char alternate)
351 addch(icon_char(num, alternate));
356 bar_graph(int n_chars, int n_pixels)
362 } else if (n_pixels > n_chars * 5) {
363 n_pixels = n_chars * 5;
367 set_brick_icon(0, 5);
368 for (i = 0; i < n_pixels / 5; i++) {
373 set_brick_icon(1, n_pixels % 5);
380 put_flows(void *pfd_)
382 struct put_flows_data *pfd = pfd_;
383 static struct rconn_packet_counter *counter;
387 counter = rconn_packet_counter_create();
391 struct ofp_stats_request *rq;
392 struct ofp_aggregate_stats_request *asr;
395 pfd->xid = random_uint32();
396 rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
398 rq->type = htons(OFPST_AGGREGATE);
399 rq->flags = htons(0);
400 asr = ofpbuf_put_uninit(b, sizeof *asr);
401 memset(asr, 0, sizeof *asr);
402 asr->match.wildcards = htonl(OFPFW_ALL);
403 asr->table_id = 0xff;
404 asr->out_port = htons(OFPP_NONE);
405 update_openflow_length(b);
406 rconn_send_with_limit(pfd->rconn, b, counter, 10);
409 if (!pfd->got_reply) {
412 rconn_run(pfd->rconn);
413 for (i = 0; i < 50; i++) {
416 b = rconn_recv(pfd->rconn);
421 parse_flow_reply(b->data, pfd);
423 if (pfd->got_reply) {
429 gethostname(host, sizeof host);
430 host[sizeof host - 1] = '\0';
431 if (strlen(host) + 6 <= 16) {
432 addf("Host: %s\n", host);
436 if (pfd->got_reply) {
437 addf("Flows: %"PRIu32, pfd->flow_count);
440 if (!pfd->got_reply) {
441 rconn_run_wait(pfd->rconn);
442 rconn_recv_wait(pfd->rconn);
447 show_flows(struct rconn *rconn)
449 static struct message *m;
450 static struct put_flows_data pfd;
452 memset(&pfd, 0, sizeof pfd);
454 emit_function(&m, P_STATUS, put_flows, &pfd);
458 struct put_dpid_ip_data {
467 parse_dp_reply(void *data, struct put_dpid_ip_data *pdid)
469 struct ofp_switch_features *osf;
470 struct ofp_header *oh;
473 if (ntohs(oh->length) < sizeof *osf) {
474 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
477 if (oh->xid != pdid->xid) {
478 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
482 if (oh->type != OFPT_FEATURES_REPLY) {
483 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
488 pdid->dpid = ntohll(osf->datapath_id);
489 pdid->got_reply = true;
493 put_dpid_id(void *pdid_)
495 struct put_dpid_ip_data *pdid = pdid_;
496 static struct rconn_packet_counter *counter;
499 counter = rconn_packet_counter_create();
503 struct ofp_header *oh;
506 pdid->xid = random_uint32();
507 oh = make_openflow_xid(sizeof *oh, OFPT_FEATURES_REQUEST,
509 rconn_send_with_limit(pdid->rconn, b, counter, 10);
512 if (!pdid->got_reply) {
515 rconn_run(pdid->rconn);
516 for (i = 0; i < 50; i++) {
519 b = rconn_recv(pdid->rconn);
524 parse_dp_reply(b->data, pdid);
526 if (pdid->got_reply) {
533 if (pdid->got_reply) {
534 addf("%012"PRIx64, pdid->dpid);
536 addf("\nIP: %s", pdid->ip);
538 if (!pdid->got_reply) {
539 rconn_run_wait(pdid->rconn);
540 rconn_recv_wait(pdid->rconn);
545 show_dpid_ip(struct rconn *rconn, const struct dict *dict)
547 static struct message *m;
548 static struct put_dpid_ip_data pdid;
549 const char *is_connected, *local_ip;
551 dict_lookup(dict, "local.is-connected", &is_connected);
552 dict_lookup(dict, "remote.local-ip", &local_ip);
553 if (!is_connected && !local_ip) {
554 /* If we're not connected to the datapath and don't have a local IP,
555 * then we won't have anything useful to show anyhow. */
559 memset(&pdid, 0, sizeof pdid);
561 ovs_strlcpy(pdid.ip, local_ip ? local_ip : "", sizeof pdid.ip);
562 emit_function(&m, P_STATUS, put_dpid_id, &pdid);
566 dict_find(const struct dict *dict, const char *name)
570 for (i = 0; i < dict->n; i++) {
571 const struct pair *p = &dict->pairs[i];
572 if (!strcmp(p->name, name)) {
581 dict_lookup(const struct dict *dict, const char *name, const char **value)
583 size_t idx = dict_find(dict, name);
584 if (idx != SIZE_MAX) {
585 *value = dict->pairs[idx].value;
594 dict_get(const struct dict *dict, const char *name)
597 return dict_lookup(dict, name, &value) ? value : NULL;
601 dict_get_int(const struct dict *dict, const char *name, int def)
604 return dict_lookup(dict, name, &value) ? atoi(value) : def;
608 dict_get_bool(const struct dict *dict, const char *name, bool def)
611 if (dict_lookup(dict, name, &value)) {
612 if (!strcmp(value, "true")) {
615 if (!strcmp(value, "false")) {
623 dict_get_string(const struct dict *dict, const char *name, const char *def)
626 return dict_lookup(dict, name, &value) ? value : def;
630 dict_get_ip(const struct dict *dict, const char *name)
633 return (inet_aton(dict_get_string(dict, name, ""), &in) ? in.s_addr
638 addf(const char *format, ...)
643 va_start(args, format);
644 vsnprintf(buf, sizeof buf, format, args);
651 show_secchan_state(const struct dict *dict)
653 static struct message *msg;
654 const char *is_connected;
656 if (!dict_lookup(dict, "remote.is-connected", &is_connected)) {
657 /* Secchan not running or not responding. */
658 emit(&msg, P_ERROR, "Switch disabled");
663 discovery_state_label(const char *name)
665 static struct dict *states;
667 states = xmalloc(sizeof *states);
669 dict_add(states, "INIT", "Init");
670 dict_add(states, "INIT_REBOOT", "Init");
671 dict_add(states, "REBOOTING", "Init");
672 dict_add(states, "SELECTING", "Searching");
673 dict_add(states, "REQUESTING", "Requesting");
674 dict_add(states, "BOUND", "Got");
675 dict_add(states, "RENEWING", "Renewing");
676 dict_add(states, "REBINDING", "Rebinding");
677 dict_add(states, "RELEASED", "Released");
679 return dict_get_string(states, name, "Error");
683 show_discovery_state(const struct dict *dict)
685 static struct message *m_bound, *m_other;
687 const char *state, *ip;
688 enum priority priority;
691 state = dict_get_string(dict, "discovery.state", NULL);
695 ip = dict_get_string(dict, "discovery.ip", NULL);
696 state_elapsed = dict_get_int(dict, "discovery.state-elapsed", 0);
698 if (!strcmp(state, "BOUND")) {
703 priority = P_PROGRESS;
705 emit(m, priority, "Discovery %s\n%s",
706 progress(), discovery_state_label(state));
708 emit(m, priority, " %s", ip);
713 human_time(int seconds, char *buf, size_t size)
715 const char *sign = "";
718 seconds = seconds == INT_MIN ? INT_MAX : -seconds;
722 snprintf(buf, size, "%s%d s", sign, seconds);
723 } else if (seconds <= 60 * 60) {
724 snprintf(buf, size, "%s%d min", sign, seconds / 60);
725 } else if (seconds <= 60 * 60 * 24 * 2) {
726 snprintf(buf, size, "%s%d h", sign, seconds / 60 / 60);
728 snprintf(buf, size, "%s%d days", sign, seconds / 60 / 60 / 24);
733 show_fail_open_state(const struct dict *dict)
735 static struct message *m;
736 int cur_duration, trigger_duration;
738 if (!dict_get_bool(dict, "fail-open.triggered", false)) {
741 trigger_duration = dict_get_int(dict, "fail-open.trigger-duration", 0);
742 cur_duration = dict_get_int(dict, "fail-open.current-duration", 0);
744 emit(&m, P_WARNING, "Failed open %s\nafter %d secs",
745 progress(), trigger_duration);
748 human_time(cur_duration - trigger_duration, buf, sizeof buf);
749 emit(&m, P_WARNING, "In fail open for\n%s now %s", buf, progress());
756 return "..." + (3 - (unsigned int) time_now() % 4);
760 show_remote_state(const struct dict *dict)
762 bool debug_mode = dict_get_bool(dict, "debug", false);
763 const char *state, *is_connected;
765 state = dict_get_string(dict, "remote.state", NULL);
769 is_connected = dict_get_string(dict, "remote.is-connected", "false");
770 if (!strcmp(is_connected, "true")) {
772 static struct message *m_connected;
774 human_time(dict_get_int(dict, "remote.last-connection", 0),
776 emit(&m_connected, P_STATUS,
777 "Connected for\nlast %s %s", buf, progress());
780 if (!strcmp(state, "IDLE")) {
781 static struct message *m_idle;
782 emit(&m_idle, P_PROGRESS, "Sent idle probe");
786 const char *name = dict_get_string(dict, "remote.name", NULL);
788 static struct message *m_name;
789 emit(&m_name, P_STATUS, "Connected to\n%s", name);
793 int elapsed, backoff;
794 const char *name, *error;
796 elapsed = dict_get_int(dict, "remote.state-elapsed", 0);
797 backoff = dict_get_int(dict, "remote.backoff", 0);
798 name = dict_get_string(dict, "remote.name", "unknown");
799 state = dict_get_string(dict, "remote.state", "VOID");
800 error = dict_get_string(dict, "remote.last-connect-error", NULL);
801 if (!strcmp(state, "VOID")) {
802 static struct message *m;
803 emit(&m, P_PROGRESS, "Controller not\nfound");
804 } else if (!strcmp(state, "BACKOFF")) {
805 static struct message *m[3];
809 emit(&m[0], P_PROGRESS, "Connect failed:\n%s", error);
811 emit(&m[2], P_STATUS, "Last connected\n%s ago", buf);
812 emit(&m[1], P_PROGRESS,
813 "Disconnected\nReconnect in %d", backoff - elapsed);
814 human_time(dict_get_int(dict, "remote.last-connection", 0),
816 } else if (!strcmp(state, "CONNECTING")) {
817 static struct message *m;
818 emit(&m, P_PROGRESS, "Connecting %s\n%s", progress(), name);
824 fetch_status(struct rconn *rconn, struct dict *dict, long long timeout)
826 static struct rconn_packet_counter *counter;
828 struct nicira_header *rq;
833 counter = rconn_packet_counter_create();
836 xid = random_uint32();
839 rq = make_openflow_xid(sizeof *rq, OFPT_VENDOR, ++xid, &b);
840 rq->vendor = htonl(NX_VENDOR_ID);
841 rq->subtype = htonl(NXT_STATUS_REQUEST);
842 retval = rconn_send_with_limit(rconn, b, counter, 10);
844 /* continue into the loop so that we pause for a while */
847 while (time_msec() < timeout) {
852 for (i = 0; i < 50; i++) {
856 b = rconn_recv(rconn);
861 got_reply = parse_reply(b->data, dict, xid);
868 rconn_run_wait(rconn);
869 rconn_recv_wait(rconn);
870 poll_timer_wait(timeout - time_msec());
876 parse_reply(void *data, struct dict *dict, uint32_t xid)
878 struct ofp_header *oh;
879 struct nicira_header *rpy;
882 if (ntohs(oh->length) < sizeof *rpy) {
883 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
886 if (oh->xid != xid) {
887 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32, oh->xid, xid);
890 if (oh->type != OFPT_VENDOR) {
891 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
896 if (rpy->vendor != htonl(NX_VENDOR_ID)) {
897 VLOG_WARN("reply has wrong vendor ID %08"PRIx32, rpy->vendor);
900 if (rpy->subtype != htonl(NXT_STATUS_REPLY)) {
901 VLOG_WARN("reply has wrong subtype %08"PRIx32, rpy->subtype);
905 dict_parse(dict, (const char *) (rpy + 1),
906 ntohs(oh->length) - sizeof *rpy);
911 dict_parse(struct dict *dict, const char *data, size_t nbytes)
913 char *save_ptr = NULL;
916 copy = xmemdup0(data, nbytes);
917 for (name = strtok_r(copy, "=", &save_ptr); name;
918 name = strtok_r(NULL, "=", &save_ptr))
920 char *value = strtok_r(NULL, "\n", &save_ptr);
924 dict_add(dict, name, value);
930 dict_init(struct dict *dict)
934 dict->pairs = xmalloc(sizeof *dict->pairs * dict->max);
938 dict_add(struct dict *dict, const char *name, const char *value)
940 dict_add_nocopy(dict, xstrdup(name), xstrdup(value));
944 dict_add_nocopy(struct dict *dict, char *name, char *value)
948 if (dict->n >= dict->max) {
950 dict->pairs = xrealloc(dict->pairs, sizeof *dict->pairs * dict->max);
952 p = &dict->pairs[dict->n++];
958 dict_delete(struct dict *dict, const char *name)
961 while ((idx = dict_find(dict, name)) != SIZE_MAX) {
962 struct pair *pair = &dict->pairs[idx];
965 dict->pairs[idx] = dict->pairs[--dict->n];
970 dict_free(struct dict *dict)
975 for (i = 0; i < dict->n; i++) {
976 free(dict->pairs[i].name);
977 free(dict->pairs[i].value);
984 initialize_terminal(void)
990 intrflush(stdscr, FALSE);
991 keypad(stdscr, TRUE);
992 nodelay(stdscr, TRUE);
994 scrollok(stdscr, TRUE);
998 restore_terminal(void *aux UNUSED)
1008 struct show_rates_data {
1009 struct rconn *rconn;
1011 struct byte_count prev, now;
1016 parse_port_reply(void *data, struct show_rates_data *rates)
1018 struct ofp_header *oh;
1019 struct ofp_stats_reply *rpy;
1020 struct ofp_port_stats *ops;
1025 if (ntohs(oh->length) < sizeof *rpy) {
1026 VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
1029 if (oh->xid != rates->xid) {
1030 VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
1031 oh->xid, rates->xid);
1034 if (oh->type != OFPT_STATS_REPLY) {
1035 VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
1040 if (rpy->type != htons(OFPST_PORT)) {
1041 VLOG_WARN("reply has wrong stat type ID %08"PRIx16, rpy->type);
1045 n_ports = ((ntohs(oh->length) - offsetof(struct ofp_stats_reply, body))
1047 ops = (struct ofp_port_stats *) rpy->body;
1048 rates->prev = rates->now;
1049 rates->now.when = time_msec();
1050 rates->now.tx_bytes = UINT64_MAX;
1051 for (i = 0; i < n_ports; i++, ops++) {
1052 if (ops->tx_bytes != htonll(UINT64_MAX)) {
1053 if (rates->now.tx_bytes == UINT64_MAX) {
1054 rates->now.tx_bytes = 0;
1056 rates->now.tx_bytes += ntohll(ops->tx_bytes);
1059 rates->got_reply = true;
1063 dump_graph(const bool graph[80])
1065 signed char icons[32];
1069 memset(icons, -1, sizeof icons);
1070 for (i = 0; i < 16; i++) {
1075 for (j = 0; j < 5; j++) {
1076 row = (row << 1) | graph[i * 5 + j];
1083 if (icons[row] < 0) {
1088 set_repeated_icon(n_icons, row);
1089 icons[row] = n_icons++;
1091 put_icon(icons[row], row == 0x1f ? '#' : ' ');
1096 do_show_data_rates(void *rates_)
1098 struct show_rates_data *rates = rates_;
1099 static struct rconn_packet_counter *counter;
1103 counter = rconn_packet_counter_create();
1106 struct ofp_stats_request *rq;
1109 rates->xid = random_uint32();
1110 rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
1112 rq->type = htons(OFPST_PORT);
1113 rq->flags = htons(0);
1114 rconn_send_with_limit(rates->rconn, b, counter, 10);
1117 if (!rates->got_reply) {
1120 rconn_run(rates->rconn);
1121 for (i = 0; i < 50; i++) {
1124 b = rconn_recv(rates->rconn);
1129 parse_port_reply(b->data, rates);
1131 if (rates->got_reply) {
1165 memset(graph, 0, sizeof graph);
1178 if (rates->now.tx_bytes != UINT64_MAX
1179 && rates->prev.tx_bytes != UINT64_MAX
1180 && rates->now.when - rates->prev.when > 500
1181 && time_msec() - rates->now.when < 2000)
1183 uint64_t bits = (rates->now.tx_bytes - rates->prev.tx_bytes) * 8;
1184 uint64_t msecs = rates->now.when - rates->prev.when;
1185 double bps = (double) bits * 1000.0 / msecs;
1186 int pixels = bps > 0 ? log(bps) / log(10.0) * 8 + .5 : 0;
1189 } else if (pixels > 80) {
1192 memset(graph, 1, pixels);
1197 if (!rates->got_reply) {
1198 rconn_run_wait(rates->rconn);
1199 rconn_recv_wait(rates->rconn);
1204 show_data_rates(struct rconn *rconn, const struct dict *dict)
1206 static struct message *m;
1207 static struct show_rates_data rates;
1208 const char *is_connected, *local_ip;
1209 static bool inited = false;
1211 dict_lookup(dict, "local.is-connected", &is_connected);
1212 dict_lookup(dict, "remote.local-ip", &local_ip);
1213 if (!is_connected && !local_ip) {
1214 /* If we're not connected to the datapath and don't have a local IP,
1215 * then we won't have anything useful to show anyhow. */
1219 rates.rconn = rconn;
1221 rates.got_reply = false;
1223 rates.now.tx_bytes = UINT64_MAX;
1224 rates.prev.tx_bytes = UINT64_MAX;
1227 emit_function(&m, P_STATUS, do_show_data_rates, &rates);
1232 void (*function)(void *aux);
1237 enum priority priority;
1242 static struct message **messages;
1243 static size_t n_messages, allocated_messages;
1245 static struct message *
1246 allocate_message(struct message **msgp)
1249 /* Allocate and initialize message. */
1250 *msgp = xcalloc(1, sizeof **msgp);
1251 (*msgp)->index = n_messages;
1253 /* Add to list of messages. */
1254 if (n_messages >= allocated_messages) {
1255 allocated_messages = 2 * allocated_messages + 1;
1256 messages = xrealloc(messages,
1257 sizeof *messages * allocated_messages);
1259 messages[n_messages++] = *msgp;
1265 emit(struct message **msgp, enum priority priority, const char *format, ...)
1267 struct message *msg = allocate_message(msgp);
1271 msg->priority = priority;
1273 va_start(args, format);
1274 length = strlen(msg->string);
1275 vsnprintf(msg->string + length, sizeof msg->string - length, format, args);
1280 emit_function(struct message **msgp, enum priority priority,
1281 void (*function)(void *aux), void *aux)
1283 struct message *msg = allocate_message(msgp);
1284 msg->priority = priority;
1285 msg->function = function;
1290 shown(struct message **msgp)
1292 struct message *msg = allocate_message(msgp);
1297 clear_messages(void)
1301 for (i = 0; i < n_messages; i++) {
1302 struct message *msg = messages[i];
1303 msg->string[0] = '\0';
1304 msg->function = NULL;
1308 static struct message *
1311 struct message *best_msg;
1315 best_score = INT_MIN;
1317 for (i = 0; i < n_messages; i++) {
1318 struct message *msg = messages[i];
1321 if (empty_message(msg)) {
1325 score = msg->priority;
1329 score -= msg->shown;
1331 if (score > best_score) {
1340 message_shown(struct message *msg)
1342 if (msg && msg->shown++ > 3600) {
1348 empty_message(const struct message *msg)
1350 return !msg || (!msg->string[0] && !msg->function);
1353 static struct message *get_message(size_t index)
1355 assert(index <= n_messages || index == SIZE_MAX);
1356 return (index < n_messages ? messages[index]
1357 : index == SIZE_MAX ? messages[n_messages - 1]
1361 static struct message *
1362 next_message(struct message *msg)
1366 for (p = get_message(msg->index + 1); p != msg;
1367 p = get_message(p->index + 1)) {
1368 if (!empty_message(p)) {
1375 static struct message *
1376 prev_message(struct message *msg)
1380 for (p = get_message(msg->index - 1); p != msg;
1381 p = get_message(p->index - 1)) {
1382 if (!empty_message(p)) {
1390 put_message(const struct message *m)
1394 } else if (m->function) {
1395 m->function(m->aux);
1406 for (i = 0; i < n_messages; i++) {
1407 struct message *msg = messages[i];
1408 if (!empty_message(msg)) {
1413 for (i = 0; i < n_messages; i++) {
1414 struct message *msg = messages[i];
1415 if (empty_message(msg)) {
1416 msg->age = msg->shown = 0;
1418 if (msg->age && msg->age % 60 == 0) {
1419 msg->shown -= MAX(0, 5 - (load + 6) / 12);
1420 if (msg->shown < 0) {
1424 if (msg->age++ > 3600) {
1431 /* Set by SIGUSR1 handler. */
1432 static volatile sig_atomic_t sigusr1_triggered;
1434 /* The time after which we stop indicating that the switch is rebooting.
1435 * (This is just in case the reboot fails.) */
1436 static time_t reboot_deadline = TIME_MIN;
1438 static void sigusr1_handler(int);
1441 init_reboot_notifier(void)
1443 signal(SIGUSR1, sigusr1_handler);
1447 sigusr1_handler(int signr UNUSED)
1449 sigusr1_triggered = true;
1453 show_reboot_state(void)
1455 if (sigusr1_triggered) {
1456 reboot_deadline = time_now() + 30;
1457 sigusr1_triggered = false;
1459 if (time_now() < reboot_deadline) {
1460 static struct message *msg;
1461 emit(&msg, P_FATAL, "Rebooting");
1469 void (*f)(const struct dict *);
1476 struct menu_item **items;
1477 size_t n_items, allocated_items;
1480 static void menu_init(struct menu *);
1481 static void menu_free(struct menu *);
1482 static struct menu_item *menu_add_item(struct menu *, const char *text, ...)
1483 PRINTF_FORMAT(2, 3);
1484 static int menu_show(const struct menu *, int start, bool select);
1486 static void cmd_shell(const struct dict *);
1487 static void cmd_show_version(const struct dict *);
1488 static void cmd_configure(const struct dict *);
1489 static void cmd_setup_pki(const struct dict *);
1490 static void cmd_browse_status(const struct dict *);
1491 static void cmd_show_motto(const struct dict *);
1494 menu_init(struct menu *menu)
1496 memset(menu, 0, sizeof *menu);
1500 menu_free(struct menu *menu)
1504 for (i = 0; i < menu->n_items; i++) {
1505 struct menu_item *item = menu->items[i];
1512 static struct menu_item *
1513 menu_add_item(struct menu *menu, const char *text, ...)
1515 struct menu_item *item;
1518 if (menu->n_items >= menu->allocated_items) {
1519 menu->allocated_items = 2 * menu->allocated_items + 1;
1520 menu->items = xrealloc(menu->items,
1521 sizeof *menu->items * menu->allocated_items);
1523 item = menu->items[menu->n_items++] = xmalloc(sizeof *item);
1524 va_start(args, text);
1525 item->text = xvasprintf(text, args);
1529 item->enabled = true;
1535 menu(const struct dict *dict)
1537 bool debug_mode = dict_get_bool(dict, "debug", false);
1542 menu_add_item(&menu, "Exit");
1543 menu_add_item(&menu, "Show Version")->f = cmd_show_version;
1544 menu_add_item(&menu, "Configure")->f = cmd_configure;
1545 menu_add_item(&menu, "Setup PKI")->f = cmd_setup_pki;
1547 menu_add_item(&menu, "Browse Status")->f = cmd_browse_status;
1548 menu_add_item(&menu, "Shell")->f = cmd_shell;
1549 menu_add_item(&menu, "Show Motto")->f = cmd_show_motto;
1552 choice = menu_show(&menu, 0, true);
1554 void (*f)(const struct dict *) = menu.items[choice]->f;
1564 menu_show(const struct menu *menu, int start, bool select)
1566 long long int adjust = LLONG_MAX;
1567 int min = 0, max = MAX(menu->n_items - 2, 0);
1596 if (menu->n_items) {
1597 pos = MIN(menu->n_items - 1, MAX(0, start));
1606 while ((key = getch()) != ERR) {
1609 if (select && selection > 0) {
1611 if (selection >= pos) {
1621 if (select && selection < menu->n_items - 1) {
1623 if (selection <= pos + 1) {
1632 case '\r': case '\n':
1633 if (select && selection >= 0 && selection < menu->n_items) {
1634 struct menu_item *item = menu->items[selection];
1635 if (!item->enabled) {
1636 show_string("Item disabled");
1638 } else if (item->toggle >= 0) {
1639 item->toggle = !item->toggle;
1645 case '\b': case '\x7f': case '\x1b':
1646 case KEY_BACKSPACE: case KEY_DC:
1649 adjust = time_msec() + 1000;
1651 if (time_msec() >= adjust && menu->n_items > 1) {
1654 } else if (pos > max) {
1662 if (!menu->n_items) {
1666 for (idx = pos; idx < pos + 2; idx++) {
1671 if (selection == idx) {
1680 } else if (idx >= menu->n_items) {
1683 const struct menu_item *item = menu->items[idx];
1684 size_t length = strlen(item->text);
1685 if (!item->enabled) {
1689 if (item->toggle >= 0) {
1691 addch(icon_char(item->toggle ? 2 : 1, 0));
1694 addstr(item->toggle ? "[X]" : "[ ]");
1698 addnstr(item->text, MIN(width, length));
1699 if (!item->enabled) {
1710 if (pos < min || pos > max) {
1711 poll_timer_wait(adjust - time_msec());
1713 poll_fd_wait(STDIN_FILENO, POLLIN);
1719 menu_show2(const struct menu *menu, int start, bool select)
1722 if (menu->n_items) {
1723 pos = MIN(menu->n_items - 1, MAX(0, start));
1748 while ((key = getch()) != ERR) {
1757 if (menu->n_items > 0 && pos < menu->n_items - 1) {
1762 case '\r': case '\n':
1763 if (select && !menu->items[pos]->enabled) {
1764 show_string("Item disabled");
1769 case '\b': case '\x7f': case '\x1b':
1770 case KEY_BACKSPACE: case KEY_DC:
1781 const struct menu_item *item = menu->items[pos];
1782 const char *line1 = item->text;
1783 size_t len1 = strcspn(line1, "\n");
1784 const char *line2 = line1[len1] ? &line1[len1 + 1] : "";
1785 size_t len2 = strcspn(line2, "\n");
1786 size_t width = 39 - 2 * !item->enabled;
1789 addch(pos > 0 ? icon_char(0, '^') : ' ');
1790 if (!item->enabled && len1) {
1793 addnstr(line1, MIN(len1, width));
1794 if (!item->enabled && len1) {
1800 addch(pos < menu->n_items - 1 ? icon_char(1, 'V') : ' ');
1801 if (!item->enabled && len2) {
1804 addnstr(line2, MIN(len2, width));
1805 if (!item->enabled && len2) {
1811 poll_fd_wait(STDIN_FILENO, POLLIN);
1817 yesno(const char *title, bool def)
1834 while ((key = getch()) != ERR) {
1851 case '\r': case '\n':
1862 addch(answer ? icon_char(0, '>') : ' ');
1866 addch(!answer ? icon_char(0, '>') : ' ');
1871 poll_fd_wait(STDIN_FILENO, POLLIN);
1877 cmd_show_version(const struct dict *dict UNUSED)
1879 show_string(VERSION BUILDNR);
1883 cmd_browse_status(const struct dict *dict)
1889 for (i = 0; i < dict->n; i++) {
1890 const struct pair *p = &dict->pairs[i];
1891 menu_add_item(&menu, "%s = %s", p->name, p->value);
1893 menu_show(&menu, 0, false);
1898 cmd_shell(const struct dict *dict UNUSED)
1906 printf("Type ^D to exit\n");
1913 home = getenv("HOME");
1918 initialize_terminal();
1922 cmd_show_motto(const struct dict *dict UNUSED)
1924 show_string("\"Just Add Ice\"");
1928 show_string(const char *string)
1930 VLOG_INFO("%s", string);
1936 block_until(time_msec() + 5000);
1940 block_until(long long timeout)
1942 while (timeout > time_msec()) {
1943 poll_timer_wait(timeout - time_msec());
1946 drain_keyboard_buffer();
1950 drain_keyboard_buffer(void)
1952 while (getch() != ERR) {
1958 read_vars(const char *cmd, struct dict *dict)
1964 stream = popen(cmd, "r");
1966 VLOG_ERR("popen(\"%s\") failed: %s", cmd, strerror(errno));
1972 while (!ds_get_line(&ds, stream)) {
1973 const char *s = ds_cstr(&ds);
1974 const char *equals = strchr(s, '=');
1976 dict_add_nocopy(dict,
1977 xmemdup0(s, equals - s), xstrdup(equals + 1));
1980 status = pclose(stream);
1982 char *msg = process_status_msg(status);
1983 VLOG_ERR("pclose(\"%s\") reported subprocess failure: %s",
1993 run_and_report_failure(char **argv, const char *title)
1995 int null_fds[3] = {0, 1, 2};
2000 s = process_escape_args(argv);
2001 VLOG_INFO("starting subprocess: %s", s);
2004 retval = process_run(argv, NULL, 0, null_fds, 3, &status);
2006 char *s = xasprintf("%s:\n%s", title, strerror(retval));
2010 } else if (status) {
2011 char *msg = process_status_msg(status);
2012 char *s = xasprintf("%s:\n%s", title, msg);
2018 VLOG_INFO("subprocess exited with status 0");
2024 do_load_config(const char *file_name, struct dict *dict)
2026 struct dict auto_vars;
2031 /* Get the list of the variables that the shell sets automatically. */
2032 retval = read_vars("set -a && env", &auto_vars);
2037 /* Get the variables from 'file_name'. */
2038 cmd = xasprintf("set -a && . '%s' && env", file_name);
2039 retval = read_vars(cmd, dict);
2042 dict_free(&auto_vars);
2047 for (i = 0; i < auto_vars.n; i++) {
2048 dict_delete(dict, auto_vars.pairs[i].name);
2050 dict_free(&auto_vars);
2055 load_config(struct dict *dict)
2057 static const char default_file[] = "/etc/default/openflow-switch";
2058 int retval = do_load_config(default_file, dict);
2062 char *s = xasprintf("Cfg load failed:\n%s", strerror(retval));
2070 save_config(const struct svec *settings)
2076 VLOG_INFO("Saving configuration:");
2077 for (i = 0; i < settings->n; i++) {
2078 VLOG_INFO("%s", settings->names[i]);
2082 svec_add(&argv, "/usr/share/openvswitch/commands/reconfigure");
2083 svec_append(&argv, settings);
2084 svec_terminate(&argv);
2085 ok = run_and_report_failure(argv.names, "Save failed");
2087 long long int timeout = time_msec() + 5000;
2092 addstr("Saved.\nRestarting...");
2096 svec_add(&argv, "/bin/sh");
2097 svec_add(&argv, "-c");
2099 "/etc/init.d/openflow-switch restart >/dev/null 2>&1");
2100 svec_terminate(&argv);
2102 ok = run_and_report_failure(argv.names, "Restart failed");
2104 block_until(timeout);
2107 svec_destroy(&argv);
2110 VLOG_INFO("Save completed successfully");
2112 VLOG_WARN("Save failed");
2118 match(pcre *re, const char *string, int length)
2123 retval = pcre_exec(re, NULL, string, length, 0, PCRE_PARTIAL,
2124 ovec, ARRAY_SIZE(ovec));
2126 if (ovec[0] >= 0 && ovec[1] >= length) {
2127 /* 're' matched all of 'string'. */
2130 /* 're' matched the initial part of 'string' but not all of it. */
2131 return PCRE_ERROR_NOMATCH;
2139 figure_choices(pcre *re, struct ds *s, int pos, struct ds *choices)
2147 /* See whether the current string is a complete match. */
2148 if (!match(re, s->string, pos)) {
2149 ds_put_char(choices, '\n');
2152 /* Then try all the other possibilities. */
2154 ds_put_buffer(&tmp, s->string, pos);
2155 for (c = 0x20; c < 0x7f; c++) {
2156 ds_put_char(&tmp, c);
2157 retval = match(re, tmp.string, pos + 1);
2158 if (retval == PCRE_ERROR_PARTIAL || !retval) {
2159 ds_put_char(choices, c);
2165 if (!choices->length) {
2166 ds_put_char(choices, '\n');
2171 figure_completion(pcre *re, struct ds *s)
2177 /* See whether the current string is a complete match. */
2178 if (!match(re, s->string, s->length)) {
2181 for (c = 0x20; c < 0x7f; c++) {
2185 retval = match(re, s->string, s->length);
2188 if (retval == PCRE_ERROR_PARTIAL || !retval) {
2198 ds_put_char(s, found);
2202 #define OCTET_RE "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
2203 #define IP_RE "("OCTET_RE"\\."OCTET_RE"\\."OCTET_RE"\\."OCTET_RE")"
2207 "[1-9][0-9][0-9]|" \
2208 "[1-9][0-9][0-9][0-9]|" \
2209 "[1-5][0-9][0-9][0-9][0-9]|" \
2210 "6[1-4][0-9][0-9][0-9]|" \
2211 "65[1-4][0-9][0-9]|" \
2214 #define XOCTET_RE "[0-9A-F][0-9A-F]"
2216 XOCTET_RE":"XOCTET_RE":"XOCTET_RE":"\
2217 XOCTET_RE":"XOCTET_RE":"XOCTET_RE
2218 #define NUM100_TO_99999_RE \
2219 "([1-9][0-9][0-9]|" \
2220 "[1-9][0-9][0-9][0-9]|" \
2221 "[1-9][0-9][0-9][0-9][0-9])"
2222 #define NUM5_TO_99999_RE \
2225 "[1-9][0-9][0-9]|" \
2226 "[1-9][0-9][0-9][0-9]|" \
2227 "[1-9][0-9][0-9][0-9][0-9])"
2228 #define NUM1_TO_99999_RE \
2231 "[1-9][0-9][0-9]|" \
2232 "[1-9][0-9][0-9][0-9]|" \
2233 "[1-9][0-9][0-9][0-9][0-9])"
2236 prompt(const char *prompt, const char *initial, const char *pattern)
2258 re = pcre_compile(pattern, PCRE_ANCHORED, &error, &erroffset, NULL);
2260 VLOG_ERR("PCRE error for pattern \"%s\" at offset %d: %s",
2261 pattern, erroffset, error);
2262 return xstrdup(initial);
2265 retval = pcre_fullinfo(re, NULL, PCRE_INFO_OKPARTIAL, &okpartial);
2271 ds_put_cstr(&ds, initial);
2273 figure_choices(re, &ds, pos, &choices);
2274 p = memchr(choices.string, initial[0], choices.length);
2275 chidx = p ? p - choices.string : 0;
2279 while ((key = getch()) != ERR) {
2282 if (choices.length > 1) {
2283 if (++chidx >= choices.length) {
2286 ds.string[pos] = choices.string[chidx];
2287 ds_truncate(&ds, pos + 1);
2288 figure_completion(re, &ds);
2293 if (choices.length > 1) {
2295 chidx = choices.length - 1;
2297 ds.string[pos] = choices.string[chidx];
2298 ds_truncate(&ds, pos + 1);
2299 figure_completion(re, &ds);
2303 case '\r': case '\n':
2304 if (choices.string[chidx] == '\n') {
2305 ds_truncate(&ds, pos);
2306 return ds_cstr(&ds);
2308 if (pos >= ds.length) {
2310 ds_put_char(&ds, choices.string[chidx]);
2311 figure_choices(re, &ds, pos, &choices);
2313 figure_completion(re, &ds);
2316 figure_choices(re, &ds, pos, &choices);
2318 figure_completion(re, &ds);
2324 ds_truncate(&ds, pos + 1);
2325 figure_choices(re, &ds, pos, &choices);
2329 case '\b': case '\x7f': case '\x1b':
2330 case KEY_BACKSPACE: case KEY_DC:
2334 return xstrdup(initial);
2336 figure_choices(re, &ds, pos, &choices);
2338 if (pos < ds.length) {
2339 p = memchr(choices.string, ds.string[pos],
2342 chidx = p - choices.string;
2348 if (key >= 0x20 && key < 0x7f) {
2349 /* Check whether 'key' is valid and toggle case if
2351 if (!memchr(choices.string, key, choices.length)) {
2352 if (memchr(choices.string, toupper(key),
2355 } else if (memchr(choices.string, tolower(key),
2363 /* Insert 'key' and advance the position. */
2364 if (pos >= ds.length) {
2365 ds_put_char(&ds, key);
2367 ds.string[pos] = key;
2371 if (choices.string[chidx] != key) {
2372 ds_truncate(&ds, pos);
2374 figure_choices(re, &ds, pos, &choices);
2376 if (pos < ds.length) {
2377 p = memchr(choices.string, ds.string[pos],
2380 chidx = p - choices.string;
2383 figure_completion(re, &ds);
2391 addnstr(prompt, MIN(40, strlen(prompt)));
2393 c = choices.string[chidx];
2395 addstr(ds_cstr(&ds));
2405 poll_fd_wait(STDIN_FILENO, POLLIN);
2411 prompt_ip(const char *title, uint32_t *ip)
2413 char *in = xasprintf(IP_FMT, IP_ARGS(ip));
2414 char *out = prompt(title, in, "^"IP_RE"$");
2415 *ip = inet_addr(out);
2421 abbreviate_netdevs(const struct svec *netdevs, struct ds *abbrev)
2426 for (i = 0; i < netdevs->n; ) {
2427 size_t i_len = strlen(netdevs->names[i]);
2430 for (j = i + 1; j < netdevs->n; j++) {
2431 size_t j_len = strlen(netdevs->names[j]);
2432 if (!i_len || !j_len || i_len != j_len
2433 || memcmp(netdevs->names[i], netdevs->names[j], i_len - 1)) {
2438 if (abbrev->length) {
2439 ds_put_char(abbrev, ' ');
2442 ds_put_cstr(abbrev, netdevs->names[i]);
2446 ds_put_buffer(abbrev, netdevs->names[i], i_len - 1);
2447 ds_put_char(abbrev, '[');
2448 for (k = i; k < j; k++) {
2449 ds_put_char(abbrev, netdevs->names[k][i_len - 1]);
2451 ds_put_char(abbrev, ']');
2458 choose_netdevs(struct svec *choices)
2460 struct svec netdevs;
2464 netdev_enumerate(&netdevs);
2465 svec_sort(&netdevs);
2468 menu_add_item(&menu, "Exit");
2469 for (i = 0; i < netdevs.n; i++) {
2470 const char *name = netdevs.names[i];
2471 struct menu_item *item;
2472 struct netdev *netdev;
2475 if (!strncmp(name, "wmaster", strlen("wmaster"))
2476 || !strncmp(name, "of", strlen("of"))
2477 || !strcmp(name, "lo")) {
2481 retval = netdev_open(name, NETDEV_ETH_TYPE_NONE, &netdev);
2483 bool exclude = netdev_get_in4(netdev, NULL, NULL);
2484 netdev_close(netdev);
2490 item = menu_add_item(&menu, "%s", name);
2491 item->toggle = svec_contains(choices, name);
2493 if (menu.n_items > 1) {
2494 menu_show(&menu, 0, true);
2496 show_string("No available\nbridge ports");
2499 svec_clear(choices);
2500 for (i = 0; i < menu.n_items; i++) {
2501 struct menu_item *item = menu.items[i];
2502 if (item->toggle > 0) {
2503 svec_add(choices, item->text);
2511 is_datapath_id_in_dmi(void)
2517 dmidecode = popen("dmidecode -s system-uuid", "r");
2521 is_in_dmi = fgets(line, sizeof line, dmidecode) && strstr(line, "-002320");
2526 struct switch_config {
2527 struct svec netdevs;
2528 enum { DISCOVERY, IN_BAND } mode;
2530 uint32_t switch_mask;
2532 enum { FAIL_DROP, FAIL_SWITCH } disconnected;
2535 int inactivity_probe;
2537 char *controller_vconn;
2542 disconnected_string(int value)
2544 #define FAIL_SWITCH_STRING "Switch packets"
2545 #define FAIL_DROP_STRING "Drop packets"
2546 return value == FAIL_SWITCH ? FAIL_SWITCH_STRING : FAIL_DROP_STRING;
2550 cmd_configure(const struct dict *dict UNUSED)
2552 bool debug_mode = dict_get_bool(dict, "debug", false);
2553 struct dict config_dict;
2554 struct switch_config config;
2557 if (!load_config(&config_dict)) {
2560 svec_init(&config.netdevs);
2561 svec_parse_words(&config.netdevs,
2562 dict_get_string(&config_dict, "NETDEVS", ""));
2563 config.mode = (!strcmp(dict_get_string(&config_dict, "MODE", "discovery"),
2564 "in-band") ? IN_BAND : DISCOVERY);
2565 config.switch_ip = dict_get_ip(&config_dict, "SWITCH_IP");
2566 config.switch_mask = dict_get_ip(&config_dict, "SWITCH_NETMASK");
2567 config.switch_gw = dict_get_ip(&config_dict, "SWITCH_GATEWAY");
2568 config.controller_vconn = xstrdup(dict_get_string(&config_dict,
2570 config.disconnected = (!strcmp(dict_get_string(&config_dict,
2571 "DISCONNECTED_MODE", ""),
2573 ? FAIL_SWITCH : FAIL_DROP);
2574 config.stp = !strcmp(dict_get_string(&config_dict, "stp", ""), "yes");
2575 config.rate_limit = dict_get_int(&config_dict, "RATE_LIMIT", -1);
2576 config.inactivity_probe = dict_get_int(&config_dict, "INACTIVITY_PROBE",
2578 config.max_backoff = dict_get_int(&config_dict, "MAX_BACKOFF", -1);
2579 if (is_datapath_id_in_dmi()) {
2580 config.datapath_id = xstrdup("DMI");
2582 const char *dpid = dict_get(&config_dict, "DATAPATH_ID");
2584 struct ds ds = DS_EMPTY_INITIALIZER;
2586 for (cp = dpid; *cp != '\0'; cp++) {
2588 ds_put_char(&ds, toupper((unsigned char) *cp));
2591 config.datapath_id = ds_cstr(&ds);
2593 config.datapath_id = xstrdup("Random");
2596 dict_free(&config_dict);
2599 while (start != -1) {
2608 MENU_DISCONNECTED_MODE,
2612 MENU_INACTIVITY_PROBE,
2617 struct menu_item *item;
2625 item = menu_add_item(&menu, "Exit");
2626 item->id = MENU_EXIT;
2629 abbreviate_netdevs(&config.netdevs, &ports);
2630 item = menu_add_item(&menu, "Bridge Ports:\n%s", ds_cstr(&ports));
2631 item->id = MENU_NETDEVS;
2635 item = menu_add_item(&menu, "Mode:\n%s",
2636 (config.mode == DISCOVERY
2637 ? "Discovery" : "In-Band"));
2638 item->id = MENU_MODE;
2641 if (config.switch_ip == htonl(0)) {
2642 item = menu_add_item(&menu, "Switch IP Addr:\nDHCP");
2644 item = menu_add_item(&menu, "Switch IP Addr:\n"IP_FMT,
2645 IP_ARGS(&config.switch_ip));
2648 item->enabled = config.mode == IN_BAND;
2651 item = menu_add_item(&menu, "Switch Netmask:\n"IP_FMT,
2652 IP_ARGS(&config.switch_mask));
2653 item->id = MENU_NETMASK;
2654 item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2657 item = menu_add_item(&menu, "Switch Gateway:\n"IP_FMT,
2658 IP_ARGS(&config.switch_gw));
2659 item->id = MENU_GATEWAY;
2660 item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2663 item = menu_add_item(&menu, "Controller:\n%s",
2664 config.controller_vconn);
2665 item->id = MENU_CONTROLLER;
2666 item->enabled = config.mode == IN_BAND;
2668 /* Disconnected mode. */
2669 item = menu_add_item(&menu, "If disconnected:\n%s\n",
2670 disconnected_string(config.disconnected));
2671 item->id = MENU_DISCONNECTED_MODE;
2674 item = menu_add_item(&menu, "Datapath ID:\n%s", config.datapath_id);
2675 item->id = MENU_DATAPATH_ID;
2676 item->enabled = strcmp(config.datapath_id, "DMI");
2678 /* Spanning tree protocol. */
2680 item = menu_add_item(&menu, "802.1D-1998 STP:\n%s",
2681 config.stp ? "Enabled" : "Disabled");
2682 item->id = MENU_STP;
2685 /* Rate-limiting. */
2687 if (config.rate_limit < 0) {
2688 item = menu_add_item(&menu, "Ctlr rate limit:\nDisabled");
2690 item = menu_add_item(&menu, "Ctlr rate limit:\n%d/s",
2693 item->id = MENU_RATE_LIMIT;
2696 /* Inactivity probe. */
2698 if (config.inactivity_probe < 0) {
2699 item = menu_add_item(&menu, "Activity probe:\nDefault");
2701 item = menu_add_item(&menu, "Activity probe:\n%d s",
2702 config.inactivity_probe);
2704 item->id = MENU_INACTIVITY_PROBE;
2709 if (config.max_backoff < 0) {
2710 item = menu_add_item(&menu, "Max backoff:\nDefault");
2712 item = menu_add_item(&menu, "Max backoff:\n%d s",
2713 config.max_backoff);
2715 item->id = MENU_MAX_BACKOFF;
2718 start = menu_show2(&menu, start, true);
2728 choose_netdevs(&config.netdevs);
2732 out = prompt("Mode:",
2733 config.mode == DISCOVERY ? "Discovery" : "In-Band",
2734 "^(Discovery|In-Band)$");
2735 config.mode = !strcmp(out, "Discovery") ? DISCOVERY : IN_BAND;
2740 in = (config.switch_ip == htonl(0) ? xstrdup("DHCP")
2741 : xasprintf(IP_FMT, IP_ARGS(&config.switch_ip)));
2742 out = prompt("Switch IP:", in, "^(DHCP|"IP_RE")$");
2743 ip = strcmp(out, "DHCP") ? inet_addr(out) : htonl(0);
2746 if (ip != config.switch_ip) {
2747 config.switch_ip = ip;
2748 if (ip != htonl(0)) {
2749 uint32_t mask = guess_netmask(ip);
2751 config.switch_mask = mask;
2752 config.switch_gw = (ip & mask) | htonl(1);
2759 prompt_ip("Switch Netmask:", &config.switch_mask);
2763 prompt_ip("Switch Gateway:", &config.switch_gw);
2766 case MENU_CONTROLLER:
2767 out = prompt("Controller:", config.controller_vconn,
2768 "^(tcp|ssl):"IP_RE"(:"PORT_RE")?$");
2769 free(config.controller_vconn);
2770 config.controller_vconn = out;
2773 case MENU_DISCONNECTED_MODE:
2774 out = prompt("If disconnected",
2775 disconnected_string(config.disconnected),
2776 "^("FAIL_DROP_STRING"|"FAIL_SWITCH_STRING")$");
2777 config.disconnected = (!strcmp(out, FAIL_DROP_STRING)
2778 ? FAIL_DROP : FAIL_SWITCH);
2782 case MENU_DATAPATH_ID:
2783 out = prompt("Datapath ID:", config.datapath_id,
2784 "^Random|"MAC_RE"$");
2785 free(config.datapath_id);
2786 config.datapath_id = out;
2790 out = prompt("802.1D-1998 STP:",
2791 config.stp ? "Enabled" : "Disabled",
2792 "^(Enabled|Disabled)$");
2793 config.stp = !strcmp(out, "Enabled");
2797 case MENU_RATE_LIMIT:
2798 in = (config.rate_limit < 0
2799 ? xstrdup("Disabled")
2800 : xasprintf("%d/s", config.rate_limit));
2801 out = prompt("Ctlr rate limit:", in,
2802 "^(Disabled|("NUM100_TO_99999_RE")/s)$");
2804 config.rate_limit = isdigit(out[0]) ? atoi(out) : -1;
2808 case MENU_INACTIVITY_PROBE:
2809 in = (config.inactivity_probe < 0
2810 ? xstrdup("Default")
2811 : xasprintf("%d s", config.inactivity_probe));
2812 out = prompt("Activity probe:", in,
2813 "^(Default|("NUM5_TO_99999_RE") s)$");
2815 config.inactivity_probe = isdigit(out[0]) ? atoi(out) : -1;
2819 case MENU_MAX_BACKOFF:
2820 in = (config.max_backoff < 0
2821 ? xstrdup("Default")
2822 : xasprintf("%d s", config.max_backoff));
2823 out = prompt("Max backoff:", in,
2824 "^(Default|("NUM1_TO_99999_RE") s)$");
2826 config.max_backoff = isdigit(out[0]) ? atoi(out) : -1;
2832 if (yesno("Save\nChanges?", false)) {
2837 netdevs = svec_join(&config.netdevs, " ", "");
2838 svec_add_nocopy(&set, xasprintf("NETDEVS=%s", netdevs));
2841 config.mode == IN_BAND ? "MODE=in-band" : "MODE=discovery");
2842 if (config.mode == IN_BAND) {
2843 if (config.switch_ip == htonl(0)) {
2844 svec_add(&set, "SWITCH_IP=dhcp");
2846 svec_add_nocopy(&set, xasprintf("SWITCH_IP="IP_FMT,
2847 IP_ARGS(&config.switch_ip)));
2848 svec_add_nocopy(&set,
2849 xasprintf("SWITCH_NETMASK="IP_FMT,
2850 IP_ARGS(&config.switch_mask)));
2851 svec_add_nocopy(&set, xasprintf("SWITCH_GATEWAY="IP_FMT,
2852 IP_ARGS(&config.switch_gw)));
2853 svec_add_nocopy(&set, xasprintf("CONTROLLER=%s",
2854 config.controller_vconn));
2857 svec_add(&set, (config.disconnected == FAIL_DROP
2858 ? "DISCONNECTED_MODE=drop"
2859 : "DISCONNECTED_MODE=switch"));
2860 svec_add_nocopy(&set, xasprintf("STP=%s", config.stp ? "yes" : "no"));
2861 if (config.rate_limit < 0) {
2862 svec_add(&set, "RATE_LIMIT=");
2864 svec_add_nocopy(&set,
2865 xasprintf("RATE_LIMIT=%d", config.rate_limit));
2867 if (config.inactivity_probe < 0) {
2868 svec_add(&set, "INACTIVITY_PROBE=");
2870 svec_add_nocopy(&set, xasprintf("INACTIVITY_PROBE=%d",
2871 config.inactivity_probe));
2873 if (config.max_backoff < 0) {
2874 svec_add(&set, "MAX_BACKOFF=");
2876 svec_add_nocopy(&set, xasprintf("MAX_BACKOFF=%d",
2877 config.max_backoff));
2883 svec_destroy(&config.netdevs);
2884 free(config.controller_vconn);
2885 free(config.datapath_id);
2889 cmd_setup_pki(const struct dict *dict UNUSED)
2891 static const char def_privkey_file[]
2892 = "/etc/openflow-switch/of0-privkey.pem";
2893 static const char def_cert_file[] = "/etc/openflow-switch/of0-cert.pem";
2894 static const char def_cacert_file[] = "/etc/openflow-switch/cacert.pem";
2895 struct dict config_dict;
2896 const char *privkey_file, *cert_file, *cacert_file;
2902 if (!load_config(&config_dict)) {
2905 privkey_file = dict_get_string(&config_dict, "PRIVKEY", def_privkey_file);
2906 cert_file = dict_get_string(&config_dict, "CERT", def_cert_file);
2907 cacert_file = dict_get_string(&config_dict, "CACERT", def_cacert_file);
2908 bootstrap = !strcmp(dict_get_string(&config_dict, "CACERT_MODE", "secure"),
2911 has_keys = !stat(privkey_file, &s) && !stat(cert_file, &s);
2913 ? yesno("Generate\nkeys?", true)
2914 : yesno("Generate\nnew keys?", false)) {
2918 privkey_file = def_privkey_file;
2919 cert_file = def_cert_file;
2922 svec_parse_words(&argv, "sh -c 'cd /etc/openflow-switch "
2923 "&& ovs-pki --force req of0"
2924 "&& ovs-pki --force self-sign of0'");
2925 svec_terminate(&argv);
2926 ok = run_and_report_failure(argv.names, "Key gen failed");
2927 svec_destroy(&argv);
2937 if (stat(cacert_file, &s) && errno == ENOENT) {
2938 bootstrap = yesno("Bootstrap\nCA cert?", bootstrap);
2939 } else if (yesno("Replace\nCA cert?", false)) {
2940 unlink(cacert_file);
2945 svec_add_nocopy(&set, xasprintf("PRIVKEY=%s", privkey_file));
2946 svec_add_nocopy(&set, xasprintf("CERT=%s", cert_file));
2947 svec_add_nocopy(&set, xasprintf("CACERT=%s", cacert_file));
2948 svec_add_nocopy(&set, xasprintf("CACERT_MODE=%s",
2949 bootstrap ? "bootstrap" : "secure"));
2955 parse_options(int argc, char *argv[])
2958 OPT_DUMMY = UCHAR_MAX + 1,
2961 static struct option long_options[] = {
2962 {"verbose", optional_argument, 0, 'v'},
2963 {"help", no_argument, 0, 'h'},
2964 {"version", no_argument, 0, 'V'},
2965 DAEMON_LONG_OPTIONS,
2969 char *short_options = long_options_to_short_options(long_options);
2974 c = getopt_long(argc, argv, short_options, long_options, NULL);
2984 OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
2987 VLOG_OPTION_HANDLERS
2988 DAEMON_OPTION_HANDLERS
2997 free(short_options);
3003 printf("%s: OpenFlow switch monitoring user interface\n"
3004 "usage: %s [OPTIONS] SWITCH\n"
3005 "where SWITCH is an active OpenFlow connection method.\n",
3006 program_name, program_name);
3007 vconn_usage(true, false, false);
3008 printf("\nOptions:\n"
3009 " -v, --verbose=MODULE:FACILITY:LEVEL configure logging levels\n"
3010 " -v, --verbose set maximum verbosity level\n"
3011 " -h, --help display this help message\n"
3012 " -V, --version display version information\n");