xenserver: allow dom0 traffic in secure pool host when controller unavailable.
[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 managagment 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(['get', 'Bridge', bridge,
119                                    'other_config:disable-in-band']).strip('"')
120
121         # Do nothing if setting is invalid, and warn the user.
122         if xapi_dib not in ['true', 'false', '']:
123             ret_str += '"' + xapi_dib + '"' + \
124                 ' is an invalid value for vswitch-disable-in-band on ' + \
125                 bridge + '  '
126
127         # Change bridge disable-in-band option if XAPI and OVS states differ.
128         elif xapi_dib != ovs_dib:
129             # 'true' or 'false'
130             if xapi_dib:
131                 vswitchCfgMod(['--', 'set', 'Bridge', bridge,
132                                'other_config:disable-in-band=' + xapi_dib])
133             # '' or None
134             else:
135                 vswitchCfgMod(['--', 'remove', 'Bridge', bridge,
136                                'other_config', 'disable-in-band'])
137             dib_changed = True
138
139         # Change bridge fail_mode if XAPI state differs from OVS state.
140         bridge_fail_mode = vswitchCfgQuery(["get", "Bridge",
141             bridge, "fail_mode"]).strip('[]"')
142
143         try:
144             fail_mode = bton[bridge]["other_config"]["vswitch-controller-fail-mode"]
145         except KeyError, e:
146             fail_mode = None
147
148         if fail_mode not in ['secure', 'standalone']:
149             fail_mode = pool_fail_mode
150
151         if fail_mode != 'secure':
152             fail_mode = 'standalone'
153
154         if bridge_fail_mode != fail_mode:
155             vswitchCfgMod(['--', 'set', 'Bridge', bridge,
156                 "fail_mode=%s" % fail_mode])
157             fail_mode_changed = True
158
159         # Determine local mgmt MAC address if host being added to secure
160         # pool so we can add default flows to allow management traffic
161         if new_controller and fail_mode_changed and pool_fail_mode == "secure":
162             oc = vswitchCfgQuery(["get", "Bridge", bridge, "other-config"])
163             m = re.match('.*hwaddr="([0-9a-fA-F:].*)".*', oc)
164             if m and m.group(1) in pool_mgmt_macs.keys():
165                 mgmt_bridge = bridge
166                 host_mgmt_mac = m.group(1)
167                 host_mgmt_device = pool_mgmt_macs[host_mgmt_mac]
168
169     if host_mgmt_mac is not None and mgmt_bridge is not None and \
170         host_mgmt_device is not None:
171         tp = "idle_timeout=0,priority=0"
172         port = vswitchCfgQuery(["get", "interface", host_mgmt_device, "ofport"])
173         addFlow(mgmt_bridge, "%s,in_port=%s,arp,nw_proto=1,actions=local" % \
174             (tp, port))
175         addFlow(mgmt_bridge, "%s,in_port=local,arp,dl_src=%s,actions=%s" % \
176             (tp, host_mgmt_mac, port))
177         addFlow(mgmt_bridge, "%s,in_port=%s,dl_dst=%s,actions=local" % \
178             (tp, port, host_mgmt_mac))
179         addFlow(mgmt_bridge, "%s,in_port=local,dl_src=%s,actions=%s" % \
180             (tp, host_mgmt_mac, port))
181
182     if dib_changed:
183         ret_str += "Updated in-band management.  "
184     if fail_mode_changed:
185         ret_str += "Updated fail_mode.  "
186
187     if ret_str != '':
188         return ret_str
189     else:
190         return "No change to configuration"
191
192 def vswitchCurrentController():
193     controller = vswitchCfgQuery(["get-manager"])
194     if controller == "":
195         return controller
196     if len(controller) < 4 or controller[0:4] != "ssl:":
197         return controller
198     else:
199         return controller.split(':')[1]
200
201 def removeControllerCfg():
202     vswitchCfgMod(["--", "del-manager",
203                    "--", "del-ssl"])
204
205 def setControllerCfg(controller):
206     # /etc/xensource/xapi-ssl.pem is mentioned twice below because it
207     # contains both the private key and the certificate.
208     vswitchCfgMod(["--", "del-manager",
209                    "--", "del-ssl",
210                    "--", "--bootstrap", "set-ssl",
211                    "/etc/xensource/xapi-ssl.pem",
212                    "/etc/xensource/xapi-ssl.pem",
213                    cacert_filename,
214                    "--", "set-manager", 'ssl:' + controller + ':6632'])
215
216 def vswitchCfgQuery(action_args):
217     cmd = [vsctl, "--timeout=5", "-vANY:console:emer"] + action_args
218     output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()
219     if len(output) == 0 or output[0] == None:
220         output = ""
221     else:
222         output = output[0].strip()
223     return output
224
225 def vswitchCfgMod(action_args):
226     cmd = [vsctl, "--timeout=5", "-vANY:console:emer"] + action_args
227     exitcode = subprocess.call(cmd)
228     if exitcode != 0:
229         raise XenAPIPlugin.Failure("VSWITCH_CONFIG_MOD_FAILURE",
230                                    [ str(exitcode) , str(action_args) ])
231
232 def emergency_reset(session, args):
233     cmd = [vsctl, "--timeout=5", "emer-reset"]
234     exitcode = subprocess.call(cmd)
235     if exitcode != 0:
236         raise XenAPIPlugin.Failure("VSWITCH_EMER_RESET_FAILURE",
237                                    [ str(exitcode) ])
238
239     return "Successfully reset configuration"
240
241 def addFlow(switch, flow):
242     cmd = [ofctl, "add-flow", switch, flow]
243     exitcode = subprocess.call(cmd)
244     if exitcode != 0:
245         raise XenAPIPlugin.Failure("VSWITCH_ADD_FLOW_FAILURE",
246                                    [ str(exitcode) , str(switch), str(flow) ])
247     
248 if __name__ == "__main__":
249     XenAPIPlugin.dispatch({"update": update,
250                            "emergency_reset": emergency_reset})