Ejemplo n.º 1
0
    def test_positive_deploy_configure_by_script(self, form_data,
                                                 virtwho_config):
        """ Verify "GET /foreman_virt_who_configure/api/

        v2/configs/:id/deploy_script"

        :id: 166ec4f8-e3fa-4555-9acb-1a5d693a42bb

        :expectedresults: Config can be created and deployed

        :CaseLevel: Integration

        :CaseImportance: High
        """
        assert virtwho_config.status == 'unknown'
        script = virtwho_config.deploy_script()
        hypervisor_name, guest_name = deploy_configure_by_script(
            script['virt_who_config_script'],
            form_data['hypervisor_type'],
            debug=True)
        virt_who_instance = (entities.VirtWhoConfig().search(
            query={'search': f'name={virtwho_config.name}'})[0].status)
        assert virt_who_instance == 'ok'
        hosts = [
            (
                hypervisor_name,
                f'product_id={virtwho.sku.vdc_physical} and type=NORMAL',
            ),
            (
                guest_name,
                f'product_id={virtwho.sku.vdc_physical} and type=STACK_DERIVED',
            ),
        ]
        for hostname, sku in hosts:
            if 'type=NORMAL' in sku:
                subscriptions = entities.Subscription().search(
                    query={'search': sku})
                vdc_id = subscriptions[0].id
            if 'type=STACK_DERIVED' in sku:
                vdc_id = self._get_guest_bonus(hypervisor_name, sku)
            host, time = wait_for(
                entities.Host().search,
                func_args=(None, {
                    'search': hostname
                }),
                fail_condition=[],
                timeout=5,
                delay=1,
            )
            entities.HostSubscription(host=host[0].id).add_subscriptions(
                data={'subscriptions': [{
                    'id': vdc_id,
                    'quantity': 1
                }]})
            result = entities.Host().search(
                query={'search': hostname})[0].read_json()
            assert result['subscription_status_label'] == 'Fully entitled'
        virtwho_config.delete()
        assert not entities.VirtWhoConfig().search(
            query={'search': f"name={form_data['name']}"})
Ejemplo n.º 2
0
    def test_positive_candlepin_events_processed_by_STOMP(self):
        """Verify that Candlepin events are being read and processed by
           attaching subscriptions, validating host subscriptions status,
           and viewing processed and failed Candlepin events

        :id: efd20ffd-8f98-4536-abb6-d080f9d23169

        :steps:

            1. Add subscriptions to content host
            2. Verify subscription status is invalid at
               <your-satellite-url>/api/v2/hosts
            3. Import a Manifest
            4. Attach subs to content host
            5. Verify subscription status is valid
            6. Check ping api for processed and failed events
               /katello/api/v2/ping

        :expectedresults: Candlepin events are being read and processed
                          correctly without any failures
        :BZ: #1826515

        :CaseImportance: High
        """
        org = entities.Organization().create()
        repo = entities.Repository(product=entities.Product(
            organization=org).create()).create()
        repo.sync()
        ak = entities.ActivationKey(
            content_view=org.default_content_view,
            max_hosts=100,
            organization=org,
            environment=entities.LifecycleEnvironment(id=org.library.id),
            auto_attach=True,
        ).create()
        with VirtualMachine(distro=DISTRO_RHEL7) as vm:
            vm.install_katello_ca()
            vm.register_contenthost(org.name, ak.name)
            host = entities.Host().search(
                query={'search': f'name={vm.hostname}'})
            host_id = host[0].id
            host_content = entities.Host(id=host_id).read_json()
            assert host_content["subscription_status"] == 2
            with manifests.clone() as manifest:
                upload_manifest(org.id, manifest.content)
            subscription = entities.Subscription(organization=org).search(
                query={'search': f'name="{DEFAULT_SUBSCRIPTION_NAME}"'})[0]
            entities.HostSubscription(host=host_id).add_subscriptions(data={
                'subscriptions': [{
                    'id': subscription.cp_id,
                    'quantity': 1
                }]
            })
            host_content = entities.Host(id=host_id).read_json()
            assert host_content["subscription_status"] == 0
            response = entities.Ping().search_json(
            )["services"]["candlepin_events"]
            assert response["status"] == "ok"
            assert "0 Failed" in response["message"]
