class ListVirtualIOServer:

    """
    ListVirtualIOServer provides the definitions
    to return the list of
    VirtualIOServer objects available in the
    given ManagedSystem and contains the
    print definition to print the VirtualIOServer
    attribute details.
    """

    def __init__(self):
        self.content_type = CONTENT_TYPE

    def list_VirtualIOServer(self, ip, uuid, session_id):
        """
        Accessed with VirtualIOServer object
        Args:
              ip:ip address of the hmc
              uuid:ManagedSystem uuid
              session_id:session to access the VirtualIOServer
        Returns:
              object_list containing the list of available
              VirtualIOServer Objects
        """
        log_object.log_debug("List of VIOS started")
        listing_object = ListModule.ListModule()
        object_list = listing_object.listing("uom", ip,
                                             "ManagedSystem",
                                             self.content_type,
                                             "VirtualIOServer",
                                             session_id, uuid)
        log_object.log_debug("Returns VirtualIOServer objects" +
                             "to the main module")
        return object_list

    def print_virtualioserver_attributes(self, vios_object):
        """
        Accessed with Listvirtualioserver object
        Arguments:
                object_list:the selected object
                choice from src.the available virtualioserver objects.
        """

        log_object.log_debug("Print VirtualIOServer" +
                             "details that user has selected")
        print("\n")
        print("PartitionName".ljust(35), ":",
              vios_object.PartitionName.value())
        print("PartitionID".ljust(35), ":", vios_object.PartitionID.value())
        print("PartitionType".ljust(35), ":",
              vios_object.PartitionType.value())
        print("PartitionUUID".ljust(35), ":",
              vios_object.PartitionUUID.value())
        print("IsVirtualServiceAttentionLEDOn".ljust(35), ":", vios_object.
              IsVirtualServiceAttentionLEDOn.value())
        print("APICapable".ljust(35), ":", vios_object.APICapable.value())
        print("PartitionState".ljust(35), ":",
              vios_object.PartitionState.value())
        print("AssociatedManagedSystem".ljust(35), ":",
              vios_object.AssociatedManagedSystem.href)
        print("Maximum Memory".ljust(35), ":",
              vios_object.PartitionMemoryConfiguration.MaximumMemory.value())
        print("Desired Memory".ljust(35), ":",
              vios_object.PartitionMemoryConfiguration.DesiredMemory.value())
        print("Minimum Memory".ljust(35), ":",
              vios_object.PartitionMemoryConfiguration.MinimumMemory.value())
        print("HasDedicatedProcessors ".ljust(35), ":",
              vios_object.PartitionProcessorConfiguration.
              HasDedicatedProcessors.value())
        if vios_object.PartitionProcessorConfiguration.\
           HasDedicatedProcessors.value() == True:
            print("Maximum Processors".ljust(35), ":",
                  vios_object.PartitionProcessorConfiguration.
                  DedicatedProcessorConfiguration.MaximumProcessors.value())
            print("Desired Processors".ljust(35), ":",
                  vios_object.PartitionProcessorConfiguration.
                  DedicatedProcessorConfiguration.DesiredProcessors.value())
            print("Minimum Processors".ljust(35), ":",
                  vios_object.PartitionProcessorConfiguration.
                  DedicatedProcessorConfiguration.MinimumProcessors.value()) class VirtualSCSIMapping:
    
    def __init__(self):
        """
        initializes root and content-type
        """
        self.root = ROOT
        self.content_type = CONTENT_TYPE
        
    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") class VirtualFibreChannelMapping:
    
    def __init__(self):
        """
        initializes root and content-type
        """
        self.root = ROOT
        self.content_type = CONTENT_TYPE
        
    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") class CreateVolumeGroup:
    """
    Creates a VolumeGroup with one physical Volume
    """
    
    def __init__(self):
        """
        initializes root and content-type
        """
        self.root = ROOT
        self.content_type = CONTENT_TYPE
        
    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") class ListVolumeGroup:
    
    def __init__(self):
        """
        initializes root and content-type
        """
        self.root = ROOT
        self.content_type = CONTENT_TYPE
        
    def list_volumegroup(self, ip, virtualioserver_id, x_api_session):
        """
        returns a list of volume group objects available in the given virtualioserver
        Args:
            ip : ip address of HMC
            virtualioserver_id : UUID of VirtualIOServer on which VolumeGroups are to be listed
            x_api_session : session to be used
        """
        log.log_debug("List of Volume Group started")
        list_object = ListModule.ListModule()
        volumegroup_list = list_object.listing("uom" ,ip,
                                               self.root, self.content_type,
                                               "VolumeGroup", x_api_session,
                                               virtualioserver_id)
        log.log_debug("List of Volume Group returned")
        return volumegroup_list
    
    def print_volumegroup_attributes(self, volumegroup_object):
        """
        prints the details of the given volume group object
        """
        print("\n")
        print("VolumeGroup Name".ljust(35),":",volumegroup_object.GroupName.value())
        print("\nPHYSICAL VOLUMES : \n--------------------")
        for physicalvolume in volumegroup_object.PhysicalVolumes.PhysicalVolume:
            print("PhysicalVolume Name".ljust(35),":",physicalvolume.VolumeName.value())
            print("PhysicalVolume Capacity".ljust(35),":",physicalvolume.VolumeCapacity.value())
            print("\n")
        if volumegroup_object.VirtualDisks.VirtualDisk != []:
            print("\nVIRTUAL DISKS :\n-----------------")
        for virtualdisk in volumegroup_object.VirtualDisks.VirtualDisk:
            print("DiskName".ljust(35),":",virtualdisk.DiskName.value())
            print("DiskCapacity".ljust(35),":",virtualdisk.DiskCapacity.value())
            print("\n") class ModifyVolumeGroup:
    
    def __init__(self):
        """
        initializes root and content-type
        """
        self.root = ROOT
        self.content_type = CONTENT_TYPE
        
    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")
    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") class PowerOnPartition(JobStatus):
    
    def __init__(self, partition_type):
        """
        initializes root and content_type
        Args:
            partition_type : type of  object Logical Partition or VirtualIOServer
        """
        self.content_type = CONTENT_TYPE
        self.root = partition_type
        self.headers_obj = HmcHeaders.HmcHeaders("web")
        directory_path=os.path.dirname(__file__)
        self.input = open(directory_path+"/data/poweron_lpar.xml","r").read()
        
    def poweron_Partition(self, ip, logicalpartition_object, session_id):
        """
        performs poweron operation for the provided LogicalPartition object
        Args:
           ip : ip address of HMC
           logicalpartition_object : object of the logical partition to be activated
           session_id : session to be used
        """
        super().__init__(ip, self.root, self.content_type, session_id)
        log_object.log_debug("Power on of lpar started")
        namespace = self.headers_obj.ns["xmlns"]
        logicalpartitionprofile_object = ListLogicalPartitionProfile.ListLogicalPartitionProfile(self.root)
        object_list = logicalpartitionprofile_object.list_LogicalPartitionProfile(ip,logicalpartition_object.PartitionUUID.value(),session_id)
        ProfileUUID = object_list[0].Metadata.Atom.AtomID.value()
        inputpayload = self.input.format(self.root, ProfileUUID)
        logicalpartition_uuid = logicalpartition_object.PartitionUUID.value()
        request_object = HTTPClient.HTTPClient("uom", ip, self.root, self.content_type, session_id)
        request_object.HTTPPut(payload=inputpayload, append=str(logicalpartition_uuid)+"/do/PowerOn")
        log_object.log_debug("response of lpar poweron --- %s"%(request_object.response))
        if request_object.response_b:
            self.get_job_status(request_object) class PowerOffPartition(JobStatus):
    
    def __init__(self, partition_type):
        """
        initializes root and content_type
        Args:
            partition_type : type of  object Logical Partition or VirtualIOServer
        """
        self.content_type = CONTENT_TYPE
        self.root = partition_type
        self.headers_obj = HmcHeaders.HmcHeaders("web")
        directory_path=os.path.dirname(__file__)
        self.input = open(directory_path+"\data\poweroff_lpar.xml","r").read()
        self.input = self.input.format(partition_type)
        
    def poweroff_Partition(self, ip, logicalpartition_object, session_id):
        """
        performs the poweroff operation for the provided LogicalPartition object
        Args:
           ip : ip address of HMC
           logicalpartition_object : object of logicalpartition to be deactivated
           session_id : session to be used
        """
        super().__init__(ip, self.root, self.content_type, session_id)
        log_object.log_debug("power off of lpar started")
        namespace = self.headers_obj.ns["xmlns"]
        logicalpartition_uuid = logicalpartition_object.PartitionUUID.value()
        request_object = HTTPClient.HTTPClient("uom", ip, self.root, self.content_type, session_id)
        request_object.HTTPPut(payload=self.input, append=str(logicalpartition_uuid)+"/do/PowerOff")
        log_object.log_debug("response of power off job request --- %s"%(request_object.response))
        if request_object.response_b:
            self.get_job_status(request_object) class ModifyPartition:
    """
    class provides definitions for Modifying LogicalPartition 
    """
    
    def __init__(self, partition_type):
        """
        initializes the content-type and root
        Args:
            partition_type : type of  object Logical Partition or VirtualIOServer
        """
        
        self.content_type = CONTENT_TYPE%(partition_type)
        self.root = partition_type
        self.headers_obj = HmcHeaders.HmcHeaders("uom")
        
    def modify_Partition(self, ip, logicalpartition_object, session_id):
            """
            Modifies the Memory attributes of provided logicalpartition object
            Args:
               ip : IP address of HMC
               logicalpartition_object : the object of LogicalPartition
                                         to be modified
               session_id : session to be used
            """
            log_object.log_debug("modification of lpar started ")
            logicalpartition_object.PartitionMemoryConfiguration.DesiredMemory = DES_MEMORY
            logicalpartition_object.PartitionMemoryConfiguration.MaximumMemory = MAX_MEMORY
            logicalpartition_object.PartitionMemoryConfiguration.MinimumMemory = MIN_MEMORY
            inputpayload = logicalpartition_object.toxml("utf-8")
            request_object = HTTPClient.HTTPClient("uom",ip,self.root,self.content_type,session_id)
            request_object.HTTPPost(payload=inputpayload,append=str(logicalpartition_object.PartitionUUID.value()))
            log_object.log_debug("response of lpar modification --- %s"%(request_object.response))
            if request_object.response_b:
                log_object.log_debug("updations to partition are made successfully")
                return True
            else:
                return False class CreatePartition:
    """
    class provides definitions for LogicalPartition Creation
    """
    
    def __init__(self, partition_type):
        """
        initializes the content-type and root
        Args:
            partition_type : type of  object Logical Partition or VirtualIOServer
        """
        self.type = partition_type
        self.content_type = CONTENT_TYPE%(partition_type)
        self.root = ROOT
        self.headers_obj = HmcHeaders.HmcHeaders("uom")
        
    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 class ListLogicalPartitionProfile:
    """
    ListLogicalPartitionProfile provides the definitions
    to return the list of
    LogicalPartitionProfile objects available in the
    given vios and contains the
    print definition to print the LogicalPartitionProfile
    attribute details.
    """
     
    def __init__(self,root):        
        
        self.content_type = CONTENT_TYPE
        self.root=root
        
    def list_LogicalPartitionProfile(self,ip,uuid,session_id):
        """
        Accessed with ListLogicalPartitionProfile object
        Args:
              ip:ip address of the hmc
              uuid:vios uuid
              session_id:session to access the vios
        Returns:
              object_list containing the list of available LogicalPartitionProfile Objects
        """
        log_object.log_debug("List of Logical Partition Profile Started")
        listing_object = ListModule.ListModule()
        object_list = listing_object.listing("uom", ip,
                                                  self.root,
                                                  self.content_type, "LogicalPartitionProfile",
                                                  session_id, uuid)
        log_object.log_debug("Returns Logical Partition Profile" +
                                  "objects to the main module")
        return object_list
    
    def print_logicalpartitionprofile_attributes(self, profile_object):
        """
        Accessed with ListLogicalPartitionProfile object

        Args:
            object_list:the selected object choice from src.the available LogicalPartitionProfile objects.
        """
        
        print("\n")
        print("ProfileName".ljust(35),":",profile_object.ProfileName.value())
        print("ProfileType".ljust(35),":",profile_object.ProfileType.value())
        print("Maximum Memory".ljust(35),":",profile_object.ProfileMemory.MaximumMemory.value())
        print("Desired Memory".ljust(35),":",profile_object.ProfileMemory.DesiredMemory.value())
        print("Minimum Memory".ljust(35),":",profile_object.ProfileMemory.MinimumMemory.value())
        print("HasDedicatedProcessors".ljust(35),":",
              profile_object.ProcessorAttributes.HasDedicatedProcessors.value())
        if profile_object.ProcessorAttributes.HasDedicatedProcessors.value():
            print("Maximum Processors".ljust(35),":",profile_object.ProcessorAttributes.\
                                  DedicatedProcessorConfiguration.MaximumProcessors.value())
            print("Desired Processors".ljust(35),":",profile_object.ProcessorAttributes.\
                                  DedicatedProcessorConfiguration.DesiredProcessors.value())
            print("Minimum Processors".ljust(35),":",profile_object.ProcessorAttributes.\
                                  DedicatedProcessorConfiguration.MinimumProcessors.value())
        else:
            print("Maximum ProcessingUnits".ljust(35),":",profile_object.ProcessorAttributes.\
                                  SharedProcessorConfiguration.MaximumProcessingUnits.value())
            print("Desired ProcessingUnits".ljust(35),":",profile_object.ProcessorAttributes.\
                                  SharedProcessorConfiguration.DesiredProcessingUnits.value())
            print("Minimum ProcessingUnits".ljust(35),":",profile_object.ProcessorAttributes.\
                                  SharedProcessorConfiguration.MinimumProcessingUnits.value()) class CreateLogicalPartitionProfile:
    """
    class provides definitions for LogicalPartitionProfile Creation
    """
    
    def __init__(self,root):
        """
        initializes the content-type and root
        """
        
        self.content_type = CONTENT_TYPE
        self.root = root
        self.headers_obj = HmcHeaders.HmcHeaders("uom")
        
    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") class ModifyLogicalPartitionProfile:
    """
    class provides definitions for Modifying LogicalPartitionProfile
    """
    
    def __init__(self,root):
        """
        initializes the content-type and root
        """
        
        self.content_type = CONTENT_TYPE
        self.root = root
        self.headers_obj = HmcHeaders.HmcHeaders("uom")
        
    def modify_LogicalPartitionProfile(self, ip, logicalpartition_uuid, logicalpartitionprofile_object, session_id):
            """
            Modifies the Memory attributes of provided logicalpartitionprofile object
            Args:
               ip : IP address of HMC
               logicalpartition_uuid : the Logical partition uuid under which the profile to be modified
               logicalpartitionprofile_object : the Logical partition profile uuid which is to be modified
               session_id : session to be used
            """
            log_object.log_debug("LPAR profile modification started")
            logicalpartitionprofile_object.ProfileMemory.DesiredMemory = 512
            logicalpartitionprofile_object.ProfileMemory.MaximumMemory = 512
            logicalpartitionprofile_object.ProfileMemory.MinimumMemory = 512
            inputpayload = logicalpartitionprofile_object.toxml("utf-8")
            profileuuid = str(logicalpartitionprofile_object.Metadata.Atom.AtomID.value())
            request_object = HTTPClient.HTTPClient("uom",ip,self.root,self.content_type,session_id)
            request_object.HTTPPost(payload=inputpayload,append=str(logicalpartition_uuid)+"/LogicalPartitionProfile/%s" \
                                                                    %(profileuuid))
            log_object.log_debug("response of profile modification --- %s"%(request_object.response))
            if request_object.response_b:
                log_object.log_debug("partitions are updated successfully")
                return True
            else:
                return False class ListLogicalPartition:
    
    def __init__(self):
        """
        initializes root and content-type
        """
        self.content_type = CONTENT_TYPE
        self.root = ROOT
        self.headers_obj = HmcHeaders.HmcHeaders("uom")
        
    def list_LogicalPartition(self, ip, uuid, session_id):
        """
        returns the list of available logicalpartition objects
         Args:
           ip : ip address of HMC
           uuid : UUID of the Logical Partition
           session_id : session to be used
        """
        log_object.log_debug("list of Lpar started")
        listing_object = ListModule.ListModule()
        object_list = listing_object.listing("uom",ip,self.root,self.content_type,"LogicalPartition",session_id,uuid)
        log_object.log_debug("Returns Logical Partition objects to the main module")
        return object_list
    
    def print_logicalpartition_attributes(self,logicalpartition_object):
        """
        prints the details of the given LogicalPartition object to the console
        """
        try:
            print("\n")
            print("PartitionName".ljust(35),":",logicalpartition_object.PartitionName.value())
            print("PartitionID".ljust(35),":",logicalpartition_object.PartitionID.value())
            print("PartitionType".ljust(35),":",logicalpartition_object.PartitionType.value())
            print("PartitionState".ljust(35),":",logicalpartition_object.PartitionState.value())
            print("MigrationState".ljust(35),":",logicalpartition_object.MigrationState.value())
            print("PartitionUUID".ljust(35),":",logicalpartition_object.PartitionUUID.value())
            print("AssociatedManagedSystem".ljust(35),":",logicalpartition_object.AssociatedManagedSystem.href)
            print("IsVirtualServiceAttentionLEDOn".ljust(35),":",logicalpartition_object.IsVirtualServiceAttentionLEDOn.value())
            print("Maximum Memory".ljust(35),":",logicalpartition_object.PartitionMemoryConfiguration.MaximumMemory.value())
            print("Desired Memory".ljust(35),":",logicalpartition_object.PartitionMemoryConfiguration.DesiredMemory.value())
            print("Minimum Memory".ljust(35),":",logicalpartition_object.PartitionMemoryConfiguration.MinimumMemory.value())
            print("HasDedicatedProcessors".ljust(35),":",logicalpartition_object.PartitionProcessorConfiguration.HasDedicatedProcessors.value())
            if logicalpartition_object.PartitionProcessorConfiguration.HasDedicatedProcessors.value():
                print("Maximum Processors".ljust(35),":",logicalpartition_object.PartitionProcessorConfiguration.\
                                      DedicatedProcessorConfiguration.MaximumProcessors.value())
                print("Desired Processors".ljust(35),":",logicalpartition_object.PartitionProcessorConfiguration.\
                                      DedicatedProcessorConfiguration.DesiredProcessors.value())
                print("Minimum Processors".ljust(35),":",logicalpartition_object.PartitionProcessorConfiguration.\
                                      DedicatedProcessorConfiguration.MinimumProcessors.value())
            else:
                print("Maximum ProcessingUnits".ljust(35),":",logicalpartition_object.PartitionProcessorConfiguration.\
                                      SharedProcessorConfiguration.MaximumProcessingUnits.value())
                print("Desired ProcessingUnits".ljust(35),":",logicalpartition_object.PartitionProcessorConfiguration.\
                                      SharedProcessorConfiguration.DesiredProcessingUnits.value())
                print("Minimum ProcessingUnits".ljust(35),":",logicalpartition_object.PartitionProcessorConfiguration.\
                                      SharedProcessorConfiguration.MinimumProcessingUnits.value())
        except Exception as e:
            self.log_object.log_info("Nonetype object found")
