2 # Copyright (c) 2009, 2010, 2011, 2012 Nicira Networks
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 # A daemon to monitor the external_ids columns of the Bridge and
18 # Interface OVSDB tables for changes that require interrogating XAPI.
19 # Its responsibilities include:
21 # - Set the "bridge-id" key in the Bridge table.
22 # - Set the "iface-id" key in the Interface table.
23 # - Set the fail-mode on internal bridges.
34 from ovs.db import error
35 from ovs.db import types
39 root_prefix = '' # Prefix for absolute file names, for testing.
40 vlog = ovs.vlog.Vlog("ovs-xapi-sync")
45 # Set up a session to interact with XAPI.
47 # On system start-up, OVS comes up before XAPI, so we can't log into the
48 # session until later. Try to do this on-demand, since we won't
49 # actually do anything interesting until XAPI is up.
52 if session is not None:
56 session = XenAPI.xapi_local()
57 session.xenapi.login_with_password("", "")
58 except XenAPI.Failure, e:
60 vlog.warn("Couldn't login to XAPI (%s)" % e)
66 def get_network_by_bridge(br_name):
67 if not init_session():
68 vlog.warn("Failed to get bridge id %s because"
69 " XAPI session could not be initialized" % br_name)
72 for n in session.xenapi.network.get_all():
73 rec = session.xenapi.network.get_record(n)
74 if rec['bridge'] == br_name:
80 # By default, the "bridge-id" external id in the Bridge table is the
81 # same as "xs-network-uuids". This may be overridden by defining a
82 # "nicira-bridge-id" key in the "other_config" field of the network
83 # record of XAPI. If nicira-bridge-id is undefined returns default.
84 # On error returns None.
85 def get_bridge_id(br_name, default=None):
86 rec = get_network_by_bridge(br_name)
88 return rec['other_config'].get('nicira-bridge-id', default)
92 # By default, the "iface-id" external id in the Interface table is the
93 # same as "xs-vif-uuid". This may be overridden by defining a
94 # "nicira-iface-id" key in the "other_config" field of the VIF
96 def get_iface_id(if_name, xs_vif_uuid):
97 if not if_name.startswith("vif") and not if_name.startswith("tap"):
98 # Treat whatever was passed into 'xs_vif_uuid' as a default
102 if not init_session():
103 vlog.warn("Failed to get interface id %s because"
104 " XAPI session could not be initialized" % if_name)
108 vif = session.xenapi.VIF.get_by_uuid(xs_vif_uuid)
109 rec = session.xenapi.VIF.get_record(vif)
110 return rec['other_config'].get('nicira-iface-id', xs_vif_uuid)
111 except XenAPI.Failure:
112 vlog.warn("Could not find XAPI entry for VIF %s" % if_name)
116 def set_or_delete(d, key, value):
122 if d.get(key) != value:
128 def set_external_id(row, key, value):
129 external_ids = row.external_ids
130 if set_or_delete(external_ids, key, value):
131 row.external_ids = external_ids
134 # XenServer does not call interface-reconfigure on internal networks,
135 # which is where the fail-mode would normally be set.
136 def update_fail_mode(row):
137 rec = get_network_by_bridge(row.name)
141 fail_mode = rec['other_config'].get('vswitch-controller-fail-mode')
144 pools = session.xenapi.pool.get_all()
146 prec = session.xenapi.pool.get_record(pools[0])
147 fail_mode = prec['other_config'].get(
148 'vswitch-controller-fail-mode')
150 if fail_mode not in ['standalone', 'secure']:
151 fail_mode = 'standalone'
153 if row.fail_mode != fail_mode:
154 row.fail_mode = fail_mode
157 def update_in_band_mgmt(row):
158 rec = get_network_by_bridge(row.name)
162 dib = rec['other_config'].get('vswitch-disable-in-band')
164 other_config = row.other_config
165 if dib and dib not in ['true', 'false']:
166 vlog.warn('"%s" isn\'t a valid setting for '
167 "other_config:disable-in-band on %s" % (dib, row.name))
168 elif set_or_delete(other_config, 'disable-in-band', dib):
169 row.other_config = other_config
172 def update_bridge_id(row):
173 id_ = get_bridge_id(row.name, row.external_ids.get("xs-network-uuids"))
177 set_external_id(row, "bridge-id", id_.split(";")[0])
180 def keep_table_columns(schema, table_name, columns):
181 table = schema.tables.get(table_name)
183 raise error.Error("schema has no %s table" % table_name)
186 for column_name in columns:
187 column = table.columns.get(column_name)
189 raise error.Error("%s table schema lacks %s column"
190 % (table_name, column_name))
191 new_columns[column_name] = column
192 table.columns = new_columns
196 def prune_schema(schema):
198 new_tables["Bridge"] = keep_table_columns(
199 schema, "Bridge", ("name", "external_ids", "other_config",
201 new_tables["Interface"] = keep_table_columns(
202 schema, "Interface", ("name", "external_ids"))
203 schema.tables = new_tables
206 def handler(signum, _):
208 if (signum == signal.SIGHUP):
215 parser = argparse.ArgumentParser()
216 parser.add_argument("database", metavar="DATABASE",
217 help="A socket on which ovsdb-server is listening.")
218 parser.add_argument("--root-prefix", metavar="DIR",
219 help="Use DIR as alternate root directory"
222 ovs.vlog.add_args(parser)
223 ovs.daemon.add_args(parser)
224 args = parser.parse_args()
225 ovs.vlog.handle_args(args)
226 ovs.daemon.handle_args(args)
230 root_prefix = args.root_prefix
232 remote = args.database
233 schema_file = "%s/vswitch.ovsschema" % ovs.dirs.PKGDATADIR
234 schema = ovs.db.schema.DbSchema.from_json(ovs.json.from_file(schema_file))
236 idl = ovs.db.idl.Idl(remote, schema)
238 ovs.daemon.daemonize()
240 # This daemon is usually started before XAPI, but to complete our
241 # tasks, we need it. Wait here until it's up.
242 cookie_file = root_prefix + "/var/run/xapi_init_complete.cookie"
243 while not os.path.exists(cookie_file):
246 signal.signal(signal.SIGHUP, handler)
248 bridges = {} # Map from bridge name to xs_network_uuids
249 iface_ids = {} # Map from xs-vif-uuid to iface-id
251 if not force_run and not idl.run():
252 poller = ovs.poller.Poller()
258 vlog.info("Forced to re-run as the result of a SIGHUP")
263 txn = ovs.db.idl.Transaction(idl)
266 for row in idl.tables["Bridge"].rows.itervalues():
267 old_xnu = bridges.get(row.name)
268 new_xnu = row.external_ids.get("xs-network-uuids", "")
271 update_fail_mode(row)
272 update_in_band_mgmt(row)
273 if new_xnu != old_xnu:
274 # New bridge or bridge's xs-network-uuids has changed.
275 update_bridge_id(row)
276 new_bridges[row.name] = new_xnu
277 bridges = new_bridges
280 for row in idl.tables["Interface"].rows.itervalues():
281 iface_by_name[row.name] = row
284 for row in idl.tables["Interface"].rows.itervalues():
285 # Match up paired vif and tap devices.
286 if row.name.startswith("vif"):
288 tap = iface_by_name.get("tap%s" % row.name[3:])
289 elif row.name.startswith("tap"):
291 vif = iface_by_name.get("vif%s" % row.name[3:])
295 # Several tap external-ids need to be copied from the vif.
296 if row == tap and vif:
297 keys = ["attached-mac",
302 set_external_id(row, k, vif.external_ids.get(k))
304 # Map from xs-vif-uuid to iface-id.
306 # (A tap's xs-vif-uuid comes from its vif. That falls out
307 # naturally from the copy loop above.)
308 xvu = row.external_ids.get("xs-vif-uuid")
310 iface_id = (new_iface_ids.get(xvu)
311 or iface_ids.get(xvu)
312 or get_iface_id(row.name, xvu))
313 new_iface_ids[xvu] = iface_id
315 # No xs-vif-uuid therefore no iface-id.
317 set_external_id(row, "iface-id", iface_id)
319 # When there's a vif and a tap, the tap is active (used for
320 # traffic). When there's just a vif, the vif is active.
322 # A tap on its own shouldn't happen, and we don't know
323 # anything about other kinds of devices, so we don't use
324 # an iface-status for those devices at all.
326 set_external_id(tap, "iface-status", "active")
327 set_external_id(vif, "iface-status", "inactive")
329 set_external_id(vif, "iface-status", "active")
331 set_external_id(row, "iface-status", None)
332 iface_ids = new_iface_ids
337 if __name__ == '__main__':
341 # Let system.exit() calls complete normally
344 vlog.exception("traceback")
345 sys.exit(ovs.daemon.RESTART_EXIT_CODE)