Merge "next" branch into "master".
[sliver-openvswitch.git] / xenserver / usr_lib_xsconsole_plugins-base_XSFeatureVSwitch.py
1 # Copyright (c) Citrix Systems 2008. All rights reserved.
2 # xsconsole is proprietary software.
3 #
4 # Xen, the Xen logo, XenCenter, XenMotion are trademarks or registered
5 # trademarks of Citrix Systems, Inc., in the United States and other
6 # countries.
7
8 # Copyright (c) 2009 Nicira Networks.
9
10 from XSConsoleLog import *
11
12 import os
13 import socket
14 import subprocess
15
16 vsctl="/usr/bin/ovs-vsctl"
17
18 if __name__ == "__main__":
19     raise Exception("This script is a plugin for xsconsole and cannot run independently")
20
21 from XSConsoleStandard import *
22
23 class VSwitchService:
24     service = {}
25
26     def __init__(self, name, processname=None):
27         self.name = name
28         self.processname = processname
29         if self.processname == None:
30             self.processname = name
31
32     def version(self):
33         try:
34             output = ShellPipe(["service", self.name, "version"]).Stdout()
35         except StandardError, e:
36             XSLogError("vswitch version retrieval error: " + str(e))
37             return "<unknown>"
38         for line in output:
39             if self.processname in line:
40                 return line.split()[-1]
41         return "<unknown>"
42
43     def status(self):
44         try:
45             output = ShellPipe(["service", self.name, "status"]).Stdout()
46         except StandardError, e:
47             XSLogError("vswitch status retrieval error: " + str(e))
48             return "<unknown>"
49         if len(output) == 0:
50             return "<unknown>"
51         for line in output:
52             if self.processname not in line:
53                 continue
54             elif "running" in line:
55                 return "Running"
56             elif "stop" in line:
57                 return "Stopped"
58             else:
59                 return "<unknown>"
60         return "<unknown>"
61
62     def restart(self):
63         try:
64             ShellPipe(["service", self.name, "restart"]).Call()
65         except StandardError, e:
66             XSLogError("vswitch restart error: " + str(e))
67
68     @classmethod
69     def Inst(cls, name, processname=None):
70         key = name
71         if processname != None:
72             key = key + "-" + processname
73         if name not in cls.service:
74             cls.service[key] = VSwitchService(name, processname)
75         return cls.service[key]
76
77 class VSwitchConfig:
78
79     @staticmethod
80     def Get(action):
81         try:
82             output = ShellPipe([vsctl, "-vANY:console:emer", action]).Stdout()
83         except StandardError, e:
84             XSLogError("config retrieval error: " + str(e))
85             return "<unknown>"
86
87         if len(output) == 0:
88             output = ""
89         else:
90             output = output[0].strip()
91         return output
92
93
94 class VSwitchControllerDialogue(Dialogue):
95     def __init__(self):
96         Dialogue.__init__(self)
97         data=Data.Inst()
98
99         self.hostsInPool = 0
100         self.hostsUpdated = 0
101         pool = data.GetPoolForThisHost()
102         if pool is not None:
103             self.controller = pool.get("other_config", {}).get("vSwitchController", "")
104         else:
105             self.controller = ""
106
107         choiceDefs = [
108             ChoiceDef(Lang("Set pool-wide controller"),
109                       lambda: self.getController()),
110             ChoiceDef(Lang("Delete pool-wide controller"),
111                       lambda: self.deleteController()),
112             ChoiceDef(Lang("Resync server controller config"),
113                       lambda: self.syncController()),
114 #             ChoiceDef(Lang("Restart ovs-vswitchd"),
115 #                       lambda: self.restartService("vswitch")),
116 #             ChoiceDef(Lang("Restart ovs-brcompatd"),
117 #                       lambda: self.restartService("vswitch-brcompatd"))
118             ]
119         self.menu = Menu(self, None, Lang("Configure vSwitch"), choiceDefs)
120
121         self.ChangeState("INITIAL")
122
123     def BuildPane(self):
124         pane = self.NewPane(DialoguePane(self.parent))
125         pane.TitleSet(Lang("Configure vSwitch"))
126         pane.AddBox()
127
128     def ChangeState(self, inState):
129         self.state = inState
130         self.BuildPane()
131         self.UpdateFields()
132
133     def UpdateFields(self):
134         self.Pane().ResetPosition()
135         getattr(self, "UpdateFields" + self.state)() # Dispatch method named 'UpdateFields'+self.state
136
137     def UpdateFieldsINITIAL(self):
138         pane = self.Pane()
139         pane.AddTitleField(Lang("Select an action"))
140         pane.AddMenuField(self.menu)
141         pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Cancel") } )
142
143     def UpdateFieldsGETCONTROLLER(self):
144         pane = self.Pane()
145         pane.ResetFields()
146
147         pane.AddTitleField(Lang("Enter IP address of controller"))
148         pane.AddInputField(Lang("Address", 16), self.controller, "address")
149         pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Exit") } )
150         if pane.CurrentInput() is None:
151             pane.InputIndexSet(0)
152
153     def HandleKey(self, inKey):
154         handled = False
155         if hasattr(self, "HandleKey" + self.state):
156             handled = getattr(self, "HandleKey" + self.state)(inKey)
157         if not handled and inKey == 'KEY_ESCAPE':
158             Layout.Inst().PopDialogue()
159             handled = True
160         return handled
161
162     def HandleKeyINITIAL(self, inKey):
163         return self.menu.HandleKey(inKey)
164
165     def HandleKeyGETCONTROLLER(self, inKey):
166         pane = self.Pane()
167         if pane.CurrentInput() is None:
168             pane.InputIndexSet(0)
169         if inKey == 'KEY_ENTER':
170             inputValues = pane.GetFieldValues()
171             self.controller = inputValues['address']
172             Layout.Inst().PopDialogue()
173
174             # Make sure the controller is specified as a valid dotted quad
175             try:
176                 socket.inet_aton(self.controller)
177             except socket.error:
178                 Layout.Inst().PushDialogue(InfoDialogue(Lang("Please enter in dotted quad format")))
179                 return True
180
181             Layout.Inst().TransientBanner(Lang("Setting controller..."))
182             try:
183                 self.SetController(self.controller)
184                 Layout.Inst().PushDialogue(InfoDialogue(Lang("Setting controller successful")))
185             except Exception, e:
186                 Layout.Inst().PushDialogue(InfoDialogue(Lang("Setting controller failed")))
187
188             self.ChangeState("INITIAL")
189             return True
190         else:
191             return pane.CurrentInput().HandleKey(inKey)
192
193     def restartService(self, name):
194         s = VSwitchService.Inst(name)
195         s.restart()
196         Layout.Inst().PopDialogue()
197
198     def getController(self):
199         self.ChangeState("GETCONTROLLER")
200         self.Pane().InputIndexSet(0)
201
202     def deleteController(self):
203         self.controller = ""
204         Layout.Inst().PopDialogue()
205         Layout.Inst().TransientBanner(Lang("Deleting controller..."))
206         try:
207             self.SetController(None)
208             Layout.Inst().PushDialogue(InfoDialogue(Lang("Controller deletion successful")))
209         except Exception, e:
210             Layout.Inst().PushDialogue(InfoDialogue(Lang("Controller deletion failed")))
211
212     def syncController(self):
213         Layout.Inst().PopDialogue()
214         Layout.Inst().TransientBanner(Lang("Resyncing controller setting..."))
215         try:
216             Task.Sync(lambda s: self._updateThisServer(s))
217             Layout.Inst().PushDialogue(InfoDialogue(Lang("Resyncing controller config successful")))
218         except Exception, e:
219             Layout.Inst().PushDialogue(InfoDialogue(Lang("Resyncing controller config failed")))
220
221     def SetController(self, ip):
222         self.hostsInPool = 0
223         self.hostsUpdated = 0
224         Task.Sync(lambda s: self._modifyPoolConfig(s, "vSwitchController", ip))
225         # Should be done asynchronously, maybe with an external script?
226         Task.Sync(lambda s: self._updateActiveServers(s))
227
228     def _modifyPoolConfig(self, session, key, value):
229         """Modify pool configuration.
230
231         If value == None then delete key, otherwise set key to value."""
232         pools = session.xenapi.pool.get_all()
233         # We assume there is only ever one pool...
234         if len(pools) == 0:
235             log.error("No pool for host.")
236             raise XenAPIPlugin.Failure("NO_POOL_FOR_HOST", [])
237         if len(pools) > 1:
238             log.error("More than one pool for host.")
239             raise XenAPIPlugin.Failure("MORE_THAN_ONE_POOL_FOR_HOST", [])
240         session.xenapi.pool.remove_from_other_config(pools[0], key)
241         if value != None:
242             session.xenapi.pool.add_to_other_config(pools[0], key, value)
243         Data.Inst().Update()
244
245     def _updateActiveServers(self, session):
246         hosts = session.xenapi.host.get_all()
247         self.hostsUpdated = 0
248         self.hostsInPool = len(hosts)
249         self.UpdateFields()
250         for host in hosts:
251             Layout.Inst().TransientBanner("Updating host %d out of %d" 
252                     % (self.hostsUpdated + 1, self.hostsInPool))
253             session.xenapi.host.call_plugin(host, "vswitch-cfg-update", "update", {})
254             self.hostsUpdated = self.hostsUpdated + 1
255
256     def _updateThisServer(self, session):
257         data = Data.Inst()
258         host = data.host.opaqueref()
259         session.xenapi.host.call_plugin(host, "vswitch-cfg-update", "update", {})
260
261
262 class XSFeatureVSwitch:
263
264     @classmethod
265     def StatusUpdateHandler(cls, inPane):
266         data = Data.Inst()
267
268         inPane.AddTitleField(Lang("vSwitch"))
269
270         inPane.NewLine()
271
272         inPane.AddStatusField(Lang("Version", 20),
273                               VSwitchService.Inst("vswitch", "ovs-vswitchd").version())
274
275         inPane.NewLine()
276
277         pool = data.GetPoolForThisHost()
278         if pool is not None:
279             dbController = pool.get("other_config", {}).get("vSwitchController", "")
280         else:
281             dbController = ""
282
283         if dbController == "":
284             dbController = Lang("<None>")
285         inPane.AddStatusField(Lang("Controller (config)", 20), dbController)
286         controller = VSwitchConfig.Get("get-controller")
287         if controller == "":
288             controller = Lang("<None>")
289         elif controller[0:4] == "ssl:":
290             controller = controller[4:]
291         inPane.AddStatusField(Lang("Controller (in-use)", 20), controller)
292
293         inPane.NewLine()
294         inPane.AddStatusField(Lang("ovs-vswitchd status", 20),
295                               VSwitchService.Inst("vswitch", "ovs-vswitchd").status())
296         inPane.AddStatusField(Lang("ovs-brcompatd status", 20),
297                               VSwitchService.Inst("vswitch", "ovs-brcompatd").status())
298
299         inPane.AddKeyHelpField( {
300             Lang("<Enter>") : Lang("Reconfigure"),
301             Lang("<F5>") : Lang("Refresh")
302         })
303
304     @classmethod
305     def ActivateHandler(cls):
306         DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(VSwitchControllerDialogue()))
307
308     def Register(self):
309         Importer.RegisterNamedPlugIn(
310             self,
311             'VSwitch', # Key of this plugin for replacement, etc.
312             {
313                 'menuname' : 'MENU_NETWORK',
314                 'menupriority' : 800,
315                 'menutext' : Lang('vSwitch') ,
316                 'statusupdatehandler' : self.StatusUpdateHandler,
317                 'activatehandler' : self.ActivateHandler
318             }
319         )
320
321 # Register this plugin when module is imported
322 XSFeatureVSwitch().Register()