Beispiel #1
0
def _typed_randrange(lo, hi, type):
    if type == 'sint8':
        return pywbem.Sint8(
            random.randrange(pywbem.Sint8(lo), pywbem.Sint8(hi)))
    elif type == 'sint16':
        return pywbem.Sint16(
            random.randrange(pywbem.Sint16(lo), pywbem.Sint16(hi)))
    elif type == 'sint32':
        return pywbem.Sint32(
            random.randrange(pywbem.Sint32(lo), pywbem.Sint32(hi)))
    elif type == 'sint64':
        return pywbem.Sint64(
            random.randrange(pywbem.Sint64(lo), pywbem.Sint64(hi)))
    elif type == 'uint8':
        return pywbem.Uint8(
            random.randrange(pywbem.Uint8(lo), pywbem.Uint8(hi)))
    elif type == 'uint16':
        return pywbem.Uint16(
            random.randrange(pywbem.Uint16(lo), pywbem.Uint16(hi)))
    elif type == 'uint32':
        return pywbem.Uint32(
            random.randrange(pywbem.Uint32(lo), pywbem.Uint32(hi)))
    elif type == 'uint64':
        return pywbem.Uint64(
            random.randrange(pywbem.Uint64(lo), pywbem.Uint64(hi)))
    elif type == 'real32':
        return pywbem.Real32(
            random.randrange(pywbem.Real32(lo), pywbem.Real32(hi)))
    elif type == 'real64':
        return pywbem.Real64(
            random.randrange(pywbem.Real64(lo), pywbem.Real64(hi)))
    def get_instance(self, env, model):
        """Return an instance.

        Keyword arguments:
        env -- Provider Environment (pycimmb.ProviderEnvironment)
        model -- A template of the pywbem.CIMInstance to be returned.  The 
            key properties are set on this instance to correspond to the 
            instanceName that was requested.  The properties of the model
            are already filtered according to the PropertyList from the 
            request.  Only properties present in the model need to be
            given values.  If you prefer, you can set all of the 
            values, and the instance will be filtered for you. 

        Possible Errors:
        CIM_ERR_ACCESS_DENIED
        CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized 
            or otherwise incorrect parameters)
        CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM 
            Instance does not exist in the specified namespace)
        CIM_ERR_FAILED (some other unspecified error occurred)

        """

        logger = env.get_logger()
        logger.log_debug('Entering %s.get_instance()' \
                % self.__class__.__name__)

        key = self.fromInstanceID(model['InstanceID'])
        concreteJob = concrete_job.AnyJob.load(key)
        logEntriesLen = len(list(concreteJob.logs.enumerate()))

        #model['AvailableRequestedStates'] = [self.Values.AvailableRequestedStates.<VAL>,] # TODO 
        #model['Caption'] = '' # TODO 
        #model['CommunicationStatus'] = self.Values.CommunicationStatus.<VAL> # TODO 
        model['CurrentNumberOfRecords'] = pywbem.Uint64(logEntriesLen)
        #model['Description'] = '' # TODO 
        #model['DetailedStatus'] = self.Values.DetailedStatus.<VAL> # TODO 
        #model['ElementName'] = '' # TODO 
        #model['EnabledDefault'] = self.Values.EnabledDefault.Enabled # TODO 
        #model['EnabledState'] = self.Values.EnabledState.Not_Applicable # TODO 
        #model['Generation'] = pywbem.Uint64() # TODO 
        #model['HealthState'] = self.Values.HealthState.<VAL> # TODO 
        #model['InstallDate'] = pywbem.CIMDateTime() # TODO 
        model['LogState'] = self.Values.LogState.Normal
        model['MaxNumberOfRecords'] = pywbem.Uint64(0)
        #model['Name'] = '' # TODO 
        #model['OperatingStatus'] = self.Values.OperatingStatus.<VAL> # TODO 
        #model['OperationalStatus'] = [self.Values.OperationalStatus.<VAL>,] # TODO 
        #model['OtherEnabledState'] = '' # TODO 
        model['OverwritePolicy'] = self.Values.OverwritePolicy.Never_Overwrites
        #model['PrimaryStatus'] = self.Values.PrimaryStatus.<VAL> # TODO 
        #model['RequestedState'] = self.Values.RequestedState.Not_Applicable # TODO 
        #model['Status'] = self.Values.Status.<VAL> # TODO 
        #model['StatusDescriptions'] = ['',] # TODO 
        #model['TimeOfLastStateChange'] = pywbem.CIMDateTime() # TODO 
        #model['TransitioningToState'] = self.Values.TransitioningToState.Not_Applicable # TODO 
        return model
Beispiel #3
0
    def _create_test_instance(self, name_of_atom, number):
        """ Create a TestAtom instance.  """

        weight = _atomic_weights[name_of_atom]
        #new_instance['char16Prop']  = 
        #new_instance['char16Propa'] = Null
        new_instance = pywbem.CIMInstance('TestAtom')
        new_instance['Name'] = name_of_atom
        new_instance['boolProp']     = False
        new_instance['dateProp']     = self.time
        new_instance['real32Prop']   = pywbem.Real32(weight)
        new_instance['real32Propa']  = [pywbem.Real32(weight), \
                                        pywbem.Real32(weight), \
                                        pywbem.Real32(weight)]
        new_instance['real64Prop']   = pywbem.Real64(weight)
        new_instance['real64Propa']  = [pywbem.Real64(weight), \
                                        pywbem.Real64(weight), \
                                        pywbem.Real64(weight)]
        new_instance['sint16Prop']   = pywbem.Sint16(number)
        new_instance['sint16Propa']  = [pywbem.Sint16(number), \
                                        pywbem.Sint16(number), \
                                        pywbem.Sint16(number)]
        new_instance['sint32Prop']   = pywbem.Sint32(number)
        new_instance['sint32Propa']  = [pywbem.Sint32(number), \
                                        pywbem.Sint32(number), \
                                        pywbem.Sint32(number)]
        new_instance['sint64Prop']   = pywbem.Sint64(number)
        new_instance['sint64Propa']  = [pywbem.Sint64(number), \
                                        pywbem.Sint64(number), \
                                        pywbem.Sint64(number)]
        new_instance['sint8prop']    = pywbem.Sint8(number)
        new_instance['sint8Propa']   = [pywbem.Sint8(number), \
                                        pywbem.Sint8(number), \
                                        pywbem.Sint8(number)]
        new_instance['stringProp']   = name_of_atom
        new_instance['stringPropa']  = ['proton', 'electron', 'neutron']
        new_instance['uint16Prop']   = pywbem.Uint16(number)
        new_instance['uint16Propa']  = [pywbem.Uint16(number), \
                                        pywbem.Uint16(number), \
                                        pywbem.Uint16(number)]
        new_instance['uint32Prop']   = pywbem.Uint32(number)
        new_instance['uint32Propa']  = [pywbem.Uint32(number), \
                                        pywbem.Uint32(number), \
                                        pywbem.Uint32(number)]
        new_instance['uint64Prop']   = pywbem.Uint64(number)
        new_instance['uint64Propa']  = [pywbem.Uint64(number), \
                                        pywbem.Uint64(number), \
                                        pywbem.Uint64(number)]
        new_instance['uint8Prop']    = pywbem.Uint64(number)
        new_instance['uint8Propa']   = [pywbem.Uint64(number), \
                                        pywbem.Uint64(number), \
                                        pywbem.Uint64(number)]

        try:
            cipath = self.conn.CreateInstance(new_instance)
            new_instance.path = cipath
            self.inst_paths.append(cipath)

        except pywbem.CIMError, arg:
            return None, arg
Beispiel #4
0
    def test_6_modify_instance(self):
        """Test modify instance"""
        rinst, msg = self._create_test_instance('Boron', 5)
        if not rinst:
            self.fail('%s: CreateInstance Failed.' % str(msg))
            return

        propertylist = ['uint64Prop', 'dateProp', 'stringProp', 'real32Prop', \
                        'sint64Propa', 'sint64prop', 'boolProp']
        keybindings = {'Name': 'Boron'}

        mod_instance = get_instance(self.conn, keybindings, propertylist)

        weight = _atomic_weights['Boron']
        new_time = pywbem.CIMDateTime.now()
        if mod_instance['boolProp']:
            mod_instance['boolProp'] = False
        else:
            mod_instance['boolProp'] = True
        mod_instance['uint64Prop'] = pywbem.Uint64(2)
        mod_instance['dateProp'] = new_time
        mod_instance['stringProp'] = "Helium"
        mod_instance['real32Prop'] = pywbem.Real32(weight)
        mod_instance['sint64Propa'] = pywbem.CIMProperty('sint64Propa', \
                                        value=[pywbem.Sint64(2),  \
                                        pywbem.Sint64(2), pywbem.Sint64(2)])
        mod_instance['sint64prop'] = pywbem.Sint64(2)
        mod_instance['Name'] = 'Boron'

        try:
            self.conn.ModifyInstance(mod_instance)
        except pywbem.CIMError, arg:
            self.fail(arg)
Beispiel #5
0
 def __AttachNicToNetwork(self, switch, nics):
     result = 0
     if switch != None:
         try:
             rasd = CIMInstance('Xen_HostNetworkPortSettingData')
             rasd['ResourceType'] = pywbem.Uint16(33)
             rasd['VlanTag'] = pywbem.Uint64(23)
             rasd['Connection'] = nics
             print 'adding resources %s' % rasd.items()
             vssd = CIMInstanceName('Xen_VirtualSwitchSettingData')
             vssd['InstanceID'] = 'Xen:' + switch['Name']
             nic_rasds = [rasd]
             in_params = {
                 'AffectedConfiguration': vssd,
                 'ResourceSettings': nic_rasds
             }
             (rval,
              out_params) = self.conn.InvokeMethod('AddResourceSettings',
                                                   self.vsms, **in_params)
             if rval == 0:
                 result = 1
                 try:
                     nics = self.__FindNicsAssociatedWithSwitch(switch)
                     if len(nics) == 0:
                         result = 0
                 except Exception, e:
                     print 'exception %s was received' % str(e)
                     result = 0
             else:
                 print 'Method returned error %d' % rval
Beispiel #6
0
 def CreateBondedNetwork(self):
     self.TestBegin()
     # eth1 and eth2 PIFs are bonded and a network is created out of them
     rasd1 = CIMInstance('Xen_HostNetworkPortSettingData')
     rasd1['ResourceType'] = pywbem.Uint16(33)
     rasd1['Connection'] = ["eth1"]
     rasd1['VlanTag'] = pywbem.Uint64(2)
     rasd2 = CIMInstance('Xen_NetworkPortSettingData')
     rasd2['ResourceType'] = pywbem.Uint16(33)
     rasd2['Connection'] = ["eth2"]
     rasd2['VlanTag'] = pywbem.Uint64(2)
     rasds = [rasd1, rasd2]
     result = 0
     bonded_network = self.__CreateNetwork(rasds)
     if bonded_network != None:
         result = 1
     self.TestEnd(result)
     return bonded_network
