def create_clientnetwork_adapter(self, ip, logicalpartition_id,
                                  x_api_session):
     """
     Args:
        ip:ip address of the hmc
        logicalpartition_id:the uuid of the logical partition on which network adapter
        is to be created
        x_api_session:session used to create network adapter
     """
     log.log_debug("create client network adapter starting")
     pyxb.RequireValidWhenGenerating(True)
     clientnetwork_adapter_object = UOM.ClientNetworkAdapter()
     clientnetwork_adapter_object.PortVLANID = PORT_VLAN_ID
     clientnetwork_adapter_object.schemaVersion = SCHEMA_VER
     xml = clientnetwork_adapter_object.toxml()
     http_object = HTTPClient.HTTPClient("uom", ip, self.root,
                                         self.content_type, x_api_session)
     http_object.HTTPPut(xml,
                         append=logicalpartition_id +
                         "/ClientNetworkAdapter")
     log.log_debug("response of create client network adapter --- %s" %
                   (http_object.response))
     if http_object.response_b:
         print("ClientNetworkAdapter Created successfully")
         log.log_debug("ClientNetworkAdapter Created successfully")
     else:
         log.log_error("Error in ClientNetworkAdapter Creation")
 def add_virtualdisk(self, ip, vios_uuid, x_api_session,
                     volumegroup_object):
     """
      creates a virtualdisk in VolumeGroup
      Args:
         ip:ip address of hmc
         vios_uuid:UUID of VirtualIOServer
         x_api_session:session to be used
         volumegroup_object:volume group object to be modified
      """
     pyxb.RequireValidWhenGenerating(True)
     virtualdisk_object = UOM.VirtualDisk()
     virtualdisk_object.DiskName = LOGICALVOLUME_NAME
     virtualdisk_object.schemaVersion = SCHEMA_VERSION
     virtualdisk_object.DiskCapacity = volumegroup_object.GroupCapacity.value(
     ) / 2
     volumegroup_object.VirtualDisks.VirtualDisk.append(virtualdisk_object)
     xml = volumegroup_object.toxml()
     volumegroup_id = volumegroup_object.Metadata.Atom.AtomID.value()
     response = sendrequest(xml, ip, self.root, self.content_type,
                            x_api_session, vios_uuid, volumegroup_id)
     if response:
         print("VirtualDisk Created in VolumeGroup Successfully")
     else:
         print("VirtualDisk Creation unsuccessfull")
 def create_vscsi_clientadapter(self, ip, logicalpartition_uuid,
                                x_api_session):
     """
     Args:
         ip: ip address of hmc
         logicalpartition_uuid:UUID of Logical partition on which virtual SCSI
         adapter is to be created
         x_api_session:session used to create virtual SCSI adapter
     """
     log.log_debug("creation of scsi adapter started")
     vscsi_object = UOM.VirtualSCSIClientAdapter()
     vscsi_object.AdapterType = ADAPTER_TYPE
     vscsi_object.RemoteLogicalPartitionID = PARTITION_ID
     vscsi_object.RemoteSlotNumber = SLOT_NUMBER
     vscsi_object.schemaVersion = SCHEMA_VER
     pyxb.RequireValidWhenGenerating(True)
     xml = vscsi_object.toxml()
     http_object = HTTPClient.HTTPClient("uom", ip, self.root,
                                         self.content_type, x_api_session)
     http_object.HTTPPut(xml,
                         append=logicalpartition_uuid +
                         "/VirtualSCSIClientAdapter")
     log.log_debug("response of create scsi adapter --- %s" %
                   (http_object.response))
     if http_object.response_b:
         print("VirtualSCSIClientAdapter created successfully")
         log.log_debug("VirtualSCSIClientAdapter created successfully")
     else:
         log.log_error(
             "Error in VirtualSCSIClientAdapter creation.Verify the attribute values"
         )
    def add_physicalvolume(self, ip, vios_uuid, x_api_session,
                           volumegroup_object):
        """ 
            adds a Physical volume to the selected volume group
            Args:
               ip:ip address of hmc
               vios_uuid:UUID of VirtualIOServer
               x_api_session:session to be used
               volumegroup_object:volume group object to be modified
            """
        pyxb.RequireValidWhenGenerating(True)
        physicalvolume_object = UOM.PhysicalVolume()

        physicalvolume_object.VolumeName = PHYSICALVOLUME_NAME
        physicalvolume_object.schemaVersion = SCHEMA_VERSION
        volumegroup_object.PhysicalVolumes.PhysicalVolume.append(
            physicalvolume_object)
        xml = volumegroup_object.toxml()
        volumegroup_id = volumegroup_object.Metadata.Atom.AtomID.value()
        response = sendrequest(xml, ip, self.root, self.content_type,
                               x_api_session, vios_uuid, volumegroup_id)
        if response:
            print("Physical volume added to volumegroup Successfully")
        else:
            print("Adding Physical volume to volumegroup failed")
