Ejemplo n.º 1
0
    def get_attr(self, key):
        """ This method gets attribute value of a Managed Object. """
        if key == "_class_id" and self.__dict__.has_key(key):
            return self.__dict__[key]

        if CoreUtils.find_class_id_in_mo_meta_ignore_case(self.class_id):
            if self.__dict__.has_key(key):
                if key in _MANAGED_OBJECT_META[self.class_id]:
                    # property exists
                    return self.__dict__[key]
            else:
                if self.__dict__.has_key('_ManagedObject__xtra_property'):
                    if self.__xtra_property.has_key(key):
                        return self.__xtra_property[ImcUtils.word_u(key)]
                    else:
                        raise AttributeError(key)
                else:
                    print "No xtra_property in mo:", self.class_id, " key:", key
        else:
            # property does not exist
            if self.__dict__['_ManagedObject__xtra_property'].has_key(key):
                return self.__xtra_property[ImcUtils.word_u(key)]
            elif key == "Dn" or key == "Rn":
                return None
            else:
                raise AttributeError(key)
Ejemplo n.º 2
0
    def get_attr(self, key):
        """ This method gets attribute value of a Managed Object. """
        if key == "_class_id" and self.__dict__.has_key(key):
            return self.__dict__[key]

        if CoreUtils.find_class_id_in_mo_meta_ignore_case(self.class_id):
            if self.__dict__.has_key(key):
                if key in _MANAGED_OBJECT_META[self.class_id]:
                    # property exists
                    return self.__dict__[key]
            else:
                if self.__dict__.has_key('_ManagedObject__xtra_property'):
                    if self.__xtra_property.has_key(key):
                        return self.__xtra_property[ImcUtils.word_u(key)]
                    else:
                        raise AttributeError(key)
                else:
                    print "No xtra_property in mo:", self.class_id, " key:", key
        else:
            # property does not exist
            if self.__dict__['_ManagedObject__xtra_property'].has_key(key):
                return self.__xtra_property[ImcUtils.word_u(key)]
            elif key == "Dn" or key == "Rn":
                return None
            else:
                raise AttributeError(key)
Ejemplo n.º 3
0
def _translate_imc_managedobject(m_obj, xlate_map):
    """ Method used to translate a managedobject. This method is used in compare_imc_managedobject. """

    x_mo = m_obj.clone()
    x_mo.set_handle(m_obj.get_handle())

    if xlate_map != None:
        original_dn = x_mo.dn
        if original_dn in xlate_map:
            x_mometa = CoreUtils.get_mo_property_meta(ImcUtils.word_u(x_mo.class_id), "Meta")
            if x_mometa == None:
                ImcUtils.write_imc_warning('[Warning]: Could not translate [%s]' %(original_dn))
                return x_mo

            #Check for naming property
            match_obj = re.findall(r'(\[[^\]]+\])', x_mometa.rn)
            if match_obj:
                _update_mo_dn_along_with_naming_properties(x_mo, x_mometa, xlate_map[original_dn])
            else:
                #print "Translating", x_mo.dn, " => ", xlate_map[original_dn]
                x_mo.dn = xlate_map[original_dn]
        else:
            original_dn = re.sub(r'[/]*[^/]+$', '', original_dn)
            while original_dn != None or original_dn == "":
                if not original_dn in xlate_map:
                    original_dn = re.sub(r'[/]*[^/]+$', '', original_dn)
                    continue

                new_dn = re.sub("^%s/"%(original_dn), "%s/"%(xlate_map[original_dn]), x_mo.dn)
                #print "Translating", x_mo.dn, " => ", new_dn
                x_mo.dn = new_dn
                break

    return x_mo
Ejemplo n.º 4
0
    def load_from_xml(self, element, handle):
        """ Method creates the object from the XML representation of the an external method object. """
        from Imc import class_factory
        self.set_handle(handle)
        if element.attrib:
            for attr_name, attr_value in element.attrib.iteritems():
                attr = ImcUtils.word_u(attr_name)
                if attr in CoreUtils.get_property_list(self._class_id):
                    at_meta = CoreUtils.get_method_property_meta(self._class_id, attr)
                    if at_meta.io == "Input" or at_meta.is_complex_type:
                        continue
                    self.set_attr(attr, str(attr_value))
                elif attr_name in _EXTERNAL_METHOD_ATTRS:
                    self.set_attr(_EXTERNAL_METHOD_ATTRS[attr_name], str(attr_value))

        child_elements = element.getchildren()
        if child_elements:
            for child_element in child_elements:
                if not ET.iselement(child_element) :
                    continue
        
                cln = ImcUtils.word_u(child_element.tag)
                if cln in CoreUtils.get_property_list(self._class_id):
                    prop_meta = CoreUtils.get_method_property_meta(self._class_id, cln)
                    if prop_meta.io == "Output" and prop_meta.is_complex_type:
                        child = class_factory(prop_meta.field_type)
                        if child != None:
                            self.set_attr(cln, child)
                            child.load_from_xml(child_element, handle)
Ejemplo n.º 5
0
    def load_from_xml(self, element, handle):
        """ Method creates the object from the xml representation of the managed object. """
        self.set_handle(handle)
        if element.attrib:
            for attr_name, attr_value in element.attrib.iteritems():
                attr = ImcUtils.word_u(attr_name)
                if CoreUtils.find_class_id_in_mo_meta_ignore_case(self._class_id) != None:
                    if attr in CoreUtils.get_property_list(self._class_id):
                        self.set_attr(attr, str(attr_value))
                    else:
                        self.set_attr(attr, str(attr_value))
                else:
                    self.set_attr(ImcUtils.word_u(attr), str(attr_value))
            
            if self.get_attr("Rn") == None and self.get_attr("Dn") != None:
                self.set_attr("Rn", str(re.sub(r'^.*/', '', self.get_attr("Dn"))))

        child_elements = element.getchildren()
        if child_elements:
            for child_element in child_elements:
                if not ET.iselement(child_element) :
                    continue
    
                if child_element.tag in self.prop_mo_meta.field_names:
                    pass
                #TODO: Need code analysis.
                child = ManagedObject(ImcUtils.word_u(child_element.tag))
                self._child.append(child)
                child.load_from_xml(child_element, handle)
Ejemplo n.º 6
0
def _write_mo(mo):
    """ Method to return string representation of a managed object. """
    class_not_found = False
    if CoreUtils.find_class_id_in_mo_meta_ignore_case(mo.class_id) == None:
        class_not_found = True
    tab_size = 8
    out_str = "\n"
    if class_not_found:
        out_str += "Managed Object\t\t\t:\t" + str(ImcUtils.word_u(mo.class_id)) + "\n"
    else:
        out_str += "Managed Object\t\t\t:\t" + str(mo.prop_mo_meta.name) + "\n"
    out_str += "-"*len("Managed Object") + "\n"
    if not class_not_found:
        for prop in CoreUtils.get_property_list(mo.prop_mo_meta.name):
            #prop_meta = CoreUtils.get_mo_property_meta(mo.prop_mo_meta.name, prop)
            #if (prop_meta.access == MoPropertyMeta.Internal):
                #continue
            val = mo.get_attr(prop)
            #if val != None and val != "":
            out_str += str(prop).ljust(tab_size*4) + ':' + str(val) + "\n"
    else:
        for prop in mo.__dict__:
            if prop in ['_class_id', '_ManagedObject__xtra_property', '_handle', 'prop_mo_meta', '_dirty_mask', '_child']:
                continue
            val = mo.__dict__[prop]
            out_str += str(ImcUtils.word_u(prop)).ljust(tab_size*4) + ':' + str(val) + "\n"
    if mo.__dict__.has_key('_ManagedObject__xtra_property'):
        for xtra_prop in mo.__dict__['_ManagedObject__xtra_property']:
            out_str += ('[X]' + str(ImcUtils.word_u(xtra_prop))).ljust(tab_size*4) + ':' + str(mo.__dict__['_ManagedObject__xtra_property'][xtra_prop]) + "\n"

    out_str += str("Imc").ljust(tab_size*4) + ':' + str(mo.handle.imc) + "\n"

    out_str += "\n"
    return out_str
Ejemplo n.º 7
0
    def config_resolve_children(self,
                                class_id,
                                in_dn,
                                in_hierarchical=YesOrNo.FALSE,
                                dump_xml=None):
        """ Auto-generated IMC XML API Method. """
        method = ExternalMethod("ConfigResolveChildren")

        meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(
            class_id)
        if meta_class_id != None:
            class_id = ImcUtils.word_l(meta_class_id)
        else:
            class_id = ImcUtils.word_l(class_id)
        method.ClassId = class_id
        method.Cookie = self.__cookie
        method.InDn = in_dn
        method.InHierarchical = ((
            "false", "true")[in_hierarchical in ImcUtils.AFFIRMATIVE_LIST])

        response = self.xml_query(method, WriteXmlOption.DIRTY, dump_xml)

        if response != None:
            return response
        return None
Ejemplo n.º 8
0
    def load_from_xml(self, element, handle):
        """ Method creates the object from the xml representation of the managed object. """
        self.set_handle(handle)
        if element.attrib:
            for attr_name, attr_value in element.attrib.iteritems():
                attr = ImcUtils.word_u(attr_name)
                if CoreUtils.find_class_id_in_mo_meta_ignore_case(
                        self._class_id) != None:
                    if attr in CoreUtils.get_property_list(self._class_id):
                        self.set_attr(attr, str(attr_value))
                    else:
                        self.set_attr(attr, str(attr_value))
                else:
                    self.set_attr(ImcUtils.word_u(attr), str(attr_value))

            if self.get_attr("Rn") == None and self.get_attr("Dn") != None:
                self.set_attr("Rn",
                              str(re.sub(r'^.*/', '', self.get_attr("Dn"))))

        child_elements = element.getchildren()
        if child_elements:
            for child_element in child_elements:
                if not ET.iselement(child_element):
                    continue

                if child_element.tag in self.prop_mo_meta.field_names:
                    pass
                #TODO: Need code analysis.
                child = ManagedObject(ImcUtils.word_u(child_element.tag))
                self._child.append(child)
                child.load_from_xml(child_element, handle)
Ejemplo n.º 9
0
    def load_from_xml(self, element, handle):
        """ Method creates the object from the XML representation of the an external method object. """
        from Imc import class_factory
        self.set_handle(handle)
        if element.attrib:
            for attr_name, attr_value in element.attrib.iteritems():
                attr = ImcUtils.word_u(attr_name)
                if attr in CoreUtils.get_property_list(self._class_id):
                    at_meta = CoreUtils.get_method_property_meta(
                        self._class_id, attr)
                    if at_meta.io == "Input" or at_meta.is_complex_type:
                        continue
                    self.set_attr(attr, str(attr_value))
                elif attr_name in _EXTERNAL_METHOD_ATTRS:
                    self.set_attr(_EXTERNAL_METHOD_ATTRS[attr_name],
                                  str(attr_value))

        child_elements = element.getchildren()
        if child_elements:
            for child_element in child_elements:
                if not ET.iselement(child_element):
                    continue

                cln = ImcUtils.word_u(child_element.tag)
                if cln in CoreUtils.get_property_list(self._class_id):
                    prop_meta = CoreUtils.get_method_property_meta(
                        self._class_id, cln)
                    if prop_meta.io == "Output" and prop_meta.is_complex_type:
                        child = class_factory(prop_meta.field_type)
                        if child != None:
                            self.set_attr(cln, child)
                            child.load_from_xml(child_element, handle)
