xenserver: Allow fail_mode to be set from xapi.
[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
30 vsctl="/usr/bin/ovs-vsctl"
31 cacert_filename="/etc/openvswitch/vswitchd.cacert"
32
33 # Delete the CA certificate, so that we go back to boot-strapping mode
34 def delete_cacert():
35     try:
36         os.remove(cacert_filename)
37     except OSError:
38         # Ignore error if file doesn't exist
39         pass
40
41 def update(session, args):
42     # Refresh bridge network UUIDs in case this host joined or left a pool.
43     script = "/opt/xensource/libexec/interface-reconfigure"
44     try:
45         retval = subprocess.call([script, "rewrite"])
46         if retval != 0:
47             syslog.syslog("%s exited with status %d" % (script, retval))
48     except OSError, e:
49         syslog.syslog("%s: failed to execute (%s)" % (script, e.strerror))
50
51     pools = session.xenapi.pool.get_all()
52     # We assume there is only ever one pool...
53     if len(pools) == 0:
54         raise XenAPIPlugin.Failure("NO_POOL_FOR_HOST", [])
55     if len(pools) > 1:
56         raise XenAPIPlugin.Failure("MORE_THAN_ONE_POOL_FOR_HOST", [])
57     pool = session.xenapi.pool.get_record(pools[0])
58     try:
59         try:
60             controller = pool["vswitch_controller"]
61         except KeyError:
62             # On systems older than XenServer 5.6.0, we needed to store
63             # the key in "other_config".
64             controller = pool["other_config"]["vSwitchController"]
65     except KeyError, e:
66         controller = ""
67     ret_str = ""
68     currentController = vswitchCurrentController()
69     if controller == "" and currentController != "":
70         delete_cacert()
71         try:
72             emergency_reset(session, None)
73         except:
74             pass
75         removeControllerCfg()
76         ret_str += "Successfully removed controller config.  "
77     elif controller != currentController:
78         delete_cacert()
79         try:
80             emergency_reset(session, None)
81         except:
82             pass
83         setControllerCfg(controller)
84         ret_str += "Successfully set controller to %s.  " % controller
85
86     try:
87         fail_mode = pool["other_config"]["vswitch-controller-fail-mode"]
88     except KeyError, e:
89         fail_mode = None
90
91     if fail_mode != 'secure':
92         fail_mode = 'standalone'
93
94     fail_mode_changed = False
95     for (p, rec) in session.xenapi.PIF.get_all_records().items():
96         try:
97             network = session.xenapi.network.get_record(rec['network'])
98             bridge = network['bridge']
99         except Exception, e:
100             syslog.syslog("%s: failed to get bridge name (%s)" %
101                     (script, str(e)))
102             continue
103
104         bridge_fail_mode = vswitchCfgQuery(["get", "Bridge",
105             bridge, "fail_mode"]).strip('[]"')
106
107         if bridge_fail_mode != fail_mode:
108             vswitchCfgMod(['--', 'set', 'Bridge', bridge,
109                 "fail_mode=%s" % fail_mode])
110             fail_mode_changed = True
111
112     if fail_mode_changed:
113         ret_str += "Set fail_mode to %s.  " % fail_mode
114
115     if ret_str != '':
116         return ret_str
117     else:
118         return "No change to configuration"
119
120 def vswitchCurrentController():
121     controller = vswitchCfgQuery(["get", "Open_vSwitch", 
122                                   ".", "managers"]).strip('[]"')
123     if controller == "":
124         return controller
125     if len(controller) < 4 or controller[0:4] != "ssl:":
126         return controller
127     else:
128         return controller.split(':')[1]
129
130 def removeControllerCfg():
131     vswitchCfgMod(["--", "clear", "Open_vSwitch", ".", "managers",
132                    "--", "del-ssl"])
133
134 def setControllerCfg(controller):
135     # /etc/xensource/xapi-ssl.pem is mentioned twice below because it
136     # contains both the private key and the certificate.
137     vswitchCfgMod(["--", "clear", "Open_vSwitch", ".", "managers",
138                    "--", "del-ssl",
139                    "--", "--bootstrap", "set-ssl",
140                    "/etc/xensource/xapi-ssl.pem",
141                    "/etc/xensource/xapi-ssl.pem",
142                    cacert_filename,
143                    "--", "set", "Open_vSwitch", ".",
144                    'managers="ssl:' + controller + ':6632"'])
145
146 def vswitchCfgQuery(action_args):
147     cmd = [vsctl, "--timeout=5", "-vANY:console:emer"] + action_args
148     output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()
149     if len(output) == 0 or output[0] == None:
150         output = ""
151     else:
152         output = output[0].strip()
153     return output
154
155 def vswitchCfgMod(action_args):
156     cmd = [vsctl, "--timeout=5", "-vANY:console:emer"] + action_args
157     exitcode = subprocess.call(cmd)
158     if exitcode != 0:
159         raise XenAPIPlugin.Failure("VSWITCH_CONFIG_MOD_FAILURE",
160                                    [ str(exitcode) , str(action_args) ])
161
162 def emergency_reset(session, args):
163     cmd = [vsctl, "--timeout=5", "emer-reset"]
164     exitcode = subprocess.call(cmd)
165     if exitcode != 0:
166         raise XenAPIPlugin.Failure("VSWITCH_EMER_RESET_FAILURE",
167                                    [ str(exitcode) ])
168
169     return "Successfully reset configuration"
170     
171 if __name__ == "__main__":
172     XenAPIPlugin.dispatch({"update": update,
173                            "emergency_reset": emergency_reset})