Example #5
0
 def create_virtualnetwork(self, ip, managedsystem_uuid, x_api_session, virtualswitch_object):
     """
     create a virtual network in a given managed system
     Args:
         ip:ip address of hmc
         managedsystem_uuid:UUID of managedsystem
         x_api_session:session to be used
         virtualswitch_object:Virtual switch object to be used for virtual network
     Returns:
         boolean value
     """
     log.log_debug("virtual network creation started")
     pyxb.RequireValidWhenGenerating(True)
     virtual_network_object = UOM.VirtualNetwork()
     virtual_network_object.schemaVersion = SCHEMA_VER
     virtual_network_object.AssociatedSwitch = pyxb.BIND()
     virtual_network_object.AssociatedSwitch.href = "https://%s:12443/rest/api/uom/ManagedSystem/%s/VirtualSwitch/%s"\
                                                    %(ip,managedsystem_uuid,virtualswitch_object.Metadata.Atom.AtomID.value())
     virtual_network_object.AssociatedSwitch.rel = "related"
     virtual_network_object.NetworkVLANID = NETWORK_VLAN_ID 
     virtual_network_object.NetworkName = "VLAN%s-%s"%(virtual_network_object.NetworkVLANID.value(),virtualswitch_object.SwitchName.value())
     virtual_network_object.VswitchID = virtualswitch_object.SwitchID.value()
     virtual_network_object.TaggedNetwork = TAGGED_NETWORK
     xml = virtual_network_object.toxml()
     http_object = HTTPClient.HTTPClient("uom",ip,self.root,self.content_type,x_api_session)
     http_object.HTTPPut(xml,append=managedsystem_uuid+"/VirtualNetwork")
     log.log_debug("virtualnetwork creation response -- %s"%(http_object.response))
     if http_object.response_b:
         return True
     else :
         return False
Example #6
0
 def create_volumegroup(self, ip, virtualioserver_uuid, x_api_session):
     """
     Args:
         ip:ip address of hmc
         virtualioserver_uuid:UUID of VirtualIOServer
         x_api_session:session to be used
     """
     log.log_debug("create volume group started")
     pyxb.RequireValidWhenGenerating(True)
     volumegroup_object = UOM.VolumeGroup()
     volumegroup_object.schemaVersion = SCHEMA_VER
     volumegroup_object.GroupName = VOLUMEGROUP_NAME
     physicalvolume_object = UOM.PhysicalVolume()
     physicalvolume_object.VolumeName = PHYSICALVOLUME_NAME
     physicalvolume_object.schemaVersion = SCHEMA_VER
     volumegroup_object.PhysicalVolumes = pyxb.BIND()
     volumegroup_object.PhysicalVolumes.schemaVersion = SCHEMA_VER
     volumegroup_object.PhysicalVolumes.append(physicalvolume_object)
     xml = volumegroup_object.toxml()
     http_object = HTTPClient.HTTPClient("uom", ip, self.root,
                                         self.content_type, x_api_session)
     http_object.HTTPPut(xml, append=virtualioserver_uuid + "/VolumeGroup")
     log.log_debug("response of volume group creation -- %s" %
                   (http_object.response))
     if http_object.response_b:
         print("VolumeGroup Created Successfully")
         log.log_debug("VolumeGroup Created Successfully")
     else:
         log.log_error(
             "Error in VolumeGroup creation.Verify the attribute values")
