def searchReference(self, element, doc): name = "unnamed" try: if element.hasAttribute("name"): name = element.getAttribute("name") __xquery = "//" # __xquery+=element.tagName __xquery += "*" __xquery += '[@id="' __xquery += element.getAttribute("refid") __xquery += '"]' # cloneNode to be safe __element = XmlTools.evaluateXPath(__xquery, doc)[0] ComLog.getLogger("DataObject").debug("found refid " + element.getAttribute("refid")) __childs = XmlTools.evaluateXPath("./*", element) __new = __element.cloneNode(True) self.appendChildren(__new, __childs) return __new except exceptions.Exception: raise ComException( "Element " + element.tagName + " with name " + name + " and id " + element.getAttribute("refid") + " not found. Query: " + __xquery )
""" def __init__(self, cmd, rc, out, err): self.cmd=cmd self.rc=rc self.out=out self.err=err def __str__(self): return """cmd=%s, errorcode=%s output: %s error: %s """ %(self.cmd, self.rc, self.out, self.err) __EXEC_REALLY_DO = None log=ComLog.getLogger("ComSystem") simcmds=list() siminfo=dict() def clearSimCommands(): """ Resets all stored simcommands """ global simcmds global siminfo simcmds=list() siminfo=dict() def getSimCommands(): """ Returns all commands being simulated """
class Sysrq(DataObject): logger=ComLog.getLogger("comoonics.ComSysrq.Sysrq") TAGNAME="sysrq" CMD_MAPPINGS={ "rebootf": "b", "reboot": "c", "locks": "d", "sigterm": "e", "oom_kill": "f", "kgdb": "g", "help": "h", "kill": "i", "sak": "k", "memory": "m", "niceable": "n", "shutoff": "o", "regs": "p", "timers": "q", "kbd_xlate": "r", "sync": "s", "tasks": "t", "readonly": "u", "voyager": "v", "blocked": "w", "xmon": "x", "log0": "0", "log1": "1", "log2": "2", "log3": "3", "log4": "4", "log5": "5", "log6": "6", "log7": "7", "log8": "8", "log9": "9", } CMD_HELP={ "rebootf": "Will immediately reboot the system without syncing or unmounting your disks.", "reboot": "Will perform a kexec reboot in order to take a crashdump.", "locks": "Shows all locks that are held.", "sigterm": "Send a SIGTERM to all processes, except for init.", "oom_kill": "Will call oom_kill to kill a memory hog process.", "kgdb": "Used by kgdb on ppc and sh platforms.", "help": "Will display help (actually any other key than those listed above will display help. but 'h' is easy to remember :-)", "kill": "Send a SIGKILL to all processes, except for init.", "sak": """Secure Access Key (SAK) Kills all programs on the current virtual console. NOTE: See important comments below in SAK section.""", "memory": "Will dump current memory info to your console.", "niceable": "Used to make RT tasks nice-able", "shutoff": "Will shut your system off (if configured and supported).", "regs": "Will dump the current registers and flags to your console.", "timers": "Will dump a list of all running timers.", "kbd_xlate": "Turns off keyboard raw mode and sets it to XLATE.", "sync": "Will attempt to sync all mounted filesystems.", "tasks": "Will dump a list of current tasks and their information to your console.", "readonly": "Will attempt to remount all mounted filesystems read-only.", "voyager": "Dumps Voyager SMP processor info to your console.", "blocked": "Dumps tasks that are in uninterruptable (blocked) state.", "xmon": "Used by xmon interface on ppc/powerpc platforms.", "log0": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log1": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log2": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log3": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log4": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log5": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log6": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log7": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log8": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", "log9": """Sets the console log level, controlling which kernel messages will be printed to your console. ('0', for example would make it so that only emergency messages like PANICs or OOPSes would make it to your console.)""", } TRIGGER_FILE="/proc/sysrq-trigger" TRIGGER_SET_FILE="/proc/sys/kernel/sysrq" def _createCommand(_name, _doc): _element=_doc.createElement("command") _element.setAttribute("name", _name) return _element _createCommand=staticmethod(_createCommand) def _createElement(command=None, settrigger=True): import xml.dom _impl=xml.dom.getDOMImplementation() _doc=_impl.createDocument(None, Sysrq.TAGNAME, None) _element=_doc.documentElement if command and type(command)==list: for _cmd in command: _element.appendChild(Sysrq._createCommand(_cmd, _doc)) elif command: _element.setAttribute("command", command) if settrigger: _element.setAttribute("settrigger", "true") elif settrigger==False: _element.setAttribute("settrigger", "false") else: _element.setAttribute("settrigger", "true") return (_element, _doc) _createElement=staticmethod(_createElement) def __init__(self, *params, **kwds): """ __init__(self, element, doc) __init__(self, doc=doc, element=element) __init__(self, command=cmd, [settrigger=*True|False]) __init__(self, commands=list<cmd>, [settrigger=*True|False]) __init__(self, [settrigger=*True|False]) @element: the element of the modification @doc: the root document @command: sysrq command to be executed @commands: list of sysrq commands to be executed @settrigger: set the trigger or not """ Sysrq.logger.debug("__init__(params: %s, kwds: %s" %(params, kwds)) if len(params)==0 and len(kwds)==0: (element, doc)=Sysrq._createElement() elif params and len(params)==2: element=params[0] doc=params[1] elif kwds and kwds.has_key("element") and kwds.has_key("doc"): element=kwds["element"] doc=kwds["doc"] elif kwds and kwds.has_key("command"): (element, doc)=Sysrq._createElement(kwds.get("command"), kwds.get("settrigger", True)) elif kwds and kwds.has_key("commands"): (element, doc)=Sysrq._createElement(kwds.get("commands"), kwds.get("settrigger", True)) else: raise TypeError("__init__() takes exactly 2 arguments or different keys. (%u given)" %len(params)) super(Sysrq, self).__init__(element, doc) def getCommands(self): _cmds=list() if self.hasAttribute("command"): _cmds.append(self.getAttribute("command")) else: for _cmdelement in self.getElement().getElementsByTagName("command"): _cmds.append(_cmdelement.getAttribute("name")) return _cmds def getCmdKey(self, _command): return Sysrq.CMD_MAPPINGS[_command] def doCommands(self): for command in self.getCommands(): ComSystem.execMethod(self.doCommand, command) def doCommand(self, _command): trigger=file(Sysrq.TRIGGER_FILE,"w") trigger.write(self.getCmdKey(_command)) trigger.close() def setTrigger(self): if self.getAttribute("settrigger", "false")=="true": trigger=file(Sysrq.TRIGGER_SET_FILE,"r+") self.oldtrigger=trigger.read(50) trigger.write("1") trigger.close() def restoreTrigger(self): if self.oldtrigger: trigger=file(Sysrq.TRIGGER_SET_FILE,"w") trigger.write(self.oldtrigger) trigger.close()
class Sysreport(object): head_set = "sysreport-head" save_set = "save-sysreport" XPATH_DESTINATION = "//path/@name" XPATH_TARFILE = "//destination/data/archive/@name" logger = ComLog.getLogger("comoonics.ComSysreport.Sysreport") """ the Baseclass for doing sysreports takes a Systeminformation as parameter to determine which systemreport components are needed. """ def __init__(self, _sysinfo, _destination, _tarfile=None, sysreport_templatesbase=SYSREPORT_TEMPLATEBASE): """ __init__(_sysinfo, _destination) @_sysinfo: the systeminformation of this system @_destination: where to write to """ super(Sysreport, self).__init__() self._sysinfo = _sysinfo self.sysreport_templatesbase = sysreport_templatesbase self.destination = _destination self.tarfile = _tarfile self.xml_validate = 1 self.templatefiles = self.getTemplateFiles() self.enterprisecopy = self.getEnterprisecopy() def getTemplateFiles(self): import os.path import dircache import re _features = list(self._sysinfo.getFeatures()) _file = DEFAULT_TEMPLATE_FILE _files = dict() _ret_files = dict() __dirfiles = dircache.listdir(self.sysreport_templatesbase) __dirfiles.sort() for _file in __dirfiles: #_file=re.sub("^\d+_", "", _file) self.logger.debug("file: %s" % _file) _file_features = os.path.splitext(_file)[0].split("-") if not _files.has_key(len(_file_features)): _files[len(_file_features)] = [_file_features] else: _files[len(_file_features)].append(_file_features) _keys = _files.keys() _keys.sort() _keys.reverse() self.logger.debug("getTemplateFiles: _files: %s" % _files) for _i in _keys: _file_features = _files[_i] for _file_feature_list in _file_features: _found = 0 for _file_feature in _file_feature_list: if _file_feature in _features: _found += 1 self.logger.debug( "getTemplateFiles: _file_feature_list: %s/%s, found: %u" % (_file_feature_list, _features, _found)) if _found == len(_file_feature_list): # self.logger.debug("getTemplateFiles(): index(%s): %u" %(_file_feature_list, self._getFeatureIndex(_file_feature_list))) _ret_files[self._getFeatureIndex( _file_feature_list )] = "%s.xml" % "-".join(_file_feature_list) for _feature in _file_feature_list: if _feature in _features: _features.remove(_feature) self.logger.debug("getTemplateFiles: Found files: %s" % _ret_files) _ks = _ret_files.keys() _ks.sort() _ks.reverse() _ret = list() for _k in _ks: _ret.append(_ret_files[_k]) return _ret def _getFeatureIndex(self, _file_feature_list): i = 0 _features = self._sysinfo.getFeatures() # self.logger.debug("_getFeatureIndex(): features: %s" %_features) for _feature in _file_feature_list: if _feature in _features: if _features.index(_feature) > i: i = _features.index(_feature) return i def getEnterprisecopy(self): from xml.dom.ext.reader import Sax2 from XmlTools import clone_node import xml.dom from comoonics import odict import os.path result_doc = None source = None reader = Sax2.Reader(validate=self.xml_validate) ret_doc = None ret_element = None _sets = odict.Odict() for _templatefile in self.templatefiles: _file = open( os.path.join(self.sysreport_templatesbase, _templatefile), "r") doc = reader.fromStream(_file) if not ret_doc: _impl = xml.dom.getDOMImplementation() ret_doc = _impl.createDocument(None, doc.documentElement.tagName, None) ret_element = ret_doc.documentElement for _child in doc.documentElement.childNodes: if _child.nodeType == xml.dom.Node.ELEMENT_NODE: if _child.hasAttribute("name"): _sets[_child.getAttribute("name")] = clone_node( _child, ret_doc) elif _child.nodeType == xml.dom.Node.ATTRIBUTE_NODE: ret_element.appendChild(clone_node(_child, ret_doc)) # remove the save-sysreport and add it to the end _save_set = _sets[self.save_set] del _sets[self.save_set] _sets[self.save_set] = _save_set for _set in _sets.values(): Sysreport.logger.debug("getEnterprisecopy() adding child: %s" % _set.getAttribute("name")) ret_element.appendChild(_set) del _sets[self.save_set] del _sets[self.head_set] self.sets = _sets return EnterpriseCopy(ret_element, ret_doc) def getOverwriteMap(self): _map = dict() _map[self.XPATH_DESTINATION] = self.destination if self.tarfile: _map[self.XPATH_TARFILE] = self.tarfile return _map def overwriteDestination(self): from comoonics import XmlTools XmlTools.overwrite_element_with_xpaths( self.enterprisecopy.getElement(), self.getOverwriteMap()) return self.enterprisecopy.getElement() def getSetNames(self): return self.sets.keys() def getSets(self): return self.sets.values() def doSets(self, setnames=None, _head_set=True, _save_set=True): self.overwriteDestination() if not setnames: setnames = self.getSetNames() if _head_set: self.enterprisecopy.doAllsets(self.head_set) self.enterprisecopy.doAllsets(setnames) if _save_set: self.enterprisecopy.doAllsets(self.save_set)
#!/usr/bin/python """ An Autodelegator class copied the from O'Reilly Python Cookbook """ import ComLog logger=ComLog.getLogger("comoonics.AutoDelegator") class AutoDelegator(object): delegates=list() do_not_delegate=list() _cash=dict() autocash=True def __getattr__(self, key, _super=False, with_delegator=True): #logger.debug("__getattr__(%s, %s)" %(key, _super)) if _super: _attr=super(AutoDelegator, self).__getattr__(self, key) if key not in self.do_not_delegate: try: if not with_delegator: return self.__getattr__(key, True) except AttributeError: pass for d in self.delegates: if self.autocash: try: return self._cash[key] except KeyError: pass try:
#!/usr/bin/python """ An Autodelegator class copied the from O'Reilly Python Cookbook """ import ComLog logger = ComLog.getLogger("comoonics.AutoDelegator") class AutoDelegator(object): delegates = list() do_not_delegate = list() _cash = dict() autocash = True def __getattr__(self, key, _super=False, with_delegator=True): #logger.debug("__getattr__(%s, %s)" %(key, _super)) if _super: _attr = super(AutoDelegator, self).__getattr__(self, key) if key not in self.do_not_delegate: try: if not with_delegator: return self.__getattr__(key, True) except AttributeError: pass for d in self.delegates: if self.autocash: try: return self._cash[key] except KeyError:
self.cmd = cmd self.rc = rc self.out = out self.err = err def __str__(self): return """cmd=%s, errorcode=%s output: %s error: %s """ % (self.cmd, self.rc, self.out, self.err) __EXEC_REALLY_DO = None log = ComLog.getLogger("ComSystem") simcmds = list() siminfo = dict() def clearSimCommands(): """ Resets all stored simcommands """ global simcmds global siminfo simcmds = list() siminfo = dict() def getSimCommands():
class Path(DataObject): logger = ComLog.getLogger("comoonics.ComPath.Path") TAGNAME = "path" def _createElement(self, path): import xml.dom _impl = xml.dom.getDOMImplementation() _doc = _impl.createDocument(None, Path.TAGNAME, None) _element = _doc.documentElement _element.setAttribute("name", path) return (_element, _doc) def __init__(self, *params, **kwds): """ The following path constructors are allowed __init__(path) __init__(element, doc) __init__(element=.., doc=..) __init__(path=..) """ self.oldpaths = list() # Case path is given if not params and not kwds: (element, doc) = self._createElement(os.getcwd()) elif params and len(params) == 1: (element, doc) = self._createElement(params[0]) elif params and len(params) == 2: (element, doc) = params elif kwds and kwds.has_key("element"): element = kwds["element"] elif kwds and kwds.has_key("doc"): doc = kwds["doc"] elif kwds and kwds.has_key("path"): (element, doc) = self._createElement(kwds["path"]) else: raise TypeError( "__init__() takes exactly 2 arguments or different keys. (%u given)" % len(params)) super(Path, self).__init__(element, doc) self.setPath(self.getPath()) self.__created = createddirs if not self.__created.has_key(self.getPath()): self.__created[self.getPath()] = False def getPath(self): return self.getAttribute("name") def setPath(self, path): try: if ComSystem.isSimulate(): self.setAttribute("name", path) else: self.setAttribute( "name", str(ComSystem.execLocalOutput("echo %s" % path)[0])[:-1]) except ExecLocalException: self.setAttribute("name", path) def getOldPaths(self): return self.oldpaths def pushd(self, path=None): _cwd = os.getcwd() if not path: path = _cwd # path=self.getPath() # if str(path) == _cwd: # return os.chdir(str(path)) self.getOldPaths().append(_cwd) self.setAttribute("name", path) if not self.__created.has_key(self.getPath()): self.__created[self.getPath()] = False def popd(self): path = None #Path.logger.debug("popd: %s" %self.getOldPaths()) if len(self.getOldPaths()) > 0: _path = self.getPath() path = self.getOldPaths().pop() os.chdir(str(path)) # we don't want the old cwd to be the path as it was not specified like this. if len(self.getOldPaths()) > 0: self.setAttribute("name", path) # Path.logger.debug("popd: _created: %s" %self.__created) return path def remove(self, path=None, force=False): if not path: path = self.getPath() if path and ((self.__created.has_key(path) and self.__created[path] and self.getAttribute("remove", "false") == "true") or force): Path.logger.debug("remove %s, %s" % (path, self.__created)) out = ComSystem.execLocalOutput("rm -rf %s" % str(path), True) if self.__created.has_key(path): del self.__created[path] def exists(self, path=None): if not path: path = self.getPath() return os.path.exists(str(path)) and os.path.isdir(str(path)) def mkdir(self, path=None, mode=0777): if not path: path = self.getPath() if not self.exists(path): os.makedirs(str(path), mode) self.__created[path] = True def __str__(self): return "currentpath: %s, oldpaths: %s" % (self.getPath(), self.getOldPaths())
return self.properties.keys() def values(self): return self.properties.values() def getAttribute(self, name): if self.has_key(name): # ComLog.getLogger("Properties").debug("name: %s, value: %s" %(name, self.getProperty(name).getAttribute("value"))) return self.getProperty(name).getAttribute(Property.ATTRIBUTE_VALUE) else: raise KeyError(name) def list(self, _pairsdelim="\n", _pairdelim="=", ): buf=list() for _property in self.iter(): buf.append("%s%s%s" %(_property.getAttribute(Property.ATTRIBUTE_NAME), _pairdelim, _property.getValue())) return _pairsdelim.join(buf) mylogger=ComLog.getLogger(Properties.__logStrLevel__) # $Log: ComProperties.py,v $ # Revision 1.10 2010-11-22 12:25:51 marc # added type attribute. # # Revision 1.9 2010/11/21 21:48:19 marc # - fixed bug 391 # - moved to upstream XmlTools implementation # # Revision 1.8 2010/02/05 12:23:30 marc # - added list method # # Revision 1.7 2009/07/22 08:37:40 marc # fedora compliant # # Revision 1.6 2008/01/25 13:04:50 marc