Ejemplo n.º 10
0
def update_imc_firmware(handle, in_mo, admin_state, protocol, share_type, remote_server, remote_path, username, password, secure_boot=None, dump_xml=None):
    """
    Uploads the Firmware image to IMC Server.

    - in_mo            specifies the respective Managed Object to upload image.
    - remoteserver        specifies the IP address of host containing firmware image.
    - username        specifies the Username login credential of host containing firmware image.
    - password        specifies the Password login credential of host containing firmware image.
    - remotepath        specifies the path of firmware image on remoteserver.
    - protocol            specifies the protocol used for transferring the file to remotehost.
    - sharetype            specifies the share type.
    - admin_state        specifies the admin state.
    """
    from ImcMos import FirmwareUpdatable
    dn = None

    if in_mo != None:
        if str(ImcUtils.word_u(in_mo.class_id)) == "FirmwareUpdatable":
            dn = in_mo.get_attr("Dn")
        elif str(ImcUtils.word_u(in_mo.class_id)) == "BiosUnit":
            dn = CoreUtils.make_dn([in_mo.get_attr("Dn"), CoreUtils.make_rn("FirmwareUpdatable")])
        elif str(ImcUtils.word_u(in_mo.class_id)) == "MgmtController":
            dn = CoreUtils.make_dn([in_mo.get_attr("Dn"), CoreUtils.make_rn("FirmwareUpdatable")])
        else:
            raise ImcValidationException("Please provide correct Managed Object. Valid MOs <FirmwareUpdatable or BiosUnit or MgmtController")
    else:
        raise ImcValidationException("Please provide correct Managed Object. Valid MOs <FirmwareUpdatable or BiosUnit or MgmtController")

#        if updatetype == FirmwareUpdatable.CONST_TYPE_BLADE_CONTROLLER:
#            dn = "sys/rack-unit-1/mgmt/fw-updatable"
#        if updatetype == FirmwareUpdatable.CONST_TYPE_BLADE_BIOS:
#            dn = "sys/rack-unit-1/bios/fw-updatable"
#        if updatetype == FirmwareUpdatable.CONST_TYPE_ADAPTOR:
#            dn = "sys/rack-unit-1/adaptor-1/mgmt/fw-updatable"

    firmware_updater = ManagedObject(NamingId.FIRMWARE_UPDATABLE)
    firmware_updater.dn = dn
    firmware_updater.Status = Status.MODIFIED
    #firmware_updater.AdminState = FirmwareUpdatable.CONST_ADMIN_STATE_TRIGGER
    firmware_updater.AdminState = admin_state
    firmware_updater.Protocol = protocol
    firmware_updater.RemoteServer = remote_server
    firmware_updater.RemotePath = remote_path
    firmware_updater.User = username
    firmware_updater.Pwd = password
    firmware_updater.Type = share_type
    firmware_updater.SecureBoot = secure_boot

    in_config = ConfigConfig()
    in_config.add_child(firmware_updater)

    ccm = handle.config_conf_mo(dn=dn, in_config=in_config, in_hierarchical=YesOrNo.FALSE, dump_xml=dump_xml)

    if ccm.error_code != 0:
        raise ImcException(ccm.error_code, ccm.error_descr)

    return ccm.OutConfig.child
Ejemplo n.º 11
0
    def xml_rawquery(self, xml_str, dump_xml=None):
        """
        Accepts xmlQuery String and returns XML response String. No object manipulation is done in this method.
        """

        if dump_xml == None:
            dump_xml = self.__dump_xml

        uri = self.uri() + '/nuova'
        if dump_xml in ImcUtils.AFFIRMATIVE_LIST:
            print '%s ====> %s' % (self.__imc, xml_str)

        xml_doc = ET.fromstring(xml_str)

        if self.__nossl:
            req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
            opener = urllib2.build_opener(ImcUtils.SmartRedirectHandler())
            resp = opener.open(req)

            if type(resp) is list:
                if len(resp) == 2 and (resp[0] == 302 or resp[0] == 301):
                    uri = resp[1]
                    req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
                    resp = urllib2.urlopen(req)
                    #print "status code is:",f[0]
                    #print "location is:", f[1]
        else:
            req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
            resp = urllib2.urlopen(req)

        rsp = resp.read()
        if dump_xml in ImcUtils.AFFIRMATIVE_LIST:
            print '%s <==== %s' % (self.__imc, rsp)
        return rsp
Ejemplo n.º 12
0
    def write_xml(self, xml_doc=None, option=None, element_name=None):
        """create Xml Document Node using object attributes"""
        if xml_doc is None:
            xml_obj = Element(self._class_id)
        else:
            if element_name == None:
                xml_obj = SubElement(xml_doc, self._class_id)
            else:
                xml_obj = SubElement(xml_doc, element_name)


#        if element_name == None:
#            xml_obj = xml_doc.createElement(self._class_id)
#        else:
#            xml_obj = xml_doc.createElement(element_name)

        for prop in self.__dict__['properties']:
            xml_obj.setAttribute(ImcUtils.word_l(prop),
                                 self.__dict__['properties'][prop])
        self.child_write_xml(xml_obj, option)
        #        x_child = self.child_write_xml(xml_doc, option)
        #        for xchild in x_child:
        #            if xchild != None:
        #                xml_obj.appendChild(xchild)
        return xml_obj
Ejemplo n.º 13
0
    def write_xml(self, xml_doc=None, option=None, element_name=None):
        """ Method writes the XML representation of the external method object. """
        if xml_doc is None:
            xml_obj = Element(self.prop_mo_meta.xml_attribute)
        else:
            if element_name == None:
                xml_obj = SubElement(xml_doc, self.prop_mo_meta.xml_attribute)
            else:
                xml_obj = SubElement(xml_doc, element_name)

        for prop in CoreUtils.get_property_list(self._class_id):
            prop_meta = CoreUtils.get_method_property_meta(
                self._class_id, prop)
            if prop_meta.io == "Output":
                continue
            if prop_meta.is_complex_type:
                if self.get_attr(prop) != None:
                    self.__dict__[prop].write_xml(xml_obj, option,
                                                  ImcUtils.word_l(prop))
                    #xml_obj.append(self.__dict__[prop].write_xml(xml_obj, option, ImcUtils.word_l(prop)))
                    #print ET.tostring(xml_obj)
            elif self.get_attr(prop) != None:
                xml_obj.set(prop_meta.xml_attribute, self.get_attr(prop))

        self.child_write_xml(xml_obj, option)
        #        x_child = self.child_write_xml(xml_obj, option)
        #        for xchild in x_child:
        #            if xchild != None:
        #                xml_obj.append(xchild)
        return xml_obj
Ejemplo n.º 14
0
    def write_xml(self, xml_doc=None, option=None, element_name=None):
        """ Method writes the xml representation of the managed object. """
        if option == WriteXmlOption.DIRTY and not self.is_dirty():
            return
        if xml_doc is None:
            xml_obj = Element(self.prop_mo_meta.xml_attribute)
        else:
            if element_name == None:
                xml_obj = SubElement(xml_doc, self.prop_mo_meta.xml_attribute)
            else:
                xml_obj = SubElement(xml_doc, element_name)
        if CoreUtils.find_class_id_in_mo_meta_ignore_case(self._class_id) != None:
            for prop in CoreUtils.get_property_list(self._class_id):
                prop_meta = CoreUtils.get_mo_property_meta(self._class_id, prop)
                #if (at_meta.access == MoPropertyMeta.Internal):
            #        continue
                #elif ((option != WriteXmlOption.DIRTY) or ((at_meta.mask != None) and (self._dirty_mask & at_meta.mask) != 0)):
                if option != WriteXmlOption.DIRTY or (prop_meta.mask != None and (self._dirty_mask & prop_meta.mask) != 0):
                    if self.get_attr(prop) != None:
                        #xml_obj.setAttribute(prop_meta.xml_attribute, self.get_attr(prop))
                        xml_obj.set(prop_meta.xml_attribute,self.get_attr(prop))
        #Adding xtraProperties from object into Xml query document
        for xtra_prop in self.__xtra_property:
            #xml_obj.setAttribute(ImcUtils.word_l(xtra_prop), self.__xtra_property[xtra_prop])
            xml_obj.set(ImcUtils.word_l(xtra_prop),self.__xtra_property[xtra_prop])
        self.child_write_xml(xml_obj, option)
#        x_child = self.child_write_xml(xml_obj, option)
#        for xchild in x_child:
#            if xchild != None:
#                xml_obj.append(xchild)
        return xml_obj
Ejemplo n.º 15
0
    def write_xml(self, xml_doc=None, option=None, element_name=None):
        """ Method writes the XML representation of the external method object. """
        if xml_doc is None:
            xml_obj = Element(self.prop_mo_meta.xml_attribute)
        else:
            if element_name == None:
                xml_obj = SubElement(xml_doc, self.prop_mo_meta.xml_attribute)
            else:
                xml_obj = SubElement(xml_doc, element_name)
        
        for prop in CoreUtils.get_property_list(self._class_id):
            prop_meta = CoreUtils.get_method_property_meta(self._class_id, prop)
            if prop_meta.io == "Output":
                continue
            if prop_meta.is_complex_type:
                if self.get_attr(prop) != None:
                    self.__dict__[prop].write_xml(xml_obj, option, ImcUtils.word_l(prop))
                    #xml_obj.append(self.__dict__[prop].write_xml(xml_obj, option, ImcUtils.word_l(prop)))
                    #print ET.tostring(xml_obj)
            elif self.get_attr(prop) != None:
                xml_obj.set(prop_meta.xml_attribute, self.get_attr(prop))
                
        self.child_write_xml(xml_obj, option)
#        x_child = self.child_write_xml(xml_obj, option)
#        for xchild in x_child:
#            if xchild != None:
#                xml_obj.append(xchild)
        return xml_obj
Ejemplo n.º 16
0
    def config_resolve_class(self, class_id, in_hierarchical=YesOrNo.FALSE, dump_xml=None):
        """ Auto-generated IMC XML API Method. """
        method = ExternalMethod("ConfigResolveClass")

        meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(class_id)
        if meta_class_id != None:
            class_id = ImcUtils.word_l(meta_class_id)
        else:
            class_id = ImcUtils.word_l(class_id)
        method.ClassId = class_id
        method.Cookie = self.__cookie
        method.InHierarchical = (("false", "true")[in_hierarchical in ImcUtils.AFFIRMATIVE_LIST])

        response = self.xml_query(method, WriteXmlOption.DIRTY, dump_xml)

        if response != None:
            return response
        return None
