Exemple #1
0
 def rest_api_entity(self):
     collection = "instances" if self.VM_TYPE == "Instance" else "vms"
     try:
         return (getattr(
             self.appliance.rest_api.collections, collection).filter(
                 Q("name", "=", self.name)
                 & Q("ems_id", "=", self.provider.rest_api_entity.id)).
                 resources[0])
     except IndexError:
         raise RestLookupError(
             f"No {self.VM_TYPE} rest entity found matching name {self.name}"
         )
Exemple #2
0
    def process_id(self):
        """ Resolves target_id by target_type and target name."""
        if 'target_name' in self.event_attrs and 'target_id' not in self.event_attrs:
            try:
                target_type = self.event_attrs['target_type'].value
                target_name = self.event_attrs['target_name'].value

                # Target type should be present in TARGET_TYPES
                if target_type not in self.TARGET_TYPES:
                    raise TypeError(
                        'Type {} is not specified in the TARGET_TYPES.'.format(target_type))

                target_rest = self.TARGET_TYPES[target_type]
                target_collection = getattr(self._appliance.rest_api.collections, target_rest)
                o = target_collection.filter(Q('name', '=', target_name))

                if not o.resources:
                    raise ValueError('{} with name {} not found.'.format(target_type, target_name))

                # Set target_id if target object was found
                self.event_attrs['target_id'] = EventAttr(**{'target_id': o[0].id})

            except ValueError:
                # Target isn't added yet. Need to wait
                sleep(1)
Exemple #3
0
def test_filtering_vm_with_multiple_ips(appliance, provider):
    """
    Polarion:
        assignee: pvala
        caseimportance: high
        casecomponent: Rest
        initialEstimate: 1/4h
        setup:
            1. Add a provider.
        testSteps:
            1. Select a VM with multiple IP addresses and note one ipaddress.
            2. Send a GET request with the noted ipaddress.
                GET /api/vms?expand=resources&attributes=ipaddresses&filter[]=ipaddresses=':ipaddr'
        expectedResults:
            1.
            2. Selected VM must be present in the resources sent by response.

    Bugzilla:
        1684681
    """
    # 1
    vm = appliance.collections.infra_vms.instantiate(
        provider.data["cap_and_util"]["capandu_vm"], provider)
    # 2
    result = appliance.rest_api.collections.vms.filter(
        Q("ipaddresses", "=", choice(vm.all_ip_addresses)))
    assert_response(appliance)
    assert vm.name in [resource.name for resource in result.resources]
Exemple #4
0
def test_database_wildcard_should_work_and_be_included_in_the_query(
        appliance, request, provider):
    """ Database wildcard should work and be included in the query
    Bugzilla:
        1581853

    Polarion:
        assignee: pvala
        casecomponent: Rest
        testtype: functional
        initialEstimate: 1/4h
        startsin: 5.10
        testSteps:
            1. Create a VM with some name, for e.g test-25-xyz.
            2. Filter VM with wild character and substring of the name, for e.g. "%25%"
        expectedResults:
            1. VM is created successfully.
            2. VM is obtained without any error.
    """
    vm_name = _vm(request,
                  provider,
                  appliance,
                  name=fauxfactory.gen_alpha(start="test-25-", length=12))
    with LogValidator("/var/www/miq/vmdb/log/production.log",
                      failure_patterns=[".*FATAL.*"]).waiting(timeout=20):
        result = appliance.rest_api.collections.vms.filter(
            Q("name", "=", "%25%"))

    assert result.subcount
    assert vm_name in [vm.name for vm in result.resources]
Exemple #5
0
    def get_next_portion(self, evt):
        """ Returns list with one or more events matched with expected event.

        Returns None if there is no matched events."""
        evt.process_id()

        q = Q('id', '>', self._last_processed_id)  # ensure we get only new events

        used_filters = set(self.FILTER_ATTRS).intersection(set(evt.event_attrs))
        for filter_attr in used_filters:
            evt_attr = evt.event_attrs[filter_attr]
            if evt_attr.value:
                q &= Q(filter_attr, '=', evt_attr.value)
        result = self.event_streams.filter(q)

        if len(result):
            return result
    def _get_object(self, client, collection_name, name, query_dict):
        _query_dict = dict(query_dict)
        _query_dict['filter[]'] = Q.from_dict({'name': name}).as_filters

        resources = self._get_objects(client, collection_name, _query_dict)

        obj = None
        if len(resources) > 0:
            self.logger.debug("{} '{}' already exists.".format(collection_name, name))
            # this object already exists
            obj = resources[0]
        else:
            self.logger.debug("{} '{}' does not exists.".format(collection_name, name))

        return obj
Exemple #7
0
    def get(self, client, kwargs_dict):
        """Reads a single custom attributes on the VM
        :param client:
        :param kwargs_dict:
        :returns: a dictionary of the results returned from ManageIQ
        :rtype: dict
        """
        id = self._get_arg("id", kwargs_dict)
        key = self._get_arg("key", kwargs_dict)

        query_dict = self._get_query()
        query_dict['filter[]'] = Q.from_dict({'name': key}).as_filters

        object_response = client.collections.vms(id)
        search_results = object_response.custom_attributes.query_string(**query_dict)
        return self._resources_from_search_results(search_results)