Ejemplo n.º 3
0
def test_positive_candlepin_events_processed_by_stomp(rhel7_contenthost,
                                                      function_org,
                                                      default_sat):
    """Verify that Candlepin events are being read and processed by
        attaching subscriptions, validating host subscriptions status,
        and viewing processed and failed Candlepin events

    :id: efd20ffd-8f98-4536-abb6-d080f9d23169

    :steps:

        1. Add subscriptions to content host
        2. Verify subscription status is invalid at
            <your-satellite-url>/api/v2/hosts
        3. Import a Manifest
        4. Attach subs to content host
        5. Verify subscription status is valid
        6. Check ping api for processed and failed events
            /katello/api/v2/ping

    :expectedresults: Candlepin events are being read and processed
                        correctly without any failures
    :BZ: 1826515

    :parametrized: yes

    :CaseImportance: High
    """
    repo = entities.Repository(product=entities.Product(
        organization=function_org).create()).create()
    repo.sync()
    ak = entities.ActivationKey(
        content_view=function_org.default_content_view,
        max_hosts=100,
        organization=function_org,
        environment=entities.LifecycleEnvironment(id=function_org.library.id),
        auto_attach=True,
    ).create()
    rhel7_contenthost.install_katello_ca(default_sat)
    rhel7_contenthost.register_contenthost(function_org.name, ak.name)
    host = entities.Host().search(
        query={'search': f'name={rhel7_contenthost.hostname}'})
    host_id = host[0].id
    host_content = entities.Host(id=host_id).read_json()
    assert host_content['subscription_status'] == 2
    with manifests.clone() as manifest:
        upload_manifest(function_org.id, manifest.content)
    subscription = entities.Subscription(organization=function_org).search(
        query={'search': f'name="{DEFAULT_SUBSCRIPTION_NAME}"'})[0]
    entities.HostSubscription(host=host_id).add_subscriptions(
        data={'subscriptions': [{
            'id': subscription.cp_id,
            'quantity': 1
        }]})
    host_content = entities.Host(id=host_id).read_json()
    assert host_content['subscription_status'] == 0
    response = entities.Ping().search_json()['services']['candlepin_events']
    assert response['status'] == 'ok'
    assert '0 Failed' in response['message']
Ejemplo n.º 4
0
    def test_positive_deploy_configure_by_script(self, default_org, form_data,
                                                 virtwho_config):
        """Verify "GET /foreman_virt_who_configure/api/

        v2/configs/:id/deploy_script"

        :id: 9668b900-0d2f-42ae-b2f8-523ca292b2bd

        :expectedresults: Config can be created and deployed

        :CaseLevel: Integration

        :CaseImportance: High
        """
        assert virtwho_config.status == 'unknown'
        script = virtwho_config.deploy_script()
        hypervisor_name, guest_name = deploy_configure_by_script(
            script['virt_who_config_script'],
            form_data['hypervisor_type'],
            debug=True,
            org=default_org.label,
        )
        virt_who_instance = (entities.VirtWhoConfig().search(
            query={'search': f'name={virtwho_config.name}'})[0].status)
        assert virt_who_instance == 'ok'
        hosts = [
            (
                hypervisor_name,
                f'product_id={settings.virtwho.sku.vdc_physical} and type=NORMAL',
            ),
            (
                guest_name,
                f'product_id={settings.virtwho.sku.vdc_physical} and type=STACK_DERIVED',
            ),
        ]
        for hostname, sku in hosts:
            host = Host.list({'search': hostname})[0]
            subscriptions = Subscription.list({
                'organization': default_org.name,
                'search': sku
            })
            vdc_id = subscriptions[0]['id']
            if 'type=STACK_DERIVED' in sku:
                for item in subscriptions:
                    if hypervisor_name.lower() in item['type']:
                        vdc_id = item['id']
                        break
            entities.HostSubscription(host=host['id']).add_subscriptions(
                data={'subscriptions': [{
                    'id': vdc_id,
                    'quantity': 1
                }]})
            result = entities.Host().search(
                query={'search': hostname})[0].read_json()
            assert result['subscription_status_label'] == 'Fully entitled'
        virtwho_config.delete()
        assert not entities.VirtWhoConfig().search(
            query={'search': f"name={form_data['name']}"})