Example #7
0
 def create_Partition(self, ip, uuid, session_id):
     """
         Args:
           ip:ip address of HMC
           uuid:ManagedSystemUUID
           session_id:to access the session
         Returns:
           Returns the created LogicalPartition object
         """
     log_object.log_debug("creation of logical partition started")
     obj = eval(self.type)()
     ns = self.headers_obj.ns
     obj.schemaVersion = SCHEMA_VER
     pyxb.RequireValidWhenGenerating(True)
     obj.PartitionMemoryConfiguration = pyxb.BIND()
     obj.PartitionMemoryConfiguration.schemaVersion = SCHEMA_VER
     obj.PartitionMemoryConfiguration.DesiredMemory = DES_MEMORY
     obj.PartitionMemoryConfiguration.MaximumMemory = MAX_MEMORY
     obj.PartitionMemoryConfiguration.MinimumMemory = MIN_MEMORY
     obj.PartitionProcessorConfiguration = pyxb.BIND()
     obj.PartitionProcessorConfiguration.schemaVersion = SCHEMA_VER
     obj.PartitionProcessorConfiguration.HasDedicatedProcessors = DEDICATED_PROCESSORS
     obj.PartitionProcessorConfiguration.SharedProcessorConfiguration = pyxb.BIND(
     )
     obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.schemaVersion = SCHEMA_VER
     obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.DesiredProcessingUnits = DES_PROC_UNITS
     obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.DesiredVirtualProcessors = DES_VIRTUAL_PROCESSORS
     obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.MaximumProcessingUnits = MAX_PROC_UNITS
     obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.MaximumVirtualProcessors = MAX_VIRTUAL_PROCESSORS
     obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.MinimumProcessingUnits = MIN_PROC_UNITS
     obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.MinimumVirtualProcessors = MIN_VIRTUAL_PROCESSORS
     obj.PartitionProcessorConfiguration.SharingMode = SHARING_MODE
     if self.type == "VirtualIOServer":
         obj.PartitionType = "Virtual IO Server"
         partition_name = PARTITION_NAME % ("VIOS") + "" + time.strftime(
             "%d%m%y-%X")
     else:
         obj.PartitionType = "AIX/Linux"
         partition_name = PARTITION_NAME % ("LPAR") + "" + time.strftime(
             "%d%m%y-%X")
     obj.PartitionName = partition_name
     xmlobject = obj.toDOM()
     xmlobject.documentElement.setAttribute("xmlns", ns["xmlns"])
     xmlpayload = xmlobject.toxml("utf-8")
     request_obj = HTTPClient.HTTPClient("uom", ip, self.root,
                                         self.content_type, session_id)
     request_obj.HTTPPut(xmlpayload, append=str(uuid) + "/" + self.type)
     log_object.log_debug("response of lpar creation -- %s" %
                          (request_obj.response))
     if request_obj.response_b:
         root = etree.fromstring(request_obj.response.content)
         entry = root.findall(".//%s:%s" % (self.type, self.type),
                              namespaces={self.type: ns["xmlns"]})
         xmlstring = etree.tostring(entry[0])
         xml_object = CreateFromDocument(xmlstring)
         log_object.log_debug("partition created successfully")
         return xml_object