Ejemplo n.º 17
0
def _write_mo(mo):
    """ Method to return string representation of a managed object. """
    class_not_found = False
    if CoreUtils.find_class_id_in_mo_meta_ignore_case(mo.class_id) == None:
        class_not_found = True
    tab_size = 8
    out_str = "\n"
    if class_not_found:
        out_str += "Managed Object\t\t\t:\t" + str(ImcUtils.word_u(
            mo.class_id)) + "\n"
    else:
        out_str += "Managed Object\t\t\t:\t" + str(mo.prop_mo_meta.name) + "\n"
    out_str += "-" * len("Managed Object") + "\n"
    if not class_not_found:
        for prop in CoreUtils.get_property_list(mo.prop_mo_meta.name):
            #prop_meta = CoreUtils.get_mo_property_meta(mo.prop_mo_meta.name, prop)
            #if (prop_meta.access == MoPropertyMeta.Internal):
            #continue
            val = mo.get_attr(prop)
            #if val != None and val != "":
            out_str += str(prop).ljust(tab_size * 4) + ':' + str(val) + "\n"
    else:
        for prop in mo.__dict__:
            if prop in [
                    '_class_id', '_ManagedObject__xtra_property', '_handle',
                    'prop_mo_meta', '_dirty_mask', '_child'
            ]:
                continue
            val = mo.__dict__[prop]
            out_str += str(ImcUtils.word_u(prop)).ljust(
                tab_size * 4) + ':' + str(val) + "\n"
    if mo.__dict__.has_key('_ManagedObject__xtra_property'):
        for xtra_prop in mo.__dict__['_ManagedObject__xtra_property']:
            out_str += ('[X]' + str(ImcUtils.word_u(xtra_prop))).ljust(
                tab_size * 4) + ':' + str(
                    mo.__dict__['_ManagedObject__xtra_property']
                    [xtra_prop]) + "\n"

    out_str += str("Imc").ljust(tab_size * 4) + ':' + str(mo.handle.imc) + "\n"

    out_str += "\n"
    return out_str
Ejemplo n.º 18
0
    def to_managed_object(self):
        """
        Method creates and returns an object of ManagedObject class using the class_id and information from the
        Generic managed object.
        """
        from Imc import class_factory

        cln = ImcUtils.word_u(self._class_id)
        mo = class_factory(cln)
        if mo and isinstance(mo, ManagedObject) == True:
            meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(
                self._class_id)
            mo.set_handle(self._handle)
            for prop in self.properties:
                if ImcUtils.word_u(prop) in CoreUtils.get_property_list(
                        meta_class_id):
                    mo.set_attr(ImcUtils.word_u(prop), self.properties[prop])
                else:
                    ImcUtils.write_imc_warning(
                        "Property %s Not Exist in MO %s" %
                        (ImcUtils.word_u(prop), meta_class_id))

            if len(self._child):
                for child in self._child:
                    moch = child.to_managed_object()
                    mo.child.append(moch)
            return mo
        else:
            return None
Ejemplo n.º 19
0
    def to_managed_object(self):
        """
        Method creates and returns an object of ManagedObject class using the class_id and information from the
        Generic managed object.
        """
        from Imc import class_factory

        cln = ImcUtils.word_u(self._class_id)
        mo = class_factory(cln)
        if mo and isinstance(mo, ManagedObject) == True:
            meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(self._class_id)
            mo.set_handle(self._handle)
            for prop in self.properties:
                if ImcUtils.word_u(prop) in CoreUtils.get_property_list(meta_class_id):
                    mo.set_attr(ImcUtils.word_u(prop), self.properties[prop])
                else:
                    ImcUtils.write_imc_warning("Property %s Not Exist in MO %s" %(ImcUtils.word_u(prop), meta_class_id))

            if len(self._child):
                for child in self._child:
                    moch = child.to_managed_object()
                    mo.child.append(moch)
            return mo
        else:
            return None
Ejemplo n.º 20
0
def _translate_imc_managedobject(m_obj, xlate_map):
    """ Method used to translate a managedobject. This method is used in compare_imc_managedobject. """

    x_mo = m_obj.clone()
    x_mo.set_handle(m_obj.get_handle())

    if xlate_map != None:
        original_dn = x_mo.dn
        if original_dn in xlate_map:
            x_mometa = CoreUtils.get_mo_property_meta(
                ImcUtils.word_u(x_mo.class_id), "Meta")
            if x_mometa == None:
                ImcUtils.write_imc_warning(
                    '[Warning]: Could not translate [%s]' % (original_dn))
                return x_mo

            #Check for naming property
            match_obj = re.findall(r'(\[[^\]]+\])', x_mometa.rn)
            if match_obj:
                _update_mo_dn_along_with_naming_properties(
                    x_mo, x_mometa, xlate_map[original_dn])
            else:
                #print "Translating", x_mo.dn, " => ", xlate_map[original_dn]
                x_mo.dn = xlate_map[original_dn]
        else:
            original_dn = re.sub(r'[/]*[^/]+$', '', original_dn)
            while original_dn != None or original_dn == "":
                if not original_dn in xlate_map:
                    original_dn = re.sub(r'[/]*[^/]+$', '', original_dn)
                    continue

                new_dn = re.sub("^%s/" % (original_dn),
                                "%s/" % (xlate_map[original_dn]), x_mo.dn)
                #print "Translating", x_mo.dn, " => ", new_dn
                x_mo.dn = new_dn
                break

    return x_mo
Ejemplo n.º 21
0
    def set_attr(self, key, value):
        """ This method sets attribute of a Managed Object. """
        if CoreUtils.find_class_id_in_mo_meta_ignore_case(self._class_id) != None:
            if key in _MANAGED_OBJECT_META[self._class_id]:
                prop_meta = CoreUtils.get_mo_property_meta(self._class_id, key)

                if prop_meta.validate_property_value(value) == False:
                    #print "Validation Failure"
                    return False

                if prop_meta.mask != None:
                    self._dirty_mask |= prop_meta.mask

                self.__dict__[key] = value
            else:
                self.__xtra_property[key] = value
        else:
            # no such property
            self.__xtra_property[ImcUtils.word_u(key)] = value
Ejemplo n.º 22
0
    def set_attr(self, key, value):
        """ This method sets attribute of a Managed Object. """
        if CoreUtils.find_class_id_in_mo_meta_ignore_case(
                self._class_id) != None:
            if key in _MANAGED_OBJECT_META[self._class_id]:
                prop_meta = CoreUtils.get_mo_property_meta(self._class_id, key)

                if prop_meta.validate_property_value(value) == False:
                    #print "Validation Failure"
                    return False

                if prop_meta.mask != None:
                    self._dirty_mask |= prop_meta.mask

                self.__dict__[key] = value
            else:
                self.__xtra_property[key] = value
        else:
            # no such property
            self.__xtra_property[ImcUtils.word_u(key)] = value
Ejemplo n.º 23
0
    def write_xml(self, xml_doc=None, option=None, element_name=None):
        """create Xml Document Node using object attributes"""
        if xml_doc is None:
            xml_obj=Element(self._class_id)
        else:
            if element_name == None:
                xml_obj = SubElement(xml_doc,self._class_id)
            else:
                xml_obj = SubElement(xml_doc,element_name)
                               
#        if element_name == None:
#            xml_obj = xml_doc.createElement(self._class_id)
#        else:
#            xml_obj = xml_doc.createElement(element_name)

        for prop in self.__dict__['properties']:
            xml_obj.setAttribute(ImcUtils.word_l(prop), self.__dict__['properties'][prop])
        self.child_write_xml(xml_obj, option)
#        x_child = self.child_write_xml(xml_doc, option)
#        for xchild in x_child:
#            if xchild != None:
#                xml_obj.appendChild(xchild)
        return xml_obj
Ejemplo n.º 24
0
 def write_xml(self, xml_doc=None, option=None, element_name=None):
     """ Method writes the xml representation of the managed object. """
     if option == WriteXmlOption.DIRTY and not self.is_dirty():
         return
     if xml_doc is None:
         xml_obj = Element(self.prop_mo_meta.xml_attribute)
     else:
         if element_name == None:
             xml_obj = SubElement(xml_doc, self.prop_mo_meta.xml_attribute)
         else:
             xml_obj = SubElement(xml_doc, element_name)
     if CoreUtils.find_class_id_in_mo_meta_ignore_case(
             self._class_id) != None:
         for prop in CoreUtils.get_property_list(self._class_id):
             prop_meta = CoreUtils.get_mo_property_meta(
                 self._class_id, prop)
             #if (at_meta.access == MoPropertyMeta.Internal):
             #        continue
             #elif ((option != WriteXmlOption.DIRTY) or ((at_meta.mask != None) and (self._dirty_mask & at_meta.mask) != 0)):
             if option != WriteXmlOption.DIRTY or (
                     prop_meta.mask != None and
                 (self._dirty_mask & prop_meta.mask) != 0):
                 if self.get_attr(prop) != None:
                     #xml_obj.setAttribute(prop_meta.xml_attribute, self.get_attr(prop))
                     xml_obj.set(prop_meta.xml_attribute,
                                 self.get_attr(prop))
     #Adding xtraProperties from object into Xml query document
     for xtra_prop in self.__xtra_property:
         #xml_obj.setAttribute(ImcUtils.word_l(xtra_prop), self.__xtra_property[xtra_prop])
         xml_obj.set(ImcUtils.word_l(xtra_prop),
                     self.__xtra_property[xtra_prop])
     self.child_write_xml(xml_obj, option)
     #        x_child = self.child_write_xml(xml_obj, option)
     #        for xchild in x_child:
     #            if xchild != None:
     #                xml_obj.append(xchild)
     return xml_obj