Beispiel #7
0
def createCIMXMLVM(password = None,
                   hostIPAddr = None,
                   vmName = None):
    cimxmlConn = cimxmlConnection(password,hostIPAddr)

    # Virtual System setting data for an HVM type
    hvmVssd = CIMInstance("Xen_ComputerSystemSettingData")
    hvmVssd['Description'] = vmName
    hvmVssd['ElementName'] = vmName
    hvmVssd['VirtualSystemType'] = 'DMTF:xen:HVM'
    hvmVssd['HVM_Boot_Params'] = ['order=dc']
    hvmVssd['HVM_Boot_Policy'] = 'BIOS order'
    hvmVssd['Platform'] = ['acpi=true','apic=true','pae=true']

    # RASD to specify processor allocation for the VM
    # Processor RASD
    procRasd = CIMInstance('CIM_ResourceAllocationSettingData')
    procRasd['ResourceType'] = pywbem.Uint16(3)
    procRasd['VirtualQuantity'] = pywbem.Uint64(1)
    procRasd['AllocationUnits'] = 'count'

    # memory RASD to specify memory allocation settings for a VM
    memRasd = CIMInstance('Xen_MemorySettingData')
    memRasd['ResourceType'] = pywbem.Uint16(4)
    memRasd['VirtualQuantity'] = pywbem.Uint64(512)
    memRasd['AllocationUnits'] = 'byte*2^20'

    vsms = cimxmlConn.EnumerateInstanceNames("Xen_VirtualSystemManagementService")

    rasds = [procRasd, memRasd]
    hvmParams = {'SystemSettings': hvmVssd, 'ResourceSettings': rasds}

    newVM = None
    try:
        (rval, outParams) = cimxmlConn.InvokeMethod('DefineSystem', vsms[0], **hvmParams)

        if((rval != 4096) and (rval != 0)):
            raise xenrt.XRTError("Following error occured while invoking DefineSystem %s" % (rval))

        newVM = outParams['ResultingSystem']
        xenrt.sleep(10)

    except  Exception, e:
        raise xenrt.XRTError("Caught exception while invoking DefineSystem")
Beispiel #8
0
    def get_instance(self, env, model, cim_class, stat=None):
        """Return an instance.

        Keyword arguments:
        env -- Provider Environment
        model -- A template of the CIMInstance to be returned.  The key 
            properties are set on this instance to correspond to the 
            instanceName that was requested.  The properties of the model
            are already filtered according to the PropertyList from the 
            request.
        cim_class -- The CIMClass

        Possible Errors:
        CIM_ERR_ACCESS_DENIED
        CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized 
            or otherwise incorrect parameters)
        CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM 
            Instance does not exist in the specified namespace)
        CIM_ERR_FAILED (some other unspecified error occurred)

        """

        logger = env.get_logger()
        logger.log_debug('Entering %s.get_instance()' %
                         self.__class__.__name__)

        if stat is None:
            stat = os.lstat(model['name'])

        mode = stat[ST_MODE]
        model['Writeable'] = bool(mode & S_IWUSR)
        model['HealthState'] = pywbem.Uint16(5)
        #model['StatusDescriptions'] = # TODO (type = string[])
        model['Executable'] = bool(mode & S_IXUSR)
        model['Readable'] = bool(mode & S_IRUSR)
        #model['OperationalStatus'] = # TODO (type = uint16[])
        model['FileSize'] = pywbem.Uint64(stat[ST_SIZE])
        #model['CompressionMethod'] = # TODO (type = string)
        #model['Status'] = # TODO (type = string)
        #model['Description'] = # TODO (type = string)
        #model['InstallDate'] = # TODO (type = datetime)
        model['LastModified'] = pywbem.CIMDateTime.fromtimestamp(
            stat[ST_MTIME])
        #model['InUseCount'] = # TODO (type = uint64)
        #model['EncryptionMethod'] = # TODO (type = string)
        model['LastAccessed'] = pywbem.CIMDateTime.fromtimestamp(
            stat[ST_ATIME])
        model['ElementName'] = model['name'] == '/' and '/' or \
                    os.path.basename(model['name'])
        #model['Caption'] = # TODO (type = string)
        model['CreationDate'] = pywbem.CIMDateTime.fromtimestamp(
            stat[ST_CTIME])
        return model
Beispiel #9
0
 def CreateInvalidBondedNetwork(self):
     self.TestBegin()
     # 2 invalid pifs (with the wrong interfaces specified) are bonded
     rasd1 = CIMInstance('Xen_NetworkPortSettingData')
     rasd1['ResourceType'] = pywbem.Uint16(33)
     rasd1['Connection'] = ["eth11234", "eth2345"]
     rasd1['VlanTag'] = pywbem.Uint64(2)
     rasds = [rasd1]
     result = 0
     bonded_network = self.__CreateNetwork(rasds)
     if bonded_network == None:
         result = 1
     self.TestEnd(result)
def getnum(num, datatype):
    try:
        result = {
            '8': pywbem.Uint8(num),
            '16': pywbem.Uint16(num),
            '32': pywbem.Uint32(num),
            '64': pywbem.Uint64(num)
        }
        result = result.get(datatype, num)
    except NameError:
        result = num

    return result
Beispiel #11
0
 def CreateInvalidBondedNetwork2(self):
     self.TestBegin()
     # one invalid pif is bonded with an valid pif
     rasd1 = CIMInstance('Xen_HostNetworkPortSettingData')
     rasd1['ResourceType'] = pywbem.Uint16(33)
     rasd1['Connection'] = ["eth11234", "eth1"]
     rasd1['VlanTag'] = pywbem.Uint64(2)
     rasds = [rasd1]
     result = 0
     bonded_network = self.__CreateNetwork(rasds)
     if bonded_network == None:
         result = 1
     self.TestEnd(result)
Beispiel #12
0
 def ConvertExternalVLANNetworkToInternalNetwork(self):
     self.TestBegin()
     result = 0
     # create an internal network first
     rasd = CIMInstance('Xen_HostNetworkPortSettingData')
     rasd['ResourceType'] = pywbem.Uint16(33)
     rasd['Connection'] = ["eth0"]
     rasd['VlanTag'] = pywbem.Uint64(256)
     switch = self.__CreateNetwork(rasd)
     print switch.items()
     rasds = self.__FindNicsAssociatedWithSwitch(switch)
     result = self.__RemoveNicsFromNetwork(switch, rasds)
     self.TestEnd(result)
     return switch
Beispiel #13
0
def add_vm_resources (conn, vsms, vm_ref):
    try:
        print '*** Adding processor and CD resources to VM %s ' % vm_ref['Name']
        # AddResourceSettings requires the Xen_ComputerSystemSettingData reference, find it
        # We'll use the association class for that
        association_class = 'CIM_SettingsDefineState'      # association to traverse via Xen_ComputerSystem
        result_class      = 'CIM_VirtualSystemSettingData' # result class we are looking for
        in_params         = {'ResultClass': result_class, 'AssocClass': association_class }
        affected_config_arr  = conn.AssociatorNames(vm_ref, **in_params)
        affected_config = affected_config_arr[0]

        cd_drive = pywbem.CIMInstance('Xen_DiskSettingData')
        cd_drive['Elementname']       = 'my_cd_drive'
        cd_drive['ResourceType']      = pywbem.Uint16(15)
        cd_drive['VirtualQuantity']   = pywbem.Uint64(1)
        cd_drive['AllocationUnits']   = "count"
        cd_drive['Access']            = pywbem.Uint8(1)
        cd_drive['Bootable']          = True

        more_mem = pywbem.CIMInstance('CIM_ResourceAllocationSettingData')
        more_mem['ResourceType']    = pywbem.Uint16(4)
        more_mem['VirtualQuantity'] = pywbem.Uint64(512)
        more_mem['AllocationUnits'] = 'byte*2^20'

        rasds = [cd_drive, more_mem]
        in_params = {'ResourceSettings': rasds, 'AffectedConfiguration':affected_config}
        [rval, out_params] = conn.InvokeMethod('AddResourceSettings', vsms, **in_params)
        if rval != 4096:
            sys.stderr.write('%s returned error: %s\n' % (sys._getframe(0).f_code.co_name, rval))
            return 0
        job_ref = out_params['Job']
        job = wait_for_job_to_complete(conn, job_ref)
        conn.DeleteInstance(job_ref)
    except Exception, e:
        sys.stderr.write('Exception caught in %s: %s\n' % (sys._getframe(0).f_code.co_name, e))
        return 0
Beispiel #14
0
 def CreateExternalNetwork(self):
     self.TestBegin()
     result = 0
     rasd = CIMInstance('Xen_HostNetworkPortSettingData')
     rasd['ResourceType'] = pywbem.Uint16(33)
     rasd['Connection'] = ["eth0"]
     rasd['VlanTag'] = pywbem.Uint64(3)
     rasds = [rasd]
     external_network = self.__CreateNetwork(rasds)
     if external_network != None:
         result = 1
     # create another VLAN for the same interface with a different VLAN id
     rasd = CIMInstance('Xen_HostNetworkPortSettingData')
     rasd['ResourceType'] = pywbem.Uint16(33)
     rasd['Connection'] = ["eth0"]
     rasd['VlanTag'] = pywbem.Uint64(4)
     rasds = [rasd]
     external_network2 = self.__CreateNetwork(rasds)
     if external_network2 == None:
         result = 0
     else:
         self.__DeleteNetwork(external_network2)
     self.TestEnd(result)
     return external_network
Beispiel #15
0
 def CreateBondedNetwork2(self):
     self.TestBegin()
     # A second way of specify the two interfaces to bond (in the same RASD)
     # eth1 and eth2 PIFs are bonded and a network is created out of them
     rasd1 = CIMInstance('Xen_HostNetworkPortSettingData')
     rasd1['ResourceType'] = pywbem.Uint16(33)
     rasd1['Connection'] = ["eth1", "eth2"]
     rasd1['VlanTag'] = pywbem.Uint64(2)
     rasds = [rasd1]
     result = 0
     bonded_network = self.__CreateNetwork(rasds)
     if bonded_network != None:
         result = 1
     self.TestEnd(result)
     return bonded_network
Beispiel #16
0
 def CreateNetworkErrorTests(self):
     self.TestBegin()
     result = 1
     # rasd with wrong resourcetype specified (needs to be 33)
     print 'Error Test: bad RASD with wrong resourcetype'
     try:
         rasd_with_wrong_resource_type = CIMInstance(
             'CIM_ResourceAllocationSettingData')
         rasd_with_wrong_resource_type['ResourceType'] = pywbem.Uint16(19)
         rasd_with_wrong_resource_type['Connection'] = ["eth0"]
         rasd_with_wrong_resource_type['VlanTag'] = pywbem.Uint64(2)
         rasds = [rasd_with_wrong_resource_type]
         network = self.__CreateNetwork(rasds)
         if network != None:
             print 'Virtual Switch was created when it shouldnt have'
             result = 0
     except Exception, e:
         print 'Exception: %s' % str(e)