Example #8
0
    def set_managedsystempcmpreference(self):
        ''' This function is used to set/update the existing PCM Preferences of the Managed System '''

        get_managedsystempcmpreference_object1 = self.get_managedsystempcmpreference(
        )
        pyxb.RequireValidWhenGenerating(True)
        print("options for set/update Managed System Pcm Preferences \n")
        option = eval(
            input(
                " Choose an option \n 1.ComputeLTM \n 2.ComputeLTM + Long term monitor \n 3.ComputeLTM + Long term monitor + AggregationEnabled \n"
            ))

        if option == "1":
            get_managedsystempcmpreference_object1.ComputeLTMEnabled = "true"
            get_managedsystempcmpreference_object1.ComputeLTMEnabled.ksv = "V1_1_0"

            get_managedsystempcmpreference_object1.AggregationEnabled = "false"
            get_managedsystempcmpreference_object1.LongTermMonitorEnabled = "false"

        elif option == "2":
            get_managedsystempcmpreference_object1.LongTermMonitorEnabled = "true"
            get_managedsystempcmpreference_object1.ComputeLTMEnabled = "true"
            get_managedsystempcmpreference_object1.ComputeLTMEnabled.ksv = "V1_1_0"

            get_managedsystempcmpreference_object1.LongTermMonitorEnabled = "false"

        elif option == "3":
            get_managedsystempcmpreference_object1.AggregationEnabled = "true"
            get_managedsystempcmpreference_object1.LongTermMonitorEnabled = "true"
            get_managedsystempcmpreference_object1.ComputeLTMEnabled = "true"
            get_managedsystempcmpreference_object1.ComputeLTMEnabled.ksv = "V1_1_0"

        short_term_monitor = eval(
            input("do u want to enable ShortTermMonitorEnabled ? y/n\n"))
        if short_term_monitor == "y":
            get_managedsystempcmpreference_object1.ShortTermMonitorEnabled = "true"
        else:
            get_managedsystempcmpreference_object1.ShortTermMonitorEnabled = "false"

        # genarating the xml request body for the post reqeust by using ToXml method
        post_payload = ToXml.ToXml(get_managedsystempcmpreference_object1)
        HTTP_object = HTTPClient.HTTPClient(self.service, self.ip, self.root,
                                            "application/xml",
                                            self.x_api_session)
        # perform the post request for managed system pcm preferences
        HTTP_object.HTTPPost(post_payload,
                             append=self.managedsystem_id + "/preferences")
        log_object.log_debug(
            "response code for set_managedsystempcmpreference %s" %
            (HTTP_object.response))
        if HTTP_object.response.status_code == 200:
            self.print_managedsystempcmpreference(
                get_managedsystempcmpreference_object1)