Ejemplo n.º 25
0
    def add_imc_managedobject(self,
                              in_mo=None,
                              class_id=None,
                              params=None,
                              dump_xml=None):
        """
        Adds a Managed Object to IMC.

        - in_mo, if provided, it acts as a parent for the present operation.
          It should be None unless a username wants to define a parent scope.
          It can be a single MO or a list containing multiple managed objects.
        - class_id of the managed object/s to be added.
        - params contains semicolon (;) separated list of key/value pairs(key=value),
          that are used as filters for selecting specific managed objects.
          The key should be a valid property of the managed object to be added.
        """

        unknown_mo = False
        if class_id == None or class_id == "":
            raise ImcValidationException(
                '[Error]: add_imc_managedobject [Description]: class_id is Null'
            )

        meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(
            class_id)
        if meta_class_id != None:
            class_id = meta_class_id
            mo_meta = CoreUtils.get_mo_property_meta(class_id, "Meta")
        else:
            unknown_mo = True

        config_map = ConfigMap()
        rn = None
        dn = None
        #mo_meta = CoreUtils.get_mo_property_meta(class_id, "Meta")
        if params != None:
            keys = params.keys()
        else:
            keys = []

        if not unknown_mo:
            rn = mo_meta.rn
            for prop in CoreUtils.get_property_list(class_id):
                prop_meta = CoreUtils.get_mo_property_meta(class_id, prop)
                if prop_meta.access != MoPropertyMeta.NAMING:
                    continue
                naming_prop_found = False
                for key in keys:
                    if key.lower() == prop.lower():
                        rn = re.sub(r'\[%s\]' % prop, '%s' % params[key], rn)
                        naming_prop_found = True
                        break

                if naming_prop_found == False:
                    ImcUtils.write_imc_warning(
                        "[Warning]: add_imc_managedobject [Description]:Expected NAMING Property %s for ClassId %s not found"
                        % (prop, class_id))
                    rn = re.sub(r'\[%s\]' % prop, '%s' % "", rn)

        obj = ManagedObject(class_id)

        for prop in keys:
            if not unknown_mo:
                prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(
                    class_id, prop)
                if prop_mo_meta != None:
                    if prop.lower() == "rn" or prop.lower() == "dn":
                        pass
                    elif prop_mo_meta.access == MoPropertyMeta.READ_ONLY:
                        ImcUtils.write_imc_warning(
                            "[Warning]: AddManagedObject [Description]:Attempt to add non-writeable property %s in Class %s"
                            % (prop, class_id))

                    if prop.lower() == "rn":
                        if in_mo == None or not isinstance(
                                in_mo, list) or len(in_mo) == 0:
                            ImcUtils.write_imc_warning(
                                "[Warning]: AddManagedObject [Description]:Ignoring Rn since no parent provided"
                            )
                        if rn != params[prop]:
                            ImcUtils.write_imc_warning(
                                "[Warning]: AddManagedObject [Description]:Rn Mismatch. Provided %s Computed %s. Ignoring Computed Rn"
                                % (params[prop], rn))
                            rn = params[
                                prop]  #bug fix. if Rn and Name are both provided by username then Rn will get preference.

                    if prop.lower() == "dn":
                        dn = params[prop]

                    obj.set_attr(prop_mo_meta.name, str(params[prop]))
                else:
                    #Known MO - Unknown Property
                    obj.set_attr(ImcUtils.word_l(prop), str(params[prop]))
            else:
                #Unknown MO
                if prop.lower() == "dn":
                    dn = params[prop]

                if prop.lower() == "rn":
                    rn = params[prop]
                if rn == None:
                    rn = ""

                obj.set_attr(ImcUtils.word_l(prop), str(params[prop]))

        obj.set_attr("Status", Status().CREATED)

        if dn != None and dn != "":
            obj.set_attr("Dn", dn)
            pair = Pair()
            #pair.set_attr("Key", obj.dn)
            pair.set_attr("Key", obj.get_attr("Dn"))
            pair.add_child(obj)
            config_map.add_child(pair)
        elif in_mo != None and isinstance(in_mo, list) and len(in_mo) > 0:
            for mo in in_mo:
                pdn = mo.get_attr("Dn")
                if pdn != None:
                    obj.set_attr("Dn", pdn + '/' + rn)
                    pair = Pair()
                    #pair.set_attr("Key", obj.dn)
                    pair.set_attr("Key", obj.get_attr("Dn"))
                    pair.add_child(obj.clone())
                    config_map.add_child(pair)

        if config_map.get_child_count() == 0:
            ImcUtils.write_imc_warning(
                '[Warning]: AddManagedObject [Description]: Nothing to Add')
            return None

        output_molist = []
        for pair in config_map.child:
            in_config = ConfigConfig()
            for mo in pair.child:
                in_config.add_child(mo)
            ccm = self.config_conf_mo(dn=pair.Key,
                                      in_config=in_config,
                                      in_hierarchical=YesOrNo.FALSE,
                                      dump_xml=dump_xml)
            if ccm.error_code == 0:
                molist = []
                for child in ccm.OutConfig.child:
                    if isinstance(child, Pair) == True:
                        for mo in child.child:
                            molist.append(mo)
                    elif isinstance(child, ManagedObject) == True:
                        molist.append(child)
                output_molist.extend(molist)
            else:
                raise ImcException(ccm.error_code, ccm.error_descr)

        return output_molist
Ejemplo n.º 26
0
    def set_imc_managedobject(self,
                              in_mo,
                              class_id=None,
                              params=None,
                              dump_xml=None):
        """
        Modifies Managed Object in IMC.

        - in_mo, if provided, it acts as the target object for the present operation.
          It should be None unless a username wants to provide an in_mo.
          It can be a single MO or a list containing multiple managed objects.
        - class_id of the managed object/s to be removed.
        - params contains semicolon (;) separated list of key/value pairs(key=value),
          that are used as filters for selecting specific managed objects.
          The key should be a valid property of the managed object to be modified.
        """

        #unknown_mo = False
        dn = None
        obj = None
        config_map = None
        dn_param_set = False

        if params != None:
            keys = params.keys()
        else:
            keys = []

        for key in keys:
            if key.lower() == "dn":
                # ClassId And dn Specified - No Parent Necessary
                dn_param_set = True
                dn = params[key]

        if in_mo == None or not isinstance(in_mo, list) or len(in_mo) == 0:
            if not dn_param_set:
                if class_id == None or class_id == "":
                    raise ImcValidationException(
                        '[Error]: set_imc_managedobject [Description]: in_mo and ClassId are both not specified'
                    )
                else:
                    raise ImcValidationException(
                        '[Error]: set_imc_managedobject [Description]: in_mo and dn are both not specified'
                    )
            else:
                if class_id == None or class_id == "":
                    raise ImcValidationException(
                        '[Error]: set_imc_managedobject [Description]: in_mo and ClassId are both not specified'
                    )
                else:
                    meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(
                        class_id)
                    if meta_class_id != None:
                        class_id = meta_class_id
                    #    mo_meta = CoreUtils.get_mo_property_meta(class_id, "Meta")
                    #else:
                    #    unknown_mo = True

                    obj = ManagedObject(class_id)
                    for prop in keys:
                        prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(
                            class_id, prop)
                        if prop_mo_meta != None:
                            if prop.lower() == "rn" or prop.lower() == "dn":
                                pass
                            elif prop_mo_meta.access == MoPropertyMeta.READ_ONLY:
                                ImcUtils.write_imc_warning(
                                    "[Warning]: SetManagedObject [Description] Attempt to set non-writable property %s in Class %s"
                                    % (prop, class_id))

                            obj.set_attr(prop_mo_meta.name, str(params[prop]))
                        else:
                            #Sets the unknown property/value as Xtra_property in obj
                            obj.set_attr(ImcUtils.word_l(prop),
                                         str(params[prop]))

                    obj.set_attr("Dn", dn)
                    obj.set_attr("Status", Status().MODIFIED)
                    pair = Pair()
                    pair.set_attr("Key", obj.get_attr("Dn"))
                    pair.add_child(obj)
                    config_map = ConfigMap()
                    config_map.add_child(pair)

        else:
            if class_id != None and class_id != "":
                ImcUtils.write_imc_warning(
                    "[Warning]: SetManagedObject [Description] ClassId <%s> is ignored with InMo input"
                    % (class_id))

            config_map = ConfigMap()
            for mo in in_mo:
                obj = ManagedObject(mo.prop_mo_meta.name)
                dn = mo.get_attr("Dn")
                class_id = mo.prop_mo_meta.name

                for prop in keys:
                    prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(
                        class_id, prop)
                    if prop_mo_meta != None:
                        if prop.lower() == "rn" or prop.lower() == "dn":
                            pass
                        elif prop_mo_meta.access == MoPropertyMeta.READ_ONLY:
                            ImcUtils.write_imc_warning(
                                "[Warning]: SetManagedObject [Description] Attempt to set non-writeable property %s in Class %s"
                                % (prop, class_id))

                        obj.set_attr(prop_mo_meta.name, str(params[prop]))
                    else:
                        #Sets the unknown property/value as Xtra_property in obj
                        obj.set_attr(ImcUtils.word_l(prop), str(params[prop]))

                obj.set_attr("Dn", dn)
                obj.set_attr("Status", Status.MODIFIED)
                pair = Pair()
                pair.set_attr("Key", obj.get_attr("Dn"))
                pair.add_child(obj)
                config_map.add_child(pair)

        output_molist = []
        for pair in config_map.child:
            in_config = ConfigConfig()
            for mo in pair.child:
                in_config.add_child(mo)

            ccm = self.config_conf_mo(dn=pair.Key,
                                      in_config=in_config,
                                      in_hierarchical=YesOrNo.FALSE,
                                      dump_xml=dump_xml)

            if ccm.error_code == 0:
                molist = []
                for child in ccm.OutConfig.child:
                    if isinstance(child, Pair) == True:
                        for mo in child.child:
                            molist.append(mo)
                    elif isinstance(child, ManagedObject) == True:
                        molist.append(child)
                output_molist.extend(molist)
            else:
                raise ImcException(ccm.error_code, ccm.error_descr)

        return output_molist
Ejemplo n.º 27
0
def import_imc_session(file_path, key):
    """
    This operation will do a login to each IMC which is present in credential file.

    - file_path specifies the path of the credential file.
    - key specifies string used for secure encryption while export_imc_session operation.
    """
    from ImcUtilityCore import _ImcLoginXml

    if file_path is None:
        raise ImcValidationException('[Error]: Please provide file_path')

    if key is None:
        raise ImcValidationException('[Error]: Please provide key')

    if not os.path.isfile(file_path) or not os.path.exists(file_path):
        raise ImcValidationException('[Error]: File <%s> does not exist ' %(file_path))

    doc = xml.dom.minidom.parse(file_path)
    top_node = doc.documentElement
    #print top_node.localName

    if top_node is None or top_node.localName != _ImcLoginXml.IMC_HANDLES:
        return None

    if top_node.hasChildNodes():
        child_list = top_node.childNodes
        child_count = len(child_list)
        for count in range(child_count):
            child_node = child_list.item(count)
            if child_node.nodeType != Node.ELEMENT_NODE:
                continue

            if child_node.localName != _ImcLoginXml.IMC:
                continue

            lname = None
            lusername = None
            lpassword = None
            lnossl = False
            lport = None

            if child_node.hasAttribute(_ImcLoginXml.NAME):
                lname = child_node.getAttribute(_ImcLoginXml.NAME)
            if child_node.hasAttribute(_ImcLoginXml.USER_NAME):
                lusername = child_node.getAttribute(_ImcLoginXml.USER_NAME)
            if child_node.hasAttribute(_ImcLoginXml.PASSWORD):
                #lpassword = p3_decrypt(child_node.getAttribute(_ImcLoginXml.PASSWORD), key)
                lpassword = ImcUtils.decrypt_password(child_node.getAttribute(_ImcLoginXml.PASSWORD), key)
            if child_node.hasAttribute(_ImcLoginXml.NO_SSL):
                lnossl = child_node.getAttribute(_ImcLoginXml.NO_SSL)
            if child_node.hasAttribute(_ImcLoginXml.PORT):
                lport = child_node.getAttribute(_ImcLoginXml.PORT)

            # Process login
            if lname is None or lusername == None or lpassword == None:
                ImcUtils.write_imc_warning("[Warning] Insufficient information for login ...")
                continue
            try:

                handle = ImcHandle()
                handle.login(name=lname, username=lusername, password=lpassword, nossl=lnossl, port=lport)

            except Exception, err:
                ImcUtils.write_imc_warning("[Connection Error<%s>] %s" %(lname, str(err)))