Beispiel #17
0
 def _create_disk_image (self, sr_to_use):
     print sr_to_use.items()
     [system_id, sep, pool_id] = sr_to_use['InstanceID'].partition('/')
     print 'PoolID - %s' % pool_id
     new_disk_sasd = CIMInstance('Xen_DiskSettingData')
     new_disk_sasd['ElementName'] = sys._getframe(0).f_code.co_name
     new_disk_sasd['ResourceType'] = pywbem.Uint16(19)
     new_disk_sasd['ResourceSubType'] = "Disk" 
     new_disk_sasd['VirtualQuantity'] = pywbem.Uint64(2048)
     new_disk_sasd['AllocationUnits'] = "MegaBytes"
     new_disk_sasd['Bootable'] = False
     new_disk_sasd['Access'] = pywbem.Uint8(3)
     new_disk_sasd['PoolID'] = pool_id
     in_params = {"ResourceSetting": new_disk_sasd}
     [rc, out_params] = self.conn.InvokeMethod("CreateDiskImage", self.spms[0], **in_params)
     new_disk = out_params["ResultingDiskImage"]
     print "Created Disk"
     print new_disk.items()
     return [rc, new_disk]
Beispiel #18
0
def CreateDiskImage(conn, spms, sr_to_use, size_in_bytes, name):
    print sr_to_use.items()
    [system_id, sep, pool_id] = sr_to_use['InstanceID'].partition('/')
    print 'PoolID - %s' % pool_id
    new_disk_sasd = CIMInstance('Xen_DiskSettingData')
    new_disk_sasd['ElementName'] = name
    new_disk_sasd['ResourceType'] = pywbem.Uint16(19)
    new_disk_sasd['ResourceSubType'] = "Disk"
    new_disk_sasd['VirtualQuantity'] = pywbem.Uint64(size_in_bytes)
    new_disk_sasd['AllocationUnits'] = "Bytes"
    new_disk_sasd['Bootable'] = False
    new_disk_sasd['Access'] = pywbem.Uint8(3)
    new_disk_sasd['PoolID'] = pool_id
    in_params = {"ResourceSetting": new_disk_sasd}
    [rc, out_params] = conn.InvokeMethod("CreateDiskImage", spms, **in_params)
    new_disk = out_params["ResultingDiskImage"]
    print "Created Disk"
    print new_disk.items()
    return [rc, new_disk]
Beispiel #19
0
    def get_num(self, numStr, datatype):
        """Get the ecom int from the number.

        :param numStr: the number in string format
        :param datatype: the type to convert it to
        :returns: result
        """
        try:
            result = {
                '8': pywbem.Uint8(numStr),
                '16': pywbem.Uint16(numStr),
                '32': pywbem.Uint32(numStr),
                '64': pywbem.Uint64(numStr)
            }
            result = result.get(datatype, numStr)
        except NameError:
            result = numStr

        return result
Beispiel #20
0
    def removeNonExistingResources(self):
        self.TestBegin()
        local_disk_rasd = CIMInstance('CIM_ResourceAllocationSettingData')
        local_disk_rasd['PoolID'] = self.DiskPoolID
        local_disk_rasd['Elementname'] = self.__class__.__name__ + '_Disk1'
        local_disk_rasd['ResourceType'] = pywbem.Uint16(19)
        local_disk_rasd['ResourceSubType'] = "Disk"
        local_disk_rasd['VirtualQuantity'] = pywbem.Uint64(2147483648)
        local_disk_rasd['AllocationUnits'] = "Bytes"

        rasds_to_delete = []
        rasds_to_delete.append(local_disk_rasd)
        in_params = {'ResourceSettings': rasds_to_delete}
        n = DeleteVMResources(self.conn, self.vsms[0], in_params)
        result = 0
        if (n == 1):
            print "Deleted non existing resource"
            result = 0
        else:
            result = 1
        self.TestEnd(result)
Beispiel #21
0
 def get_value(string):
     vtype, value = string.split(',', 1)
     if vtype == 'str':
         return str(value)
     elif vtype == 'uint8':
         return pywbem.Uint8(value)
     elif vtype == 'sint8':
         return pywbem.Sint8(value)
     elif vtype == 'uint16':
         return pywbem.Uint16(value)
     elif vtype == 'sint16':
         return pywbem.Sint16(value)
     elif vtype == 'uint32':
         return pywbem.Uint32(value)
     elif vtype == 'sint32':
         return pywbem.Sint32(value)
     elif vtype == 'uint64':
         return pywbem.Uint64(value)
     elif vtype == 'sint64':
         return pywbem.Sint64(value)
     else:
         print "Input value is invalid : %s" % string
         sys.exit(1)
Beispiel #22
0
def _create_test_instance(ch, name_of_atom, number, time):
    """ Create a TestAtom instance.  """
    global _inst_paths

    new_instance = pywbem.CIMInstance('TestAtom')
    new_instance['Name'] = name_of_atom
    new_instance['boolProp'] = False
    #new_instance['char16Prop']  =
    #new_instance['char16Propa'] = Null
    new_instance['dateProp'] = time
    new_instance['real32Prop'] = pywbem.Real32(number)
    #new_instance['real32Propa'] = pywbem.CIMProperty('Real32Propa', \ type='Real32', is_array=True, value=None)
    new_instance['real32Propa']  = [pywbem.Real32(number), \
                                    pywbem.Real32(number), \
                                    pywbem.Real32(number)]
    new_instance['real64Prop'] = pywbem.Real64(number)
    new_instance['real64Propa']  = [pywbem.Real64(number), \
                                    pywbem.Real64(number), \
                                    pywbem.Real64(number)]
    new_instance['sint16Prop'] = pywbem.Sint16(number)
    new_instance['sint16Propa']  = [pywbem.Sint16(number), \
                                    pywbem.Sint16(number), \
                                    pywbem.Sint16(number)]
    new_instance['sint32Prop'] = pywbem.Sint32(number)
    new_instance['sint32Propa']  = [pywbem.Sint32(number), \
                                    pywbem.Sint32(number), \
                                    pywbem.Sint32(number)]
    new_instance['sint64Prop'] = pywbem.Sint64(number)
    new_instance['sint64Propa']  = [pywbem.Sint64(number), \
                                    pywbem.Sint64(number), \
                                    pywbem.Sint64(number)]
    new_instance['sint8prop'] = pywbem.Sint8(number)
    new_instance['sint8Propa']   = [pywbem.Sint8(number), \
                                    pywbem.Sint8(number), \
                                    pywbem.Sint8(number)]
    new_instance['stringProp'] = name_of_atom
    new_instance['stringPropa'] = ['proton', 'electron', 'neutron']
    new_instance['uint16Prop'] = pywbem.Uint16(number)
    new_instance['uint16Propa']  = [pywbem.Uint16(number), \
                                    pywbem.Uint16(number), \
                                    pywbem.Uint16(number)]
    new_instance['uint32Prop'] = pywbem.Uint32(number)
    new_instance['uint32Propa']  = [pywbem.Uint32(number), \
                                    pywbem.Uint32(number), \
                                    pywbem.Uint32(number)]
    new_instance['uint64Prop'] = pywbem.Uint64(number)
    new_instance['uint64Propa']  = [pywbem.Uint64(number), \
                                    pywbem.Uint64(number), \
                                    pywbem.Uint64(number)]
    new_instance['uint8Prop'] = pywbem.Uint8(number)
    new_instance['uint8Propa']   = [pywbem.Uint8(number), \
                                    pywbem.Uint8(number), \
                                    pywbem.Uint8(number)]

    try:
        msg = ''
        cipath = ch.CreateInstance(new_instance)
        new_instance.path = cipath
        _inst_paths.append(cipath)

    except pywbem.CIMError, arg:
        raise