def test_check_vm_retirement_requester(
    appliance, request, provider, vm_retirement_report
):
    """
    Polarion:
        assignee: pvala
        casecomponent: Infra
        caseimportance: medium
        initialEstimate: 1/2h
        tags: retirement
        setup:
            1. Add a provider.
            2. Provision a VM.
            3. Once the VM has been provisioned, retire the VM.
            4. Create a report(See attachment in BZ).
        testSteps:
            1. Queue the report once the VM has retired
                and check the retirement_requester column for the VM.
        expectedResults:
            1. Requester name must be visible.

    Bugzilla:
        1638502
        1805119
    """
    vm_name, report = vm_retirement_report
    saved_report = report.queue(wait_for_finish=True)

    # filtering the request by description because description sometimes changes with version
    requester_id = (
        appliance.rest_api.collections.requests.filter(
            Q("description", "=", f"VM Retire for: {vm_name}*")
        )
        .resources[0]
        .requester_id
    )

    # obtaining the retirement requester's userid from retirement request
    requester_userid = appliance.rest_api.collections.users.get(id=requester_id).userid

    # the report filter is such that we will only obtain one row in the report
    row_data = saved_report.data.find_row("Name", vm_name)
    assert (
        row_data["Name"],
        row_data["Retirement Requester"],
        row_data["Retirement State"],
    ) == (vm_name, requester_userid, "retired")
def set_conversion_host_api(appliance, transformation_method, source_provider,
                            target_provider):
    """
    Setting conversion host for RHV and OSP provider via REST

    Note: Support for using VMs as UCI conversion hosts will be added for RHV in 5.11.5.
    """
    vmware_ssh_private_key = None
    vmware_vddk_package_url = None

    delete_hosts = appliance.ssh_client.run_rails_command(
        "'MiqTask.delete_all; ConversionHost.delete_all'")
    if not delete_hosts.success:
        pytest.skip(
            f"Failed to delete all conversion hosts: {delete_hosts.output}")

    conversion_data = get_conversion_data(appliance, target_provider)
    if transformation_method == "SSH":
        vmware_key = conf.credentials[source_provider.data["private-keys"]
                                      ["vmware-ssh-key"]["credentials"]]
        vmware_ssh_private_key = vmware_key.password
    else:
        vmware_vddk_package_url = vddk_url()

    for host in conversion_data["hosts"]:
        conversion_entity = ("hosts" if target_provider.one_of(RHEVMProvider)
                             and appliance.version < '5.11.5' else "vms")
        host_id = (getattr(appliance.rest_api.collections,
                           conversion_entity).filter(
                               Q.from_dict({"name": host})).resources[0].id)
        response = appliance.rest_api.collections.conversion_hosts.action.create(
            resource_id=host_id,
            resource_type=conversion_data["resource_type"],
            vmware_vddk_package_url=vmware_vddk_package_url,
            vmware_ssh_private_key=vmware_ssh_private_key,
            conversion_host_ssh_private_key=conversion_data["private_key"],
            auth_user=conversion_data["auth_user"])[0]
        response.reload()
        wait_for(
            lambda: response.task.state == "Finished",
            fail_func=response.task.reload,
            num_sec=240,
            delay=3,
            message="Waiting for conversion configuration task to be finished")
Exemple #10
0
def request_task(appliance, request, provider, provision_data):
    # create a provision request by provisioning a VM
    vm_name = provision_data["vm_fields"]["vm_name"]
    request.addfinalizer(lambda: clean_vm(appliance, provider, vm_name))
    provision_request = appliance.rest_api.collections.provision_requests.action.create(
        **provision_data)[0]
    assert_response(appliance)

    # wait until the request is finished
    wait_for(
        lambda: provision_request.request_state == "finished",
        fail_func=provision_request.reload,
        num_sec=1800,
        delay=20,
    )

    # Return the request_task related to the subject vm
    return provision_request.request_tasks.filter(
        Q("description", "=", f"Provision from *to*{vm_name}*")).resources[0]
Exemple #11
0
    def __call__(self, query, attr=None):
        """Performs a basic query on a collection.

        :param query: query containing name, operand and value
        :type query: tuple
        :return: collection resources matching the supplied query
        :rtype: list

        Usage:

        .. code-block: python

            # query vms collection to find the following vm by name
            query = BasicQuery(vm_collection)
            query(('name', '=', 'vm_foo'))
            # -- or --
            query.__call__(('name', '=', 'vm_foo'))
        """
        if len(query) != 3:
            log.warning('Query must contain three indexes. i.e. '
                        '(name, operand, value)')
            return self.resources

        try:
            resources = getattr(self.collection,
                                'filter')(Q(query[0], query[1], query[2]))

            self.resources = resources.resources

            if attr:
                for ent in resources.resources:
                    ent.reload(True, True, attr)

        except (APIException, ValueError) as e:
            log.error('Query attempted failed: {0}, error: {1}'.format(
                query, e))

        return self.resources
 def test_bad_operator(self):
     with pytest.raises(ValueError):
         Q('foo', 'explode', 'bar')
 def test_or(self):
     assert (Q('foo', '=', 'bar') | Q('xyz', '=', 'abc')).as_filters == [
         'foo = "bar"', 'or xyz = "abc"'
     ]
 def test_and(self):
     assert (Q('foo', '=', 'bar') & Q('xyz', '=', 'abc')).as_filters == [
         'foo = "bar"', 'xyz = "abc"'
     ]
 def test_single(self):
     assert Q('foo', '=', 'bar').as_filters == ['foo = "bar"']