Update primary code license to Apache 2.0.
[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 subprocess
31
32 cfg_mod="/root/vswitch/bin/ovs-cfg-mod"
33 vswitchd_cfg_filename="/etc/ovs-vswitchd.conf"
34
35 def update(session, args):
36     pools = session.xenapi.pool.get_all()
37     # We assume there is only ever one pool...
38     if len(pools) == 0:
39         log.error("No pool for host.")
40         raise XenAPIPlugin.Failure("NO_POOL_FOR_HOST", [])
41     if len(pools) > 1:
42         log.error("More than one pool for host.")
43         raise XenAPIPlugin.Failure("MORE_THAN_ONE_POOL_FOR_HOST", [])
44     pool = session.xenapi.pool.get_record(pools[0])
45     try:
46         controller = pool["other_config"]["vSwitchController"]
47     except KeyError, e:
48         controller = ""
49     currentController = vswitchCurrentController()
50     if controller == "" and currentController != "":
51         log.debug("Removing controller configuration.")
52         removeControllerCfg()
53         return "Successfully removed controller config"
54     elif controller != currentController:
55         if len(controller) == 0:
56             log.debug("Setting controller to: %s" % (controller))
57         else:
58             log.debug("Changing controller from %s to %s" % (currentController, controller))
59         setControllerCfg(controller)
60         return "Successfully set controller to " + controller
61     else:
62         log.debug("No change to controller configuration required.")
63     return "No change to configuration"
64         
65 def vswitchCurrentController():
66     controller = vswitchCfgQuery("mgmt.controller")
67     if controller == "":
68         return controller
69     if len(controller) < 4 or controller[0:4] != "ssl:":
70         log.warning("Controller does not specify ssl connection type, returning entire string.")
71         return controller
72     else:
73         return controller[4:]
74
75 def removeControllerCfg():
76     vswitchCfgMod(["--del-match", "mgmt.controller=*",
77                    "--del-match", "ssl.bootstrap-ca-cert=*",
78                    "--del-match", "ssl.ca-cert=*",
79                    "--del-match", "ssl.private-key=*",
80                    "--del-match", "ssl.certificate=*"])
81                                        
82 def setControllerCfg(controller):
83     vswitchCfgMod(["--del-match", "mgmt.controller=*",
84                    "--del-match", "ssl.bootstrap-ca-cert=*",
85                    "--del-match", "ssl.ca-cert=*",
86                    "--del-match", "ssl.private-key=*",
87                    "--del-match", "ssl.certificate=*",
88                    "-a", "mgmt.controller=ssl:" + controller,
89                    "-a", "ssl.bootstrap-ca-cert=true",
90                    "-a", "ssl.ca-cert=/etc/ovs-vswitchd.cacert",
91                    "-a", "ssl.private-key=/etc/xensource/xapi-ssl.pem",
92                    "-a", "ssl.certificate=/etc/xensource/xapi-ssl.pem"])
93
94 def vswitchCfgQuery(key):
95     cmd = [cfg_mod, "--config-file=" + vswitchd_cfg_filename, "-q", key]
96     output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()
97     if len(output) == 0 or output[0] == None:
98         output = ""
99     else:
100         output = output[0].strip()
101     return output
102
103 def vswitchCfgMod(action_args):
104     cmd = [cfg_mod, "-vANY:console:emer",
105            "--config-file=" + vswitchd_cfg_filename] + action_args
106     exitcode = subprocess.call(cmd)
107     if exitcode != 0:
108         log.error("ovs-cfg-mod failed with exit code "
109                   + str(exitcode) + " for " + repr(action_args))
110         raise XenAPIPlugin.Failure("VSWITCH_CONFIG_MOD_FAILURE",
111                                    [ str(exitcode) , str(action_args) ])
112     vswitchReload()
113     
114 def vswitchReload():
115     exitcode = subprocess.call(["/sbin/service", "vswitch", "reload"])
116     if exitcode != 0:
117         log.error("vswitch reload failed with exit code " + str(exitcode))
118         raise XenAPIPlugin.Failure("VSWITCH_CFG_RELOAD_FAILURE", [ str(exitcode) ])
119     
120
121 if __name__ == "__main__":
122     XenAPIPlugin.dispatch({"update": update})