Beispiel #23
0
class TestMethods(unittest.TestCase):

    limits = {
        'sint8_min': pywbem.Sint8(-128),
        'sint8_max': pywbem.Sint8(127),
        'sint16_min': pywbem.Sint16(-32768),
        'sint16_max': pywbem.Sint16(32767),
        'sint32_min': pywbem.Sint32(-2147483648),
        'sint32_max': pywbem.Sint32(2147483647),
        'sint64_min': pywbem.Sint64(-92233736854775808L),
        'sint64_max': pywbem.Sint64(9223372036854775807L),
        'uint8_min': pywbem.Uint8(0),
        'uint8_max': pywbem.Uint8(0xFF),
        'uint16_min': pywbem.Uint16(0),
        'uint16_max': pywbem.Uint16(0xFFFF),
        'uint32_min': pywbem.Uint32(0),
        'uint32_max': pywbem.Uint32(0xFFFFFFFF),
        'uint64_min': pywbem.Uint64(0L),
        'uint64_max': pywbem.Uint64(0x7FFFFFFFFFFFFFFFL),
        'real32_min': pywbem.Real32(-123456.78),
        'real32_max': pywbem.Real32(123456.78),
        'real64_min': pywbem.Real64(-12345678987654.32),
        'real64_max': pywbem.Real64(12345678987654.32)
    }
    # note: the last Uint64 value should be 0xFFFFFFFFFFFFFFFF but there is a bug somewhere...

    inttypes = [
        'sint8', 'sint16', 'sint32', 'sint64', 'uint8', 'uint16', 'uint32',
        'uint64'
    ]

    realtypes = ['real32', 'real64']

    zeros = {
        'sint8': pywbem.Sint8(0),
        'sint16': pywbem.Sint16(0),
        'sint32': pywbem.Sint32(0),
        'sint64': pywbem.Sint64(0),
        'uint8': pywbem.Uint8(0),
        'uint16': pywbem.Uint16(0),
        'uint32': pywbem.Uint32(0),
        'uint64': pywbem.Uint64(0),
        'real32': pywbem.Real32(0),
        'real64': pywbem.Real64(0)
    }

    ones = {
        'sint8': pywbem.Sint8(1),
        'sint16': pywbem.Sint16(1),
        'sint32': pywbem.Sint32(1),
        'sint64': pywbem.Sint64(1),
        'uint8': pywbem.Uint8(1),
        'uint16': pywbem.Uint16(1),
        'uint32': pywbem.Uint32(1),
        'uint64': pywbem.Uint64(1),
        'real32': pywbem.Real32(0),
        'real64': pywbem.Real64(0)
    }

    tens = {
        'sint8': pywbem.Sint8(10),
        'sint16': pywbem.Sint16(10),
        'sint32': pywbem.Sint32(10),
        'sint64': pywbem.Sint64(10),
        'uint8': pywbem.Uint8(10),
        'uint16': pywbem.Uint16(10),
        'uint32': pywbem.Uint32(10),
        'uint64': pywbem.Uint64(10),
        'real32': pywbem.Real32(10),
        'real64': pywbem.Real64(10)
    }

    twenties = {
        'sint8': pywbem.Sint8(20),
        'sint16': pywbem.Sint16(20),
        'sint32': pywbem.Sint32(20),
        'sint64': pywbem.Sint64(20),
        'uint8': pywbem.Uint8(20),
        'uint16': pywbem.Uint16(20),
        'uint32': pywbem.Uint32(20),
        'uint64': pywbem.Uint64(20),
        'real32': pywbem.Real32(20),
        'real64': pywbem.Real64(20)
    }

    numlists = {
        'sint8': [
            pywbem.Sint8(8),
            pywbem.Sint8(2),
            pywbem.Sint8(5),
            pywbem.Sint8(6),
            pywbem.Sint8(3),
            pywbem.Sint8(9),
            pywbem.Sint8(7),
            pywbem.Sint8(1),
            pywbem.Sint8(4)
        ],
        'sint16': [
            pywbem.Sint16(8),
            pywbem.Sint16(2),
            pywbem.Sint16(5),
            pywbem.Sint16(6),
            pywbem.Sint16(3),
            pywbem.Sint16(9),
            pywbem.Sint16(7),
            pywbem.Sint16(1),
            pywbem.Sint16(4)
        ],
        'sint32': [
            pywbem.Sint32(8),
            pywbem.Sint32(2),
            pywbem.Sint32(5),
            pywbem.Sint32(6),
            pywbem.Sint32(3),
            pywbem.Sint32(9),
            pywbem.Sint32(7),
            pywbem.Sint32(1),
            pywbem.Sint32(4)
        ],
        'sint64': [
            pywbem.Sint64(8),
            pywbem.Sint64(2),
            pywbem.Sint64(5),
            pywbem.Sint64(6),
            pywbem.Sint64(3),
            pywbem.Sint64(9),
            pywbem.Sint64(7),
            pywbem.Sint64(1),
            pywbem.Sint64(4)
        ],
        'uint8': [
            pywbem.Uint8(8),
            pywbem.Uint8(2),
            pywbem.Uint8(5),
            pywbem.Uint8(6),
            pywbem.Uint8(3),
            pywbem.Uint8(9),
            pywbem.Uint8(7),
            pywbem.Uint8(1),
            pywbem.Uint8(4)
        ],
        'uint16': [
            pywbem.Uint16(8),
            pywbem.Uint16(2),
            pywbem.Uint16(5),
            pywbem.Uint16(6),
            pywbem.Uint16(3),
            pywbem.Uint16(9),
            pywbem.Uint16(7),
            pywbem.Uint16(1),
            pywbem.Uint16(4)
        ],
        'uint32': [
            pywbem.Uint32(8),
            pywbem.Uint32(2),
            pywbem.Uint32(5),
            pywbem.Uint32(6),
            pywbem.Uint32(3),
            pywbem.Uint32(9),
            pywbem.Uint32(7),
            pywbem.Uint32(1),
            pywbem.Uint32(4)
        ],
        'uint64': [
            pywbem.Uint64(8),
            pywbem.Uint64(2),
            pywbem.Uint64(5),
            pywbem.Uint64(6),
            pywbem.Uint64(3),
            pywbem.Uint64(9),
            pywbem.Uint64(7),
            pywbem.Uint64(1),
            pywbem.Uint64(4)
        ],
        'real32': [
            pywbem.Real32(8),
            pywbem.Real32(2),
            pywbem.Real32(5),
            pywbem.Real32(6),
            pywbem.Real32(3),
            pywbem.Real32(9),
            pywbem.Real32(7),
            pywbem.Real32(1),
            pywbem.Real32(4)
        ],
        'real64': [
            pywbem.Real64(8),
            pywbem.Real64(2),
            pywbem.Real64(5),
            pywbem.Real64(6),
            pywbem.Real64(3),
            pywbem.Real64(9),
            pywbem.Real64(7),
            pywbem.Real64(1),
            pywbem.Real64(4)
        ]
    }

    def _dbgPrint(self, msg=''):
        if self._verbose:
            if len(msg):
                print('\t -- %s --' % msg)
            else:
                print('')

    def setUp(self):
        unittest.TestCase.setUp(self)
        wconn = wbem_connection.wbem_connection()
        self.conn = wconn._WBEMConnFromOptions(_g_opts)
        for iname in self.conn.EnumerateInstanceNames('TestMethod'):
            self.conn.DeleteInstance(iname)
        self._verbose = _g_opts.verbose
        self._dbgPrint()

    def tearDown(self):
        unittest.TestCase.tearDown(self)
        for iname in self.conn.EnumerateInstanceNames('TestMethod'):
            self.conn.DeleteInstance(iname)

    def _run_and_validate_getrand(self,
                                  type,
                                  methodName,
                                  min,
                                  max,
                                  expectedReturnValue=None,
                                  minReturnValue=None,
                                  maxReturnValue=None):
        isRealType = False
        if type.startswith('real'):
            isRealType = True
        if isRealType:
            self._dbgPrint('Testing %s invocation with min=%f, max=%f' %
                           (methodName, min, max))
        else:
            self._dbgPrint('Testing %s invocation with min=%d, max=%d' %
                           (methodName, min, max))
        (rv, oparams) = self.conn.InvokeMethod(methodName,
                                               'TestMethod',
                                               min=min,
                                               max=max)
        if not oparams['success']:
            self.fail(
                '"Success" reported as false for invocation of method %s' %
                methodName)
        if expectedReturnValue is not None:
            if isRealType:
                self._dbgPrint(
                    'Verifying return value (%f) equal to expected return value %f...'
                    % (rv, expectedReturnValue))
                if abs(expectedReturnValue - rv) > real_tolerance:
                    self.fail(
                        'Return value not as expected for invocation of method %s'
                        % methodName)
            else:
                self._dbgPrint(
                    'Verifying return value (%d) equal to expected return value %d...'
                    % (rv, expectedReturnValue))
                if expectedReturnValue != rv:
                    self.fail(
                        'Return value not as expected for invocation of method %s'
                        % methodName)
            self._dbgPrint('Return value is as expected.')
        if minReturnValue is not None:
            if isRealType:
                self._dbgPrint('Verifying return value (%f) >= %f' %
                               (rv, minReturnValue))
            else:
                self._dbgPrint('Verifying return value (%d) >= %d' %
                               (rv, minReturnValue))
            if rv < minReturnValue:
                self.fail(
                    'Return value less than expected for invocation of method %s'
                    % methodName)
            self._dbgPrint('Return value is as expected.')
        if maxReturnValue is not None:
            if isRealType:
                self._dbgPrint('Verifying return value (%f) <= %f' %
                               (rv, maxReturnValue))
            else:
                self._dbgPrint('Verifying return value (%d) <= %d' %
                               (rv, maxReturnValue))
            if rv > maxReturnValue:
                self.fail(
                    'Return value greater than expected for invocation of method %s'
                    % methodName)
            self._dbgPrint('Return value is as expected.')

    def _run_and_validate_getrandlist(self, type, methodName, min, max,
                                      nelems):
        isRealType = False
        if type.startswith('real'):
            isRealType = True
        if isRealType:
            self._dbgPrint('Testing %s invocation with min=%f, max=%f' %
                           (methodName, min, max))
        else:
            self._dbgPrint('Testing %s invocation with min=%d, max=%d' %
                           (methodName, min, max))
        (rv, oparams) = self.conn.InvokeMethod(methodName,
                                               'TestMethod',
                                               lo=min,
                                               hi=max,
                                               nelems=nelems)
        if not rv:
            self.fail('Invocation of %s returned false success value.' %
                      methodName)
        self._dbgPrint('Invocation of %s returned successfully.' % methodName)
        if isRealType:
            self._dbgPrint('Validating lo (%f) and hi (%f) outparams...' %
                           (min, max))
            if abs(oparams['lo'] - min) > real_tolerance:
                self.fail(
                    'Returned low range value (%f) not equal to specified value (%f).'
                    % (oparams['lo'], min))
            if abs(oparams['hi'] - max) > real_tolerance:
                self.fail(
                    'Returned high range value (%f) not equal to specified value (%f).'
                    % (oparams['hi'], max))
        else:
            self._dbgPrint('Validating lo (%d) and hi (%d) outparams...' %
                           (min, max))
            if oparams['lo'] != min:
                self.fail(
                    'Returned low range value (%d) not equal to specified value (%d).'
                    % (oparams['lo'], min))
            if oparams['hi'] != max:
                self.fail(
                    'Returned high range value (%d) not equal to specified value (%d).'
                    % (oparams['hi'], max))
        self._dbgPrint('Lo and hi outparams validated successfully.')
        self._dbgPrint('Validating random list values...')
        if oparams['nlist'] is None:
            self.fail('Expected a list of values but got none.')
        if len(oparams['nlist']) != nelems:
            self.fail('Expected a list of %d items but got %d items instead.' %
                      (nelems, len(oparams['nlist'])))
        minkey = '%s_min' % type
        maxkey = '%s_max' % type
        for num in oparams['nlist']:
            if num < TestMethods.limits[minkey] or \
                    num > TestMethods.limits[maxkey]:
                if isRealType:
                    self.fail(
                        'List element %f not in expected range for type %s.' %
                        (num, type))
                else:
                    self.fail(
                        'List element %d not in expected range for type %s.' %
                        (num, type))
        self._dbgPrint('Random list values validated successfully.')

    def _run_and_validate_minmedmax(self, type, methodName, numlist):
        self._dbgPrint('Testing %s invocation' % methodName)
        (rv, oparams) = self.conn.InvokeMethod(methodName,
                                               'TestMethod',
                                               numlist=numlist)
        if not rv:
            self.fail('Invocation of %s returned false success value.' %
                      methodName)
        self._dbgPrint('Invocation of %s returned successfully.' % methodName)
        self._dbgPrint('Validating min, median, and max outparams...')
        if oparams['min'] != 1:
            self.fail('Expected min of 1 but instead got %d' % oparams['min'])
        if oparams['max'] != 9:
            self.fail('Expected max of 9 but instead got %d' % oparams['max'])
        if oparams['med'] != 5:
            self.fail('Expected median of 5 but instead got %d' %
                      oparams['med'])
        self._dbgPrint('Min, median, and max values validated successfully.')

    def _run_numeric_type_tests(self, typelist):
        gr = self._run_and_validate_getrand
        grl = self._run_and_validate_getrandlist
        mmm = self._run_and_validate_minmedmax
        for type in typelist:
            method = 'genRand_%s' % type
            minkey = '%s_min' % type
            maxkey = '%s_max' % type
            min = TestMethods.limits[minkey]
            max = TestMethods.limits[maxkey]
            gr(type, method, min, max, None, min, max)
            gr(type, method, min, min, min)
            gr(type, method, max, max, max)
            if min != 0:
                gr(type, method, TestMethods.zeros[type],
                   TestMethods.zeros[type], TestMethods.zeros[type])
            gr(type, method, TestMethods.tens[type],
               TestMethods.twenties[type], None, TestMethods.tens[type],
               TestMethods.twenties[type])
            # the next two should cause exceptions; getting a TypeError exception is not an error in this case.
            try:
                gr(type, method, min - 1, min - 1, min - 1)
            except TypeError:
                pass
            try:
                gr(type, method, max + 1, max + 1, max + 1)
            except TypeError:
                pass

            method = 'genRandList_%s' % type
            nelems = _typed_randrange(TestMethods.tens[type],
                                      TestMethods.twenties[type], type)
            grl(type, method, min, max, nelems)
            grl(type, method, min, max, TestMethods.ones[type])
            grl(type, method, min, max, TestMethods.zeros[type])
            if min != 0:
                grl(type, method, TestMethods.zeros[type], max, nelems)
            else:
                grl(type, method, min, TestMethods.zeros[type], nelems)
            grl(type, method, TestMethods.tens[type],
                TestMethods.twenties[type], nelems)
            grl(type, method, TestMethods.tens[type],
                TestMethods.twenties[type], TestMethods.ones[type])
            grl(type, method, TestMethods.tens[type],
                TestMethods.twenties[type], TestMethods.zeros[type])

            method = 'minmedmax_%s' % type
            mmm(type, method, TestMethods.numlists[type])

    def test_integer_types(self):
        self._run_numeric_type_tests(TestMethods.inttypes)

    def test_real_types(self):
        self._run_numeric_type_tests(TestMethods.realtypes)

    def test_refs(self):
        inst = pywbem.CIMInstance('TestMethod',
                                  properties={
                                      'id': 'one',
                                      'p_str': 'One',
                                      'p_sint32': pywbem.Sint32(1)
                                  })
        self.conn.CreateInstance(inst)

        iname = pywbem.CIMInstanceName('TestMethod',
                                       namespace='root/cimv2',
                                       keybindings={'id': 'one'})
        rv, outs = self.conn.InvokeMethod('getStrProp', iname)
        self.assertEquals(rv, 'One')

        rv, outs = self.conn.InvokeMethod('setStrProp', iname, value='won')
        self.assertFalse(outs)
        self.assertEquals(rv, 'One')
        rv, outs = self.conn.InvokeMethod('getStrProp', iname)
        self.assertEquals(rv, 'won')
        inst = self.conn.GetInstance(iname)
        self.assertEquals(inst['p_str'], 'won')

        rv, outs = self.conn.InvokeMethod('getIntProp', iname)
        self.assertEquals(rv, 1)
        self.assertTrue(isinstance(rv, pywbem.Sint32))
        self.assertEquals(inst['p_sint32'], 1)
        rv, outs = self.conn.InvokeMethod('setIntProp',
                                          iname,
                                          value=pywbem.Sint32(2))
        self.assertTrue(isinstance(rv, pywbem.Sint32))
        self.assertEquals(rv, 1)
        self.assertFalse(outs)
        rv, outs = self.conn.InvokeMethod('getIntProp', iname)
        self.assertEquals(rv, 2)
        self.assertTrue(isinstance(rv, pywbem.Sint32))
        inst = self.conn.GetInstance(iname)
        self.assertEquals(inst['p_sint32'], 2)

        rv, outs = self.conn.InvokeMethod('getObjectPath', 'TestMethod')
        self.assertTrue(isinstance(outs['path'], pywbem.CIMInstanceName))
        self.assertEquals(outs['path']['id'], 'one')

        inst = pywbem.CIMInstance('TestMethod',
                                  properties={
                                      'id': 'two',
                                      'p_str': 'Two',
                                      'p_sint32': pywbem.Sint32(2)
                                  })
        self.conn.CreateInstance(inst)

        rv, outs = self.conn.InvokeMethod('getObjectPaths', 'TestMethod')
        self.assertEquals(len(outs['paths']), 2)
        self.assertTrue(isinstance(outs['paths'][0], pywbem.CIMInstanceName))
        to_delete = outs['paths']

        inst = pywbem.CIMInstance('TestMethod',
                                  properties={
                                      'id': 'three',
                                      'p_str': 'Three',
                                      'p_sint32': pywbem.Sint32(3)
                                  })
        self.conn.CreateInstance(inst)

        iname = pywbem.CIMInstanceName('TestMethod',
                                       namespace='root/cimv2',
                                       keybindings={'id': 'three'})

        inames = self.conn.EnumerateInstanceNames('TestMethod')
        self.assertEquals(len(inames), 3)
        rv, outs = self.conn.InvokeMethod('delObject',
                                          'TestMethod',
                                          path=iname)

        inames = self.conn.EnumerateInstanceNames('TestMethod')
        self.assertEquals(len(inames), 2)

        self.conn.CreateInstance(inst)
        '''  # OpenWBEM is broken!  uncomment this for Pegasus.  '''
        rv, outs = self.conn.InvokeMethod('delObjects',
                                          'TestMethod',
                                          paths=to_delete)

        inames = self.conn.EnumerateInstanceNames('TestMethod')
        self.assertEquals(len(inames), 1)
        self.assertEquals(inames[0]['id'], 'three')

    def test_mkUniStr_sint8(self):
        s = 'Scrum Rocks!'
        l = [pywbem.Sint8(ord(x)) for x in s]
        rv, outs = self.conn.InvokeMethod('mkUniStr_sint8',
                                          'TestMethod',
                                          cArr=l)
        self.assertFalse(outs)
        self.assertEquals(rv, s)
        rv, outs = self.conn.InvokeMethod('mkUniStr_sint8',
                                          'TestMethod',
                                          cArr=[])
        self.assertEquals(rv, '')

    def test_strCat(self):
        ra = ['one', 'two', 'three', 'four']
        rv, outs = self.conn.InvokeMethod('strCat',
                                          'TestMethod',
                                          strs=ra,
                                          sep=',')
        self.assertEquals(rv, ','.join(ra))
        self.assertFalse(outs)

    def test_strSplit(self):
        ra = 'one,two,three,four'
        rv, outs = self.conn.InvokeMethod('strSplit',
                                          'TestMethod',
                                          str=ra,
                                          sep=',')
        self.assertEquals(outs['elems'], ra.split(','))
        self.assertTrue(ra)

    def test_getDate(self):
        dt = pywbem.CIMDateTime.now()
        rv, outs = self.conn.InvokeMethod('getDate',
                                          'TestMethod',
                                          datestr=str(dt))
        self.assertFalse(outs)
        self.assertEquals(rv, dt)
        self.assertEquals(str(rv), str(dt))
        self.assertTrue(isinstance(rv, pywbem.CIMDateTime))

    def test_getDates(self):
        dt = pywbem.CIMDateTime.now()
        s1 = str(dt)
        ra = [s1]
        dt = pywbem.CIMDateTime(pywbem.datetime.now() + \
                pywbem.timedelta(seconds=10))
        s2 = str(dt)
        ra.append(s2)
        dt = pywbem.CIMDateTime(pywbem.datetime.now() + \
                pywbem.timedelta(seconds=10))
        s3 = str(dt)
        ra.append(s3)

        rv, outs = self.conn.InvokeMethod('getDates',
                                          'TestMethod',
                                          datestrs=ra)
        self.assertTrue(rv)
        self.assertTrue(isinstance(rv, bool))
        self.assertEquals(outs['nelems'], len(ra))
        self.assertTrue(isinstance(outs['nelems'], pywbem.Sint32))

        for i in range(0, len(ra)):
            self.assertTrue(isinstance(outs['elems'][i], pywbem.CIMDateTime))
            self.assertEquals(str(outs['elems'][i]), ra[i])

    def test_minmedmax(self):
        for tstr in [
                'Sint8', 'Uint8', 'Sint16', 'Uint16', 'Sint32', 'Uint32',
                'Sint64', 'Uint64', 'Real32', 'Real64'
        ]:
            dt = getattr(pywbem, tstr)
            method = 'minmedmax_%s' % tstr
            numlist = [
                dt(2),
                dt(5),
                dt(8),
                dt(1),
                dt(9),
                dt(6),
                dt(4),
                dt(7),
                dt(3),
            ]
            rv, outs = self.conn.InvokeMethod(method,
                                              'TestMethod',
                                              numlist=numlist)
            self.assertTrue(rv)
            self.assertTrue(isinstance(rv, bool))
            self.assertTrue(isinstance(outs['min'], dt))
            self.assertTrue(isinstance(outs['med'], dt))
            self.assertTrue(isinstance(outs['max'], dt))
            self.assertEquals(outs['min'], 1)
            self.assertEquals(outs['max'], 9)
            self.assertEquals(outs['med'], 5)
