3 # xapi plugin script to update the cache of configuration items in the
4 # ovs-vswitchd configuration that are managed in the xapi database when
5 # integrated with Citrix management tools.
7 # Copyright (C) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
9 # Licensed under the Apache License, Version 2.0 (the "License");
10 # you may not use this file except in compliance with the License.
11 # You may obtain a copy of the License at:
13 # http://www.apache.org/licenses/LICENSE-2.0
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS,
17 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 # See the License for the specific language governing permissions and
19 # limitations under the License.
21 # TBD: - error handling needs to be improved. Currently this can leave
22 # TBD: the system in a bad state if anything goes wrong.
30 vsctl = '/usr/bin/ovs-vsctl'
31 ofctl = '/usr/bin/ovs-ofctl'
32 cacert_filename = '/etc/openvswitch/vswitchd.cacert'
35 # Delete the CA certificate, so that we go back to boot-strapping mode
38 os.remove(cacert_filename)
40 # Ignore error if file doesn't exist
44 def update(session, args):
45 # Refresh bridge network UUIDs in case this host joined or left a pool.
46 script = '/opt/xensource/libexec/interface-reconfigure'
48 retval = subprocess.call([script, 'rewrite'])
50 syslog.syslog('%s exited with status %d' % (script, retval))
52 syslog.syslog('%s: failed to execute (%s)' % (script, e.strerror))
54 pools = session.xenapi.pool.get_all()
55 # We assume there is only ever one pool...
57 raise XenAPIPlugin.Failure('NO_POOL_FOR_HOST', [])
59 raise XenAPIPlugin.Failure('MORE_THAN_ONE_POOL_FOR_HOST', [])
60 new_controller = False
61 pool = session.xenapi.pool.get_record(pools[0])
62 controller = pool.get('vswitch_controller', '')
64 currentController = vswitchCurrentController()
65 if controller == '' and currentController != '':
68 emergency_reset(session, None)
72 ret_str += 'Successfully removed controller config. '
73 elif controller != currentController:
76 emergency_reset(session, None)
79 setControllerCfg(controller)
81 ret_str += 'Successfully set controller to %s. ' % controller
84 pool_fail_mode = pool['other_config']['vswitch-controller-fail-mode']
90 for rec in session.xenapi.network.get_all_records().values():
92 bton[rec['bridge']] = rec
96 # If new controller, get management MAC addresses from XAPI now
97 # in case fail_mode set to secure which may affect XAPI access
100 host_mgmt_device = None
103 query = 'field "management"="true"'
104 recs = session.xenapi.PIF.get_all_records_where(query)
105 for rec in recs.itervalues():
106 pool_mgmt_macs[rec.get('MAC')] = rec.get('device')
109 fail_mode_changed = False
110 for bridge in vswitchCfgQuery(['list-br']).split():
111 network = bton[bridge]
112 bridge = vswitchCfgQuery(['br-to-parent', bridge])
114 xapi_dib = network['other_config'].get('vswitch-disable-in-band')
118 ovs_dib = vswitchCfgQuery(['--', '--if-exists', 'get', 'Bridge',
120 'other_config:disable-in-band']).strip('"')
122 # Do nothing if setting is invalid, and warn the user.
123 if xapi_dib not in ['true', 'false', '']:
124 ret_str += '"' + xapi_dib + '"' + \
125 ' is an invalid value for vswitch-disable-in-band on ' + \
128 # Change bridge disable-in-band option if XAPI and OVS states differ.
129 elif xapi_dib != ovs_dib:
132 vswitchCfgMod(['--', 'set', 'Bridge', bridge,
133 'other_config:disable-in-band=' + xapi_dib])
136 vswitchCfgMod(['--', 'remove', 'Bridge', bridge,
137 'other_config', 'disable-in-band'])
140 # Change bridge fail_mode if XAPI state differs from OVS state.
141 bridge_fail_mode = vswitchCfgQuery(['get', 'Bridge',
142 bridge, 'fail_mode']).strip('[]"')
145 other_config = bton[bridge]['other_config']
146 fail_mode = other_config['vswitch-controller-fail-mode']
150 if fail_mode not in ['secure', 'standalone']:
151 fail_mode = pool_fail_mode
153 if fail_mode != 'secure':
154 fail_mode = 'standalone'
156 if bridge_fail_mode != fail_mode:
157 vswitchCfgMod(['--', 'set', 'Bridge', bridge,
158 'fail_mode=%s' % fail_mode])
159 fail_mode_changed = True
161 # Determine local mgmt MAC address if host being added to secure
162 # pool so we can add default flows to allow management traffic
163 if new_controller and fail_mode_changed and pool_fail_mode == 'secure':
164 oc = vswitchCfgQuery(['get', 'Bridge', bridge, 'other-config'])
165 m = re.match('.*hwaddr="([0-9a-fA-F:].*)".*', oc)
166 if m and m.group(1) in pool_mgmt_macs.keys():
168 host_mgmt_mac = m.group(1)
169 host_mgmt_device = pool_mgmt_macs[host_mgmt_mac]
171 if (host_mgmt_mac is not None and mgmt_bridge is not None and
172 host_mgmt_device is not None):
173 tp = 'idle_timeout=0,priority=0'
174 port = vswitchCfgQuery(['get', 'interface', host_mgmt_device,
177 addFlow(mgmt_bridge, '%s,in_port=%s,arp,nw_proto=1,actions=local' %
179 addFlow(mgmt_bridge, '%s,in_port=local,arp,dl_src=%s,actions=%s' %
180 (tp, host_mgmt_mac, port))
181 addFlow(mgmt_bridge, '%s,in_port=%s,dl_dst=%s,actions=local' %
182 (tp, port, host_mgmt_mac))
183 addFlow(mgmt_bridge, '%s,in_port=local,dl_src=%s,actions=%s' %
184 (tp, host_mgmt_mac, port))
187 ret_str += 'Updated in-band management. '
188 if fail_mode_changed:
189 ret_str += 'Updated fail_mode. '
194 return 'No change to configuration'
197 def vswitchCurrentController():
198 controller = vswitchCfgQuery(['get-manager'])
201 if len(controller) < 4 or controller[0:4] != 'ssl:':
204 return controller.split(':')[1]
207 def removeControllerCfg():
208 vswitchCfgMod(['--', 'del-manager',
212 def setControllerCfg(controller):
213 # /etc/xensource/xapi-ssl.pem is mentioned twice below because it
214 # contains both the private key and the certificate.
215 vswitchCfgMod(['--', 'del-manager',
217 '--', '--bootstrap', 'set-ssl',
218 '/etc/xensource/xapi-ssl.pem',
219 '/etc/xensource/xapi-ssl.pem',
221 '--', 'set-manager', 'ssl:' + controller + ':6632'])
224 def vswitchCfgQuery(action_args):
225 cmd = [vsctl, '-vconsole:off'] + action_args
226 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()
227 if len(output) == 0 or output[0] is None:
230 output = output[0].strip()
234 def vswitchCfgMod(action_args):
235 cmd = [vsctl, '--timeout=5', '-vconsole:off'] + action_args
236 exitcode = subprocess.call(cmd)
238 raise XenAPIPlugin.Failure('VSWITCH_CONFIG_MOD_FAILURE',
239 [str(exitcode), str(action_args)])
242 def emergency_reset(session, args):
243 cmd = [vsctl, '--timeout=5', 'emer-reset']
244 exitcode = subprocess.call(cmd)
246 raise XenAPIPlugin.Failure('VSWITCH_EMER_RESET_FAILURE',
249 return 'Successfully reset configuration'
252 def addFlow(switch, flow):
253 cmd = [ofctl, 'add-flow', switch, flow]
254 exitcode = subprocess.call(cmd)
256 raise XenAPIPlugin.Failure('VSWITCH_ADD_FLOW_FAILURE',
257 [str(exitcode), str(switch), str(flow)])
260 if __name__ == '__main__':
261 XenAPIPlugin.dispatch({'update': update,
262 'emergency_reset': emergency_reset})