Ejemplo n.º 28
0
    def get_imc_managedobject(self,
                              in_mo=None,
                              class_id=None,
                              params=None,
                              in_hierarchical=False,
                              dump_xml=None):
        """
        Gets Managed Object from IMC.

        - in_mo, if provided, it acts as a parent for the present operation.
          It should be None unless a username wants to define a parent scope.
          It can be a single MO or a list containing multiple managed objects.
        - class_id of the managed object/s to get.
        - params contains semicolon (;) separated list of key/value pairs(key=value),
          that are used as filters for selecting specific managed objects.
          The key should be a valid property of the managed object to be retrieved.
        - in_hierarchical, Explores hierarchy if true, else returns managed objects at a single level.
        """

        if params != None:
            keys = params.keys()
        else:
            keys = []

        out_config = []
        meta_class_id = ""
        if class_id != None and class_id != "":
            #ClassId param set
            meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(
                class_id)
            if meta_class_id == None:
                meta_class_id = class_id
                mo_meta = MoMeta(ImcUtils.word_u(class_id),
                                 ImcUtils.word_l(class_id), "", "",
                                 "InputOutput", ManagedObject.DUMMYDIRTY, [],
                                 [], [], [], [])
            else:
                mo_meta = CoreUtils.get_mo_property_meta(meta_class_id, "Meta")

            if mo_meta == None:
                raise ImcValidationException(
                    '[Error]: get_imc_managedobject: mo_meta for class_id [%s] is not valid'
                    % (class_id))
                #return None

            if in_mo != None and isinstance(in_mo, list) and len(in_mo) > 0:
                for mo in in_mo:
                    crc = self.config_resolve_children(mo_meta.xml_attribute,
                                                       mo.get_attr("Dn"),
                                                       in_hierarchical,
                                                       dump_xml)
                    if crc.error_code != 0:
                        raise ImcException(crc.error_code, crc.error_descr)

                    for child in crc.OutConfigs.child:
                        out_config.append(child)
            else:
                crc = self.config_resolve_class(mo_meta.xml_attribute,
                                                in_hierarchical, dump_xml)
                if crc.error_code != 0:
                    raise ImcException(crc.error_code, crc.error_descr)
                for child in crc.OutConfigs.child:
                    out_config.append(child)
        else:
            dn = ""
            for key in keys:
                if key.lower() == "dn":
                    dn = params[key]
            if not dn:
                raise ImcValidationException(
                    '[Error]: Please provide ClassId or dn')
            cr_dn = self.config_resolve_dn(dn, in_hierarchical, dump_xml)
            if cr_dn.error_code != 0:
                raise ImcException(cr_dn.error_code, cr_dn.error_descr)
            for child in cr_dn.OutConfig.child:
                out_config.append(child)

        #client side filtering starts
        for key in keys:
            prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(
                meta_class_id, key)
            if prop_mo_meta != None:
                attr_name = prop_mo_meta.xml_attribute
            else:
                attr_name = key
            for mo in out_config[:]:
                attr_name = attr_name[0].upper() + attr_name[1:]
                if mo.get_attr(attr_name) != params[key]:
                    out_config.remove(mo)
        #client side filtering ends

        molist = []
        current_molist = out_config
        while len(current_molist) > 0:
            child_molist = []
            for mo in current_molist:
                molist.append(mo)
                while mo.get_child_count() > 0:
                    for child in mo.child:
                        mo.remove_child(child)
                        if child.__dict__.has_key('Dn'):
                            if child.Dn == None or child.Dn == "":
                                child.set_attr("Dn", mo.Dn + '/' + child.Rn)
                                child.mark_clean()
                        else:
                            child.set_attr("Dn", mo.Dn + '/' + child.Rn)
                            child.mark_clean()
                        child_molist.append(child)
                        break
            current_molist = child_molist

        return molist
Ejemplo n.º 29
0
def backup_imc(handle, remotehost, remotefile, protocol, username, password, passphrase=None, timeout_sec=ImcConstant.TIME_OUT_IN_SEC, dump_xml=None):
    """
    Creates and downloads the backup of IMC.

    - remotehost    specifies the host where username need to download the backup.
    - remotefile    specifies the path on remotehost where username need to download the backup.
    - protocol        specifies the protocol used for transferring the file to remotehost.
    - username        specifies the username credential to login to remotehost.
    - password        specifies the password credential to login to remotehost.
    - timeout_sec     specifies the time in seconds for which method waits for the backUp file
                    to generate else exit. Default is 600 Seconds.
    """
    from ImcMos import MgmtBackup

    if timeout_sec == None or timeout_sec == "" or timeout_sec < 1:
        timeout_sec = ImcConstant.TIME_OUT_IN_SEC
        ImcUtils.write_imc_warning('[Warning]: Inappropriate <timeoutsec>. Chosen default value is 600 Seconds')

    #dn = "sys/export-config"
    #dn = ImcUtils.make_dn([ManagedObject(NamingId.TOP_SYSTEM).make_rn(),ManagedObject(NamingId.MGMT_BACKUP).make_rn()])
    dn = CoreUtils.make_dn([CoreUtils.make_rn(NamingId.TOP_SYSTEM), CoreUtils.make_rn(NamingId.MGMT_BACKUP)])

    mgmt_backup = ManagedObject(NamingId.MGMT_BACKUP)

    mgmt_backup.Hostname = remotehost
    mgmt_backup.User = username
    mgmt_backup.Pwd = password
    mgmt_backup.Proto = protocol
    mgmt_backup.RemoteFile = remotefile
    mgmt_backup.dn = dn
    mgmt_backup.AdminState = MgmtBackup.CONST_ADMIN_STATE_ENABLED
    mgmt_backup.Status = Status.MODIFIED
    mgmt_backup.Passphrase = passphrase

    in_config = ConfigConfig()
    in_config.add_child(mgmt_backup)
    response = handle.config_conf_mo(dn, in_config=in_config, in_hierarchical=YesOrNo.FALSE, dump_xml=dump_xml)
    if response.error_code != 0:
        raise ImcException(response.error_code, response.error_descr)
        #raise Exception('[Error]: backup_imc [Code]:' + ccm.error_code + ' [Description]:' + ccm.error_descr)

    time.sleep(10) #Wait for 10 seconds before start checking.

    duration = timeout_sec
    poll_interval = ImcConstant.POLL_INTERVAL_IN_SEC

    cr_dn = None
    status = False

    while True:
        cr_dn = handle.config_resolve_dn(dn, in_hierarchical=YesOrNo.FALSE, dump_xml=dump_xml)
        if cr_dn.error_code == 0:
            for each_mgmt_dn in cr_dn.OutConfig.child:
                if each_mgmt_dn.AdminState == MgmtBackup.CONST_ADMIN_STATE_DISABLED:
                    if each_mgmt_dn.FsmStageDescr == "Completed successfully":
                        status = True
                    if each_mgmt_dn.FsmStageDescr == "Error":
                        raise ImcValidationException("Failed to export the CIMC configuration file." + "Error Code: " + each_mgmt_dn.FsmRmtInvErrCode + " Error Description: " + each_mgmt_dn.FsmRmtInvErrDescr)

        else:
            raise ImcException(cr_dn.error_code, cr_dn.error_descr)

        if status:
            break

        time.sleep(min(duration, poll_interval))
        duration = max(0, (duration-poll_interval))

        if duration == 0:
            raise ImcValidationException('Backup operation in progress but utility backup_imc timed out. Exiting Method backup_imc')

    return cr_dn.OutConfig.child
Ejemplo n.º 30
0
    def xml_query(self, method, options, dump_xml=None):
        """
        xml_query method opens a connection to URL, sends the xmlQuery string to URL location,
        and returns result.
        Prepares objects from XML query result and returns external method response.
        """
        #import sys
        #if not sys.version_info < (2, 5):
        #    from functools import partial
        #    import ssl
        #    ssl.wrap_socket = partial(ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1)

        if dump_xml == None:
            dump_xml = self.__dump_xml

        try:
            #xml_doc = xml.dom.minidom.Document()
            #xml_doc.appendChild(method.write_xml(xml_doc, options))
            #print method.__dict__
            xml_doc = method.write_xml(option=options)

            uri = self.uri() + '/nuova'
            if dump_xml in ImcUtils.AFFIRMATIVE_LIST:
                print '%s ====> %s' % (self.__imc, ET.tostring(xml_doc))

            if self.__proxy is None:
                if self.__nossl:
                    req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
                    opener = urllib2.build_opener(
                        ImcUtils.SmartRedirectHandler())
                    resp = opener.open(req)
                    if type(resp) is list:
                        if len(resp) == 2 and (resp[0] == 302
                                               or resp[0] == 301):
                            uri = resp[1]
                            req = urllib2.Request(url=uri,
                                                  data=ET.tostring(xml_doc))
                            resp = urllib2.urlopen(req)
                else:
                    req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
                    opener = urllib2.build_opener(ImcUtils.TLS1Handler())
                    resp = opener.open(req)
            else:
                proxy_handler = urllib2.ProxyHandler({
                    'http': self.__proxy,
                    'https': self.__proxy
                })

                if self.__nossl:
                    req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
                    opener = urllib2.build_opener(
                        proxy_handler, ImcUtils.SmartRedirectHandler())
                    resp = opener.open(req)

                    if type(resp) is list:
                        if len(resp) == 2 and (resp[0] == 302
                                               or resp[0] == 301):
                            uri = resp[1]
                            req = urllib2.Request(url=uri,
                                                  data=ET.tostring(xml_doc))
                            opener = urllib2.build_opener(proxy_handler)
                            resp = opener.open(req)
                else:
                    req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
                    opener = urllib2.build_opener(ImcUtils.TLS1Handler(),
                                                  proxy_handler)
                    resp = opener.open(req)

            rsp = resp.read()

            if dump_xml in ImcUtils.AFFIRMATIVE_LIST:
                print '%s <==== %s' % (self.__imc, rsp)

            response = ExternalMethod(method.prop_mo_meta.name)
            root_element = ET.fromstring(rsp)
            response.load_from_xml(root_element, self)
            return response
        except Exception:
            raise