Beispiel #24
0
    def get_instance(self, env, model, cim_class, stat=None):
        """Return an instance.

        Keyword arguments:
        env -- Provider Environment
        model -- A template of the CIMInstance to be returned.  The key 
            properties are set on this instance to correspond to the 
            instanceName that was requested.  The properties of the model
            are already filtered according to the PropertyList from the 
            request.
        cim_class -- The CIMClass

        Possible Errors:
        CIM_ERR_ACCESS_DENIED
        CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized 
            or otherwise incorrect parameters)
        CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM 
            Instance does not exist in the specified namespace)
        CIM_ERR_FAILED (some other unspecified error occurred)

        """

        if stat is None:
            stat = os.stat(model['lfname'])
        statvfs = os.statvfs(model['lfname'])
        mode = stat[ST_MODE]

        model['SetUid'] = bool(mode & S_ISUID)
        model['HealthState'] = self.Values_HealthState.OK
        #model['PosixSyncIo'] = # TODO (type = uint64)
        #model['StatusDescriptions'] = # TODO (type = string[])
        model['GroupWritable'] = bool(mode & S_IWGRP)
        #model['PosixChownRestricted'] = # TODO (type = uint64)
        model['LinkCount'] = pywbem.Uint64(stat[ST_NLINK])
        model['UserWritable'] = bool(mode & S_IWUSR)
        #model['LinkMax'] = # TODO (type = uint64)
        model['OperationalStatus'] = [self.Values_OperationalStatus.OK]
        model['SetGid'] = bool(mode & S_ISGID)
        model['SaveText'] = bool(mode & S_ISVTX)
        try:
            gid = grp.getgrgid(stat[ST_GID])[0]
        except KeyError:
            gid = str(stat[ST_GID])
        model['GroupID'] = gid
        model['UserExecutable'] = bool(mode & S_IXUSR)
        #model['Status'] = # TODO (type = string)
        #model['Description'] = # TODO (type = string)
        #model['InstallDate'] = # TODO (type = datetime)
        #model['LastModifiedInode'] = # TODO (type = datetime)
        model['WorldReadable'] = bool(mode & S_IROTH)
        #model['PosixPrioIo'] = # TODO (type = uint64)
        #model['PathMax'] = # TODO (type = uint64)
        model['WorldExecutable'] = bool(mode & S_IXOTH)
        model['GroupReadable'] = bool(mode & S_IRGRP)
        model['NameMax'] = pywbem.Uint64(statvfs[F_NAMEMAX])
        model['Name'] = model['lfname']
        model['ElementName'] = model['name'] == '/' and '/' or \
                    os.path.basename(model['name'])
        try:
            uid = pwd.getpwuid(stat[ST_UID])[0]
        except:
            uid = str(stat[ST_UID])
        model['UserID'] = uid
        model['UserReadable'] = bool(mode & S_IRUSR)
        model['GroupExecutable'] = bool(mode & S_IXGRP)
        #model['Caption'] = # TODO (type = string)
        #model['PosixAsyncIo'] = # TODO (type = uint64)
        model['WorldWritable'] = bool(mode & S_IWOTH)
        #model['PosixNoTrunc'] = # TODO (type = uint64)
        model['FileInodeNumber'] = str(stat[ST_INO])
        return model
