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 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_ofproto_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_ofproto_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;
1107 struct ofp_port_stats_request *psr;
1110 rates->xid = random_uint32();
1111 rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
1113 rq->type = htons(OFPST_PORT);
1114 rq->flags = htons(0);
1115 psr = ofbuf_put_uninit(b, sizeof *psr);
1116 memset(psr, 0, sizeof *psr);
1117 psr->port_no = htons(OFPP_NONE);
1118 update_openflow_length(b);
1119 rconn_send_with_limit(rates->rconn, b, counter, 10);
1122 if (!rates->got_reply) {
1125 rconn_run(rates->rconn);
1126 for (i = 0; i < 50; i++) {
1129 b = rconn_recv(rates->rconn);
1134 parse_port_reply(b->data, rates);
1136 if (rates->got_reply) {
1170 memset(graph, 0, sizeof graph);
1183 if (rates->now.tx_bytes != UINT64_MAX
1184 && rates->prev.tx_bytes != UINT64_MAX
1185 && rates->now.when - rates->prev.when > 500
1186 && time_msec() - rates->now.when < 2000)
1188 uint64_t bits = (rates->now.tx_bytes - rates->prev.tx_bytes) * 8;
1189 uint64_t msecs = rates->now.when - rates->prev.when;
1190 double bps = (double) bits * 1000.0 / msecs;
1191 int pixels = bps > 0 ? log(bps) / log(10.0) * 8 + .5 : 0;
1194 } else if (pixels > 80) {
1197 memset(graph, 1, pixels);
1202 if (!rates->got_reply) {
1203 rconn_run_wait(rates->rconn);
1204 rconn_recv_wait(rates->rconn);
1209 show_data_rates(struct rconn *rconn, const struct dict *dict)
1211 static struct message *m;
1212 static struct show_rates_data rates;
1213 const char *is_connected, *local_ip;
1214 static bool inited = false;
1216 dict_lookup(dict, "local.is-connected", &is_connected);
1217 dict_lookup(dict, "remote.local-ip", &local_ip);
1218 if (!is_connected && !local_ip) {
1219 /* If we're not connected to the datapath and don't have a local IP,
1220 * then we won't have anything useful to show anyhow. */
1224 rates.rconn = rconn;
1226 rates.got_reply = false;
1228 rates.now.tx_bytes = UINT64_MAX;
1229 rates.prev.tx_bytes = UINT64_MAX;
1232 emit_function(&m, P_STATUS, do_show_data_rates, &rates);
1237 void (*function)(void *aux);
1242 enum priority priority;
1247 static struct message **messages;
1248 static size_t n_messages, allocated_messages;
1250 static struct message *
1251 allocate_message(struct message **msgp)
1254 /* Allocate and initialize message. */
1255 *msgp = xcalloc(1, sizeof **msgp);
1256 (*msgp)->index = n_messages;
1258 /* Add to list of messages. */
1259 if (n_messages >= allocated_messages) {
1260 allocated_messages = 2 * allocated_messages + 1;
1261 messages = xrealloc(messages,
1262 sizeof *messages * allocated_messages);
1264 messages[n_messages++] = *msgp;
1270 emit(struct message **msgp, enum priority priority, const char *format, ...)
1272 struct message *msg = allocate_message(msgp);
1276 msg->priority = priority;
1278 va_start(args, format);
1279 length = strlen(msg->string);
1280 vsnprintf(msg->string + length, sizeof msg->string - length, format, args);
1285 emit_function(struct message **msgp, enum priority priority,
1286 void (*function)(void *aux), void *aux)
1288 struct message *msg = allocate_message(msgp);
1289 msg->priority = priority;
1290 msg->function = function;
1295 shown(struct message **msgp)
1297 struct message *msg = allocate_message(msgp);
1302 clear_messages(void)
1306 for (i = 0; i < n_messages; i++) {
1307 struct message *msg = messages[i];
1308 msg->string[0] = '\0';
1309 msg->function = NULL;
1313 static struct message *
1316 struct message *best_msg;
1320 best_score = INT_MIN;
1322 for (i = 0; i < n_messages; i++) {
1323 struct message *msg = messages[i];
1326 if (empty_message(msg)) {
1330 score = msg->priority;
1334 score -= msg->shown;
1336 if (score > best_score) {
1345 message_shown(struct message *msg)
1347 if (msg && msg->shown++ > 3600) {
1353 empty_message(const struct message *msg)
1355 return !msg || (!msg->string[0] && !msg->function);
1358 static struct message *get_message(size_t index)
1360 assert(index <= n_messages || index == SIZE_MAX);
1361 return (index < n_messages ? messages[index]
1362 : index == SIZE_MAX ? messages[n_messages - 1]
1366 static struct message *
1367 next_message(struct message *msg)
1371 for (p = get_message(msg->index + 1); p != msg;
1372 p = get_message(p->index + 1)) {
1373 if (!empty_message(p)) {
1380 static struct message *
1381 prev_message(struct message *msg)
1385 for (p = get_message(msg->index - 1); p != msg;
1386 p = get_message(p->index - 1)) {
1387 if (!empty_message(p)) {
1395 put_message(const struct message *m)
1399 } else if (m->function) {
1400 m->function(m->aux);
1411 for (i = 0; i < n_messages; i++) {
1412 struct message *msg = messages[i];
1413 if (!empty_message(msg)) {
1418 for (i = 0; i < n_messages; i++) {
1419 struct message *msg = messages[i];
1420 if (empty_message(msg)) {
1421 msg->age = msg->shown = 0;
1423 if (msg->age && msg->age % 60 == 0) {
1424 msg->shown -= MAX(0, 5 - (load + 6) / 12);
1425 if (msg->shown < 0) {
1429 if (msg->age++ > 3600) {
1436 /* Set by SIGUSR1 handler. */
1437 static volatile sig_atomic_t sigusr1_triggered;
1439 /* The time after which we stop indicating that the switch is rebooting.
1440 * (This is just in case the reboot fails.) */
1441 static time_t reboot_deadline = TIME_MIN;
1443 static void sigusr1_handler(int);
1446 init_reboot_notifier(void)
1448 signal(SIGUSR1, sigusr1_handler);
1452 sigusr1_handler(int signr UNUSED)
1454 sigusr1_triggered = true;
1458 show_reboot_state(void)
1460 if (sigusr1_triggered) {
1461 reboot_deadline = time_now() + 30;
1462 sigusr1_triggered = false;
1464 if (time_now() < reboot_deadline) {
1465 static struct message *msg;
1466 emit(&msg, P_FATAL, "Rebooting");
1474 void (*f)(const struct dict *);
1481 struct menu_item **items;
1482 size_t n_items, allocated_items;
1485 static void menu_init(struct menu *);
1486 static void menu_free(struct menu *);
1487 static struct menu_item *menu_add_item(struct menu *, const char *text, ...)
1488 PRINTF_FORMAT(2, 3);
1489 static int menu_show(const struct menu *, int start, bool select);
1491 static void cmd_shell(const struct dict *);
1492 static void cmd_show_version(const struct dict *);
1493 static void cmd_configure(const struct dict *);
1494 static void cmd_set_up_pki(const struct dict *);
1495 static void cmd_browse_status(const struct dict *);
1496 static void cmd_show_motto(const struct dict *);
1499 menu_init(struct menu *menu)
1501 memset(menu, 0, sizeof *menu);
1505 menu_free(struct menu *menu)
1509 for (i = 0; i < menu->n_items; i++) {
1510 struct menu_item *item = menu->items[i];
1517 static struct menu_item *
1518 menu_add_item(struct menu *menu, const char *text, ...)
1520 struct menu_item *item;
1523 if (menu->n_items >= menu->allocated_items) {
1524 menu->allocated_items = 2 * menu->allocated_items + 1;
1525 menu->items = xrealloc(menu->items,
1526 sizeof *menu->items * menu->allocated_items);
1528 item = menu->items[menu->n_items++] = xmalloc(sizeof *item);
1529 va_start(args, text);
1530 item->text = xvasprintf(text, args);
1534 item->enabled = true;
1540 menu(const struct dict *dict)
1542 bool debug_mode = dict_get_bool(dict, "debug", false);
1547 menu_add_item(&menu, "Exit");
1548 menu_add_item(&menu, "Show Version")->f = cmd_show_version;
1549 menu_add_item(&menu, "Configure")->f = cmd_configure;
1550 menu_add_item(&menu, "Set up PKI")->f = cmd_set_up_pki;
1552 menu_add_item(&menu, "Browse Status")->f = cmd_browse_status;
1553 menu_add_item(&menu, "Shell")->f = cmd_shell;
1554 menu_add_item(&menu, "Show Motto")->f = cmd_show_motto;
1557 choice = menu_show(&menu, 0, true);
1559 void (*f)(const struct dict *) = menu.items[choice]->f;
1569 menu_show(const struct menu *menu, int start, bool select)
1571 long long int adjust = LLONG_MAX;
1572 int min = 0, max = MAX(menu->n_items - 2, 0);
1601 if (menu->n_items) {
1602 pos = MIN(menu->n_items - 1, MAX(0, start));
1611 while ((key = getch()) != ERR) {
1614 if (select && selection > 0) {
1616 if (selection >= pos) {
1626 if (select && selection < menu->n_items - 1) {
1628 if (selection <= pos + 1) {
1637 case '\r': case '\n':
1638 if (select && selection >= 0 && selection < menu->n_items) {
1639 struct menu_item *item = menu->items[selection];
1640 if (!item->enabled) {
1641 show_string("Item disabled");
1643 } else if (item->toggle >= 0) {
1644 item->toggle = !item->toggle;
1650 case '\b': case '\x7f': case '\x1b':
1651 case KEY_BACKSPACE: case KEY_DC:
1654 adjust = time_msec() + 1000;
1656 if (time_msec() >= adjust && menu->n_items > 1) {
1659 } else if (pos > max) {
1667 if (!menu->n_items) {
1671 for (idx = pos; idx < pos + 2; idx++) {
1676 if (selection == idx) {
1685 } else if (idx >= menu->n_items) {
1688 const struct menu_item *item = menu->items[idx];
1689 size_t length = strlen(item->text);
1690 if (!item->enabled) {
1694 if (item->toggle >= 0) {
1696 addch(icon_char(item->toggle ? 2 : 1, 0));
1699 addstr(item->toggle ? "[X]" : "[ ]");
1703 addnstr(item->text, MIN(width, length));
1704 if (!item->enabled) {
1715 if (pos < min || pos > max) {
1716 poll_timer_wait(adjust - time_msec());
1718 poll_fd_wait(STDIN_FILENO, POLLIN);
1724 menu_show2(const struct menu *menu, int start, bool select)
1727 if (menu->n_items) {
1728 pos = MIN(menu->n_items - 1, MAX(0, start));
1753 while ((key = getch()) != ERR) {
1762 if (menu->n_items > 0 && pos < menu->n_items - 1) {
1767 case '\r': case '\n':
1768 if (select && !menu->items[pos]->enabled) {
1769 show_string("Item disabled");
1774 case '\b': case '\x7f': case '\x1b':
1775 case KEY_BACKSPACE: case KEY_DC:
1786 const struct menu_item *item = menu->items[pos];
1787 const char *line1 = item->text;
1788 size_t len1 = strcspn(line1, "\n");
1789 const char *line2 = line1[len1] ? &line1[len1 + 1] : "";
1790 size_t len2 = strcspn(line2, "\n");
1791 size_t width = 39 - 2 * !item->enabled;
1794 addch(pos > 0 ? icon_char(0, '^') : ' ');
1795 if (!item->enabled && len1) {
1798 addnstr(line1, MIN(len1, width));
1799 if (!item->enabled && len1) {
1805 addch(pos < menu->n_items - 1 ? icon_char(1, 'V') : ' ');
1806 if (!item->enabled && len2) {
1809 addnstr(line2, MIN(len2, width));
1810 if (!item->enabled && len2) {
1816 poll_fd_wait(STDIN_FILENO, POLLIN);
1822 yesno(const char *title, bool def)
1839 while ((key = getch()) != ERR) {
1856 case '\r': case '\n':
1867 addch(answer ? icon_char(0, '>') : ' ');
1871 addch(!answer ? icon_char(0, '>') : ' ');
1876 poll_fd_wait(STDIN_FILENO, POLLIN);
1882 cmd_show_version(const struct dict *dict UNUSED)
1884 show_string(VERSION BUILDNR);
1888 cmd_browse_status(const struct dict *dict)
1894 for (i = 0; i < dict->n; i++) {
1895 const struct pair *p = &dict->pairs[i];
1896 menu_add_item(&menu, "%s = %s", p->name, p->value);
1898 menu_show(&menu, 0, false);
1903 cmd_shell(const struct dict *dict UNUSED)
1911 printf("Type ^D to exit\n");
1918 home = getenv("HOME");
1923 initialize_terminal();
1927 cmd_show_motto(const struct dict *dict UNUSED)
1929 show_string("\"Just Add Ice\"");
1933 show_string(const char *string)
1935 VLOG_INFO("%s", string);
1941 block_until(time_msec() + 5000);
1945 block_until(long long timeout)
1947 while (timeout > time_msec()) {
1948 poll_timer_wait(timeout - time_msec());
1951 drain_keyboard_buffer();
1955 drain_keyboard_buffer(void)
1957 while (getch() != ERR) {
1963 read_vars(const char *cmd, struct dict *dict)
1969 stream = popen(cmd, "r");
1971 VLOG_ERR("popen(\"%s\") failed: %s", cmd, strerror(errno));
1977 while (!ds_get_line(&ds, stream)) {
1978 const char *s = ds_cstr(&ds);
1979 const char *equals = strchr(s, '=');
1981 dict_add_nocopy(dict,
1982 xmemdup0(s, equals - s), xstrdup(equals + 1));
1985 status = pclose(stream);
1987 char *msg = process_status_msg(status);
1988 VLOG_ERR("pclose(\"%s\") reported subprocess failure: %s",
1998 run_and_report_failure(char **argv, const char *title)
2000 int null_fds[3] = {0, 1, 2};
2005 s = process_escape_args(argv);
2006 VLOG_INFO("starting subprocess: %s", s);
2009 retval = process_run(argv, NULL, 0, null_fds, 3, &status);
2011 char *s = xasprintf("%s:\n%s", title, strerror(retval));
2015 } else if (status) {
2016 char *msg = process_status_msg(status);
2017 char *s = xasprintf("%s:\n%s", title, msg);
2023 VLOG_INFO("subprocess exited with status 0");
2029 do_load_config(const char *file_name, struct dict *dict)
2031 struct dict auto_vars;
2036 /* Get the list of the variables that the shell sets automatically. */
2037 retval = read_vars("set -a && env", &auto_vars);
2042 /* Get the variables from 'file_name'. */
2043 cmd = xasprintf("set -a && . '%s' && env", file_name);
2044 retval = read_vars(cmd, dict);
2047 dict_free(&auto_vars);
2052 for (i = 0; i < auto_vars.n; i++) {
2053 dict_delete(dict, auto_vars.pairs[i].name);
2055 dict_free(&auto_vars);
2060 load_config(struct dict *dict)
2062 static const char default_file[] = "/etc/default/openflow-switch";
2063 int retval = do_load_config(default_file, dict);
2067 char *s = xasprintf("Cfg load failed:\n%s", strerror(retval));
2075 save_config(const struct svec *settings)
2081 VLOG_INFO("Saving configuration:");
2082 for (i = 0; i < settings->n; i++) {
2083 VLOG_INFO("%s", settings->names[i]);
2087 svec_add(&argv, "/usr/share/openvswitch/commands/reconfigure");
2088 svec_append(&argv, settings);
2089 svec_terminate(&argv);
2090 ok = run_and_report_failure(argv.names, "Save failed");
2092 long long int timeout = time_msec() + 5000;
2097 addstr("Saved.\nRestarting...");
2101 svec_add(&argv, "/bin/sh");
2102 svec_add(&argv, "-c");
2104 "/etc/init.d/openflow-switch restart >/dev/null 2>&1");
2105 svec_terminate(&argv);
2107 ok = run_and_report_failure(argv.names, "Restart failed");
2109 block_until(timeout);
2112 svec_destroy(&argv);
2115 VLOG_INFO("Save completed successfully");
2117 VLOG_WARN("Save failed");
2123 match(pcre *re, const char *string, int length)
2128 retval = pcre_exec(re, NULL, string, length, 0, PCRE_PARTIAL,
2129 ovec, ARRAY_SIZE(ovec));
2131 if (ovec[0] >= 0 && ovec[1] >= length) {
2132 /* 're' matched all of 'string'. */
2135 /* 're' matched the initial part of 'string' but not all of it. */
2136 return PCRE_ERROR_NOMATCH;
2144 figure_choices(pcre *re, struct ds *s, int pos, struct ds *choices)
2152 /* See whether the current string is a complete match. */
2153 if (!match(re, s->string, pos)) {
2154 ds_put_char(choices, '\n');
2157 /* Then try all the other possibilities. */
2159 ds_put_buffer(&tmp, s->string, pos);
2160 for (c = 0x20; c < 0x7f; c++) {
2161 ds_put_char(&tmp, c);
2162 retval = match(re, tmp.string, pos + 1);
2163 if (retval == PCRE_ERROR_PARTIAL || !retval) {
2164 ds_put_char(choices, c);
2170 if (!choices->length) {
2171 ds_put_char(choices, '\n');
2176 figure_completion(pcre *re, struct ds *s)
2182 /* See whether the current string is a complete match. */
2183 if (!match(re, s->string, s->length)) {
2186 for (c = 0x20; c < 0x7f; c++) {
2190 retval = match(re, s->string, s->length);
2193 if (retval == PCRE_ERROR_PARTIAL || !retval) {
2203 ds_put_char(s, found);
2207 #define OCTET_RE "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
2208 #define IP_RE "("OCTET_RE"\\."OCTET_RE"\\."OCTET_RE"\\."OCTET_RE")"
2212 "[1-9][0-9][0-9]|" \
2213 "[1-9][0-9][0-9][0-9]|" \
2214 "[1-5][0-9][0-9][0-9][0-9]|" \
2215 "6[1-4][0-9][0-9][0-9]|" \
2216 "65[1-4][0-9][0-9]|" \
2219 #define XOCTET_RE "[0-9A-F][0-9A-F]"
2221 XOCTET_RE":"XOCTET_RE":"XOCTET_RE":"\
2222 XOCTET_RE":"XOCTET_RE":"XOCTET_RE
2223 #define NUM100_TO_99999_RE \
2224 "([1-9][0-9][0-9]|" \
2225 "[1-9][0-9][0-9][0-9]|" \
2226 "[1-9][0-9][0-9][0-9][0-9])"
2227 #define NUM5_TO_99999_RE \
2230 "[1-9][0-9][0-9]|" \
2231 "[1-9][0-9][0-9][0-9]|" \
2232 "[1-9][0-9][0-9][0-9][0-9])"
2233 #define NUM1_TO_99999_RE \
2236 "[1-9][0-9][0-9]|" \
2237 "[1-9][0-9][0-9][0-9]|" \
2238 "[1-9][0-9][0-9][0-9][0-9])"
2241 prompt(const char *prompt, const char *initial, const char *pattern)
2263 re = pcre_compile(pattern, PCRE_ANCHORED, &error, &erroffset, NULL);
2265 VLOG_ERR("PCRE error for pattern \"%s\" at offset %d: %s",
2266 pattern, erroffset, error);
2267 return xstrdup(initial);
2270 retval = pcre_fullinfo(re, NULL, PCRE_INFO_OKPARTIAL, &okpartial);
2276 ds_put_cstr(&ds, initial);
2278 figure_choices(re, &ds, pos, &choices);
2279 p = memchr(choices.string, initial[0], choices.length);
2280 chidx = p ? p - choices.string : 0;
2284 while ((key = getch()) != ERR) {
2287 if (choices.length > 1) {
2288 if (++chidx >= choices.length) {
2291 ds.string[pos] = choices.string[chidx];
2292 ds_truncate(&ds, pos + 1);
2293 figure_completion(re, &ds);
2298 if (choices.length > 1) {
2300 chidx = choices.length - 1;
2302 ds.string[pos] = choices.string[chidx];
2303 ds_truncate(&ds, pos + 1);
2304 figure_completion(re, &ds);
2308 case '\r': case '\n':
2309 if (choices.string[chidx] == '\n') {
2310 ds_truncate(&ds, pos);
2311 return ds_cstr(&ds);
2313 if (pos >= ds.length) {
2315 ds_put_char(&ds, choices.string[chidx]);
2316 figure_choices(re, &ds, pos, &choices);
2318 figure_completion(re, &ds);
2321 figure_choices(re, &ds, pos, &choices);
2323 figure_completion(re, &ds);
2329 ds_truncate(&ds, pos + 1);
2330 figure_choices(re, &ds, pos, &choices);
2334 case '\b': case '\x7f': case '\x1b':
2335 case KEY_BACKSPACE: case KEY_DC:
2339 return xstrdup(initial);
2341 figure_choices(re, &ds, pos, &choices);
2343 if (pos < ds.length) {
2344 p = memchr(choices.string, ds.string[pos],
2347 chidx = p - choices.string;
2353 if (key >= 0x20 && key < 0x7f) {
2354 /* Check whether 'key' is valid and toggle case if
2356 if (!memchr(choices.string, key, choices.length)) {
2357 if (memchr(choices.string, toupper(key),
2360 } else if (memchr(choices.string, tolower(key),
2368 /* Insert 'key' and advance the position. */
2369 if (pos >= ds.length) {
2370 ds_put_char(&ds, key);
2372 ds.string[pos] = key;
2376 if (choices.string[chidx] != key) {
2377 ds_truncate(&ds, pos);
2379 figure_choices(re, &ds, pos, &choices);
2381 if (pos < ds.length) {
2382 p = memchr(choices.string, ds.string[pos],
2385 chidx = p - choices.string;
2388 figure_completion(re, &ds);
2396 addnstr(prompt, MIN(40, strlen(prompt)));
2398 c = choices.string[chidx];
2400 addstr(ds_cstr(&ds));
2410 poll_fd_wait(STDIN_FILENO, POLLIN);
2416 prompt_ip(const char *title, uint32_t *ip)
2418 char *in = xasprintf(IP_FMT, IP_ARGS(ip));
2419 char *out = prompt(title, in, "^"IP_RE"$");
2420 *ip = inet_addr(out);
2426 abbreviate_netdevs(const struct svec *netdevs, struct ds *abbrev)
2431 for (i = 0; i < netdevs->n; ) {
2432 size_t i_len = strlen(netdevs->names[i]);
2435 for (j = i + 1; j < netdevs->n; j++) {
2436 size_t j_len = strlen(netdevs->names[j]);
2437 if (!i_len || !j_len || i_len != j_len
2438 || memcmp(netdevs->names[i], netdevs->names[j], i_len - 1)) {
2443 if (abbrev->length) {
2444 ds_put_char(abbrev, ' ');
2447 ds_put_cstr(abbrev, netdevs->names[i]);
2451 ds_put_buffer(abbrev, netdevs->names[i], i_len - 1);
2452 ds_put_char(abbrev, '[');
2453 for (k = i; k < j; k++) {
2454 ds_put_char(abbrev, netdevs->names[k][i_len - 1]);
2456 ds_put_char(abbrev, ']');
2463 choose_netdevs(struct svec *choices)
2465 struct svec netdevs;
2469 netdev_enumerate(&netdevs);
2470 svec_sort(&netdevs);
2473 menu_add_item(&menu, "Exit");
2474 for (i = 0; i < netdevs.n; i++) {
2475 const char *name = netdevs.names[i];
2476 struct menu_item *item;
2477 struct netdev *netdev;
2480 if (!strncmp(name, "wmaster", strlen("wmaster"))
2481 || !strncmp(name, "of", strlen("of"))
2482 || !strcmp(name, "lo")) {
2486 retval = netdev_open(name, NETDEV_ETH_TYPE_NONE, &netdev);
2488 bool exclude = netdev_get_in4(netdev, NULL, NULL) == 0;
2489 netdev_close(netdev);
2495 item = menu_add_item(&menu, "%s", name);
2496 item->toggle = svec_contains(choices, name);
2498 if (menu.n_items > 1) {
2499 menu_show(&menu, 0, true);
2501 show_string("No available\nbridge ports");
2504 svec_clear(choices);
2505 for (i = 0; i < menu.n_items; i++) {
2506 struct menu_item *item = menu.items[i];
2507 if (item->toggle > 0) {
2508 svec_add(choices, item->text);
2516 is_datapath_id_in_dmi(void)
2522 dmidecode = popen("dmidecode -s system-uuid", "r");
2526 is_in_dmi = fgets(line, sizeof line, dmidecode) && strstr(line, "-002320");
2531 struct switch_config {
2532 struct svec netdevs;
2533 enum { DISCOVERY, IN_BAND } mode;
2535 uint32_t switch_mask;
2537 enum { FAIL_DROP, FAIL_SWITCH } disconnected;
2540 int inactivity_probe;
2542 char *controller_vconn;
2547 disconnected_string(int value)
2549 #define FAIL_SWITCH_STRING "Switch packets"
2550 #define FAIL_DROP_STRING "Drop packets"
2551 return value == FAIL_SWITCH ? FAIL_SWITCH_STRING : FAIL_DROP_STRING;
2555 cmd_configure(const struct dict *dict UNUSED)
2557 bool debug_mode = dict_get_bool(dict, "debug", false);
2558 struct dict config_dict;
2559 struct switch_config config;
2562 if (!load_config(&config_dict)) {
2565 svec_init(&config.netdevs);
2566 svec_parse_words(&config.netdevs,
2567 dict_get_string(&config_dict, "NETDEVS", ""));
2568 config.mode = (!strcmp(dict_get_string(&config_dict, "MODE", "discovery"),
2569 "in-band") ? IN_BAND : DISCOVERY);
2570 config.switch_ip = dict_get_ip(&config_dict, "SWITCH_IP");
2571 config.switch_mask = dict_get_ip(&config_dict, "SWITCH_NETMASK");
2572 config.switch_gw = dict_get_ip(&config_dict, "SWITCH_GATEWAY");
2573 config.controller_vconn = xstrdup(dict_get_string(&config_dict,
2575 config.disconnected = (!strcmp(dict_get_string(&config_dict,
2576 "DISCONNECTED_MODE", ""),
2578 ? FAIL_SWITCH : FAIL_DROP);
2579 config.stp = !strcmp(dict_get_string(&config_dict, "stp", ""), "yes");
2580 config.rate_limit = dict_get_int(&config_dict, "RATE_LIMIT", -1);
2581 config.inactivity_probe = dict_get_int(&config_dict, "INACTIVITY_PROBE",
2583 config.max_backoff = dict_get_int(&config_dict, "MAX_BACKOFF", -1);
2584 if (is_datapath_id_in_dmi()) {
2585 config.datapath_id = xstrdup("DMI");
2587 const char *dpid = dict_get(&config_dict, "DATAPATH_ID");
2589 struct ds ds = DS_EMPTY_INITIALIZER;
2591 for (cp = dpid; *cp != '\0'; cp++) {
2593 ds_put_char(&ds, toupper((unsigned char) *cp));
2596 config.datapath_id = ds_cstr(&ds);
2598 config.datapath_id = xstrdup("Random");
2601 dict_free(&config_dict);
2604 while (start != -1) {
2613 MENU_DISCONNECTED_MODE,
2617 MENU_INACTIVITY_PROBE,
2622 struct menu_item *item;
2630 item = menu_add_item(&menu, "Exit");
2631 item->id = MENU_EXIT;
2634 abbreviate_netdevs(&config.netdevs, &ports);
2635 item = menu_add_item(&menu, "Bridge Ports:\n%s", ds_cstr(&ports));
2636 item->id = MENU_NETDEVS;
2640 item = menu_add_item(&menu, "Mode:\n%s",
2641 (config.mode == DISCOVERY
2642 ? "Discovery" : "In-Band"));
2643 item->id = MENU_MODE;
2646 if (config.switch_ip == htonl(0)) {
2647 item = menu_add_item(&menu, "Switch IP Addr:\nDHCP");
2649 item = menu_add_item(&menu, "Switch IP Addr:\n"IP_FMT,
2650 IP_ARGS(&config.switch_ip));
2653 item->enabled = config.mode == IN_BAND;
2656 item = menu_add_item(&menu, "Switch Netmask:\n"IP_FMT,
2657 IP_ARGS(&config.switch_mask));
2658 item->id = MENU_NETMASK;
2659 item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2662 item = menu_add_item(&menu, "Switch Gateway:\n"IP_FMT,
2663 IP_ARGS(&config.switch_gw));
2664 item->id = MENU_GATEWAY;
2665 item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2668 item = menu_add_item(&menu, "Controller:\n%s",
2669 config.controller_vconn);
2670 item->id = MENU_CONTROLLER;
2671 item->enabled = config.mode == IN_BAND;
2673 /* Disconnected mode. */
2674 item = menu_add_item(&menu, "If disconnected:\n%s\n",
2675 disconnected_string(config.disconnected));
2676 item->id = MENU_DISCONNECTED_MODE;
2679 item = menu_add_item(&menu, "Datapath ID:\n%s", config.datapath_id);
2680 item->id = MENU_DATAPATH_ID;
2681 item->enabled = strcmp(config.datapath_id, "DMI");
2683 /* Spanning tree protocol. */
2685 item = menu_add_item(&menu, "802.1D-1998 STP:\n%s",
2686 config.stp ? "Enabled" : "Disabled");
2687 item->id = MENU_STP;
2690 /* Rate-limiting. */
2692 if (config.rate_limit < 0) {
2693 item = menu_add_item(&menu, "Ctlr rate limit:\nDisabled");
2695 item = menu_add_item(&menu, "Ctlr rate limit:\n%d/s",
2698 item->id = MENU_RATE_LIMIT;
2701 /* Inactivity probe. */
2703 if (config.inactivity_probe < 0) {
2704 item = menu_add_item(&menu, "Activity probe:\nDefault");
2706 item = menu_add_item(&menu, "Activity probe:\n%d s",
2707 config.inactivity_probe);
2709 item->id = MENU_INACTIVITY_PROBE;
2714 if (config.max_backoff < 0) {
2715 item = menu_add_item(&menu, "Max backoff:\nDefault");
2717 item = menu_add_item(&menu, "Max backoff:\n%d s",
2718 config.max_backoff);
2720 item->id = MENU_MAX_BACKOFF;
2723 start = menu_show2(&menu, start, true);
2733 choose_netdevs(&config.netdevs);
2737 out = prompt("Mode:",
2738 config.mode == DISCOVERY ? "Discovery" : "In-Band",
2739 "^(Discovery|In-Band)$");
2740 config.mode = !strcmp(out, "Discovery") ? DISCOVERY : IN_BAND;
2745 in = (config.switch_ip == htonl(0) ? xstrdup("DHCP")
2746 : xasprintf(IP_FMT, IP_ARGS(&config.switch_ip)));
2747 out = prompt("Switch IP:", in, "^(DHCP|"IP_RE")$");
2748 ip = strcmp(out, "DHCP") ? inet_addr(out) : htonl(0);
2751 if (ip != config.switch_ip) {
2752 config.switch_ip = ip;
2753 if (ip != htonl(0)) {
2754 uint32_t mask = guess_netmask(ip);
2756 config.switch_mask = mask;
2757 config.switch_gw = (ip & mask) | htonl(1);
2764 prompt_ip("Switch Netmask:", &config.switch_mask);
2768 prompt_ip("Switch Gateway:", &config.switch_gw);
2771 case MENU_CONTROLLER:
2772 out = prompt("Controller:", config.controller_vconn,
2773 "^(tcp|ssl):"IP_RE"(:"PORT_RE")?$");
2774 free(config.controller_vconn);
2775 config.controller_vconn = out;
2778 case MENU_DISCONNECTED_MODE:
2779 out = prompt("If disconnected",
2780 disconnected_string(config.disconnected),
2781 "^("FAIL_DROP_STRING"|"FAIL_SWITCH_STRING")$");
2782 config.disconnected = (!strcmp(out, FAIL_DROP_STRING)
2783 ? FAIL_DROP : FAIL_SWITCH);
2787 case MENU_DATAPATH_ID:
2788 out = prompt("Datapath ID:", config.datapath_id,
2789 "^Random|"MAC_RE"$");
2790 free(config.datapath_id);
2791 config.datapath_id = out;
2795 out = prompt("802.1D-1998 STP:",
2796 config.stp ? "Enabled" : "Disabled",
2797 "^(Enabled|Disabled)$");
2798 config.stp = !strcmp(out, "Enabled");
2802 case MENU_RATE_LIMIT:
2803 in = (config.rate_limit < 0
2804 ? xstrdup("Disabled")
2805 : xasprintf("%d/s", config.rate_limit));
2806 out = prompt("Ctlr rate limit:", in,
2807 "^(Disabled|("NUM100_TO_99999_RE")/s)$");
2810 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2814 case MENU_INACTIVITY_PROBE:
2815 in = (config.inactivity_probe < 0
2816 ? xstrdup("Default")
2817 : xasprintf("%d s", config.inactivity_probe));
2818 out = prompt("Activity probe:", in,
2819 "^(Default|("NUM5_TO_99999_RE") s)$");
2821 config.inactivity_probe
2822 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2826 case MENU_MAX_BACKOFF:
2827 in = (config.max_backoff < 0
2828 ? xstrdup("Default")
2829 : xasprintf("%d s", config.max_backoff));
2830 out = prompt("Max backoff:", in,
2831 "^(Default|("NUM1_TO_99999_RE") s)$");
2834 = isdigit((unsigned char)out[0]) ? atoi(out) : -1;
2840 if (yesno("Save\nChanges?", false)) {
2845 netdevs = svec_join(&config.netdevs, " ", "");
2846 svec_add_nocopy(&set, xasprintf("NETDEVS=%s", netdevs));
2849 config.mode == IN_BAND ? "MODE=in-band" : "MODE=discovery");
2850 if (config.mode == IN_BAND) {
2851 if (config.switch_ip == htonl(0)) {
2852 svec_add(&set, "SWITCH_IP=dhcp");
2854 svec_add_nocopy(&set, xasprintf("SWITCH_IP="IP_FMT,
2855 IP_ARGS(&config.switch_ip)));
2856 svec_add_nocopy(&set,
2857 xasprintf("SWITCH_NETMASK="IP_FMT,
2858 IP_ARGS(&config.switch_mask)));
2859 svec_add_nocopy(&set, xasprintf("SWITCH_GATEWAY="IP_FMT,
2860 IP_ARGS(&config.switch_gw)));
2861 svec_add_nocopy(&set, xasprintf("CONTROLLER=%s",
2862 config.controller_vconn));
2865 svec_add(&set, (config.disconnected == FAIL_DROP
2866 ? "DISCONNECTED_MODE=drop"
2867 : "DISCONNECTED_MODE=switch"));
2868 svec_add_nocopy(&set, xasprintf("STP=%s", config.stp ? "yes" : "no"));
2869 if (config.rate_limit < 0) {
2870 svec_add(&set, "RATE_LIMIT=");
2872 svec_add_nocopy(&set,
2873 xasprintf("RATE_LIMIT=%d", config.rate_limit));
2875 if (config.inactivity_probe < 0) {
2876 svec_add(&set, "INACTIVITY_PROBE=");
2878 svec_add_nocopy(&set, xasprintf("INACTIVITY_PROBE=%d",
2879 config.inactivity_probe));
2881 if (config.max_backoff < 0) {
2882 svec_add(&set, "MAX_BACKOFF=");
2884 svec_add_nocopy(&set, xasprintf("MAX_BACKOFF=%d",
2885 config.max_backoff));
2891 svec_destroy(&config.netdevs);
2892 free(config.controller_vconn);
2893 free(config.datapath_id);
2897 cmd_set_up_pki(const struct dict *dict UNUSED)
2899 static const char def_privkey_file[]
2900 = "/etc/openflow-switch/of0-privkey.pem";
2901 static const char def_cert_file[] = "/etc/openflow-switch/of0-cert.pem";
2902 static const char def_cacert_file[] = "/etc/openflow-switch/cacert.pem";
2903 struct dict config_dict;
2904 const char *privkey_file, *cert_file, *cacert_file;
2910 if (!load_config(&config_dict)) {
2913 privkey_file = dict_get_string(&config_dict, "PRIVKEY", def_privkey_file);
2914 cert_file = dict_get_string(&config_dict, "CERT", def_cert_file);
2915 cacert_file = dict_get_string(&config_dict, "CACERT", def_cacert_file);
2916 bootstrap = !strcmp(dict_get_string(&config_dict, "CACERT_MODE", "secure"),
2919 has_keys = !stat(privkey_file, &s) && !stat(cert_file, &s);
2921 ? yesno("Generate\nkeys?", true)
2922 : yesno("Generate\nnew keys?", false)) {
2926 privkey_file = def_privkey_file;
2927 cert_file = def_cert_file;
2930 svec_parse_words(&argv, "sh -c 'cd /etc/openflow-switch "
2931 "&& ovs-pki --force req of0"
2932 "&& ovs-pki --force self-sign of0'");
2933 svec_terminate(&argv);
2934 ok = run_and_report_failure(argv.names, "Key gen failed");
2935 svec_destroy(&argv);
2945 if (stat(cacert_file, &s) && errno == ENOENT) {
2946 bootstrap = yesno("Bootstrap\nCA cert?", bootstrap);
2947 } else if (yesno("Replace\nCA cert?", false)) {
2948 unlink(cacert_file);
2953 svec_add_nocopy(&set, xasprintf("PRIVKEY=%s", privkey_file));
2954 svec_add_nocopy(&set, xasprintf("CERT=%s", cert_file));
2955 svec_add_nocopy(&set, xasprintf("CACERT=%s", cacert_file));
2956 svec_add_nocopy(&set, xasprintf("CACERT_MODE=%s",
2957 bootstrap ? "bootstrap" : "secure"));
2963 parse_options(int argc, char *argv[])
2966 OPT_DUMMY = UCHAR_MAX + 1,
2969 static struct option long_options[] = {
2970 {"verbose", optional_argument, 0, 'v'},
2971 {"help", no_argument, 0, 'h'},
2972 {"version", no_argument, 0, 'V'},
2973 DAEMON_LONG_OPTIONS,
2977 char *short_options = long_options_to_short_options(long_options);
2982 c = getopt_long(argc, argv, short_options, long_options, NULL);
2992 OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
2995 VLOG_OPTION_HANDLERS
2996 DAEMON_OPTION_HANDLERS
3005 free(short_options);
3011 printf("%s: OpenFlow switch monitoring user interface\n"
3012 "usage: %s [OPTIONS] SWITCH\n"
3013 "where SWITCH is an active OpenFlow connection method.\n",
3014 program_name, program_name);
3015 vconn_usage(true, false, false);
3016 printf("\nOptions:\n"
3017 " -v, --verbose=MODULE:FACILITY:LEVEL configure logging levels\n"
3018 " -v, --verbose set maximum verbosity level\n"
3019 " -h, --help display this help message\n"
3020 " -V, --version display version information\n");