Ejemplo n.º 5
0
def test_sca_end_to_end(module_ak, rhel7_contenthost, module_org, rh_repo,
                        custom_repo, default_sat):
    """Perform end to end testing for Simple Content Access Mode

    :id: c6c4b68c-a506-46c9-bd1d-22e4c1926ef8

    :BZ: 1890643, 1890661, 1890664

    :expectedresults: All tests pass and clients have access
        to repos without needing to add subscriptions

    :parametrized: yes

    :CaseImportance: Critical
    """
    rhel7_contenthost.install_katello_ca(default_sat)
    rhel7_contenthost.register_contenthost(module_org.label, module_ak.name)
    assert rhel7_contenthost.subscribed
    # Check to see if Organization is in SCA Mode
    assert entities.Organization(
        id=module_org.id).read().simple_content_access is True
    # Verify that you cannot attach a subscription to an activation key in SCA Mode
    subscription = entities.Subscription(organization=module_org).search(
        query={'search': f'name="{DEFAULT_SUBSCRIPTION_NAME}"'})[0]
    with pytest.raises(HTTPError) as ak_context:
        module_ak.add_subscriptions(data={
            'quantity': 1,
            'subscription_id': subscription.id
        })
    assert 'Simple Content Access' in ak_context.value.response.text
    # Verify that you cannot attach a subscription to an Host in SCA Mode
    with pytest.raises(HTTPError) as host_context:
        entities.HostSubscription(
            host=rhel7_contenthost.nailgun_host.id
        ).add_subscriptions(
            data={'subscriptions': [{
                'id': subscription.id,
                'quantity': 1
            }]})
    assert 'Simple Content Access' in host_context.value.response.text
    # Create a content view with repos and check to see that the client has access
    content_view = entities.ContentView(organization=module_org).create()
    content_view.repository = [rh_repo, custom_repo]
    content_view.update(['repository'])
    content_view.publish()
    assert len(content_view.repository) == 2
    host = rhel7_contenthost.nailgun_host
    host.content_facet_attributes = {'content_view_id': content_view.id}
    host.update(['content_facet_attributes'])
    rhel7_contenthost.run('subscription-manager repos --enable *')
    repos = rhel7_contenthost.run(
        'subscription-manager refresh && yum repolist')
    assert content_view.repository[1].name in repos.stdout
    assert 'Red Hat Satellite Tools' in repos.stdout
    # install package and verify it succeeds or is already installed
    package = rhel7_contenthost.run('yum install -y python-pulp-manifest')
    assert 'Complete!' in package.stdout or 'already installed' in package.stdout