Beispiel #25
0
            rasd_with_wrong_resource_type['VlanTag'] = pywbem.Uint64(2)
            rasds = [rasd_with_wrong_resource_type]
            network = self.__CreateNetwork(rasds)
            if network != None:
                print 'Virtual Switch was created when it shouldnt have'
                result = 0
        except Exception, e:
            print 'Exception: %s' % str(e)
        # RASD where Connection property is of invalid type
        print 'Error Test: bad RASD with bad Connection property'
        try:
            rasd_with_wrong_connection = CIMInstance(
                'CIM_ResourceAllocationSettingData')
            rasd_with_wrong_connection['ResourceType'] = pywbem.Uint16(33)
            rasd_with_wrong_connection['Connection'] = pywbem.Uint32(1234)
            rasd_with_wrong_connection['VlanTag'] = pywbem.Uint64(2)
            rasds = [rasd_with_wrong_connection]
            network = self.__CreateNetwork(rasds)
            if network != None:
                print 'Virtual Switch was created when it shouldnt have'
                result = 0
        except Exception, e:
            print 'Exception: %s' % str(e)

        self.TestEnd(result)

    def DeleteNetworkErrorTests(self):
        self.TestBegin()
        result = 1
        # specify a bad (non-existent) switch reference
        print 'Error Test: Bad switch reference'
Beispiel #26
0
def create_partition(ns, device, size=None, partition_type=None):
    """
    Create new partition on given device.

    :type device: LMIInstance/CIM_StorageExtent or string
    :param device: Device which should be partitioned.
    :type size: int
    :param size: Size of the device, in blocks. See device's BlockSize
        to get it. If no size is provided, the largest possible partition
        is created.
    :type partition_type: int
    :param partition_type: Requested partition type.
        See PARTITION_TYPE_xxx variables. If no type is given, extended partition
        will be automatically created as 4th partition on MS-DOS style partition
        table with a logical partition with requested size on it.

    :rtype: LMIInstance/CIM_GenericDiskPartition.
    """
    device = common.str2device(ns, device)
    setting = None

    try:
        args = {'extent': device}
        if size:
            args['Size'] = pywbem.Uint64(size)

        if partition_type:
            # create a setting and modify it
            caps = ns.LMI_DiskPartitionConfigurationCapabilities\
                        .first_instance()
            (ret, outparams, err) = caps.CreateSetting()
            if ret != 0:
                if err:
                    LmiFailed("Cannot create " \
                        "LMI_DiskPartitionConfigurationSetting for the " \
                        "partition: %s." % err)
                raise LmiFailed("Cannot create " \
                        "LMI_DiskPartitionConfigurationSetting for the " \
                        "partition: %d." % ret)
            setting = outparams['setting'].to_instance()
            setting.PartitionType = pywbem.Uint16(partition_type)
            (ret, _outparams, err) = setting.push()
            if ret != 0:
                if err:
                    raise LmiFailed("Cannot change " \
                            "LMI_DiskPartitionConfigurationSetting for the " \
                            "partition: %s." % err)
                raise LmiFailed("Cannot change " \
                        "LMI_DiskPartitionConfigurationSetting for the " \
                        "partition: %d." % ret)
            args['Goal'] = setting

        service = ns.LMI_DiskPartitionConfigurationService.first_instance()
        (ret, outparams, err) = service.SyncLMI_CreateOrModifyPartition(**args)
        if ret != 0:
            if err:
                raise LmiFailed("Cannot create the partition: %s." % err)
            values = service.LMI_CreateOrModifyPartition\
                    .LMI_CreateOrModifyPartitionValues
            raise LmiFailed("Cannot create the partition: %s." %
                            (values.value_name(ret)))
    finally:
        if setting:
            setting.delete()
    return outparams['Partition']
    def get_instance(self, env, model, withCleanup=True):
        """Return an instance.

        Keyword arguments:
        env -- Provider Environment (pycimmb.ProviderEnvironment)
        model -- A template of the pywbem.CIMInstance to be returned.  The 
            key properties are set on this instance to correspond to the 
            instanceName that was requested.  The properties of the model
            are already filtered according to the PropertyList from the 
            request.  Only properties present in the model need to be
            given values.  If you prefer, you can set all of the 
            values, and the instance will be filtered for you. 

        Possible Errors:
        CIM_ERR_ACCESS_DENIED
        CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized 
            or otherwise incorrect parameters)
        CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM 
            Instance does not exist in the specified namespace)
        CIM_ERR_FAILED (some other unspecified error occurred)

        """

        logger = env.get_logger()
        logger.log_debug('Entering %s.get_instance()' \
                % self.__class__.__name__)

        if withCleanup:
            self._populateTroveCache()

        troveId = model['InstanceID']

        nvf, isInstalled = self._conarySoftwareMap[troveId]

        modelName = modelDescription = nvf[0]
        if isInstalled is self.installationService.SystemModelType:
            # We use the system model's file mtime as the version timestamp
            verTimestamp = int(nvf[2])
            operatingStatus = self.Values.OperatingStatus.In_Service
            productLabel = self.installationService.SystemModelElementName
            versionString = nvf[1]
        else:
            # Our timestamps are 32-bit, so we store the 2 MSB as buildNumber
            # and the 2LSB as the revision number.
            verTimestamp = int(nvf[1].trailingRevision().getTimestamp())
            operatingStatus = ((isInstalled
                                and self.Values.OperatingStatus.In_Service)
                               or self.Values.OperatingStatus.Dormant)

            productLabel = str(nvf[1].trailingLabel())
            versionString = "%s[%s]" % (nvf[1].freeze(), str(nvf[2]))

        buildNumber = verTimestamp & 0xFFFF
        revisionNumber = (verTimestamp & 0xFFFF0000) >> 16
        vendorURL = 'http://www.rpath.org/rbuilder'

        model['BuildNumber'] = pywbem.Uint16(buildNumber)
        #model['Caption'] = '' # TODO
        #model['ClassificationDescriptions'] = ['',] # TODO
        #model['Classifications'] = [self.Values.Classifications.<VAL>,] # TODO
        #model['CommunicationStatus'] = self.Values.CommunicationStatus.<VAL> # TODO
        model['Description'] = modelDescription
        #model['DetailedStatus'] = self.Values.DetailedStatus.<VAL> # TODO
        model['ElementName'] = modelName
        #model['ExtendedResourceType'] = self.Values.ExtendedResourceType.<VAL> # TODO
        #model['Generation'] = pywbem.Uint64() # TODO
        model['HealthState'] = self.Values.HealthState.OK
        # XXX Some of these have hard-coded values
        model['IdentityInfoType'] = [
            'VMware-VAMI:VendorUUID', 'VMware-VAMI:ProductRID',
            'VMware-VAMI:VendorURL', 'VMware-VAMI:ProductURL',
            'VMware-VAMI:SupportURL', 'VMware-VAMI:UpdateInfo'
        ]
        model['IdentityInfoValue'] = [
            'com.rpath', productLabel, vendorURL,
            'http://www.rpath.org/project/remote-update', vendorURL, ''
        ]
        #model['InstallDate'] = pywbem.CIMDateTime() # TODO
        model['IsEntity'] = True
        model['IsLargeBuildNumber'] = True
        #model['Languages'] = ['',] # TODO
        model['LargeBuildNumber'] = pywbem.Uint64(verTimestamp)
        model['MajorVersion'] = pywbem.Uint16(0)
        model['Manufacturer'] = 'rPath, Inc.'
        #model['MinExtendedResourceTypeBuildNumber'] = pywbem.Uint16() # TODO
        #model['MinExtendedResourceTypeMajorVersion'] = pywbem.Uint16() # TODO
        #model['MinExtendedResourceTypeMinorVersion'] = pywbem.Uint16() # TODO
        #model['MinExtendedResourceTypeRevisionNumber'] = pywbem.Uint16() # TODO
        model['MinorVersion'] = pywbem.Uint16(0)
        model['Name'] = modelName
        model['OperatingStatus'] = operatingStatus
        #model['OperationalStatus'] = [self.Values.OperationalStatus.<VAL>,] # TODO
        #model['OtherExtendedResourceTypeDescription'] = '' # TODO
        model['PrimaryStatus'] = self.Values.PrimaryStatus.OK
        model['ReleaseDate'] = pywbem.CIMDateTime(
            utils.Time.format(verTimestamp))
        model['RevisionNumber'] = pywbem.Uint16(revisionNumber)
        #model['SerialNumber'] = '' # TODO
        #model['Status'] = self.Values.Status.<VAL> # TODO
        #model['StatusDescriptions'] = ['',] # TODO
        #model['TargetOperatingSystems'] = ['',] # TODO
        model['TargetOSTypes'] = [
            self.Values.TargetOSTypes.LINUX,
        ]
        #model['TargetTypes'] = ['',] # TODO
        model['VersionString'] = versionString
        if withCleanup:
            self._conarySoftwareMap.clear()
        return model