Ejemplo n.º 31
0
    def add_imc_managedobject(self, in_mo=None, class_id=None, params=None, dump_xml=None):
        """
        Adds a Managed Object to IMC.

        - in_mo, if provided, it acts as a parent for the present operation.
          It should be None unless a username wants to define a parent scope.
          It can be a single MO or a list containing multiple managed objects.
        - class_id of the managed object/s to be added.
        - params contains semicolon (;) separated list of key/value pairs(key=value),
          that are used as filters for selecting specific managed objects.
          The key should be a valid property of the managed object to be added.
        """

        unknown_mo = False
        if class_id == None or class_id == "":
            raise ImcValidationException('[Error]: add_imc_managedobject [Description]: class_id is Null')

        meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(class_id)
        if meta_class_id != None:
            class_id = meta_class_id
            mo_meta = CoreUtils.get_mo_property_meta(class_id, "Meta")
        else:
            unknown_mo = True

        config_map = ConfigMap()
        rn = None
        dn = None
        #mo_meta = CoreUtils.get_mo_property_meta(class_id, "Meta")
        if params != None:
            keys = params.keys()
        else:
            keys = []

        if not unknown_mo:
            rn = mo_meta.rn
            for prop in CoreUtils.get_property_list(class_id):
                prop_meta = CoreUtils.get_mo_property_meta(class_id, prop)
                if prop_meta.access != MoPropertyMeta.NAMING:
                    continue
                naming_prop_found = False
                for key in keys:
                    if key.lower() == prop.lower():
                        rn = re.sub(r'\[%s\]' % prop, '%s' % params[key], rn)
                        naming_prop_found = True
                        break

                if naming_prop_found == False:
                    ImcUtils.write_imc_warning("[Warning]: add_imc_managedobject [Description]:Expected NAMING Property %s for ClassId %s not found" %(prop, class_id))
                    rn = re.sub(r'\[%s\]' % prop, '%s' % "", rn)

        obj = ManagedObject(class_id)

        for prop in keys:
            if not unknown_mo:
                prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(class_id, prop)
                if prop_mo_meta != None:
                    if prop.lower() == "rn" or prop.lower() == "dn":
                        pass
                    elif prop_mo_meta.access == MoPropertyMeta.READ_ONLY:
                        ImcUtils.write_imc_warning("[Warning]: AddManagedObject [Description]:Attempt to add non-writeable property %s in Class %s" %(prop, class_id))

                    if prop.lower() == "rn":
                        if in_mo == None or not isinstance(in_mo, list) or len(in_mo) == 0:
                            ImcUtils.write_imc_warning("[Warning]: AddManagedObject [Description]:Ignoring Rn since no parent provided")
                        if rn != params[prop]:
                            ImcUtils.write_imc_warning("[Warning]: AddManagedObject [Description]:Rn Mismatch. Provided %s Computed %s. Ignoring Computed Rn" %(params[prop], rn))
                            rn = params[prop]#bug fix. if Rn and Name are both provided by username then Rn will get preference.

                    if prop.lower() == "dn":
                        dn = params[prop]

                    obj.set_attr(prop_mo_meta.name, str(params[prop]))
                else:
                    #Known MO - Unknown Property
                    obj.set_attr(ImcUtils.word_l(prop), str(params[prop]))
            else:
                #Unknown MO
                if prop.lower() == "dn":
                    dn = params[prop]

                if prop.lower() == "rn":
                    rn = params[prop]
                if rn == None:
                    rn = ""

                obj.set_attr(ImcUtils.word_l(prop), str(params[prop]))

        obj.set_attr("Status", Status().CREATED)

        if dn != None and dn != "":
            obj.set_attr("Dn", dn)
            pair = Pair()
            #pair.set_attr("Key", obj.dn)
            pair.set_attr("Key", obj.get_attr("Dn"))
            pair.add_child(obj)
            config_map.add_child(pair)
        elif in_mo != None and isinstance(in_mo, list) and len(in_mo) > 0:
            for mo in in_mo:
                pdn = mo.get_attr("Dn")
                if pdn != None:
                    obj.set_attr("Dn", pdn + '/' +rn)
                    pair = Pair()
                    #pair.set_attr("Key", obj.dn)
                    pair.set_attr("Key", obj.get_attr("Dn"))
                    pair.add_child(obj.clone())
                    config_map.add_child(pair)

        if config_map.get_child_count() == 0:
            ImcUtils.write_imc_warning('[Warning]: AddManagedObject [Description]: Nothing to Add')
            return None

        output_molist = []
        for pair in config_map.child:
            in_config = ConfigConfig()
            for mo in pair.child:
                in_config.add_child(mo)
            ccm = self.config_conf_mo(dn=pair.Key, in_config=in_config, in_hierarchical=YesOrNo.FALSE, dump_xml=dump_xml)
            if ccm.error_code == 0:
                molist = []
                for child in ccm.OutConfig.child:
                    if isinstance(child, Pair) == True:
                        for mo in child.child:
                            molist.append(mo)
                    elif isinstance(child, ManagedObject) == True:
                        molist.append(child)
                output_molist.extend(molist)
            else:
                raise ImcException(ccm.error_code, ccm.error_descr)

        return output_molist
Ejemplo n.º 32
0
    def set_imc_managedobject(self, in_mo, class_id=None, params=None, dump_xml=None):
        """
        Modifies Managed Object in IMC.

        - in_mo, if provided, it acts as the target object for the present operation.
          It should be None unless a username wants to provide an in_mo.
          It can be a single MO or a list containing multiple managed objects.
        - class_id of the managed object/s to be removed.
        - params contains semicolon (;) separated list of key/value pairs(key=value),
          that are used as filters for selecting specific managed objects.
          The key should be a valid property of the managed object to be modified.
        """

        #unknown_mo = False
        dn = None
        obj = None
        config_map = None
        dn_param_set = False

        if params != None:
            keys = params.keys()
        else:
            keys = []

        for key in keys:
            if key.lower() == "dn":
                # ClassId And dn Specified - No Parent Necessary
                dn_param_set = True
                dn = params[key]

        if in_mo == None or not isinstance(in_mo, list) or len(in_mo) == 0:
            if not dn_param_set:
                if class_id == None or class_id == "":
                    raise ImcValidationException('[Error]: set_imc_managedobject [Description]: in_mo and ClassId are both not specified')
                else:
                    raise ImcValidationException('[Error]: set_imc_managedobject [Description]: in_mo and dn are both not specified')
            else:
                if class_id == None or class_id == "":
                    raise ImcValidationException('[Error]: set_imc_managedobject [Description]: in_mo and ClassId are both not specified')
                else:
                    meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(class_id)
                    if meta_class_id != None:
                        class_id = meta_class_id
                    #    mo_meta = CoreUtils.get_mo_property_meta(class_id, "Meta")
                    #else:
                    #    unknown_mo = True

                    obj = ManagedObject(class_id)
                    for prop in keys:
                        prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(class_id, prop)
                        if prop_mo_meta != None:
                            if prop.lower() == "rn" or prop.lower() == "dn":
                                pass
                            elif prop_mo_meta.access == MoPropertyMeta.READ_ONLY:
                                ImcUtils.write_imc_warning("[Warning]: SetManagedObject [Description] Attempt to set non-writable property %s in Class %s" %(prop, class_id))

                            obj.set_attr(prop_mo_meta.name, str(params[prop]))
                        else:
                            #Sets the unknown property/value as Xtra_property in obj
                            obj.set_attr(ImcUtils.word_l(prop), str(params[prop]))

                    obj.set_attr("Dn", dn)
                    obj.set_attr("Status", Status().MODIFIED)
                    pair = Pair()
                    pair.set_attr("Key", obj.get_attr("Dn"))
                    pair.add_child(obj)
                    config_map = ConfigMap()
                    config_map.add_child(pair)

        else:
            if class_id != None and class_id != "":
                ImcUtils.write_imc_warning("[Warning]: SetManagedObject [Description] ClassId <%s> is ignored with InMo input" %(class_id))

            config_map = ConfigMap()
            for mo in in_mo:
                obj = ManagedObject(mo.prop_mo_meta.name)
                dn = mo.get_attr("Dn")
                class_id = mo.prop_mo_meta.name

                for prop in keys:
                    prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(class_id, prop)
                    if prop_mo_meta != None:
                        if prop.lower() == "rn" or prop.lower() == "dn":
                            pass
                        elif prop_mo_meta.access == MoPropertyMeta.READ_ONLY:
                            ImcUtils.write_imc_warning("[Warning]: SetManagedObject [Description] Attempt to set non-writeable property %s in Class %s" %(prop, class_id))

                        obj.set_attr(prop_mo_meta.name, str(params[prop]))
                    else:
                        #Sets the unknown property/value as Xtra_property in obj
                        obj.set_attr(ImcUtils.word_l(prop), str(params[prop]))

                obj.set_attr("Dn", dn)
                obj.set_attr("Status", Status.MODIFIED)
                pair = Pair()
                pair.set_attr("Key", obj.get_attr("Dn"))
                pair.add_child(obj)
                config_map.add_child(pair)

        output_molist = []
        for pair in config_map.child:
            in_config = ConfigConfig()
            for mo in pair.child:
                in_config.add_child(mo)

            ccm = self.config_conf_mo(dn=pair.Key, in_config=in_config, in_hierarchical=YesOrNo.FALSE, dump_xml=dump_xml)

            if ccm.error_code == 0:
                molist = []
                for child in ccm.OutConfig.child:
                    if isinstance(child, Pair) == True:
                        for mo in child.child:
                            molist.append(mo)
                    elif isinstance(child, ManagedObject) == True:
                        molist.append(child)
                output_molist.extend(molist)
            else:
                raise ImcException(ccm.error_code, ccm.error_descr)

        return output_molist
