vconn: Have check_action() perform all validation
[cascardo/ovs.git] / xenserver / etc_xapi.d_plugins_vswitch-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 file that are managed in the xapi database
5 # when integrated with Citrix management tools.
6
7 # Copyright (C) 2009 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 logging
25 log = logging.getLogger("vswitch-cfg-update")
26 logging.basicConfig(filename="/var/log/vswitch-cfg-update.log", level=logging.DEBUG)
27
28 import XenAPIPlugin
29 import XenAPI
30 import os
31 import subprocess
32
33 cfg_mod="/root/vswitch/bin/ovs-cfg-mod"
34 vswitchd_cfg_filename="/etc/ovs-vswitchd.conf"
35 cacert_filename="/etc/ovs-vswitchd.cacert"
36
37 # Delete the CA certificate, so that we go back to boot-strapping mode
38 def delete_cacert():
39     try:
40         os.remove(cacert_filename)
41     except OSError:
42         # Ignore error if file doesn't exist
43         pass
44
45 def update(session, args):
46     pools = session.xenapi.pool.get_all()
47     # We assume there is only ever one pool...
48     if len(pools) == 0:
49         log.error("No pool for host.")
50         raise XenAPIPlugin.Failure("NO_POOL_FOR_HOST", [])
51     if len(pools) > 1:
52         log.error("More than one pool for host.")
53         raise XenAPIPlugin.Failure("MORE_THAN_ONE_POOL_FOR_HOST", [])
54     pool = session.xenapi.pool.get_record(pools[0])
55     try:
56         controller = pool["other_config"]["vSwitchController"]
57     except KeyError, e:
58         controller = ""
59     currentController = vswitchCurrentController()
60     if controller == "" and currentController != "":
61         log.debug("Removing controller configuration.")
62         delete_cacert()
63         removeControllerCfg()
64         return "Successfully removed controller config"
65     elif controller != currentController:
66         if len(controller) == 0:
67             log.debug("Setting controller to: %s" % (controller))
68         else:
69             log.debug("Changing controller from %s to %s" % (currentController, controller))
70         delete_cacert()
71         setControllerCfg(controller)
72         return "Successfully set controller to " + controller
73     else:
74         log.debug("No change to controller configuration required.")
75     return "No change to configuration"
76         
77 def vswitchCurrentController():
78     controller = vswitchCfgQuery("mgmt.controller")
79     if controller == "":
80         return controller
81     if len(controller) < 4 or controller[0:4] != "ssl:":
82         log.warning("Controller does not specify ssl connection type, returning entire string.")
83         return controller
84     else:
85         return controller[4:]
86
87 def removeControllerCfg():
88     vswitchCfgMod(["--del-match", "mgmt.controller=*",
89                    "--del-match", "ssl.bootstrap-ca-cert=*",
90                    "--del-match", "ssl.ca-cert=*",
91                    "--del-match", "ssl.private-key=*",
92                    "--del-match", "ssl.certificate=*"])
93                                        
94 def setControllerCfg(controller):
95     vswitchCfgMod(["--del-match", "mgmt.controller=*",
96                    "--del-match", "ssl.bootstrap-ca-cert=*",
97                    "--del-match", "ssl.ca-cert=*",
98                    "--del-match", "ssl.private-key=*",
99                    "--del-match", "ssl.certificate=*",
100                    "-a", "mgmt.controller=ssl:" + controller,
101                    "-a", "ssl.bootstrap-ca-cert=true",
102                    "-a", "ssl.ca-cert=/etc/ovs-vswitchd.cacert",
103                    "-a", "ssl.private-key=/etc/xensource/xapi-ssl.pem",
104                    "-a", "ssl.certificate=/etc/xensource/xapi-ssl.pem"])
105
106 def vswitchCfgQuery(key):
107     cmd = [cfg_mod, "--config-file=" + vswitchd_cfg_filename, "-q", key]
108     output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()
109     if len(output) == 0 or output[0] == None:
110         output = ""
111     else:
112         output = output[0].strip()
113     return output
114
115 def vswitchCfgMod(action_args):
116     cmd = [cfg_mod, "-vANY:console:emer",
117            "--config-file=" + vswitchd_cfg_filename] + action_args
118     exitcode = subprocess.call(cmd)
119     if exitcode != 0:
120         log.error("ovs-cfg-mod failed with exit code "
121                   + str(exitcode) + " for " + repr(action_args))
122         raise XenAPIPlugin.Failure("VSWITCH_CONFIG_MOD_FAILURE",
123                                    [ str(exitcode) , str(action_args) ])
124     vswitchReload()
125     
126 def vswitchReload():
127     exitcode = subprocess.call(["/sbin/service", "vswitch", "reload"])
128     if exitcode != 0:
129         log.error("vswitch reload failed with exit code " + str(exitcode))
130         raise XenAPIPlugin.Failure("VSWITCH_CFG_RELOAD_FAILURE", [ str(exitcode) ])
131     
132
133 if __name__ == "__main__":
134     XenAPIPlugin.dispatch({"update": update})