Ejemplo n.º 6
0
    def test_positive_deploy_configure_by_script(self):
        """ Verify "GET /foreman_virt_who_configure/api/

        v2/configs/:id/deploy_script"

        :id: bb673b27-c258-4517-8fb9-436a4b51ba9d

        :expectedresults: Config can be created and deployed

        :CaseLevel: Integration

        :CaseImportance: High
        """
        name = gen_string('alpha')
        args = self._make_virtwho_configure()
        args.update({'name': name})
        vhd = entities.VirtWhoConfig(**args).create()
        self.assertEqual(vhd.status, 'unknown')
        script = vhd.deploy_script()
        hypervisor_name, guest_name = deploy_configure_by_script(
            script['virt_who_config_script'], debug=True)
        self.assertEqual(
            entities.VirtWhoConfig().search(
                query={'search': 'name={}'.format(name)})[0].status, 'ok')
        hosts = [
            (hypervisor_name,
             'product_id={} and type=NORMAL'.format(self.vdc_physical)),
            (guest_name,
             'product_id={} and type=STACK_DERIVED'.format(self.vdc_physical))
        ]
        for hostname, sku in hosts:
            if 'type=NORMAL' in sku:
                subscriptions = entities.Subscription().search(
                    query={'search': '{0}'.format(sku)})
                vdc_id = subscriptions[0].id
            if 'type=STACK_DERIVED' in sku:
                vdc_id = self._get_guest_bonus(hypervisor_name, sku)
            host, time = wait_for(entities.Host().search,
                                  func_args=(None, {
                                      'search': "{0}".format(hostname)
                                  }),
                                  fail_condition=[],
                                  timeout=5,
                                  delay=1)
            entities.HostSubscription(host=host[0].id).add_subscriptions(
                data={'subscriptions': [{
                    'id': vdc_id,
                    'quantity': 1
                }]})
            result = entities.Host().search(
                query={'search': '{0}'.format(hostname)})[0].read_json()
            self.assertEqual(result['subscription_status_label'],
                             'Fully entitled')
        vhd.delete()
        self.assertFalse(entities.VirtWhoConfig().search(
            query={'search': 'name={}'.format(name)}))
Ejemplo n.º 7
0
def attach_custom_product_subscription(prod_name=None, host_name=None):
    """Attach custom product subscription to client host
    :param str prod_name: custom product name
    :param str host_name: client host name
    """
    host = entities.Host().search(query={'search': f'{host_name}'})[0]
    product_subscription = entities.Subscription().search(query={'search': f'name={prod_name}'})[0]
    entities.HostSubscription(host=host.id).add_subscriptions(
        data={'subscriptions': [{'id': product_subscription.id, 'quantity': 1}]}
    )
Ejemplo n.º 8
0
    def test_positive_deploy_configure_by_id(self, form_data, virtwho_config):
        """Verify "POST /foreman_virt_who_configure/api/v2/configs"

        :id: 72d74c05-2580-4f38-b6c0-999ff470d4d6

        :expectedresults: Config can be created and deployed

        :CaseLevel: Integration

        :CaseImportance: High
        """
        assert virtwho_config.status == 'unknown'
        command = get_configure_command(virtwho_config.id)
        hypervisor_name, guest_name = deploy_configure_by_command(
            command, form_data['hypervisor_type'], debug=True)
        virt_who_instance = (entities.VirtWhoConfig().search(
            query={'search': f'name={virtwho_config.name}'})[0].status)
        assert virt_who_instance == 'ok'
        hosts = [
            (
                hypervisor_name,
                f'product_id={settings.virtwho.sku.vdc_physical} and type=NORMAL',
            ),
            (
                guest_name,
                f'product_id={settings.virtwho.sku.vdc_physical} and type=STACK_DERIVED',
            ),
        ]
        for hostname, sku in hosts:
            host = Host.list({'search': hostname})[0]
            subscriptions = Subscription.list({
                'organization': DEFAULT_ORG,
                'search': sku
            })
            vdc_id = subscriptions[0]['id']
            if 'type=STACK_DERIVED' in sku:
                for item in subscriptions:
                    if hypervisor_name.lower() in item['type']:
                        vdc_id = item['id']
                        break
            entities.HostSubscription(host=host['id']).add_subscriptions(
                data={'subscriptions': [{
                    'id': vdc_id,
                    'quantity': 1
                }]})
            result = entities.Host().search(
                query={'search': hostname})[0].read_json()
            assert result['subscription_status_label'] == 'Fully entitled'
        virtwho_config.delete()
        assert not entities.VirtWhoConfig().search(
            query={'search': f"name={form_data['name']}"})