Beispiel #28
0
    def __init__(self,
                 Ip,
                 userName,
                 password,
                 need_shared_storage=False,
                 create_vms=True,
                 logfile=None):
        dir = os.getcwd()
        if logfile == None:
            self.logfilename = sys._getframe(2).f_code.co_filename + ".log"
        else:
            self.logfilename = logfile
        print "Location of result log : " + self.logfilename
        self.oldstdout = sys.stdout
        self.oldstderr = sys.stderr
        self.logfile = open(self.logfilename, 'w')
        sys.stdout = self.logfile
        sys.stderr = self.logfile

        print 'TestSetup...'

        verbose = "false"
        for arg in sys.argv:
            if arg == "verbose":
                verbose = "true"

        # some useful counters
        self.TestsPassed = 0
        self.TestsFailed = 0
        self.TestFailedDescriptions = ""

        #self.inputMsg = ">"
        self.IPAddress = Ip
        self.UserName = userName
        self.Password = password

        self.hvmname = 'test-hvm-vm'
        self.pvname = 'test-pv-vm'
        self.pv_test_vm = None
        self.hvm_test_vm = None

        # create a CIM connection to the server
        self.conn = pywbem.WBEMConnection('http://' + self.IPAddress,
                                          (self.UserName, self.Password))

        # Enumerate the Xen Pool
        my_pool = None
        pools = self.conn.EnumerateInstances("Xen_HostPool")
        if len(pools) != 0:
            my_pool = pools[0]

        # Enumerate all networks and pick an appropriate network to use
        network_to_use = None
        networks = self.conn.EnumerateInstances("Xen_NetworkConnectionPool")
        for network in networks:
            network_to_use = network  # pick the first one ? this will be what the VM will be connected on
            break
        print "Using Network: %s (%s)" % (network_to_use['PoolID'],
                                          network_to_use['Name'])

        # Pick an appropriate SR for use in tests
        self.sr_to_use = None
        sr_to_use_local = None
        if my_pool != None:
            # Try the default storage of the host pool, if available
            if my_pool['DefaultStoragePoolID'] != None and my_pool[
                    'DefaultStoragePoolID'] != '':
                print 'default storage pool id %s' % my_pool[
                    'DefaultStoragePoolID']
                #query_str = "SELECT * FROM Xen_StoragePool WHERE InstanceID = \""+my_pool['DefaultStoragePoolID']+"\""
                query_str = "SELECT * FROM Xen_StoragePool WHERE InstanceID LIKE \"%" + my_pool[
                    'DefaultStoragePoolID'] + "%\""
                print 'Executing query: %s' % query_str
                defsrs = self.conn.ExecQuery("WQL", query_str, "root/cimv2")
                sr_to_use_local = defsrs[0]
                #sr_ref = CIMInstanceName(classname="Xen_StoragePool", keybindings={"InstanceID":'Xen:Shared\\'+my_pool["DefaultStoragePoolID"]})
                #sr_to_use_local  = self.conn.GetInstance(sr_ref)
        if sr_to_use_local == None:  # No default SR is available
            srs = self.conn.EnumerateInstances("Xen_StoragePool")
            for sr in srs:
                if sr['ResourceSubType'] == 'nfs' or sr[
                        'ResourceSubType'] == 'lvmoiscsi':
                    sr_to_use_local = sr
                    break
                elif need_shared_storage == False and sr[
                        'Name'] == 'Local storage':
                    sr_to_use_local = sr
                    break
        print "Using SR: %s (%s)" % (sr_to_use_local["PoolID"],
                                     sr_to_use_local['Name'])

        # create CIM reference out of CIM instance
        self.sr_to_use = CIMInstanceName(
            classname=sr_to_use_local.classname,
            keybindings={"InstanceID": sr_to_use_local["InstanceID"]})
        self.DiskPoolID = sr_to_use_local['PoolID']

        # Get instance of Virtual System Management Service
        self.vsms = self.conn.EnumerateInstanceNames(
            "Xen_VirtualSystemManagementService")

        ################ Virtual System Setting Data (VSSD) ################
        # VSSD for a PV VM type
        self.pv_vssd = CIMInstance("Xen_ComputerSystemSettingData")
        self.pv_vssd['Description'] = 'Test PV VM'
        self.pv_vssd['ElementName'] = self.__class__.__name__ + '_PV'
        self.pv_vssd['VirtualSystemType'] = 'DMTF:xen:PV'
        self.pv_vssd['PV_Bootloader'] = 'pygrub'
        self.pv_vssd['AutomaticShutdownAction'] = pywbem.Uint8(2)
        self.pv_vssd['AutomaticStartupAction'] = pywbem.Uint8(3)
        self.pv_vssd['AutomaticRecoveryAction'] = pywbem.Uint8(3)
        self.pv_vssd['PV_Args'] = 'Term=xterm'
        self.pv_vssd['Other_Config'] = ['HideFromXenCenter=false']

        # Virtual System setting data for an HVM type
        self.hvm_vssd = CIMInstance("Xen_ComputerSystemSettingData")
        self.hvm_vssd['Description'] = 'Test HVM VM'
        self.hvm_vssd['ElementName'] = self.__class__.__name__ + '_HVM'
        self.hvm_vssd['VirtualSystemType'] = 'DMTF:xen:HVM'
        self.hvm_vssd['HVM_Boot_Params'] = ['order=dc']
        self.hvm_vssd['HVM_Boot_Policy'] = 'BIOS order'
        self.hvm_vssd['Platform'] = ['acpi=true', 'apic=true', 'pae=true']

        #######################################################################
        # define all the Virtual System Resource Allocation Setting Data (RASD)
        #######################################################################

        #######################################################################
        # RASD to specify processor allocation for the VM
        # Processor RASD
        self.proc_rasd = CIMInstance('CIM_ResourceAllocationSettingData')
        self.proc_rasd['ResourceType'] = pywbem.Uint16(3)
        self.proc_rasd['VirtualQuantity'] = pywbem.Uint64(1)
        self.proc_rasd['AllocationUnits'] = 'count'

        # Another processor RASD with different limit/weight values
        self.proc1_rasd = self.proc_rasd.copy()
        self.proc1_rasd['VirtualQuantity'] = pywbem.Uint64(1)
        self.proc1_rasd['Limit'] = pywbem.Uint32(
            95)  # max host CPU it could take up in %
        self.proc1_rasd['Weight'] = pywbem.Uint32(
            512)  # relative weight between VCPUs (1-65536)

        # Processor RASD with wrong resource type
        self.invalid_proc_rasd = self.proc_rasd.copy()
        self.invalid_proc_rasd['ResourceType'] = pywbem.Uint32(10000)

        # processor RASD with no resource type specified, the classname has to be base class
        self.nort_proc_rasd = CIMInstance('CIM_ResourceAllocationSettingData')
        self.nort_proc_rasd['VirtualQuantity'] = pywbem.Uint64(1)
        self.nort_proc_rasd['AllocationUnits'] = 'count'

        # processor RASD with invalid quantity specified
        self.invalid_vq_proc_rasd = self.proc_rasd.copy()
        self.invalid_vq_proc_rasd['VirtualQuantity'] = pywbem.Uint64(10000)

        # plain old bad processor rasd - mixed types for properties
        self.bad_proc_rasd = self.proc_rasd.copy()
        self.bad_proc_rasd['ResourceType'] = '3'  # string instead of integer
        self.bad_proc_rasd['VirtualQuantity'] = '1'
        self.bad_proc_rasd['AllocationUnits'] = pywbem.Uint8(
            1)  # integer instead of string
        self.bad_proc_rasd['Limit'] = '100'  # string instead of integer

        #######################################################################
        # memory RASD to specify memory allocation settings for a VM
        self.mem_rasd = CIMInstance('Xen_MemorySettingData')
        self.mem_rasd['ResourceType'] = pywbem.Uint16(4)
        self.mem_rasd['VirtualQuantity'] = pywbem.Uint64(512)
        self.mem_rasd['AllocationUnits'] = 'byte*2^20'

        # 2nd RASD to specify more memory
        self.mem1_rasd = self.mem_rasd.copy()
        self.mem1_rasd['VirtualQuantity'] = pywbem.Uint64(1024)

        # mix in wrong types (integers for strings, and strings for integers)
        self.bad_mem_rasd = self.mem_rasd.copy()
        self.bad_mem_rasd['AllocationUnits'] = pywbem.Uint32(20)
        self.bad_mem_rasd['VirtualQuantity'] = "1024"
        self.bad_mem_rasd['ResourceType'] = "4"

        #######################################################################
        # Resource Allocation Settings to specify Virtual Disk allocation

        # Start off with a CD drive
        self.disk0_rasd = CIMInstance('Xen_DiskSettingData')
        self.disk0_rasd['ElementName'] = self.__class__.__name__ + '_CDRom'
        self.disk0_rasd['ResourceType'] = pywbem.Uint16(15)  # DVD Drive
        self.disk0_rasd['ResourceSubType'] = 'CD'
        # self.disk1_rasd['PoolID'] = '<SR ID>' # (No need to specify a SR or VDI, should create an empty DVD
        # self.disk1_rasd['HostResource'] = '<VDI ID>' # (No need to specify a SR or VDI, should create an empty DVD
        self.disk0_rasd['Bootable'] = True
        self.disk0_rasd['Access'] = pywbem.Uint8(1)

        # A virtual disk of 2 GB size
        self.disk1_rasd = self.disk0_rasd.copy()
        self.disk1_rasd['PoolID'] = sr_to_use_local['PoolID']
        self.disk1_rasd['ElementName'] = self.__class__.__name__ + '_Disk1'
        self.disk1_rasd['ResourceType'] = pywbem.Uint16(19)  # Storage extent
        self.disk1_rasd['ResourceSubType'] = 'Disk'
        self.disk1_rasd['VirtualQuantity'] = pywbem.Uint64(2147483648)  # 2GB
        self.disk1_rasd['AllocationUnits'] = 'byte'

        # Another virtual disk of 2 GB size
        self.disk2_rasd = self.disk0_rasd.copy()
        self.disk2_rasd['PoolID'] = sr_to_use_local['PoolID']
        self.disk2_rasd['ResourceType'] = pywbem.Uint16(19)  # Storage extent
        self.disk2_rasd['ResourceSubType'] = 'Disk'
        self.disk2_rasd['ElementName'] = self.__class__.__name__ + '_Disk2'
        self.disk2_rasd['VirtualQuantity'] = pywbem.Uint64(2147483648)  # 2GB
        self.disk2_rasd['AllocationUnits'] = 'byte'

        # mix in wrong types (integers for strings, and strings for integers)
        self.bad_disk_rasd = self.disk0_rasd.copy()
        self.bad_disk_rasd['PoolID'] = sr_to_use_local['PoolID']
        self.bad_disk_rasd['ElementName'] = pywbem.Uint8(1)
        self.bad_disk_rasd['ResourceType'] = '15'
        self.bad_disk_rasd['HostResource'] = pywbem.Uint16(12345)
        self.bad_disk_rasd['Bootable'] = pywbem.Uint8(1)

        # create a disk out of a non-existent SR
        self.invalid_poolId_rasd = self.disk0_rasd.copy()
        self.invalid_poolId_rasd[
            'PoolId'] = 'ed1bd47e-1ab8-d80a-aecf-06447871211c'

        # Specify bad allocation units
        self.invalid_aunits_rasd = self.disk0_rasd.copy()
        self.invalid_aunits_rasd['PoolID'] = sr_to_use_local['PoolID']
        self.invalid_poolId_rasd['AllocationUnits'] = 'KiloMeters'

        #######################################################################
        # Specify the network connection resource allocation setting data
        # The system will create a virtual NIC for each resource
        #
        self.nic_rasd = CIMInstance('Xen_NetworkPortSettingData')
        self.nic_rasd['ResourceType'] = pywbem.Uint16(
            33)  # ethernet connection type
        self.nic_rasd[
            'Address'] = '00:13:72:24:32:f4'  # manually generated MAC
        self.nic_rasd['PoolID'] = network_to_use['PoolID']

        # NIC RASD With no mac address - generate one
        # NIC RASD with no ElementName either - pick next available address
        self.nic1_rasd = self.nic_rasd.copy()
        del self.nic1_rasd['Address']

        # RASD with no resource type
        self.nort_nic_rasd = self.nic_rasd.copy()
        del self.nort_nic_rasd['ResourceType']

        # RASD with bad MAC address specified
        self.invalid_nic_rasd = self.nic_rasd.copy()
        self.invalid_nic_rasd['Address'] = '00:13:72:24:32:rr'

        # mixed types for properties (strings for integers and vice versa)
        self.bad_nic_rasd = self.nic_rasd.copy()
        self.bad_nic_rasd['ResourceType'] = '33'  # supposed to be a int
        self.bad_nic_rasd['ElementName'] = pywbem.Uint8(
            0)  # supposed to be a string
        self.bad_nic_rasd['Address'] = pywbem.Uint64(
            001372243245)  # supposed to be a string

        #######################################################################
        # Create the test VMs if requested during the test
        #
        # Create the PV VM from the Demo Linux VM template (previously the Debian Etch Template)
        try:
            pv_template_list = self.conn.ExecQuery(
                "WQL",
                "SELECT * FROM Xen_ComputerSystemTemplate WHERE ElementName LIKE \"%XenServer Transfer VM%\"",
                "root/cimv2")
            self.pv_template = CIMInstanceName(
                classname=pv_template_list[0].classname,
                keybindings={"InstanceID": pv_template_list[0]["InstanceID"]})

            self.rasds = [
                self.proc_rasd, self.mem_rasd, self.disk0_rasd,
                self.disk1_rasd, self.nic_rasd
            ]
            self.hvm_params = {
                'SystemSettings': self.hvm_vssd,
                'ResourceSettings': self.rasds
            }
            self.pv_params = {
                'SystemSettings': self.pv_vssd,
                'ResourceSettings': self.rasds,
                'ReferenceConfiguration': self.pv_template
            }
            self.pv_test_vm = None
            self.hvm_test_vm = None

            if create_vms:
                #print 'using template %s to create PV vm: ' % str(debian_template)
                print 'Creating PV vm'
                self.pv_test_vm = CreateVM(self.conn, self.vsms[0],
                                           self.pv_params)
                print 'Creating HVM vm'
                self.hvm_test_vm = CreateVM(self.conn, self.vsms[0],
                                            self.hvm_params)
        except Exception, e:
            print "Exception: %s. Has the TVM template been installed?" % e
