1 # Copyright (c) Citrix Systems 2008. All rights reserved.
2 # xsconsole is proprietary software.
4 # Xen, the Xen logo, XenCenter, XenMotion are trademarks or registered
5 # trademarks of Citrix Systems, Inc., in the United States and other
8 # Copyright (c) 2009 Nicira Networks.
11 log = logging.getLogger("vswitch-cfg-update")
12 logging.basicConfig(filename="/var/log/vswitch-xsplugin.log", level=logging.DEBUG)
18 cfg_mod="/root/vswitch/bin/ovs-cfg-mod"
19 vswitchd_cfg_filename="/etc/ovs-vswitchd.conf"
21 if __name__ == "__main__":
22 raise Exception("This script is a plugin for xsconsole and cannot run independently")
24 from XSConsoleStandard import *
29 def __init__(self, name, processname=None):
31 self.processname = processname
32 if self.processname == None:
33 self.processname = name
37 output = ShellPipe(["service", self.name, "status"]).Stdout()
38 except StandardError, e:
39 log.error("status retrieval error: " + str(e))
44 if self.processname not in l:
56 ShellPipe(["service", self.name, "restart"]).Call()
57 except StandardError, e:
58 log.error("restart error: " + str(e))
61 def Inst(cls, name, processname=None):
63 if processname != None:
64 key = key + "-" + processname
65 if name not in cls.service:
66 cls.service[key] = VSwitchService(name, processname)
67 return cls.service[key]
74 output = ShellPipe([cfg_mod, "-vANY:console:emer", "-F",
75 vswitchd_cfg_filename, "-q", key]).Stdout()
76 except StandardError, e:
77 log.error("config retrieval error: " + str(e))
83 output = output[0].strip()
87 class VSwitchControllerDialogue(Dialogue):
89 Dialogue.__init__(self)
94 pool = data.GetPoolForThisHost()
96 self.controller = pool.get("other_config", {}).get("vSwitchController", "")
101 ChoiceDef(Lang("Set pool-wide controller"),
102 lambda: self.getController()),
103 ChoiceDef(Lang("Delete pool-wide controller"),
104 lambda: self.deleteController()),
105 ChoiceDef(Lang("Resync server controller config"),
106 lambda: self.syncController()),
107 # ChoiceDef(Lang("Restart ovs-vswitchd"),
108 # lambda: self.restartService("vswitch")),
109 # ChoiceDef(Lang("Restart ovs-brcompatd"),
110 # lambda: self.restartService("vswitch-brcompatd"))
112 self.menu = Menu(self, None, Lang("Configure vSwitch"), choiceDefs)
114 self.ChangeState("INITIAL")
117 pane = self.NewPane(DialoguePane(self.parent))
118 pane.TitleSet(Lang("Configure vSwitch"))
121 def ChangeState(self, inState):
126 def UpdateFields(self):
127 self.Pane().ResetPosition()
128 getattr(self, "UpdateFields" + self.state)() # Dispatch method named 'UpdateFields'+self.state
130 def UpdateFieldsINITIAL(self):
132 pane.AddTitleField(Lang("Select an action"))
133 pane.AddMenuField(self.menu)
134 pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Cancel") } )
136 def UpdateFieldsGETCONTROLLER(self):
140 pane.AddTitleField(Lang("Enter IP address of controller"))
141 pane.AddInputField(Lang("Address", 16), self.controller, "address")
142 pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Exit") } )
143 if pane.CurrentInput() is None:
144 pane.InputIndexSet(0)
146 def HandleKey(self, inKey):
148 if hasattr(self, "HandleKey" + self.state):
149 handled = getattr(self, "HandleKey" + self.state)(inKey)
150 if not handled and inKey == 'KEY_ESCAPE':
151 Layout.Inst().PopDialogue()
155 def HandleKeyINITIAL(self, inKey):
156 return self.menu.HandleKey(inKey)
158 def HandleKeyGETCONTROLLER(self, inKey):
160 if pane.CurrentInput() is None:
161 pane.InputIndexSet(0)
162 if inKey == 'KEY_ENTER':
163 inputValues = pane.GetFieldValues()
164 self.controller = inputValues['address']
165 Layout.Inst().PopDialogue()
167 # Make sure the controller is specified as a valid dotted quad
169 socket.inet_aton(self.controller)
171 Layout.Inst().PushDialogue(InfoDialogue(Lang("Please enter in dotted quad format")))
174 Layout.Inst().TransientBanner(Lang("Setting controller..."))
176 self.SetController(self.controller)
177 Layout.Inst().PushDialogue(InfoDialogue(Lang("Setting controller successful")))
179 Layout.Inst().PushDialogue(InfoDialogue(Lang("Setting controller failed")))
181 self.ChangeState("INITIAL")
184 return pane.CurrentInput().HandleKey(inKey)
186 def restartService(self, name):
187 s = VSwitchService.Inst(name)
189 Layout.Inst().PopDialogue()
191 def getController(self):
192 self.ChangeState("GETCONTROLLER")
193 self.Pane().InputIndexSet(0)
195 def deleteController(self):
197 Layout.Inst().PopDialogue()
198 Layout.Inst().TransientBanner(Lang("Deleting controller..."))
200 self.SetController(None)
201 Layout.Inst().PushDialogue(InfoDialogue(Lang("Controller deletion successful")))
203 Layout.Inst().PushDialogue(InfoDialogue(Lang("Controller deletion failed")))
205 def syncController(self):
206 Layout.Inst().PopDialogue()
207 Layout.Inst().TransientBanner(Lang("Resyncing controller setting..."))
209 Task.Sync(lambda s: self._updateThisServer(s))
210 Layout.Inst().PushDialogue(InfoDialogue(Lang("Resyncing controller config successful")))
212 Layout.Inst().PushDialogue(InfoDialogue(Lang("Resyncing controller config failed")))
214 def SetController(self, ip):
216 self.hostsUpdated = 0
217 Task.Sync(lambda s: self._modifyPoolConfig(s, "vSwitchController", ip))
218 # Should be done asynchronously, maybe with an external script?
219 Task.Sync(lambda s: self._updateActiveServers(s))
221 def _modifyPoolConfig(self, session, key, value):
222 """Modify pool configuration.
224 If value == None then delete key, otherwise set key to value."""
225 pools = session.xenapi.pool.get_all()
226 # We assume there is only ever one pool...
228 log.error("No pool for host.")
229 raise XenAPIPlugin.Failure("NO_POOL_FOR_HOST", [])
231 log.error("More than one pool for host.")
232 raise XenAPIPlugin.Failure("MORE_THAN_ONE_POOL_FOR_HOST", [])
233 session.xenapi.pool.remove_from_other_config(pools[0], key)
235 session.xenapi.pool.add_to_other_config(pools[0], key, value)
238 def _updateActiveServers(self, session):
239 hosts = session.xenapi.host.get_all()
240 self.hostsUpdated = 0
241 self.hostsInPool = len(hosts)
244 Layout.Inst().TransientBanner("Updating host %d out of %d"
245 % (self.hostsUpdated + 1, self.hostsInPool))
246 session.xenapi.host.call_plugin(host, "vswitch-cfg-update", "update", {})
247 self.hostsUpdated = self.hostsUpdated + 1
249 def _updateThisServer(self, session):
251 host = data.host.opaqueref()
252 session.xenapi.host.call_plugin(host, "vswitch-cfg-update", "update", {})
255 class XSFeatureVSwitch:
258 def StatusUpdateHandler(cls, inPane):
261 inPane.AddTitleField(Lang("vSwitch"))
265 versionStr = data.host.other_config({}).get("vSwitchVersion", "<Unknown>")
266 inPane.AddStatusField(Lang("Version", 20), versionStr)
270 pool = data.GetPoolForThisHost()
272 dbController = pool.get("other_config", {}).get("vSwitchController", "")
276 if dbController == "":
277 dbController = Lang("<None>")
278 inPane.AddStatusField(Lang("Controller (config)", 20), dbController)
279 controller = VSwitchConfig.Get("mgmt.controller")
281 controller = Lang("<None>")
282 elif controller[0:4] == "ssl:":
283 controller = controller[4:]
284 inPane.AddStatusField(Lang("Controller (in-use)", 20), controller)
287 inPane.AddStatusField(Lang("ovs-vswitchd status", 20),
288 VSwitchService.Inst("vswitch", "ovs-vswitchd").status())
289 inPane.AddStatusField(Lang("ovs-brcompatd status", 20),
290 VSwitchService.Inst("vswitch", "ovs-brcompatd").status())
292 inPane.AddKeyHelpField( {
293 Lang("<Enter>") : Lang("Reconfigure"),
294 Lang("<F5>") : Lang("Refresh")
298 def ActivateHandler(cls):
299 DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(VSwitchControllerDialogue()))
302 Importer.RegisterNamedPlugIn(
304 'VSwitch', # Key of this plugin for replacement, etc.
306 'menuname' : 'MENU_NETWORK',
307 'menupriority' : 800,
308 'menutext' : Lang('vSwitch') ,
309 'statusupdatehandler' : self.StatusUpdateHandler,
310 'activatehandler' : self.ActivateHandler
314 # Register this plugin when module is imported
315 XSFeatureVSwitch().Register()