Ejemplo n.º 9
0
def add_custom_product_subscription_to_hosts(product, hosts):
    """Adds custom product subscription to given list of hosts

    :param str product: The custom product name
    :param list hosts: List of content host names
    """
    from_version = os.environ.get('FROM_VERSION')
    for host in hosts:
        sub = entities.Subscription().search(
            query={'search': 'name={0}'.format(product)})[0]
        if float(from_version) <= 6.1:
            execute(
                attach_subscription_to_host_from_content_host, sub.cp_id, host=host)
        else:
            host = entities.Host().search(query={'search': 'name={}'.format(host)})[0]
            entities.HostSubscription(host=host).add_subscriptions(
                data={'subscriptions': [{'id': sub.id, 'quantity': 1}]})
Ejemplo n.º 10
0
def test_positive_add_remove_subscription(module_org, module_ak_cv_lce,
                                          module_puppet_classes):
    """Try to bulk add and remove a subscription to members of a host collection.

    :id: c4ec5727-eb25-452e-a91f-87cafb16666b

    :steps:

        1. Create HC, add AK to HC
        2. Create product so we can use it's subscription
        3. Create some VMs and register them with AK so they are in HC
        4. Add the subscription to the members of the Host Collection
        5. Assert subscription is added
        6. Bulk remove subscription
        7. Assert it is removed

    :expectedresults: subscription added to, and removed from, members of host collection

    :CaseImportance: Critical
    """
    # this command creates a host collection and "appends", makes available, to the AK
    module_ak_cv_lce.host_collection.append(
        entities.HostCollection(organization=module_org).create())
    # Move HC from Add tab to List tab on AK view
    module_ak_cv_lce = module_ak_cv_lce.update(['host_collection'])
    # Create a product so we have a subscription to use
    product = entities.Product(organization=module_org).create()
    prod_name = product.name
    product_subscription = entities.Subscription().search(
        query={'search': f'name={prod_name}'})[0]
    # Create and register VMs as members of Host Collection
    with VMBroker(nick='rhel7', host_classes={'host': ContentHost},
                  _count=2) as hosts:
        for client in hosts:
            client.install_katello_ca()
            client.register_contenthost(module_org.label,
                                        module_ak_cv_lce.name)
        # Read host_collection back from Satellite to get host_ids
        host_collection = module_ak_cv_lce.host_collection[0].read()
        host_ids = [host.id for host in host_collection.host]
        # Add subscription
        # Call nailgun to make the API PUT to members of Host Collection
        entities.Host().bulk_add_subscriptions(
            data={
                "organization_id": module_org.id,
                "included": {
                    "ids": host_ids
                },
                "subscriptions": [{
                    "id": product_subscription.id,
                    "quantity": 1
                }],
            })
        # GET the subscriptions from hosts and assert they are there
        for host_id in host_ids:
            req = entities.HostSubscription(host=host_id).subscriptions()
            assert (prod_name in req['results'][0]['product_name']
                    ), 'Subscription not applied to HC members'
        # Remove the subscription
        # Call nailgun to make the API PUT to members of Host Collection
        entities.Host().bulk_remove_subscriptions(
            data={
                "organization_id": module_org.id,
                "included": {
                    "ids": host_ids
                },
                "subscriptions": [{
                    "id": product_subscription.id,
                    "quantity": 1
                }],
            })
        # GET the subscriptions from hosts and assert they are gone
        for host_id in host_ids:
            req = entities.HostSubscription(host=host_id).subscriptions()
            assert not req[
                'results'], 'Subscription not removed from HC members'
Ejemplo n.º 11
0
    def test_pre_create_virt_who_configuration(self, form_data):
        """Create and deploy virt-who configuration.

        :id: preupgrade-a36cbe89-47a2-422f-9881-0f86bea0e24e

        :steps: In Preupgrade Satellite, Create and deploy virt-who configuration.

        :expectedresults:
            1. Config can be created and deployed by command.
            2. No error msg in /var/log/rhsm/rhsm.log.
            3. Report is sent to satellite.
            4. Virtual sku can be generated and attached.
        """
        default_loc_id = entities.Location().search(
            query={'search': f'name="{DEFAULT_LOC}"'})[0].id
        default_loc = entities.Location(id=default_loc_id).read()
        org = entities.Organization(name=ORG_DATA['name']).create()
        default_loc.organization.append(entities.Organization(id=org.id))
        default_loc.update(['organization'])
        with manifests.clone() as manifest:
            upload_manifest(org.id, manifest.content)
        form_data.update({'organization_id': org.id})
        vhd = entities.VirtWhoConfig(**form_data).create()
        assert vhd.status == 'unknown'
        command = get_configure_command(vhd.id, org=org.name)
        hypervisor_name, guest_name = deploy_configure_by_command(
            command, form_data['hypervisor_type'], debug=True, org=org.label)
        virt_who_instance = (entities.VirtWhoConfig(
            organization_id=org.id).search(
                query={'search': f'name={form_data["name"]}'})[0].status)
        assert virt_who_instance == 'ok'
        hosts = [
            (hypervisor_name,
             f'product_id={settings.virtwho.sku.vdc_physical} and type=NORMAL'
             ),
            (guest_name,
             f'product_id={settings.virtwho.sku.vdc_physical} and type=STACK_DERIVED'
             ),
        ]
        for hostname, sku in hosts:
            host = Host.list({'search': hostname})[0]
            subscriptions = Subscription.list({
                'organization-id': org.id,
                'search': sku
            })
            vdc_id = subscriptions[0]['id']
            if 'type=STACK_DERIVED' in sku:
                for item in subscriptions:
                    if hypervisor_name.lower() in item['type']:
                        vdc_id = item['id']
                        break
            entities.HostSubscription(host=host['id']).add_subscriptions(
                data={'subscriptions': [{
                    'id': vdc_id,
                    'quantity': 1
                }]})
            result = (entities.Host(organization=org.id).search(
                query={'search': hostname})[0].read_json())
            assert result['subscription_status_label'] == 'Fully entitled'

        scenario_dict = {
            self.__class__.__name__: {
                'hypervisor_name': hypervisor_name,
                'guest_name': guest_name,
            }
        }
        create_dict(scenario_dict)
Ejemplo n.º 12
0
def sync_tools_repos_to_upgrade(client_os, hosts):
    """This syncs tools repo in Satellite server and also attaches
    the new tools repo subscription onto each client

    :param string client_os: The client OS of which tools repo to be synced
        e.g: rhel6, rhel7
    :param list hosts: The list of capsule hostnames to which new capsule
        repo subscription will be attached

    Following environment variable affects this function:

    TOOLS_URL_{client_os}
        The url of tools repo from latest satellite compose.
    FROM_VERSION
        Current Satellite version - to differentiate default organization.
        e.g. '6.1', '6.0'

    Personal Upgrade Env Vars:

    CLIENT_AK
        The ak_name attached to subscription of client

    Rhevm upgrade Env Vars:

    RHEV_CLIENT_AK
        The AK name used in client subscription
    """
    client_os = client_os.upper()
    tools_repo_url = os.environ.get('TOOLS_URL_{}'.format(client_os))
    if tools_repo_url is None:
        logger.warning('The Tools Repo URL for {} is not provided '
                       'to perform Client Upgrade !'.format(client_os))
        sys.exit(1)
    ak_name = os.environ.get(
        'CLIENT_AK_{}'.format(client_os),
        os.environ.get('RHEV_CLIENT_AK_{}'.format(client_os)))
    if ak_name is None:
        logger.warning('The AK details are not provided for {0} Client '
                       'upgrade!'.format(client_os))
        sys.exit(1)
    org = entities.Organization().search(
        query={'search': 'name="{}"'.format("Default Organization")})[0]
    ak = entities.ActivationKey(organization=org).search(
        query={'search': 'name={}'.format(ak_name)})[0]
    cv = ak.content_view.read()
    lenv = ak.environment.read()
    toolsproduct_name = customcontents['tools']['prod'].format(
        client_os=client_os)
    toolsrepo_name = customcontents['tools']['repo'].format(
        client_os=client_os)
    # adding sleeps in between to avoid race conditions
    tools_product = entities.Product(name=toolsproduct_name,
                                     organization=org).create()
    tools_repo = entities.Repository(name=toolsrepo_name,
                                     product=tools_product,
                                     url=tools_repo_url,
                                     organization=org,
                                     content_type='yum').create()
    entities.Repository(id=tools_repo.id).sync()
    cv.repository += [tools_repo]
    cv.update(['repository'])
    call_entity_method_with_timeout(cv.read().publish, timeout=2500)
    published_ver = entities.ContentViewVersion(
        id=max([cv_ver.id for cv_ver in cv.read().version])).read()
    published_ver.promote(data={'environment_id': lenv.id, 'force': False})
    tools_sub = entities.Subscription().search(
        query={'search': 'name={0}'.format(toolsproduct_name)})[0]
    ak.add_subscriptions(data={
        'quantity': 1,
        'subscription_id': tools_sub.id,
    })
    # Add this latest tools repo to hosts to upgrade
    sub = entities.Subscription().search(
        query={'search': 'name={0}'.format(toolsproduct_name)})[0]
    for host in hosts:
        if float(os.environ.get('FROM_VERSION')) <= 6.1:
            # If not User Hosts then, attach sub to dockered clients
            if not all([
                    os.environ.get('CLIENT6_HOSTS'),
                    os.environ.get('CLIENT7_HOSTS')
            ]):
                docker_vm = os.environ.get('DOCKER_VM')
                execute(attach_subscription_to_host_from_content_host,
                        sub.cp_id,
                        True,
                        host,
                        host=docker_vm)
            # Else, Attach subs to user hosts
            else:
                execute(attach_subscription_to_host_from_content_host,
                        sub.cp_id,
                        host=host)
        else:
            host = entities.Host().search(
                query={'search': 'name={}'.format(host)})[0]
            entities.HostSubscription(host=host).add_subscriptions(
                data={'subscriptions': [{
                    'id': sub.id,
                    'quantity': 1
                }]})
Ejemplo n.º 13
0
    def test_positive_add_remove_subscription(self):
        """Try to bulk add and remove a subscription to members of a host collection.

        :id: c4ec5727-eb25-452e-a91f-87cafb16666b

        :steps:

            1. Create AK and HC, add AK to HC
            2. Create product so we can use it's subscription
            3. Create some VMs and register them with AK so they are in HC
            4. Add the subscription to the members of the Host Collection
            5. Assert subscription is added
            6. Bulk remove subscription
            7. Assert it is removed

        :expectedresults: subscription added to, and removed from, members of host collection

        :CaseImportance: Critical
        """
        # Create an activate key for this test
        act_key = entities.ActivationKey(content_view=self.content_view,
                                         environment=self.lce,
                                         organization=self.org).create()
        # this command creates a host collection and "appends", makes available, to the AK
        act_key.host_collection.append(
            entities.HostCollection(organization=self.org).create())
        # Move HC from Add tab to List tab on AK view
        act_key = act_key.update(['host_collection'])
        # Create a product so we have a subscription to use
        product = entities.Product(organization=self.org).create()
        prod_name = product.name
        product_subscription = entities.Subscription().search(
            query={'search': f'name={prod_name}'})[0]
        # Create and register VMs as members of Host Collection
        with VirtualMachine(distro=DISTRO_RHEL7) as client1, VirtualMachine(
                distro=DISTRO_RHEL7) as client2:
            for client in [client1, client2]:
                client.install_katello_ca()
                client.register_contenthost(self.org.label, act_key.name)
            # Read host_collection back from Satellite to get host_ids
            host_collection = act_key.host_collection[0].read()
            host_ids = [host.id for host in host_collection.host]
            # Add subscription
            # Call nailgun to make the API PUT to members of Host Collection
            entities.Host().bulk_add_subscriptions(
                data={
                    "organization_id":
                    self.org.id,
                    "included": {
                        "ids": host_ids
                    },
                    "subscriptions": [{
                        "id": product_subscription.id,
                        "quantity": 1
                    }],
                })
            # GET the subscriptions from hosts and assert they are there
            for host_id in host_ids:
                req = entities.HostSubscription(host=host_id).subscriptions()
                assert (prod_name in req['results'][0]['product_name']
                        ), 'Subscription not applied to HC members'
            # Remove the subscription
            # Call nailgun to make the API PUT to members of Host Collection
            entities.Host().bulk_remove_subscriptions(
                data={
                    "organization_id":
                    self.org.id,
                    "included": {
                        "ids": host_ids
                    },
                    "subscriptions": [{
                        "id": product_subscription.id,
                        "quantity": 1
                    }],
                })
            # GET the subscriptions from hosts and assert they are gone
            for host_id in host_ids:
                req = entities.HostSubscription(host=host_id).subscriptions()
                assert not req[
                    'results'], 'Subscription not removed from HC members'
Ejemplo n.º 14
0
    def test_pre_create_virt_who_configuration(self):
        """Create and deploy virt-who configuration.

        :id: preupgrade-a36cbe89-47a2-422f-9881-0f86bea0e24e

        :steps: In Preupgrade Satellite, Create and deploy virt-who configuration.

        :expectedresults:
            1. Config can be created and deployed by command.
            2. No error msg in /var/log/rhsm/rhsm.log.
            3. Report is sent to satellite.
            4. Virtual sku can be generated and attached.
        """
        default_loc_id = (
            entities.Location().search(query={'search': 'name="{}"'.format(DEFAULT_LOC)})[0].id
        )
        default_loc = entities.Location(id=default_loc_id).read()
        org = entities.Organization(name=self.org_name).create()
        default_loc.organization.append(entities.Organization(id=org.id))
        default_loc.update(['organization'])
        with manifests.clone() as manifest:
            upload_manifest(org.id, manifest.content)
        args = self._make_virtwho_configure()
        args.update({'name': self.name, 'organization_id': org.id})
        vhd = entities.VirtWhoConfig(**args).create()
        self.assertEqual(vhd.status, 'unknown')
        command = get_configure_command(vhd.id, org=org.name)
        hypervisor_name, guest_name = deploy_configure_by_command(
            command, args['hypervisor_type'], debug=True, org=org.name
        )
        self.assertEqual(
            entities.VirtWhoConfig(organization_id=org.id)
            .search(query={'search': 'name={}'.format(self.name)})[0]
            .status,
            'ok',
        )
        hosts = [
            (hypervisor_name, 'product_id={} and type=NORMAL'.format(self.vdc_physical)),
            (guest_name, 'product_id={} and type=STACK_DERIVED'.format(self.vdc_physical)),
        ]
        for hostname, sku in hosts:
            if 'type=NORMAL' in sku:
                subscriptions = entities.Subscription(organization=org.id).search(
                    query={'search': sku}
                )
                vdc_id = subscriptions[0].id
            if 'type=STACK_DERIVED' in sku:
                subscriptions = entities.Subscription(organization=org.id).search(
                    query={'search': sku}
                )
                vdc_id = subscriptions[0].id
            host, time = wait_for(
                entities.Host(organization=org.id).search,
                func_args=(None, {'search': hostname}),
                fail_condition=[],
                timeout=5,
                delay=1,
            )
            entities.HostSubscription(host=host[0].id).add_subscriptions(
                data={'subscriptions': [{'id': vdc_id, 'quantity': 1}]}
            )
            result = (
                entities.Host(organization=org.id)
                .search(query={'search': hostname})[0]
                .read_json()
            )
            self.assertEqual(result['subscription_status_label'], 'Fully entitled')

        scenario_dict = {
            self.__class__.__name__: {
                'hypervisor_name': hypervisor_name,
                'guest_name': guest_name,
            }
        }
        create_dict(scenario_dict)