Beispiel #29
0
    def create_snapshot_error_tests(self):
        self.TestBegin()
        rc = 1
        print 'Try with a bad snapshot setting'
        bad_snapshot_setting = CIMInstance('Xen_ComputerSystemSnapshot')
        bad_snapshot_setting['ElementName'] = pywbem.Uint64(12345)
        in_params = {
            'AffectedSystem': self.test_vm,
            'SnapshotSettings': bad_snapshot_setting
        }

        snapshot_ref = CreateVMSnapshot(self.conn, self.vsss[0], in_params)
        if snapshot_ref != None:
            print 'Snapshot created unexpectedly'
            rc = 0
        print 'Try with a different bad snapshot setting'
        bad_snapshot_setting = CIMInstance('Xen_ComputerSystemSnapshot123')
        bad_snapshot_setting['ElementName'] = '12345'
        in_params = {
            'AffectedSystem': self.test_vm,
            'SnapshotSettings': bad_snapshot_setting
        }
        snapshot_ref = CreateVMSnapshot(self.conn, self.vsss[0], in_params)
        if snapshot_ref != None:
            print 'Snapshot created unexpectedly'
            rc = 0
        print 'Try with an emtpy snapshot setting'
        bad_snapshot_setting = '''
           '''
        in_params = {
            'AffectedSystem': self.test_vm,
            'SnapshotSettings': bad_snapshot_setting
        }
        snapshot_ref = CreateVMSnapshot(self.conn, self.vsss[0], in_params)
        if snapshot_ref != None:
            print 'Snapshot created unexpectedly'
            rc = 0
        print 'Try with a NULL snapshot setting'
        in_params = {'AffectedSystem': self.test_vm, 'SnapshotSettings': None}
        snapshot_ref = CreateVMSnapshot(self.conn, self.vsss[0], in_params)
        if snapshot_ref != None:
            print 'Snapshot created unexpectedly'
            rc = 0
        print 'Try with a bad reference to an affected system'
        bad_test_vm = self.test_vm.copy()
        bad_test_vm['Name'] = 'bad-reference'
        in_params = {
            'AffectedSystem': bad_test_vm,
            'SnapshotSettings': self.snapshot_settings
        }
        snapshot_ref = CreateVMSnapshot(self.conn, self.vsss[0], in_params)
        if snapshot_ref != None:
            print 'Snapshot created unexpectedly'
            rc = 0
        print 'Try with a NULL affected system'
        in_params = {
            'AffectedSystem': None,
            'SnapshotSettings': self.snapshot_settings
        }
        snapshot_ref = CreateVMSnapshot(self.conn, self.vsss[0], in_params)
        if snapshot_ref != None:
            print 'Snapshot created unexpectedly'
            rc = 0
        print 'Try with no input parameters'
        in_params = {}
        snapshot_ref = CreateVMSnapshot(self.conn, self.vsss[0], in_params)
        if snapshot_ref != None:
            print 'Snapshot created unexpectedly'
            rc = 0

        self.TestEnd(rc)
Beispiel #30
0
def create_new_PV_and_HVM_vms (conn, vsms):
    #
    # the metadata for a XenServer Paravirtualized VM we are going to create
    pv_virtualsystemsettingdata = pywbem.CIMInstance ("Xen_ComputerSystemSettingData")
    pv_virtualsystemsettingdata['Caption']              = "This is a PV VM"
    pv_virtualsystemsettingdata['ElementName']          = "test-pv-vm"
    pv_virtualsystemsettingdata['VirtualSystemType']    = "DMTF:xen:PV"     
    pv_virtualsystemsettingdata['AutomaticShutdownAction'] = pywbem.Uint8(0)
    pv_virtualsystemsettingdata['AutomaticStarupAction']   = pywbem.Uint8(1)
    pv_virtualsystemsettingdata['AutomaticRecoveryAction'] = pywbem.Uint8(2)
    # the following are XenServer specific CIM extensions
    pv_virtualsystemsettingdata['PV_Bootloader']        = "pygrub"      # use pygrub as the bootloader
    pv_virtualsystemsettingdata['PV_Bootloader_Args']   = ""
    pv_virtualsystemsettingdata['PV_Args']              = "Term=xterm"

    # We shall also base the PV VM on an existing XenServer template
    # This automatically allocates default proc/mem/disk/network resources specified by the template
    pv_template_list = conn.ExecQuery("WQL", "SELECT * FROM Xen_ComputerSystemTemplate WHERE ElementName LIKE \"%Debian Lenny%\"", "root/cimv2")
    reference_configuration = pywbem.CIMInstanceName(classname=pv_template_list[0].classname, keybindings={"InstanceID":pv_template_list[0]["InstanceID"]})

    # The metadata settings for a XenServer HVM VM (Hardware Virtualized) we will create
    hvm_virtualsystemsettingdata = pywbem.CIMInstance("Xen_ComputerSystemSettingData")
    hvm_virtualsystemsettingdata['Caption']             = 'This is an HVM VM'
    hvm_virtualsystemsettingdata['ElementName']         = 'test-hvm-vm'
    hvm_virtualsystemsettingdata['VirtualSystemType']   = 'DMTF:xen:HVM'
    hvm_virtualsystemsettingdata['AutomaticShutdownAction'] = pywbem.Uint8(0)
    hvm_virtualsystemsettingdata['AutomaticStarupAction']   = pywbem.Uint8(1)
    hvm_virtualsystemsettingdata['AutomaticRecoveryAction'] = pywbem.Uint8(2)
    # the following are XenServer specific CIM extensions
    hvm_virtualsystemsettingdata['HVM_Boot_Params']     = ['order=dc']      # boot order is cd drive and then hard drive
    hvm_virtualsystemsettingdata['HVM_Boot_Policy']     = 'BIOS order'      # boot based on the BIOS boot order specified above
    hvm_virtualsystemsettingdata['Platform']            = ['acpi=true','apic=true','pae=true'] # use ACPI, APIC, PAE emulation

    #
    # define all the resource settings (processor, memory, disk, network)
    # via ResourceAllocationSettingData instances
    #
    # processor
    proc_resource = pywbem.CIMInstance('CIM_ResourceAllocationSettingData')
    proc_resource['ResourceType']     = pywbem.Uint16(3)
    proc_resource['VirtualQuantity']  = pywbem.Uint64(1)
    proc_resource['AllocationUnits']  = "count"
    proc_resource['Limit']            = pywbem.Uint32(100)
    proc_resource['Weight']           = pywbem.Uint32(512)

    # memory
    mem_resource = pywbem.CIMInstance('CIM_ResourceAllocationSettingData')
    mem_resource['ResourceType']    = pywbem.Uint16(4)
    mem_resource['VirtualQuantity'] = pywbem.Uint64(512)
    mem_resource['AllocationUnits'] = 'byte*2^20'           # DMTF way of specifying MegaBytes

    # disks  
    sr_to_use = None
    # find all SRs available to us
    srs = conn.EnumerateInstances("Xen_StoragePool") 
    for sr in srs:
        if sr['Name'] == 'Local storage':
            sr_to_use = sr
    disk_resource = pywbem.CIMInstance('Xen_DiskSettingData')
    disk_resource['Elementname']       = 'my_vm_disk'
    disk_resource['ResourceType']      = pywbem.Uint16(19)
    disk_resource['ResourceSubType']   = "Disk"  # as opposed to "CD"
    disk_resource['VirtualQuantity']   = pywbem.Uint64(2048)
    disk_resource['AllocationUnits']   = "byte*2^20"        # DMTF way of specifying MegaBytes
    disk_resource['Access']            = pywbem.Uint8(3)
    disk_resource['Bootable']          = False
    disk_resource['PoolID']            = sr_to_use['PoolID']# XenServer SR to allocate the disk out of

    # nic 
    network_to_use = None
    # find all network switch connection pools available to us
    networks = conn.EnumerateInstances("Xen_NetworkConnectionPool") 
    for network in networks:
        if network['Name'].find('eth0') != -1:
            network_to_use = network

    # only RASDs of type NetworkConnection (33) are supported
    nic_resource = pywbem.CIMInstance('Xen_NetworkPortSettingData')
    nic_resource['ResourceType']   = pywbem.Uint16(33)
    nic_resource['ElementName']    = "0"
    nic_resource['PoolID']         = network_to_use['PoolID']# Virtual Switch to connect to

    rasds = [proc_resource, mem_resource, 
             disk_resource, nic_resource]

    hvm_params = {'SystemSettings': hvm_virtualsystemsettingdata, 
                  'ResourceSettings': rasds }

    pv_params =  {'SystemSettings': pv_virtualsystemsettingdata, 
                  'ReferenceConfiguration': reference_configuration}

    print '*** Creating PV VM %s' % (pv_virtualsystemsettingdata['ElementName'])
    new_pv_vm_reference     = create_vm_helper(conn, vsms, pv_params)
    print '*** Creating HVM VM %s' % (hvm_virtualsystemsettingdata['ElementName'])
    new_hvm_vm_reference    = create_vm_helper(conn, vsms, hvm_params)
    if new_pv_vm_reference == None:
        print 'PV VM was not created'
        sys.exit(1)
    if new_hvm_vm_reference == None:
        print 'HVM VM was not created'
        sys.exit(1)
    return [new_pv_vm_reference, new_hvm_vm_reference]