Example #9
0
def prettyxml(pyxb_xml, ns=None, xslt=None, toxml=True):
    """ Pretty printer for pyxb object. This differs from the standard minidom's
        toprettyxml because it doesn't touch anything inside a i{value} tag.
        
        @param pyxb_xml: The pyxb node to format
        
        @param ns: base namespace to use for encoding
        @param xslt: name of xslt module to include in header
        @param toxml: if True, convert to XML otherwise already is in XML
    """
    pyxb.defaultNamespace = ns
    domutils.BindingDOMSupport.SetDefaultNamespace(ns if ns else defaultNS)
    pyxb.RequireValidWhenGenerating(True)
    return prettyxml_(
        pyxb_xml.toxml(encoding='utf-8') if toxml else pyxb_xml, xslt)
 def create_LogicalPartitionProfile(self, ip, logicalpartition_object,
                                    session_id):
     """
     Assign values to the profile object and creates the profile to the given vios
     Args:
        ip : ip address of hmc
        logicalpartition_object : VIOS/Logical Partition object on which
                                  profile should be created
        session_id : session to be used
     """
     log_object.log_debug("creation of lpar profile started")
     ns = self.headers_obj.ns
     logicalpartitionprofile_object = UOM.LogicalPartitionProfile()
     pyxb.RequireValidWhenGenerating(True)
     logicalpartitionprofile_object.ProfileName = PROFILE_NAME % (
         time.strftime("%d%m%y-%X"))
     logicalpartitionprofile_object.ProfileType = PROFILE_TYPE
     logicalpartitionprofile_object.schemaVersion = SCHEMA_VER
     logicalpartitionprofile_object.ProfileMemory = pyxb.BIND()
     logicalpartitionprofile_object.ProfileMemory.schemaVersion = SCHEMA_VER
     logicalpartitionprofile_object.ProfileMemory.MaximumMemory = MAX_MEMORY
     logicalpartitionprofile_object.ProfileMemory.MinimumMemory = MIN_MEMORY
     logicalpartitionprofile_object.ProfileMemory.DesiredMemory = DES_MEMORY
     xmlobject = logicalpartitionprofile_object.toDOM()
     xmlobject.documentElement.setAttribute("xmlns", ns["xmlns"])
     xmlpayload = xmlobject.toxml("utf-8")
     HTTPClient_object = HTTPClient.HTTPClient("uom", ip, self.root,
                                               self.content_type,
                                               session_id)
     HTTPClient_object.HTTPPut(
         payload=xmlpayload,
         append=str(logicalpartition_object.PartitionUUID.value()) +
         "/LogicalPartitionProfile")
     log_object.log_debug("response of profile creation -- %s" %
                          (HTTPClient_object.response))
     if HTTPClient_object.response_b:
         root = etree.fromstring(HTTPClient_object.response.content)
         entry = root.findall(
             ".//LogicalPartitionProfile:LogicalPartitionProfile",
             namespaces={"LogicalPartitionProfile": ns["xmlns"]})
         xmlstring = etree.tostring(entry[0])
         xml_object = UOM.CreateFromDocument(xmlstring)
         log_object.log_debug("created partition successfully")
         return xml_object
     else:
         log_object.log_error("Error in Profile creation")
Example #11
0
 def create_virtualswitch(self, ip, managedsystem_uuid, x_api_session):
     """
     Args:
         ip:ip address of hmc
         managedsystem_uuid:UUID of managedsystem
         x_api_session:session to be used
     """
     log.log_debug("creation of virtual switch started")
     pyxb.RequireValidWhenGenerating(True)
     virtualswitch_object = UOM.VirtualSwitch()
     virtualswitch_object.schemaVersion = SCHEMA_VER
     virtualswitch_object.SwitchName = SWITCH_NAME
     xml = virtualswitch_object.toxml()
     http_object = HTTPClient.HTTPClient("uom",ip,self.root,self.content_type,x_api_session)
     http_object.HTTPPut(xml,append=managedsystem_uuid+"/VirtualSwitch")
     log.log_debug("response for creation of virtual switch -- %s"%(http_object.response))
     if http_object.response_b:
         return True
     else:
         return False
 def create_virtualfibrechannel_mapping(self, ip, managedsystem_uuid,
                                        x_api_session, vios_object,
                                        lpar_id):
     """
     creates a virtual fibre mapping between given vios object and lpar
     Args:
         ip:ip address of hmc
         managedsystem_uuid:UUID of VirtualIOServer
         x_api_session:session to be used
         vios_object:vios object in which mapping is created
         lpar_id:UUID of logical partition to which mapping is created
     """
     log.log_debug("creation of fc mapping started")
     pyxb.RequireValidWhenGenerating(True)
     lpar_link = "https://" + ip + ":12443/rest/api/uom/ManagedSystem/" + managedsystem_uuid + "/LogicalPartition/" + lpar_id
     virtualfibrechannel_mapping_object = UOM.VirtualFibreChannelMapping()
     virtualfibrechannel_mapping_object.AssociatedLogicalPartition = pyxb.BIND(
     )
     virtualfibrechannel_mapping_object.AssociatedLogicalPartition.href = lpar_link
     virtualfibrechannel_mapping_object.AssociatedLogicalPartition.rel = "related"
     virtualfibrechannel_mapping_object.Port = pyxb.BIND()
     virtualfibrechannel_mapping_object.Port.PortName = FIBRE_CHANNEL_PORT_NAME
     virtualfibrechannel_mapping_object.Port.schemaVersion = SCHEMA_VER
     virtualfibrechannel_mapping_object.schemaVersion = SCHEMA_VER
     vios_object.VirtualFibreChannelMappings.append(
         virtualfibrechannel_mapping_object)
     xml = vios_object.toxml()
     http_object = HTTPClient.HTTPClient("uom", ip, self.root,
                                         self.content_type, x_api_session)
     http_object.HTTPPost(xml,
                          append=vios_object.Metadata.Atom.AtomID.value())
     log.log_debug("response of fc mapping creation -- %s" %
                   (http_object.response))
     if http_object.response_b:
         print("\nVirtual FibreChannel Mapping created successfully")
     else:
         log.log_error(
             "\nError in creation of FibreChannelMapping.Verify the attribute values"
         )