Ejemplo n.º 33
0
    def get_imc_managedobject(self, in_mo=None, class_id=None, params=None, in_hierarchical=False, dump_xml=None):
        """
        Gets Managed Object from IMC.

        - in_mo, if provided, it acts as a parent for the present operation.
          It should be None unless a username wants to define a parent scope.
          It can be a single MO or a list containing multiple managed objects.
        - class_id of the managed object/s to get.
        - params contains semicolon (;) separated list of key/value pairs(key=value),
          that are used as filters for selecting specific managed objects.
          The key should be a valid property of the managed object to be retrieved.
        - in_hierarchical, Explores hierarchy if true, else returns managed objects at a single level.
        """

        if params != None:
            keys = params.keys()
        else:
            keys = []

        out_config = []
        meta_class_id = ""
        if class_id != None and class_id != "":
            #ClassId param set
            meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(class_id)
            if meta_class_id == None:
                meta_class_id = class_id
                mo_meta = MoMeta(ImcUtils.word_u(class_id), ImcUtils.word_l(class_id), "", "", "InputOutput", ManagedObject.DUMMYDIRTY, [], [], [], [], [])
            else:
                mo_meta = CoreUtils.get_mo_property_meta(meta_class_id, "Meta")

            if mo_meta == None:
                raise ImcValidationException('[Error]: get_imc_managedobject: mo_meta for class_id [%s] is not valid' %(class_id))
                #return None

            if in_mo != None and isinstance(in_mo, list) and len(in_mo) > 0:
                for mo in in_mo:
                    crc = self.config_resolve_children(mo_meta.xml_attribute, mo.get_attr("Dn"), in_hierarchical, dump_xml)
                    if crc.error_code != 0:
                        raise ImcException(crc.error_code, crc.error_descr)

                    for child in crc.OutConfigs.child:
                        out_config.append(child)
            else:
                crc = self.config_resolve_class(mo_meta.xml_attribute, in_hierarchical, dump_xml)
                if crc.error_code != 0:
                    raise ImcException(crc.error_code, crc.error_descr)
                for child in crc.OutConfigs.child:
                    out_config.append(child)
        else:
            dn = ""
            for key in keys:
                if key.lower() == "dn":
                    dn = params[key]
            if not dn:
                raise ImcValidationException('[Error]: Please provide ClassId or dn')
            cr_dn = self.config_resolve_dn(dn, in_hierarchical, dump_xml)
            if cr_dn.error_code != 0:
                raise ImcException(cr_dn.error_code, cr_dn.error_descr)
            for child in cr_dn.OutConfig.child:
                out_config.append(child)

        #client side filtering starts
        for key in keys:
            prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(meta_class_id, key)
            if prop_mo_meta != None:
                attr_name = prop_mo_meta.xml_attribute
            else:
                attr_name = key
            for mo in out_config[:]:
                attr_name = attr_name[0].upper() + attr_name[1:]
                if mo.get_attr(attr_name) != params[key]:
                    out_config.remove(mo)
        #client side filtering ends

        molist = []
        current_molist = out_config
        while len(current_molist) > 0:
            child_molist = []
            for mo in current_molist:
                molist.append(mo)
                while mo.get_child_count() > 0:
                    for child in mo.child:
                        mo.remove_child(child)
                        if child.__dict__.has_key('Dn'):
                            if child.Dn == None or child.Dn == "":
                                child.set_attr("Dn", mo.Dn + '/' + child.Rn)
                                child.mark_clean()
                        else:
                            child.set_attr("Dn", mo.Dn + '/' + child.Rn)
                            child.mark_clean()
                        child_molist.append(child)
                        break
            current_molist = child_molist

        return molist
Ejemplo n.º 34
0
def export_imc_session(file_path, key, merge=YesOrNo.FALSE):
    """
    Stores the credential of currently logged in IMC in current session to a file. Password will be stored in encrypted format using key.

    - file_path specifies the path of the credential file.
    - key specifies any string used for secure encryption.
    - merge should be set as False unless username wants to append the existing credential file with new credential.
    """
    from ImcUtilityCore import _ImcLoginXml

    if file_path is None:
        raise ImcValidationException('[Error]: Please provide file_path')

    if key is None:
        raise ImcValidationException('[Error]: Please provide key')

    doc = xml.dom.minidom.Document()
    node_list = None

    if merge in ImcUtils.AFFIRMATIVE_LIST and os.path.isfile(file_path):#isfile() checks for file. exists() return true for directory as well
        doc = xml.dom.minidom.parse(file_path)
        node_list = doc.documentElement.childNodes
    else:
        doc.appendChild(doc.createElement(_ImcLoginXml.IMC_HANDLES))

    h_imc_array = default_imc.values()

    if h_imc_array != None:
        for h_imc in h_imc_array:
            updated = False
            if node_list != None:
                for child_node in node_list:
                    if child_node.nodeType != Node.ELEMENT_NODE:
                        continue

                    elem = child_node
                    if not elem.hasAttribute(_ImcLoginXml.NAME) or not elem.hasAttribute(_ImcLoginXml.USER_NAME):
                        continue
                    if elem.getAttribute(_ImcLoginXml.NAME) != h_imc.name or elem.getAttribute(_ImcLoginXml.USER_NAME) != h_imc.username:
                        continue

                    if h_imc.nossl:
                        elem.setAttribute(_ImcLoginXml.NO_SSL, h_imc.nossl)
                    elif elem.hasAttribute(_ImcLoginXml.NO_SSL):
                        elem.removeAttribute(_ImcLoginXml.NO_SSL)

                    if (h_imc.nossl and h_imc.port != 80) or (not h_imc.nossl and h_imc.port != 443):
                        elem.setAttribute(_ImcLoginXml.PORT, h_imc.port)
                    elif elem.hasAttribute(_ImcLoginXml.PORT):
                        elem.removeAttribute(_ImcLoginXml.PORT)

                    #elem.setAttribute(_ImcLoginXml.PASSWORD, p3_encrypt(h_imc.__password,key))
                    elem.setAttribute(_ImcLoginXml.PASSWORD, ImcUtils.encrypt_password(h_imc.password, key))
                    updated = True
                    break

            if updated:
                continue

            node = doc.createElement(_ImcLoginXml.IMC)
            attr = doc.createAttribute(_ImcLoginXml.NAME)
            attr.value = h_imc.name
            node.setAttributeNode(attr)
            attr = doc.createAttribute(_ImcLoginXml.USER_NAME)
            attr.value = h_imc.username
            node.setAttributeNode(attr)

            if h_imc.nossl:
                attr = doc.createAttribute(_ImcLoginXml.NO_SSL)
                attr.value = h_imc.nossl
                node.setAttributeNode(attr)

            if (h_imc.nossl and h_imc.port != 80) or (not h_imc.nossl and h_imc.port != 443):
                attr = doc.createAttribute(_ImcLoginXml.PORT)
                attr.value = h_imc.port
                node.setAttributeNode(attr)

            attr = doc.createAttribute(_ImcLoginXml.PASSWORD)
            #attr.value = p3_encrypt(h_imc.__password,key)
            attr.value = ImcUtils.encrypt_password(h_imc.password, key)
            node.setAttributeNode(attr)

            doc.documentElement.insertBefore(node, doc.documentElement.lastChild)

    xml_new = doc.toprettyxml(indent=" ")
    xml_new = re.sub(r"^.*?xml version.*\n", "", xml_new)
    xml_new = re.sub(r"\n[\s]*\n", "\n", xml_new)
    xml_new = re.sub(r"^(.*)", r"\1", xml_new, re.MULTILINE)

    f_handle = open(file_path, 'w')
    f_handle.write(xml_new)
    f_handle.close()
Ejemplo n.º 35
0
def get_imc_techsupport(handle, remotehost, remotefile, protocol, username, password, timeout_sec=ImcConstant.TIME_OUT_IN_SEC, dump_xml=None):
    """
    Creates and downloads the technical support data of IMC server.

    - remotehost    specifies the host where username need to download the technical support data.
    - remotefile    specifies the path on remotehost where username need to download the technical support data.
    - protocol        specifies the protocol used for transferring the file to remotehost.
    - username        specifies the username credential to login to remotehost.
    - password        specifies the password credential to login to remotehost.
    - timeout_sec     specifies the time in seconds for which method waits for the technical support data file
            to generate else exit.Default is 600 Seconds.
    """
    from ImcMos import MgmtImporter

    if timeout_sec == None or timeout_sec == "" or timeout_sec < 1:
        timeout_sec = ImcConstant.TIME_OUT_IN_SEC
        ImcUtils.write_imc_warning('[Warning]: Inappropriate <timeoutsec>. Chosen default value is 600 Seconds')

    #dn = "sys/rack-unit-1/tech-support"
    dn = CoreUtils.make_dn([CoreUtils.make_rn(NamingId.TOP_SYSTEM), CoreUtils.make_rn(NamingId.COMPUTE_RACK_UNIT, ServerId="1"), CoreUtils.make_rn(NamingId.SYSDEBUG_TECH_SUPPORT_EXPORT)])
    sysdebug_techsupport = ManagedObject(NamingId.SYSDEBUG_TECH_SUPPORT_EXPORT)
    sysdebug_techsupport.DN = dn
    sysdebug_techsupport.AdminState = MgmtImporter.CONST_ADMIN_STATE_ENABLED
    sysdebug_techsupport.RemoteFile = remotefile
    sysdebug_techsupport.Protocol = protocol
    sysdebug_techsupport.Status = Status.MODIFIED
    sysdebug_techsupport.Hostname = remotehost
    sysdebug_techsupport.User = username
    sysdebug_techsupport.Pwd = password

    in_config = ConfigConfig()
    in_config.add_child(sysdebug_techsupport)
    ccm = handle.config_conf_mo(dn=dn, in_config=in_config, in_hierarchical=YesOrNo.FALSE, dump_xml=dump_xml)
    time.sleep(10) #Wait for 10 seconds before start checking.

    #TODO: CHECK THE FIELD fsmStageDescr
    duration = timeout_sec
    poll_interval = ImcConstant.POLL_INTERVAL_IN_SEC
    crd = None
    if ccm.error_code == 0:
        ImcUtils.write_imc_warning('Waiting for the Tech Support file to become available (this may take several minutes).')
        status = False
        while True:
            crd = handle.config_resolve_dn(dn, in_hierarchical=YesOrNo.FALSE, dump_xml=dump_xml)
            if crd.error_code == 0:
                if crd.OutConfig.get_child_count() > 0:
                    for tech_support in crd.OutConfig.child:
                        if tech_support.AdminState == MgmtImporter.CONST_ADMIN_STATE_DISABLED: #TODO: replace the hard-coded string after schema change
                            if tech_support.FsmStatus == "success":
                                status = True
                            else:
                                raise ImcValidationException('Failed to create the TechSupport file.' + tech_support.FsmStatus)
                else:
                    raise ImcValidationException('Failed to create the TechSupport file.')
            else:
                raise ImcException(crd.error_code, crd.error_descr)
            if status:
                break
            time.sleep(min(duration, poll_interval))
            duration = max(0, (duration-poll_interval))
            if duration == 0:
                raise ImcValidationException('TechSupport generation in progress but get_imc_techsupport process timed out. Exiting Method get_imc_techsupport')
    else:
        raise ImcException(ccm.error_code, ccm.error_descr)

    return crd.OutConfig.child
