Prepare Open vSwitch 1.1.2 release.
[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     controller = pool.get("vswitch_controller", "")
59     ret_str = ""
60     currentController = vswitchCurrentController()
61     if controller == "" and currentController != "":
62         delete_cacert()
63         try:
64             emergency_reset(session, None)
65         except:
66             pass
67         removeControllerCfg()
68         ret_str += "Successfully removed controller config.  "
69     elif controller != currentController:
70         delete_cacert()
71         try:
72             emergency_reset(session, None)
73         except:
74             pass
75         setControllerCfg(controller)
76         ret_str += "Successfully set controller to %s.  " % controller
77
78     try:
79         pool_fail_mode = pool["other_config"]["vswitch-controller-fail-mode"]
80     except KeyError, e:
81         pool_fail_mode = None
82
83     bton = {}
84
85     for n in session.xenapi.network.get_all():
86         rec = session.xenapi.network.get_record(n)
87         try:
88             bton[rec['bridge']] = rec
89         except KeyError:
90             pass
91
92     dib_changed = False
93     fail_mode_changed = False
94     for bridge in vswitchCfgQuery(['list-br']).split():
95         network = bton[bridge]
96         bridge = vswitchCfgQuery(['br-to-parent', bridge])
97
98         xapi_dib = network['other_config'].get('vswitch-disable-in-band')
99         if not xapi_dib:
100             xapi_dib = ''
101
102         ovs_dib = vswitchCfgQuery(['--', '--if-exists', 'get', 'Bridge',
103                                    bridge,
104                                    'other_config:disable-in-band']).strip('"')
105
106         # Do nothing if setting is invalid, and warn the user.
107         if xapi_dib not in ['true', 'false', '']:
108             ret_str += '"' + xapi_dib + '"' + \
109                 ' is an invalid value for vswitch-disable-in-band on ' + \
110                 bridge + '  '
111
112         # Change bridge disable-in-band option if XAPI and OVS states differ.
113         elif xapi_dib != ovs_dib:
114             # 'true' or 'false'
115             if xapi_dib:
116                 vswitchCfgMod(['--', 'set', 'Bridge', bridge,
117                                'other_config:disable-in-band=' + xapi_dib])
118             # '' or None
119             else:
120                 vswitchCfgMod(['--', 'remove', 'Bridge', bridge,
121                                'other_config', 'disable-in-band'])
122             dib_changed = True
123
124         # Change bridge fail_mode if XAPI state differs from OVS state.
125         bridge_fail_mode = vswitchCfgQuery(["get", "Bridge",
126             bridge, "fail_mode"]).strip('[]"')
127
128         try:
129             fail_mode = bton[bridge]["other_config"]["vswitch-controller-fail-mode"]
130         except KeyError, e:
131             fail_mode = None
132
133         if fail_mode not in ['secure', 'standalone']:
134             fail_mode = pool_fail_mode
135
136         if fail_mode != 'secure':
137             fail_mode = 'standalone'
138
139         if bridge_fail_mode != fail_mode:
140             vswitchCfgMod(['--', 'set', 'Bridge', bridge,
141                 "fail_mode=%s" % fail_mode])
142             fail_mode_changed = True
143
144     if dib_changed:
145         ret_str += "Updated in-band management.  "
146     if fail_mode_changed:
147         ret_str += "Updated fail_mode.  "
148
149     if ret_str != '':
150         return ret_str
151     else:
152         return "No change to configuration"
153
154 def vswitchCurrentController():
155     controller = vswitchCfgQuery(["get-manager"])
156     if controller == "":
157         return controller
158     if len(controller) < 4 or controller[0:4] != "ssl:":
159         return controller
160     else:
161         return controller.split(':')[1]
162
163 def removeControllerCfg():
164     vswitchCfgMod(["--", "del-manager",
165                    "--", "del-ssl"])
166
167 def setControllerCfg(controller):
168     # /etc/xensource/xapi-ssl.pem is mentioned twice below because it
169     # contains both the private key and the certificate.
170     vswitchCfgMod(["--", "del-manager",
171                    "--", "del-ssl",
172                    "--", "--bootstrap", "set-ssl",
173                    "/etc/xensource/xapi-ssl.pem",
174                    "/etc/xensource/xapi-ssl.pem",
175                    cacert_filename,
176                    "--", "set-manager", 'ssl:' + controller + ':6632'])
177
178 def vswitchCfgQuery(action_args):
179     cmd = [vsctl, "--timeout=5", "-vANY:console:emer"] + action_args
180     output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()
181     if len(output) == 0 or output[0] == None:
182         output = ""
183     else:
184         output = output[0].strip()
185     return output
186
187 def vswitchCfgMod(action_args):
188     cmd = [vsctl, "--timeout=5", "-vANY:console:emer"] + action_args
189     exitcode = subprocess.call(cmd)
190     if exitcode != 0:
191         raise XenAPIPlugin.Failure("VSWITCH_CONFIG_MOD_FAILURE",
192                                    [ str(exitcode) , str(action_args) ])
193
194 def emergency_reset(session, args):
195     cmd = [vsctl, "--timeout=5", "emer-reset"]
196     exitcode = subprocess.call(cmd)
197     if exitcode != 0:
198         raise XenAPIPlugin.Failure("VSWITCH_EMER_RESET_FAILURE",
199                                    [ str(exitcode) ])
200
201     return "Successfully reset configuration"
202     
203 if __name__ == "__main__":
204     XenAPIPlugin.dispatch({"update": update,
205                            "emergency_reset": emergency_reset})