Example #13
0
 def create_vscsi_mapping(self, ip, managedsystem_uuid, x_api_session,
                          virtualioserver_object, logicalPartition_id):
     """
     Creates a Virtual SCSI mapping between seleced vios and lpar
     Args:
         ip:ip address of hmc
         managedsystem_uuid:UUID of VirtualIOServer
         x_api_session:session to be used
         virtualioserver_object:vios object in which mapping is created
         logicalPartition_id:UUID of logical partition to which mapping is created
     """
     log.log_debug("create vscsi mapping started")
     logicalpartition_link = "http://" + ip + ":12443/rest/api/uom/ManagedSystem/" + managedsystem_uuid + "/LogicalPartition/" + logicalPartition_id
     pyxb.RequireValidWhenGenerating(True)
     vscsi_mapping_object = UOM.VirtualSCSIMapping()
     vscsi_mapping_object.Storage = pyxb.BIND()
     vscsi_mapping_object.Storage.PhysicalVolume = pyxb.BIND()
     vscsi_mapping_object.Storage.PhysicalVolume.schemaVersion = SCHEMA_VER
     vscsi_mapping_object.Storage.PhysicalVolume.VolumeName = PHYSICALVOLUME_NAME
     vscsi_mapping_object.schemaVersion = SCHEMA_VER
     vscsi_mapping_object.AssociatedLogicalPartition = pyxb.BIND()
     vscsi_mapping_object.AssociatedLogicalPartition.href = logicalpartition_link
     vscsi_mapping_object.AssociatedLogicalPartition.rel = "related"
     virtualioserver_object.VirtualSCSIMappings.VirtualSCSIMapping.append(
         vscsi_mapping_object)
     virtualioserver_id = virtualioserver_object.Metadata.Atom.AtomID.value(
     )
     xml = virtualioserver_object.toxml()
     http_object = HTTPClient.HTTPClient("uom", ip, self.root,
                                         self.content_type, x_api_session)
     http_object.HTTPPost(xml, append=virtualioserver_id)
     log.log_debug("response of scsi mapping creation -- %s" %
                   (http_object.response))
     if http_object.response_b:
         print("VSCSIMapping Created Successfully")
     else:
         log.log_error("Error in VSCSIMapping.Verify the attribute values")