from src.main.HmcRestClient import *
from src.virtual_io_server import ListVirtualIOServer, \
                                  VirtualSCSIMapping, \
                                  VirtualFibreChannelMapping
from src.virtual_io_server.volume_group import CreateVolumeGroup, \
                                               ListVolumeGroup, \
                                               ModifyVolumeGroup
from src.partition_operation_util import PowerOnPartition,\
                                     PowerOffPartition,\
                                     ModifyPartition, \
                                     CreatePartition
from src.logical_partition_profile import ListLogicalPartitionProfile,\
                                          CreateLogicalPartitionProfile,\
                                          ModifyLogicalPartitionProfile
from src.logical_partition import ListLogicalPartition
import sys
import os
                selected_vios = get_selectedobject(object_list)
            try:
                if x == 1:
                    #object creation and method call to list the details of the selected vios 
                   if selected_vios != None:
                       virtualioserver_object.print_virtualioserver_attributes(selected_vios)
                   
                elif x == 2:
                     #object creation and method call to create vios
                    try:
                         print("\nVirtualIOServer will be created with Following configruations,\n maximum,mimimum and desired memory = 256",
                               "\nShared processors,Minimum,Desired and maximum processing units = 0.5")
                         logicalpartition_object = CreatePartition.CreatePartition("VirtualIOServer")
                         created_logicalpartition_object = logicalpartition_object.create_Partition(ip,managedsystem_uuid,x_api_session)
                         print("\nPartition %s Created Successfully\n"%(created_logicalpartition_object.PartitionName.value()))
                    except (TypeError,AttributeError) :
                         log_object.log_error("Error in VIOS creation")
                 
                elif x == 3:
                     #object creation and method call to modify existing vios memory attributes
                     if selected_vios != None:
                         print("\nVIOS memory attributes are modified as maximum ,minimum ,desired memory = 512") 
                         modify_logicalpartition_object = ModifyPartition.ModifyPartition("VirtualIOServer")
                         result = modify_logicalpartition_object.modify_Partition(ip,selected_vios,x_api_session)
                         if result:
                             print("\nModifications are updated successfully")
                         else:
                             log_object.log_error("Error occured while updating the modifications.Verify \
                                   whether the vios is in running or not activated state before updating it")
                elif x == 4:
                     #object creation and method call to poweron inactive vios
                     virtualioserver_object = ListVirtualIOServer.ListVirtualIOServer()
                     object_list = virtualioserver_object.\
                              list_VirtualIOServer(ip, managedsystem_uuid,
                                                              x_api_session)
                     print("\nList of VIOS in inactive state")
                     k = 0
                     inactive_object_list = []
                     for i in range(0,len(object_list)):
                             if object_list[i].PartitionState.value() == "not activated":
                                 k = k+1
                                 print("%s.%s" % (k,object_list[i].PartitionName.value()))
                                 inactive_object_list.append(object_list[i])
                     if k>0:
                        try:
                             c = int(input("\nSelect any partition index the operation to be performed:"))
                             if c > 0:
                                 ch = c-1               
                                 selected_vios = inactive_object_list[ch]
                                 logicalpartition_object = PowerOnPartition.PowerOnPartition("VirtualIOServer")
                                 logicalpartition_object.poweron_Partition(ip,selected_vios,x_api_session)
                                 
                             else :
                                print("\nTry again using valid option")
                        except IndexError :
                             print("\nTry again using valid option")
                     else:
                         log_object.log_warn("No Partitions are in inactive state")
                elif x == 5:
                     #object creation and method call to poweroff selected active state vios
                         virtualioserver_object = ListVirtualIOServer.ListVirtualIOServer()
                         object_list = virtualioserver_object.\
                              list_VirtualIOServer(ip, managedsystem_uuid,
                                                              x_api_session)
                         print("\nList of VIOS in active state")
                         k = 0
                         active_object_list = []
                         for i in range(0,len(object_list)):
                                if object_list[i].PartitionState.value() == "open firmware" or object_list[i].PartitionState.value() == "running":
                                     k = k+1
                                     print("%s.%s" % (k,object_list[i].PartitionName.value()))
                                     active_object_list.append(object_list[i])
                         if k>0 :
                             try:
                                 c = int(input("\nSelect any VIOS index the operation to be performed:"))
                                 if c > 0:
                                     ch = c-1
                                     selected_vios = active_object_list[ch]
                                     logicalpartition_object = PowerOffPartition.PowerOffPartition("VirtualIOServer")
                                     logicalpartition_object.poweroff_Partition(ip,selected_vios,x_api_session)
                                 else:
                                    print("\nTry again using valid option")
                             except IndexError :
                                 print("\nTry again using valid option")
                elif x == 6:
                    os.system("cls")
                    return 1
                elif x == 7:
                    os.system("cls")
                    return 2
                elif x == 8:
                    os.system("cls")
                    return 3
                elif x == 9:
                    print(open(directory+"/help/VirtualIOServer/VirtualIOServerOperations.txt").read())
                elif x == 10:
                    sys.exit(1)
                else:
                    print("\nTry again using valid option")
                back_to_menu()
                    
            except TypeError :
                log_object.log_warn("No VirtualIOServers Available")
                back_to_menu()
                
    elif n == 2:
        while True:
            print ("\n\n","LogicalPartitionProfile".center(50))
            print_list = ['List','Create','Modify','Return to vios menu',
                          'Return to ManagedSystem menu','Return to MainMenu',
                          'Help','Exit']
            #select any  LogicalPartitionProfile operation
            x1 = int(print_obj.print_on_screen(print_list))
            if x1 > 0  and x1 < 4:
                print("\nAvailable VirtualIOServers :")
                virtualioserver_object = ListVirtualIOServer.ListVirtualIOServer()
                object_list = virtualioserver_object.\
                              list_VirtualIOServer(ip, managedsystem_uuid,
                                                              x_api_session)
                selected_vios = get_selectedobject(object_list)

                list_logicalpartitionprofile_object=ListLogicalPartitionProfile.ListLogicalPartitionProfile("VirtualIOServer")