Implement "brctl showmacs" support in brcompat and ovs-brcompatd.
[sliver-openvswitch.git] / vswitchd / ovs-brcompatd.c
1 /* Copyright (c) 2008, 2009 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 "cfg.h"
37 #include "command-line.h"
38 #include "coverage.h"
39 #include "daemon.h"
40 #include "dirs.h"
41 #include "dpif.h"
42 #include "dynamic-string.h"
43 #include "fatal-signal.h"
44 #include "fault.h"
45 #include "leak-checker.h"
46 #include "netdev.h"
47 #include "netlink.h"
48 #include "ofpbuf.h"
49 #include "openvswitch/brcompat-netlink.h"
50 #include "packets.h"
51 #include "poll-loop.h"
52 #include "process.h"
53 #include "signals.h"
54 #include "svec.h"
55 #include "timeval.h"
56 #include "unixctl.h"
57 #include "util.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 void 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 for the config file to be
79  * unlocked.  If set to zero, no waiting will occur. */
80 static int lock_timeout = 500;
81
82 /* Maximum number of milliseconds to wait before pruning port entries that 
83  * no longer exist.  If set to zero, ports are never pruned. */
84 static int prune_timeout = 5000;
85
86 /* Config file shared with ovs-vswitchd (usually ovs-vswitchd.conf). */
87 static char *config_file;
88
89 /* Shell command to execute (via popen()) to send a control command to the
90  * running ovs-vswitchd process.  The string must contain one instance of %s,
91  * which is replaced by the control command. */
92 static char *appctl_command;
93
94 /* Netlink socket to listen for interface changes. */
95 static struct nl_sock *rtnl_sock;
96
97 /* Netlink socket to bridge compatibility kernel module. */
98 static struct nl_sock *brc_sock;
99
100 /* The Generic Netlink family number used for bridge compatibility. */
101 static int brc_family;
102
103 static const struct nl_policy brc_multicast_policy[] = {
104     [BRC_GENL_A_MC_GROUP] = {.type = NL_A_U32 }
105 };
106
107 static const struct nl_policy rtnlgrp_link_policy[] = {
108     [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
109     [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
110 };
111
112 static int
113 lookup_brc_multicast_group(int *multicast_group)
114 {
115     struct nl_sock *sock;
116     struct ofpbuf request, *reply;
117     struct nlattr *attrs[ARRAY_SIZE(brc_multicast_policy)];
118     int retval;
119
120     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
121     if (retval) {
122         return retval;
123     }
124     ofpbuf_init(&request, 0);
125     nl_msg_put_genlmsghdr(&request, sock, 0, brc_family,
126             NLM_F_REQUEST, BRC_GENL_C_QUERY_MC, 1);
127     retval = nl_sock_transact(sock, &request, &reply);
128     ofpbuf_uninit(&request);
129     if (retval) {
130         nl_sock_destroy(sock);
131         return retval;
132     }
133     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
134                          brc_multicast_policy, attrs,
135                          ARRAY_SIZE(brc_multicast_policy))) {
136         nl_sock_destroy(sock);
137         ofpbuf_delete(reply);
138         return EPROTO;
139     }
140     *multicast_group = nl_attr_get_u32(attrs[BRC_GENL_A_MC_GROUP]);
141     nl_sock_destroy(sock);
142     ofpbuf_delete(reply);
143
144     return 0;
145 }
146
147 /* Opens a socket for brcompat notifications.  Returns 0 if successful,
148  * otherwise a positive errno value. */
149 static int
150 brc_open(struct nl_sock **sock)
151 {
152     int multicast_group = 0;
153     int retval;
154
155     retval = nl_lookup_genl_family(BRC_GENL_FAMILY_NAME, &brc_family);
156     if (retval) {
157         return retval;
158     }
159
160     retval = lookup_brc_multicast_group(&multicast_group);
161     if (retval) {
162         return retval;
163     }
164
165     retval = nl_sock_create(NETLINK_GENERIC, multicast_group, 0, 0, sock);
166     if (retval) {
167         return retval;
168     }
169
170     return 0;
171 }
172
173 static const struct nl_policy brc_dp_policy[] = {
174     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
175 };
176
177 static bool
178 bridge_exists(const char *name)
179 {
180     return cfg_has_section("bridge.%s", name);
181 }
182
183 static int
184 execute_appctl_command(const char *unixctl_command, char **output)
185 {
186     char *stdout_log, *stderr_log;
187     int error, status;
188     char *argv[5];
189
190     argv[0] = "/bin/sh";
191     argv[1] = "-c";
192     argv[2] = xasprintf(appctl_command, unixctl_command);
193     argv[3] = NULL;
194
195     /* Run process and log status. */
196     error = process_run_capture(argv, &stdout_log, &stderr_log, &status);
197     if (error) {
198         VLOG_ERR("failed to execute %s command via ovs-appctl: %s",
199                  unixctl_command, strerror(error));
200     } else if (status) {
201         char *msg = process_status_msg(status);
202         VLOG_ERR("ovs-appctl exited with error (%s)", msg);
203         free(msg);
204         error = ECHILD;
205     }
206
207     /* Deal with stdout_log. */
208     if (output) {
209         *output = stdout_log;
210     } else {
211         free(stdout_log);
212     }
213
214     /* Deal with stderr_log */
215     if (stderr_log && *stderr_log) {
216         VLOG_INFO("ovs-appctl wrote to stderr:\n%s", stderr_log);
217     }
218     free(stderr_log);
219
220     free(argv[2]);
221
222     return error;
223 }
224
225 static int
226 rewrite_and_reload_config(void)
227 {
228     if (cfg_is_dirty()) {
229         int error1 = cfg_write();
230         int error2 = cfg_read();
231         long long int reload_start = time_msec();
232         int error3 = execute_appctl_command("vswitchd/reload", NULL);
233         long long int elapsed = time_msec() - reload_start;
234         COVERAGE_INC(brcompatd_reload);
235         if (elapsed > 0) {
236             VLOG_INFO("reload command executed in %lld ms", elapsed);
237         }
238         return error1 ? error1 : error2 ? error2 : error3;
239     }
240     return 0;
241 }
242
243 /* Get all the interfaces for 'bridge' as 'ifaces', breaking bonded interfaces
244  * down into their constituent parts. */
245 static void
246 get_bridge_ifaces(const char *bridge, struct svec *ifaces)
247 {
248     struct svec ports;
249     int i;
250
251     svec_init(&ports);
252     svec_init(ifaces);
253     cfg_get_all_keys(&ports, "bridge.%s.port", bridge);
254     for (i = 0; i < ports.n; i++) {
255         const char *port_name = ports.names[i];
256         if (cfg_has_section("bonding.%s", port_name)) {
257             struct svec slaves;
258             svec_init(&slaves);
259             cfg_get_all_keys(&slaves, "bonding.%s.slave", port_name);
260             svec_append(ifaces, &slaves);
261             svec_destroy(&slaves);
262         } else {
263             svec_add(ifaces, port_name);
264         }
265     }
266     svec_destroy(&ports);
267 }
268
269 /* Go through the configuration file and remove any ports that no longer
270  * exist associated with a bridge. */
271 static void
272 prune_ports(void)
273 {
274     int i, j;
275     int error;
276     struct svec bridges, delete;
277
278     if (cfg_lock(NULL, 0)) {
279         /* Couldn't lock config file. */
280         return;
281     }
282
283     svec_init(&bridges);
284     svec_init(&delete);
285     cfg_get_subsections(&bridges, "bridge");
286     for (i=0; i<bridges.n; i++) {
287         const char *br_name = bridges.names[i];
288         struct svec ifaces;
289
290         /* Check that each bridge interface exists. */
291         get_bridge_ifaces(br_name, &ifaces);
292         for (j = 0; j < ifaces.n; j++) {
293             const char *iface_name = ifaces.names[j];
294             enum netdev_flags flags;
295
296             /* The local port and internal ports are created and destroyed by
297              * ovs-vswitchd itself, so don't bother checking for them at all.
298              * In practice, they might not exist if ovs-vswitchd hasn't
299              * finished reloading since the configuration file was updated. */
300             if (!strcmp(iface_name, br_name)
301                 || cfg_get_bool(0, "iface.%s.internal", iface_name)) {
302                 continue;
303             }
304
305             error = netdev_nodev_get_flags(iface_name, &flags);
306             if (error == ENODEV) {
307                 VLOG_INFO_RL(&rl, "removing dead interface %s from %s",
308                              iface_name, br_name);
309                 svec_add(&delete, iface_name);
310             } else if (error) {
311                 VLOG_INFO_RL(&rl, "unknown error %d on interface %s from %s",
312                              error, iface_name, br_name);
313             }
314         }
315         svec_destroy(&ifaces);
316     }
317     svec_destroy(&bridges);
318
319     if (delete.n) {
320         size_t i;
321
322         for (i = 0; i < delete.n; i++) {
323             cfg_del_match("bridge.*.port=%s", delete.names[i]);
324             cfg_del_match("bonding.*.slave=%s", delete.names[i]);
325         }
326         rewrite_and_reload_config();
327         cfg_unlock();
328     } else {
329         cfg_unlock();
330     }
331     svec_destroy(&delete);
332 }
333
334
335 /* Checks whether a network device named 'name' exists and returns true if so,
336  * false otherwise.
337  *
338  * XXX it is possible that this doesn't entirely accomplish what we want in
339  * context, since ovs-vswitchd.conf may cause vswitchd to create or destroy
340  * network devices based on iface.*.internal settings.
341  *
342  * XXX may want to move this to lib/netdev.
343  *
344  * XXX why not just use netdev_nodev_get_flags() or similar function? */
345 static bool
346 netdev_exists(const char *name)
347 {
348     struct stat s;
349     char *filename;
350     int error;
351
352     filename = xasprintf("/sys/class/net/%s", name);
353     error = stat(filename, &s);
354     free(filename);
355     return !error;
356 }
357
358 static int
359 add_bridge(const char *br_name)
360 {
361     if (bridge_exists(br_name)) {
362         VLOG_WARN("addbr %s: bridge %s exists", br_name, br_name);
363         return EEXIST;
364     } else if (netdev_exists(br_name)) {
365         if (cfg_get_bool(0, "iface.%s.fake-bridge", br_name)) {
366             VLOG_WARN("addbr %s: %s exists as a fake bridge",
367                       br_name, br_name);
368             return 0;
369         } else {
370             VLOG_WARN("addbr %s: cannot create bridge %s because a network "
371                       "device named %s already exists",
372                       br_name, br_name, br_name);
373             return EEXIST;
374         }
375     }
376
377     cfg_add_entry("bridge.%s.port=%s", br_name, br_name);
378     VLOG_INFO("addbr %s: success", br_name);
379
380     return 0;
381 }
382
383 static int 
384 del_bridge(const char *br_name)
385 {
386     if (!bridge_exists(br_name)) {
387         VLOG_WARN("delbr %s: no bridge named %s", br_name, br_name);
388         return ENXIO;
389     }
390
391     cfg_del_section("bridge.%s", br_name);
392     VLOG_INFO("delbr %s: success", br_name);
393
394     return 0;
395 }
396
397 static int
398 parse_command(struct ofpbuf *buffer, uint32_t *seq, const char **br_name,
399               const char **port_name, uint64_t *count, uint64_t *skip)
400 {
401     static const struct nl_policy policy[] = {
402         [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
403         [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING, .optional = true },
404         [BRC_GENL_A_FDB_COUNT] = { .type = NL_A_U64, .optional = true },
405         [BRC_GENL_A_FDB_SKIP] = { .type = NL_A_U64, .optional = true },
406     };
407     struct nlattr *attrs[ARRAY_SIZE(policy)];
408
409     if (!nl_policy_parse(buffer, NLMSG_HDRLEN + GENL_HDRLEN, policy,
410                          attrs, ARRAY_SIZE(policy))
411         || (port_name && !attrs[BRC_GENL_A_PORT_NAME])
412         || (count && !attrs[BRC_GENL_A_FDB_COUNT])
413         || (skip && !attrs[BRC_GENL_A_FDB_SKIP])) {
414         return EINVAL;
415     }
416
417     *seq = ((struct nlmsghdr *) buffer->data)->nlmsg_seq;
418     *br_name = nl_attr_get_string(attrs[BRC_GENL_A_DP_NAME]);
419     if (port_name) {
420         *port_name = nl_attr_get_string(attrs[BRC_GENL_A_PORT_NAME]);
421     }
422     if (count) {
423         *count = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_COUNT]);
424     }
425     if (skip) {
426         *skip = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_SKIP]);
427     }
428     return 0;
429 }
430
431 static void
432 send_reply(uint32_t seq, int error, struct ofpbuf *fdb_query_data)
433 {
434     struct ofpbuf msg;
435     int retval;
436
437     /* Compose reply. */
438     ofpbuf_init(&msg, 0);
439     nl_msg_put_genlmsghdr(&msg, brc_sock, 32, brc_family, NLM_F_REQUEST,
440                           BRC_GENL_C_DP_RESULT, 1);
441     ((struct nlmsghdr *) msg.data)->nlmsg_seq = seq;
442     nl_msg_put_u32(&msg, BRC_GENL_A_ERR_CODE, error);
443     if (fdb_query_data) {
444         nl_msg_put_unspec(&msg, BRC_GENL_A_FDB_DATA,
445                           fdb_query_data->data, fdb_query_data->size);
446     }
447
448     /* Send reply. */
449     retval = nl_sock_send(brc_sock, &msg, false);
450     if (retval) {
451         VLOG_WARN_RL(&rl, "replying to brcompat request: %s",
452                      strerror(retval));
453     }
454     ofpbuf_uninit(&msg);
455 }
456
457 static int
458 handle_bridge_cmd(struct ofpbuf *buffer, bool add)
459 {
460     const char *br_name;
461     uint32_t seq;
462     int error;
463
464     error = parse_command(buffer, &seq, &br_name, NULL, NULL, NULL);
465     if (!error) {
466         error = add ? add_bridge(br_name) : del_bridge(br_name);
467         if (!error) {
468             error = rewrite_and_reload_config();
469         }
470         send_reply(seq, error, NULL);
471     }
472     return error;
473 }
474
475 static const struct nl_policy brc_port_policy[] = {
476     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
477     [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING },
478 };
479
480 static void
481 del_port(const char *br_name, const char *port_name)
482 {
483     cfg_del_entry("bridge.%s.port=%s", br_name, port_name);
484     cfg_del_match("bonding.*.slave=%s", port_name);
485     cfg_del_match("vlan.%s.*", port_name);
486 }
487
488 static int
489 handle_port_cmd(struct ofpbuf *buffer, bool add)
490 {
491     const char *cmd_name = add ? "add-if" : "del-if";
492     const char *br_name, *port_name;
493     uint32_t seq;
494     int error;
495
496     error = parse_command(buffer, &seq, &br_name, &port_name, NULL, NULL);
497     if (!error) {
498         if (!bridge_exists(br_name)) {
499             VLOG_WARN("%s %s %s: no bridge named %s",
500                       cmd_name, br_name, port_name, br_name);
501             error = EINVAL;
502         } else if (!netdev_exists(port_name)) {
503             VLOG_WARN("%s %s %s: no network device named %s",
504                       cmd_name, br_name, port_name, port_name);
505             error = EINVAL;
506         } else {
507             if (add) {
508                 cfg_add_entry("bridge.%s.port=%s", br_name, port_name);
509             } else {
510                 del_port(br_name, port_name);
511             }
512             VLOG_INFO("%s %s %s: success", cmd_name, br_name, port_name);
513             error = rewrite_and_reload_config();
514         }
515         send_reply(seq, error, NULL);
516     }
517
518     return error;
519 }
520
521 static int
522 handle_fdb_query_cmd(struct ofpbuf *buffer)
523 {
524     /* This structure is copied directly from the Linux 2.6.30 header files.
525      * It would be more straightforward to #include <linux/if_bridge.h>, but
526      * the 'port_hi' member was only introduced in Linux 2.6.26 and so systems
527      * with old header files won't have it. */
528     struct __fdb_entry {
529         __u8 mac_addr[6];
530         __u8 port_no;
531         __u8 is_local;
532         __u32 ageing_timer_value;
533         __u8 port_hi;
534         __u8 pad0;
535         __u16 unused;
536     };
537
538     struct mac {
539         uint8_t addr[6];
540     };
541     struct mac *local_macs;
542     int n_local_macs;
543     int i;
544
545     struct ofpbuf query_data;
546     char *unixctl_command;
547     uint64_t count, skip;
548     const char *br_name;
549     struct svec ifaces;
550     char *output;
551     char *save_ptr;
552     uint32_t seq;
553     int error;
554
555     /* Parse the command received from brcompat_mod. */
556     error = parse_command(buffer, &seq, &br_name, NULL, &count, &skip);
557     if (error) {
558         return error;
559     }
560
561     /* Fetch the forwarding database using ovs-appctl. */
562     unixctl_command = xasprintf("fdb/show %s", br_name);
563     error = execute_appctl_command(unixctl_command, &output);
564     free(unixctl_command);
565     if (error) {
566         send_reply(seq, error, NULL);
567         return error;
568     }
569
570     /* Fetch the MAC address for each interface on the bridge, so that we can
571      * fill in the is_local field in the response. */
572     cfg_read();
573     get_bridge_ifaces(br_name, &ifaces);
574     local_macs = xmalloc(ifaces.n * sizeof *local_macs);
575     n_local_macs = 0;
576     for (i = 0; i < ifaces.n; i++) {
577         const char *iface_name = ifaces.names[i];
578         struct mac *mac = &local_macs[n_local_macs];
579         if (!netdev_nodev_get_etheraddr(iface_name, mac->addr)) {
580             n_local_macs++;
581         }
582     }
583     svec_destroy(&ifaces);
584
585     /* Parse the response from ovs-appctl and convert it to binary format to
586      * pass back to the kernel. */
587     ofpbuf_init(&query_data, sizeof(struct __fdb_entry) * 8);
588     save_ptr = NULL;
589     strtok_r(output, "\n", &save_ptr); /* Skip header line. */
590     while (count > 0) {
591         struct __fdb_entry *entry;
592         int port, vlan, age;
593         uint8_t mac[ETH_ADDR_LEN];
594         char *line;
595         bool is_local;
596
597         line = strtok_r(NULL, "\n", &save_ptr);
598         if (!line) {
599             break;
600         }
601
602         if (sscanf(line, "%d %d "ETH_ADDR_SCAN_FMT" %d",
603                    &port, &vlan, ETH_ADDR_SCAN_ARGS(mac), &age)
604             != 2 + ETH_ADDR_SCAN_COUNT + 1) {
605             struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
606             VLOG_INFO_RL(&rl, "fdb/show output has invalid format: %s", line);
607             continue;
608         }
609
610         if (skip > 0) {
611             skip--;
612             continue;
613         }
614
615         /* Is this the MAC address of an interface on the bridge? */
616         is_local = false;
617         for (i = 0; i < n_local_macs; i++) {
618             if (eth_addr_equals(local_macs[i].addr, mac)) {
619                 is_local = true;
620                 break;
621             }
622         }
623
624         entry = ofpbuf_put_uninit(&query_data, sizeof *entry);
625         memcpy(entry->mac_addr, mac, ETH_ADDR_LEN);
626         entry->port_no = port & 0xff;
627         entry->is_local = is_local;
628         entry->ageing_timer_value = age * HZ;
629         entry->port_hi = (port & 0xff00) >> 8;
630         entry->pad0 = 0;
631         entry->unused = 0;
632         count--;
633     }
634     free(output);
635
636     send_reply(seq, 0, &query_data);
637     ofpbuf_uninit(&query_data);
638
639     return 0;
640 }
641
642 static int
643 brc_recv_update(void)
644 {
645     int retval;
646     struct ofpbuf *buffer;
647     struct genlmsghdr *genlmsghdr;
648
649
650     buffer = NULL;
651     do {
652         ofpbuf_delete(buffer);
653         retval = nl_sock_recv(brc_sock, &buffer, false);
654     } while (retval == ENOBUFS
655             || (!retval
656                 && (nl_msg_nlmsgerr(buffer, NULL)
657                     || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE)));
658     if (retval) {
659         if (retval != EAGAIN) {
660             VLOG_WARN_RL(&rl, "brc_recv_update: %s", strerror(retval));
661         }
662         return retval;
663     }
664
665     genlmsghdr = nl_msg_genlmsghdr(buffer);
666     if (!genlmsghdr) {
667         VLOG_WARN_RL(&rl, "received packet too short for generic NetLink");
668         goto error;
669     }
670
671     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != brc_family) {
672         VLOG_DBG_RL(&rl, "received type (%"PRIu16") != brcompat family (%d)",
673                 nl_msg_nlmsghdr(buffer)->nlmsg_type, brc_family);
674         goto error;
675     }
676
677     if (cfg_lock(NULL, lock_timeout)) {
678         /* Couldn't lock config file. */
679         retval = EAGAIN;
680         goto error;
681     }
682
683     switch (genlmsghdr->cmd) {
684     case BRC_GENL_C_DP_ADD:
685         retval = handle_bridge_cmd(buffer, true);
686         break;
687
688     case BRC_GENL_C_DP_DEL:
689         retval = handle_bridge_cmd(buffer, false);
690         break;
691
692     case BRC_GENL_C_PORT_ADD:
693         retval = handle_port_cmd(buffer, true);
694         break;
695
696     case BRC_GENL_C_PORT_DEL:
697         retval = handle_port_cmd(buffer, false);
698         break;
699
700     case BRC_GENL_C_FDB_QUERY:
701         retval = handle_fdb_query_cmd(buffer);
702         break;
703
704     default:
705         retval = EPROTO;
706     }
707
708     cfg_unlock();
709
710 error:
711     ofpbuf_delete(buffer);
712     return retval;
713 }
714
715 /* Check for interface configuration changes announced through RTNL. */
716 static void
717 rtnl_recv_update(void)
718 {
719     struct ofpbuf *buf;
720
721     int error = nl_sock_recv(rtnl_sock, &buf, false);
722     if (error == EAGAIN) {
723         /* Nothing to do. */
724     } else if (error == ENOBUFS) {
725         VLOG_WARN_RL(&rl, "network monitor socket overflowed");
726     } else if (error) {
727         VLOG_WARN_RL(&rl, "error on network monitor socket: %s", 
728                 strerror(error));
729     } else {
730         struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
731         struct nlmsghdr *nlh;
732         struct ifinfomsg *iim;
733
734         nlh = ofpbuf_at(buf, 0, NLMSG_HDRLEN);
735         iim = ofpbuf_at(buf, NLMSG_HDRLEN, sizeof *iim);
736         if (!iim) {
737             VLOG_WARN_RL(&rl, "received bad rtnl message (no ifinfomsg)");
738             ofpbuf_delete(buf);
739             return;
740         } 
741     
742         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
743                              rtnlgrp_link_policy,
744                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
745             VLOG_WARN_RL(&rl,"received bad rtnl message (policy)");
746             ofpbuf_delete(buf);
747             return;
748         }
749         if (nlh->nlmsg_type == RTM_DELLINK && attrs[IFLA_MASTER]) {
750             const char *port_name = nl_attr_get_string(attrs[IFLA_IFNAME]);
751             char br_name[IFNAMSIZ];
752             uint32_t br_idx = nl_attr_get_u32(attrs[IFLA_MASTER]);
753             struct svec ports;
754             enum netdev_flags flags;
755
756             if (!if_indextoname(br_idx, br_name)) {
757                 ofpbuf_delete(buf);
758                 return;
759             }
760
761             if (cfg_lock(NULL, lock_timeout)) {
762                 /* Couldn't lock config file. */
763                 /* xxx this should try again and print error msg. */
764                 ofpbuf_delete(buf);
765                 return;
766             }
767
768             if (netdev_nodev_get_flags(port_name, &flags) == ENODEV) {
769                 /* Network device is really gone. */
770                 VLOG_INFO("network device %s destroyed, "
771                           "removing from bridge %s", port_name, br_name);
772                 svec_init(&ports);
773                 cfg_get_all_keys(&ports, "bridge.%s.port", br_name);
774                 svec_sort(&ports);
775                 if (svec_contains(&ports, port_name)) {
776                     del_port(br_name, port_name);
777                     rewrite_and_reload_config();
778                 }
779             } else {
780                 /* A network device by that name exists even though the kernel
781                  * told us it had disappeared.  Probably, what happened was
782                  * this:
783                  *
784                  *      1. Device destroyed.
785                  *      2. Notification sent to us.
786                  *      3. New device created with same name as old one.
787                  *      4. ovs-brcompatd notified, removes device from bridge.
788                  *
789                  * There's no a priori reason that in this situation that the
790                  * new device with the same name should remain in the bridge;
791                  * on the contrary, that would be unexpected.  *But* there is
792                  * one important situation where, if we do this, bad things
793                  * happen.  This is the case of XenServer Tools version 5.0.0,
794                  * which on boot of a Windows VM cause something like this to
795                  * happen on the Xen host:
796                  *
797                  *      i. Create tap1.0 and vif1.0.
798                  *      ii. Delete tap1.0.
799                  *      iii. Delete vif1.0.
800                  *      iv. Re-create vif1.0.
801                  *
802                  * (XenServer Tools 5.5.0 does not exhibit this behavior, and
803                  * neither does a VM without Tools installed at all.@.)
804                  *
805                  * Steps iii and iv happen within a few seconds of each other.
806                  * Step iv causes /etc/xensource/scripts/vif to run, which in
807                  * turn calls ovs-cfg-mod to add the new device to the bridge.
808                  * If step iv happens after step 4 (in our first list of
809                  * steps), then all is well, but if it happens between 3 and 4
810                  * (which can easily happen if ovs-brcompatd has to wait to
811                  * lock the configuration file), then we will remove the new
812                  * incarnation from the bridge instead of the old one!
813                  *
814                  * So, to avoid this problem, we do nothing here.  This is
815                  * strictly incorrect except for this one particular case, and
816                  * perhaps that will bite us someday.  If that happens, then we
817                  * will have to somehow track network devices by ifindex, since
818                  * a new device will have a new ifindex even if it has the same
819                  * name as an old device.
820                  */
821                 VLOG_INFO("kernel reported network device %s removed but "
822                           "a device by that name exists (XS Tools 5.0.0?)",
823                           port_name);
824             }
825             cfg_unlock();
826         }
827         ofpbuf_delete(buf);
828     }
829 }
830
831 int
832 main(int argc, char *argv[])
833 {
834     struct unixctl_server *unixctl;
835     int retval;
836
837     set_program_name(argv[0]);
838     register_fault_handlers();
839     time_init();
840     vlog_init();
841     parse_options(argc, argv);
842     signal(SIGPIPE, SIG_IGN);
843     process_init();
844
845     die_if_already_running();
846     daemonize();
847
848     retval = unixctl_server_create(NULL, &unixctl);
849     if (retval) {
850         ovs_fatal(retval, "could not listen for vlog connections");
851     }
852
853     if (brc_open(&brc_sock)) {
854         ovs_fatal(0, "could not open brcompat socket.  Check "
855                 "\"brcompat\" kernel module.");
856     }
857
858     if (prune_timeout) {
859         if (nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &rtnl_sock)) {
860             ovs_fatal(0, "could not create rtnetlink socket");
861         }
862     }
863
864     cfg_read();
865
866     for (;;) {
867         unixctl_server_run(unixctl);
868         brc_recv_update();
869
870         /* If 'prune_timeout' is non-zero, we actively prune from the
871          * config file any 'bridge.<br_name>.port' entries that are no 
872          * longer valid.  We use two methods: 
873          *
874          *   1) The kernel explicitly notifies us of removed ports
875          *      through the RTNL messages.
876          *
877          *   2) We periodically check all ports associated with bridges
878          *      to see if they no longer exist.
879          */
880         if (prune_timeout) {
881             rtnl_recv_update();
882             prune_ports();
883
884             nl_sock_wait(rtnl_sock, POLLIN);
885             poll_timer_wait(prune_timeout);
886         }
887
888         nl_sock_wait(brc_sock, POLLIN);
889         unixctl_server_wait(unixctl);
890         poll_block();
891     }
892
893     return 0;
894 }
895
896 static void
897 validate_appctl_command(void)
898 {
899     const char *p;
900     int n;
901
902     n = 0;
903     for (p = strchr(appctl_command, '%'); p; p = strchr(p + 2, '%')) {
904         if (p[1] == '%') {
905             /* Nothing to do. */
906         } else if (p[1] == 's') {
907             n++;
908         } else {
909             ovs_fatal(0, "only '%%s' and '%%%%' allowed in --appctl-command");
910         }
911     }
912     if (n != 1) {
913         ovs_fatal(0, "'%%s' must appear exactly once in --appctl-command");
914     }
915 }
916
917 static void
918 parse_options(int argc, char *argv[])
919 {
920     enum {
921         OPT_LOCK_TIMEOUT = UCHAR_MAX + 1,
922         OPT_PRUNE_TIMEOUT,
923         OPT_APPCTL_COMMAND,
924         VLOG_OPTION_ENUMS,
925         LEAK_CHECKER_OPTION_ENUMS
926     };
927     static struct option long_options[] = {
928         {"help",             no_argument, 0, 'h'},
929         {"version",          no_argument, 0, 'V'},
930         {"lock-timeout",     required_argument, 0, OPT_LOCK_TIMEOUT},
931         {"prune-timeout",    required_argument, 0, OPT_PRUNE_TIMEOUT},
932         {"appctl-command",   required_argument, 0, OPT_APPCTL_COMMAND},
933         DAEMON_LONG_OPTIONS,
934         VLOG_LONG_OPTIONS,
935         LEAK_CHECKER_LONG_OPTIONS,
936         {0, 0, 0, 0},
937     };
938     char *short_options = long_options_to_short_options(long_options);
939     int error;
940
941     appctl_command = xasprintf("%s/ovs-appctl -t "
942                                "%s/ovs-vswitchd.`cat %s/ovs-vswitchd.pid`.ctl "
943                                "-e '%%s'",
944                                ovs_bindir, ovs_rundir, ovs_rundir);
945     for (;;) {
946         int c;
947
948         c = getopt_long(argc, argv, short_options, long_options, NULL);
949         if (c == -1) {
950             break;
951         }
952
953         switch (c) {
954         case 'H':
955         case 'h':
956             usage();
957
958         case 'V':
959             OVS_PRINT_VERSION(0, 0);
960             exit(EXIT_SUCCESS);
961
962         case OPT_LOCK_TIMEOUT:
963             lock_timeout = atoi(optarg);
964             break;
965
966         case OPT_PRUNE_TIMEOUT:
967             prune_timeout = atoi(optarg) * 1000;
968             break;
969
970         case OPT_APPCTL_COMMAND:
971             appctl_command = optarg;
972             break;
973
974         VLOG_OPTION_HANDLERS
975         DAEMON_OPTION_HANDLERS
976         LEAK_CHECKER_OPTION_HANDLERS
977
978         case '?':
979             exit(EXIT_FAILURE);
980
981         default:
982             abort();
983         }
984     }
985     free(short_options);
986
987     validate_appctl_command();
988
989     argc -= optind;
990     argv += optind;
991
992     if (argc != 1) {
993         ovs_fatal(0, "exactly one non-option argument required; "
994                 "use --help for usage");
995     }
996
997     config_file = argv[0];
998     error = cfg_set_file(config_file);
999     if (error) {
1000         ovs_fatal(error, "failed to add configuration file \"%s\"", 
1001                 config_file);
1002     }
1003 }
1004
1005 static void
1006 usage(void)
1007 {
1008     printf("%s: bridge compatibility front-end for ovs-vswitchd\n"
1009            "usage: %s [OPTIONS] CONFIG\n"
1010            "CONFIG is the configuration file used by ovs-vswitchd.\n",
1011            program_name, program_name);
1012     printf("\nConfiguration options:\n"
1013            "  --appctl-command=COMMAND  shell command to run ovs-appctl\n"
1014            "  --prune-timeout=SECS    wait at most SECS before pruning ports\n"
1015            "  --lock-timeout=MSECS    wait at most MSECS for CONFIG to unlock\n"
1016           );
1017     daemon_usage();
1018     vlog_usage();
1019     printf("\nOther options:\n"
1020            "  -h, --help              display this help message\n"
1021            "  -V, --version           display version information\n");
1022     leak_checker_usage();
1023     printf("\nThe default appctl command is:\n%s\n", appctl_command);
1024     exit(EXIT_SUCCESS);
1025 }