Example #14
0
def prettyxml(pyxb_xml, validate=True, ns=None, xslt=None):
    """ XML pretty printer.  Surprising as it may seem, there doesn't seem to be a really decent
        Python based pretty printer for XML, so we rolled this one ourselves.
        Note: Sometimes setting RequireValidWhenGenerating to false results in errors.

        @param pyxb_xml: XML to be prettified
        @type pyxb_xml: either a string containing xml or a pyxb node
        @param validate: Indicator on whether the XML should be validated.  Only applies if the input is of type pyxb node
        @type validate: C{bool}
        @param ns: default namespace
        @type ns: C{pyxb.Namespace}
        @param xslt: URI of an XSLT transform if needed
        @type xslt: String
        @return: Pretty xml
    """

    def indent(depth, prev):
        return ('\n' + (' ' * 4 * depth)) if prev != 'd' else ""
        
    def args(alist):
        if len(alist):
            return ' ' + ' '.join([k+'="'+v+'"' for (k,v) in alist.items()])
        return ''

    pyxb.defaultNamespace = ns
    pyxb.utils.domutils.BindingDOMSupport.SetDefaultNamespace(ns if ns else defaultNS)
    pyxb.RequireValidWhenGenerating(validate)
    rawxml = pyxb_xml if isinstance(pyxb_xml, basestring) else pyxb_xml.toxml()

    seq = []
    p = xml.parsers.expat.ParserCreate('UTF-8')
    p.StartElementHandler  = lambda name, attrs: seq.append( ('s', name, attrs))
    p.EndElementHandler    = lambda name:        seq.append( ('e', name ))
    p.CharacterDataHandler = lambda data:        seq.append( ('d', data ))
    p.Parse(rawxml.encode('UTF-8'),1)

    depth, prev, rval = (0, 'e', '<?xml version="1.0" encoding="UTF-8"?>' + (xslt if xslt else ""))
    dataText = ''
    while len(seq):
        e = seq.pop(0)
        if e[0] == 's':
            # shortcut the simple start end tag
            if seq[0][0] == 'e':
                assert e[1] == seq[0][1]
                seq.pop(0)
                rval += indent(depth, prev)
                rval += '<' + e[1] + args(e[2]) + '/>'
                depth -= 1
            else:
                if prev != 'e':
                    depth += 1
                if dataText:
                    rval += dataText
                    dataText = ''
                rval += indent(depth, prev)
                rval += '<' + e[1] + args(e[2]) + '>'
        elif e[0] == 'e':
            if prev != 'd':
                depth -= 1
            else:
                rval += escape(unescape(dataText))
                dataText = ''
            rval += indent(depth, prev)
            rval += '</' + e[1] + '>'
        else:
            if prev != 'e' or e[0] <> 'd' or e[1].strip():
                dataText += e[1]
        if prev != 'e' or e[0] <> 'd' or e[1].strip():
            prev = e[0]
    return rval 
Example #15
0
# examples/manual/demo4c.py
from __future__ import print_function

import pyxb
import po4
import address
import pyxb.binding.datatypes as xs

po = po4.purchaseOrder(orderDate=xs.date(1999, 10, 20))
po.shipTo = address.USAddress('Alice Smith', '123 Maple Street', 'Anytown',
                              'AK', 12341)
po.billTo = address.USAddress('Robert Smith', '8 Oak Avenue', 'Anytown', 'AK',
                              12341)

