def updateMetaData(self, element):
    ComLog.getLogger(self.__logStrLevel__).debug("%u logical volumes cloning all from source" %(len(self.getVolumeGroup().getLogicalVolumes())))
    #ComLog.getLogger(self.__logStrLevel__).debug("Element to copy %s" %(element))
    if (len(self.getVolumeGroup().getLogicalVolumes()) == 0):
       #ComLog.getLogger(self.__logStrLevel__).debug("0 logical volumes cloning all from source")
       XmlTools.merge_trees_with_pk(element, self.getVolumeGroup().getElement(), self.document, "name", XmlTools.ElementFilter("logicalvolume"))
       self.vg=VolumeGroup(self.getVolumeGroup().getElement(), self.getDocument())
    def setUp(self):
        from comoonics.storage.hp.ComHP_EVA_Storage import HP_EVA_Storage
        from comoonics import XmlTools
        from comoonics.storage.ComDisk import StorageDisk
        #mylogger.debug("xml: %s" %(match.group(1)))
        xml_dump="""
        <disk name="Virtual Disks/atix/sourcedisk">
            <properties>
                <property name="size" value="10"/>
                <property name="disk_group" value="146er"/>
            </properties>
        </disk>
"""
        doc=XmlTools.parseXMLString(xml_dump)
        self.disk=StorageDisk(doc.documentElement, doc)
        self.storage=HP_EVA_Storage(system="127.0.0.1/EVA5000", username="******", password="******", autoconnect=True, cmd="../ComHP_EVA_SSSU_Sim.py")
        xml_dump="""
        <disk name="Virtual Disks/atix/sourcedisk_snap">
            <mapping lun="1">
                <host name="server1"/>
            </mapping>
        </disk>
"""
        doc=XmlTools.parseXMLString(xml_dump)
        self.snapdisk=StorageDisk(doc.documentElement, doc)
 def setUp(self):
     self.docs = list()
     for i in range(len(xmls)):
         if i < len(xpaths):
             self.docs.append([XmlTools.parseXMLString(xmls[i]), xpaths[i]])
         else:
             self.docs.append([XmlTools.parseXMLString(xmls[i])])
 def testCloneNode(self):
     for doc in self.docs:
         doc = doc[0]
         buf1 = XmlTools.toPrettyXML(doc.documentElement)
         buf2 = XmlTools.toPrettyXML(
             XmlTools.clone_node(doc.documentElement))
         self.assertEquals(buf1, buf2)
    def setUp(self):
        from comoonics.storage.hp.ComHP_EVA_Storage import HP_EVA_Storage
        from comoonics import XmlTools
        from comoonics.storage.ComDisk import StorageDisk
        #mylogger.debug("xml: %s" %(match.group(1)))
        xml_dump = """
        <disk name="Virtual Disks/atix/sourcedisk">
            <properties>
                <property name="size" value="10"/>
                <property name="disk_group" value="146er"/>
            </properties>
        </disk>
"""
        doc = XmlTools.parseXMLString(xml_dump)
        self.disk = StorageDisk(doc.documentElement, doc)
        self.storage = HP_EVA_Storage(system="127.0.0.1/EVA5000",
                                      username="******",
                                      password="******",
                                      autoconnect=True,
                                      cmd="../ComHP_EVA_SSSU_Sim.py")
        xml_dump = """
        <disk name="Virtual Disks/atix/sourcedisk_snap">
            <mapping lun="1">
                <host name="server1"/>
            </mapping>
        </disk>
"""
        doc = XmlTools.parseXMLString(xml_dump)
        self.snapdisk = StorageDisk(doc.documentElement, doc)
 def setUp(self):
     self.docs=list()
     for i in range(len(xmls)): 
         if i < len(xpaths):
             self.docs.append([ XmlTools.parseXMLString(xmls[i]), xpaths[i]])
         else:
             self.docs.append([ XmlTools.parseXMLString(xmls[i]) ])
    def getEnterprisecopy(self):
        from comoonics import XmlTools
        import xml.dom
        import odict
        import os.path
        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=XmlTools.parseXMLFP(_file)
            # Initially create ret_doc. Cannot do it before cause we need the doc
            if not ret_doc:
                ret_doc=XmlTools.getDOMImplementation().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")]=XmlTools.clone_node(_child, ret_doc)
                elif _child.nodeType == xml.dom.Node.ATTRIBUTE_NODE:
                    ret_element.appendChild(XmlTools.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 __test_overwrite_element_with_xpaths(self):
     for doc in self.docs:
         if len(doc) > 1:
             (doc, xpathtest)=doc
             (xpath, expectedresult, newvalue) = xpathtest
             xml2=XmlTools.overwrite_element_with_xpaths(doc.documentElement, { xpath: newvalue })
             buf=XmlTools.toPrettyXML(doc)
             self.assertEquals(buf.replace("\n", "").replace(" ", ""), XmlTools.toPrettyXML(doc).replace("\n", "").replace(" ", ""))
 def test_overwrite_attributes_with_xpaths(self):
     for doc in self.docs:
         if len(doc) > 1:
             (doc, xpathtest)=doc
             (xpath, expectedresult, newvalue) = xpathtest
             xml2=XmlTools.overwrite_attributes_with_xpaths(doc.documentElement, { xpath: newvalue })
             buf=XmlTools.toPrettyXML(xml2)
             self.assertEquals(buf.replace("\n", "").replace(" ", "").replace('<?xmlversion="1.0"?>', ""), 
                               XmlTools.toPrettyXML(doc).replace("\n", "").replace(" ", "").replace('<?xmlversion="1.0"?>', "").replace("lilr629", "myname").replace("/dev/sda1", "mydisk"))
    def testClusterRepositoryEXT3(self):
        from comoonics import XmlTools
        result="""<cluster config_version="1" name="testcluster">
    <clusternodes>
        <clusternode name="name0" nodeid="1" votes="1">
            <com_info>
                <eth master="bond0" name="eth0" slave="yes"/>
                <eth master="bond0" name="eth1" slave="yes"/>
                <eth bondingopts="miimon=100,mode=passive" name="bond0"/>
                <eth gateway="10.0.0.2" ip="10.0.0.1" name="bond0.100" netmask="255.255.255.0"/>
                <rootvolume fstype="ext3" name="/dev/vg_testcluster_sr/lv_sharedroot"/>
            </com_info>
            <fence>
                <method name="1"/>
            </fence>
        </clusternode>
    </clusternodes>
    <fencedevices/>
    <cman expected_votes="1" two_node="0"/>
    <rm>
        <resources/>
        <failoverdomains/>
    </rm>
</cluster>
"""
        self.numnodes=1
        osrcluster=OSRCluster(self.clustername, self.numnodes)
        for i in range(self.numnodes):
            _node=OSRClusterNode(osrcluster, "name%u" %i, self.rootvolume)
            _node.rootvol=self.rootvolume
            _node.rootfstype="ext3"
            _netdev=OSRClusterNodeNetdev(_node, "eth0")
            _netdev.master="bond0"
            _netdev.slave="yes"
            _node.addNetdev(_netdev)
            _netdev=OSRClusterNodeNetdev(_node, "eth1")
            _netdev.master="bond0"
            _netdev.slave="yes"
            _node.addNetdev(_netdev)
            _netdev=OSRClusterNodeNetdev(_node, "bond0")
            _netdev.bondingopts="miimon=100,mode=passive"
            _node.addNetdev(_netdev)
            _netdev=OSRClusterNodeNetdev(_node, "bond0.100")
            _netdev.ip="10.0.0.1"
            _netdev.netmask="255.255.255.0"
            _netdev.gateway="10.0.0.2"
            _node.addNetdev(_netdev)
            osrcluster.addNode(_node)
        log.debug("Cluster: %s" %osrcluster)
        log.debug("Cluster as hash: %s" %osrcluster.toHash())
        from comoonics.cluster import getClusterRepository
        hash=osrcluster.toHash()
        tmp=getClusterRepository(None,None,hash,self.defaults)
        print XmlTools.toPrettyXML(tmp.getElement())
        tmp=XmlTools.toPrettyXML(tmp.getElement())
        self.assertEquals(result.replace(" ", "").replace("\n", ""), tmp.replace("\t", "").replace(" ", "").replace("\n", ""))
def getXPathFromXMLFile(xpath, filename):
    try:
        from comoonics import XmlTools
        document = XmlTools.parseXMLFile(filename)
        return XmlTools.evaluateXPath(xpath, document.documentElement)
    except ImportError:
        import xml.dom.minidom
        from xml.xpath import Evaluate
        import os
        filep = os.fdopen(os.open(filename, os.O_RDONLY))
        doc = xml.dom.minidom.parse(filep)
        return Evaluate(xpath, doc.documentElement)
 def __test_overwrite_element_with_xpaths(self):
     for doc in self.docs:
         if len(doc) > 1:
             (doc, xpathtest) = doc
             (xpath, expectedresult, newvalue) = xpathtest
             xml2 = XmlTools.overwrite_element_with_xpaths(
                 doc.documentElement, {xpath: newvalue})
             buf = XmlTools.toPrettyXML(doc)
             self.assertEquals(
                 buf.replace("\n", "").replace(" ", ""),
                 XmlTools.toPrettyXML(doc).replace("\n",
                                                   "").replace(" ", ""))
def getXPathFromXMLFile(xpath, filename):
    try:
        from comoonics import XmlTools
        document=XmlTools.parseXMLFile(filename)
        return XmlTools.evaluateXPath(xpath, document.documentElement)
    except ImportError:
        import xml.dom.minidom
        from xml.xpath import Evaluate
        import os
        filep = os.fdopen(os.open(filename, os.O_RDONLY))
        doc=xml.dom.minidom.parse(filep)
        return Evaluate(xpath, doc.documentElement)
    def test_removePrettyTextNodes(self):
        docstring="""<?xml version="1.0" ?>
<x>
  <y>
  abcdef
  </y>
</x>
"""     
        doc=XmlTools.parseXMLString(docstring)
        XmlTools.removePrettyTextNodes(doc)
        result=XmlTools.toPrettyXML(doc, "  ", "\n")
        self.assertEquals(docstring.replace("\n", "").replace(" ", ""), result.replace("\n", "").replace(" ", ""))        
示例#15
0
 def updateMetaData(self, element):
     ComLog.getLogger(self.__logStrLevel__).debug(
         "%u logical volumes cloning all from source" %
         (len(self.getVolumeGroup().getLogicalVolumes())))
     #ComLog.getLogger(self.__logStrLevel__).debug("Element to copy %s" %(element))
     if (len(self.getVolumeGroup().getLogicalVolumes()) == 0):
         #ComLog.getLogger(self.__logStrLevel__).debug("0 logical volumes cloning all from source")
         XmlTools.merge_trees_with_pk(
             element,
             self.getVolumeGroup().getElement(), self.document, "name",
             XmlTools.ElementFilter("logicalvolume"))
         self.vg = VolumeGroup(self.getVolumeGroup().getElement(),
                               self.getDocument())
    def test_toPrettyXml(self):
        docstring = """<?xml version="1.0" ?>
\t<x>
\t  <y>
\t    abc
\t  </y>
\t</x>
"""
        doc = XmlTools.parseXMLString(docstring)
        self.assertEquals(
            docstring.replace("\n", "").replace("\t", "").replace(" ", ""),
            XmlTools.toPrettyXML(doc).replace("\n",
                                              "").replace("\t",
                                                          "").replace(" ", ""))
    def test_removePrettyTextNodes(self):
        docstring = """<?xml version="1.0" ?>
<x>
  <y>
  abcdef
  </y>
</x>
"""
        doc = XmlTools.parseXMLString(docstring)
        XmlTools.removePrettyTextNodes(doc)
        result = XmlTools.toPrettyXML(doc, "  ", "\n")
        self.assertEquals(
            docstring.replace("\n", "").replace(" ", ""),
            result.replace("\n", "").replace(" ", ""))
 def _createElement(filename, document, element=None):
     """
     Create an empty file element. If document is given the document is the bases.
     @param filename: the filename to be given to the file
     @type  filename: String
     @param document: the xml.dom.Document to use for creating a new element. If None it will be 
                      automatically created
     @type  document: xml.dom.Document
     @param element:  if given the element will be used as bases for creating the file element. Default: None (empty element will be created)
     @type  element:  xml.dom.Element
     @return: The element and the document being created
     @rtype:  [xml.dom.Element, xml.dom.Document] 
     """
     import xml.dom
     from comoonics import XmlTools
     if not document:
         impl=xml.dom.getDOMImplementation()
         document=impl.createDocument(None, File.TAGNAME, None)
         relement=document.documentElement
     elif not element:
         relement=document.createElement(File.TAGNAME)
     else:
         relement=XmlTools.clone_node(element, document)
     relement.setAttribute(File.ATTRNAME, filename)
     return (relement, document)
 def testMigration(self):
     import comoonics.cdsl.migration
     from comoonics.cdsl.ComCdslRepository import ComoonicsCdslRepository
     from comoonics import XmlTools
     from comoonics.cdsl import stripleadingsep
     fromsource = os.path.join(baseSetup.testpath, "cdsl4.xml")
     cwd = Path()
     cwd.pushd(baseSetup.tmppath)
     repository = comoonics.cdsl.migration.migrate(
         None,
         ComoonicsCdslRepository.version,
         fromresource=fromsource,
         root=baseSetup.tmppath,
         mountpoint="repo8",
         ignoreerrors=True)
     oldelement = XmlTools.parseXMLFile(fromsource)
     wanttocdsls = oldelement.documentElement.getElementsByTagName("cdsl")
     for i in range(len(wanttocdsls)):
         wanttocdsl = wanttocdsls[i]
         src = stripleadingsep(wanttocdsl.getAttribute("src"))
         iscdsl = repository.getCdsl(src)
         self.assertTrue(wanttocdsl.getAttribute("timestamp") == iscdsl.getAttribute("timestamp") and \
                         wanttocdsl.getAttribute("type") == iscdsl.getAttribute("type"), \
                         "Cdsl %s has different timestamp or type after migration" %iscdsl)
     os.remove(
         os.path.join(repository.root, repository.getMountpoint(),
                      repository.resource))
     cwd.popd()
    def hasFlag(self, name):
        try:
            from comoonics import XmlTools

            return len(XmlTools.evaluateXPath("flag/@name=" + name, self.element))
        except Exception:
            return False
 def removeFlag(self, name):
     try:
         from comoonics import XmlTools
         node=XmlTools.evaluateXPath('flag/@name='+name, self.element)[0]
         self.element.removeChild(node)
     except Exception:
         raise ComException("no flag with name %s found" %name)
示例#22
0
 def hasFlag(self, name):
     try:
         from comoonics import XmlTools
         return len(
             XmlTools.evaluateXPath('flag/@name=' + name, self.element))
     except Exception:
         return False
示例#23
0
 def addDOMElement(self, element, name=None):
     '''adds an DOM Element as member name'''
     from comoonics import XmlTools
     if name == None:
         name = self.getNextFileName()
     fd, path = tempfile.mkstemp()
     file = os.fdopen(fd, "w")
     XmlTools.toPrettyXMLFP(element, file)
     file.close()
     try:
         self.ahandler.addFile(path, name)
         os.unlink(path)
     except Exception, e:
         os.unlink(path)
         ComLog.debugTraceLog(Archive.log)
         raise e
示例#24
0
 def getDOMElement(self, name):
     '''returns a DOM Element from the given member name'''
     from comoonics import XmlTools
     file = self.ahandler.getFileObj(name)
     doc = XmlTools.parseXMLFP(file)
     self.ahandler.closeAll()
     return doc.documentElement
 def getDOMElement(self, name):
     '''returns a DOM Element from the given member name'''
     from comoonics import XmlTools
     file=self.ahandler.getFileObj(name)
     doc=XmlTools.parseXMLFP(file)
     self.ahandler.closeAll()
     return doc.documentElement
 def addDOMElement(self, element, name=None):
     '''adds an DOM Element as member name'''
     from comoonics import XmlTools
     if name == None:
         name=self.getNextFileName()
     fd, path = tempfile.mkstemp()
     file = os.fdopen(fd, "w")
     XmlTools.toPrettyXMLFP(element, file)
     file.close()
     try:
         self.ahandler.addFile(path, name)
         os.unlink(path)
     except Exception, e:
         os.unlink(path)
         ComLog.debugTraceLog(Archive.log)
         raise e
 def test_evaluateXPath(self):
     for doc in self.docs:
         if len(doc) > 1:
             (doc, xpathtest)=doc
             (xpath, expectedresult, dummy) = xpathtest
             result=XmlTools.evaluateXPath(xpath, doc)
             self.assertEquals(result, expectedresult, "Result of xpath %s in document does not equals the expected result: %s != %s" %(xpath, result, expectedresult))
 def _testDiskDump(self, dump):
     try:
         from comoonics.storage.ComDisk import StorageDisk
         from comoonics import XmlTools
         doc = XmlTools.parseXMLString(dump)
         StorageDisk(doc.documentElement, doc)
     except:
         self.fail("Could not create Disk for dump %s" % dump)
    def fromXML(element, theclass=None):
        from xml.dom import Node
        from comoonics import XmlTools
        localmap = globals()
        objecttype = None
        instance = None
        if not theclass:
            ot_elements = element.getElementsByTagName("objecttype")
            if len(ot_elements) == 1:
                objecttype = XmlTools.getTextFromElement(ot_elements[0])
                #mylogger.debug("objecttype: %s, %s" %(objecttype, localmap))
        if localmap.has_key("HP_EVA_%s" % (element.nodeName.capitalize())
                            ) and not theclass and not objecttype:
            myclass = localmap["HP_EVA_%s" % (element.nodeName.capitalize())]
            #mylogger.debug("theclass: %s" %(myclass))
            instance = HP_EVA_Object.fromXML(element, myclass)
        elif objecttype and localmap.has_key(
                "HP_EVA_%s" % (objecttype.capitalize())) and not theclass:
            myclass = localmap["HP_EVA_%s" % (objecttype.capitalize())]
            #mylogger.debug("theclass: %s" %(myclass))
            instance = HP_EVA_Object.fromXML(element, myclass)
        elif theclass:
            #mylogger.debug("theclass: %s" %(theclass))
            instance = object.__new__(theclass)
            instance.__init__()
            for child in element.childNodes:
                if child.nodeType == Node.ELEMENT_NODE:
                    paramname = child.nodeName
                    paramvalue = XmlTools.getTextFromElement(child)
                    if paramvalue:
                        paramvalue = paramvalue.strip()
                    if paramname and paramvalue and paramvalue != "":
                        #mylogger.debug("setattr(%s, %s, %s)" %(theclass, paramname, paramvalue))
                        setattr(instance, paramname, paramvalue)
                    elif paramname == "parentstoragecellinfo":
                        ids = child.getElementsByTagName("storagecellid")
                        if len(ids) == 1:
                            id = XmlTools.getTextFromElement(ids[0])
                            if HP_EVA_Storagecells.has_key(id):
                                #mylogger.debug("storagecellkey: %s, keys: %s, has_key:%u" %(id, HP_EVA_Storagecells.names(), HP_EVA_Storagecells.has_key(id)))
                                instance.setParent(HP_EVA_Storagecells.get(id))
                    elif paramname:
                        setattr(instance, paramname,
                                HP_EVA_Object.fromXML(child))

        return instance
def parseClusterConfFP(_clusterconffp, _clusterconf, _validate=False):
    from comoonics import ComLog
    from comoonics import XmlTools
    try:
        doc = XmlTools.parseXMLFP(_clusterconffp)
    except Exception, arg:
        ComLog.getLogger().critical("Problem while reading clusterconfiguration (%s): %s" %(_clusterconf, str(arg)))
        raise
 def _testDiskDump(self, dump):
     try:
         from comoonics.storage.ComDisk import StorageDisk
         from comoonics import XmlTools
         doc=XmlTools.parseXMLString(dump)
         StorageDisk(doc.documentElement, doc)
     except:
         self.fail("Could not create Disk for dump %s" %dump)
示例#32
0
 def removeFlag(self, name):
     try:
         from comoonics import XmlTools
         node = XmlTools.evaluateXPath('flag/@name=' + name,
                                       self.element)[0]
         self.element.removeChild(node)
     except Exception:
         raise ComException("no flag with name %s found" % name)
 def overwriteDestination(self):
     from comoonics import XmlTools
     self.enterprisecopy=EnterpriseCopy(XmlTools.overwrite_attributes_with_xpaths(self.enterprisecopy.getElement(), self.getOverwriteMap()), self.enterprisecopy.getDocument())
     for setname in self.sets:
         for myset in self.enterprisecopy.allsets:
             if myset.hasAttribute("name") and myset.getAttribute("name"):
                 self.sets[setname]=myset
     return self.enterprisecopy.getElement()
 def getClusterName(self):
     """
     FIXME (marc): Should go in some cluster api (ccs_xml_query!!)
         Cluster->getClusterName()
           |
           -> RedhatCluster->getClusterName()
     """
     from comoonics import XmlTools
     return XmlTools.evaluateXPath(self.XPATH_CLUSTERNAME, self.cluster_conf)[0].nodeValue
    def test_toPrettyXml(self):
        docstring="""<?xml version="1.0" ?>
\t<x>
\t  <y>
\t    abc
\t  </y>
\t</x>
"""
        doc=XmlTools.parseXMLString(docstring)
        self.assertEquals(docstring.replace("\n", "").replace("\t", "").replace(" ", ""), XmlTools.toPrettyXML(doc).replace("\n", "").replace("\t", "").replace(" ", ""))            
 def getClusterName(self):
     """
     FIXME (marc): Should go in some cluster api (ccs_xml_query!!)
         Cluster->getClusterName()
           |
           -> RedhatCluster->getClusterName()
     """
     from comoonics import XmlTools
     return XmlTools.evaluateXPath(self.XPATH_CLUSTERNAME,
                                   self.cluster_conf)[0].nodeValue
示例#37
0
def parseClusterConfFP(_clusterconffp, _clusterconf, _validate=False):
    from comoonics import ComLog
    from comoonics import XmlTools
    try:
        doc = XmlTools.parseXMLFP(_clusterconffp)
    except Exception, arg:
        ComLog.getLogger().critical(
            "Problem while reading clusterconfiguration (%s): %s" %
            (_clusterconf, str(arg)))
        raise
    def fromXML(element, theclass=None):
        from xml.dom import Node
        from comoonics import XmlTools
        localmap=globals()
        objecttype=None
        instance=None
        if not theclass:
            ot_elements=element.getElementsByTagName("objecttype")
            if len(ot_elements)==1:
                objecttype=XmlTools.getTextFromElement(ot_elements[0])
                #mylogger.debug("objecttype: %s, %s" %(objecttype, localmap))
        if localmap.has_key("HP_EVA_%s" %(element.nodeName.capitalize())) and not theclass and not objecttype:
            myclass=localmap["HP_EVA_%s" %(element.nodeName.capitalize())]
            #mylogger.debug("theclass: %s" %(myclass))
            instance=HP_EVA_Object.fromXML(element, myclass)
        elif objecttype and localmap.has_key("HP_EVA_%s" %(objecttype.capitalize())) and not theclass:
            myclass=localmap["HP_EVA_%s" %(objecttype.capitalize())]
            #mylogger.debug("theclass: %s" %(myclass))
            instance=HP_EVA_Object.fromXML(element, myclass)
        elif theclass:
            #mylogger.debug("theclass: %s" %(theclass))
            instance=object.__new__(theclass)
            instance.__init__()
            for child in element.childNodes:
                if child.nodeType == Node.ELEMENT_NODE:
                    paramname=child.nodeName
                    paramvalue=XmlTools.getTextFromElement(child)
                    if paramvalue:
                        paramvalue=paramvalue.strip()
                    if paramname and paramvalue and paramvalue!="":
                        #mylogger.debug("setattr(%s, %s, %s)" %(theclass, paramname, paramvalue))
                        setattr(instance, paramname, paramvalue)
                    elif paramname == "parentstoragecellinfo":
                        ids=child.getElementsByTagName("storagecellid")
                        if len(ids)==1:
                            id=XmlTools.getTextFromElement(ids[0])
                            if HP_EVA_Storagecells.has_key(id):
                                #mylogger.debug("storagecellkey: %s, keys: %s, has_key:%u" %(id, HP_EVA_Storagecells.names(), HP_EVA_Storagecells.has_key(id)))
                                instance.setParent(HP_EVA_Storagecells.get(id))
                    elif paramname:
                        setattr(instance, paramname, HP_EVA_Object.fromXML(child))

        return instance
 def test_evaluateXPath(self):
     for doc in self.docs:
         if len(doc) > 1:
             (doc, xpathtest) = doc
             (xpath, expectedresult, dummy) = xpathtest
             result = XmlTools.evaluateXPath(xpath, doc)
             self.assertEquals(
                 result, expectedresult,
                 "Result of xpath %s in document does not equals the expected result: %s != %s"
                 % (xpath, result, expectedresult))
    def test_overwrite_attributes_with_xpaths2(self):
        doc="""<a>
   <b name="hallo"/>
   <b name="hallo2"/>
   <c name="hallo3"/>
   <c name2="hallo4"/>
   <c name="hallo5"/>
</a>
"""
        edoc="""<a>
   <b name="marc"/>
   <b name="marc"/>
   <c name="marc"/>
   <c name2="hallo4"/>
   <c name="marc"/>
</a>
"""
        rdoc=XmlTools.overwrite_attributes_with_xpaths(XmlTools.parseXMLString(doc), {"//b/@name": "marc", "/a/c/@name": "marc"})
        self.failUnlessEqual(XmlTools.toPrettyXML(rdoc).replace("\n", "").replace(" ", "").replace("\t", "").replace('<?xmlversion="1.0"?>', ""), edoc.replace("\n", "").replace(" ", "").replace("\t", ""))   
 def __init__(self, *args, **kwds):
     from comoonics import XmlTools
     super(RedhatClusterSystemInformation, self).__init__(*args, **kwds)
     self.features.append("redhatcluster")
     if not kwds and not args:
         self.cluster_conf = XmlTools.parseXMLFile(self.REDHAT_CLUSTER_CONF)
         self.type = SystemTypes.CLUSTER
         self.name = self.getClusterName()
     else:
         self.__dict__.update(dict(kwds))
         self.type = SystemTypes.CLUSTER
 def __init__(self, *args, **kwds):
     from comoonics import XmlTools
     super(RedhatClusterSystemInformation, self).__init__(*args, **kwds)
     self.features.append("redhatcluster")
     if not kwds and not args:
         self.cluster_conf=XmlTools.parseXMLFile(self.REDHAT_CLUSTER_CONF)
         self.type=SystemTypes.CLUSTER
         self.name=self.getClusterName()
     else:
         self.__dict__.update(dict(kwds))
         self.type=SystemTypes.CLUSTER
 def _do(self):
     _message = ""
     if self.parent.hasAttribute("message"):
         _message = self.parent.getAttribute("message")
         _message += "\n"
     else:
         _textelements = self.parent.getElement().getElementsByTagName(
             "text")
         for _textelement in _textelements:
             _message += XmlTools.getTextFromElement(_textelement)
             _message += "\n"
     self.out.write(_message)
 def getClusterName(self):
     """
     FIXME (marc): Should go in some cluster api (ccs_xml_query!!)
         Cluster->getClusterName()
           |
           -> RedhatCluster->getClusterName()
     """
     from comoonics import XmlTools
     if self.type==SystemTypes.CLUSTER:
         return XmlTools.evaluateXPath(self.XPATH_CLUSTERNAME, self.cluster_conf)[0]
     else:
         return "unknown"
 def run(self, really=False):
     if self.xsl_file:
         _xml=StringIO.StringIO()
         PrettyPrint(self.doc, _xml)
         _doc=XmlTools.createDOMfromXML(_xml.getvalue(), self.xsl_file)
     else:
         _doc=self.doc
     
     if really:
         ecopy=ComEnterpriseCopy.getEnterpriseCopy(_doc.documentElement, _doc)
         ecopy.doAllsets()
     else:
         PrettyPrint(_doc)
    def getNextDOMElement(self):
        ''' returns a DOM representation of the next defined file
            <file name="filename.xml"/>
        '''
        from comoonics import XmlTools
        file=self.getNextFileObj()
        # there is no nextElement
        if file == None:
            return None

        doc=XmlTools.parseXMLFP(file)
        self.ahandler.closeAll()
        return doc.documentElement
示例#47
0
    def getNextDOMElement(self):
        ''' returns a DOM representation of the next defined file
            <file name="filename.xml"/>
        '''
        from comoonics import XmlTools
        file = self.getNextFileObj()
        # there is no nextElement
        if file == None:
            return None

        doc = XmlTools.parseXMLFP(file)
        self.ahandler.closeAll()
        return doc.documentElement
示例#48
0
    def migrate(self, fromversion, toversion, **kwds):
        from comoonics.cdsl.ComCdsl import ComoonicsCdsl
        import os.path
        from comoonics import XmlTools
        root = kwds.get("root", "/")
        mountpoint = kwds.get("mountpoint", "")
        toresource = kwds.get("toresource",
                              ComoonicsCdslRepository.default_resources[0])
        fromresource = kwds.get("fromresource",
                                ComoonicsCdslRepository.default_resources[1])

        if os.path.exists(fromresource):
            fromdoc = XmlTools.parseXMLFile(fromresource, False)
            fromelement = fromdoc.documentElement
            if fromelement.tagName != ComoonicsCdslRepository.cdsls_element:
                raise ConfigfileFormatException(
                    "Config file \"%s\"does not start with an cdsls element. Wrong format."
                    % fromresource)

            defaults = fromelement.getElementsByTagName("defaults")
            if defaults:
                defaults = defaults[0]

            defaultkeys = self.getDefaultKeys(defaults)
            defaultkeys["root"] = root
            defaultkeys["mountpoint"] = mountpoint
            defaultkeys["resource"] = toresource
            self.logger.debug("defaults: %s" % defaultkeys)
            torepository = ComoonicsCdslRepository(**defaultkeys)
            cdsls = fromelement.getElementsByTagName("cdsl")
            if cdsls and len(cdsls) > 0:
                for i in range(len(cdsls)):
                    nodes = []
                    nodeselement = cdsls[i].getElementsByTagName("nodes")
                    if nodeselement:
                        nodeselement = nodeselement[0]
                        noderefs = nodeselement.getElementsByTagName("noderef")
                        if noderefs and len(noderefs) > 0:
                            for j in range(len(noderefs)):
                                nodes.append(noderefs[j].getAttribute("ref"))
                    cdsl = ComoonicsCdsl(cdsls[i].getAttribute("src"),
                                         cdsls[i].getAttribute("type"),
                                         torepository, None, nodes,
                                         cdsls[i].getAttribute("timestamp"),
                                         kwds.get("ignoreerrors", True))
                    torepository.commit(cdsl)
            return torepository
        else:
            raise IOError(
                2, "Could not find cdsl inventory file %s in %s" %
                (fromresource, os.getcwd()))
def fromXML(options, xmlfile):
    from comoonics import XmlTools
    import xml.dom
    if options.xml=="-":
        logger.debug("Parsing document from stdin")
        doc = XmlTools.parseXMLFP(sys.stdin, options.xmlvalidate)
    elif os.path.isfile(options.xml):
        logger.debug("Parsing document %s " % options.xml)
        doc = XmlTools.parseXMLFile(options.xml, options.xmlvalidate)

    if options.clusterconf:
        from xml import xpath
        if options.nodename != None or options.nodename != "":
            (rc, options.nodename)=ComSystem.execLocalStatusOutput("cman_tool status | grep 'Node name:'")
            logger.debug("options.nodename: %s" %options.nodename)
            options.nodename=options.nodename.split(" ")[2]
            _xmlnodepath='/cluster/clusternodes/clusternode[@name="%s"]/com_info/fenceackserver' %(options.nodename)
            logger.debug("Nodename: %s, path: %s" %(options.nodename, _xmlnodepath))
            node=xpath.Evaluate(_xmlnodepath, doc)[0]
    elif options.xmlnodepath and options.xmlnodepath != "":
        from xml import xpath
        logger.debug("Path2Config: %s" %options.xmlnodepath)
        node=xpath.Evaluate(options.xmlnodepath, doc)[0]
    else:
        node=doc.documentElement

    if node.hasAttribute("port"): options.port=node.getAttribute("port")
    if node.hasAttribute("user"): options.user=node.getAttribute("user")
    if node.hasAttribute("passwd"): options.password=node.getAttribute("passwd")
    if node.hasAttribute("bind"): options.bind=node.getAttribute("bind")
    sslnodes=node.getElementsByTagName("ssl")
    if sslnodes:
        options.ssl=True
        if node.hasAttribute("keyfile"): options.ssl_keyfile=node.getAttribute("keyfile")
        if node.hasAttribute("certfile"): options.ssl_certfile=node.getAttribute("certfile")
        if node.hasAttribute("verifyfile"): options.ssl_verifyfile=node.getAttribute("verifyfile")

    return
 def setUp(self):
     from comoonics import XmlTools
     import StringIO
     from comoonics.storage.ComDevice import Device
     from comoonics.storage.ComMountpoint import MountPoint
     from comoonics.storage.ComFileSystem import getFileSystem
     
     xmlfp=StringIO.StringIO(self.xml)
     doc=XmlTools.parseXMLFP(xmlfp)
     __device=doc.documentElement
     
     self.device=Device(__device, doc)
     __fs=__device.getElementsByTagName("filesystem")[0]
     self.filesystem=getFileSystem(__fs, doc)
     __mp=__device.getElementsByTagName("mountpoint")[0]
     self.mountpoint=MountPoint(__mp, doc)
示例#51
0
    def setUp(self):
        from comoonics import XmlTools
        import StringIO
        from comoonics.storage.ComDevice import Device
        from comoonics.storage.ComMountpoint import MountPoint
        from comoonics.storage.ComFileSystem import getFileSystem

        xmlfp = StringIO.StringIO(self.xml)
        doc = XmlTools.parseXMLFP(xmlfp)
        __device = doc.documentElement

        self.device = Device(__device, doc)
        __fs = __device.getElementsByTagName("filesystem")[0]
        self.filesystem = getFileSystem(__fs, doc)
        __mp = __device.getElementsByTagName("mountpoint")[0]
        self.mountpoint = MountPoint(__mp, doc)
示例#52
0
 def read(self, filename):
     """ This method reads the file and initializes all internal structures for handling as ConfigParser. """
     if isinstance(filename, basestring):
         self.doc=XmlTools.parseXMLFile(filename, self.validate)
         try:
             if self.doc.documentElement.tagName == self.LOGGING_TAGNAME:
                 _baseelement=self.doc.documentElement
             else:
                 _baseelement=self.doc.documentElement.getElementsByTagName(self.LOGGING_TAGNAME)[0]
         except:
             mylogger.exception("No Logging configuration found in file %s" %(filename))
             raise NoLoggingConfigFound, "No Logging configuration found in file %s" %(filename)
     elif isinstance(filename, Node):
         _baseelement=filename
     else:
         raise IncompatibleConfigFileType(type(filename))
     self._read(_baseelement, filename)
 def migrate(self, fromversion, toversion, **kwds):
     from comoonics.cdsl.ComCdslRepository import ComoonicsCdslRepository
     from comoonics.cdsl.ComCdsl import ComoonicsCdsl
     import os.path
     from comoonics import XmlTools
     root=kwds.get("root", "/")
     mountpoint=kwds.get("mountpoint", "")
     toresource=kwds.get("toresource", ComoonicsCdslRepository.default_resources[0])
     fromresource=kwds.get("fromresource", ComoonicsCdslRepository.default_resources[1])
     
     if os.path.exists(fromresource):
         fromdoc=XmlTools.parseXMLFile(fromresource, False)
         fromelement=fromdoc.documentElement
         if fromelement.tagName != ComoonicsCdslRepository.cdsls_element:
             raise ConfigfileFormatException("Config file \"%s\"does not start with an cdsls element. Wrong format." %fromresource)
         
         defaults=fromelement.getElementsByTagName("defaults")
         if defaults:
             defaults=defaults[0]
         
         defaultkeys=self.getDefaultKeys(defaults)
         defaultkeys["root"]=root
         defaultkeys["mountpoint"]=mountpoint
         defaultkeys["resource"]=toresource
         self.logger.debug("defaults: %s" %defaultkeys)
         torepository=ComoonicsCdslRepository(**defaultkeys)
         cdsls=fromelement.getElementsByTagName("cdsl")
         if cdsls and len(cdsls)>0:
             for i in range(len(cdsls)):
                 nodes=[]
                 nodeselement=cdsls[i].getElementsByTagName("nodes")
                 if nodeselement:
                     nodeselement=nodeselement[0]
                     noderefs=nodeselement.getElementsByTagName("noderef")
                     if noderefs and len(noderefs) > 0:
                         for j in range(len(noderefs)):
                             nodes.append(noderefs[j].getAttribute("ref"))
                 cdsl=ComoonicsCdsl(cdsls[i].getAttribute("src"), cdsls[i].getAttribute("type"), torepository, None, nodes, cdsls[i].getAttribute("timestamp"), kwds.get("ignoreerrors", True))
                 torepository.commit(cdsl)
         return torepository
     else:
         raise IOError(2, "Could not find cdsl inventory file %s in %s" %(fromresource, os.getcwd()))
示例#54
0
 def testName(self):
     _xml="""
 <copyset type="filesystem" name="save-sysreport-redhat">
     <source type="path">
         <path name="/tmp/sysreport-$(date -u +%G%m%d%k%M%S | /usr/bin/tr -d ' ')"/>
     </source>
     <destination type="backup">
         <metadata>
             <archive name='/tmp/meta-clone-lilr627-02.tar' format='tar' type='file'>
                 <file name='./path.xml'/>
             </archive>
         </metadata>
         <data>
             <archive name='/tmp/path-02.tgz' format='tar' type='file' compression='gzip'/>
         </data>
     </destination>
 </copyset>"""
     from comoonics.enterprisecopy.ComCopyset import Copyset
     from comoonics import XmlTools
     doc=XmlTools.parseXMLString(_xml)
     _copyset=Copyset(doc.documentElement, doc)
     self.__testPathCopyset(_copyset)
 def testGetTextFromElement1(self):
     doc = self.docs[2][0]
     self.assertEquals("abcd",
                       XmlTools.getTextFromElement(doc.documentElement))
 def testGetTextFromElement(self):
     doc = self.docs[3][0]
     self.assertEquals(None,
                       XmlTools.getTextFromElement(doc.documentElement))
示例#57
0
 def overwriteDestination(self):
     from comoonics import XmlTools
     XmlTools.overwrite_element_with_xpaths(
         self.enterprisecopy.getElement(), self.getOverwriteMap())
     return self.enterprisecopy.getElement()
示例#58
0
 def _parse_dateformat(self, cursect, child):
     _format=XmlTools.getTextFromElement(child)
     cursect["dateformat"]=_format