xenserver: ovs-xapi-sync should create a log file.
[sliver-openvswitch.git] / xenserver / etc_xapi.d_plugins_openvswitch-cfg-update
1 #!/usr/bin/env python
2 #
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.
6
7 # Copyright (C) 2009, 2010, 2011 Nicira Networks, Inc.
8 #
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:
12 #
13 #     http://www.apache.org/licenses/LICENSE-2.0
14 #
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.
20
21 # TBD: - error handling needs to be improved.  Currently this can leave
22 # TBD:   the system in a bad state if anything goes wrong.
23
24 import XenAPIPlugin
25 import XenAPI
26 import os
27 import subprocess
28 import syslog
29 import re
30
31 vsctl="/usr/bin/ovs-vsctl"
32 ofctl="/usr/bin/ovs-ofctl"
33 cacert_filename="/etc/openvswitch/vswitchd.cacert"
34
35 # Delete the CA certificate, so that we go back to boot-strapping mode
36 def delete_cacert():
37     try:
38         os.remove(cacert_filename)
39     except OSError:
40         # Ignore error if file doesn't exist
41         pass
42
43 def update(session, args):
44     # Refresh bridge network UUIDs in case this host joined or left a pool.
45     script = "/opt/xensource/libexec/interface-reconfigure"
46     try:
47         retval = subprocess.call([script, "rewrite"])
48         if retval != 0:
49             syslog.syslog("%s exited with status %d" % (script, retval))
50     except OSError, e:
51         syslog.syslog("%s: failed to execute (%s)" % (script, e.strerror))
52
53     pools = session.xenapi.pool.get_all()
54     # We assume there is only ever one pool...
55     if len(pools) == 0:
56         raise XenAPIPlugin.Failure("NO_POOL_FOR_HOST", [])
57     if len(pools) > 1:
58         raise XenAPIPlugin.Failure("MORE_THAN_ONE_POOL_FOR_HOST", [])
59     new_controller = False
60     pool = session.xenapi.pool.get_record(pools[0])
61     controller = pool.get("vswitch_controller", "")
62     ret_str = ""
63     currentController = vswitchCurrentController()
64     if controller == "" and currentController != "":
65         delete_cacert()
66         try:
67             emergency_reset(session, None)
68         except:
69             pass
70         removeControllerCfg()
71         ret_str += "Successfully removed controller config.  "
72     elif controller != currentController:
73         delete_cacert()
74         try:
75             emergency_reset(session, None)
76         except:
77             pass
78         setControllerCfg(controller)
79         new_controller = True
80         ret_str += "Successfully set controller to %s.  " % controller
81
82     try:
83         pool_fail_mode = pool["other_config"]["vswitch-controller-fail-mode"]
84     except KeyError, e:
85         pool_fail_mode = None
86
87     bton = {}
88
89     for n in session.xenapi.network.get_all():
90         rec = session.xenapi.network.get_record(n)
91         try:
92             bton[rec['bridge']] = rec
93         except KeyError:
94             pass
95
96     # If new controller, get management MAC addresses from XAPI now
97     # in case fail_mode set to secure which may affect XAPI access
98     mgmt_bridge = None
99     host_mgmt_mac = None
100     host_mgmt_device = None
101     pool_mgmt_macs = {}
102     if new_controller:
103         for n in session.xenapi.PIF.get_all():
104             rec = session.xenapi.PIF.get_record(n)
105             if rec.get('management', False):
106                 pool_mgmt_macs[rec.get('MAC')] = rec.get('device')
107
108     dib_changed = False
109     fail_mode_changed = False
110     for bridge in vswitchCfgQuery(['list-br']).split():
111         network = bton[bridge]
112         bridge = vswitchCfgQuery(['br-to-parent', bridge])
113
114         xapi_dib = network['other_config'].get('vswitch-disable-in-band')
115         if not xapi_dib:
116             xapi_dib = ''
117
118         ovs_dib = vswitchCfgQuery(['--', '--if-exists', 'get', 'Bridge',
119                                    bridge,
120                                    'other_config:disable-in-band']).strip('"')
121
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 ' + \
126                 bridge + '  '
127
128         # Change bridge disable-in-band option if XAPI and OVS states differ.
129         elif xapi_dib != ovs_dib:
130             # 'true' or 'false'
131             if xapi_dib:
132                 vswitchCfgMod(['--', 'set', 'Bridge', bridge,
133                                'other_config:disable-in-band=' + xapi_dib])
134             # '' or None
135             else:
136                 vswitchCfgMod(['--', 'remove', 'Bridge', bridge,
137                                'other_config', 'disable-in-band'])
138             dib_changed = True
139
140         # Change bridge fail_mode if XAPI state differs from OVS state.
141         bridge_fail_mode = vswitchCfgQuery(["get", "Bridge",
142             bridge, "fail_mode"]).strip('[]"')
143
144         try:
145             fail_mode = bton[bridge]["other_config"]["vswitch-controller-fail-mode"]
146         except KeyError, e:
147             fail_mode = None
148
149         if fail_mode not in ['secure', 'standalone']:
150             fail_mode = pool_fail_mode
151
152         if fail_mode != 'secure':
153             fail_mode = 'standalone'
154
155         if bridge_fail_mode != fail_mode:
156             vswitchCfgMod(['--', 'set', 'Bridge', bridge,
157                 "fail_mode=%s" % fail_mode])
158             fail_mode_changed = True
159
160         # Determine local mgmt MAC address if host being added to secure
161         # pool so we can add default flows to allow management traffic
162         if new_controller and fail_mode_changed and pool_fail_mode == "secure":
163             oc = vswitchCfgQuery(["get", "Bridge", bridge, "other-config"])
164             m = re.match('.*hwaddr="([0-9a-fA-F:].*)".*', oc)
165             if m and m.group(1) in pool_mgmt_macs.keys():
166                 mgmt_bridge = bridge
167                 host_mgmt_mac = m.group(1)
168                 host_mgmt_device = pool_mgmt_macs[host_mgmt_mac]
169
170     if host_mgmt_mac is not None and mgmt_bridge is not None and \
171         host_mgmt_device is not None:
172         tp = "idle_timeout=0,priority=0"
173         port = vswitchCfgQuery(["get", "interface", host_mgmt_device, "ofport"])
174         addFlow(mgmt_bridge, "%s,in_port=%s,arp,nw_proto=1,actions=local" % \
175             (tp, port))
176         addFlow(mgmt_bridge, "%s,in_port=local,arp,dl_src=%s,actions=%s" % \
177             (tp, host_mgmt_mac, port))
178         addFlow(mgmt_bridge, "%s,in_port=%s,dl_dst=%s,actions=local" % \
179             (tp, port, host_mgmt_mac))
180         addFlow(mgmt_bridge, "%s,in_port=local,dl_src=%s,actions=%s" % \
181             (tp, host_mgmt_mac, port))
182
183     if dib_changed:
184         ret_str += "Updated in-band management.  "
185     if fail_mode_changed:
186         ret_str += "Updated fail_mode.  "
187
188     if ret_str != '':
189         return ret_str
190     else:
191         return "No change to configuration"
192
193 def vswitchCurrentController():
194     controller = vswitchCfgQuery(["get-manager"])
195     if controller == "":
196         return controller
197     if len(controller) < 4 or controller[0:4] != "ssl:":
198         return controller
199     else:
200         return controller.split(':')[1]
201
202 def removeControllerCfg():
203     vswitchCfgMod(["--", "del-manager",
204                    "--", "del-ssl"])
205
206 def setControllerCfg(controller):
207     # /etc/xensource/xapi-ssl.pem is mentioned twice below because it
208     # contains both the private key and the certificate.
209     vswitchCfgMod(["--", "del-manager",
210                    "--", "del-ssl",
211                    "--", "--bootstrap", "set-ssl",
212                    "/etc/xensource/xapi-ssl.pem",
213                    "/etc/xensource/xapi-ssl.pem",
214                    cacert_filename,
215                    "--", "set-manager", 'ssl:' + controller + ':6632'])
216
217 def vswitchCfgQuery(action_args):
218     cmd = [vsctl, "--timeout=5", "-vANY:console:off"] + action_args
219     output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()
220     if len(output) == 0 or output[0] == None:
221         output = ""
222     else:
223         output = output[0].strip()
224     return output
225
226 def vswitchCfgMod(action_args):
227     cmd = [vsctl, "--timeout=5", "-vANY:console:off"] + action_args
228     exitcode = subprocess.call(cmd)
229     if exitcode != 0:
230         raise XenAPIPlugin.Failure("VSWITCH_CONFIG_MOD_FAILURE",
231                                    [ str(exitcode) , str(action_args) ])
232
233 def emergency_reset(session, args):
234     cmd = [vsctl, "--timeout=5", "emer-reset"]
235     exitcode = subprocess.call(cmd)
236     if exitcode != 0:
237         raise XenAPIPlugin.Failure("VSWITCH_EMER_RESET_FAILURE",
238                                    [ str(exitcode) ])
239
240     return "Successfully reset configuration"
241
242 def addFlow(switch, flow):
243     cmd = [ofctl, "add-flow", switch, flow]
244     exitcode = subprocess.call(cmd)
245     if exitcode != 0:
246         raise XenAPIPlugin.Failure("VSWITCH_ADD_FLOW_FAILURE",
247                                    [ str(exitcode) , str(switch), str(flow) ])
248     
249 if __name__ == "__main__":
250     XenAPIPlugin.dispatch({"update": update,
251                            "emergency_reset": emergency_reset})