pyxb.RequireValidWhenGenerating(False)
print(po.toxml("utf-8"))
    def create_network_bridge(self, ip, managedsystem_uuid, session_id,
                              vios_uuid, virtual_network_uuid):
        """
        creates a network bridge in a given managed system.
        Args:
            ip:ip address of hmc
            managedsystem_uuid:UUID of managed system
            session_id:session to be used
            vios_uuid:UUID of vios to create trunk and shared ethernet adapter
            virtual_network_uuid:UUID of virtual network on which network bridge is to be created
        """
        log.log_debug("creation of network bridge started")
        link = "https://%s:12443/rest/api/uom/ManagedSystem/%s/%s"
        vios_link = link % (ip, managedsystem_uuid,
                            "VirtualIOServer/" + vios_uuid)
        virtual_network_link = link % (
            ip, managedsystem_uuid, "VirtualNetwork/" + virtual_network_uuid)
        ns = self.headers_obj.ns
        pyxb.RequireValidWhenGenerating(True)
        network_bridge_object = UOM.NetworkBridge()
        network_bridge_object.schemaVersion = SCHEMA_VER
        network_bridge_object.FailoverEnabled = FAILOVER_ENABLED
        network_bridge_object.LoadBalancingEnabled = LOADBALANCING_ENABLED
        network_bridge_object.LoadGroups = pyxb.BIND()
        virtual_network = UOM.VirtualNetwork_Links_Type()
        virtual_network.link.append(
            UOM.AtomLink_Type(rel="related", href=virtual_network_link))

        load_groups_obj = UOM.LoadGroup()
        load_groups_obj.PortVLANID = LOADGROUP_PORT_VLAN_ID
        load_groups_obj.schemaVersion = SCHEMA_VER
        load_groups_obj.VirtualNetworks = pyxb.BIND()
        load_groups_obj.VirtualNetworks.link = virtual_network.link
        network_bridge_object.LoadGroups = pyxb.BIND(load_groups_obj,
                                                     schemaVersion="V1_3_0")

        network_bridge_object.SharedEthernetAdapters = pyxb.BIND()
        sea_obj = UOM.SharedEthernetAdapter()
        sea_obj.schemaVersion = SCHEMA_VER
        sea_obj.AssignedVirtualIOServer = pyxb.BIND()
        sea_obj.AssignedVirtualIOServer.href = vios_link
        sea_obj.AssignedVirtualIOServer.rel = "related"
        sea_obj.BackingDeviceChoice = pyxb.BIND()
        sea_obj.BackingDeviceChoice.EthernetBackingDevice = pyxb.BIND()
        sea_obj.BackingDeviceChoice.EthernetBackingDevice.schemaVersion = SCHEMA_VER
        sea_obj.BackingDeviceChoice.EthernetBackingDevice.AdapterID = BACKINGDEVICE_ADAPTER_ID
        sea_obj.BackingDeviceChoice.EthernetBackingDevice.DeviceName = BACKINGDEVICE_NAME
        sea_obj.PortVLANID = SEA_PORT_VLAN_ID
        sea_obj.IsPrimary = SEA_IS_PRIMARY
        network_bridge_object.SharedEthernetAdapters = pyxb.BIND(
            sea_obj, schemaVersion="V1_3_0")

        network_bridge_object.PortVLANID = NETWORK_BRIDGE_PVLANID
        network_bridge_object.VirtualNetworks = pyxb.BIND()
        virtual_network = UOM.VirtualNetwork_Links_Type()
        virtual_network.link.append(
            UOM.AtomLink_Type(rel="related", href=virtual_network_link))
        network_bridge_object.VirtualNetworks.link = virtual_network.link

        xmlobject = network_bridge_object.toDOM()
        xmlobject.documentElement.setAttribute("xmlns", ns["xmlns"])
        xmlpayload = xmlobject.toxml("utf-8")
        request_obj = HTTPClient.HTTPClient("uom", ip, self.root,
                                            self.content_type, session_id)
        request_obj.HTTPPut(xmlpayload,
                            append=str(managedsystem_uuid) + "/NetworkBridge")
        log.log_debug("response of network bridge creation -- %s" %
                      (request_obj.response))
        if request_obj.response_b:
            root = etree.fromstring(request_obj.response.content)
            entry = root.findall(".//NetworkBridge:NetworkBridge",
                                 namespaces={"NetworkBridge": ns["xmlns"]})
            xmlstring = etree.tostring(entry[0])
            xml_object = UOM.CreateFromDocument(xmlstring)
            return xml_object
Example #17
0
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from datetime import datetime
from . import amelding_logic
import base64
import pyxb
import logging
_logger = logging.getLogger(__name__)

pyxb.RequireValidWhenGenerating(True)


class Amelding(models.Model):
    _name = 'l10n_no_payroll.amelding'
    _description = 'A-melding'

    @api.depends('meldingsId', 'kalendermaaned')
    def _compute_amelding_filename(self):
        self.ensure_one()
        name = 'A-melding for {kalendermaaned} - id {meldingsId}.xml'.format(
            kalendermaaned=self.kalendermaaned, meldingsId=self.meldingsId)
        self.amelding_filename = name

    @api.depends('amelding')
    def _compute_amelding_xml(self):
        self.amelding_xml = base64.b64encode(bytes(self.amelding, 'utf-8'))

    company_id = fields.Many2one('res.company',
                                 string='Company',
                                 required=True,
                                 store=True,