ovsdb-idl: Make ovsdb_idl_txn_add_comment() take a printf() format string.
[sliver-openvswitch.git] / vswitchd / ovs-brcompatd.c
1 /* Copyright (c) 2008, 2009, 2010 Nicira Networks
2  *
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:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
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.
14  */
15
16 #include <config.h>
17
18 #include <asm/param.h>
19 #include <assert.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <net/if.h>
25 #include <linux/genetlink.h>
26 #include <linux/rtnetlink.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <time.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #include "command-line.h"
37 #include "coverage.h"
38 #include "daemon.h"
39 #include "dirs.h"
40 #include "dynamic-string.h"
41 #include "fatal-signal.h"
42 #include "json.h"
43 #include "leak-checker.h"
44 #include "netdev.h"
45 #include "netlink.h"
46 #include "ofpbuf.h"
47 #include "openvswitch/brcompat-netlink.h"
48 #include "ovsdb-idl.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "process.h"
52 #include "signals.h"
53 #include "svec.h"
54 #include "timeval.h"
55 #include "unixctl.h"
56 #include "util.h"
57 #include "vswitchd/vswitch-idl.h"
58
59 #include "vlog.h"
60 #define THIS_MODULE VLM_brcompatd
61
62
63 /* xxx Just hangs if datapath is rmmod/insmod.  Learn to reconnect? */
64
65 /* Actions to modify bridge compatibility configuration. */
66 enum bmc_action {
67     BMC_ADD_DP,
68     BMC_DEL_DP,
69     BMC_ADD_PORT,
70     BMC_DEL_PORT
71 };
72
73 static const char *parse_options(int argc, char *argv[]);
74 static void usage(void) NO_RETURN;
75
76 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 60);
77
78 /* Maximum number of milliseconds to wait before pruning port entries that 
79  * no longer exist.  If set to zero, ports are never pruned. */
80 static int prune_timeout = 5000;
81
82 /* Shell command to execute (via popen()) to send a control command to the
83  * running ovs-vswitchd process.  The string must contain one instance of %s,
84  * which is replaced by the control command. */
85 static char *appctl_command;
86
87 /* Netlink socket to listen for interface changes. */
88 static struct nl_sock *rtnl_sock;
89
90 /* Netlink socket to bridge compatibility kernel module. */
91 static struct nl_sock *brc_sock;
92
93 /* The Generic Netlink family number used for bridge compatibility. */
94 static int brc_family;
95
96 static const struct nl_policy brc_multicast_policy[] = {
97     [BRC_GENL_A_MC_GROUP] = {.type = NL_A_U32 }
98 };
99
100 static const struct nl_policy rtnlgrp_link_policy[] = {
101     [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
102     [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
103 };
104
105 static int
106 lookup_brc_multicast_group(int *multicast_group)
107 {
108     struct nl_sock *sock;
109     struct ofpbuf request, *reply;
110     struct nlattr *attrs[ARRAY_SIZE(brc_multicast_policy)];
111     int retval;
112
113     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
114     if (retval) {
115         return retval;
116     }
117     ofpbuf_init(&request, 0);
118     nl_msg_put_genlmsghdr(&request, sock, 0, brc_family,
119             NLM_F_REQUEST, BRC_GENL_C_QUERY_MC, 1);
120     retval = nl_sock_transact(sock, &request, &reply);
121     ofpbuf_uninit(&request);
122     if (retval) {
123         nl_sock_destroy(sock);
124         return retval;
125     }
126     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
127                          brc_multicast_policy, attrs,
128                          ARRAY_SIZE(brc_multicast_policy))) {
129         nl_sock_destroy(sock);
130         ofpbuf_delete(reply);
131         return EPROTO;
132     }
133     *multicast_group = nl_attr_get_u32(attrs[BRC_GENL_A_MC_GROUP]);
134     nl_sock_destroy(sock);
135     ofpbuf_delete(reply);
136
137     return 0;
138 }
139
140 /* Opens a socket for brcompat notifications.  Returns 0 if successful,
141  * otherwise a positive errno value. */
142 static int
143 brc_open(struct nl_sock **sock)
144 {
145     int multicast_group = 0;
146     int retval;
147
148     retval = nl_lookup_genl_family(BRC_GENL_FAMILY_NAME, &brc_family);
149     if (retval) {
150         return retval;
151     }
152
153     retval = lookup_brc_multicast_group(&multicast_group);
154     if (retval) {
155         return retval;
156     }
157
158     retval = nl_sock_create(NETLINK_GENERIC, multicast_group, 0, 0, sock);
159     if (retval) {
160         return retval;
161     }
162
163     return 0;
164 }
165
166 static const struct nl_policy brc_dp_policy[] = {
167     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
168 };
169
170 static struct ovsrec_bridge *
171 find_bridge(const struct ovsrec_open_vswitch *ovs, const char *br_name)
172 {
173     size_t i;
174
175     for (i = 0; i < ovs->n_bridges; i++) {
176         if (!strcmp(br_name, ovs->bridges[i]->name)) {
177             return ovs->bridges[i];
178         }
179     }
180
181     return NULL;
182 }
183
184 static int
185 execute_appctl_command(const char *unixctl_command, char **output)
186 {
187     char *stdout_log, *stderr_log;
188     int error, status;
189     char *argv[5];
190
191     argv[0] = "/bin/sh";
192     argv[1] = "-c";
193     argv[2] = xasprintf(appctl_command, unixctl_command);
194     argv[3] = NULL;
195
196     /* Run process and log status. */
197     error = process_run_capture(argv, &stdout_log, &stderr_log, &status);
198     if (error) {
199         VLOG_ERR("failed to execute %s command via ovs-appctl: %s",
200                  unixctl_command, strerror(error));
201     } else if (status) {
202         char *msg = process_status_msg(status);
203         VLOG_ERR("ovs-appctl exited with error (%s)", msg);
204         free(msg);
205         error = ECHILD;
206     }
207
208     /* Deal with stdout_log. */
209     if (output) {
210         *output = stdout_log;
211     } else {
212         free(stdout_log);
213     }
214
215     /* Deal with stderr_log */
216     if (stderr_log && *stderr_log) {
217         VLOG_INFO("ovs-appctl wrote to stderr:\n%s", stderr_log);
218     }
219     free(stderr_log);
220
221     free(argv[2]);
222
223     return error;
224 }
225
226 static void
227 do_get_bridge_parts(const struct ovsrec_bridge *br, struct svec *parts, 
228                     int vlan, bool break_down_bonds)
229 {
230     struct svec ports;
231     size_t i, j;
232
233     svec_init(&ports);
234     for (i = 0; i < br->n_ports; i++) {
235         const struct ovsrec_port *port = br->ports[i];
236
237         svec_add(&ports, port->name);
238         if (vlan >= 0) {
239             int port_vlan = port->n_tag ? *port->tag : 0;
240             if (vlan != port_vlan) {
241                 continue;
242             }
243         }
244         if (break_down_bonds) {
245             for (j = 0; j < port->n_interfaces; j++) {
246                 const struct ovsrec_interface *iface = port->interfaces[j];
247                 svec_add(parts, iface->name);
248             }
249         } else {
250             svec_add(parts, port->name);
251         }
252     }
253     svec_destroy(&ports);
254 }
255
256 /* Add all the interfaces for 'bridge' to 'ifaces', breaking bonded interfaces
257  * down into their constituent parts.
258  *
259  * If 'vlan' < 0, all interfaces on 'bridge' are reported.  If 'vlan' == 0,
260  * then only interfaces for trunk ports or ports with implicit VLAN 0 are
261  * reported.  If 'vlan' > 0, only interfaces with implicit VLAN 'vlan' are
262  * reported.  */
263 static void
264 get_bridge_ifaces(const struct ovsrec_bridge *br, struct svec *ifaces, 
265                   int vlan)
266 {
267     do_get_bridge_parts(br, ifaces, vlan, true);
268 }
269
270 /* Add all the ports for 'bridge' to 'ports'.  Bonded ports are reported under
271  * the bond name, not broken down into their constituent interfaces.
272  *
273  * If 'vlan' < 0, all ports on 'bridge' are reported.  If 'vlan' == 0, then
274  * only trunk ports or ports with implicit VLAN 0 are reported.  If 'vlan' > 0,
275  * only port with implicit VLAN 'vlan' are reported.  */
276 static void
277 get_bridge_ports(const struct ovsrec_bridge *br, struct svec *ports, 
278                  int vlan)
279 {
280     do_get_bridge_parts(br, ports, vlan, false);
281 }
282
283 #if 0
284 /* Go through the configuration file and remove any ports that no longer
285  * exist associated with a bridge. */
286 static void
287 prune_ports(void)
288 {
289     int i, j;
290     struct svec bridges, delete;
291
292     if (cfg_lock(NULL, 0)) {
293         /* Couldn't lock config file. */
294         return;
295     }
296
297     svec_init(&bridges);
298     svec_init(&delete);
299     cfg_get_subsections(&bridges, "bridge");
300     for (i=0; i<bridges.n; i++) {
301         const char *br_name = bridges.names[i];
302         struct svec ifaces;
303
304         /* Check that each bridge interface exists. */
305         svec_init(&ifaces);
306         get_bridge_ifaces(br_name, &ifaces, -1);
307         for (j = 0; j < ifaces.n; j++) {
308             const char *iface_name = ifaces.names[j];
309
310             /* The local port and internal ports are created and destroyed by
311              * ovs-vswitchd itself, so don't bother checking for them at all.
312              * In practice, they might not exist if ovs-vswitchd hasn't
313              * finished reloading since the configuration file was updated. */
314             if (!strcmp(iface_name, br_name)
315                 || cfg_get_bool(0, "iface.%s.internal", iface_name)) {
316                 continue;
317             }
318
319             if (!netdev_exists(iface_name)) {
320                 VLOG_INFO_RL(&rl, "removing dead interface %s from %s",
321                              iface_name, br_name);
322                 svec_add(&delete, iface_name);
323             }
324         }
325         svec_destroy(&ifaces);
326     }
327     svec_destroy(&bridges);
328
329     if (delete.n) {
330         size_t i;
331
332         for (i = 0; i < delete.n; i++) {
333             cfg_del_match("bridge.*.port=%s", delete.names[i]);
334             cfg_del_match("bonding.*.slave=%s", delete.names[i]);
335         }
336         reload_config();
337         cfg_unlock();
338     } else {
339         cfg_unlock();
340     }
341     svec_destroy(&delete);
342 }
343 #endif
344
345 static struct ovsdb_idl_txn *
346 txn_from_openvswitch(const struct ovsrec_open_vswitch *ovs)
347 {
348     return ovsdb_idl_txn_get(&ovs->header_);
349 }
350
351 static bool
352 port_is_fake_bridge(const struct ovsrec_port *port)
353 {
354     return (port->fake_bridge
355             && port->tag
356             && *port->tag >= 1 && *port->tag <= 4095);
357 }
358
359 static void
360 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
361                   struct ovsrec_bridge *bridge)
362 {
363     struct ovsrec_bridge **bridges;
364     size_t i;     
365
366     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
367     for (i = 0; i < ovs->n_bridges; i++) {
368         bridges[i] = ovs->bridges[i];
369     }
370     bridges[ovs->n_bridges] = bridge;
371     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
372     free(bridges);
373 }   
374
375 static struct json *
376 where_uuid_equals(const struct uuid *uuid)
377 {
378     return
379         json_array_create_1(
380             json_array_create_3(
381                 json_string_create("_uuid"),
382                 json_string_create("=="),
383                 json_array_create_2(
384                     json_string_create("uuid"),
385                     json_string_create_nocopy(
386                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
387 }
388
389 /* Commits 'txn'.  If 'wait_for_reload' is true, also waits for Open vSwitch to
390    reload the configuration before returning.
391
392    Returns EAGAIN if the caller should try the operation again, 0 on success,
393    otherwise a positive errno value. */
394 static int
395 commit_txn(struct ovsdb_idl_txn *txn, bool wait_for_reload)
396 {
397     struct ovsdb_idl *idl = ovsdb_idl_txn_get_idl (txn);
398     enum ovsdb_idl_txn_status status;
399     int64_t next_cfg = 0;
400
401     if (wait_for_reload) {
402         const struct ovsrec_open_vswitch *ovs = ovsrec_open_vswitch_first(idl);
403         struct json *where = where_uuid_equals(&ovs->header_.uuid);
404         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
405         json_destroy(where);
406     }
407     status = ovsdb_idl_txn_commit_block(txn);
408     if (wait_for_reload && status == TXN_SUCCESS) {
409         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
410     }
411     ovsdb_idl_txn_destroy(txn);
412
413     switch (status) {
414     case TXN_INCOMPLETE:
415         NOT_REACHED();
416
417     case TXN_ABORTED:
418         VLOG_ERR_RL(&rl, "OVSDB transaction unexpectedly aborted");
419         return ECONNABORTED;
420
421     case TXN_UNCHANGED:
422         return 0;
423
424     case TXN_SUCCESS:
425         if (wait_for_reload) {
426             for (;;) {
427                 /* We can't use 'ovs' any longer because ovsdb_idl_run() can
428                  * destroy it. */
429                 const struct ovsrec_open_vswitch *ovs2;
430
431                 ovsdb_idl_run(idl);
432                 OVSREC_OPEN_VSWITCH_FOR_EACH (ovs2, idl) {
433                     if (ovs2->cur_cfg >= next_cfg) {
434                         goto done;
435                     }
436                 }
437                 ovsdb_idl_wait(idl);
438                 poll_block();
439             }
440         done: ;
441         }
442         return 0;
443
444     case TXN_TRY_AGAIN:
445         VLOG_ERR_RL(&rl, "OVSDB transaction needs retry");
446         return EAGAIN;
447
448     case TXN_ERROR:
449         VLOG_ERR_RL(&rl, "OVSDB transaction failed: %s",
450                     ovsdb_idl_txn_get_error(txn));
451         return EBUSY;
452
453     default:
454         NOT_REACHED();
455     }
456 }
457
458 static int
459 add_bridge(struct ovsdb_idl *idl, const struct ovsrec_open_vswitch *ovs,
460            const char *br_name)
461 {
462     struct ovsrec_bridge *br;
463     struct ovsrec_port *port;
464     struct ovsrec_interface *iface;
465     struct ovsdb_idl_txn *txn;
466
467     if (find_bridge(ovs, br_name)) {
468         VLOG_WARN("addbr %s: bridge %s exists", br_name, br_name);
469         return EEXIST;
470     } else if (netdev_exists(br_name)) {
471         size_t i;
472
473         for (i = 0; i < ovs->n_bridges; i++) {
474             size_t j;
475             struct ovsrec_bridge *br_cfg = ovs->bridges[i];
476
477             for (j = 0; j < br_cfg->n_ports; j++) {
478                 if (port_is_fake_bridge(br_cfg->ports[j])) {
479                     VLOG_WARN("addbr %s: %s exists as a fake bridge",
480                               br_name, br_name);
481                     return 0;
482                 }
483             }
484         }
485
486         VLOG_WARN("addbr %s: cannot create bridge %s because a network "
487                   "device named %s already exists",
488                   br_name, br_name, br_name);
489         return EEXIST;
490     }
491
492     txn = ovsdb_idl_txn_create(idl);
493
494     ovsdb_idl_txn_add_comment(txn, "ovs-brcompatd: addbr %s", br_name);
495
496     iface = ovsrec_interface_insert(txn_from_openvswitch(ovs));
497     ovsrec_interface_set_name(iface, br_name);
498
499     port = ovsrec_port_insert(txn_from_openvswitch(ovs));
500     ovsrec_port_set_name(port, br_name);
501     ovsrec_port_set_interfaces(port, &iface, 1);
502     
503     br = ovsrec_bridge_insert(txn_from_openvswitch(ovs));
504     ovsrec_bridge_set_name(br, br_name);
505     ovsrec_bridge_set_ports(br, &port, 1);
506     
507     ovs_insert_bridge(ovs, br);
508
509     return commit_txn(txn, true);
510 }
511
512 static void
513 add_port(const struct ovsrec_open_vswitch *ovs, 
514          const struct ovsrec_bridge *br, const char *port_name)
515 {
516     struct ovsrec_interface *iface;
517     struct ovsrec_port *port;
518     struct ovsrec_port **ports;
519     size_t i;
520
521     /* xxx Check conflicts? */
522     iface = ovsrec_interface_insert(txn_from_openvswitch(ovs));
523     ovsrec_interface_set_name(iface, port_name);
524
525     port = ovsrec_port_insert(txn_from_openvswitch(ovs));
526     ovsrec_port_set_name(port, port_name);
527     ovsrec_port_set_interfaces(port, &iface, 1);
528
529     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
530     for (i = 0; i < br->n_ports; i++) {
531         ports[i] = br->ports[i];
532     }
533     ports[br->n_ports] = port;
534     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
535     free(ports);
536 }
537
538 static void
539 del_port(const struct ovsrec_bridge *br, const char *port_name)
540 {
541     size_t i, j;
542     struct ovsrec_port *port_rec = NULL;
543
544     for (i = 0; i < br->n_ports; i++) {
545         struct ovsrec_port *port = br->ports[i];
546         if (!strcmp(port_name, port->name)) {
547             port_rec = port;
548         }
549         for (j = 0; j < port->n_interfaces; j++) {
550             struct ovsrec_interface *iface = port->interfaces[j];
551             if (!strcmp(port_name, iface->name)) {
552                 ovsrec_interface_delete(iface);
553             }
554         }
555     }
556
557     /* xxx Probably can move this into the "for" loop. */
558     if (port_rec) {
559         struct ovsrec_port **ports;
560         size_t n;
561
562         ports = xmalloc(sizeof *br->ports * br->n_ports);
563         for (i = n = 0; i < br->n_ports; i++) {
564             if (br->ports[i] != port_rec) {
565                 ports[n++] = br->ports[i];
566             }
567         }
568         ovsrec_bridge_set_ports(br, ports, n);
569         free(ports);
570
571         ovsrec_port_delete(port_rec);
572     }
573 }
574
575 static int
576 del_bridge(struct ovsdb_idl *idl,
577            const struct ovsrec_open_vswitch *ovs, const char *br_name)
578 {
579     struct ovsrec_bridge *br = find_bridge(ovs, br_name);
580     struct ovsrec_bridge **bridges;
581     struct ovsdb_idl_txn *txn;
582     size_t i, n;
583
584     if (!br) {
585         VLOG_WARN("delbr %s: no bridge named %s", br_name, br_name);
586         return ENXIO;
587     }
588
589     txn = ovsdb_idl_txn_create(idl);
590
591     ovsdb_idl_txn_add_comment(txn, "ovs-brcompatd: delbr %s", br_name);
592
593     del_port(br, br_name);
594
595     bridges = xmalloc(sizeof *ovs->bridges * ovs->n_bridges);
596     for (i = n = 0; i < ovs->n_bridges; i++) {
597         if (ovs->bridges[i] != br) {
598             bridges[n++] = ovs->bridges[i];
599         }
600     }
601     ovsrec_open_vswitch_set_bridges(ovs, bridges, n);
602     free(bridges);
603
604     /* Delete the bridge itself. */
605     ovsrec_bridge_delete(br);
606
607     return commit_txn(txn, true);
608 }
609
610 static int
611 parse_command(struct ofpbuf *buffer, uint32_t *seq, const char **br_name,
612               const char **port_name, uint64_t *count, uint64_t *skip)
613 {
614     static const struct nl_policy policy[] = {
615         [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING, .optional = true },
616         [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING, .optional = true },
617         [BRC_GENL_A_FDB_COUNT] = { .type = NL_A_U64, .optional = true },
618         [BRC_GENL_A_FDB_SKIP] = { .type = NL_A_U64, .optional = true },
619     };
620     struct nlattr *attrs[ARRAY_SIZE(policy)];
621
622     if (!nl_policy_parse(buffer, NLMSG_HDRLEN + GENL_HDRLEN, policy,
623                          attrs, ARRAY_SIZE(policy))
624         || (br_name && !attrs[BRC_GENL_A_DP_NAME])
625         || (port_name && !attrs[BRC_GENL_A_PORT_NAME])
626         || (count && !attrs[BRC_GENL_A_FDB_COUNT])
627         || (skip && !attrs[BRC_GENL_A_FDB_SKIP])) {
628         return EINVAL;
629     }
630
631     *seq = ((struct nlmsghdr *) buffer->data)->nlmsg_seq;
632     if (br_name) {
633         *br_name = nl_attr_get_string(attrs[BRC_GENL_A_DP_NAME]);
634     }
635     if (port_name) {
636         *port_name = nl_attr_get_string(attrs[BRC_GENL_A_PORT_NAME]);
637     }
638     if (count) {
639         *count = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_COUNT]);
640     }
641     if (skip) {
642         *skip = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_SKIP]);
643     }
644     return 0;
645 }
646
647 /* Composes and returns a reply to a request made by the datapath with Netlink
648  * sequence number 'seq' and error code 'error'.  The caller may add additional
649  * attributes to the message, then it may send it with send_reply(). */
650 static struct ofpbuf *
651 compose_reply(uint32_t seq, int error)
652 {
653     struct ofpbuf *reply = ofpbuf_new(4096);
654     nl_msg_put_genlmsghdr(reply, brc_sock, 32, brc_family, NLM_F_REQUEST,
655                           BRC_GENL_C_DP_RESULT, 1);
656     ((struct nlmsghdr *) reply->data)->nlmsg_seq = seq;
657     nl_msg_put_u32(reply, BRC_GENL_A_ERR_CODE, error);
658     return reply;
659 }
660
661 /* Sends 'reply' to the datapath and frees it. */
662 static void
663 send_reply(struct ofpbuf *reply)
664 {
665     int retval = nl_sock_send(brc_sock, reply, false);
666     if (retval) {
667         VLOG_WARN_RL(&rl, "replying to brcompat request: %s",
668                      strerror(retval));
669     }
670     ofpbuf_delete(reply);
671 }
672
673 /* Composes and sends a reply to a request made by the datapath with Netlink
674  * sequence number 'seq' and error code 'error'. */
675 static void
676 send_simple_reply(uint32_t seq, int error)
677 {
678     send_reply(compose_reply(seq, error));
679 }
680
681 static int
682 handle_bridge_cmd(struct ovsdb_idl *idl,
683                   const struct ovsrec_open_vswitch *ovs, 
684                   struct ofpbuf *buffer, bool add)
685 {
686     const char *br_name;
687     uint32_t seq;
688     int error;
689
690     error = parse_command(buffer, &seq, &br_name, NULL, NULL, NULL);
691     if (!error) {
692         int retval;
693
694         do {
695             retval = (add ? add_bridge : del_bridge)(idl, ovs, br_name);
696             VLOG_INFO_RL(&rl, "%sbr %s: %s",
697                          add ? "add" : "del", br_name, strerror(retval));
698         } while (retval == EAGAIN);
699
700         send_simple_reply(seq, error);
701     }
702     return error;
703 }
704
705 static const struct nl_policy brc_port_policy[] = {
706     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
707     [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING },
708 };
709
710 static int
711 handle_port_cmd(struct ovsdb_idl *idl,
712                 const struct ovsrec_open_vswitch *ovs,
713                 struct ofpbuf *buffer, bool add)
714 {
715     const char *cmd_name = add ? "add-if" : "del-if";
716     const char *br_name, *port_name;
717     uint32_t seq;
718     int error;
719
720     error = parse_command(buffer, &seq, &br_name, &port_name, NULL, NULL);
721     if (!error) {
722         struct ovsrec_bridge *br = find_bridge(ovs, br_name);
723
724         if (!br) {
725             VLOG_WARN("%s %s %s: no bridge named %s",
726                       cmd_name, br_name, port_name, br_name);
727             error = EINVAL;
728         } else if (!netdev_exists(port_name)) {
729             VLOG_WARN("%s %s %s: no network device named %s",
730                       cmd_name, br_name, port_name, port_name);
731             error = EINVAL;
732         } else {
733             do {
734                 struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
735
736                 if (add) {
737                     ovsdb_idl_txn_add_comment(txn, "ovs-brcompatd: add-if %s",
738                                               port_name);
739                     add_port(ovs, br, port_name);
740                 } else {
741                     ovsdb_idl_txn_add_comment(txn, "ovs-brcompatd: del-if %s",
742                                               port_name);
743                     del_port(br, port_name);
744                 }
745
746                 error = commit_txn(txn, true);
747                 VLOG_INFO_RL(&rl, "%s %s %s: %s",
748                              cmd_name, br_name, port_name, strerror(error));
749             } while (error == EAGAIN);
750         }
751         send_simple_reply(seq, error);
752     }
753
754     return error;
755 }
756
757 /* The caller is responsible for freeing '*ovs_name' if the call is
758  * successful. */
759 static int
760 linux_bridge_to_ovs_bridge(const struct ovsrec_open_vswitch *ovs,
761                            const char *linux_name,
762                            const struct ovsrec_bridge **ovs_bridge,
763                            int *br_vlan)
764 {
765     *ovs_bridge = find_bridge(ovs, linux_name);
766     if (*ovs_bridge) {
767         /* Bridge name is the same.  We are interested in VLAN 0. */
768         *br_vlan = 0;
769         return 0;
770     } else {
771         /* No such Open vSwitch bridge 'linux_name', but there might be an
772          * internal port named 'linux_name' on some other bridge
773          * 'ovs_bridge'.  If so then we are interested in the VLAN assigned to
774          * port 'linux_name' on the bridge named 'ovs_bridge'. */
775         size_t i, j;
776
777         for (i = 0; i < ovs->n_bridges; i++) {
778             const struct ovsrec_bridge *br = ovs->bridges[i];
779
780             for (j = 0; j < br->n_ports; j++) {
781                 const struct ovsrec_port *port = br->ports[j];
782
783                 if (!strcmp(port->name, linux_name)) {
784                     *ovs_bridge = br;
785                     *br_vlan = port->n_tag ? *port->tag : -1;
786                     return 0;
787                 }
788             }
789
790         }
791         return ENODEV;
792     }
793 }
794
795 static int
796 handle_fdb_query_cmd(const struct ovsrec_open_vswitch *ovs,
797                      struct ofpbuf *buffer)
798 {
799     /* This structure is copied directly from the Linux 2.6.30 header files.
800      * It would be more straightforward to #include <linux/if_bridge.h>, but
801      * the 'port_hi' member was only introduced in Linux 2.6.26 and so systems
802      * with old header files won't have it. */
803     struct __fdb_entry {
804         __u8 mac_addr[6];
805         __u8 port_no;
806         __u8 is_local;
807         __u32 ageing_timer_value;
808         __u8 port_hi;
809         __u8 pad0;
810         __u16 unused;
811     };
812
813     struct mac {
814         uint8_t addr[6];
815     };
816     struct mac *local_macs;
817     int n_local_macs;
818     int i;
819
820     /* Impedance matching between the vswitchd and Linux kernel notions of what
821      * a bridge is.  The kernel only handles a single VLAN per bridge, but
822      * vswitchd can deal with all the VLANs on a single bridge.  We have to
823      * pretend that the former is the case even though the latter is the
824      * implementation. */
825     const char *linux_name;   /* Name used by brctl. */
826     const struct ovsrec_bridge *ovs_bridge;  /* Bridge used by ovs-vswitchd. */
827     int br_vlan;                /* VLAN tag. */
828     struct svec ifaces;
829
830     struct ofpbuf query_data;
831     struct ofpbuf *reply;
832     char *unixctl_command;
833     uint64_t count, skip;
834     char *output;
835     char *save_ptr;
836     uint32_t seq;
837     int error;
838
839     /* Parse the command received from brcompat_mod. */
840     error = parse_command(buffer, &seq, &linux_name, NULL, &count, &skip);
841     if (error) {
842         return error;
843     }
844
845     /* Figure out vswitchd bridge and VLAN. */
846     error = linux_bridge_to_ovs_bridge(ovs, linux_name, 
847                                        &ovs_bridge, &br_vlan);
848     if (error) {
849         send_simple_reply(seq, error);
850         return error;
851     }
852
853     /* Fetch the forwarding database using ovs-appctl. */
854     unixctl_command = xasprintf("fdb/show %s", ovs_bridge->name);
855     error = execute_appctl_command(unixctl_command, &output);
856     free(unixctl_command);
857     if (error) {
858         send_simple_reply(seq, error);
859         return error;
860     }
861
862     /* Fetch the MAC address for each interface on the bridge, so that we can
863      * fill in the is_local field in the response. */
864     svec_init(&ifaces);
865     get_bridge_ifaces(ovs_bridge, &ifaces, br_vlan);
866     local_macs = xmalloc(ifaces.n * sizeof *local_macs);
867     n_local_macs = 0;
868     for (i = 0; i < ifaces.n; i++) {
869         const char *iface_name = ifaces.names[i];
870         struct mac *mac = &local_macs[n_local_macs];
871         struct netdev *netdev;
872
873         error = netdev_open_default(iface_name, &netdev);
874         if (!error) {
875             if (!netdev_get_etheraddr(netdev, mac->addr)) {
876                 n_local_macs++;
877             }
878             netdev_close(netdev);
879         }
880     }
881     svec_destroy(&ifaces);
882
883     /* Parse the response from ovs-appctl and convert it to binary format to
884      * pass back to the kernel. */
885     ofpbuf_init(&query_data, sizeof(struct __fdb_entry) * 8);
886     save_ptr = NULL;
887     strtok_r(output, "\n", &save_ptr); /* Skip header line. */
888     while (count > 0) {
889         struct __fdb_entry *entry;
890         int port, vlan, age;
891         uint8_t mac[ETH_ADDR_LEN];
892         char *line;
893         bool is_local;
894
895         line = strtok_r(NULL, "\n", &save_ptr);
896         if (!line) {
897             break;
898         }
899
900         if (sscanf(line, "%d %d "ETH_ADDR_SCAN_FMT" %d",
901                    &port, &vlan, ETH_ADDR_SCAN_ARGS(mac), &age)
902             != 2 + ETH_ADDR_SCAN_COUNT + 1) {
903             struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
904             VLOG_INFO_RL(&rl, "fdb/show output has invalid format: %s", line);
905             continue;
906         }
907
908         if (vlan != br_vlan) {
909             continue;
910         }
911
912         if (skip > 0) {
913             skip--;
914             continue;
915         }
916
917         /* Is this the MAC address of an interface on the bridge? */
918         is_local = false;
919         for (i = 0; i < n_local_macs; i++) {
920             if (eth_addr_equals(local_macs[i].addr, mac)) {
921                 is_local = true;
922                 break;
923             }
924         }
925
926         entry = ofpbuf_put_uninit(&query_data, sizeof *entry);
927         memcpy(entry->mac_addr, mac, ETH_ADDR_LEN);
928         entry->port_no = port & 0xff;
929         entry->is_local = is_local;
930         entry->ageing_timer_value = age * HZ;
931         entry->port_hi = (port & 0xff00) >> 8;
932         entry->pad0 = 0;
933         entry->unused = 0;
934         count--;
935     }
936     free(output);
937
938     /* Compose and send reply to datapath. */
939     reply = compose_reply(seq, 0);
940     nl_msg_put_unspec(reply, BRC_GENL_A_FDB_DATA,
941                       query_data.data, query_data.size);
942     send_reply(reply);
943
944     /* Free memory. */
945     ofpbuf_uninit(&query_data);
946
947     return 0;
948 }
949
950 static void
951 send_ifindex_reply(uint32_t seq, struct svec *ifaces)
952 {
953     struct ofpbuf *reply;
954     const char *iface;
955     size_t n_indices;
956     int *indices;
957     size_t i;
958
959     /* Make sure that any given interface only occurs once.  This shouldn't
960      * happen, but who knows what people put into their configuration files. */
961     svec_sort_unique(ifaces);
962
963     /* Convert 'ifaces' into ifindexes. */
964     n_indices = 0;
965     indices = xmalloc(ifaces->n * sizeof *indices);
966     SVEC_FOR_EACH (i, iface, ifaces) {
967         int ifindex = if_nametoindex(iface);
968         if (ifindex) {
969             indices[n_indices++] = ifindex;
970         }
971     }
972
973     /* Compose and send reply. */
974     reply = compose_reply(seq, 0);
975     nl_msg_put_unspec(reply, BRC_GENL_A_IFINDEXES,
976                       indices, n_indices * sizeof *indices);
977     send_reply(reply);
978
979     /* Free memory. */
980     free(indices);
981 }
982
983 static int
984 handle_get_bridges_cmd(const struct ovsrec_open_vswitch *ovs,
985                        struct ofpbuf *buffer)
986 {
987     struct svec bridges;
988     size_t i, j;
989
990     uint32_t seq;
991
992     int error;
993
994     /* Parse Netlink command.
995      *
996      * The command doesn't actually have any arguments, but we need the
997      * sequence number to send the reply. */
998     error = parse_command(buffer, &seq, NULL, NULL, NULL, NULL);
999     if (error) {
1000         return error;
1001     }
1002
1003     /* Get all the real bridges and all the fake ones. */
1004     svec_init(&bridges);
1005     for (i = 0; i < ovs->n_bridges; i++) {
1006         const struct ovsrec_bridge *br = ovs->bridges[i];
1007
1008         svec_add(&bridges, br->name);
1009         for (j = 0; j < br->n_ports; j++) {
1010             const struct ovsrec_port *port = br->ports[j];
1011
1012             if (port->fake_bridge) {
1013                 svec_add(&bridges, port->name);
1014             }
1015         }
1016     }
1017
1018     send_ifindex_reply(seq, &bridges);
1019     svec_destroy(&bridges);
1020
1021     return 0;
1022 }
1023
1024 static int
1025 handle_get_ports_cmd(const struct ovsrec_open_vswitch *ovs,
1026                      struct ofpbuf *buffer)
1027 {
1028     uint32_t seq;
1029
1030     const char *linux_name;
1031     const struct ovsrec_bridge *ovs_bridge;
1032     int br_vlan;
1033
1034     struct svec ports;
1035
1036     int error;
1037
1038     /* Parse Netlink command. */
1039     error = parse_command(buffer, &seq, &linux_name, NULL, NULL, NULL);
1040     if (error) {
1041         return error;
1042     }
1043
1044     error = linux_bridge_to_ovs_bridge(ovs, linux_name, 
1045                                        &ovs_bridge, &br_vlan);
1046     if (error) {
1047         send_simple_reply(seq, error);
1048         return error;
1049     }
1050
1051     svec_init(&ports);
1052     get_bridge_ports(ovs_bridge, &ports, br_vlan);
1053     svec_sort(&ports);
1054     svec_del(&ports, linux_name);
1055     send_ifindex_reply(seq, &ports); /* XXX bonds won't show up */
1056     svec_destroy(&ports);
1057
1058     return 0;
1059 }
1060
1061 static void
1062 brc_recv_update(struct ovsdb_idl *idl)
1063 {
1064     int retval;
1065     struct ofpbuf *buffer;
1066     struct genlmsghdr *genlmsghdr;
1067     const struct ovsrec_open_vswitch *ovs;
1068
1069     buffer = NULL;
1070     do {
1071         ofpbuf_delete(buffer);
1072         retval = nl_sock_recv(brc_sock, &buffer, false);
1073     } while (retval == ENOBUFS
1074             || (!retval
1075                 && (nl_msg_nlmsgerr(buffer, NULL)
1076                     || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE)));
1077     if (retval) {
1078         if (retval != EAGAIN) {
1079             VLOG_WARN_RL(&rl, "brc_recv_update: %s", strerror(retval));
1080         }
1081         return;
1082     }
1083
1084     genlmsghdr = nl_msg_genlmsghdr(buffer);
1085     if (!genlmsghdr) {
1086         VLOG_WARN_RL(&rl, "received packet too short for generic NetLink");
1087         goto error;
1088     }
1089
1090     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != brc_family) {
1091         VLOG_DBG_RL(&rl, "received type (%"PRIu16") != brcompat family (%d)",
1092                 nl_msg_nlmsghdr(buffer)->nlmsg_type, brc_family);
1093         goto error;
1094     }
1095
1096     /* Get the Open vSwitch configuration.  Just drop the request on the floor
1097      * if a valid configuration doesn't exist.  (We could check this earlier,
1098      * but we want to drain pending Netlink messages even when there is no Open
1099      * vSwitch configuration.) */
1100     ovs = ovsrec_open_vswitch_first(idl);
1101     if (!ovs) {
1102         VLOG_WARN_RL(&rl, "could not find valid configuration to update");
1103         goto error;
1104     }
1105
1106     switch (genlmsghdr->cmd) {
1107     case BRC_GENL_C_DP_ADD:
1108         handle_bridge_cmd(idl, ovs, buffer, true);
1109         break;
1110
1111     case BRC_GENL_C_DP_DEL:
1112         handle_bridge_cmd(idl, ovs, buffer, false);
1113         break;
1114
1115     case BRC_GENL_C_PORT_ADD:
1116         handle_port_cmd(idl, ovs, buffer, true);
1117         break;
1118
1119     case BRC_GENL_C_PORT_DEL:
1120         handle_port_cmd(idl, ovs, buffer, false);
1121         break;
1122
1123     case BRC_GENL_C_FDB_QUERY:
1124         handle_fdb_query_cmd(ovs, buffer);
1125         break;
1126
1127     case BRC_GENL_C_GET_BRIDGES:
1128         handle_get_bridges_cmd(ovs, buffer);
1129         break;
1130
1131     case BRC_GENL_C_GET_PORTS:
1132         handle_get_ports_cmd(ovs, buffer);
1133         break;
1134
1135     default:
1136         VLOG_WARN_RL(&rl, "received unknown brc netlink command: %d\n",
1137                      genlmsghdr->cmd);
1138         break;
1139     }
1140
1141 error:
1142     ofpbuf_delete(buffer);
1143     return;
1144 }
1145
1146 /* Check for interface configuration changes announced through RTNL. */
1147 static void
1148 rtnl_recv_update(struct ovsdb_idl *idl,
1149                  const struct ovsrec_open_vswitch *ovs)
1150 {
1151     struct ofpbuf *buf;
1152
1153     int error = nl_sock_recv(rtnl_sock, &buf, false);
1154     if (error == EAGAIN) {
1155         /* Nothing to do. */
1156     } else if (error == ENOBUFS) {
1157         VLOG_WARN_RL(&rl, "network monitor socket overflowed");
1158     } else if (error) {
1159         VLOG_WARN_RL(&rl, "error on network monitor socket: %s", 
1160                 strerror(error));
1161     } else {
1162         struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1163         struct nlmsghdr *nlh;
1164         struct ifinfomsg *iim;
1165
1166         nlh = ofpbuf_at(buf, 0, NLMSG_HDRLEN);
1167         iim = ofpbuf_at(buf, NLMSG_HDRLEN, sizeof *iim);
1168         if (!iim) {
1169             VLOG_WARN_RL(&rl, "received bad rtnl message (no ifinfomsg)");
1170             ofpbuf_delete(buf);
1171             return;
1172         } 
1173     
1174         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1175                              rtnlgrp_link_policy,
1176                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1177             VLOG_WARN_RL(&rl,"received bad rtnl message (policy)");
1178             ofpbuf_delete(buf);
1179             return;
1180         }
1181         if (nlh->nlmsg_type == RTM_DELLINK && attrs[IFLA_MASTER]) {
1182             const char *port_name = nl_attr_get_string(attrs[IFLA_IFNAME]);
1183             char br_name[IFNAMSIZ];
1184             uint32_t br_idx = nl_attr_get_u32(attrs[IFLA_MASTER]);
1185
1186             if (!if_indextoname(br_idx, br_name)) {
1187                 ofpbuf_delete(buf);
1188                 return;
1189             }
1190
1191             if (!netdev_exists(port_name)) {
1192                 /* Network device is really gone. */
1193                 struct ovsdb_idl_txn *txn;
1194                 struct ovsrec_bridge *br;
1195
1196                 VLOG_INFO("network device %s destroyed, "
1197                           "removing from bridge %s", port_name, br_name);
1198
1199                 br = find_bridge(ovs, br_name);
1200                 if (!br) {
1201                     VLOG_WARN("no bridge named %s from which to remove %s", 
1202                             br_name, port_name);
1203                     ofpbuf_delete(buf);
1204                     return;
1205                 }
1206
1207                 txn = ovsdb_idl_txn_create(idl);
1208                 ovsdb_idl_txn_add_comment(txn,
1209                                           "ovs-brcompatd: destroy port %s",
1210                                           port_name);
1211
1212                 del_port(br, port_name);
1213                 commit_txn(txn, false);
1214             } else {
1215                 /* A network device by that name exists even though the kernel
1216                  * told us it had disappeared.  Probably, what happened was
1217                  * this:
1218                  *
1219                  *      1. Device destroyed.
1220                  *      2. Notification sent to us.
1221                  *      3. New device created with same name as old one.
1222                  *      4. ovs-brcompatd notified, removes device from bridge.
1223                  *
1224                  * There's no a priori reason that in this situation that the
1225                  * new device with the same name should remain in the bridge;
1226                  * on the contrary, that would be unexpected.  *But* there is
1227                  * one important situation where, if we do this, bad things
1228                  * happen.  This is the case of XenServer Tools version 5.0.0,
1229                  * which on boot of a Windows VM cause something like this to
1230                  * happen on the Xen host:
1231                  *
1232                  *      i. Create tap1.0 and vif1.0.
1233                  *      ii. Delete tap1.0.
1234                  *      iii. Delete vif1.0.
1235                  *      iv. Re-create vif1.0.
1236                  *
1237                  * (XenServer Tools 5.5.0 does not exhibit this behavior, and
1238                  * neither does a VM without Tools installed at all.@.)
1239                  *
1240                  * Steps iii and iv happen within a few seconds of each other.
1241                  * Step iv causes /etc/xensource/scripts/vif to run, which in
1242                  * turn calls ovs-cfg-mod to add the new device to the bridge.
1243                  * If step iv happens after step 4 (in our first list of
1244                  * steps), then all is well, but if it happens between 3 and 4
1245                  * (which can easily happen if ovs-brcompatd has to wait to
1246                  * lock the configuration file), then we will remove the new
1247                  * incarnation from the bridge instead of the old one!
1248                  *
1249                  * So, to avoid this problem, we do nothing here.  This is
1250                  * strictly incorrect except for this one particular case, and
1251                  * perhaps that will bite us someday.  If that happens, then we
1252                  * will have to somehow track network devices by ifindex, since
1253                  * a new device will have a new ifindex even if it has the same
1254                  * name as an old device.
1255                  */
1256                 VLOG_INFO("kernel reported network device %s removed but "
1257                           "a device by that name exists (XS Tools 5.0.0?)",
1258                           port_name);
1259             }
1260         }
1261         ofpbuf_delete(buf);
1262     }
1263 }
1264
1265 int
1266 main(int argc, char *argv[])
1267 {
1268     struct unixctl_server *unixctl;
1269     const char *remote;
1270     struct ovsdb_idl *idl;
1271     int retval;
1272
1273     proctitle_init(argc, argv);
1274     set_program_name(argv[0]);
1275     time_init();
1276     vlog_init();
1277     vlog_set_levels(VLM_ANY_MODULE, VLF_CONSOLE, VLL_WARN);
1278     vlog_set_levels(VLM_reconnect, VLF_ANY_FACILITY, VLL_WARN);
1279
1280     remote = parse_options(argc, argv);
1281     signal(SIGPIPE, SIG_IGN);
1282     process_init();
1283     ovsrec_init();
1284
1285     die_if_already_running();
1286     daemonize_start();
1287
1288     retval = unixctl_server_create(NULL, &unixctl);
1289     if (retval) {
1290         exit(EXIT_FAILURE);
1291     }
1292
1293     if (brc_open(&brc_sock)) {
1294         ovs_fatal(0, "could not open brcompat socket.  Check "
1295                 "\"brcompat\" kernel module.");
1296     }
1297
1298     if (prune_timeout) {
1299         if (nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &rtnl_sock)) {
1300             ovs_fatal(0, "could not create rtnetlink socket");
1301         }
1302     }
1303
1304     daemonize_complete();
1305
1306     idl = ovsdb_idl_create(remote, &ovsrec_idl_class);
1307
1308     for (;;) {
1309         const struct ovsrec_open_vswitch *ovs;
1310
1311         ovsdb_idl_run(idl);
1312
1313         unixctl_server_run(unixctl);
1314         brc_recv_update(idl);
1315
1316         ovs = ovsrec_open_vswitch_first(idl);
1317         if (!ovs && ovsdb_idl_has_ever_connected(idl)) {
1318             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1319             VLOG_WARN_RL(&rl, "%s: database does not contain any Open vSwitch "
1320                          "configuration", remote);
1321         }
1322         netdev_run();
1323
1324         /* If 'prune_timeout' is non-zero, we actively prune from the
1325          * configuration of port entries that are no longer valid.  We 
1326          * use two methods: 
1327          *
1328          *   1) The kernel explicitly notifies us of removed ports
1329          *      through the RTNL messages.
1330          *
1331          *   2) We periodically check all ports associated with bridges
1332          *      to see if they no longer exist.
1333          */
1334         if (ovs && prune_timeout) {
1335             rtnl_recv_update(idl, ovs);
1336 #if 0
1337             prune_ports();
1338 #endif
1339
1340             nl_sock_wait(rtnl_sock, POLLIN);
1341             poll_timer_wait(prune_timeout);
1342         }
1343
1344
1345         nl_sock_wait(brc_sock, POLLIN);
1346         ovsdb_idl_wait(idl);
1347         unixctl_server_wait(unixctl);
1348         netdev_wait();
1349         poll_block();
1350     }
1351
1352     ovsdb_idl_destroy(idl);
1353
1354     return 0;
1355 }
1356
1357 static void
1358 validate_appctl_command(void)
1359 {
1360     const char *p;
1361     int n;
1362
1363     n = 0;
1364     for (p = strchr(appctl_command, '%'); p; p = strchr(p + 2, '%')) {
1365         if (p[1] == '%') {
1366             /* Nothing to do. */
1367         } else if (p[1] == 's') {
1368             n++;
1369         } else {
1370             ovs_fatal(0, "only '%%s' and '%%%%' allowed in --appctl-command");
1371         }
1372     }
1373     if (n != 1) {
1374         ovs_fatal(0, "'%%s' must appear exactly once in --appctl-command");
1375     }
1376 }
1377
1378 static const char *
1379 parse_options(int argc, char *argv[])
1380 {
1381     enum {
1382         OPT_PRUNE_TIMEOUT,
1383         OPT_APPCTL_COMMAND,
1384         VLOG_OPTION_ENUMS,
1385         LEAK_CHECKER_OPTION_ENUMS
1386     };
1387     static struct option long_options[] = {
1388         {"help",             no_argument, 0, 'h'},
1389         {"version",          no_argument, 0, 'V'},
1390         {"prune-timeout",    required_argument, 0, OPT_PRUNE_TIMEOUT},
1391         {"appctl-command",   required_argument, 0, OPT_APPCTL_COMMAND},
1392         DAEMON_LONG_OPTIONS,
1393         VLOG_LONG_OPTIONS,
1394         LEAK_CHECKER_LONG_OPTIONS,
1395         {0, 0, 0, 0},
1396     };
1397     char *short_options = long_options_to_short_options(long_options);
1398
1399     appctl_command = xasprintf("%s/ovs-appctl %%s", ovs_bindir);
1400     for (;;) {
1401         int c;
1402
1403         c = getopt_long(argc, argv, short_options, long_options, NULL);
1404         if (c == -1) {
1405             break;
1406         }
1407
1408         switch (c) {
1409         case 'H':
1410         case 'h':
1411             usage();
1412
1413         case 'V':
1414             OVS_PRINT_VERSION(0, 0);
1415             exit(EXIT_SUCCESS);
1416
1417         case OPT_PRUNE_TIMEOUT:
1418             prune_timeout = atoi(optarg) * 1000;
1419             break;
1420
1421         case OPT_APPCTL_COMMAND:
1422             appctl_command = optarg;
1423             break;
1424
1425         VLOG_OPTION_HANDLERS
1426         DAEMON_OPTION_HANDLERS
1427         LEAK_CHECKER_OPTION_HANDLERS
1428
1429         case '?':
1430             exit(EXIT_FAILURE);
1431
1432         default:
1433             abort();
1434         }
1435     }
1436     free(short_options);
1437
1438     validate_appctl_command();
1439
1440     argc -= optind;
1441     argv += optind;
1442
1443     if (argc != 1) {
1444         ovs_fatal(0, "database socket is non-option argument; "
1445                 "use --help for usage");
1446     }
1447
1448     return argv[0];
1449 }
1450
1451 static void
1452 usage(void)
1453 {
1454     printf("%s: bridge compatibility front-end for ovs-vswitchd\n"
1455            "usage: %s [OPTIONS] CONFIG\n"
1456            "CONFIG is the configuration file used by ovs-vswitchd.\n",
1457            program_name, program_name);
1458     printf("\nConfiguration options:\n"
1459            "  --appctl-command=COMMAND  shell command to run ovs-appctl\n"
1460            "  --prune-timeout=SECS    wait at most SECS before pruning ports\n"
1461           );
1462     daemon_usage();
1463     vlog_usage();
1464     printf("\nOther options:\n"
1465            "  -h, --help              display this help message\n"
1466            "  -V, --version           display version information\n");
1467     leak_checker_usage();
1468     printf("\nThe default appctl command is:\n%s\n", appctl_command);
1469     exit(EXIT_SUCCESS);
1470 }