Ejemplo n.º 36
0
def sync_imc_managedobject(handle, difference, delete_not_present=False, no_version_filter=True, dump_xml=None):
    """
    Syncs Managed Object.

    Method takes the difference object (output of compare_imc_managedobject) and applies the differences
    on reference Managed Object.
    - difference specifies the Difference object (output of compare_imc_managedobject) which has
      differences of the properties of two or more Managed Objects.
    - delete_not_present, if set as True, any missing MOs in reference Managed Object set will be deleted.
    - no_version_filter, If set as True, minversion for Mos or properties to be added in reference
      Managed Object will not be checked.
    """
    from ImcUtilityCore import _ImcMoDiff

    if difference == None or (isinstance(difference, list) and len(difference) == 0):
        raise ImcValidationException("[Error]: sync_imc_managedobject: Difference Object can not be Null")

    config_map = ConfigMap()

    for mo_diff in difference:
        mo = mo_diff.input_object
        class_id = mo.class_id
        gmo_diff = None
        meta_class_id = CoreUtils.find_class_id_in_mo_meta_ignore_case(class_id)
        if meta_class_id == None:
            ImcUtils.write_imc_warning("Ignoring [%s]. Unknown ClassId [%s]." %(mo_diff.input_object.get_attr("dn"), class_id))
            continue

        #Removes Difference Object.
        if mo_diff.side_indicator == _ImcMoDiff.REMOVE and delete_not_present:
            gmo_diff = ManagedObject(class_id)
            gmo_diff.set_attr("dn", mo.get_attr("dn"))
            gmo_diff.set_attr("Status", Status().DELETED)
            gmo_diff = GenericMO(gmo_diff, WriteXmlOption.ALL_CONFIG)#gmo_diff should be generic object

        if mo_diff.side_indicator == _ImcMoDiff.ADD_MODIFY:
            gmo_diff = ManagedObject(class_id)
            add_exists = False
            mo_meta = CoreUtils.is_property_in_meta_ignore_case(class_id, "Meta")

            if mo_meta != None and 'Add' in mo_meta.verbs:
                add_exists = True

            #Add Difference Object.
            if add_exists and (mo_diff.diff_property == None or len(mo_diff.diff_property) == 0):
                for prop in mo.__dict__:
                    prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(class_id, prop)
                    if prop_mo_meta != None:
                        if prop.lower() == "rn" or prop.lower() == "dn" or prop_mo_meta.access == MoPropertyMeta.READ_ONLY:
                            continue
                        gmo_diff.set_attr(prop_mo_meta.name, mo.get_attr(prop))

                gmo_diff.set_attr("Dn", mo.get_attr("Dn"))
                gmo_diff.set_attr("Status", Status().CREATED)

                gmo_diff = GenericMO(gmo_diff, WriteXmlOption.ALL_CONFIG)#gmo_diff should be generic object
                if not no_version_filter:
                    h_reference = mo.get_handle()
                    if h_reference != None and h_reference.version != None:
                        gmo_diff.filter_version(h_reference.version)

            #Modify the Managed Object
            else:
                if mo_diff.diff_property == None or len(mo_diff.diff_property) == 0:
                    ImcUtils.write_imc_warning('Add not supported for class_id ' + class_id +'. Reverting to modify.')
                    continue

                final_diff_props = mo_diff.diff_property
                gmo_diff = ManagedObject(class_id)
                for prop in final_diff_props:
                    prop_mo_meta = CoreUtils.is_property_in_meta_ignore_case(class_id, prop)
                    if prop_mo_meta != None:
                        #if (prop.lower() == "rn" or prop.lower() == "dn" or prop_mo_meta.access == MoPropertyMeta.ReadOnly):
                        if prop.lower() == "rn" or prop.lower() == "dn":
                            continue
                        gmo_diff.set_attr(prop_mo_meta.name, mo.get_attr(prop))

                gmo_diff.set_attr("Dn", mo.get_attr("Dn"))
                gmo_diff.set_attr("Status", Status().MODIFIED)
                gmo_diff = GenericMO(gmo_diff, WriteXmlOption.ALL_CONFIG)#gmo_diff should be generic object to apply filter_version on it.

        #TODO: NoversionFilter functionality discussion.

        if gmo_diff != None and not no_version_filter:
            gmo_meta = CoreUtils.get_mo_property_meta(gmo_diff.class_id, "Meta")
            if gmo_meta != None and handle.version != None:
                if handle.version < gmo_meta.version:
                    ImcUtils.write_imc_warning('Ignoring unsupported class_id %s for dn %s.'  %(gmo_diff.class_id, gmo_diff.get_attr("dn")))
                    gmo_diff = None

                if gmo_diff != None and handle.version != None:
                    gmo_diff.filter_version(h_reference.version)

            if gmo_diff.__dict__.has_key("_exclude_prop_list"):
                for prop in gmo_diff.excludePropList:
                    if prop == "Xtra_property":
                        gmo_diff.__dict__[prop] = {}
                        continue
                    gmo_diff.__dict__[prop] = None

        if gmo_diff != None:
            pair = Pair()
            pair.set_attr("Key", gmo_diff.get_attr("Dn"))
            pair.add_child(gmo_diff)
            config_map.add_child(pair)

    if config_map.get_child_count() == 0:
        return None

    output_molist = []
    for pair in config_map.child:
        in_config = ConfigConfig()
        for mo in pair.child:
            in_config.add_child(mo)

        ccm = handle.config_conf_mo(dn=pair.Key, in_config=in_config, in_hierarchical=YesOrNo.FALSE, dump_xml=dump_xml)
        if ccm.error_code == 0:
            molist = []
            for child in ccm.OutConfig.child:
                if isinstance(child, Pair) == True:
                    for mo in child.child:
                        molist.append(mo)
                elif isinstance(child, ManagedObject) == True:
                    molist.append(child)
            output_molist.extend(molist)
        else:
            raise ImcException(ccm.error_code, ccm.error_descr)

    return output_molist
Ejemplo n.º 37
0
def compare_imc_managedobject(reference_object, difference_object, exclude_different=YesOrNo.FALSE, include_equal=YesOrNo.FALSE, no_version_filter=YesOrNo.FALSE, include_operational=YesOrNo.FALSE, xlate_map=None):
    """
    Compares managed objects.

    - reference_object specifies objects used as a reference for comparison.
    - difference_object specifies objects that are compared to the reference objects.
    - exclude_different, if set as True then displays only the properties of compared objects that are equal.
    - include_equal, set as True to display properties of compared objects that are equal. By default, only properties that differ between the
      reference and difference objects are displayed.
    - no_version_filter, set as True to ignore minimum version in properties.
    - include_operational, set as True to include operational properties.
    - xlate_map specifies translation map with DNs of entities that needs to be translated.
    """
    from ImcUtilityCore import _ImcMoDiff, _compare, _CompareStatus, _translate_imc_managedobject
    reference_dict = {}
    difference_dict = {}

    if reference_object != None and isinstance(reference_object, list) and len(reference_object) > 0:
        for mo in reference_object:
            if mo == None:
                continue

            mo_meta = CoreUtils.is_property_in_meta_ignore_case(mo.prop_mo_meta.name, "Meta")

            if mo_meta != None:
                if mo_meta.io == MoMeta.ACCESS_TYPE_OUTPUTONLY:
                    ImcUtils.write_imc_warning('[Warning]: Ignoring [%s]. Non-configurable class [%s]' %(mo.Dn, mo.prop_mo_meta.name))
                    continue
                if mo_meta.io == MoMeta.ACCESS_TYPE_IO and len(mo_meta.access) == 1 and mo_meta.access[0] == "read-only":
                    ImcUtils.write_imc_warning('[Warning]: Ignoring read-only MO  [%s]. Class [%s]' %(mo.Dn, mo.prop_mo_meta.name))
                    continue

            reference_dict[mo.Dn] = mo

    if difference_object != None and isinstance(difference_object, list) and len(difference_object) > 0:
        for mo in difference_object:
            if mo == None:
                continue

            mo_meta = CoreUtils.is_property_in_meta_ignore_case(mo.prop_mo_meta.name, "Meta")
            if mo_meta != None:
                if mo_meta.access == MoMeta.ACCESS_TYPE_OUTPUTONLY:
                    ImcUtils.write_imc_warning('[Warning]: Ignoring [%s]. Non-configurable class [%s]' %(mo.Dn, mo.prop_mo_meta.name))
                    continue
                if mo_meta.access == MoMeta.ACCESS_TYPE_IO and len(mo_meta.access) == 1 and mo_meta.access[0] == "read-only":
                    ImcUtils.write_imc_warning('[Warning]: Ignoring read-only MO  [%s]. Class [%s]' %(mo.Dn, mo.prop_mo_meta.name))
                    continue
            if xlate_map in ImcUtils.AFFIRMATIVE_LIST:
                translated_mo = _translate_imc_managedobject(mo, xlate_map)
                difference_dict[translated_mo.Dn] = translated_mo
            else:
                difference_dict[mo.Dn] = mo

    dn_list = []
    for key in reference_dict:
        dn_list.append(key)
    for key in difference_dict:
        if key not in reference_dict:
            dn_list.append(key)
    dn_list = sorted(dn_list)
    diff_output = []

    for dn in dn_list:
        if dn not in difference_dict:
            if exclude_different not in ImcUtils.AFFIRMATIVE_LIST:
                mo_diff = _ImcMoDiff(reference_dict[dn], _ImcMoDiff.REMOVE)
                diff_output.append(mo_diff)
        elif dn not in reference_dict:
            if exclude_different not in ImcUtils.AFFIRMATIVE_LIST:
                mo_diff = _ImcMoDiff(difference_dict[dn], _ImcMoDiff.ADD_MODIFY)
                diff_output.append(mo_diff)
        else:
            diff_props = []
            option = WriteXmlOption.ALL_CONFIG
            if include_operational in ImcUtils.AFFIRMATIVE_LIST:
                option = WriteXmlOption.ALL
            gmo_reference = GenericMO(reference_dict[dn], option)
            gmo_difference = GenericMO(difference_dict[dn], option)
            if not no_version_filter:
                handle = gmo_reference.get_handle()
                if handle != None and handle.version != None:
                    gmo_reference.filter_version(handle.version)

                handle = gmo_difference.get_handle()
                if handle != None and handle.version != None:
                    gmo_difference.filter_version(handle.version)

            diff_status = _compare(gmo_reference, gmo_difference, diff_props)
            if diff_status == _CompareStatus.EQUAL and include_equal in ImcUtils.AFFIRMATIVE_LIST:
                mo_diff = _ImcMoDiff(reference_dict[dn], _ImcMoDiff.EQUAL)
                diff_output.append(mo_diff)
            elif diff_status == _CompareStatus.TYPES_DIFFERENT and exclude_different not in ImcUtils.AFFIRMATIVE_LIST:
                mo_diff = _ImcMoDiff(reference_dict[dn], _ImcMoDiff.REMOVE)
                diff_output.append(mo_diff)
                mo_diff = _ImcMoDiff(reference_dict[dn], _ImcMoDiff.ADD_MODIFY)
                diff_output.append(mo_diff)
            elif diff_status == _CompareStatus.PROPS_DIFFERENT and exclude_different not in ImcUtils.AFFIRMATIVE_LIST:
                ref_values = {}
                diff_values = {}
                for prop in diff_props:
                    ref_values[prop] = gmo_reference.get_attr(prop)
                    diff_values[prop] = gmo_difference.get_attr(prop)
                mo_diff = _ImcMoDiff(difference_dict[dn], _ImcMoDiff.ADD_MODIFY, diff_props, ref_values, diff_values)
                diff_output.append(mo_diff)

    return diff_output