diff --git a/INSTALL b/INSTALL index d91154a..e9a7ae1 100644 --- a/INSTALL +++ b/INSTALL @@ -1,6 +1,6 @@ There are prerequisites for building a xsconsole for XenServer. All the following must be installed, either by visiting the -project webpage or installing a pre-built package provided by +project webpage or installing a pre-built package provided by your OS distributor: * RPM build * Redhat rpm config (if debuginfo is required) @@ -36,12 +36,12 @@ Follow these steps to build an RPM. Move xsconsole.spec to /usr/src/redhat/SPECS/ Move xsconsole-plugins-oem.tar.bz2 to /usr/src/redhat/SOURCES/ Move xsconsole-plugins-oem.spec to /usr/src/redhat/SPECS/ - + 5. To build the RPMs run: cd /usr/src/redhat/SPECS/ rpmbuild -ba xsconsole.spec --target noarch rpmbuild -ba xsconsole-plugins-oem.spec --target noarch - + 6. Install using rpm -ivh /usr/src/redhat/RPMS/noarch/xsconsole*.rpm diff --git a/MaintenanceReadme.txt b/MaintenanceReadme.txt index d7ec493..a370de3 100644 --- a/MaintenanceReadme.txt +++ b/MaintenanceReadme.txt @@ -83,7 +83,7 @@ Very rarely this gives a pane height one line to short, probably because the ref 6. UpdateFields generally recreates fields from scratch, so you can't just call it whenever you like because, e.g. values in text entry fields will be lost and cursors reset. It's fine to update the root dialogue though. -7. It's tricky to get the ncurses display to refresh without flicker. Using the curses erase or clear methods on windows can lead to flickering redraws. Currently only scrolling in the right hand pane of the root dialogue has this problem. Since there's not much use of erase or clear the app does pretty minimal redraws, and things like spurious kernel message that scroll the screen can leave it in a mess for some time. +7. It's tricky to get the ncurses display to refresh without flicker. Using the curses erase or clear methods on windows can lead to flickering redraws. Currently only scrolling in the right hand pane of the root dialogue has this problem. Since there's not much use of erase or clear the app does pretty minimal redraws, and things like spurious kernel message that scroll the screen can leave it in a mess for some time. 8. MountVDI's Create VDB/Plug VBD/Mount VBD/Use VBD/Unmount VBD/Unplug VBD/Destroy VBD sequence failed when trying to mount empty CD drives. Now only MountVDIDirectly is used. diff --git a/README.md b/README.md index a87971d..b17fd06 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ What is this repository ? This is the repository of XenServer-specific commits to the Xen project xsconsole. -xsconsole is python based and provides and a ncurses GUI to get/set +xsconsole is python based and provides and a ncurses GUI to get/set XenServer information from within a Domain0 console. To contribute bug fixes, email them to the XenServer development mailing diff --git a/XSConsole.py b/XSConsole.py index 234886b..f6a8883 100755 --- a/XSConsole.py +++ b/XSConsole.py @@ -35,7 +35,7 @@ def main(): app.Build( ['plugins-base', 'plugins-oem', 'plugins-extras'] ) try: app.Enter() - except Exception, e: + except Exception as e: # it may be that the screen size has changed app.AssertScreenSize() # if we get here then it was some other problem @@ -44,7 +44,7 @@ def main(): if __name__ == "__main__": try: main() - except Exception, e: + except Exception as e: # Add backtrace to log try: trace = traceback.format_tb(sys.exc_info()[2]) diff --git a/XSConsoleAuth.py b/XSConsoleAuth.py index 2a6f06d..e35e316 100644 --- a/XSConsoleAuth.py +++ b/XSConsoleAuth.py @@ -128,7 +128,7 @@ def PAMConv(inAuth, inQueryList, *theRest): auth.authenticate() auth.acct_mgmt() # No exception implies a successful login - except Exception, e: + except Exception as e: # Display a generic message for all failures raise Exception(Lang("The system could not log you in. Please check your access credentials and try again.")) @@ -188,7 +188,7 @@ def OpenSession(self): session = None self.masterConnectionBroken = True self.error = 'The master connection has timed out.' - except Exception, e: + except Exception as e: session = None self.error = e @@ -198,7 +198,7 @@ def OpenSession(self): try: session.login_with_password('root', self.defaultPassword,'','XSConsole') - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'HOST_IS_SLAVE': # Ignore slave errors when testing session = None self.error = e @@ -206,7 +206,7 @@ def OpenSession(self): session = None self.masterConnectionBroken = True self.error = 'The master connection has timed out.' - except Exception, e: + except Exception as e: session = None self.error = e return session @@ -218,7 +218,7 @@ def CloseSession(self, inSession): if inSession._session is not None: try: inSession.logout() - except XenAPI.Failure, e: + except XenAPI.Failure as e: XSLog('XAPI Failed to logout exception was ', e) return None @@ -241,7 +241,7 @@ def ChangePassword(self, inOldPassword, inNewPassword): if self.IsPasswordSet(): try: self.PAMAuthenticate('root', inOldPassword) - except Exception, e: + except Exception as e: raise Exception(Lang('Old password not accepted. Please check your access credentials and try again.')) self.AssertAuthenticated() @@ -252,7 +252,7 @@ def ChangePassword(self, inOldPassword, inNewPassword): session.xenapi.session.change_password(inOldPassword, inNewPassword) finally: self.CloseSession(session) - except Exception, e: + except Exception as e: ShellPipe("/usr/bin/passwd", "--stdin", "root").Call(inNewPassword) raise Exception(Lang("The underlying Xen API xapi could not be used. Password changed successfully on this host only.")) diff --git a/XSConsoleBases.py b/XSConsoleBases.py index 5de2ef6..abf69de 100644 --- a/XSConsoleBases.py +++ b/XSConsoleBases.py @@ -35,6 +35,6 @@ class Struct: def __init__(self, *inArgs, **inKeywords): for k, v in inKeywords.items(): setattr(self, k, v) - + def __repr__(self): return str(self.__dict__) diff --git a/XSConsoleCurses.py b/XSConsoleCurses.py index 7881cd6..f2fbb2b 100644 --- a/XSConsoleCurses.py +++ b/XSConsoleCurses.py @@ -180,7 +180,7 @@ def ClippedAddStr(self, inString, inX, inY, inColour): # Internal use self.win.addstr(inY, xPos, len(clippedStr)*' ', CursesPalette.ColourAttr(FirstValue(inColour, self.defaultColour))) self.win.refresh() self.win.addstr(inY, xPos, encodedStr, CursesPalette.ColourAttr(FirstValue(inColour, self.defaultColour))) - except Exception, e: + except Exception as e: if xPos + len(inString) == self.xSize and inY + 1 == self.ySize: # Curses incorrectly raises an exception when writing the bottom right # character in a window, but still completes the write, so ignore it diff --git a/XSConsoleData.py b/XSConsoleData.py index dde81a9..85261fd 100644 --- a/XSConsoleData.py +++ b/XSConsoleData.py @@ -164,7 +164,7 @@ def Update(self): try: try: thisHost = self.session.xenapi.session.get_this_host(self.session._session) - except XenAPI.Failure, e: + except XenAPI.Failure as e: XSLog('Data update connection failed - retrying. Exception was:', e) self.session = Auth.Inst().CloseSession(self.session) self.RequireSession() @@ -203,7 +203,7 @@ def convertPIF(inPIF): try: retVal['network'] = self.session.xenapi.network.get_record(retVal['network']) - except XenAPI.Failure, e: + except XenAPI.Failure as e: XSLogError('Missing network record: ', e) retVal['opaqueref'] = inPIF @@ -306,7 +306,7 @@ def update_SR_reference(inPool, retPool, key): except socket.timeout: self.session = None - except Exception, e: + except Exception as e: XSLogError('Data update failed: ', e) try: @@ -326,7 +326,7 @@ def update_SR_reference(inPool, retPool, key): self.data['sr'].append(values) - except Exception, e: + except Exception as e: XSLogError('SR data update failed: ', e) self.UpdateFromResolveConf() @@ -1046,7 +1046,7 @@ def PurgeVBDs(self): if vbd['currently_attached']: self.UnplugVBD(vbd) self.DestroyVBD(vbd) - except Exception, e: + except Exception as e: XSLogError('VBD purge failed', e) def IsXAPIRunning(self): diff --git a/XSConsoleDataUtils.py b/XSConsoleDataUtils.py index d39d5d0..5947720 100644 --- a/XSConsoleDataUtils.py +++ b/XSConsoleDataUtils.py @@ -130,7 +130,7 @@ def SizeString(cls, inSizeOrFilename, inDefault = None): else: retVal = str(int(fileSize)) - except Exception, e: + except Exception as e: retVal = FirstValue(inDefault, '') return retVal @@ -164,7 +164,7 @@ def USBFormat(self, inVDI): try: popenObj.wait() # Must wait for completion before mkfs break - except IOError, e: + except IOError as e: if e.errno != errno.EINTR: # Loop if EINTR raise @@ -241,17 +241,17 @@ def __init__(self, inVDI, inMode = None): if status != 0: try: self.Unmount() - except Exception, e: + except Exception as e: XSLogFailure('Device failed to unmount', e) output += '\n'+self.mountDev self.HandleMountFailure(output.split("\n")) self.mountedVBD = True - except Exception, e: + except Exception as e: try: self.Unmount() - except Exception, e: + except Exception as e: # Report the original exception, not this one XSLogFailure('Device failed to unmount', e) raise e @@ -324,7 +324,7 @@ def Unmount(self): time.sleep(5) try: self.vbd = Data.Inst().UnplugVBD(self.vbd) - except Exception, e: + except Exception as e: XSLogFailure('Device failed to unmount', e) self.pluggedVBD = False @@ -364,17 +364,17 @@ def __init__(self, inVDI, inMode = None): if status != 0: try: self.Unmount() - except Exception, e: + except Exception as e: XSLogFailure('Device failed to unmount', e) output += '\n'+self.mountDev self.HandleMountFailure(status, output.split("\n")) self.mountedVDI = True XSLog('Mounted '+self.mountDev + ' on ' + self.mountPoint + ' mode ' + self.mode) - except Exception, e: + except Exception as e: try: self.Unmount() - except Exception, e: + except Exception as e: XSLogFailure('Device failed to unmount', e) raise e diff --git a/XSConsoleDialogueBases.py b/XSConsoleDialogueBases.py index a6d989a..8b9931a 100644 --- a/XSConsoleDialogueBases.py +++ b/XSConsoleDialogueBases.py @@ -204,7 +204,7 @@ def HandleKey(self, inKey): else: Layout.Inst().PushDialogue(InfoDialogue( Lang('Login Successful'))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang('Login Failed: ')+Lang(e))) Data.Inst().Update() @@ -401,7 +401,7 @@ def HandleKeyUSBNOTFORMATTED(self, inKey): try: FileUtils.USBFormat(self.vdi) self.HandleDevice() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Formatting Failed"), Lang(e))) handled = True @@ -425,7 +425,7 @@ def HandleKeyCUSTOM(self, inKey): FileUtils.AssertSafeLeafname(inputValues['filename']) self.filename = inputValues['filename'] self.ChangeState('CONFIRM') - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue(Lang(e))) elif pane.CurrentInput().HandleKey(inKey): @@ -477,7 +477,7 @@ def HandleDevice(self): except USBNotMountable: Layout.Inst().PopDialogue() self.ChangeState('USBNOTMOUNTABLE') - except Exception, e: + except Exception as e: try: self.PreExitActions() except Exception: @@ -542,7 +542,7 @@ def HandleKey(self, inKey): Layout.Inst().DoUpdate() title, info = self.HandleCommit(self.Pane().GetFieldValues()) Layout.Inst().PushDialogue(InfoDialogue( title, info)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang('Failed: ')+Lang(e))) elif inKey == 'KEY_TAB': pane.ActivateNextInput() @@ -651,7 +651,7 @@ def UpdateFieldsINITIAL(self): durationSecs = self.task.DurationSecs() elapsedStr = TimeUtils.DurationString(durationSecs) - except Exception, e: + except Exception as e: progressStr = Lang('') elapsedStr = Lang('') @@ -677,7 +677,7 @@ def UpdateFieldsCANCEL(self): durationSecs = self.task.DurationSecs() elapsedStr = TimeUtils.DurationString(durationSecs) - except Exception, e: + except Exception as e: progressStr = Lang('') elapsedStr = Lang('') @@ -702,7 +702,7 @@ def UpdateFieldsCOMPLETE(self): durationSecs = self.task.DurationSecs() elapsedStr = TimeUtils.DurationString(durationSecs) - except Exception, e: + except Exception as e: elapsedStr = Lang(e) pane.AddWrappedTextField(Lang('Time', 16) + elapsedStr) diff --git a/XSConsoleHotData.py b/XSConsoleHotData.py index 14e2a60..e05103e 100644 --- a/XSConsoleHotData.py +++ b/XSConsoleHotData.py @@ -196,7 +196,7 @@ def GetData(self, inNames, inDefault, inRefs): raise Exception("List index "+str(currentRef)+" out of range in '"+'.'.join(inNames)+"'") itemRef = itemRef[currentRef] return itemRef - except Exception, e: + except Exception as e: # Data not present/fetchable, so return the default value return FirstValue(inDefault, None) diff --git a/XSConsoleImporter.py b/XSConsoleImporter.py index a45984d..454be61 100644 --- a/XSConsoleImporter.py +++ b/XSConsoleImporter.py @@ -47,7 +47,7 @@ def ImportAbsDir(cls, inDir): # Import using variable as module name (fileObj, pathName, description) = imp.find_module(importName, [root]) imp.load_module(importName, fileObj, pathName, description) - except Exception, e: + except Exception as e: try: XSLogError(*traceback.format_tb(sys.exc_info()[2])) except: pass try: XSLogError("*** PlugIn '"+importName+"' failed to load: "+str(e)) diff --git a/XSConsoleKeymaps.py b/XSConsoleKeymaps.py index 682f847..f6610a4 100644 --- a/XSConsoleKeymaps.py +++ b/XSConsoleKeymaps.py @@ -55,9 +55,9 @@ class Keymaps: Lang("US International") : 'us-acentos', Lang("US English") : 'us' } - + @classmethod def NamesToMaps(cls): return cls.namesToMaps - - + + diff --git a/XSConsoleLang.py b/XSConsoleLang.py index 4ae8bac..e13f8f7 100644 --- a/XSConsoleLang.py +++ b/XSConsoleLang.py @@ -25,20 +25,20 @@ def Lang(inLabel, inPad = 0): if inPad > 0: retStr = retStr.ljust(inPad, ' ') return retStr - + class Language: instance = None stringHook = None errorHook = None errorLoggingHook = None - + def __init__(self): self.brandingMap = Config.Inst().BrandingMap() - + @classmethod def SetStringHook(cls, inHook): cls.stringHook = inHook - + @classmethod def SetErrorHook(cls, inHook): cls.errorHook = inHook @@ -52,7 +52,7 @@ def Inst(self): if self.instance is None: self.instance = Language() return self.instance - + @classmethod def Quantity(cls, inText, inNumber): if inNumber == 1: @@ -112,19 +112,19 @@ def ReflowText(cls, inText, inWidth): lineLength = inWidth else: lineLength = spacePos - + thisLine = text[:lineLength] thisLine = thisLine.replace("\t", " ") # Tab is used as a non-breaking space thisLine = thisLine.replace("\r", "RET") # Debugging thisLine = thisLine.strip() # Remove leading whitespace (generally the second space in a double space) if len(thisLine) > 0 or retPos != -1: # Only add blank lines if they follow a return retArray.append(thisLine) - + if spacePos == -1: text = text[lineLength:] # Split at non-space/return, so keep else: text = text[lineLength+1:] # Split at space or return so discard - + return retArray def Branding(self, inText): diff --git a/XSConsoleLayout.py b/XSConsoleLayout.py index 28a2d2c..1de2884 100644 --- a/XSConsoleLayout.py +++ b/XSConsoleLayout.py @@ -20,12 +20,12 @@ class Layout: WIN_MAIN = 0 WIN_TOPLINE = 1 - + APP_XSIZE = 80 APP_YSIZE = 24 - + instance = None - + def __init__(self, inParent = None): self.parent = inParent self.windows = [] @@ -45,12 +45,12 @@ def Inst(cls): if cls.instance is None: cls.instance = Layout() return cls.instance - + @classmethod def NewInst(cls): cls.instance = Layout() return cls.instance - + def ParentSet(self, inParent): self.parent = inParent @@ -59,13 +59,13 @@ def Parent(self): def ExitBanner(self): return self.exitBanner - + def ExitBannerSet(self, inBanner): self.exitBanner = inBanner - + def ExitCommand(self): return self.exitCommand - + def ExitCommandSet(self, inCommand): self.exitCommand = inCommand self.exitCommandIsExec = True @@ -79,13 +79,13 @@ def ExitCommandIsExec(self): def Window(self, inNum): return self.windows[inNum] - + def TopDialogue(self): return self.dialogues[-1] - + def PushDialogue(self, inDialogue): self.dialogues.append(inDialogue) - + def PopDialogue(self): if len(self.dialogues) < 1: raise Exception("Stack underflow in PopDialogue") @@ -97,11 +97,11 @@ def PopDialogue(self): HotData.Inst().DeleteCache() self.TopDialogue().UpdateFields() self.Refresh() - + def UpdateRootFields(self): if len(self.dialogues) > 0: self.dialogues[0].UpdateFields() - + def LiveUpdateFields(self): needsRefresh = False if len(self.dialogues) > 0: @@ -110,38 +110,38 @@ def LiveUpdateFields(self): topDialogue.LiveUpdateFields() needsRefresh = True return needsRefresh - + def TransientBannerHandlerSet(self, inHandler): self.transientBannerHandler = inHandler - + def TransientBanner(self, inMessage): self.transientBannerHandler(inMessage) - + def WriteParentOffset(self, inParent): self.AssertScreenSize() - + # Centralise subsequent windows inParent.OffsetSet( (inParent.XSize() - self.APP_XSIZE) / 2, (inParent.YSize() - self.APP_YSIZE) / 2) - + def Create(self): self.windows.append(CursesWindow(0,1,self.APP_XSIZE, self.APP_YSIZE-1, self.parent)) # MainWindow self.windows.append(CursesWindow(0,0,self.APP_XSIZE,1, self.parent)) # Top line window self.windows[self.WIN_MAIN].DefaultColourSet('MAIN_BASE') self.windows[self.WIN_TOPLINE].DefaultColourSet('TOPLINE_BASE') - + self.Window(self.WIN_MAIN).AddBox() self.Window(self.WIN_MAIN).TitleSet("Configuration") - + def CreateRootDialogue(self, inRootDialogue): self.dialogues = [ inRootDialogue ] - + def Reset(self): while len(self.dialogues) > 1: self.PopDialogue() self.TopDialogue().Reset() - + def Refresh(self): self.Window(self.WIN_MAIN).Erase() # Unknown why main won't redraw without this for window in self.windows: @@ -149,7 +149,7 @@ def Refresh(self): for dialogue in self.dialogues: dialogue.Render() - + if not self.TopDialogue().NeedsCursor(): self.TopDialogue().CursorOff() @@ -157,12 +157,12 @@ def Redraw(self): for window in self.windows: window.Win().redrawwin() window.Win().refresh() - + def Clear(self): for window in self.windows: window.Clear() self.Refresh() - + def DoUpdate(self): curses.doupdate() - + diff --git a/XSConsoleLog.py b/XSConsoleLog.py index 0e98428..fc18e3c 100644 --- a/XSConsoleLog.py +++ b/XSConsoleLog.py @@ -19,7 +19,7 @@ def XSLog(*inParams): XSLogger.Inst().Log(syslog.LOG_INFO, *inParams) - + def XSLogFatal(*inParams): XSLogger.Inst().Log(syslog.LOG_CRIT, *inParams) @@ -45,7 +45,7 @@ def Inst(cls): def Log(self, inPriority, *inParams): for param in inParams: syslog.syslog(inPriority, str(param)) - + def LogFailure(self, *inParams): logString = "\n".join( [ str(param) for param in inParams ] ) message = Lang(Exception(logString)) # Translation using Lang() causes the exception tp be logged diff --git a/XSConsoleMenus.py b/XSConsoleMenus.py index d8248fe..e06937a 100644 --- a/XSConsoleMenus.py +++ b/XSConsoleMenus.py @@ -26,13 +26,13 @@ class ChoiceDef: def __init__(self, name, onAction = None, onEnter = None, priority = None, statusUpdateHandler = None, handle = None): ParamsToAttr() - + def StatusUpdateHandler(self): return self.statusUpdateHandler - + def StatusUpdateHandlerSet(self, inHandler): self.statusUpdateHandler = inHandler - + def OnAction(self): return self.onAction @@ -63,24 +63,24 @@ def AddChoiceDef(self, inChoiceDef, inPriority = None): self.defaultPriority += 100 else: priority = inPriority - + inChoiceDef.priority = priority # FIXME (modifies input parameter) self.choiceDefs.append(inChoiceDef) - + self.choiceDefs.sort(lambda x, y : cmp(x.priority, y.priority)) def AddChoice(self, name, onAction = None, onEnter = None, priority = None, statusUpdateHandler = None, handle = None): choiceDef = ChoiceDef(name, onAction, onEnter, priority, statusUpdateHandler, handle) self.AddChoiceDef(choiceDef) - + def RemoveChoices(self): self.choiceDefs = [] self.defaultPriority=1000 - + def CurrentChoiceSet(self, inChoice): self.choiceIndex = inChoice # Also need to call HandleEnter - + def CurrentChoiceDef(self): if self.choiceIndex >= len(self.choiceDefs): self.choiceIndex = max(0, len(self.choiceDefs) - 1) @@ -151,23 +151,23 @@ def HandleKey(self, inKey): self.HandleEnter() handled = True break - + return handled - + class RootMenu: def __init__(self, inDialogue): self.menus = {'MENU_ROOT' : Menu(self, None, Lang("Customize System"), [ ]) } self.currentKey = 'MENU_ROOT' - + def GetMenu(self, inMenuName): retVal = self.menus.get(inMenuName, None) if retVal is None: raise Exception(Lang("Unknown menu '")+inMenuName+"'") return retVal - + def SetMenu(self, inMenuName, inMenu): self.menus[inMenuName] = inMenu - + def CurrentMenu(self): return self.menus[self.currentKey] @@ -180,16 +180,16 @@ def ChangeMenu(self, inKey): def Reset(self): self.currentKey = 'MENU_ROOT' - + for menu in self.menus.values(): menu.CurrentChoiceSet(0) - + self.CurrentMenu().HandleEnter() - + def AddChoice(self, inMenuName, inChoiceDef, inPriority = None): if not self.menus.has_key(inMenuName): raise Exception(Lang("Unknown menu '")+inMenuName+"'") - + self.menus[inMenuName].AddChoiceDef(inChoiceDef, inPriority) def CreateMenuIfNotPresent(self, inName, inTitle = None, inParent = None): diff --git a/XSConsoleMetrics.py b/XSConsoleMetrics.py index 6f005d9..0e96199 100644 --- a/XSConsoleMetrics.py +++ b/XSConsoleMetrics.py @@ -51,12 +51,12 @@ def LocalHostMetrics(self): try: retVal['memory_total'] = float(self.data[hostPrefix +':memory_total_kib']) * 1024.0 - except Exception, e: + except Exception as e: retVal['memory_total'] = None try: retVal['memory_free'] = float(self.data[hostPrefix +':memory_free_kib']) * 1024.0 - except Exception, e: + except Exception as e: retVal['memory_free'] = None return retVal @@ -76,12 +76,12 @@ def VMMetrics(self, inUUID): try: retVal['memory_total'] = float(self.data[vmPrefix +':memory']) # Not scaled - except Exception, e: + except Exception as e: retVal['memory_total'] = None try: retVal['memory_free'] = float(self.data[vmPrefix +':memory_internal_free']) * 1024.0 # Value is in kiB - except Exception, e: + except Exception as e: retVal['memory_free'] = None return retVal diff --git a/XSConsoleRemoteTest.py b/XSConsoleRemoteTest.py index ab294a9..b506bf2 100644 --- a/XSConsoleRemoteTest.py +++ b/XSConsoleRemoteTest.py @@ -108,7 +108,7 @@ def ErrorString(self, inException = None): for i, pane in enumerate(snapshot): for line in pane: retVal += 'Pane '+str(i) + ':' + line + '\n' - except Exception, e: + except Exception as e: retVal += 'Failed: '+Lang(e) if len(self.errors) > 0: retVal += "\n\nExceptions process by Lang()\n\n" + "\n".join(self.errors) @@ -121,14 +121,14 @@ def ErrorString(self, inException = None): def WrapProcedure(self, inProc): # Any return value of inProc is discarded try: inProc() - except Exception, e: + except Exception as e: raise xmlrpclib.Fault(1, self.ErrorString(e)) return None def WrapFunction(self, inFunc): # inFunc returns a value try: retVal = inFunc() - except Exception, e: + except Exception as e: raise xmlrpclib.Fault(1, self.ErrorString(e)) return retVal diff --git a/XSConsoleRootDialogue.py b/XSConsoleRootDialogue.py index 80c37d0..75fd3c2 100644 --- a/XSConsoleRootDialogue.py +++ b/XSConsoleRootDialogue.py @@ -28,7 +28,7 @@ from XSConsoleMenus import * class RootDialogue(Dialogue): - + def __init__(self, inLayout, inParent): Dialogue.__init__(self, inLayout, inParent) menuPane = self.NewPane(DialoguePane(self.parent, PaneSizerFixed(1, 2, 39, 21)), 'menu') @@ -50,29 +50,29 @@ def UpdateFields(self): menuPane.AddTitleField(currentMenu.Title()) menuPane.AddMenuField(currentMenu, 16) # Allow extra height for this menu - + statusPane = self.Pane('status') try: statusPane.ResetFields() statusPane.ResetPosition() - + statusUpdateHandler = currentChoiceDef.StatusUpdateHandler() if statusUpdateHandler is not None: if currentChoiceDef.handle is not None: statusUpdateHandler(statusPane, currentChoiceDef.handle) else: statusUpdateHandler(statusPane) - + else: raise Exception(Lang("Missing status handler")) - except Exception, e: + except Exception as e: statusPane.ResetFields() statusPane.ResetPosition() statusPane.AddTitleField(Lang("Information not available")) statusPane.AddWrappedTextField(Lang(e)) - + keyHash = { Lang("") : Lang("Select") } if self.menu.CurrentMenu().Parent() != None: keyHash[ Lang("") ] = Lang("Back") @@ -81,14 +81,14 @@ def UpdateFields(self): keyHash[ Lang("") ] = Lang("OK") menuPane.AddKeyHelpField( keyHash ) - + if statusPane.NumStaticFields() == 0: # No key help yet if statusPane.NeedsScroll(): statusPane.AddKeyHelpField( { Lang("") : Lang("Scroll"), Lang("") : Lang("Refresh"), }) - + def HandleKey(self, inKey): currentMenu = self.menu.CurrentMenu() @@ -97,16 +97,16 @@ def HandleKey(self, inKey): if not handled and inKey == 'KEY_PPAGE': self.Pane('status').ScrollPageUp() handled = True - + if not handled and inKey == 'KEY_NPAGE': self.Pane('status').ScrollPageDown() handled = True - + if handled: self.UpdateFields() self.Pane('menu').Refresh() self.Pane('status').Refresh() - + return handled def ChangeMenu(self, inName): @@ -114,7 +114,7 @@ def ChangeMenu(self, inName): self.menuName = inName self.menu.ChangeMenu(inName) self.menu.CurrentMenu().HandleEnter() - + def Reset(self): self.menu.Reset() self.UpdateFields() diff --git a/XSConsoleState.py b/XSConsoleState.py index 291bedb..f0f786e 100644 --- a/XSConsoleState.py +++ b/XSConsoleState.py @@ -24,7 +24,7 @@ class State: savePath = '/etc/xsconsole' saveLeafname = 'state.txt' thisVersion = 9 - + #*** #*** Increment thisVersion (above) when adding attributes to this object #*** @@ -38,11 +38,11 @@ def __init__(self): self.verboseBoot = False self.keymap = None self.sleepSeconds = 30*60 - + @classmethod def SaveFilename(self): return self.savePath+'/'+self.saveLeafname - + @classmethod def Inst(cls): # Load the saved state if we can, otherwise create a default object @@ -59,56 +59,56 @@ def Inst(cls): # Version mismatch - don't use the state information cls.instance = None XSLog('State file version mismatch - discarding') - except Exception, e: + except Exception as e: cls.instance = None - + if cls.instance is None: cls.instance = State() XSLog('No saved state available - using default state') - + # Fill in pseudo-state cls.instance.isFirstBoot = isFirstBoot cls.instance.MakeSane() - + return cls.instance - + def AuthTimeoutSeconds(self): return self.authTimeoutSeconds - + def PasswordChangeRequired(self): return self.passwordChangeRequired - + def PasswordChangeRequiredSet(self, inValue): self.passwordChangeRequired = inValue self.modified = True - + def RebootMessage(self): return self.rebootMessage - + def RebootMessageSet(self, inValue): self.rebootMessage = inValue self.modified = True - + def VerboseBoot(self): return self.verboseBoot - + def VerboseBootSet(self, inValue): self.verboseBoot = inValue self.modified = True - + def Keymap(self): return self.keymap - + def KeymapSet(self, inValue): self.keymap = inValue self.modified = True def IsFirstBoot(self): return self.isFirstBoot - + def WeStoppedXAPI(self): return self.weStoppedXAPI - + def WeStoppedXAPISet(self, inValue): self.weStoppedXAPI = inValue self.modified = True @@ -119,32 +119,32 @@ def AuthTimeoutSecondsSet(self, inSeconds): # Don't call this directly - use Aut if self.authTimeoutSeconds != inSeconds: self.authTimeoutSeconds = inSeconds self.modified = True - + def AuthTimeoutMinutes(self): return int((self.AuthTimeoutSeconds() + 30) / 60) - + def SleepSeconds(self): return self.sleepSeconds - + def MakeSane(self): self.authTimeoutSeconds = int(self.authTimeoutSeconds) if self.authTimeoutSeconds < 60: AuthTimeoutSecondsSet(60) - + def SaveIfRequired(self): if self.modified: self.MakeSane() try: if not os.path.isdir(self.savePath): os.mkdir(self.savePath, 0700) - + saveFile = open(self.SaveFilename(), "w") pickler = pickle.Pickler(saveFile) self.modified = False # Set unmodified before saving pickler.dump(self) saveFile.close() XSLog('Saved state file') - except Exception, e: + except Exception as e: XSLogFailure('Failed to save state file', e) diff --git a/XSConsoleTerm.py b/XSConsoleTerm.py index 2c6f7ab..904f450 100644 --- a/XSConsoleTerm.py +++ b/XSConsoleTerm.py @@ -139,16 +139,16 @@ def Enter(self): os.system(self.layout.ExitCommand()) Data.Inst().Update() # Pick up changes caused by the subshell command - except KeyboardInterrupt, e: # Catch Ctrl-C + except KeyboardInterrupt as e: # Catch Ctrl-C XSLog('Resetting due to Ctrl-C') Data.Reset() sys.stderr.write("\033[H\033[J"+Lang("Resetting...")) # Clear screen and print banner try: time.sleep(0.5) # Prevent flicker - except Exception, e: + except Exception as e: pass # Catch repeated Ctrl-C - except Exception, e: + except Exception as e: sys.stderr.write(Lang(e)+"\n") doQuit = True raise @@ -212,7 +212,7 @@ def MainLoop(self): else: gotKey = self.layout.Window(Layout.WIN_MAIN).GetKey() - except Exception, e: + except Exception as e: gotKey = None # Catch timeout if gotKey == "\011": gotKey = "KEY_TAB" @@ -257,7 +257,7 @@ def MainLoop(self): try: self.HandleKeypress(gotKey) - except Exception, e: + except Exception as e: if Auth.Inst().IsTestMode(): raise message = Lang(e) # Also logs the error diff --git a/XSConsoleUtils.py b/XSConsoleUtils.py index f5a3ad1..3ff451e 100644 --- a/XSConsoleUtils.py +++ b/XSConsoleUtils.py @@ -49,35 +49,35 @@ def __init__(self, *inParams): self.stdout = [] self.stderr = [] self.called = False - + def _NewPipe(self, *inParams): if len(inParams) == 1 and isinstance(inParams, (types.ListType, types.TupleType)): params = inParams[0] else: params = inParams - + self.pipe = subprocess.Popen(params, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) self.called = False - + def Stdout(self): if not self.called: self.Call() return self.stdout - + def Stderr(self): if not self.called: self.Call() return self.stderr - + def AllOutput(self): if not self.called: self.Call() return self.stdout + self.stderr - + def Communicate(self, inInput = None): if self.called: raise Exception("ShellPipe called more than once") @@ -88,19 +88,19 @@ def Communicate(self, inInput = None): stdout, stderr = self.pipe.communicate("\n".join(inInput)) else: stdout, stderr = self.pipe.communicate(inInput) - + self.stdout += stdout.splitlines() self.stderr += stderr.splitlines() break - except IOError, e: + except IOError as e: if e.errno != errno.EINTR: # Loop if EINTR raise # Other exceptions propagate to the caller - + def CallRC(self, inInput = None): # Raise exception or return the return code self.Communicate(inInput) return self.pipe.returncode - + def Call(self, inInput = None): # Raise exception on failure self.Communicate(inInput) if self.pipe.returncode != 0: @@ -111,14 +111,14 @@ def Call(self, inInput = None): # Raise exception on failure else: raise Exception("Unknown failure") return self - + def Chain(self, *inParams): if not self.called: self.Call() self._NewPipe(*inParams) self.Call() return self - + def Pipe(self, *inParams): if not self.called: self.Call() @@ -135,7 +135,7 @@ def MakeSafeParam(cls, inParam): if not re.match(r'[-A-Za-z0-9/._~:@]*$', inParam): raise Exception("Invalid characters in parameter '"+inParam+"'") return inParam - + @classmethod def WaitOnPipe(cls, inPipe): # Wait on a popen2 pipe, handling Interrupted System Call exceptions @@ -143,7 +143,7 @@ def WaitOnPipe(cls, inPipe): try: inPipe.wait() break - except IOError, e: + except IOError as e: if e.errno != errno.EINTR: # Loop if EINTR raise @@ -154,7 +154,7 @@ class TimeUtils: @staticmethod def AlarmHandler(inSigNum, inStackFrame): raise TimeException("Operation timed out") - + @classmethod def TimeoutWrapper(cls, inCallable, inTimeout): oldHandler = signal.signal(signal.SIGALRM, TimeUtils.AlarmHandler) @@ -164,11 +164,11 @@ def TimeoutWrapper(cls, inCallable, inTimeout): finally: signal.alarm(0) signal.signal(signal.SIGALRM, oldHandler) - + @classmethod def DurationString(cls, inSecs): secs = max(0, int(inSecs)) - + hours = int(secs / 3600) secs -= hours * 3600 mins = int(secs / 60) @@ -178,7 +178,7 @@ def DurationString(cls, inSecs): else: retVal = "%d:%2.2d" % (mins, secs) return retVal - + @classmethod def DateTimeToSecs(cls, inDateTime): structTime = time.strptime(inDateTime.value, '%Y%m%dT%H:%M:%SZ') @@ -186,7 +186,7 @@ def DateTimeToSecs(cls, inDateTime): if retVal <= 3601.0: # Handle the effect of daylight savings on start of epoch retVal = 0.0 return retVal - + class IPUtils: @classmethod def ValidateIP(cls, text): @@ -199,7 +199,7 @@ def ValidateIP(cls, text): largest = max(largest, i) if largest is 0: return False return True - + @classmethod def ValidateNetmask(cls, text): rc = re.match("^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$", text) @@ -229,7 +229,7 @@ def AssertValidHostname(cls, inName): if not re.match(r'[0-9A-Za-z]([-0-9A-Za-z]{0,61}[0-9A-Za-z]|)$', inName): raise Exception(Lang('Invalid hostname')) return inName - + @classmethod def AssertValidNetworkName(cls, inName): # Also allow FQDN-style names @@ -261,7 +261,7 @@ def AssertValidNFSPathName(cls, inName): for subName in splitNames[1:]: cls.AssertValidNFSDirectoryName(subName) return inName - + @classmethod def AssertValidCIFSPathName(cls, inName): splitNames = inName.split('\\') @@ -277,7 +277,7 @@ def BinarySizeString(cls, inBytes, inInFix = None): else: inFix = FirstValue(inInFix, '') bytes = int(inBytes) - + if bytes is None or bytes < 0: retVal = Lang('') elif bytes >= 1073741824: # 1GiB @@ -320,7 +320,7 @@ def DecimalSizeString(cls, inBytes, inPrefix = None): @classmethod def MemorySizeString(cls, inBytes): return cls.BinarySizeString(inBytes) - + @classmethod def SRSizeString(cls, inBytes): return cls.BinarySizeString(inBytes) @@ -328,4 +328,4 @@ def SRSizeString(cls, inBytes): @classmethod def DiskSizeString(cls, inBytes): return cls.BinarySizeString(inBytes)+' ('+cls.DecimalSizeString(inBytes)+')' - + diff --git a/install-sh b/install-sh index e9de238..eed95e3 100755 --- a/install-sh +++ b/install-sh @@ -115,7 +115,7 @@ fi if [ x"$dir_arg" != x ]; then dst=$src src="" - + if [ -d $dst ]; then instcmd=: chmodcmd="" @@ -125,7 +125,7 @@ if [ x"$dir_arg" != x ]; then else # Waiting for this to be detected by the "$instcmd $src $dsttmp" command -# might cause directories to be created, which would be especially bad +# might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if [ -f $src -o -d $src ] @@ -135,7 +135,7 @@ else echo "install: $src does not exist" exit 1 fi - + if [ x"$dst" = x ] then echo "install: no destination specified" @@ -202,17 +202,17 @@ else # If we're going to rename the final executable, determine the name now. - if [ x"$transformarg" = x ] + if [ x"$transformarg" = x ] then dstfile=`basename $dst` else - dstfile=`basename $dst $transformbasename | + dstfile=`basename $dst $transformbasename | sed $transformarg`$transformbasename fi # don't allow the sed command to completely eliminate the filename - if [ x"$dstfile" = x ] + if [ x"$dstfile" = x ] then dstfile=`basename $dst` else @@ -243,7 +243,7 @@ else # Now rename the file to the real destination. $doit $rmcmd -f $dstdir/$dstfile && - $doit $mvcmd $dsttmp $dstdir/$dstfile + $doit $mvcmd $dsttmp $dstdir/$dstfile fi && diff --git a/plugins-base/XSFeatureChangePassword.py b/plugins-base/XSFeatureChangePassword.py index df28468..021c618 100644 --- a/plugins-base/XSFeatureChangePassword.py +++ b/plugins-base/XSFeatureChangePassword.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class ChangePasswordDialogue(Dialogue): @@ -31,7 +31,7 @@ def __init__(self, inText = None, inSuccessFunc = None): self.UpdateFields() if not self.isPasswordSet: pane.InputIndexSet(None) # Reactivate cursor if this dialogue is initially covered and revealed later - + def UpdateFields(self): pane = self.Pane() pane.ResetFields() @@ -46,10 +46,10 @@ def UpdateFields(self): Lang("") : Lang("Cancel"), Lang("") : Lang("Next") }) - + if pane.InputIndex() is None: pane.InputIndexSet(0) # Activate first field for input - + def HandleKey(self, inKey): handled = True pane = self.Pane() @@ -68,30 +68,30 @@ def HandleKey(self, inKey): # Log in automatically if we're not Auth.Inst().ProcessLogin('root', inputValues.get('oldpassword', '')) successMessage += Lang(". User 'root' logged in.") - + if inputValues['newpassword1'] != inputValues['newpassword2']: raise Exception(Lang('New passwords do not match')) if len(inputValues['newpassword1']) < 6: raise Exception(Lang('New password is too short (minimum length is 6 characters)')) Auth.Inst().ChangePassword(inputValues.get('oldpassword', ''), inputValues['newpassword1']) - - except Exception, e: + + except Exception as e: if self.isPasswordSet: # Only remove the dialogue if this isn't the initial password set (which needs to succeed) Layout.Inst().PopDialogue() else: # Disable the input field so that it gets reactivated by UpdateFields when the info box is dismissed pane.InputIndexSet(None) - + Layout.Inst().PushDialogue(InfoDialogue( Lang('Password Change Failed: ')+Lang(e))) - + else: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue( successMessage)) State.Inst().PasswordChangeRequiredSet(False) - + Data.Inst().Update() elif inKey == 'KEY_TAB': @@ -108,13 +108,13 @@ class XSFeatureChangePassword: @classmethod def StatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Change Password")) - + inPane.AddWrappedTextField(Lang("Press to change the password for user 'root'. " "This will also change the password for local and remote login shells. " "If this host is in a Pool, it will change the password for the Pool.")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Change Password") }) - + @classmethod def ActivateHandler(cls, *inParams): DialogueUtils.AuthenticatedOrPasswordUnsetOnly(lambda: Layout.Inst().PushDialogue(ChangePasswordDialogue(*inParams))) @@ -123,7 +123,7 @@ def ActivateHandler(cls, *inParams): def ReadyHandler(cls, *inParams): if State.Inst().PasswordChangeRequired() or not Auth.Inst().IsPasswordSet(): cls.ActivateHandler(*inParams) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureChangeTimeout.py b/plugins-base/XSFeatureChangeTimeout.py index 912f194..e68e442 100644 --- a/plugins-base/XSFeatureChangeTimeout.py +++ b/plugins-base/XSFeatureChangeTimeout.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class ChangeTimeoutDialogue(InputDialogue): @@ -29,17 +29,17 @@ def __init__(self): def HandleCommit(self, inValues): try: timeoutMinutes = int(inValues['timeout']) - except Exception, e: + except Exception as e: raise Exception("Invalid value - please supply a numeric value") - + Auth.Inst().TimeoutSecondsSet(timeoutMinutes * 60) return Lang('Timeout Change Successful'), Lang("Timeout changed to ")+inValues['timeout']+Language.Quantity(" minute", timeoutMinutes)+'.' - + class XSFeatureChangeTimeout: @classmethod def StatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Change Auto-Logout Time")) - + timeout = State.Inst().AuthTimeoutMinutes() message = Lang("The current auto-logout time is ") + str(timeout) + " " @@ -47,15 +47,15 @@ def StatusUpdateHandler(cls, inPane): message += Lang("Users will be automatically logged out after there has been no keyboard " "activity for this time. This timeout applies to this console and to " "local shells.") - + inPane.AddWrappedTextField(message) - + inPane.AddKeyHelpField( { Lang("") : Lang("Change Timeout") }) @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(ChangeTimeoutDialogue())) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureCrashDumpSR.py b/plugins-base/XSFeatureCrashDumpSR.py index 353b0c5..c2bd3ec 100644 --- a/plugins-base/XSFeatureCrashDumpSR.py +++ b/plugins-base/XSFeatureCrashDumpSR.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class CrashDumpSRDialogue(SRDialogue): @@ -28,16 +28,16 @@ def __init__(self): 'capabilities' : 'vdi_create' } SRDialogue.__init__(self) # Must fill in self.custom before calling __init__ - + def DoAction(self, inSR): success = False - + Layout.Inst().PopDialogue() try: Data.Inst().CrashDumpSRSet(inSR) Layout.Inst().PushDialogue(InfoDialogue( Lang('Configuration Successful'), Lang("Crash Dump SR set to '"+inSR['name_label']+"'"))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration failed: ")+str(e))) Data.Inst().Update() @@ -46,23 +46,23 @@ class XSFeatureCrashDumpSR: def StatusUpdateHandler(cls, inPane): data = Data.Inst() inPane.AddTitleField(Lang("Specify Crash Dump SR")) - + inPane.AddWrappedTextField(Lang("This server can be configured to use a Storage Repository to store Crash Dumps.")) inPane.NewLine() - + if not data.host.crash_dump_sr(False): inPane.AddWrappedTextField(Lang("A Crash Dump SR is not configured on this server.")) else: inPane.AddWrappedTextField(Lang("The SR named '")+data.host.crash_dump_sr.name_label()+Lang("' is configured as the Crash Dump SR for this server.")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Specify Crash Dump SR") }) - + @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(CrashDumpSRDialogue())) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureDNS.py b/plugins-base/XSFeatureDNS.py index 132b209..97b48c0 100644 --- a/plugins-base/XSFeatureDNS.py +++ b/plugins-base/XSFeatureDNS.py @@ -106,7 +106,7 @@ def HandleKeyADD(self, inKey): nameservers.append(inputValues['name']) data.NameserversSet(nameservers) self.Commit(Lang("DNS server")+" "+inputValues['name']+" "+Lang("added")) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang(e))) elif pane.CurrentInput().HandleKey(inKey): pass # Leave handled as True @@ -140,7 +140,7 @@ def HandleInitialChoice(self, inChoice): data.NameserversSet([]) self.Commit(Lang("All server entries deleted")) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Operation Failed"), Lang(e))) data.Update() @@ -160,7 +160,7 @@ def Commit(self, inMessage): try: data.SaveToResolveConf() Layout.Inst().PushDialogue(InfoDialogue( inMessage)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Update failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeatureDRBackup.py b/plugins-base/XSFeatureDRBackup.py index b05ac49..c4ab9c7 100644 --- a/plugins-base/XSFeatureDRBackup.py +++ b/plugins-base/XSFeatureDRBackup.py @@ -51,7 +51,7 @@ def DoAction(self, inSR): Layout.Inst().PushDialogue(InfoDialogue(Lang("Backup Successful"), output)) else: raise Exception(output) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Metadata Backup failed: ")+Lang(e))) Data.Inst().Update() diff --git a/plugins-base/XSFeatureDRRestore.py b/plugins-base/XSFeatureDRRestore.py index 2cadde5..197a3ce 100644 --- a/plugins-base/XSFeatureDRRestore.py +++ b/plugins-base/XSFeatureDRRestore.py @@ -170,7 +170,7 @@ def DoAction(self, inSR): if status != 0: raise Exception("(%s,%s)" % (output,errput)) Layout.Inst().PushDialogue(DRRestoreSelection(output, vdi_uuid, sr_uuid)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Metadata Restore failed: ")+Lang(e))) Data.Inst().Update() diff --git a/plugins-base/XSFeatureDisplayNICs.py b/plugins-base/XSFeatureDisplayNICs.py index 293b850..7302159 100644 --- a/plugins-base/XSFeatureDisplayNICs.py +++ b/plugins-base/XSFeatureDisplayNICs.py @@ -15,29 +15,29 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureDisplayNICs: @classmethod def StatusUpdateHandler(cls, inPane): data = Data.Inst() - + inPane.AddTitleField(Lang("Network Interfaces")) - + for pif in data.host.PIFs([]): inPane.AddWrappedBoldTextField(pif['metrics']['device_name']) if pif['metrics']['carrier']: inPane.AddWrappedTextField(Lang("(connected)")) else: inPane.AddWrappedTextField(Lang("(not connected)")) - + inPane.AddStatusField(Lang("MAC Address", 16), pif['MAC']) inPane.AddStatusField(Lang("Device", 16), pif['device']) if int(pif['VLAN']) >= 0: inPane.AddStatusField(Lang("VLAN", 16), pif['VLAN']) inPane.NewLine() - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureEULA.py b/plugins-base/XSFeatureEULA.py index 15f5adf..bd99594 100644 --- a/plugins-base/XSFeatureEULA.py +++ b/plugins-base/XSFeatureEULA.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class EULADialogue(Dialogue): @@ -32,25 +32,25 @@ def __init__(self, inFilename): contents = ''.join(file.readlines()) finally: file.close() - except Exception, e: + except Exception as e: contents = str(e) - + self.maxLine = 0 for line in contents.split('\n'): self.maxLine = max(self.maxLine, len(line)) self.padding = ' ' * max(0, (xSize - 4 - self.maxLine) / 2) - + self.text = Lang("End User License Agreement") self.info = contents paneSizer = PaneSizerFixed(0, 1, xSize, ySize - 1) pane = self.NewPane(DialoguePane(self.parent, paneSizer)) pane.AddBox() self.UpdateFields() - + def UpdateFields(self): pane = self.Pane() pane.ResetFields() - + pane.AddWrappedCentredBoldTextField(self.text) if self.info is not None: @@ -67,7 +67,7 @@ def UpdateFields(self): }) pane.AddKeyHelpField( helpKeys ) - + def HandleKey(self, inKey): handled = True if inKey == 'KEY_ESCAPE': @@ -95,7 +95,7 @@ def ReadyHandler(cls, *inParams): if not Auth.Inst().IsPasswordSet(): for eula in Config.Inst().FirstBootEULAs(): Layout.Inst().PushDialogue(EULADialogue(eula, *inParams)) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureFullVersion.py b/plugins-base/XSFeatureFullVersion.py index f545c94..875ff06 100644 --- a/plugins-base/XSFeatureFullVersion.py +++ b/plugins-base/XSFeatureFullVersion.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureFullVersion: @@ -25,7 +25,7 @@ def StatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Software Build Information")) inPane.AddWrappedTextField(Language.Inst().Branding(data.derived.brand()) + ' ' + data.derived.fullversion()) - + @classmethod def ActivateHandler(cls): return diff --git a/plugins-base/XSFeatureHostCommon.py b/plugins-base/XSFeatureHostCommon.py index 9fecd68..f9cb828 100644 --- a/plugins-base/XSFeatureHostCommon.py +++ b/plugins-base/XSFeatureHostCommon.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class HostUtils: @@ -24,20 +24,20 @@ class HostUtils: 'enable' : Struct(name = Lang("Enable"), priority = 20), 'designate_new_master' : Struct(name = Lang("Designate as new Pool Master"), priority = 30) } - + @classmethod def AllowedOperations(cls): return cls.operationNames.keys() - + @classmethod def OtherConfigRemove(cls, inHostHandle, inName): Task.Sync(lambda x: x.xenapi.host.remove_from_other_config(inHostHandle.OpaqueRef(), inName)) - + @classmethod def OtherConfigReplace(cls, inHostHandle, inName, inValue): cls.OtherConfigRemove(inHostHandle, inName) Task.Sync(lambda x: x.xenapi.host.add_to_other_config(inHostHandle.OpaqueRef(), inName, inValue)) - + @classmethod def AsyncOperation(cls, inOperation, inHostHandle, *inParams): if inOperation == 'evacuate': @@ -62,13 +62,13 @@ def AsyncOperation(cls, inOperation, inHostHandle, *inParams): task = Task.New(lambda x: x.xenapi.Async.pool.eject(inHostHandle.OpaqueRef())) else: raise Exception("Unknown Host operation "+str(inOperation)) - + return task - + @classmethod def DoOperation(cls, inOperation, inHostHandle): task = cls.AsyncOperation(inOperation, inHostHandle) - + if task is not None: while task.IsPending(): time.sleep(0.1) diff --git a/plugins-base/XSFeatureHostEvacuate.py b/plugins-base/XSFeatureHostEvacuate.py index d654fe7..df902de 100644 --- a/plugins-base/XSFeatureHostEvacuate.py +++ b/plugins-base/XSFeatureHostEvacuate.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class HostEvacuateDialogue(Dialogue): @@ -31,7 +31,7 @@ def __init__(self): self.migrateMenu.AddChoice(name = Lang('Do Not Alter Virtual Machines'), onAction = self.HandleMigrateChoice, handle = 'NO') - + if self.hostWasEnabled: if db.local_pool.master.uuid() == db.local_host.uuid(): # We are the pool master @@ -67,7 +67,7 @@ def BuildPaneCHOOSEMASTER(self): self.hostMenu.AddChoice(name = host.name_label(), onAction = self.HandleHostChoice, handle = host) - + if self.hostMenu.NumChoices() == 0: self.hostMenu.AddChoice(name = Lang('')) @@ -86,14 +86,14 @@ def UpdateFieldsCHOOSEMASTER(self): pane.AddWrappedBoldTextField(Lang("This host is the Pool Master. To enable this host to enter Maintenance Mode, please nominate a new Master for this Pool.")) pane.NewLine() pane.AddMenuField(self.hostMenu) - + pane.AddKeyHelpField( { Lang("") : Lang("Select"), Lang("") : Lang("OK"), Lang("") : Lang("Cancel") } ) - - + + def UpdateFieldsMIGRATEBACK(self): pane = self.Pane() pane.ResetFields() - + pane.AddTitleField(Lang('The following were running on this host when it entered Maintenance Mode. Would you like reinstate them on this host?')) for i, vmRef in enumerate(self.evacuatedVMs): if i > 4: @@ -101,11 +101,11 @@ def UpdateFieldsMIGRATEBACK(self): break pane.AddWrappedTextField(HotAccessor().vm[vmRef].name_label(Lang(''))) - + pane.NewLine() pane.AddMenuField(self.migrateMenu) pane.AddKeyHelpField( { Lang("") : Lang("Select"), Lang("") : Lang("OK"), Lang("") : Lang("Cancel") } ) - + def UpdateFieldsCONFIRM(self): pane = self.Pane() pane.ResetFields() @@ -117,7 +117,7 @@ def UpdateFieldsCONFIRM(self): pane.AddWrappedTextField(Lang('1. Prevent new VMs starting on or migrating to this host')) pane.AddWrappedTextField(Lang('2. Migrate ') + str(numVMs) + Language.Quantity(' Virtual Machine', numVMs) + Lang(' to other hosts')) - + if self.newMaster is not None: pane.AddWrappedTextField(Lang('3. Designate host ') + self.newMaster.name_label(Lang('')) + Lang(' as the new Pool Master')) @@ -125,7 +125,7 @@ def UpdateFieldsCONFIRM(self): pane.AddWrappedBoldTextField(Lang('Press to exit Maintenance Mode and return this host to normal operation')) pane.AddKeyHelpField( { Lang("") : Lang("OK"), Lang("") : Lang("Cancel") } ) - + def UpdateFields(self): self.Pane().ResetPosition() getattr(self, 'UpdateFields'+self.state)() # Despatch method named 'UpdateFields'+self.state @@ -134,10 +134,10 @@ def ChangeState(self, inState): self.state = inState self.BuildPane() self.UpdateFields() - + def HandleKeyCHOOSEMASTER(self, inKey): return self.hostMenu.HandleKey(inKey) - + def HandleKeyMIGRATEBACK(self, inKey): return self.migrateMenu.HandleKey(inKey) @@ -149,7 +149,7 @@ def HandleKey(self, inKey): handled = False if hasattr(self, 'HandleKey'+self.state): handled = getattr(self, 'HandleKey'+self.state)(inKey) - + if not handled and inKey == 'KEY_ESCAPE': Layout.Inst().PopDialogue() handled = True @@ -179,10 +179,10 @@ def Commit(self): if self.newMaster is not None: Layout.Inst().TransientBanner(Lang('Designating New Pool Master...')) hostUtils.DoOperation('designate_new_master', self.newMaster.HotOpaqueRef()) - + message = Lang('Please allow several seconds for the pool to propagate information about the new Master') Layout.Inst().PushDialogue(InfoDialogue(Lang("Host Successfully Entered Maintenance Mode"), message)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Enter Maintenance Mode Failed to Complete"), Lang(e))) else: try: @@ -191,20 +191,20 @@ def Commit(self): vmUtils = Importer.GetResource('VMUtils') vmUtils.ReinstateVMs(HotAccessor().local_host_ref(), self.evacuatedVMs) Layout.Inst().PushDialogue(InfoDialogue(Lang("Host Successfully Exited Maintenance Mode"))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Exit Maintenance Mode Failed"), Lang(e))) - + class XSFeatureHostEvacuate: @classmethod def StatusUpdateHandler(cls, inPane): db = HotAccessor() inPane.AddTitleField("Maintenance Mode") if db.local_host.enabled(): - + inPane.AddWrappedTextField(Lang('Entering Maintenance Mode will migrate all Virtual Machines running on this host ' 'to other hosts in the Resource Pool. It is used before shutting down a host for maintenance.')) inPane.NewLine() - + if db.host(None) is None: pass # Info not available, so print nothing elif len(db.host([])) > 1 and db.local_pool.master.uuid() == db.local_host.uuid(): @@ -217,7 +217,7 @@ def StatusUpdateHandler(cls, inPane): else: inPane.AddWrappedTextField(Lang('This host is already in Maintenance Mode. Press to ' 'exit Maintenance Mode and return to normal operation.')) - + @classmethod def ActivateHandler(cls): db=HotAccessor() @@ -226,7 +226,7 @@ def ActivateHandler(cls): Layout.Inst().PushDialogue(InfoDialogue(Lang('This host has running Virtual Machines. Please suspend or shutdown the Virtual Machines before entering Maintenance Mode.'))) else: DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(HostEvacuateDialogue())) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureHostInfo.py b/plugins-base/XSFeatureHostInfo.py index 754c683..2bb9bf5 100644 --- a/plugins-base/XSFeatureHostInfo.py +++ b/plugins-base/XSFeatureHostInfo.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureHostInfo: @@ -24,15 +24,15 @@ def StatusUpdateHandler(cls, inPane): inPane.AddTitleField("Host Performance Information") try: localHostMetrics = HotMetrics.Inst().LocalHostMetrics() - except Exception, e: + except Exception as e: XSLogFailure('LocalHostMetrics failed', e) localHostMetrics = {} - + try: cpuUsage = localHostMetrics['cpuusage'] cpuUsage = max(0.0, min(1.0, cpuUsage)) cpuUsageStr = "%d%% of %d CPUs" % (int(cpuUsage * 100), localHostMetrics['numcpus']) - except Exception, e: + except Exception as e: cpuUsageStr = Lang('') try: @@ -43,16 +43,16 @@ def StatusUpdateHandler(cls, inPane): # Increase memory slightly to counteract metrics error totalMemory *= 1.001 memoryUsageStr = "%d%% of %s" % (int(memoryUsage * 100), SizeUtils.MemorySizeString(totalMemory)) - except Exception, e: + except Exception as e: memoryUsageStr = Lang('') inPane.AddStatusField(Lang("CPU Usage", 16), cpuUsageStr) inPane.AddStatusField(Lang("Memory Usage", 16), memoryUsageStr) - + @classmethod def ActivateHandler(cls): pass - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureInterface.py b/plugins-base/XSFeatureInterface.py index d36646b..5769f44 100644 --- a/plugins-base/XSFeatureInterface.py +++ b/plugins-base/XSFeatureInterface.py @@ -315,7 +315,7 @@ def HandleKeyPRECOMMIT(self, inKey): else: self.Complete() # Disabled management interface - except Exception, e: + except Exception as e: self.Complete(Lang("Configuration Failed: "+Lang(e))) else: @@ -337,7 +337,7 @@ def HandleKeyNAMELABEL(self, inKey): try: Data.Inst().NameLabelSet(nameLabel) self.Complete() - except Exception, e: + except Exception as e: self.Complete(Lang("Name Change Failed: ")+str(e)) elif pane.CurrentInput().HandleKey(inKey): @@ -415,7 +415,7 @@ def HandleRenewChoice(self): if ipAddress == '': ipAddress = Lang('') Layout.Inst().PushDialogue(InfoDialogue(Lang("DHCP Renewed with IP address ")+ipAddress)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Renewal Failed"), Lang(e))) def Commit(self): diff --git a/plugins-base/XSFeatureKeyboard.py b/plugins-base/XSFeatureKeyboard.py index 8b0676d..9a68f84 100644 --- a/plugins-base/XSFeatureKeyboard.py +++ b/plugins-base/XSFeatureKeyboard.py @@ -101,7 +101,7 @@ def HandleNameChoice(self, inChoice): else: try: self.Commit(inChoice) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Missing keymap: ")+Lang(e))) def HandleKeymapChoice(self, inChoice): @@ -116,7 +116,7 @@ def Commit(self, inKeymap): message = Lang('Keyboard type set to ')+data.KeymapToName(inKeymap) Layout.Inst().PushDialogue(InfoDialogue( message)) XSLog(message) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeatureLocalShell.py b/plugins-base/XSFeatureLocalShell.py index 66f5d77..ce33e7c 100644 --- a/plugins-base/XSFeatureLocalShell.py +++ b/plugins-base/XSFeatureLocalShell.py @@ -15,18 +15,18 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureLocalShell: @classmethod def StatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Local Command Shell")) - + inPane.AddWrappedTextField(Lang( "Press to start a local command shell on this server. " "This shell will have root privileges.")) - + @classmethod def StartLocalShell(self): user = os.environ.get('USER', 'root') @@ -34,11 +34,11 @@ def StartLocalShell(self): Lang("Type 'exit' to return to the management console.\r")) Layout.Inst().SubshellCommandSet("( export HOME=/root; export TMOUT="+str(State.Inst().AuthTimeoutSeconds())+" && cat /etc/motd && /bin/bash --login )") XSLog('Local shell') - + @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: cls.StartLocalShell()) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureLogInOut.py b/plugins-base/XSFeatureLogInOut.py index 4a4b8c4..a53f9cf 100644 --- a/plugins-base/XSFeatureLogInOut.py +++ b/plugins-base/XSFeatureLogInOut.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureLogInOut: diff --git a/plugins-base/XSFeatureNTP.py b/plugins-base/XSFeatureNTP.py index ad58811..b855411 100644 --- a/plugins-base/XSFeatureNTP.py +++ b/plugins-base/XSFeatureNTP.py @@ -111,7 +111,7 @@ def HandleKeyADD(self, inKey): servers.append(inputValues['name']) data.NTPServersSet(servers) self.Commit(Lang("NTP server")+" "+inputValues['name']+" "+Lang("added")) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang(e))) elif pane.CurrentInput().HandleKey(inKey): pass # Leave handled as True @@ -160,7 +160,7 @@ def HandleInitialChoice(self, inChoice): message = data.NTPStatus()+Lang("\n\n(Initial synchronization may take several minutes)") Layout.Inst().PushDialogue(InfoDialogue( Lang("NTP Status"), message)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Operation Failed"), Lang(e))) data.Update() @@ -183,7 +183,7 @@ def Commit(self, inMessage): Layout.Inst().TransientBanner(Lang("Restarting NTP daemon with new configuration...")) data.RestartService('chronyd') Layout.Inst().PushDialogue(InfoDialogue( inMessage)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Update failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeaturePoolEject.py b/plugins-base/XSFeaturePoolEject.py index 573309b..692ca57 100644 --- a/plugins-base/XSFeaturePoolEject.py +++ b/plugins-base/XSFeaturePoolEject.py @@ -96,7 +96,7 @@ def Commit(self): hostUtils.DoOperation('eject', HotAccessor().local_host_ref()) Layout.Inst().ExitBannerSet(Lang('Removal Successful. This Host Will Now Reboot...')) Layout.Inst().ExitCommandSet('/bin/sleep 120') - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Failed to Remove Host from Pool"), Lang(e))) class XSFeaturePoolEject: diff --git a/plugins-base/XSFeaturePoolJoin.py b/plugins-base/XSFeaturePoolJoin.py index e1abbf2..7fa1ca9 100644 --- a/plugins-base/XSFeaturePoolJoin.py +++ b/plugins-base/XSFeaturePoolJoin.py @@ -102,7 +102,7 @@ def HandleKeyGATHER(self, inKey): try: IPUtils.AssertValidNetworkName(self.params['hostname']) self.ChangeState('CONFIRM') - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang(e))) @@ -149,7 +149,7 @@ def Commit(self): self.params['hostname'], self.params['username'], self.params['password']) Layout.Inst().PushDialogue(ProgressDialogue(task, Lang("Joining Pool with Master '")+self.params['hostname']+"'")) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Host Failed to Join the Pool"), Lang(e))) class XSFeaturePoolJoin: diff --git a/plugins-base/XSFeaturePoolNewMaster.py b/plugins-base/XSFeaturePoolNewMaster.py index 6685970..4d2ba3f 100644 --- a/plugins-base/XSFeaturePoolNewMaster.py +++ b/plugins-base/XSFeaturePoolNewMaster.py @@ -102,7 +102,7 @@ def Commit(self): Layout.Inst().TransientBanner(Lang('Designating New Pool Master...')) hostUtils.DoOperation('designate_new_master', self.newMaster.HotOpaqueRef()) Layout.Inst().PushDialogue(InfoDialogue(Lang("The Pool Master Has Been Changed"), Lang('Please allow several seconds for the change to propagate throughout the Pool.'))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Failed to Designate New Pool Master"), Lang(e))) class XSFeaturePoolNewMaster: diff --git a/plugins-base/XSFeatureQuit.py b/plugins-base/XSFeatureQuit.py index 33c9988..bb02d1f 100644 --- a/plugins-base/XSFeatureQuit.py +++ b/plugins-base/XSFeatureQuit.py @@ -15,14 +15,14 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureQuit: @classmethod def StatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Quit")) - + inPane.AddWrappedTextField(Lang( "Press to quit this console.")) @@ -30,7 +30,7 @@ def StatusUpdateHandler(cls, inPane): def ActivateHandler(cls): Layout.Inst().ExitBannerSet(Lang("Quitting...")) Layout.Inst().ExitCommandSet('') # Just exit - + def Register(self): # When started from inittab, mingetty adds -f root to the command, so use this to suppress the Quit choice if not '-f' in sys.argv: diff --git a/plugins-base/XSFeatureReboot.py b/plugins-base/XSFeatureReboot.py index deaff3f..8bcb130 100644 --- a/plugins-base/XSFeatureReboot.py +++ b/plugins-base/XSFeatureReboot.py @@ -15,17 +15,17 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureReboot: @classmethod def StatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Reboot Server")) - + inPane.AddWrappedTextField(Lang( "Press to reboot this server.")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Reboot Server") } ) @@ -38,13 +38,13 @@ def RebootReplyHandler(cls, inYesNo): Data.Inst().LocalHostDisable() except XenAPI.Failure: raise - except Exception, e: + except Exception as e: # Ignore non-xapi failure - we want HA to veto the reboot but not other problems XSLogFailure('Host disable before reboot failed', e) Layout.Inst().ExitBannerSet(Lang("Rebooting...")) Layout.Inst().ExitCommandSet('/sbin/shutdown -r now') XSLog('Initiating reboot') - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Reboot Failed"), Lang(e))) @classmethod @@ -58,7 +58,7 @@ def ReadyHandler(cls, inMessage = None): if State.Inst().RebootMessage() is not None and not ( State.Inst().PasswordChangeRequired() or not Auth.Inst().IsPasswordSet()): cls.ActivateHandler(inMessage) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureRemoteShell.py b/plugins-base/XSFeatureRemoteShell.py index e666c0f..1bdf83a 100644 --- a/plugins-base/XSFeatureRemoteShell.py +++ b/plugins-base/XSFeatureRemoteShell.py @@ -70,7 +70,7 @@ def HandleChoice(self, inChoice): Layout.Inst().PushDialogue(InfoDialogue(message)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeatureSRCommon.py b/plugins-base/XSFeatureSRCommon.py index 5782da6..da3b024 100644 --- a/plugins-base/XSFeatureSRCommon.py +++ b/plugins-base/XSFeatureSRCommon.py @@ -49,7 +49,7 @@ def AsyncOperation(cls, inOperation, inSRHandle, inParam0 = None): for pbd in sr.PBDs: try: Task.Sync(lambda x: x.xenapi.PBD.destroy(pbd.HotOpaqueRef().OpaqueRef())) - except Exception, e: + except Exception as e: storedError = e if storedError is not None: @@ -69,7 +69,7 @@ def AsyncOperation(cls, inOperation, inSRHandle, inParam0 = None): for pbd in sr.PBDs: try: Task.Sync(lambda x: x.xenapi.PBD.plug(pbd.HotOpaqueRef().OpaqueRef())) - except Exception, e: + except Exception as e: storedError = e if storedError is not None: @@ -88,7 +88,7 @@ def AsyncOperation(cls, inOperation, inSRHandle, inParam0 = None): for pbd in unplugged: try: Task.Sync(lambda x: x.xenapi.PBD.plug(pbd.HotOpaqueRef().OpaqueRef())) - except Exception, e: + except Exception as e: XSLogFailure('SR undo failed', e) raise # Reraise the original exception @@ -289,7 +289,7 @@ def Commit(self): task = SRUtils.DoOperation(self.operation, self.srHandle, *self.opParams) Layout.Inst().PushDialogue(InfoDialogue(messagePrefix + Lang("successful"), )) - except Exception, e: + except Exception as e: self.ChangeState('INITIAL') Layout.Inst().PushDialogue(InfoDialogue(messagePrefix + Lang("failed"), Lang(e))) diff --git a/plugins-base/XSFeatureSRCreate.py b/plugins-base/XSFeatureSRCreate.py index 1ef7383..5326763 100644 --- a/plugins-base/XSFeatureSRCreate.py +++ b/plugins-base/XSFeatureSRCreate.py @@ -545,7 +545,7 @@ def HandleKeyGATHER_NFS(self, inKey): Layout.Inst().TransientBanner(Lang('Probing for Storage Repositories...')) self.HandleCommonData(inputValues) self.HandleNFSData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -563,7 +563,7 @@ def HandleKeyGATHER_CIFS_ISO(self, inKey): inputValues = pane.GetFieldValues() self.HandleCommonData(inputValues) self.HandleCIFSData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -578,7 +578,7 @@ def HandleKeyGATHER_ISCSI(self, inKey): inputValues = pane.GetFieldValues() self.HandleCommonData(inputValues) self.HandleISCSIData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -594,7 +594,7 @@ def HandleKeyGATHER_NETAPP(self, inKey): Layout.Inst().TransientBanner(Lang('Probing NetApp...')) self.HandleCommonData(inputValues) self.HandleNetAppData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -609,7 +609,7 @@ def HandleKeyGATHER_HBA(self, inKey): # No input fields for HBA Layout.Inst().TransientBanner(Lang('Probing for HBA Devices...')) self.HandleHBAData({}) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: handled = False @@ -631,7 +631,7 @@ def HandleKeyPROBE_HBA_NAME(self, inKey): self.ChangeState('PROBE_HBA_SR') else: self.ChangeState('CONFIRM') - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -647,7 +647,7 @@ def HandleKeyGATHER_EQUAL(self, inKey): Layout.Inst().TransientBanner(Lang('Probing Dell EqualLogic Server...')) self.HandleCommonData(inputValues) self.HandleEqualData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -667,7 +667,7 @@ def HandleKeyPROBE_ISCSI_IQN(self, inKey): message += Lang("IQN", 12)+iqn.name Layout.Inst().PushDialogue(InfoDialogue( Lang("IQN Information"), message)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Failed: ")+Lang(e))) handled = True else: @@ -693,7 +693,7 @@ def HandleKeyPROBE_NETAPP_FLEXVOLS(self, inKey): raise Exception(Lang('The number of FlexVols must be between 1 and 32')) self.srParams['numflexvols'] = numFlexVols self.ChangeState('PROBE_NETAPP_PROVISIONING') - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Invalid Value"), Lang(e))) else: @@ -724,7 +724,7 @@ def HandleKeyCONFIRM(self, inKey): try: # Despatch method named 'Commit'+self.srCreateType+'_'+self.variant getattr(self, 'Commit'+self.createType+'_'+self.variant)() - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) handled = True @@ -816,7 +816,7 @@ def HandleISCSIData(self, inParams): self.srTypes['ISCSI'] # type ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'SR_BACKEND_FAILURE_96': raise # Parse XML for UUID values @@ -833,7 +833,7 @@ def HandleISCSIData(self, inParams): name=iqn, iqn=iqn)) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_ISCSI_IQN') @@ -876,7 +876,7 @@ def HandleNetAppData(self, inParams): True # shared ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'SR_BACKEND_FAILURE_123': raise # Parse XML for UUID values @@ -897,7 +897,7 @@ def HandleNetAppData(self, inParams): raidType = raidType, asisdedup = asisdedup)) # NetApp's Advanced Single Instance Storage Deduplication, 'true' if supported - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_NETAPP_AGGREGATE') elif self.variant=='ATTACH': @@ -922,7 +922,7 @@ def HandleNetAppData(self, inParams): aggregate = aggregate )) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_NETAPP_SR') @@ -940,7 +940,7 @@ def HandleHBAData(self, inParams): self.srTypes['HBA'], # type ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'SR_BACKEND_FAILURE_107': raise # Parse XML for UUID values @@ -954,7 +954,7 @@ def HandleHBAData(self, inParams): setattr(deviceInfo, name.lower(), str(device.getElementsByTagName(name)[0].firstChild.nodeValue.strip())) self.deviceChoices.append(deviceInfo) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_HBA_DEVICE') @@ -996,7 +996,7 @@ def HandleEqualData(self, inParams): True # shared ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'SR_BACKEND_FAILURE_163': raise # Parse XML for UUID values @@ -1010,7 +1010,7 @@ def HandleEqualData(self, inParams): setattr(storageInfo, name.lower(), storagePool.getElementsByTagName(name)[0].firstChild.nodeValue.strip()) self.storagePoolChoices.append(storageInfo) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_EQUAL_STORAGEPOOL') elif self.variant=='ATTACH': @@ -1033,7 +1033,7 @@ def HandleEqualData(self, inParams): size = size )) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_EQUAL_SR') @@ -1068,7 +1068,7 @@ def HandleIQNChoice(self, inChoice): self.srTypes['ISCSI'] # type ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: # Parse XML for UUID values if e.details[0] != 'SR_BACKEND_FAILURE_107': raise @@ -1082,7 +1082,7 @@ def HandleIQNChoice(self, inChoice): self.lunChoices.append(record) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_ISCSI_LUN') @@ -1197,7 +1197,7 @@ def CommitCreate(self, inType, inDeviceConfig, inOtherConfig = None): Data.Inst().SetPoolSRIfRequired(srRef) Layout.Inst().PushDialogue(InfoDialogue(Lang("Storage Repository Creation Successful"))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Storage Repository Creation Failed"), Lang(e))) def CommitAttach(self, inType, inDeviceConfig, inOtherConfig, inContentType): @@ -1252,7 +1252,7 @@ def CommitAttach(self, inType, inDeviceConfig, inOtherConfig, inContentType): Data.Inst().SetPoolSRIfRequired(srRef) Layout.Inst().PushDialogue(InfoDialogue(Lang("Storage Repository Attachment Successful"))) - except Exception, e: + except Exception as e: message = Lang(e) # Attempt to undo the work we've done, because the SR is incomplete try: @@ -1263,7 +1263,7 @@ def CommitAttach(self, inType, inDeviceConfig, inOtherConfig, inContentType): Task.Sync(lambda x: x.xenapi.SR.forget(srRef)) - except Exception, e: + except Exception as e: message += Lang('. Attempts to rollback also failed: ')+Lang(e) Layout.Inst().PushDialogue(InfoDialogue(Lang("Storage Repository Attachment Failed"), message)) diff --git a/plugins-base/XSFeatureSRInfo.py b/plugins-base/XSFeatureSRInfo.py index 8ee9825..7b75c6d 100644 --- a/plugins-base/XSFeatureSRInfo.py +++ b/plugins-base/XSFeatureSRInfo.py @@ -15,15 +15,15 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureSRInfo: - + @classmethod def StatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Storage Repository Information")) - + inPane.AddWrappedTextField(Lang( "Press to display detailed information about Storage Repositories, and to Detach, Destroy or Forget Storage Repositories.")) @@ -51,7 +51,7 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): inPane.AddStatusField(Lang('Type', 10), srUtils.TypeName(sr.type())) inPane.AddStatusField(Lang('Shared', 10), sr.shared() and Lang('Yes') or Lang('No')) - + attached = False for pbd in sr.PBDs: if pbd.host.uuid() == db.local_host.uuid(): @@ -72,7 +72,7 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): inPane.AddStatusField(Lang('Port', 10), devConfig.port()) if devConfig.targetIQN() is not None: inPane.AddStatusField(Lang('Target IQN', 10), devConfig.targetIQN()) - + flags = srUtils.SRFlags(sr) if 'default' in flags and 'suspend' in flags and 'crashdump' in flags: @@ -88,32 +88,32 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): inPane.AddWarningField(Lang('This Storage Repository is detached and not usable by this host.')) elif not attached: inPane.AddWarningField(Lang('This Storage Repository is unplugged and not usable by this host.')) - + if sr.name_description('') != '': inPane.AddWrappedBoldTextField(Lang('Description')) inPane.AddWrappedTextField(sr.name_description('')) inPane.AddKeyHelpField( { Lang("") : Lang("Control This Storage Repository") } ) - + @classmethod def ActivateHandler(cls): Layout.Inst().TopDialogue().ChangeMenu('MENU_SRINFO') - + @classmethod def InfoActivateHandler(cls, inHandle): dialogue = Importer.GetResource('SRControlDialogue') DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(dialogue(inHandle))) - + @classmethod def MenuRegenerator(cls, inList, inMenu): retVal = copy.copy(inMenu) retVal.RemoveChoices() # inList is a list of HotOpaqueRef objects srList = [ sr for sr in HotAccessor().visible_sr if sr.other_config({}).get('xensource_internal', '') != 'true' ] - + # Sort list by SR shared flag then name srList.sort(lambda x, y: cmp(y.shared(False), x.shared(False)) or cmp (x.name_label(''), y.name_label())) - + srUtils = Importer.GetResource('SRUtils') for sr in srList: name = srUtils.AnnotatedName(sr) @@ -121,14 +121,14 @@ def MenuRegenerator(cls, inList, inMenu): onAction = cls.InfoActivateHandler, statusUpdateHandler = cls.InfoStatusUpdateHandler, handle = sr.HotOpaqueRef()) - + if retVal.NumChoices() == 0: retVal.AddChoice(name = Lang(''), statusUpdateHandler = cls.NoSRStatusUpdateHandler) - + return retVal - + def Register(self): Importer.RegisterMenuEntry( self, diff --git a/plugins-base/XSFeatureSaveBugReport.py b/plugins-base/XSFeatureSaveBugReport.py index e68d194..ef2f4b7 100644 --- a/plugins-base/XSFeatureSaveBugReport.py +++ b/plugins-base/XSFeatureSaveBugReport.py @@ -60,14 +60,14 @@ def DoAction(self): Layout.Inst().PushDialogue(InfoDialogue( Lang("Saved Bug Report"))) - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue( Lang("Save Failed"), Lang(e))) finally: try: self.PreExitActions() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Save Failed"), Lang(e))) class XSFeatureSaveBugReport: diff --git a/plugins-base/XSFeatureShutdown.py b/plugins-base/XSFeatureShutdown.py index bc1185a..212bf93 100644 --- a/plugins-base/XSFeatureShutdown.py +++ b/plugins-base/XSFeatureShutdown.py @@ -15,17 +15,17 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureShutdown: @classmethod def StatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Shutdown Server")) - + inPane.AddWrappedTextField(Lang( "Press to shutdown this server.")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Shutdown Server") } ) @@ -38,13 +38,13 @@ def ShutdownReplyHandler(cls, inYesNo): Data.Inst().LocalHostDisable() except XenAPI.Failure: raise - except Exception, e: + except Exception as e: # Ignore non-xapi failure - we want HA to veto the shutdown but not other problems XSLogFailure('Host disable before shutdown failed', e) Layout.Inst().ExitBannerSet(Lang("Shutting Down...")) Layout.Inst().ExitCommandSet('/sbin/shutdown -h now') XSLog('Initiated shutdown') - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Shutdown Failed"), Lang(e))) @classmethod @@ -54,7 +54,7 @@ def ActivateHandler(cls, *inParams): else: banner = Lang("Do you want to shutdown this server?") DialogueUtils.AuthenticatedOrPasswordUnsetOnly(lambda: Layout.Inst().PushDialogue(QuestionDialogue(banner, lambda x: cls.ShutdownReplyHandler(x)))) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureStatus.py b/plugins-base/XSFeatureStatus.py index 04cccb2..5a6a2b3 100644 --- a/plugins-base/XSFeatureStatus.py +++ b/plugins-base/XSFeatureStatus.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * def is_master(): @@ -38,7 +38,7 @@ def StatusUpdateHandler(cls, inPane): data.derived.coreversion()) inPane.NewLine() inPane.AddTitleField(Lang("Management Network Parameters")) - + if len(data.derived.managementpifs([])) == 0: db = HotAccessor() try: @@ -61,10 +61,10 @@ def StatusUpdateHandler(cls, inPane): inPane.AddStatusField(Lang('IP address', 16), data.ManagementIP('')) inPane.AddStatusField(Lang('Netmask', 16), data.ManagementNetmask('')) inPane.AddStatusField(Lang('Gateway', 16), data.ManagementGateway('')) - + inPane.NewLine() inPane.AddWrappedTextField(Lang('Press to display the SSL key fingerprints for this host')) - + inPane.AddKeyHelpField( { Lang("") : Lang("Refresh"), Lang("") : Lang("Fingerprints")}) @classmethod diff --git a/plugins-base/XSFeatureSuspendSR.py b/plugins-base/XSFeatureSuspendSR.py index 99c6d95..b10178f 100644 --- a/plugins-base/XSFeatureSuspendSR.py +++ b/plugins-base/XSFeatureSuspendSR.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class SuspendSRDialogue(SRDialogue): @@ -28,16 +28,16 @@ def __init__(self): 'capabilities' : 'vdi_create' } SRDialogue.__init__(self) # Must fill in self.custom before calling __init__ - + def DoAction(self, inSR): success = False - + Layout.Inst().PopDialogue() try: Data.Inst().SuspendSRSet(inSR) Layout.Inst().PushDialogue(InfoDialogue( Lang('Configuration Successful'), Lang("Suspend SR set to '"+inSR['name_label']+"'"))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration failed: ")+str(e))) Data.Inst().Update() @@ -47,23 +47,23 @@ class XSFeatureSuspendSR: def StatusUpdateHandler(cls, inPane): data = Data.Inst() inPane.AddTitleField(Lang("Specify Suspend SR")) - + inPane.AddWrappedTextField(Lang("This server can be configured to use a Storage Repository for suspend images.")) inPane.NewLine() - + if not data.host.suspend_image_sr(False): inPane.AddWrappedTextField(Lang("A Suspend Image SR is not configured on this server.")) else: inPane.AddWrappedTextField(Lang("The SR named '")+data.host.suspend_image_sr.name_label()+Lang("' is configured as the Suspend Image SR for this server.")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Specify Suspend SR") }) - + @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(SuspendSRDialogue())) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureTestNetwork.py b/plugins-base/XSFeatureTestNetwork.py index 5d25e15..2b67505 100644 --- a/plugins-base/XSFeatureTestNetwork.py +++ b/plugins-base/XSFeatureTestNetwork.py @@ -126,7 +126,7 @@ def DoPing(self, inAddress): try: Layout.Inst().TransientBanner(Lang('Pinging...')) (success, output) = Data.Inst().Ping(inAddress) - except Exception, e: + except Exception as e: output = Lang(e) if success: diff --git a/plugins-base/XSFeatureTimezone.py b/plugins-base/XSFeatureTimezone.py index b5e0522..098aaaa 100644 --- a/plugins-base/XSFeatureTimezone.py +++ b/plugins-base/XSFeatureTimezone.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class TimezoneDialogue(Dialogue): @@ -23,19 +23,19 @@ def __init__(self): Dialogue.__init__(self) data=Data.Inst() - + choiceDefs = [] - + continents = data.timezones.continents({}) keys = sorted(continents.keys()) - + for key in keys: choiceDefs.append(ChoiceDef(key, lambda: self.HandleContinentChoice(continents[keys[self.continentMenu.ChoiceIndex()]]) )) - + self.continentMenu = Menu(self, None, Lang("Select Continent"), choiceDefs) - + self.ChangeState('INITIAL') - + def BuildPane(self): if self.state == 'CITY': self.cityList = [] @@ -47,58 +47,58 @@ def BuildPane(self): if cityExp.match(city): self.cityList.append(city) choiceDefs.append(ChoiceDef(city, lambda: self.HandleCityChoice(self.cityMenu.ChoiceIndex()))) - + if len(choiceDefs) == 0: choiceDefs.append(Lang(''), None) - + self.cityMenu = Menu(self, None, Lang("Select City"), choiceDefs) - + pane = self.NewPane(DialoguePane(self.parent)) pane.TitleSet(Lang("Set Timezone")) pane.AddBox() self.UpdateFields() - + def UpdateFieldsINITIAL(self): pane = self.Pane() pane.ResetFields() - + pane.AddTitleField(Lang("Please Select Your Region")) pane.AddMenuField(self.continentMenu, 11) # There are 11 'continents' so make this menu 11 high pane.AddKeyHelpField( { Lang("") : Lang("OK"), Lang("") : Lang("Cancel") } ) - + def UpdateFieldsCITY(self): pane = self.Pane() pane.ResetFields() - + pane.AddTitleField(Lang("Please Choose a City Within Your Timezone")) pane.AddMenuField(self.cityMenu) pane.AddKeyHelpField( { Lang("") : Lang("OK") , Lang("") : Lang("Cancel") } ) - + def UpdateFields(self): self.Pane().ResetPosition() getattr(self, 'UpdateFields'+self.state)() # Despatch method named 'UpdateFields'+self.state - + def ChangeState(self, inState): self.state = inState self.BuildPane() - + def HandleKeyINITIAL(self, inKey): return self.continentMenu.HandleKey(inKey) - + def HandleKeyCITY(self, inKey): return self.cityMenu.HandleKey(inKey) - + def HandleKey(self, inKey): handled = False if hasattr(self, 'HandleKey'+self.state): handled = getattr(self, 'HandleKey'+self.state)(inKey) - + if not handled and inKey == 'KEY_ESCAPE': Layout.Inst().PopDialogue() handled = True return handled - + def HandleContinentChoice(self, inChoice): self.continentChoice = inChoice self.ChangeState('CITY') @@ -112,7 +112,7 @@ def HandleCityChoice(self, inChoice): message = Lang('The timezone has been set to ')+city +".\n\nLocal time is now "+data.CurrentTimeString() Layout.Inst().PushDialogue(InfoDialogue( Lang('Timezone Set'), message)) XSLog(message) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration failed: ")+Lang(e))) data.Update() @@ -123,7 +123,7 @@ class XSFeatureTimezone: def StatusUpdateHandler(cls, inPane): data = Data.Inst() inPane.AddTitleField(Lang("Set Timezone")) - + inPane.AddWrappedTextField(Lang("Use this option to set the timezone for this server.")) inPane.NewLine() if data.timezones.current('') != '': @@ -131,15 +131,15 @@ def StatusUpdateHandler(cls, inPane): inPane.NewLine() inPane.AddWrappedTextField(data.timezones.current(Lang(''))) inPane.NewLine() - + inPane.AddKeyHelpField( { Lang("") : Lang("Set Timezone") }) - + @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(TimezoneDialogue())) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureVMCommon.py b/plugins-base/XSFeatureVMCommon.py index 39fe497..3d333d1 100644 --- a/plugins-base/XSFeatureVMCommon.py +++ b/plugins-base/XSFeatureVMCommon.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class VMUtils: @@ -35,7 +35,7 @@ class VMUtils: @classmethod def AllowedOperations(cls): return cls.operationNames.keys() - + @classmethod def AsyncOperation(cls, inOperation, inVMHandle, inParam0 = None): if inOperation == 'hard_reboot': @@ -65,13 +65,13 @@ def AsyncOperation(cls, inOperation, inVMHandle, inParam0 = None): task = Task.New(lambda x: x.xenapi.Async.VM.suspend(inVMHandle.OpaqueRef())) else: raise Exception("Unknown VM operation "+str(inOperation)) - + return task - + @classmethod def DoOperation(cls, inOperation, inVMHandle, inParam0 = None): task = cls.AsyncOperation(inOperation, inVMHandle, inParam0) - + if task is not None: while task.IsPending(): time.sleep(0.1) @@ -126,9 +126,9 @@ def __init__(self, inVMHandle): allowedOps = vm.allowed_operations() choiceList = [ name for name in allowedOps if name in VMUtils.AllowedOperations() ] - + choiceList.sort(lambda x, y: cmp(VMUtils.OperationPriority(x), VMUtils.OperationPriority(y))) - + self.controlMenu = Menu() for choice in choiceList: self.controlMenu.AddChoice(name = VMUtils.OperationName(choice), @@ -136,14 +136,14 @@ def __init__(self, inVMHandle): handle = choice) if self.controlMenu.NumChoices() == 0: self.controlMenu.AddChoice(name = Lang('')) - + self.ChangeState('INITIAL') - + def BuildPane(self): pane = self.NewPane(DialoguePane(self.parent)) pane.TitleSet(Lang("Virtual Machine Control")) pane.AddBox() - + if self.state == 'MIGRATE': hosts = VMUtils.GetPossibleHostAccessors(self.vmHandle) hosts.sort(lambda x, y: cmp(x.name_label(), y.name_label())) @@ -169,7 +169,7 @@ def UpdateFieldsINITIAL(self): pane.AddTitleField(vmName+Lang(" is ")+Lang(vm.power_state(''))+'.') pane.AddMenuField(self.controlMenu) pane.AddKeyHelpField( { Lang("") : Lang("OK"), Lang("") : Lang("Cancel") } ) - + def UpdateFieldsMIGRATE(self): pane = self.Pane() pane.ResetFields() @@ -177,7 +177,7 @@ def UpdateFieldsMIGRATE(self): pane.AddTitleField(Lang('Please choose a new host for this Virtual Machine')) pane.AddMenuField(self.hostMenu) pane.AddKeyHelpField( { Lang("") : Lang("Select"), Lang("") : Lang("OK"), Lang("") : Lang("Cancel") } ) - + def UpdateFieldsCONFIRM(self): pane = self.Pane() pane.ResetFields() @@ -192,9 +192,9 @@ def UpdateFieldsCONFIRM(self): pane.AddStatusField(Lang("Virtual Machine", 20), vmName) for values in self.extraInfo: pane.AddStatusField(values[0], values[1]) - + pane.AddKeyHelpField( { Lang("") : Lang("OK"), Lang("") : Lang("Cancel") } ) - + def UpdateFields(self): self.Pane().ResetPosition() getattr(self, 'UpdateFields'+self.state)() # Despatch method named 'UpdateFields'+self.state @@ -203,7 +203,7 @@ def ChangeState(self, inState): self.state = inState self.BuildPane() self.UpdateFields() - + def HandleKeyINITIAL(self, inKey): return self.controlMenu.HandleKey(inKey) @@ -221,26 +221,26 @@ def HandleKey(self, inKey): handled = False if hasattr(self, 'HandleKey'+self.state): handled = getattr(self, 'HandleKey'+self.state)(inKey) - + if not handled and inKey == 'KEY_ESCAPE': Layout.Inst().PopDialogue() handled = True return handled - + def HandleControlChoice(self, inChoice): self.operation = inChoice if inChoice == 'pool_migrate': self.ChangeState('MIGRATE') else: self.ChangeState('CONFIRM') - + def HandleHostChoice(self, inChoice): self.opParams.append(inChoice) hostName = HotAccessor().vm[inChoice].name_label(Lang('')) self.extraInfo.append( (Lang('New Host', 20), hostName) ) # Append a tuple (so double brackets) self.ChangeState('CONFIRM') - + def Commit(self): Layout.Inst().PopDialogue() @@ -250,8 +250,8 @@ def Commit(self): try: task = VMUtils.AsyncOperation(self.operation, self.vmHandle, *self.opParams) Layout.Inst().PushDialogue(ProgressDialogue(task, messagePrefix)) - - except Exception, e: + + except Exception as e: self.ChangeState('INITIAL') Layout.Inst().PushDialogue(InfoDialogue(messagePrefix + Lang("Failed"), Lang(e))) diff --git a/plugins-base/XSFeatureVMInfo.py b/plugins-base/XSFeatureVMInfo.py index 8305d69..ae049b7 100644 --- a/plugins-base/XSFeatureVMInfo.py +++ b/plugins-base/XSFeatureVMInfo.py @@ -15,21 +15,21 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureVMInfo: @classmethod def ResidentStatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Virtual Machine Information")) - + inPane.AddWrappedTextField(Lang( "Press to display detailed information about Virtual Machines running on this host.")) @classmethod def AllStatusUpdateHandler(cls, inPane): inPane.AddTitleField(Lang("Virtual Machine Information")) - + inPane.AddWrappedTextField(Lang( "Press to display detailed information about all Virtual Machines in the Pool.")) @@ -47,10 +47,10 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): else: try: vmMetrics = HotMetrics.Inst().VMMetrics(vm.uuid()) - except Exception, e: + except Exception as e: XSLogFailure('VMMetrics failed', e) vmMetrics = {} - + powerState = vm.power_state(Lang('')) isRunning = powerState.lower().startswith('running') inPane.AddWrappedTextField(vm.name_label()) @@ -66,9 +66,9 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): else: cpuUsageStr = Lang('') - except Exception, e: + except Exception as e: cpuUsageStr = Lang('') - + inPane.AddStatusField(Lang("CPU Usage", 16), cpuUsageStr) if isRunning: @@ -80,24 +80,24 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): memoryUsage = usedMemory / totalMemory memoryUsage = max(0, min(memoryUsage, 1)) memoryUsageStr = "%d%% (%s)" % (int(memoryUsage * 100), SizeUtils.MemorySizeString(usedMemory)) - except Exception, e: + except Exception as e: memoryUsageStr = Lang('') - + inPane.AddStatusField(Lang("Memory Usage", 16), memoryUsageStr) - + try: networks = vm.guest_metrics.networks({}) for key in sorted(networks.keys()): inPane.AddStatusField((Lang('Network ')+key).ljust(16, ' '), networks[key]) - except Exception, e: + except Exception as e: inPane.AddStatusField(Lang('Network Info', 16), Lang('')) - + inPane.AddKeyHelpField( { Lang("") : Lang("Control This Virtual Machine") } ) - + @classmethod def ResidentActivateHandler(cls): Layout.Inst().TopDialogue().ChangeMenu('MENU_RESIDENTVM') - + @classmethod def AllActivateHandler(cls): vmIDs = Task.Sync(lambda x: x.xenapi.VM.get_all_records_where('field "is_a_template" = "false" and field "is_control_domain" = "false"')) @@ -105,12 +105,12 @@ def AllActivateHandler(cls): Layout.Inst().PushDialogue(InfoDialogue(Lang('This feature is unavailable in Pools with more than 100 Virtual Machines'))) else: Layout.Inst().TopDialogue().ChangeMenu('MENU_ALLVM') - + @classmethod def InfoActivateHandler(cls, inHandle): dialogue = Importer.GetResource('VMControlDialogue') DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(dialogue(inHandle))) - + @classmethod def MenuRegenerator(cls, inList, inMenu): retVal = copy.copy(inMenu) @@ -119,7 +119,7 @@ def MenuRegenerator(cls, inList, inMenu): vmList = [ HotAccessor().vm[x] for x in inList ] # Sort list by VM name vmList.sort(lambda x,y: cmp(x.name_label(''), y.name_label(''))) - + for vm in vmList: nameLabel = vm.name_label(Lang('')) if not vm.is_control_domain(True) and not vm.is_a_template(True): @@ -127,22 +127,22 @@ def MenuRegenerator(cls, inList, inMenu): onAction = cls.InfoActivateHandler, statusUpdateHandler = cls.InfoStatusUpdateHandler, handle = vm.HotOpaqueRef()) - + if retVal.NumChoices() == 0: retVal.AddChoice(name = Lang(''), statusUpdateHandler = cls.NoVMStatusUpdateHandler) - + return retVal - + @classmethod def ResidentMenuRegenerator(cls, inName, inMenu): return cls.MenuRegenerator(HotAccessor().local_host.resident_VMs([]), inMenu) - + @classmethod def AllMenuRegenerator(cls, inName, inMenu): # Fetching all guest_vm is an expensive operation (implies xenapi.vm.get_all_records) return cls.MenuRegenerator(HotAccessor().guest_vm({}).keys(), inMenu) - + def Register(self): Importer.RegisterMenuEntry( self, diff --git a/plugins-base/XSFeatureValidate.py b/plugins-base/XSFeatureValidate.py index 31c5b8d..e6fdc36 100644 --- a/plugins-base/XSFeatureValidate.py +++ b/plugins-base/XSFeatureValidate.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class ValidateDialogue(Dialogue): @@ -25,22 +25,22 @@ def __init__(self): data = Data.Inst() pane = self.NewPane(DialoguePane(self.parent)) - + pane.TitleSet(Lang("Validate Server Configuration")) pane.AddBox() - + self.vtResult = Lang("Not Present on CPU") for capability in data.host.capabilities([]): if re.match(r'hvm', capability): self.vtResult = Lang("OK") - + # If there is an SR that allows vdi_create, signal SR OK self.srResult = "Not Present" for pbd in data.host.PBDs([]): sr = pbd.get('SR', {}) if 'vdi_create' in sr['allowed_operations']: self.srResult = 'OK' - + self.netResult = "Not OK" if len(data.derived.managementpifs([])) > 0: managementPIF = data.derived.managementpifs()[0] @@ -50,12 +50,12 @@ def __init__(self): self.netResult = "Not connected" self.UpdateFields() - + def UpdateFields(self): data = Data.Inst() pane = self.Pane() pane.ResetFields() - + pane.AddTitleField(Lang("Validation Results")) pane.AddStatusField(Lang("VT enabled on CPU", 50), self.vtResult) pane.AddStatusField(Lang("Local default Storage Repository", 50), self.srResult) @@ -63,7 +63,7 @@ def UpdateFields(self): if self.srResult != 'OK': pane.NewLine() pane.AddWrappedTextField(Lang('A local Storage Repository is useful but not essential for ' + Language.Inst().Branding(data.host.software_version.product_brand('')) + ' operation')) - + pane.AddKeyHelpField( { Lang("") : Lang("OK") } ) def HandleKey(self, inKey): @@ -82,7 +82,7 @@ def StatusUpdateHandler(cls, inPane): inPane.AddWrappedTextField(Lang( "Press to check the basic configuration of this server.")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Validate") } ) @@ -90,7 +90,7 @@ def StatusUpdateHandler(cls, inPane): @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(ValidateDialogue())) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-base/XSFeatureXAPIConnection.py b/plugins-base/XSFeatureXAPIConnection.py index cf566a1..e0ffebd 100644 --- a/plugins-base/XSFeatureXAPIConnection.py +++ b/plugins-base/XSFeatureXAPIConnection.py @@ -27,7 +27,7 @@ def HandleRestartChoice(inChoice): Layout.Inst().TransientBanner(Lang("Restarting xapi....")) Data.Inst().StartXAPI() XSLog('Restarted xapi') - except Exception, e: + except Exception as e: XSLogFailure('Failed to restart xapi', e) Layout.Inst().PushDialogue(InfoDialogue(Lang('Restart Failed'), Lang('Xapi did not restart successfully. More information may be available in the file /var/log/xensource.log.'))) diff --git a/plugins-base/XSMenuLayout.py b/plugins-base/XSMenuLayout.py index 7e40388..5a592a0 100644 --- a/plugins-base/XSMenuLayout.py +++ b/plugins-base/XSMenuLayout.py @@ -15,29 +15,29 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSMenuLayout: def UpdateFieldsPROPERTIES(self, inPane): inPane.AddTitleField(Lang("Hardware and BIOS Information")) - + inPane.AddWrappedTextField(Lang("Press to view processor, memory, disk controller and BIOS details for this system.")) - + def UpdateFieldsAUTH(self, inPane): inPane.AddTitleField(Lang("Authentication")) - + if Auth.Inst().IsAuthenticated(): username = Auth.Inst().LoggedInUsername() else: username = "" inPane.AddStatusField(Lang("User", 14), username) - + inPane.NewLine() - + if Auth.Inst().IsAuthenticated(): inPane.AddWrappedTextField(Lang("You are logged in.")) else: @@ -46,15 +46,15 @@ def UpdateFieldsAUTH(self, inPane): inPane.NewLine() inPane.AddWrappedTextField(Lang("Only logged in users can reconfigure and control this server. " "Press to change the login password and auto-logout timeout.")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Refresh")}) def UpdateFieldsNETWORK(self, inPane): data = Data.Inst() - + inPane.AddTitleField(Lang("Network and Management Interface")) - + inPane.AddWrappedTextField(Lang("Press to configure the management network connection, hostname, and network time (NTP) settings.")) inPane.NewLine() @@ -66,7 +66,7 @@ def UpdateFieldsNETWORK(self, inPane): ntpState = 'Enabled' else: ntpState = 'Disabled' - + for pif in data.derived.managementpifs([]): inPane.AddStatusField(Lang('Device', 16), pif['device']) if int(pif['VLAN']) >= 0: @@ -81,22 +81,22 @@ def UpdateFieldsNETWORK(self, inPane): inPane.AddStatusField(Lang('NTP', 16), ntpState) inPane.AddKeyHelpField( { Lang("") : Lang("Refresh")}) - + def UpdateFieldsMANAGEMENT(self, inPane): data = Data.Inst() - + inPane.AddTitleField(Lang("Keyboard and Timezone")) - + inPane.AddWrappedTextField(Lang( "This menu configures keyboard language and timezone.")) - + inPane.NewLine() if data.timezones.current('') != '': inPane.AddWrappedTextField(Lang("The current timezone is")) inPane.NewLine() inPane.AddWrappedTextField(data.timezones.current(Lang(''))) inPane.NewLine() - + if data.keyboard.currentname('') != '': inPane.AddWrappedTextField(Lang("The current keyboard type is")) inPane.NewLine() @@ -106,7 +106,7 @@ def UpdateFieldsVM(self, inPane): hotData = HotData.Inst() inPane.AddTitleField(Lang("Virtual Machines")) - + inPane.AddWrappedTextField(Lang('Press to view the Virtual Machines menu. This menu ' 'can start, stop and migrate existing Virtual Machines on this host, and display ' 'performance information.')) @@ -115,34 +115,34 @@ def UpdateFieldsVM(self, inPane): def UpdateFieldsDISK(self, inPane): data = Data.Inst() inPane.AddTitleField(Lang("Disks and Storage Repositories")) - + inPane.AddWrappedTextField(Lang("Press to create and attach Storage Repositories, select local " "disks to use as Storage Repositories, " "and specify destinations for Suspend and Crash Dump images for this host.")) inPane.NewLine() - + inPane.AddWrappedBoldTextField(Lang('Suspend Image SR')) if data.host.suspend_image_sr(False): inPane.AddWrappedTextField(data.host.suspend_image_sr.name_label()) else: inPane.AddWrappedTextField(Lang('')) - + inPane.NewLine() - + inPane.AddWrappedBoldTextField(Lang('Crash Dump SR')) if data.host.crash_dump_sr(False): inPane.AddWrappedTextField(data.host.crash_dump_sr.name_label()) else: inPane.AddWrappedTextField(Lang('')) - + inPane.AddKeyHelpField( { Lang("") : Lang("Refresh") }) - + def UpdateFieldsPOOL(self, inPane): data = Data.Inst() inPane.AddTitleField(Lang("Resource Pool Configuration")) - + inPane.AddWrappedTextField(Lang('A Resource Pool allows a number of hosts to share resources ' 'and migrate running Virtual Machines between hosts. Press to add this host a Resource Pool ' 'or remove it from its current Pool.')) @@ -150,13 +150,13 @@ def UpdateFieldsPOOL(self, inPane): def UpdateFieldsREBOOTSHUTDOWN(self, inPane): inPane.AddTitleField(Lang("Reboot or Shutdown")) - + inPane.AddWrappedTextField(Lang( "This option can reboot or shutdown this server, and enter or exit Maintenance Mode.")) - + def UpdateFieldsTECHNICAL(self, inPane): inPane.AddTitleField(Lang("Technical Support")) - + inPane.AddWrappedTextField(Lang( "From this menu you can " "validate the configuration of this server and upload or save bug reports.")) @@ -164,13 +164,13 @@ def UpdateFieldsTECHNICAL(self, inPane): def UpdateFieldsREMOTE(self, inPane): data = Data.Inst() inPane.AddTitleField(Lang("Remote Service Configuration")) - + inPane.AddWrappedTextField(Lang("This menu configures remote services, such as access by " "remote shell (ssh) and remote logging (syslog) to other servers.")) def UpdateFieldsBUR(self, inPane): inPane.AddTitleField(Lang("Backup, Restore and Update")) - + inPane.AddWrappedTextField(Lang( "From this menu you can backup and restore the system database and Virtual Machine metadata, and apply " "software updates to the system.")) @@ -180,7 +180,7 @@ def ActivateHandler(self, inName): def Register(self): data = Data.Inst() - + rootMenuDefs = [ [ 'MENU_NETWORK', Lang("Network and Management Interface"), lambda: self.ActivateHandler('MENU_NETWORK'), self.UpdateFieldsNETWORK ], @@ -205,7 +205,7 @@ def Register(self): [ 'MENU_REBOOTSHUTDOWN', Lang("Reboot or Shutdown"), lambda: self.ActivateHandler('MENU_REBOOTSHUTDOWN'), self.UpdateFieldsREBOOTSHUTDOWN ] ] - + priority = 100 for menuDef in rootMenuDefs: diff --git a/plugins-oem/XSFeatureClaimSR.py b/plugins-oem/XSFeatureClaimSR.py index b928e2b..0b63aff 100644 --- a/plugins-oem/XSFeatureClaimSR.py +++ b/plugins-oem/XSFeatureClaimSR.py @@ -325,7 +325,7 @@ def DoAction(self): try: Data.Inst().SetPoolSRsFromDeviceIfNotSet(self.deviceToErase.device) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Disk claimed, but could not set as default SR: ") + Lang(e))) # Continue to reboot dialogue diff --git a/plugins-oem/XSFeatureManagementHelp.py b/plugins-oem/XSFeatureManagementHelp.py index af2dec8..fe5093f 100644 --- a/plugins-oem/XSFeatureManagementHelp.py +++ b/plugins-oem/XSFeatureManagementHelp.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSFeatureManagementHelp: @@ -26,10 +26,10 @@ def StatusUpdateHandler(cls, inPane): fullAppName = data.derived.full_app_name('') xenServerName = Language.Inst().Branding(data.host.software_version.product_brand('')) inPane.AddTitleField(Lang("Manage Server Using ")+appName) - + inPane.AddWrappedTextField(fullAppName+Lang(" is the ")+xenServerName+ Lang(' administration interface for the Windows(R) operating system.')) - + inPane.NewLine() inPane.AddWrappedTextField(Lang('Press for details of how to download and use ')+appName+ @@ -38,7 +38,7 @@ def StatusUpdateHandler(cls, inPane): inPane.AddKeyHelpField( { Lang("") : Lang("View ")+appName+Lang(" Info") } ) - + @classmethod def ActivateHandler(cls): data = Data.Inst() @@ -54,9 +54,9 @@ def ActivateHandler(cls): Lang('/ from a web browser on your Windows(R) desktop to download the ')+appName+ Lang(' installer.\r\rOnce installed, the same IP address ')+data.ManagementIP('')+ Lang(' can be used to connect to this server from the ')+appName+' application.') - + Layout.Inst().PushDialogue(InfoDialogue(Lang("Download and Use ")+appName, message)) - + def Register(self): data = Data.Inst() appName = data.derived.app_name('') diff --git a/plugins-oem/XSFeatureOEMBackup.py b/plugins-oem/XSFeatureOEMBackup.py index 9049986..9c01c57 100644 --- a/plugins-oem/XSFeatureOEMBackup.py +++ b/plugins-oem/XSFeatureOEMBackup.py @@ -78,7 +78,7 @@ def DoCommit(self): Lang("Backup Successful"))) XSLog('Backup successful') - except Exception, e: + except Exception as e: try: os.unlink(filename) except: pass Layout.Inst().PopDialogue() @@ -87,7 +87,7 @@ def DoCommit(self): finally: try: self.PreExitActions() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Backup Failed"), Lang(e))) diff --git a/plugins-oem/XSFeatureOEMRestore.py b/plugins-oem/XSFeatureOEMRestore.py index 9207b02..67b8014 100644 --- a/plugins-oem/XSFeatureOEMRestore.py +++ b/plugins-oem/XSFeatureOEMRestore.py @@ -69,7 +69,7 @@ def DoAction(self): XSLog('Restore successful') hostEnabled = False - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue( Lang("Restore Failed"), Lang(e))) @@ -79,7 +79,7 @@ def DoAction(self): if hostEnabled: # Dont leave the host disabled if restoration has failed Data.Inst().LocalHostEnable() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Restore Failed"), Lang(e))) diff --git a/plugins-oem/XSFeatureReset.py b/plugins-oem/XSFeatureReset.py index 1eb190b..4c5c6d1 100644 --- a/plugins-oem/XSFeatureReset.py +++ b/plugins-oem/XSFeatureReset.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class ResetDialogue(Dialogue): @@ -23,12 +23,12 @@ def __init__(self): Dialogue.__init__(self) self.ChangeState('INITIAL') - + def BuildPaneBase(self): pane = self.NewPane(DialoguePane(self.parent)) pane.TitleSet(Lang("Reset to Factory Defaults")) pane.AddBox() - + def BuildPaneINITIAL(self): self.BuildPaneBase() self.UpdateFields() @@ -36,19 +36,19 @@ def BuildPaneINITIAL(self): def BuildPaneCONFIRM(self): self.BuildPaneBase() self.UpdateFields() - + def ChangeState(self, inState): self.state = inState getattr(self, 'BuildPane'+self.state)() # Despatch method named 'BuildPane'+self.state - + def UpdateFields(self): self.Pane().ResetPosition() getattr(self, 'UpdateFields'+self.state)() # Despatch method named 'UpdateFields'+self.state - + def UpdateFieldsINITIAL(self): pane = self.Pane() pane.ResetFields() - + pane.AddWarningField(Lang("WARNING")) pane.AddWrappedTextField(Lang("This function will delete ALL configuration information, " "ALL virtual machines and ALL information within Storage Repositories on local disks. " @@ -58,7 +58,7 @@ def UpdateFieldsINITIAL(self): def UpdateFieldsCONFIRM(self): pane = self.Pane() pane.ResetFields() - + pane.AddWrappedBoldTextField(Lang("Press to confirm that you want to reset configuration data and " "erase all information in Storage Repositories on local disks, and reboot. " "The data cannot be recovered after this step.")) @@ -69,29 +69,29 @@ def HandleKey(self, inKey): handled = False if hasattr(self, 'HandleKey'+self.state): handled = getattr(self, 'HandleKey'+self.state)(inKey) - + if not handled and inKey == 'KEY_ESCAPE': Layout.Inst().PopDialogue() handled = True return handled - + def HandleKeyINITIAL(self, inKey): handled = False - + if inKey == 'KEY_F(8)': self.ChangeState('CONFIRM') handled = True - + return handled - + def HandleKeyCONFIRM(self, inKey): handled = False - + if inKey == 'KEY_ENTER': self.DoAction() handled = True - + return handled def DoAction(self): @@ -102,7 +102,7 @@ def DoAction(self): try: Layout.Inst().TransientBanner(Lang('Stopping Virtual Machines...')) ShellPipe('service', 'xapi-domains', 'stop').Call() - except Exception, e: + except Exception as e: Layout.Inst().TransientBanner(Lang('Could not stop Virtual Machines: ' + Lang(e))) time.sleep(3.0) try: @@ -111,7 +111,7 @@ def DoAction(self): Layout.Inst().TransientBanner(Lang('Rebooting...')) Layout.Inst().ExitBannerSet(Lang("Rebooting...")) Layout.Inst().SubshellCommandSet("/sbin/reboot -f") # -f avoids running init scripts on shutdown - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang('Reset to Factory Defaults Failed'), Lang(e))) class XSFeatureReset: @@ -123,13 +123,13 @@ def StatusUpdateHandler(cls, inPane): inPane.AddWrappedTextField(Lang( "This option will reset all configuration information to default values, " "delete all virtual machines and delete all Storage Repositories on local disks.")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Reset") } ) @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(ResetDialogue())) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-oem/XSFeatureUpdate.py b/plugins-oem/XSFeatureUpdate.py index 88bc7fb..21981d6 100644 --- a/plugins-oem/XSFeatureUpdate.py +++ b/plugins-oem/XSFeatureUpdate.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class UpdateDialogue(FileDialogue): @@ -30,22 +30,22 @@ def __init__(self): 'mode' : 'ro' } FileDialogue.__init__(self) # Must fill in self.custom before calling __init__ - + def DoAction(self): success = False - + Layout.Inst().PopDialogue() - + Layout.Inst().PushDialogue(BannerDialogue( Lang("Applying update... This may take several minutes. Press to abort."))) - + hostEnabled = Data.Inst().host.enabled(False) try: try: Layout.Inst().Refresh() Layout.Inst().DoUpdate() - + if VMUtils.numLocalResidentVMs() > 0: raise Exception(Lang("One or more Virtual Machines are running on this host. Please migrate, shut down or suspend Virtual Machines before continuing.")) @@ -54,32 +54,32 @@ def DoAction(self): hostRef = Data.Inst().host.uuid(None) if hostRef is None: raise Exception("Internal error 1") - + filename = self.vdiMount.MountedPath(self.filename) FileUtils.AssertSafePath(filename) command = "/opt/xensource/bin/xe update-upload file-name='"+filename+"' host-uuid="+hostRef status, output = commands.getstatusoutput(command) - + if status != 0: raise Exception(output) - + Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue( Lang("Update Successful"), Lang("Please reboot to use the newly installed software."))) XSLog('Software updated') hostEnabled = False - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue( Lang("Software Update Failed"), Lang(e))) - + finally: try: self.PreExitActions() if hostEnabled: # Dont leave the host disabled if the update has failed Data.Inst().LocalHostEnable() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Software Update Failed"), Lang(e))) class XSFeatureUpdate: @@ -91,11 +91,11 @@ def StatusUpdateHandler(cls, inPane): inPane.AddWrappedTextField(Lang( "Press to apply a software update.")) inPane.AddKeyHelpField( { Lang("") : Lang("Update") } ) - + @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(UpdateDialogue())) - + def Register(self): Importer.RegisterNamedPlugIn( self, diff --git a/plugins-oem/XSFeatureVerboseBoot.py b/plugins-oem/XSFeatureVerboseBoot.py index b13114f..76627a2 100644 --- a/plugins-oem/XSFeatureVerboseBoot.py +++ b/plugins-oem/XSFeatureVerboseBoot.py @@ -15,7 +15,7 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class VerboseBootDialogue(Dialogue): @@ -29,34 +29,34 @@ def __init__(self): ChoiceDef(Lang("Enable"), lambda: self.HandleChoice(True) ), ChoiceDef(Lang("Disable"), lambda: self.HandleChoice(False) ) ]) - + self.UpdateFields() - + def UpdateFields(self): pane = self.Pane() pane.ResetFields() - + pane.AddTitleField(Lang("Please select an option")) pane.AddMenuField(self.remoteShellMenu) pane.AddKeyHelpField( { Lang("") : Lang("OK"), Lang("") : Lang("Cancel") } ) def HandleKey(self, inKey): handled = self.remoteShellMenu.HandleKey(inKey) - + if not handled and inKey == 'KEY_ESCAPE': Layout.Inst().PopDialogue() handled = True return handled - + def HandleChoice(self, inChoice): data = Data.Inst() Layout.Inst().PopDialogue() Layout.Inst().TransientBanner(Lang("Updating...")) - + try: data.SetVerboseBoot(inChoice) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Failed: ")+Lang(e))) else: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration Updated"))) @@ -78,13 +78,13 @@ def StatusUpdateHandler(cls, inPane): inPane.AddWrappedTextField(Lang( "This option will control the level of information displayed as this server boots. " "The current state of verbose boot mode is ")+message+Lang(" press .")) - + inPane.AddKeyHelpField( { Lang("") : Lang("Configure") } ) - + @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(VerboseBootDialogue())) - + def Register(self): data = Data.Inst() Importer.RegisterNamedPlugIn( diff --git a/plugins-oem/XSMenuOEMLayout.py b/plugins-oem/XSMenuOEMLayout.py index 420dd07..e8cd590 100644 --- a/plugins-oem/XSMenuOEMLayout.py +++ b/plugins-oem/XSMenuOEMLayout.py @@ -15,20 +15,20 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") - + from XSConsoleStandard import * class XSMenuOEMLayout: - + def ActivateHandler(self, inName): Layout.Inst().TopDialogue().ChangeMenu(inName) def Register(self): data = Data.Inst() - + rootMenuDefs = [ ] - + priority = 850 for menuDef in rootMenuDefs: