Ejemplo n.º 1
0
 def setUpClass(cls):
     super(AnsibleREXTestCase, cls).setUpClass()
     cls.sat6_hostname = settings.server.hostname
     # register and setup a host here and tests will share the host, step 0.
     cls.org = entities.Organization().create()
     # create subnet for current org, default loc and domain
     # add rex proxy to subnet, default is internal proxy (id 1)
     # using API due BZ#1370460
     cls.sn = entities.Subnet(
         domain=[1],
         gateway=settings.vlan_networking.gateway,
         ipam='DHCP',
         location=[DEFAULT_LOC_ID],
         mask=settings.vlan_networking.netmask,
         network=settings.vlan_networking.subnet,
         organization=[cls.org.id],
         remote_execution_proxy=[entities.SmartProxy(id=1)],
     ).create()
     # Create VM and register content host
     cls.client = VirtualMachine(
         distro=DISTRO_RHEL7,
         provisioning_server=settings.compute_resources.libvirt_hostname,
         bridge=settings.vlan_networking.bridge)
     cls.addCleanup(vm_cleanup, cls.client)
     cls.client.create()
     cls.client.install_katello_ca()
     cls.client.register_contenthost(org=cls.org['label'], lce='Library')
     cls.assertTrue(cls.client.subscribed)
     Host.set_parameter({
         'host': cls.client.hostname,
         'name': 'remote_execution_connect_by_ip',
         'value': 'True',
     })
     add_remote_execution_ssh_key(cls.client.ip_addr)
Ejemplo n.º 2
0
    def test_positive_update_parameter_by_host_id(self):
        """Update existing host parameter by specifying host ID.

        @id: 56c43ab4-7fb0-44f5-9d54-107d3c1011bf

        @Assert: Host parameter was successfully updated with new value.

        """
        name = gen_string('alphanumeric').lower()
        old_value = gen_string('alphanumeric')
        Host.set_parameter({
            'host-id': self.host['id'],
            'name': name,
            'value': old_value,
        })
        for new_value in valid_data_list():
            with self.subTest(new_value):
                Host.set_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                    'value': new_value,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertIn(name, self.host['parameters'].keys())
                self.assertEqual(new_value, self.host['parameters'][name])
Ejemplo n.º 3
0
    def test_positive_run_default_job_template_by_ip(self):
        """Run default template on host connected by ip

        :id: 811c7747-bec6-4a2d-8e5c-b5045d3fbc0d

        :expectedresults: Verify the job was successfully ran against the host
        """
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
Ejemplo n.º 4
0
    def test_positive_update_parameter_by_host_name(self):
        """Update existing host parameter by specifying host name.

        @Feature: Hosts

        @Assert: Host parameter was successfully updated with new value.

        """
        name = gen_string('alphanumeric').lower()
        old_value = gen_string('alphanumeric')
        Host.set_parameter({
            'host': self.host['name'],
            'name': name,
            'value': old_value,
        })
        for new_value in valid_data_list():
            with self.subTest(new_value):
                Host.set_parameter({
                    'host': self.host['name'],
                    'name': name,
                    'value': new_value,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertIn(name, self.host['parameters'].keys())
                self.assertEqual(new_value, self.host['parameters'][name])
Ejemplo n.º 5
0
    def test_positive_run_job_effective_user_by_ip(self):
        """Run default job template as effective user on a host by ip

        :id: 0cd75cab-f699-47e6-94d3-4477d2a94bb7

        :expectedresults: Verify the job was successfully run under the
            effective user identity on host
        """
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        # create a user on client via remote job
        username = gen_string('alpha')
        filename = gen_string('alpha')
        make_user_job = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            "command='useradd {0}'".format(username),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(make_user_job[u'success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': make_user_job[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
        # create a file as new user
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            "command='touch /home/{0}/{1}'".format(username, filename),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
            'effective-user':
            '******'.format(username),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
        # check the file owner
        result = ssh.command('''stat -c '%U' /home/{0}/{1}'''.format(
            username, filename),
                             hostname=self.client.ip_addr)
        # assert the file is owned by the effective user
        self.assertEqual(username, result.stdout[0])
Ejemplo n.º 6
0
    def test_positive_update_parameter_by_host_id(self):
        """Update existing host parameter by specifying host ID.

        @id: 56c43ab4-7fb0-44f5-9d54-107d3c1011bf

        @Assert: Host parameter was successfully updated with new value.

        """
        name = gen_string('alphanumeric').lower()
        old_value = gen_string('alphanumeric')
        Host.set_parameter({
            'host-id': self.host['id'],
            'name': name,
            'value': old_value,
        })
        for new_value in valid_data_list():
            with self.subTest(new_value):
                Host.set_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                    'value': new_value,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertIn(name, self.host['parameters'].keys())
                self.assertEqual(new_value, self.host['parameters'][name])
Ejemplo n.º 7
0
    def test_positive_update_parameter_by_host_name(self):
        """Update existing host parameter by specifying host name.

        @id: 24bcc8a4-7787-4fa8-9bf8-dfc5e697684f

        @Assert: Host parameter was successfully updated with new value.

        """
        name = gen_string('alphanumeric').lower()
        old_value = gen_string('alphanumeric')
        Host.set_parameter({
            'host': self.host['name'],
            'name': name,
            'value': old_value,
        })
        for new_value in valid_data_list():
            with self.subTest(new_value):
                Host.set_parameter({
                    'host': self.host['name'],
                    'name': name,
                    'value': new_value,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertIn(name, self.host['parameters'].keys())
                self.assertEqual(new_value, self.host['parameters'][name])
Ejemplo n.º 8
0
    def test_positive_install_multiple_packages_with_a_job_by_ip(self):
        """Run job to install several packages on host by ip

        :id: 8b73033f-83c9-4024-83c3-5e442a79d320

        :expectedresults: Verify the packages were successfully installed
            on host
        """
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        packages = ["cow", "dog", "lion"]
        # Create a custom repo
        repo = entities.Repository(
            content_type='yum',
            product=entities.Product(organization=self.org).create(),
            url=FAKE_0_YUM_REPO,
        ).create()
        repo.sync()
        prod = repo.product.read()
        subs = entities.Subscription().search(
            query={'search': 'name={0}'.format(prod.name)}
        )
        self.assertGreater(
            len(subs), 0, 'No subscriptions matching the product returned'
        )

        ak = entities.ActivationKey(
            organization=self.org,
            content_view=self.org.default_content_view,
            environment=self.org.library
        ).create()
        ak.add_subscriptions(data={'subscriptions': [{'id': subs[0].id}]})
        self.client.register_contenthost(
            org=self.org.label, activation_key=ak.name
        )

        invocation_command = make_job_invocation({
            'job-template': 'Install Package - Katello SSH Default',
            'inputs': 'package={0} {1} {2}'.format(*packages),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        result = ssh.command(
            "rpm -q {0}".format(" ".join(packages)),
            hostname=self.client.ip_addr
        )
        self.assertEqual(result.return_code, 0)
Ejemplo n.º 9
0
    def test_positive_run_custom_job_template_by_ip(self):
        """Run custom template on host connected by ip

        :id: 9740eb1d-59f5-42b2-b3ab-659ca0202c74

        :expectedresults: Verify the job was successfully ran against the host
        """
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        template_name = gen_string('alpha', 7)
        make_job_template({
            u'organizations': self.org.name,
            u'name': template_name,
            u'file': TEMPLATE_FILE
        })
        invocation_command = make_job_invocation({
            'job-template': template_name,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
Ejemplo n.º 10
0
    def test_positive_run_default_job_template_by_ip(self, fixture_vmsetup,
                                                     fixture_org):
        """Run default template on host connected by ip

        :id: 811c7747-bec6-4a2d-8e5c-b5045d3fbc0d

        :expectedresults: Verify the job was successfully ran against the host
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            'command="ls"',
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert invocation_command['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
Ejemplo n.º 11
0
    def test_positive_run_reccuring_job(self, fixture_vmsetup, fixture_org):
        """Tests Ansible REX reccuring job runs successfully multiple times

        :id: 49b0d31d-58f9-47f1-aa5d-561a1dcb0d66

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run recurring Ansible Command job for the host

            2. Check the multiple job results at the host

        :expectedresults: multiple asserts along the code

        :caseautomation: automated

        :CaseLevel: System
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - Ansible Default',
            'inputs': 'command="ls"',
            'search-query': "name ~ {0}".format(self.client.hostname),
            'cron-line': '* * * * *',  # every minute
            'max-iteration': 2,  # just two runs
        })
        JobInvocation.get_output({
            'id': invocation_command[u'id'],
            'host': self.client.hostname
        })
        try:
            assert invocation_command['status'] == u'queued'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # Wait until the job runs
        pending_state = u'1'
        for _ in range(5):
            if pending_state != u'0':
                invocation_info = JobInvocation.info({
                    'id': invocation_command[u'id']})
                pending_state = invocation_info[u'pending']
                sleep(30)
        rec_logic = RecurringLogic.info({
            'id': invocation_command['recurring-logic-id']})
        assert rec_logic['state'] == u'finished'
        assert rec_logic['iteration'] == u'2'
Ejemplo n.º 12
0
    def test_positive_run_custom_job_template_by_ip(self):
        """Run custom template on host connected by ip

        :id: 9740eb1d-59f5-42b2-b3ab-659ca0202c74

        :expectedresults: Verify the job was successfully ran against the host
        """
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        template_name = gen_string('alpha', 7)
        make_job_template({
            u'organizations': self.org.name,
            u'name': template_name,
            u'file': TEMPLATE_FILE
        })
        invocation_command = make_job_invocation({
            'job-template': template_name,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
Ejemplo n.º 13
0
    def test_positive_install_multiple_packages_with_a_job_by_ip(self):
        """Run job to install several packages on host by ip

        :id: 8b73033f-83c9-4024-83c3-5e442a79d320

        :expectedresults: Verify the packages were successfully installed
            on host
        """
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        packages = ["cow", "dog", "lion"]
        # Create a custom repo
        repo = entities.Repository(
            content_type='yum',
            product=entities.Product(organization=self.org).create(),
            url=FAKE_0_YUM_REPO,
        ).create()
        repo.sync()
        prod = repo.product.read()
        subs = entities.Subscription().search(
            query={'search': 'name={0}'.format(prod.name)}
        )
        self.assertGreater(
            len(subs), 0, 'No subscriptions matching the product returned'
        )

        ak = entities.ActivationKey(
            organization=self.org,
            content_view=self.org.default_content_view,
            environment=self.org.library
        ).create()
        ak.add_subscriptions(data={'subscriptions': [{'id': subs[0].id}]})
        self.client.register_contenthost(
            org=self.org.label, activation_key=ak.name
        )

        invocation_command = make_job_invocation({
            'job-template': 'Install Package - Katello SSH Default',
            'inputs': 'package={0} {1} {2}'.format(*packages),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        result = ssh.command(
            "rpm -q {0}".format(" ".join(packages)),
            hostname=self.client.ip_addr
        )
        self.assertEqual(result.return_code, 0)
Ejemplo n.º 14
0
    def test_positive_run_reccuring_job(self, fixture_vmsetup, fixture_org):
        """Tests Ansible REX reccuring job runs successfully multiple times

        :id: 49b0d31d-58f9-47f1-aa5d-561a1dcb0d66

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run recurring Ansible Command job for the host

            2. Check the multiple job results at the host

        :expectedresults: multiple asserts along the code

        :CaseAutomation: automated

        :CaseLevel: System

        :parametrized: yes
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - Ansible Default',
            'inputs':
            'command="ls"',
            'search-query':
            "name ~ {0}".format(self.client.hostname),
            'cron-line':
            '* * * * *',  # every minute
            'max-iteration':
            2,  # just two runs
        })
        JobInvocation.get_output({
            'id': invocation_command['id'],
            'host': self.client.hostname
        })
        try:
            assert invocation_command['status'] == 'queued'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
        sleep(150)
        rec_logic = RecurringLogic.info(
            {'id': invocation_command['recurring-logic-id']})
        assert rec_logic['state'] == 'finished'
        assert rec_logic['iteration'] == '2'
Ejemplo n.º 15
0
    def test_positive_run_job_effective_user_by_ip(self, fixture_vmsetup, fixture_org):
        """Run default job template as effective user on a host by ip

        :id: 0cd75cab-f699-47e6-94d3-4477d2a94bb7

        :expectedresults: Verify the job was successfully run under the
            effective user identity on host
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        # create a user on client via remote job
        username = gen_string('alpha')
        filename = gen_string('alpha')
        make_user_job = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': "command='useradd -m {0}'".format(username),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert make_user_job[u'success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': make_user_job[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # create a file as new user
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': "command='touch /home/{0}/{1}'".format(
                username, filename),
            'search-query': "name ~ {0}".format(self.client.hostname),
            'effective-user': '******'.format(username),
        })
        try:
            assert invocation_command['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # check the file owner
        result = ssh.command(
            '''stat -c '%U' /home/{0}/{1}'''.format(username, filename),
            hostname=self.client.ip_addr
        )
        # assert the file is owned by the effective user
        assert username == result.stdout[0]
Ejemplo n.º 16
0
    def test_positive_run_receptor_installer(self):
        """Run Receptor installer ("Configure Cloud Connector")

        :CaseComponent: RHCloud-CloudConnector

        :Assignee: lhellebr

        :id: 811c7747-bec6-1a2d-8e5c-b5045d3fbc0d

        :expectedresults: The job passes, installs Receptor that peers with c.r.c

        :BZ: 1818076
        """
        # Set Host parameter source_display_name to something random.
        # To avoid 'name has already been taken' error when run multiple times
        # on a machine with the same hostname.
        host_id = Host.info({'name': settings.server.hostname})['id']
        Host.set_parameter({
            'host-id': host_id,
            'name': 'source_display_name',
            'value': gen_string('alpha')
        })

        template_name = 'Configure Cloud Connector'
        invocation = make_job_invocation({
            'async':
            True,
            'job-template':
            template_name,
            'inputs':
            f'satellite_user="******",\
                        satellite_password="******"',
            'search-query':
            f'name ~ {settings.server.hostname}',
        })
        invocation_id = invocation['id']

        wait_for(
            lambda: entities.JobInvocation(id=invocation_id).read().
            status_label in ["succeeded", "failed"],
            timeout="1500s",
        )
        assert entities.JobInvocation(id=invocation_id).read().status == 0

        result = ' '.join(
            JobInvocation.get_output({
                'id': invocation_id,
                'host': settings.server.hostname
            }))
        assert 'project-receptor.satellite_receptor_installer' in result
        assert 'Exit status: 0' in result
        # check that there is one receptor conf file and it's only readable
        # by the receptor user and root
        result = ssh.command(
            'stat /etc/receptor/*/receptor.conf --format "%a:%U"')
        assert result.stdout[0] == '400:foreman-proxy'
        result = ssh.command('ls -l /etc/receptor/*/receptor.conf | wc -l')
        assert result.stdout[0] == '1'
Ejemplo n.º 17
0
def test_positive_run_default_job_template_by_ip(session, module_org,
                                                 module_subnet):
    """Run a job template on a host connected by ip

    :id: 9a90aa9a-00b4-460e-b7e6-250360ee8e4d

    :Setup: Use pre-defined job template.

    :Steps:

        1. Set remote_execution_connect_by_ip on host to true
        2. Navigate to an individual host and click Run Job
        3. Select the job and appropriate template
        4. Run the job

    :expectedresults: Verify the job was successfully ran against the host

    :CaseLevel: System
    """
    with VirtualMachine(
            distro=DISTRO_RHEL6,
            provisioning_server=settings.compute_resources.libvirt_hostname,
            bridge=settings.vlan_networking.bridge,
    ) as client:
        client.install_katello_ca()
        client.register_contenthost(module_org.label, lce='Library')
        assert client.subscribed
        add_remote_execution_ssh_key(client.ip_addr)
        Host.update({
            'name': client.hostname,
            'subnet-id': module_subnet.id,
        })
        # connect to host by ip
        Host.set_parameter({
            'host': client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        hostname = client.hostname
        with session:
            session.organization.select(module_org.name)
            assert session.host.search(hostname)[0]['Name'] == hostname
            session.jobinvocation.run({
                'job_category':
                'Commands',
                'job_template':
                'Run Command - SSH Default',
                'search_query':
                'name ^ {}'.format(hostname),
                'template_content.command':
                'ls',
            })
            session.jobinvocation.wait_job_invocation_state(
                entity_name='Run ls', host_name=hostname)
            status = session.jobinvocation.read(entity_name='Run ls',
                                                host_name=hostname)
            assert status['overview']['hosts_table'][0]['Status'] == 'success'
Ejemplo n.º 18
0
    def test_positive_run_default_job_template_by_ip(self):
        """Run a job template on a host connected by ip

        :id: 9a90aa9a-00b4-460e-b7e6-250360ee8e4d

        :Setup: Use pre-defined job template.

        :Steps:

            1. Set remote_execution_connect_by_ip on host to true
            2. Navigate to an individual host and click Run Job
            3. Select the job and appropriate template
            4. Run the job

        :expectedresults: Verify the job was successfully ran against the host

        :CaseLevel: Integration
        """
        with VirtualMachine(
              distro=DISTRO_RHEL7,
              provisioning_server=settings.compute_resources.libvirt_hostname,
              bridge=settings.vlan_networking.bridge,
              ) as client:
            client.install_katello_ca()
            client.register_contenthost(self.organization.label, lce='Library')
            self.assertTrue(client.subscribed)
            add_remote_execution_ssh_key(client.ip_addr)
            Host.update({
                'name': client.hostname,
                'subnet-id': self.new_sub.id,
            })
            # connect to host by ip
            Host.set_parameter({
                'host': client.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            })
            with Session(self) as session:
                set_context(session, org=self.organization.name)
                self.hosts.click(self.hosts.search(client.hostname))
                status = self.job.run(
                    job_category='Commands',
                    job_template='Run Command - SSH Default',
                    options_list=[{'name': 'command', 'value': 'ls'}]
                )
                # get job invocation id from the current url
                invocation_id = self.browser.current_url.rsplit('/', 1)[-1]
                try:
                    self.assertTrue(status)
                except AssertionError:
                    result = 'host output: {0}'.format(
                            ' '.join(JobInvocation.get_output({
                                'id': invocation_id,
                                'host': client.hostname})
                            )
                        )
                    raise AssertionError(result)
Ejemplo n.º 19
0
def _setup_host(client, org_label):
    """Set up host for remote execution"""
    client.install_katello_ca()
    client.register_contenthost(org=org_label, lce='Library')
    assert client.subscribed
    add_remote_execution_ssh_key(client.ip_addr)
    Host.set_parameter({
        'host': client.hostname,
        'name': 'remote_execution_connect_by_ip',
        'value': 'True',
    })
Ejemplo n.º 20
0
    def test_positive_run_default_job_template_multiple_hosts_by_ip(
        self, fixture_vmsetup, fixture_org
    ):
        """Run default job template against multiple hosts by ip

        :id: 694a21d3-243b-4296-8bd0-4bad9663af15

        :expectedresults: Verify the job was successfully ran against all hosts

        :parametrized: yes
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        Host.set_parameter(
            {
                'host': self.client.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            }
        )
        with VirtualMachine(distro=DISTRO_RHEL7) as client2:
            client2.install_katello_ca()
            client2.register_contenthost(self.org.label, lce='Library')
            add_remote_execution_ssh_key(client2.ip_addr)
            Host.set_parameter(
                {
                    'host': client2.hostname,
                    'name': 'remote_execution_connect_by_ip',
                    'value': 'True',
                }
            )
            invocation_command = make_job_invocation(
                {
                    'job-template': 'Run Command - SSH Default',
                    'inputs': 'command="ls"',
                    'search-query': "name ~ {} or name ~ {}".format(
                        self.client.hostname, client2.hostname
                    ),
                }
            )
            # collect output messages from clients
            output_msgs = []
            for vm in self.client, client2:
                output_msgs.append(
                    'host output from {}: {}'.format(
                        vm.hostname,
                        ' '.join(
                            JobInvocation.get_output(
                                {'id': invocation_command['id'], 'host': vm.hostname}
                            )
                        ),
                    )
                )
            assert invocation_command['success'] == '2', output_msgs
Ejemplo n.º 21
0
def test_positive_run_default_job_template_by_ip(
        session, module_org, module_subnet):
    """Run a job template on a host connected by ip

    :id: 9a90aa9a-00b4-460e-b7e6-250360ee8e4d

    :Setup: Use pre-defined job template.

    :Steps:

        1. Set remote_execution_connect_by_ip on host to true
        2. Navigate to an individual host and click Run Job
        3. Select the job and appropriate template
        4. Run the job

    :expectedresults: Verify the job was successfully ran against the host

    :CaseLevel: Integration
    """
    with VirtualMachine(
        distro=DISTRO_RHEL6,
        provisioning_server=settings.compute_resources.libvirt_hostname,
        bridge=settings.vlan_networking.bridge,
    ) as client:
        client.install_katello_ca()
        client.register_contenthost(module_org.label, lce='Library')
        assert client.subscribed
        add_remote_execution_ssh_key(client.ip_addr)
        Host.update({
            'name': client.hostname,
            'subnet-id': module_subnet.id,
        })
        # connect to host by ip
        Host.set_parameter({
            'host': client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        hostname = client.hostname
        with session:
            session.organization.select(module_org.name)
            assert session.host.search(hostname)[0]['Name'] == hostname
            session.jobinvocation.run({
                'job_category': 'Commands',
                'job_template': 'Run Command - SSH Default',
                'search_query': 'name ^ {}'.format(hostname),
                'template_content.command': 'ls',
            })
            session.jobinvocation.wait_job_invocation_state(
                entity_name='Run ls', host_name=hostname)
            status = session.jobinvocation.read(
                entity_name='Run ls', host_name=hostname)
            assert status['overview']['hosts_table'][0]['Status'] == 'success'
Ejemplo n.º 22
0
    def test_positive_run_recurring_job_with_max_iterations_by_ip(
            self, fixture_vmsetup, fixture_org):
        """Run default job template multiple times with max iteration by ip

        :id: 0a3d1627-95d9-42ab-9478-a908f2a7c509

        :expectedresults: Verify the job was run not more than the specified
            number of times.

        :parametrized: yes
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            'command="ls"',
            'search-query':
            "name ~ {0}".format(self.client.hostname),
            'cron-line':
            '* * * * *',  # every minute
            'max-iteration':
            2,  # just two runs
        })

        JobInvocation.get_output({
            'id': invocation_command['id'],
            'host': self.client.hostname
        })
        try:
            assert invocation_command['status'] == 'queued'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)

        sleep(150)
        rec_logic = RecurringLogic.info(
            {'id': invocation_command['recurring-logic-id']})
        assert rec_logic['state'] == 'finished'
        assert rec_logic['iteration'] == '2'
Ejemplo n.º 23
0
    def test_positive_run_scheduled_job_template_by_ip(self, fixture_vmsetup,
                                                       fixture_org):
        """Schedule a job to be ran against a host

        :id: 0407e3de-ef59-4706-ae0d-b81172b81e5c

        :expectedresults: Verify the job was successfully ran after the
            designated time

        :parametrized: yes
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        system_current_time = ssh.command(
            'date --utc +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(system_current_time,
                                                '%b %d %Y %I:%M%p')
        plan_time = (current_time_object +
                     timedelta(seconds=30)).strftime("%Y-%m-%d %H:%M")
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            'command="ls"',
            'start-at':
            plan_time,
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        # Wait until the job runs
        pending_state = '1'
        while pending_state != '0':
            invocation_info = JobInvocation.info(
                {'id': invocation_command['id']})
            pending_state = invocation_info['pending']
            sleep(30)
        invocation_info = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert invocation_info['success'] == '1'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
Ejemplo n.º 24
0
    def test_positive_run_default_job_template_multiple_hosts_by_ip(self):
        """Run default job template against multiple hosts by ip

        :id: 694a21d3-243b-4296-8bd0-4bad9663af15

        :expectedresults: Verify the job was successfully ran against all hosts
        """
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        with VirtualMachine(
                distro=DISTRO_RHEL7,
                provisioning_server=settings.compute_resources.
                libvirt_hostname,
                bridge=settings.vlan_networking.bridge,
        ) as client2:
            client2.install_katello_ca()
            client2.register_contenthost(self.org.label, lce='Library')
            add_remote_execution_ssh_key(client2.ip_addr)
            Host.set_parameter({
                'host': client2.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            })
            invocation_command = make_job_invocation({
                'job-template':
                'Run Command - SSH Default',
                'inputs':
                'command="ls"',
                'search-query':
                "name ~ {0} or name ~ {1}".format(self.client.hostname,
                                                  client2.hostname),
            })
            # collect output messages from clients
            output_msgs = []
            for vm in self.client, client2:
                output_msgs.append('host output from {0}: {1}'.format(
                    vm.hostname, ' '.join(
                        JobInvocation.get_output({
                            'id':
                            invocation_command[u'id'],
                            'host':
                            vm.hostname
                        }))))
            self.assertEqual(invocation_command['success'], u'2', output_msgs)
Ejemplo n.º 25
0
    def test_positive_run_default_job_template_by_ip(self, fixture_vmsetup, fixture_org):
        """Run default template on host connected by ip and list task

        :id: 811c7747-bec6-4a2d-8e5c-b5045d3fbc0d

        :expectedresults: Verify the job was successfully ran against the host
            and task can be listed by name and ID

        :BZ: 1647582

        :parametrized: yes
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host via ip
        Host.set_parameter(
            {
                'host': self.client.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            }
        )
        command = "echo {}".format(gen_string('alpha'))
        invocation_command = make_job_invocation(
            {
                'job-template': 'Run Command - SSH Default',
                'inputs': f'command={command}',
                'search-query': f"name ~ {self.client.hostname}",
            }
        )

        try:
            assert invocation_command['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(
                ' '.join(
                    JobInvocation.get_output(
                        {'id': invocation_command['id'], 'host': self.client.hostname}
                    )
                )
            )
            raise AssertionError(result)

        task = Task.list_tasks({"search": command})[0]
        search = Task.list_tasks({"search": 'id={}'.format(task["id"])})
        assert search[0]["action"] == task["action"]
Ejemplo n.º 26
0
    def test_positive_run_scheduled_job_template_by_ip(self, fixture_vmsetup, fixture_org):
        """Schedule a job to be ran against a host

        :id: 0407e3de-ef59-4706-ae0d-b81172b81e5c

        :expectedresults: Verify the job was successfully ran after the
            designated time
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        system_current_time = ssh.command('date --utc +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(
            system_current_time, '%b %d %Y %I:%M%p')
        plan_time = (current_time_object + timedelta(seconds=30)).strftime(
            "%Y-%m-%d %H:%M")
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'start-at': plan_time,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        # Wait until the job runs
        pending_state = u'1'
        while pending_state != u'0':
            invocation_info = JobInvocation.info({
                'id': invocation_command[u'id']})
            pending_state = invocation_info[u'pending']
            sleep(30)
        invocation_info = JobInvocation.info({
            'id': invocation_command[u'id']})
        try:
            assert invocation_info['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
Ejemplo n.º 27
0
    def test_positive_add_parameter_with_name(self):
        """Add host parameter with different valid names.

        @id: 67b1c496-8f33-4a34-aebb-7339bc33ce77

        @Assert: Host parameter was successfully added with correct name.

        """
        for name in valid_data_list():
            with self.subTest(name):
                name = name.lower()
                Host.set_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                    'value': gen_string('alphanumeric'),
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertIn(name, self.host['parameters'].keys())
Ejemplo n.º 28
0
def fixture_vmsetup(request, module_org):
    """Create Org, Lifecycle Environment, Content View, Activation key,
    VM, install katello-ca, register it, add remote execution key
    """
    # Create VM and register content host
    with VMBroker(nick=request.param, host_classes={'host': ContentHost}) as client:
        client.install_katello_ca()
        client.register_contenthost(org=module_org.label, lce='Library')
        assert client.subscribed
        add_remote_execution_ssh_key(client.ip_addr)
        Host.set_parameter(
            {
                'host': client.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            }
        )
        yield client
Ejemplo n.º 29
0
    def test_positive_add_parameter_with_name(self):
        """Add host parameter with different valid names.

        @Feature: Hosts

        @Assert: Host parameter was successfully added with correct name.

        """
        for name in valid_data_list():
            with self.subTest(name):
                name = name.lower()
                Host.set_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                    'value': gen_string('alphanumeric'),
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertIn(name, self.host['parameters'].keys())
Ejemplo n.º 30
0
    def test_positive_run_recurring_job_with_max_iterations_by_ip(self, fixture_vmsetup,
                                                                  fixture_org):
        """Run default job template multiple times with max iteration by ip

        :id: 0a3d1627-95d9-42ab-9478-a908f2a7c509

        :expectedresults: Verify the job was run not more than the specified
            number of times.
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'search-query': "name ~ {0}".format(self.client.hostname),
            'cron-line': '* * * * *',  # every minute
            'max-iteration': 2,  # just two runs
        })
        if not bz_bug_is_open(1431190):
            JobInvocation.get_output({
                'id': invocation_command[u'id'],
                'host': self.client.hostname
            })
            try:
                assert invocation_command['status'] == u'queued'
            except AssertionError:
                result = 'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                        )
                    )
                raise AssertionError(result)
        sleep(150)
        rec_logic = RecurringLogic.info({
            'id': invocation_command['recurring-logic-id']})
        assert rec_logic['state'] == u'finished'
        assert rec_logic['iteration'] == u'2'
Ejemplo n.º 31
0
    def test_positive_run_default_job_template_multiple_hosts_by_ip(self):
        """Run default job template against multiple hosts by ip

        :id: 694a21d3-243b-4296-8bd0-4bad9663af15

        :expectedresults: Verify the job was successfully ran against all hosts
        """
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        with VirtualMachine(
            distro=DISTRO_RHEL7,
            provisioning_server=settings.compute_resources.libvirt_hostname,
            bridge=settings.vlan_networking.bridge,
        ) as client2:
            client2.install_katello_ca()
            client2.register_contenthost(
                self.org.label, lce='Library')
            add_remote_execution_ssh_key(client2.ip_addr)
            Host.set_parameter({
                'host': client2.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            })
            invocation_command = make_job_invocation({
                'job-template': 'Run Command - SSH Default',
                'inputs': 'command="ls"',
                'search-query': "name ~ {0} or name ~ {1}".format(
                    self.client.hostname, client2.hostname),
            })
            # collect output messages from clients
            output_msgs = []
            for vm in self.client, client2:
                output_msgs.append('host output from {0}: {1}'.format(
                    vm.hostname,
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': vm.hostname})
                    )
                )
                )
            self.assertEqual(invocation_command['success'], u'2', output_msgs)
Ejemplo n.º 32
0
    def test_positive_add_parameter_by_host_name(self):
        """Add host parameter by specifying host name.

        @Feature: Hosts

        @Assert: Host parameter was successfully added with correct name and
        value.

        """
        name = gen_string('alphanumeric').lower()
        value = gen_string('alphanumeric')
        Host.set_parameter({
            'host': self.host['name'],
            'name': name,
            'value': value,
        })
        self.host = Host.info({'id': self.host['id']})
        self.assertIn(name, self.host['parameters'].keys())
        self.assertEqual(value, self.host['parameters'][name])
Ejemplo n.º 33
0
    def test_positive_add_parameter_with_value(self):
        """Add host parameter with different valid values.

        @Feature: Hosts

        @Assert: Host parameter was successfully added with value.

        """
        for value in valid_data_list():
            with self.subTest(value):
                name = gen_string('alphanumeric').lower()
                Host.set_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                    'value': value,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertIn(name, self.host['parameters'].keys())
                self.assertEqual(value, self.host['parameters'][name])
Ejemplo n.º 34
0
    def test_negative_add_parameter(self):
        """Try to add host parameter with different invalid names.

        @Feature: Hosts

        @Assert: Host parameter was not added.

        """
        for name in invalid_values_list():
            with self.subTest(name):
                name = name.lower()
                with self.assertRaises(CLIReturnCodeError):
                    Host.set_parameter({
                        'host-id': self.host['id'],
                        'name': name,
                        'value': gen_string('alphanumeric'),
                    })
                self.host = Host.info({'id': self.host['id']})
                self.assertNotIn(name, self.host['parameters'].keys())
Ejemplo n.º 35
0
    def test_positive_install_multiple_packages_with_a_job_by_ip(self):
        """Run job to install several packages on host by ip

        :id: 8b73033f-83c9-4024-83c3-5e442a79d320

        :expectedresults: Verify the packages were successfully installed
            on host
        """
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        packages = ["cow", "dog", "lion"]
        # Create a custom repo
        setup_org_for_a_custom_repo({
            u'url': FAKE_0_YUM_REPO,
            u'organization-id': self.org['id'],
            u'content-view-id': self.content_view['id'],
            u'lifecycle-environment-id': self.env['id'],
            u'activationkey-id': self.activation_key['id'],
        })
        invocation_command = make_job_invocation({
            'job-template': 'Install Package - Katello SSH Default',
            'inputs': 'package={0} {1} {2}'.format(*packages),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        self.assertEqual(
                invocation_command['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )
        result = ssh.command(
                "rpm -q {0}".format(" ".join(packages)),
                hostname=self.client.ip_addr
                )
        self.assertEqual(result.return_code, 0)
Ejemplo n.º 36
0
def _setup_vm_client_host(vm_client, org_label, subnet_id=None, by_ip=True):
    """Setup a VM host for remote execution.

    :param VMBroker vm_client: where vm_client is VMBroker instance.
    :param str org_label: The organization label.
    :param int subnet: (Optional) Nailgun subnet entity id, to be used by the vm_client host.
    :param bool by_ip: Whether remote execution will use ip or host name to access server.
    """
    vm_client.install_katello_ca()
    vm_client.register_contenthost(org_label, lce='Library')
    assert vm_client.subscribed
    add_remote_execution_ssh_key(vm_client.ip_addr)
    if subnet_id is not None:
        Host.update({'name': vm_client.hostname, 'subnet-id': subnet_id})
    if by_ip:
        # connect to host by ip
        Host.set_parameter(
            {'host': vm_client.hostname, 'name': 'remote_execution_connect_by_ip', 'value': 'True'}
        )
Ejemplo n.º 37
0
    def test_positive_add_parameter_with_value(self):
        """Add host parameter with different valid values.

        @id: 1932b61d-8be4-4f58-9760-dc588cbca1d7

        @Assert: Host parameter was successfully added with value.

        """
        for value in valid_data_list():
            with self.subTest(value):
                name = gen_string('alphanumeric').lower()
                Host.set_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                    'value': value,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertIn(name, self.host['parameters'].keys())
                self.assertEqual(value, self.host['parameters'][name])
Ejemplo n.º 38
0
    def test_positive_add_parameter_by_host_name(self):
        """Add host parameter by specifying host name.

        @id: 32b09b07-39de-4706-ac5e-75a54255df17

        @Assert: Host parameter was successfully added with correct name and
        value.

        """
        name = gen_string('alphanumeric').lower()
        value = gen_string('alphanumeric')
        Host.set_parameter({
            'host': self.host['name'],
            'name': name,
            'value': value,
        })
        self.host = Host.info({'id': self.host['id']})
        self.assertIn(name, self.host['parameters'].keys())
        self.assertEqual(value, self.host['parameters'][name])
Ejemplo n.º 39
0
    def test_negative_add_parameter(self):
        """Try to add host parameter with different invalid names.

        @id: 473f8c3f-b66e-4526-88af-e139cc3dabcb

        @Assert: Host parameter was not added.

        """
        for name in invalid_values_list():
            with self.subTest(name):
                name = name.lower()
                with self.assertRaises(CLIReturnCodeError):
                    Host.set_parameter({
                        'host-id': self.host['id'],
                        'name': name,
                        'value': gen_string('alphanumeric'),
                    })
                self.host = Host.info({'id': self.host['id']})
                self.assertNotIn(name, self.host['parameters'].keys())
Ejemplo n.º 40
0
    def test_positive_delete_parameter_by_host_id(self):
        """Delete existing host parameter by specifying host ID.

        @id: a52da845-0403-4b66-9e83-6065f7d4551d

        @Assert: Host parameter was successfully deleted.

        """
        for name in valid_data_list():
            with self.subTest(name):
                name = name.lower()
                Host.set_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                    'value': gen_string('alphanumeric'),
                })
                Host.delete_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertNotIn(name, self.host['parameters'].keys())
Ejemplo n.º 41
0
    def test_posistive_delete_parameter_by_host_name(self):
        """Delete existing host parameter by specifying host name.

        @id: d28cbbba-d296-49c7-91f5-8fb63a80d82c

        @Assert: Host parameter was successfully deleted.

        """
        for name in valid_data_list():
            with self.subTest(name):
                name = name.lower()
                Host.set_parameter({
                    'host': self.host['name'],
                    'name': name,
                    'value': gen_string('alphanumeric'),
                })
                Host.delete_parameter({
                    'host': self.host['name'],
                    'name': name,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertNotIn(name, self.host['parameters'].keys())
Ejemplo n.º 42
0
    def test_posistive_delete_parameter_by_host_name(self):
        """Delete existing host parameter by specifying host name.

        @Feature: Hosts

        @Assert: Host parameter was successfully deleted.

        """
        for name in valid_data_list():
            with self.subTest(name):
                name = name.lower()
                Host.set_parameter({
                    'host': self.host['name'],
                    'name': name,
                    'value': gen_string('alphanumeric'),
                })
                Host.delete_parameter({
                    'host': self.host['name'],
                    'name': name,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertNotIn(name, self.host['parameters'].keys())
Ejemplo n.º 43
0
    def test_positive_delete_parameter_by_host_id(self):
        """Delete existing host parameter by specifying host ID.

        @id: a52da845-0403-4b66-9e83-6065f7d4551d

        @Assert: Host parameter was successfully deleted.

        """
        for name in valid_data_list():
            with self.subTest(name):
                name = name.lower()
                Host.set_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                    'value': gen_string('alphanumeric'),
                })
                Host.delete_parameter({
                    'host-id': self.host['id'],
                    'name': name,
                })
                self.host = Host.info({'id': self.host['id']})
                self.assertNotIn(name, self.host['parameters'].keys())
Ejemplo n.º 44
0
    def test_positive_run_effective_user_job(self, fixture_vmsetup,
                                             fixture_org):
        """Tests Ansible REX job having effective user runs successfully

        :id: a5fa20d8-c2bd-4bbf-a6dc-bf307b59dd8c

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run Ansible Command job for the host to create a user

            2. Run Ansible Command job using effective user

            3. Check the job result at the host is done under that user

        :expectedresults: multiple asserts along the code

        :CaseAutomation: automated

        :CaseLevel: System
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        # create a user on client via remote job
        username = gen_string('alpha')
        filename = gen_string('alpha')
        make_user_job = make_job_invocation({
            'job-template':
            'Run Command - Ansible Default',
            'inputs':
            "command='useradd -m {0}'".format(username),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert make_user_job[u'success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': make_user_job[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
        # create a file as new user
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - Ansible Default',
            'inputs':
            "command='touch /home/{0}/{1}'".format(username, filename),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
            'effective-user':
            '******'.format(username),
        })
        try:
            assert invocation_command['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
        # check the file owner
        result = ssh.command('''stat -c '%U' /home/{0}/{1}'''.format(
            username, filename),
                             hostname=self.client.ip_addr)
        # assert the file is owned by the effective user
        assert username == result.stdout[0], "file ownership mismatch"
Ejemplo n.º 45
0
    def test_positive_run_packages_and_services_job(self, fixture_vmsetup,
                                                    fixture_org):
        """Tests Ansible REX job can install packages and start services

        :id: 47ed82fb-77ca-43d6-a52e-f62bae5d3a42

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run Ansible Package job for the host to install a package

            2. Check the package is present at the host

            3. Run Ansible Service job for the host to start a service

            4. Check the service is started on the host

        :expectedresults: multiple asserts along the code

        :CaseAutomation: automated

        :CaseLevel: System
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        packages = ["cow"]
        # Create a custom repo
        repo = entities.Repository(
            content_type='yum',
            product=entities.Product(organization=self.org).create(),
            url=FAKE_0_YUM_REPO,
        ).create()
        repo.sync()
        prod = repo.product.read()
        subs = entities.Subscription().search(
            query={'search': 'name={0}'.format(prod.name)})
        assert len(subs) > 0, 'No subscriptions matching the product returned'
        ak = entities.ActivationKey(organization=self.org,
                                    content_view=self.org.default_content_view,
                                    environment=self.org.library).create()
        ak.add_subscriptions(data={'subscriptions': [{'id': subs[0].id}]})
        self.client.register_contenthost(org=self.org.label,
                                         activation_key=ak.name)

        # install package
        invocation_command = make_job_invocation({
            'job-template':
            'Package Action - Ansible Default',
            'inputs':
            'state=latest, name={}'.format(*packages),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert invocation_command['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
        result = ssh.command("rpm -q {0}".format(*packages),
                             hostname=self.client.ip_addr)
        assert result.return_code == 0

        # start a service
        service = "postfix"
        ssh.command(
            "sed -i 's/^inet_protocols.*/inet_protocols = ipv4/' /etc/postfix/main.cf",
            hostname=self.client.ip_addr)
        invocation_command = make_job_invocation({
            'job-template':
            'Service Action - Ansible Default',
            'inputs':
            'state=started, name={}'.format(service),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert invocation_command['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
        result = ssh.command("systemctl status {0}".format(service),
                             hostname=self.client.ip_addr)
        assert result.return_code == 0
Ejemplo n.º 46
0
    def test_positive_run_packages_and_services_job(self, fixture_vmsetup, fixture_org):
        """Tests Ansible REX job can install packages and start services

        :id: 47ed82fb-77ca-43d6-a52e-f62bae5d3a42

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run Ansible Package job for the host to install a package

            2. Check the package is present at the host

            3. Run Ansible Service job for the host to start a service

            4. Check the service is started on the host

        :expectedresults: multiple asserts along the code

        :caseautomation: automated

        :CaseLevel: System
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        packages = ["cow"]
        # Create a custom repo
        repo = entities.Repository(
            content_type='yum',
            product=entities.Product(organization=self.org).create(),
            url=FAKE_0_YUM_REPO,
        ).create()
        repo.sync()
        prod = repo.product.read()
        subs = entities.Subscription().search(
            query={'search': 'name={0}'.format(prod.name)}
        )
        assert len(subs) > 0, 'No subscriptions matching the product returned'
        ak = entities.ActivationKey(
            organization=self.org,
            content_view=self.org.default_content_view,
            environment=self.org.library
        ).create()
        ak.add_subscriptions(data={'subscriptions': [{'id': subs[0].id}]})
        self.client.register_contenthost(
            org=self.org.label, activation_key=ak.name
        )

        # install package
        invocation_command = make_job_invocation({
            'job-template': 'Package Action - Ansible Default',
            'inputs': 'state=latest, name={}'.format(*packages),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert invocation_command['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        result = ssh.command(
            "rpm -q {0}".format(*packages),
            hostname=self.client.ip_addr
        )
        assert result.return_code == 0

        # start a service
        service = "postfix"
        ssh.command(
            "sed -i 's/^inet_protocols.*/inet_protocols = ipv4/' /etc/postfix/main.cf",
            hostname=self.client.ip_addr
        )
        invocation_command = make_job_invocation({
            'job-template': 'Service Action - Ansible Default',
            'inputs': 'state=started, name={}'.format(service),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert invocation_command['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        result = ssh.command(
            "systemctl status {0}".format(service),
            hostname=self.client.ip_addr
        )
        assert result.return_code == 0
Ejemplo n.º 47
0
    def test_positive_run_effective_user_job(self, fixture_vmsetup, fixture_org):
        """Tests Ansible REX job having effective user runs successfully

        :id: a5fa20d8-c2bd-4bbf-a6dc-bf307b59dd8c

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run Ansible Command job for the host to create a user

            2. Run Ansible Command job using effective user

            3. Check the job result at the host is done under that user

        :expectedresults: multiple asserts along the code

        :caseautomation: automated

        :CaseLevel: System
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        # create a user on client via remote job
        username = gen_string('alpha')
        filename = gen_string('alpha')
        make_user_job = make_job_invocation({
            'job-template': 'Run Command - Ansible Default',
            'inputs': "command='useradd -m {0}'".format(username),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert make_user_job[u'success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': make_user_job[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # create a file as new user
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - Ansible Default',
            'inputs': "command='touch /home/{0}/{1}'".format(
                username, filename),
            'search-query': "name ~ {0}".format(self.client.hostname),
            'effective-user': '******'.format(username),
        })
        try:
            assert invocation_command['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # check the file owner
        result = ssh.command(
            '''stat -c '%U' /home/{0}/{1}'''.format(username, filename),
            hostname=self.client.ip_addr
        )
        # assert the file is owned by the effective user
        assert username == result.stdout[0], "file ownership mismatch"
    def test_positive_run_custom_job_template_by_ip(self):
        """Run a job template on a host connected by ip

        :id: e283ae09-8b14-4ce1-9a76-c1bbd511d58c

        :Setup: Create a working job template.

        :Steps:

            1. Set remote_execution_connect_by_ip on host to true
            2. Navigate to an individual host and click Run Job
            3. Select the job and appropriate template
            4. Run the job

        :expectedresults: Verify the job was successfully ran against the host

        :CaseLevel: System
        """
        jobs_template_name = gen_string('alpha')
        with VirtualMachine(
              distro=DISTRO_RHEL7,
              provisioning_server=settings.compute_resources.libvirt_hostname,
              bridge=settings.vlan_networking.bridge,
              ) as client:
            client.install_katello_ca()
            client.register_contenthost(self.organization.label, lce='Library')
            self.assertTrue(client.subscribed)
            add_remote_execution_ssh_key(client.ip_addr)
            Host.update({
                'name': client.hostname,
                'subnet-id': self.new_sub.id,
            })
            # connect to host by ip
            Host.set_parameter({
                'host': client.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            })
            with Session(self) as session:
                set_context(session, org=self.organization.name)
                make_job_template(
                    session,
                    name=jobs_template_name,
                    template_type='input',
                    template_content='<%= input("command") %>',
                    provider_type='SSH',
                )
                self.assertIsNotNone(
                    self.jobtemplate.search(jobs_template_name))
                self.jobtemplate.add_input(
                    jobs_template_name, 'command', required=True)
                self.hosts.click(self.hosts.search(client.hostname))
                status = self.job.run(
                    job_category='Miscellaneous',
                    job_template=jobs_template_name,
                    options_list=[{'name': 'command', 'value': 'ls'}]
                )
                # get job invocation id from the current url
                invocation_id = self.browser.current_url.rsplit('/', 1)[-1]
                try:
                    self.assertTrue(status)
                except AssertionError:
                    result = 'host output: {0}'.format(
                            ' '.join(JobInvocation.get_output({
                                'id': invocation_id,
                                'host': client.hostname})
                            )
                        )
                    raise AssertionError(result)
Ejemplo n.º 49
0
def test_positive_run_custom_job_template_by_ip(
        session, module_org, module_subnet):
    """Run a job template on a host connected by ip

    :id: e283ae09-8b14-4ce1-9a76-c1bbd511d58c

    :Setup: Create a working job template.

    :Steps:

        1. Set remote_execution_connect_by_ip on host to true
        2. Navigate to an individual host and click Run Job
        3. Select the job and appropriate template
        4. Run the job

    :expectedresults: Verify the job was successfully ran against the host

    :CaseLevel: System
    """
    with VirtualMachine(
            distro=DISTRO_RHEL6,
            provisioning_server=settings.compute_resources.libvirt_hostname,
            bridge=settings.vlan_networking.bridge,
    ) as client:
        client.install_katello_ca()
        client.register_contenthost(module_org.label, lce='Library')
        assert client.subscribed
        add_remote_execution_ssh_key(client.ip_addr)
        Host.update({
            'name': client.hostname,
            'subnet-id': module_subnet.id,
        })
        # connect to host by ip
        Host.set_parameter({
            'host': client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        hostname = client.hostname
        job_template_name = gen_string('alpha')
        with session:
            session.organization.select(module_org.name)
            assert session.host.search(hostname)[0]['Name'] == hostname
            session.jobtemplate.create({
                'template.name': job_template_name,
                'template.template_editor.rendering_options': 'Input',
                'template.template_editor.editor': '<%= input("command") %>',
                'job.provider_type': 'SSH',
                'inputs': [{
                    'name': 'command',
                    'required': True,
                    'input_type': 'User input',
                }],
            })
            assert session.jobtemplate.search(
                job_template_name)[0]['Name'] == job_template_name
            session.jobinvocation.run({
                'job_category': 'Miscellaneous',
                'job_template': job_template_name,
                'search_query': 'name ^ {}'.format(hostname),
                'template_content.command': 'ls',
            })
            job_description = '{0} with inputs command="ls"'.format(
                     camelize(job_template_name.lower()))
            session.jobinvocation.wait_job_invocation_state(
                entity_name=job_description,
                host_name=hostname
            )
            status = session.jobinvocation.read(
                entity_name=job_description,
                host_name=hostname
            )
            assert status['overview']['hosts_table'][0]['Status'] == 'success'
    def test_positive_run_job_template_multiple_hosts_by_ip(self):
        """Run a job template against multiple hosts by ip

        :id: c4439ec0-bb80-47f6-bc31-fa7193bfbeeb

        :Setup: Create a working job template.

        :Steps:

            1. Set remote_execution_connect_by_ip on hosts to true
            2. Navigate to the hosts page and select at least two hosts
            3. Click the "Select Action"
            4. Select the job and appropriate template
            5. Run the job

        :expectedresults: Verify the job was successfully ran against the hosts

        :CaseLevel: System
        """
        prov_server = settings.compute_resources.libvirt_hostname
        with VirtualMachine(
              distro=DISTRO_RHEL7,
              provisioning_server=prov_server,
              bridge=settings.vlan_networking.bridge,
              ) as client:
            with VirtualMachine(
                  distro=DISTRO_RHEL7,
                  provisioning_server=prov_server,
                  bridge=settings.vlan_networking.bridge,
                  ) as client2:
                for vm in client, client2:
                    vm.install_katello_ca()
                    vm.register_contenthost(
                        self.organization.label, lce='Library')
                    self.assertTrue(vm.subscribed)
                    add_remote_execution_ssh_key(vm.ip_addr)
                    Host.update({
                        'name': vm.hostname,
                        'subnet-id': self.new_sub.id,
                    })
                    # connect to host by ip
                    Host.set_parameter({
                        'host': vm.hostname,
                        'name': 'remote_execution_connect_by_ip',
                        'value': 'True',
                    })
                with Session(self) as session:
                    set_context(session, org=self.organization.name)
                    self.hosts.update_host_bulkactions(
                        [client.hostname, client2.hostname],
                        action='Schedule Remote Job',
                        parameters_list=[{'command': 'ls'}],
                    )
                    strategy, value = locators['job_invocation.status']
                    if self.job.wait_until_element(
                            (strategy, value % 'succeeded'), 240) is not None:
                        status = True
                    else:
                        status = False
                    # get job invocation id from the current url
                    invocation_id = self.browser.current_url.rsplit('/', 1)[-1]
                    try:
                        self.assertTrue(status)
                    except AssertionError:
                        result = 'host output: {0}'.format(
                                ' '.join(JobInvocation.get_output({
                                     'id': invocation_id,
                                     'host': client.hostname})
                                )
                            )
                        raise AssertionError(result)
Ejemplo n.º 51
0
    def test_positive_oscap_run_with_tailoring_file_with_ansible(self):
        """End-to-End Oscap run with tailoring files via ansible

        :id: c7ea56eb-6cf1-4e79-8d6a-fb872d1bb804

        :setup: scap content, scap policy, tailoring file, host group

        :steps:

            1. Create a valid scap content
            2. Upload a valid tailoring file
            3. Import Ansible role theforeman.foreman_scap_client
            4. Import Ansible Variables needed for the role
            5. Create a scap policy with anisble as deploy option
            6. Associate scap content with it's tailoring file
            7. Associate the policy with a hostgroup
            8. Provision a host using the hostgroup
            9. Configure REX and associate the Ansible role to created host
            10. Play roles for the host

        :expectedresults: REX job should be success and ARF report should be sent to satellite
                         reflecting the changes done via tailoring files

        :BZ: 1716307

        :CaseImportance: Critical
        """
        if settings.rhel7_repo is None:
            self.skipTest('Missing configuration for rhel7_repo')
        rhel7_repo = settings.rhel7_repo
        hgrp7_name = gen_string('alpha')
        policy_values = {
            'content': self.rhel7_content,
            'hgrp': hgrp7_name,
            'policy': gen_string('alpha'),
            'profile': OSCAP_PROFILE['security7'],
        }
        vm_values = {
            'distro': DISTRO_RHEL7,
            'hgrp': hgrp7_name,
            'rhel_repo': rhel7_repo
        }
        tailoring_file_name = gen_string('alpha')
        tailor_path = file_downloader(file_url=settings.oscap.tailoring_path,
                                      hostname=settings.server.hostname)[0]
        # Creates host_group for rhel7
        make_hostgroup({
            'content-source-id': self.proxy_id,
            'name': hgrp7_name,
            'organizations': self.config_env['org_name'],
        })

        tailor_result = make_tailoringfile({
            'name':
            tailoring_file_name,
            'scap-file':
            tailor_path,
            'organization':
            self.config_env['org_name'],
        })
        result = TailoringFiles.info({'name': tailoring_file_name})
        assert result['name'] == tailoring_file_name
        # Creates oscap_policy for rhel7.
        scap_id, scap_profile_id = self.fetch_scap_and_profile_id(
            policy_values.get('content'), policy_values.get('profile'))
        Ansible.roles_import({'proxy-id': self.proxy_id})
        Ansible.variables_import({'proxy-id': self.proxy_id})
        role_id = Ansible.roles_list({'search':
                                      'foreman_scap_client'})[0].get('id')
        make_scap_policy({
            'scap-content-id':
            scap_id,
            'hostgroups':
            policy_values.get('hgrp'),
            'deploy-by':
            'ansible',
            'name':
            policy_values.get('policy'),
            'period':
            OSCAP_PERIOD['weekly'].lower(),
            'scap-content-profile-id':
            scap_profile_id,
            'weekday':
            OSCAP_WEEKDAY['friday'].lower(),
            'tailoring-file-id':
            tailor_result['id'],
            'tailoring-file-profile-id':
            tailor_result['tailoring-file-profiles'][0]['id'],
            'organizations':
            self.config_env['org_name'],
        })
        distro_os = vm_values.get('distro')
        with VirtualMachine(distro=distro_os) as vm:
            host_name, _, host_domain = vm.hostname.partition('.')
            vm.install_katello_ca()
            vm.register_contenthost(self.config_env['org_name'],
                                    self.config_env['ak_name'].get(distro_os))
            assert vm.subscribed
            Host.set_parameter({
                'host': vm.hostname.lower(),
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            })
            vm.configure_rhel_repo(settings.rhel7_repo)
            add_remote_execution_ssh_key(vm.ip_addr)
            Host.update({
                'name': vm.hostname.lower(),
                'lifecycle-environment': self.config_env['env_name'],
                'content-view': self.config_env['cv_name'],
                'hostgroup': vm_values.get('hgrp'),
                'openscap-proxy-id': self.proxy_id,
                'organization': self.config_env['org_name'],
                'ansible-role-ids': role_id,
            })
            job_id = Host.ansible_roles_play({'name': vm.hostname.lower()
                                              })[0].get('id')
            wait_for_tasks(
                f"resource_type = JobInvocation and resource_id = {job_id} and "
                "action ~ \"hosts job\"")
            try:
                result = JobInvocation.info({'id': job_id})['success']
                assert result == '1'
            except AssertionError:
                output = ' '.join(
                    JobInvocation.get_output({
                        'id': job_id,
                        'host': vm.hostname
                    }))
                result = f'host output: {output}'
                raise AssertionError(result)
            result = vm.run(
                'cat /etc/foreman_scap_client/config.yaml | grep profile')
            assert result.return_code == 0
            # Runs the actual oscap scan on the vm/clients and
            # uploads report to Internal Capsule.
            vm.execute_foreman_scap_client()
            # Assert whether oscap reports are uploaded to
            # Satellite6.
            result = Arfreport.list({'search': f'host={vm.hostname.lower()}'})
            assert result is not None
    def test_positive_run_scheduled_job_template_by_ip(self):
        """Schedule a job to be ran against a host by ip

        :id: 4387bed9-969d-45fb-80c2-b0905bb7f1bd

        :Setup: Use pre-defined job template.

        :Steps:

            1. Set remote_execution_connect_by_ip on host to true
            2. Navigate to an individual host and click Run Job
            3. Select the job and appropriate template
            4. Select "Schedule Future Job"
            5. Enter a desired time for the job to run
            6. Click submit

        :expectedresults:

            1. Verify the job was not immediately ran
            2. Verify the job was successfully ran after the designated time

        :CaseLevel: System
        """
        with VirtualMachine(
              distro=DISTRO_RHEL7,
              provisioning_server=settings.compute_resources.libvirt_hostname,
              bridge=settings.vlan_networking.bridge,
              ) as client:
            client.install_katello_ca()
            client.register_contenthost(self.organization.label, lce='Library')
            self.assertTrue(client.subscribed)
            add_remote_execution_ssh_key(client.ip_addr)
            Host.update({
                'name': client.hostname,
                'subnet-id': self.new_sub.id,
            })
            # connect to host by ip
            Host.set_parameter({
                'host': client.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            })
            with Session(self) as session:
                set_context(session, org=self.organization.name)
                self.hosts.click(self.hosts.search(client.hostname))
                plan_time = (
                        self.get_client_datetime() + timedelta(seconds=180)
                        ).strftime("%Y-%m-%d %H:%M")
                status = self.job.run(
                    job_category='Commands',
                    job_template='Run Command - SSH Default',
                    options_list=[{'name': 'command', 'value': 'ls'}],
                    schedule='future',
                    schedule_options=[
                        {'name': 'start_at', 'value': plan_time}],
                    result='queued to start executing in 1 minute'
                )
                self.assertTrue(status)
                strategy, value = locators['job_invocation.status']
                self.job.wait_until_element_is_not_visible(
                    (strategy, value % 'queued'), 95)
                if self.job.wait_until_element(
                        (strategy, value % 'succeeded'), 180) is not None:
                    status2 = True
                else:
                    status2 = False
                # get job invocation id from the current url
                invocation_id = self.browser.current_url.rsplit('/', 1)[-1]
                try:
                    self.assertTrue(status2)
                except AssertionError:
                    result = 'host output: {0}'.format(
                            ' '.join(JobInvocation.get_output({
                                'id': invocation_id,
                                'host': client.hostname})
                            )
                        )
                    raise AssertionError(result)
Ejemplo n.º 53
0
def test_positive_run_custom_job_template_by_ip(session, module_org,
                                                module_subnet):
    """Run a job template on a host connected by ip

    :id: e283ae09-8b14-4ce1-9a76-c1bbd511d58c

    :Setup: Create a working job template.

    :Steps:

        1. Set remote_execution_connect_by_ip on host to true
        2. Navigate to an individual host and click Run Job
        3. Select the job and appropriate template
        4. Run the job

    :expectedresults: Verify the job was successfully ran against the host

    :CaseLevel: System
    """
    with VirtualMachine(
            distro=DISTRO_RHEL6,
            provisioning_server=settings.compute_resources.libvirt_hostname,
            bridge=settings.vlan_networking.bridge,
    ) as client:
        client.install_katello_ca()
        client.register_contenthost(module_org.label, lce='Library')
        assert client.subscribed
        add_remote_execution_ssh_key(client.ip_addr)
        Host.update({
            'name': client.hostname,
            'subnet-id': module_subnet.id,
        })
        # connect to host by ip
        Host.set_parameter({
            'host': client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        hostname = client.hostname
        job_template_name = gen_string('alpha')
        with session:
            session.organization.select(module_org.name)
            assert session.host.search(hostname)[0]['Name'] == hostname
            session.jobtemplate.create({
                'template.name':
                job_template_name,
                'template.template_editor.rendering_options':
                'Input',
                'template.template_editor.editor':
                '<%= input("command") %>',
                'job.provider_type':
                'SSH',
                'inputs': [{
                    'name': 'command',
                    'required': True,
                    'input_type': 'User input',
                }],
            })
            assert session.jobtemplate.search(
                job_template_name)[0]['Name'] == job_template_name
            session.jobinvocation.run({
                'job_category':
                'Miscellaneous',
                'job_template':
                job_template_name,
                'search_query':
                'name ^ {}'.format(hostname),
                'template_content.command':
                'ls',
            })
            job_description = '{0} with inputs command="ls"'.format(
                camelize(job_template_name.lower()))
            session.jobinvocation.wait_job_invocation_state(
                entity_name=job_description, host_name=hostname)
            status = session.jobinvocation.read(entity_name=job_description,
                                                host_name=hostname)
            assert status['overview']['hosts_table'][0]['Status'] == 'success'
Ejemplo n.º 54
0
def test_positive_oscap_run_via_ansible_bz_1814988(module_org, default_proxy,
                                                   content_view,
                                                   lifecycle_env):
    """End-to-End Oscap run via ansible

    :id: 375f8f08-9299-4d16-91f9-9426eeecb9c5

    :parametrized: yes

    :customerscenario: true

    :setup: scap content, scap policy, host group

    :steps:

        1. Create a valid scap content
        2. Import Ansible role theforeman.foreman_scap_client
        3. Import Ansible Variables needed for the role
        4. Create a scap policy with anisble as deploy option
        5. Associate the policy with a hostgroup
        6. Provision a host using the hostgroup
        7. Harden the host by remediating it with DISA STIG security policy
        8. Configure REX and associate the Ansible role to created host
        9. Play roles for the host

    :expectedresults: REX job should be success and ARF report should be sent to satellite

    :BZ: 1814988

    :CaseImportance: Critical
    """
    hgrp_name = gen_string('alpha')
    policy_name = gen_string('alpha')
    # Creates host_group for rhel7
    make_hostgroup({
        'content-source-id': default_proxy,
        'name': hgrp_name,
        'organizations': module_org.name,
    })
    # Creates oscap_policy.
    scap_id, scap_profile_id = fetch_scap_and_profile_id(
        OSCAP_DEFAULT_CONTENT['rhel7_content'], OSCAP_PROFILE['dsrhel7'])
    Ansible.roles_import({'proxy-id': default_proxy})
    Ansible.variables_import({'proxy-id': default_proxy})
    role_id = Ansible.roles_list({'search':
                                  'foreman_scap_client'})[0].get('id')
    make_scap_policy({
        'scap-content-id': scap_id,
        'hostgroups': hgrp_name,
        'deploy-by': 'ansible',
        'name': policy_name,
        'period': OSCAP_PERIOD['weekly'].lower(),
        'scap-content-profile-id': scap_profile_id,
        'weekday': OSCAP_WEEKDAY['friday'].lower(),
        'organizations': module_org.name,
    })
    with VMBroker(nick=DISTRO_RHEL7, host_classes={'host': ContentHost}) as vm:
        host_name, _, host_domain = vm.hostname.partition('.')
        vm.install_katello_ca()
        vm.register_contenthost(module_org.name, ak_name[DISTRO_RHEL7])
        assert vm.subscribed
        Host.set_parameter({
            'host': vm.hostname.lower(),
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        vm.configure_rhel_repo(settings.repos.rhel7_repo)
        # Harden the rhel7 client with DISA STIG security policy
        vm.run('yum install -y scap-security-guide')
        vm.run(
            'oscap xccdf eval --remediate --profile xccdf_org.ssgproject.content_profile_stig '
            '--fetch-remote-resources --results-arf results.xml '
            '/usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml', )
        add_remote_execution_ssh_key(vm.ip_addr)
        Host.update({
            'name': vm.hostname.lower(),
            'lifecycle-environment': lifecycle_env.name,
            'content-view': content_view.name,
            'hostgroup': hgrp_name,
            'openscap-proxy-id': default_proxy,
            'organization': module_org.name,
            'ansible-role-ids': role_id,
        })
        job_id = Host.ansible_roles_play({'name':
                                          vm.hostname.lower()})[0].get('id')
        wait_for_tasks(
            f'resource_type = JobInvocation and resource_id = {job_id} and action ~ "hosts job"'
        )
        try:
            result = JobInvocation.info({'id': job_id})['success']
            assert result == '1'
        except AssertionError:
            output = ' '.join(
                JobInvocation.get_output({
                    'id': job_id,
                    'host': vm.hostname
                }))
            result = f'host output: {output}'
            raise AssertionError(result)
        result = vm.run(
            'cat /etc/foreman_scap_client/config.yaml | grep profile')
        assert result.status == 0
        # Runs the actual oscap scan on the vm/clients and
        # uploads report to Internal Capsule.
        vm.execute_foreman_scap_client()
        # Assert whether oscap reports are uploaded to
        # Satellite6.
        result = Arfreport.list({'search': f'host={vm.hostname.lower()}'})
        assert result is not None