def setUpClass(cls):
     """Get host name, scripts, and create working directory."""
     super(KatelloCertsCheckTestCase, cls).setUpClass()
     _, cls.sat6_hostname = os.path.split(settings.server.hostname)
     cls.capsule_hostname = 'capsule.example.com'
     cls.key_file_name = '{0}/{0}.key'.format(cls.sat6_hostname)
     cls.cert_file_name = '{0}/{0}.crt'.format(cls.sat6_hostname)
     cls.ca_bundle_file_name = 'cacert.crt'
     cls.SUCCESS_MSG = "Validation succeeded"
     # Need a subdirectory under ssl-build with same name as Capsule name
     with get_connection(timeout=100) as connection:
         connection.run('mkdir ssl-build/{0}'.format(cls.capsule_hostname))
         # Ignore creation error, but assert directory exists
         assert connection.run('test -e ssl-build/{0}'.format(cls.capsule_hostname))
     upload_file(
         local_file=get_data_file('generate-ca.sh'), remote_file="generate-ca.sh",
     )
     upload_file(
         local_file=get_data_file('generate-crt.sh'), remote_file="generate-crt.sh",
     )
     upload_file(local_file=get_data_file('openssl.cnf'), remote_file="openssl.cnf")
     # create the CA cert.
     with get_connection(timeout=300) as connection:
         result = connection.run('echo 100001 > serial')
         result = connection.run("bash generate-ca.sh")
         assert result.return_code == 0
     # create the Satellite's cert
     with get_connection(timeout=300) as connection:
         result = connection.run(
             "yes | bash {} {}".format('generate-crt.sh', cls.sat6_hostname)
         )
         assert result.return_code == 0
 def cert_setup(self, cert_data):
     # Need a subdirectory under ssl-build with same name as Capsule name
     with get_connection(timeout=100) as connection:
         connection.run('mkdir ssl-build/{0}'.format(
             cert_data['capsule_hostname']))
         # Ignore creation error, but assert directory exists
         assert connection.run('test -e ssl-build/{0}'.format(
             cert_data['capsule_hostname']))
     upload_file(
         local_file=get_data_file('generate-ca.sh'),
         remote_file="generate-ca.sh",
     )
     upload_file(
         local_file=get_data_file('generate-crt.sh'),
         remote_file="generate-crt.sh",
     )
     upload_file(local_file=get_data_file('openssl.cnf'),
                 remote_file="openssl.cnf")
     # create the CA cert.
     with get_connection(timeout=300) as connection:
         result = connection.run('echo 100001 > serial')
         result = connection.run("bash generate-ca.sh")
         assert result.return_code == 0
     # create the Satellite's cert
     with get_connection(timeout=300) as connection:
         result = connection.run("yes | bash {} {}".format(
             'generate-crt.sh', cert_data['sat6_hostname']))
         assert result.return_code == 0
    def test_positive_update_katello_certs(self, cert_setup, cert_data,
                                           certs_cleanup):
        """Update certificates on a currently running satellite instance.

        :id: 0ddf6954-dc83-435e-b156-b567b877c2a5

        :steps:

            1. Use Jenkins provided custom certs
            2. Assert hammer ping reports running Satellite
            3. Update satellite with custom certs
            4. Assert output does not report SSL certificate error
            5. Assert all services are running


        :expectedresults: Katello-certs should be updated.

        :CaseAutomation: Automated
        """
        try:
            with get_connection(timeout=600) as connection:
                # Check for hammer ping SSL cert error
                result = connection.run('hammer ping')
                assert result.return_code == 0, 'Hammer Ping fail'
                result = connection.run(
                    'satellite-installer --scenario satellite '
                    '--certs-server-cert {} '
                    '--certs-server-key {} '
                    '--certs-server-ca-cert {} '
                    '--certs-update-server --certs-update-server-ca'.format(
                        cert_data['cert_file_name'],
                        cert_data['key_file_name'],
                        cert_data['ca_bundle_file_name'],
                    ),
                    timeout=500,
                )
                # assert no hammer ping SSL cert error
                result = connection.run('hammer ping')
                assert 'SSL certificate verification failed' not in result.stdout
                assert 'ok' in result.stdout[1]
                # assert all services are running
                result = connection.run(
                    'foreman-maintain health check --label services-up -y')
                assert result.return_code == 0, 'Not all services are running'
        finally:
            # revert to original certs
            with get_connection(timeout=600) as connection:
                result = connection.run(
                    'satellite-installer --scenario satellite --certs-reset',
                    timeout=500)
                # Check for hammer ping SSL cert error
                result = connection.run('hammer ping')
                assert result.return_code == 0, 'Hammer Ping fail'
                # assert all services are running
                result = connection.run(
                    'foreman-maintain health check --label services-up -y')
                assert result.return_code == 0, 'Not all services are running'
示例#4
0
    def test_negative_rename_sat_to_invalid_hostname(self):
        """change to invalid hostname on Satellite server

        :id: 385fad60-3990-42e0-9436-4ebb71918125

        :bz: 1485884

        :expectedresults: script terminates with a message, hostname
            is not changed

        :caseautomation: automated
        """
        with get_connection() as connection:
            hostname = gen_string('alpha')
            result = connection.run(
                'katello-change-hostname -y \
                        {0} -u {1} -p {2}'.format(
                    hostname, self.username, self.password),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 1)
            self.assertIn(BAD_HN_MSG.format(hostname), result.stdout)
            # assert no changes were made
            result = connection.run('hostname')
            self.assertEqual(self.hostname, result.stdout[0],
                             "Invalid hostame assigned")
示例#5
0
def test_positive_logging_from_foreman_proxy():
    """Check PUT to Smart Proxy API to refresh the features is logged and has request ID.

    :id: 0ecd8406-6cf1-4520-b8b6-8a164a1e60c2

    :expectedresults: line of log with PUT has request ID

    :CaseImportance: Medium
    """

    PUT_line_found = False
    request_id = None
    source_log_1 = '/var/log/foreman/production.log'
    test_logfile_1 = '/var/tmp/logfile_1_from_proxy'
    source_log_2 = '/var/log/foreman-proxy/proxy.log'
    test_logfile_2 = '/var/tmp/logfile_2_from_proxy'
    with ssh.get_connection() as connection:
        # get the number of lines in the source logs before the test
        line_count_start_1 = line_count(source_log_1, connection)
        line_count_start_2 = line_count(source_log_2, connection)
        # hammer command for this test
        result = connection.run('hammer proxy refresh-features --id 1')
        assert result.return_code == 0, "BASH command error?"
        # get the number of lines in the source logs after the test
        line_count_end_1 = line_count(source_log_1, connection)
        line_count_end_2 = line_count(source_log_2, connection)
        # get the log lines of interest, put them in test_logfile_1
        cut_lines(line_count_start_1, line_count_end_1, source_log_1,
                  test_logfile_1, connection)
        # get the log lines of interest, put them in test_logfile_2
        cut_lines(line_count_start_2, line_count_end_2, source_log_2,
                  test_logfile_2, connection)
    # use same location on remote and local for log file extract
    ssh.download_file(test_logfile_1)
    # use same location on remote and local for log file extract
    ssh.download_file(test_logfile_2)
    # search the log file extract for the line with PUT to host API
    with open(test_logfile_1) as logfile:
        for line in logfile:
            if re.search(r'Started PUT \"\/api\/smart_proxies\/1\/refresh',
                         line):
                logger.info('Found the line with PUT to foreman proxy API')
                PUT_line_found = True
                # Confirm the request ID was logged in the line with PUT
                match = re.search(r'\[I\|app\|\w{8}\]', line)
                assert match, "Request ID not found"
                logger.info("Request ID found for logging from foreman proxy")
                p = re.compile(r"\w{8}")
                result = p.search(line)
                request_id = result.group(0)
                break
    assert PUT_line_found, "The PUT command to refresh proxies was not found in logs."
    # search the local copy of proxy.log file for the same request ID
    with open(test_logfile_2) as logfile:
        for line in logfile:
            # Confirm request ID was logged in proxy.log
            match = line.find(request_id)
            assert match, "Request ID not found in proxy.log"
            logger.info("Request ID also found in proxy.log")
            break
示例#6
0
    def test_get_connection_key(self, settings):
        """Test method ``get_connection`` using key file to connect to the
        server.

        Mock up ``paramiko.SSHClient`` (by overriding method
        ``_call_paramiko_sshclient``) before calling ``get_connection``.
        Assert that certain parameters are passed to the (mock)
        ``paramiko.SSHClient`` object, and that certain methods on that object
        are called.
        """
        ssh._call_paramiko_sshclient = MockSSHClient  # pylint:disable=W0212

        key_filename = os.path.join(
            os.path.abspath(__name__), 'data', 'test_dsa.key'
        )
        settings.server.hostname = 'example.com'
        settings.server.ssh_username = '******'
        settings.server.ssh_key = key_filename
        with ssh.get_connection() as connection:  # pylint:disable=W0212
            self.assertEqual(connection.set_missing_host_key_policy_, 1)
            self.assertEqual(connection.connect_, 1)
            self.assertEqual(connection.close_, 0)
            self.assertEqual(connection.hostname, 'example.com')
            self.assertEqual(connection.username, 'nobody')
            self.assertEqual(connection.key_filename, key_filename)
        self.assertEqual(connection.set_missing_host_key_policy_, 1)
        self.assertEqual(connection.connect_, 1)
        self.assertEqual(connection.close_, 1)
示例#7
0
    def test_get_connection_pass(self, settings):
        """Test method ``get_connection`` using password of user to connect to
        the server

        Mock up ``paramiko.SSHClient`` (by overriding method
        ``_call_paramiko_sshclient``) before calling ``get_connection``.
        Assert that certain parameters are passed to the (mock)
        ``paramiko.SSHClient`` object, and that certain methods on that object
        are called.
        """
        ssh._call_paramiko_sshclient = MockSSHClient
        settings.server.hostname = 'example.com'
        settings.server.ssh_username = '******'
        settings.server.ssh_key = None
        settings.server.ssh_password = '******'
        settings.server.ssh_key_string = None
        settings.server.ssh_client.command_timeout = 300
        settings.server.ssh_client.connection_timeout = 10
        with ssh.get_connection() as connection:
            assert connection.set_missing_host_key_policy_ == 1
            assert connection.connect_ == 1
            assert connection.close_ == 0
            assert connection.hostname == 'example.com'
            assert connection.username == 'nobody'
            assert connection.password == 'test_password'
            assert connection.key_filename is None
            assert connection.pkey is None
        assert connection.set_missing_host_key_policy_ == 1
        assert connection.connect_ == 1
        assert connection.close_ == 1
示例#8
0
    def test_positive_online_backup_with_directory_created(self):
        """katello-backup --online with non-existing directory


        :id: 946991ad-125a-4f24-a33e-ea27fce38eda

        :Steps:

            1. Ensure the directory /tmp/xyz does not exist.
            2. Run ``katello-backup --online-backup /tmp/xyz``

        :expectedresults: ``/tmp/xyz`` is created and the backup is saved to it
            containing all the default files needed to restore. Services
            keep running.

        """
        with get_connection() as connection:
            dir_name = gen_string('alpha')
            tmp_directory_cleanup(connection, dir_name)
            connection.run('katello-service start')
            result = connection.run(
                'katello-backup /tmp/{0} --online-backup'.format(dir_name),
                output_format='plain')
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls -a /tmp/{0}/katello-backup*'.format(dir_name), )
            # backup could have more files than the default so it is superset
            self.assertTrue(
                set(files.stdout).issuperset(set(HOT_BACKUP_FILES)))
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#9
0
    def test_negative_rename_sat_to_invalid_hostname(self):
        """change to invalid hostname on Satellite server

        :id: 385fad60-3990-42e0-9436-4ebb71918125

        :BZ: 1485884

        :expectedresults: script terminates with a message, hostname
            is not changed

        :CaseAutomation: automated
        """
        with get_connection() as connection:
            original_name = connection.run('hostname').stdout[0]
            hostname = gen_string('alpha')
            result = connection.run(
                'satellite-change-hostname -y \
                        {0} -u {1} -p {2}'.format(hostname, self.username,
                                                  self.password),
                output_format='plain',
            )
            self.assertEqual(result.return_code, 1)
            self.assertIn(BAD_HN_MSG.format(hostname), result.stdout)
            # assert no changes were made
            result = connection.run('hostname')
            self.assertEqual(original_name, result.stdout[0],
                             "Invalid hostame assigned")
示例#10
0
def default_url_on_new_port(oldport, newport):
    """Creates context where the default capsule is forwarded on a new port

    :param int oldport: Port to be forwarded.
    :param int newport: New port to be used to forward `oldport`.

    :return: A string containing the new capsule URL with port.
    :rtype: str

    """
    domain = settings.server.hostname

    with ssh.get_connection() as connection:
        command = f'ncat -kl -p {newport} -c "ncat {domain} {oldport}"'
        logger.debug(f'Creating tunnel: {command}')
        transport = connection.get_transport()
        channel = transport.open_session()
        channel.get_pty()
        channel.exec_command(command)
        # if exit_status appears until command_timeout, throw error
        if channel.exit_status_ready():
            if channel.recv_exit_status() != 0:
                stderr = ''
                while channel.recv_stderr_ready():
                    stderr += channel.recv_stderr(1)
                logger.debug(f'Tunnel failed: {stderr}')
                # Something failed, so raise an exception.
                raise CapsuleTunnelError(stderr)
        yield f'https://{domain}:{newport}'
示例#11
0
    def test_get_connection_pass(self, settings):
        """Test method ``get_connection`` using password of user to connect to
        the server

        Mock up ``paramiko.SSHClient`` (by overriding method
        ``_call_paramiko_sshclient``) before calling ``get_connection``.
        Assert that certain parameters are passed to the (mock)
        ``paramiko.SSHClient`` object, and that certain methods on that object
        are called.
        """
        ssh._call_paramiko_sshclient = MockSSHClient  # pylint:disable=W0212
        settings.server.hostname = 'example.com'
        settings.server.ssh_username = '******'
        settings.server.ssh_key = None
        settings.server.ssh_password = '******'
        with ssh.get_connection() as connection:  # pylint:disable=W0212
            self.assertEqual(connection.set_missing_host_key_policy_, 1)
            self.assertEqual(connection.connect_, 1)
            self.assertEqual(connection.close_, 0)
            self.assertEqual(connection.hostname, 'example.com')
            self.assertEqual(connection.username, 'nobody')
            self.assertEqual(connection.password, 'test_password')
        self.assertEqual(connection.set_missing_host_key_policy_, 1)
        self.assertEqual(connection.connect_, 1)
        self.assertEqual(connection.close_, 1)
示例#12
0
    def test_positive_online_backup_with_directory_created(self):
        """katello-backup --online with non-existing directory


        :id: 946991ad-125a-4f24-a33e-ea27fce38eda

        :Steps:

            1. Ensure the directory /tmp/xyz does not exist.
            2. Run ``katello-backup --online-backup /tmp/xyz``

        :expectedresults: ``/tmp/xyz`` is created and the backup is saved to it
            containing all the default files needed to restore. Services
            keep running.

        """
        with get_connection() as connection:
            dir_name = gen_string('alpha')
            tmp_directory_cleanup(connection, dir_name)
            connection.run('katello-service start')
            result = connection.run(
                'katello-backup -y /tmp/{0} --online-backup'.format(dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls -a /tmp/{0}/katello-backup*'.format(dir_name),
            )
            # backup could have more files than the default so it is superset
            self.assertTrue(set(files.stdout).issuperset(
                set(HOT_BACKUP_FILES)))
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#13
0
    def test_positive_create_ssh_key_super_admin_from_file(self):
        """SSH Key can be added to Super Admin user from file

        :id: b865d0ae-6317-475c-a6da-600615b71eeb

        :expectedresults: SSH Key should be added to Super Admin user
                          from ssh pub file

        :CaseImportance: Critical
        """
        ssh_name = gen_string('alpha')
        ssh_key = self.gen_ssh_rsakey()
        with get_connection() as connection:
            result = connection.run(
                '''echo '{}' > test_key.pub'''.format(ssh_key))
        self.assertEqual(result.return_code, 0, 'key file not created')
        User.ssh_keys_add({
            'user': '******',
            'key-file': 'test_key.pub',
            'name': ssh_name
        })
        result = User.ssh_keys_list({'user': '******'})
        self.assertIn(ssh_name, [i['name'] for i in result])
        result = User.ssh_keys_info({'user': '******', 'name': ssh_name})
        self.assertEqual(ssh_key, result[0]['public-key'])
示例#14
0
    def test_positive_online_backup_with_existing_directory(self):
        """katello-backup --online-backup with existing directory

        :id: 3f8285d5-c68b-4d84-8568-bcd7e4f7f19e

        :Steps:

            1. Create a directory (ie /tmp/xyz)
            2. Run ``katello-backup --online-backup /tmp/xyz``

        :expectedresults: The backup is successfully created in existing folder
            and contains all the default files needed to restore. Services keep
            running.

        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            connection.run('katello-service start')
            result = connection.run(
                'katello-backup /tmp/{0} --online-backup'.format(dir_name),
                output_format='plain')
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls -a /tmp/{0}/katello-backup*'.format(dir_name), )
            # backup could have more files than the default so it is superset
            self.assertTrue(
                set(files.stdout).issuperset(set(HOT_BACKUP_FILES)))
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#15
0
    def test_get_connection_key_string(self, settings):
        """Test method ``get_connection`` using key file to connect to the
        server.

        Mock up ``paramiko.SSHClient`` (by overriding method
        ``_call_paramiko_sshclient``) before calling ``get_connection``.
        Assert that certain parameters are passed to the (mock)
        ``paramiko.SSHClient`` object, and that certain methods on that object
        are called.
        """
        ssh._call_paramiko_sshclient = MockSSHClient
        key_string = StringIO('')
        rsa_key = paramiko.rsakey.RSAKey.generate(512)
        rsa_key.write_private_key(key_string)
        settings.server.hostname = 'example.com'
        settings.server.ssh_username = '******'
        settings.server.ssh_password = None
        settings.server.ssh_key = None
        settings.server.ssh_key_string = key_string.getvalue(
        )  # resolve StringIO stream
        settings.server.ssh_client.command_timeout = 300
        settings.server.ssh_client.connection_timeout = 10
        with ssh.get_connection() as connection:
            assert connection.set_missing_host_key_policy_ == 1
            assert connection.connect_ == 1
            assert connection.close_ == 0
            assert connection.hostname == 'example.com'
            assert connection.username == 'nobody'
            assert connection.password is None
            assert connection.key_filename is None
            assert connection.pkey == rsa_key  # PKey.__cmp__
        assert connection.set_missing_host_key_policy_ == 1
        assert connection.connect_ == 1
        assert connection.close_ == 1
示例#16
0
    def test_katello_certs_check_output_invalid_input(
        self, generate_certs, error, cert_file, key_file, ca_file, certs_cleanup
    ):
        """Validate that katello-certs-check raise the correct errors for invalid
         inputs

        :id: 37742f5e-598a-11eb-a349-d46d6dd3b5b2

        :steps:

            1. Get invalid certs from generate_certs
            2. Run katello-certs-check with the required valid arguments
               katello-certs-check -c CERT_FILE -k KEY_FILE -r REQ_FILE
               -b CA_BUNDLE_FILE
            3. Assert the output has correct error with message

        :expectedresults: Katello-certs-check should raise error when it receives the invalid
         inputs.
        """
        with get_connection() as connection:
            certs_check_result = connection.run(
                f'katello-certs-check -c {cert_file} -k {key_file} -b {ca_file}',
                output_format='plain',
            )
            for result in certs_check_result.stdout.split("\n\n"):
                if error['check'] in result:
                    assert '[FAIL]' in result
                    assert (
                        error['message']
                        in f'{certs_check_result.stdout} {certs_check_result.stderr}'
                    )
                    break
            else:
                pytest.fail('Failed to receive the error for invalid katello-cert-check')
示例#17
0
    def test_positive_skip_pulp(self):
        """Katello-backup with --skip-pulp option should not create pulp
        files in destination.

        :id: 0f0c1915-dd07-4571-9b05-e0778efc85b2

        :Steps:

            1. Run backup with --skip-pulp option to /tmp/bck-no-pulp
            2. List contents of the destination

        :expectedresults: ``/tmp/bck-no-pulp`` is created and pulp related
            files are not present.
        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            result = connection.run(
                'katello-backup /tmp/{0} --online-backup '
                '--skip-pulp'.format(dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run('ls /tmp/{0}'.format(dir_name), 'list')
            self.assertNotIn(u'pulp_data.tar', files.stdout)
            self.assertNotIn(u'pulp.snar', files.stdout)
示例#18
0
def cut_lines(start_line, end_line, source_file, out_file, connection=None):
    """Given start and end line numbers, cut lines from source file
    and put them in out file."""
    connection = connection or ssh.get_connection()
    result = connection.run('sed -n "{0},{1} p" {2} < {2} > {3}'.format(
        start_line, end_line, source_file, out_file))
    return result
示例#19
0
    def test_negative_rename_sat_wrong_passwd(self):
        """change hostname with wrong password on Satellite server

        :id: e6d84c5b-4bb1-4400-8022-d01cc9216936

        :BZ: 1485884, 1897360, 1925616

        :expectedresults: script terminates with a message, hostname
            is not changed

        :CaseAutomation: Automated
        """
        username = settings.server.admin_username
        with get_connection() as connection:
            original_name = connection.run('hostname').stdout[0]
            new_hostname = f'new-{original_name}'
            password = gen_string('alpha')
            result = connection.run(
                'satellite-change-hostname -y \
                        {} -u {} -p {}'.format(new_hostname, username,
                                               password),
                output_format='plain',
            )
            assert result.return_code == 1
            assert BAD_CREDS_MSG in result.stderr
示例#20
0
    def test_positive_online_relative_path(self):
        """run katello-backup --online-backup with relative path

        :id: 3b5d8ac3-1ba1-4e3b-89f4-be950c8eef86

        :Steps:

            1. Run online backup to relative path
            2. List contents of the destination

        :bz: 1444069

        :expectedresults:  backup is successful, foreman.dump and
            candlepin.dump are created

        """
        with get_connection() as connection:
            connection.run('katello-service start')
            dir_name = gen_string('alpha')
            result = connection.run('katello-backup {0} --online-backup '
                                    '--skip-pulp-content'.format(dir_name),
                                    output_format='plain')
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls -a /tmp/{0}/katello-backup*'.format(dir_name), 'list')
            self.assertIn(u'candlepin.dump', files.stdout)
            self.assertIn(u'foreman.dump', files.stdout)
            self.assertNotIn(u'pulp_data.tar', files.stdout)
            # check if services are running correctly
            self.check_services_status()
            connection.run('rm -rf {0}'.format(dir_name))
示例#21
0
    def test_positive_online_skip_pulp(self):
        """Katello-backup --online-backup with --skip-pulp-content
        option should not create pulp files in destination.

        :id: 0f0c1915-dd07-4571-9b05-e0778efc85b2

        :Steps:

            1. Run online backup with --skip-pulp-content option
            2. List contents of the destination

        :expectedresults: ``/tmp/bck-no-pulp`` is created and pulp
            related files are not present. Services keep running.

        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            connection.run('katello-service start')
            result = connection.run('katello-backup /tmp/{0} --online-backup '
                                    '--skip-pulp-content'.format(dir_name),
                                    output_format='plain')
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls -a /tmp/{0}/katello-backup*'.format(dir_name), 'list')
            self.assertNotIn(u'pulp_data.tar', files.stdout)
            self.assertNotIn(u'.pulp.snar', files.stdout)
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#22
0
    def test_positive_backup_with_existing_directory(self):
        """katello-backup with existing directory

        :id: 3f8285d5-c68b-4d84-8568-bcd7e4f7f19e

        :Steps:

            1. Create a directory (ie /tmp/xyz)
            2. Run ``katello-backup /tmp/xyz``

        :expectedresults: The backup is successfully created in existing folder
            and contains all the default files needed to restore.
        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            result = connection.run(
                'katello-backup /tmp/{0} --online-backup'.format(dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls /tmp/{0}'.format(dir_name),
                output_format='list'
            )
            # backup could have more files than the default so it is superset
            self.assertTrue(set(files.stdout).issuperset(set(BACKUP_FILES)))
示例#23
0
    def test_positive_logical_db_backup(self):
        """Katello-backup with --logical-db-backup option should
        dump full database schema during offline backup

        :id: a1386cfa-cd7e-4f22-9ebc-7c908d514ad4

        :Steps:

            1. Run online backup with --logical-db-backup option
            2. List contents of the destination

        :expectedresults: Backup is created and additional files are
            not present. Services are started back again.

        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            result = connection.run('katello-backup /tmp/{0} '
                                    '--logical-db-backup'.format(dir_name),
                                    output_format='plain')
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls -a /tmp/{0}/katello-backup*'.format(dir_name), 'list')
            self.assertTrue(set(files.stdout).issuperset(set(BACKUP_FILES)))
            self.assertIn(u'candlepin.dump', files.stdout)
            self.assertIn(u'foreman.dump', files.stdout)
            self.assertIn(u'mongo_dump', files.stdout)
            self.assertIn(u'pg_globals.dump', files.stdout)
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#24
0
    def test_positive_online_backup_with_existing_directory(self):
        """katello-backup --online-backup with existing directory

        :id: 3f8285d5-c68b-4d84-8568-bcd7e4f7f19e

        :Steps:

            1. Create a directory (ie /tmp/xyz)
            2. Run ``katello-backup --online-backup /tmp/xyz``

        :expectedresults: The backup is successfully created in existing folder
            and contains all the default files needed to restore. Services keep
            running.

        :caseautomation: automated
        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            connection.run('katello-service start')
            result = connection.run(
                'satellite-backup -y /tmp/{0} --online-backup'.format(
                    dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls -a /tmp/{0}/satellite-backup*'.format(dir_name),
            )
            # backup could have more files than the default so it is superset
            self.assertTrue(set(files.stdout).issuperset(
                set(HOT_BACKUP_FILES)))
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#25
0
    def test_negative_rename_sat_to_invalid_hostname(self):
        """change to invalid hostname on Satellite server

        :id: 385fad60-3990-42e0-9436-4ebb71918125

        :BZ: 1485884

        :expectedresults: script terminates with a message, hostname
            is not changed

        :CaseAutomation: Automated
        """
        username = settings.server.admin_username
        password = settings.server.admin_password
        with get_connection() as connection:
            original_name = connection.run('hostname').stdout[0]
            hostname = gen_string('alpha')
            result = connection.run(
                'satellite-change-hostname -y \
                        {} -u {} -p {}'.format(hostname, username, password),
                output_format='plain',
            )
            assert result.return_code == 1
            assert BAD_HN_MSG.format(hostname) in result.stdout
            # assert no changes were made
            result = connection.run('hostname')
            assert original_name == result.stdout[
                0], "Invalid hostame assigned"
    def test_positive_validate_katello_certs_check_output(self):
        """Validate that katello-certs-check generate correct output

        :id: 4c9e4c6e-8d8e-4953-87a1-09cb55df3adf

        :steps:

            1. Generate custom certs
            2. Run katello-certs-check with the required valid arguments
               katello-certs-check -c CERT_FILE -k KEY_FILE -r REQ_FILE
               -b CA_BUNDLE_FILE
            3. Assert the output has correct commands with options

        :expectedresults: Katello-certs-check should generate correct commands
         with options.
        """
        with get_connection() as connection:
            result = connection.run(
                'katello-certs-check -c /tmp/{0} -k /tmp/{1} '
                '-b /tmp/{2}'.format(
                    self.cert_file_name,
                    self.key_file_name,
                    self.ca_bundle_file_name
                ),
                output_format='plain'
            )
            self.validate_output(result)
示例#27
0
    def test_positive_skip_pulp(self):
        """Katello-backup with --skip-pulp-content option should not
        create pulp files in destination.

        :id: f0fa2daa-209e-4d46-9b67-3041768a2a77

        :Steps:

            1. Run online backup with --skip-pulp-content option
            2. List contents of the destination

        :expectedresults: Backup is created and pulp related
            files are not present. Services are started back again.

        :caseautomation: automated
        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            result = connection.run(
                'satellite-backup -y /tmp/{0} '
                '--skip-pulp-content'.format(dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                    'ls -a /tmp/{0}/satellite-backup*'.format(dir_name),
                    'list'
                    )
            self.assertNotIn(u'pulp_data.tar', files.stdout)
            self.assertNotIn(u'.pulp.snar', files.stdout)
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#28
0
    def test_get_connection_key(self, settings):
        """Test method ``get_connection`` using key file to connect to the
        server.

        Mock up ``paramiko.SSHClient`` (by overriding method
        ``_call_paramiko_sshclient``) before calling ``get_connection``.
        Assert that certain parameters are passed to the (mock)
        ``paramiko.SSHClient`` object, and that certain methods on that object
        are called.
        """
        ssh._call_paramiko_sshclient = MockSSHClient

        key_filename = os.path.join(os.path.abspath(__name__), 'data',
                                    'test_dsa.key')
        settings.server.hostname = 'example.com'
        settings.server.ssh_username = '******'
        settings.server.ssh_key = key_filename
        settings.ssh_client.command_timeout = 300
        settings.ssh_client.connection_timeout = 10
        with ssh.get_connection() as connection:
            assert connection.set_missing_host_key_policy_ == 1
            assert connection.connect_ == 1
            assert connection.close_ == 0
            assert connection.hostname == 'example.com'
            assert connection.username == 'nobody'
            assert connection.key_filename == key_filename
        assert connection.set_missing_host_key_policy_ == 1
        assert connection.connect_ == 1
        assert connection.close_ == 1
示例#29
0
def default_url_on_new_port(oldport, newport):
    """Creates context where the default capsule is forwarded on a new port

    :param int oldport: Port to be forwarded.
    :param int newport: New port to be used to forward `oldport`.

    :return: A string containing the new capsule URL with port.
    :rtype: str

    """
    logger = logging.getLogger('robottelo')
    domain = settings.server.hostname

    with ssh.get_connection() as connection:
        command = (u'ncat -kl -p {0} -c "ncat {1} {2}"').format(
            newport, domain, oldport)
        logger.debug('Creating tunnel: {0}'.format(command))
        transport = connection.get_transport()
        channel = transport.open_session()
        channel.get_pty()
        channel.exec_command(command)
        # if exit_status appears until command_timeout, throw error
        if channel.exit_status_ready():
            if channel.recv_exit_status() != 0:
                stderr = u''
                while channel.recv_stderr_ready():
                    stderr += channel.recv_stderr(1)
                logger.debug('Tunnel failed: {0}'.format(stderr))
                # Something failed, so raise an exception.
                raise CapsuleTunnelError(stderr)
        yield 'https://{0}:{1}'.format(domain, newport)
示例#30
0
    def test_positive_directory_created(self):
        """katello-backup with non-existing directory


        :id: 946991ad-125a-4f24-a33e-ea27fce38eda

        :Steps:

            1. Ensure the directory /tmp/xyz does not exist.
            2. Run ``katello /tmp/xyz``

        :expectedresults: ``/tmp/xyz`` is created and the backup is saved to it
            containing all the default files needed to restore.
        """
        with get_connection() as connection:
            dir_name = gen_string('alpha')
            connection.run('rm -rf /tmp/{0}'.format(dir_name))
            result = connection.run(
                'katello-backup /tmp/{0} --online-backup'.format(dir_name),
                output_format='plain')
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run('ls /tmp/{0}'.format(dir_name),
                                   output_format='list')
            # backup could have more files than the default so it is superset
            self.assertTrue(set(files.stdout).issuperset(set(BACKUP_FILES)))
示例#31
0
    def test_get_connection_pass(self, settings):
        """Test method ``get_connection`` using password of user to connect to
        the server

        Mock up ``paramiko.SSHClient`` (by overriding method
        ``_call_paramiko_sshclient``) before calling ``get_connection``.
        Assert that certain parameters are passed to the (mock)
        ``paramiko.SSHClient`` object, and that certain methods on that object
        are called.
        """
        ssh._call_paramiko_sshclient = MockSSHClient  # pylint:disable=W0212
        settings.server.hostname = 'example.com'
        settings.server.ssh_username = '******'
        settings.server.ssh_key = None
        settings.server.ssh_password = '******'
        settings.ssh_client.command_timeout = 300
        settings.ssh_client.connection_timeout = 10
        with ssh.get_connection() as connection:  # pylint:disable=W0212
            self.assertEqual(connection.set_missing_host_key_policy_, 1)
            self.assertEqual(connection.connect_, 1)
            self.assertEqual(connection.close_, 0)
            self.assertEqual(connection.hostname, 'example.com')
            self.assertEqual(connection.username, 'nobody')
            self.assertEqual(connection.password, 'test_password')
        self.assertEqual(connection.set_missing_host_key_policy_, 1)
        self.assertEqual(connection.connect_, 1)
        self.assertEqual(connection.close_, 1)
示例#32
0
    def test_positive_directory_created(self):
        """katello-backup with non-existing directory


        :id: 946991ad-125a-4f24-a33e-ea27fce38eda

        :Steps:

            1. Ensure the directory /tmp/xyz does not exist.
            2. Run ``katello /tmp/xyz``

        :expectedresults: ``/tmp/xyz`` is created and the backup is saved to it
            containing all the default files needed to restore.
        """
        with get_connection() as connection:
            dir_name = gen_string('alpha')
            connection.run('rm -rf /tmp/{0}'.format(dir_name))
            result = connection.run(
                'katello-backup /tmp/{0} --online-backup'.format(dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls /tmp/{0}'.format(dir_name),
                output_format='list'
            )
            # backup could have more files than the default so it is superset
            self.assertTrue(set(files.stdout).issuperset(set(BACKUP_FILES)))
示例#33
0
    def test_positive_online_backup_exit_code_on_failure(self):
        """katello-backup --online-backup correct exit code on failure

        :id: a26795bf-faa4-49ce-8613-2ed7bc9c0540

        :Steps:

            1. Stop the postgresql service
            2. Run ``katello-backup --online-backup``
            3. Assert exit code is not 0
            4. Start the service again

        :bz: 1323607

        :expectedresults: katello-backup finished with correct exit code

        :caseautomation: automated
        """
        with get_connection() as connection:
            connection.run('katello-service start')
            dir_name = gen_string('alpha')
            dead_service = 'postgresql'
            connection.run('service {0} stop'.format(dead_service))
            tmp_directory_cleanup(connection, dir_name)
            result = connection.run(
                'satellite-backup -y /tmp/{0} --online-backup'.format(dir_name)
            )
            self.assertNotEqual(result.return_code, 0)
            connection.run('service {0} start'.format(dead_service))
            tmp_directory_cleanup(connection, dir_name)
示例#34
0
    def test_positive_online_backup_exit_code_on_failure(self):
        """katello-backup --online-backup correct exit code on failure

        :id: a26795bf-faa4-49ce-8613-2ed7bc9c0540

        :Steps:

            1. Stop the postgresql service
            2. Run ``katello-backup --online-backup``
            3. Assert exit code is not 0
            4. Start the service again

        :bz: 1323607

        :expectedresults: katello-backup finished with correct exit code

        """
        with get_connection() as connection:
            connection.run('katello-service start')
            dir_name = gen_string('alpha')
            dead_service = 'postgresql'
            connection.run('service {0} stop'.format(dead_service))
            tmp_directory_cleanup(connection, dir_name)
            result = connection.run(
                'katello-backup /tmp/{0} --online-backup'.format(dir_name))
            self.assertNotEqual(result.return_code, 0)
            connection.run('service {0} start'.format(dead_service))
            tmp_directory_cleanup(connection, dir_name)
示例#35
0
    def test_positive_online_skip_pulp(self):
        """Katello-backup --online-backup with --skip-pulp-content
        option should not create pulp files in destination.

        :id: 0f0c1915-dd07-4571-9b05-e0778efc85b2

        :Steps:

            1. Run online backup with --skip-pulp-content option
            2. List contents of the destination

        :expectedresults: ``/tmp/bck-no-pulp`` is created and pulp
            related files are not present. Services keep running.

        :caseautomation: automated
        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            connection.run('katello-service start')
            result = connection.run(
                'satellite-backup -y /tmp/{0} --online-backup '
                '--skip-pulp-content'.format(dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                    'ls -a /tmp/{0}/satellite-backup*'.format(dir_name),
                    'list'
                    )
            self.assertNotIn(u'pulp_data.tar', files.stdout)
            self.assertNotIn(u'.pulp.snar', files.stdout)
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#36
0
    def test_get_connection_key(self, settings):
        """Test method ``get_connection`` using key file to connect to the
        server.

        Mock up ``paramiko.SSHClient`` (by overriding method
        ``_call_paramiko_sshclient``) before calling ``get_connection``.
        Assert that certain parameters are passed to the (mock)
        ``paramiko.SSHClient`` object, and that certain methods on that object
        are called.
        """
        ssh._call_paramiko_sshclient = MockSSHClient  # pylint:disable=W0212

        key_filename = os.path.join(os.path.abspath(__name__), 'data',
                                    'test_dsa.key')
        settings.server.hostname = 'example.com'
        settings.server.ssh_username = '******'
        settings.server.ssh_key = key_filename
        with ssh.get_connection() as connection:  # pylint:disable=W0212
            self.assertEqual(connection.set_missing_host_key_policy_, 1)
            self.assertEqual(connection.connect_, 1)
            self.assertEqual(connection.close_, 0)
            self.assertEqual(connection.hostname, 'example.com')
            self.assertEqual(connection.username, 'nobody')
            self.assertEqual(connection.key_filename, key_filename)
        self.assertEqual(connection.set_missing_host_key_policy_, 1)
        self.assertEqual(connection.connect_, 1)
        self.assertEqual(connection.close_, 1)
示例#37
0
    def test_positive_online_incremental_skip_pulp(self):
        """Katello-backup with --online --skip-pulp-content and
        --incremental options

        :id: 49c42a81-88c3-4827-9b9e-6c41a8570234

        :Steps:

            1. Run full backup
            2. Run online incremental backup without pulp from the
                previous backup

        :expectedresults: Incremental backup is created and pulp related files
            are not present. Services keep running.

        :caseautomation: automated
        """
        with get_connection() as connection:
            b1_dir = make_random_tmp_directory(connection)
            connection.run('katello-service start')
            # run full backup
            result = connection.run(
                'satellite-backup -y /tmp/{0} --online-backup'.format(b1_dir),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(b1_dir), result.stdout)
            files = connection.run(
                    'ls -a /tmp/{0}/satellite-backup*'.format(b1_dir),
                    'list'
                    )
            # backup could have more files than the default so it is superset
            self.assertTrue(set(files.stdout).issuperset(
                set(HOT_BACKUP_FILES)))

            # run incremental backup
            b1_dest = make_random_tmp_directory(connection)
            timestamped_dir = connection.run(
                    'ls /tmp/{0}/'.format(b1_dir),
                    'list'
                    )
            result = connection.run(
                '''katello-backup -y --online-backup \
                        --skip-pulp-content /tmp/{0} \
                        --incremental /tmp/{1}/{2}'''
                .format(b1_dest, b1_dir, timestamped_dir.stdout[0]),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(b1_dest), result.stdout)
            files = connection.run(
                    'ls -a /tmp/{0}/satellite-backup*'.format(b1_dest),
                    'list'
                    )
            self.assertNotIn(u'pulp_data.tar', files.stdout)
            # check if services are running correctly
            self.check_services_status()
            self.assertTrue(
                    directory_size_compare(connection, b1_dir, b1_dest))
            tmp_directory_cleanup(connection, b1_dir, b1_dest)
    def test_positive_validate_katello_certs_check_output(
            self, cert_setup, cert_data):
        """Validate that katello-certs-check generates correct output.

        :id: 4c9e4c6e-8d8e-4953-87a1-09cb55df3adf

        :steps:

            1. Use Jenkins provided custom certs
            2. Run katello-certs-check with the required valid arguments
               katello-certs-check -c CERT_FILE -k KEY_FILE -r REQ_FILE
               -b CA_BUNDLE_FILE
            3. Assert the output has correct commands with options

        :expectedresults: Katello-certs-check should generate correct commands
         with options.
        """
        with get_connection() as connection:
            result = connection.run(
                'katello-certs-check -c {} -k {} -b {}'.format(
                    cert_data['cert_file_name'],
                    cert_data['key_file_name'],
                    cert_data['ca_bundle_file_name'],
                ),
                output_format='plain',
            )
        self.validate_output(result, cert_data)
示例#39
0
    def test_positive_restore_from_offline_backup(self):
        """katello-restore from offline backup files

        :id: d270bf40-7999-4b80-a38e-1d861a966cd9

        :Steps:

            1. Add a new user
            2. Create an offline backup
            3. Add another user
            4. Restore from backup

        :expectedresults: Restore is successfull. User 1 is
            present after restoring, User 2 is not

        """
        with get_connection() as connection:
            username1 = gen_string('alpha')
            username2 = gen_string('alpha')
            dir_name = make_random_tmp_directory(connection)
            entities.User(login=username1).create()
            result = connection.run('katello-backup /tmp/{0} '
                                    '--skip-pulp-content'.format(dir_name),
                                    output_format='plain')
            self.assertEqual(result.return_code, 0)
            entities.User(login=username2).create()
            result = connection.run(
                'katello-restore -y /tmp/{0}/katello-backup*'.format(dir_name))
            self.assertEqual(result.return_code, 0)
            user_list = entities.User().search()
            self.assertGreater(len(user_list), 0)
            username_list = [user.login for user in user_list]
            self.assertIn(username1, username_list)
            self.assertNotIn(username2, username_list)
            tmp_directory_cleanup(connection, dir_name)
示例#40
0
def default_url_on_new_port(oldport, newport):
    """Creates context where the default capsule is forwarded on a new port

    :param int oldport: Port to be forwarded.
    :param int newport: New port to be used to forward `oldport`.

    :return: A string containing the new capsule URL with port.
    :rtype: str

    """
    logger = logging.getLogger('robottelo')
    domain = settings.server.hostname

    with ssh.get_connection() as connection:
        command = (
            u'ncat -kl -p {0} -c "ncat {1} {2}"'
        ).format(newport, domain, oldport)
        logger.debug('Creating tunnel: {0}'.format(command))
        transport = connection.get_transport()
        channel = transport.open_session()
        channel.get_pty()
        channel.exec_command(command)
        # if exit_status appears until command_timeout, throw error
        if channel.exit_status_ready():
            if channel.recv_exit_status() != 0:
                stderr = u''
                while channel.recv_stderr_ready():
                    stderr += channel.recv_stderr(1)
                logger.debug('Tunnel failed: {0}'.format(stderr))
                # Something failed, so raise an exception.
                raise CapsuleTunnelError(stderr)
        yield 'https://{0}:{1}'.format(domain, newport)
示例#41
0
    def test_positive_skip_pulp(self):
        """Katello-backup with --skip-pulp-content option should not
        create pulp files in destination.

        :id: f0fa2daa-209e-4d46-9b67-3041768a2a77

        :Steps:

            1. Run online backup with --skip-pulp-content option
            2. List contents of the destination

        :expectedresults: Backup is created and pulp related
            files are not present. Services are started back again.

        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            result = connection.run('katello-backup /tmp/{0} '
                                    '--skip-pulp-content'.format(dir_name),
                                    output_format='plain')
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                'ls -a /tmp/{0}/katello-backup*'.format(dir_name), 'list')
            self.assertNotIn(u'pulp_data.tar', files.stdout)
            self.assertNotIn(u'.pulp.snar', files.stdout)
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#42
0
    def test_positive_incremental(self):
        """Make an incremental backup

        :id: a5b3536f-8365-41c7-9386-cddde588fe8c

        :Steps:

            1. Run full backup (base)
            2. Make config change c1
            3. Run incremental backup ib1
            4. Restore base backup, verify c1 config doesnt not exist
            5. restore ib1, verify c1 config does exist

        :expectedresults: Backup "ib1" is backed up.

        """
        with get_connection() as connection:
            b1_dir = make_random_tmp_directory(connection)
            # run full backup
            result = connection.run(
                'katello-backup /tmp/{0} --online-backup'.format(b1_dir),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(b1_dir), result.stdout)
            files = connection.run('ls /tmp/{0}'.format(b1_dir), 'list')
            # backup could have more files than the default so it is superset
            self.assertTrue(set(files.stdout).issuperset(set(BACKUP_FILES)))

            # Create a new repo
            repo_name = gen_string('alpha')
            entities.Repository(
                    product=self.product, name=repo_name
            ).create()

            # run incremental backup /tmp/ib1
            ib1_dir = gen_string('alpha')
            connection.run('cp -r /tmp/{0} /tmp/{1}'.format(b1_dir, ib1_dir))
            result = connection.run(
                'kattelo-backup /tmp/{0} --online-backup --incremental'
                .format(ib1_dir),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(ib1_dir), result.stdout)

            # restore /tmp/b1 and assert repo 1 is not there
            connection.run('katello-restore /tmp/{0}'.format(b1_dir))
            repo_list = entities.Repository().search(
                query={'search': 'name={0}'.format(repo_name)}
            )
            self.assertEqual(len(repo_list), 0)

            # restore /tmp/ib1 and assert repo 1 is there
            connection.run('katello-restore /tmp/{0}'.format(ib1_dir))
            repo_list = entities.Repository().search(
                query={'search': 'name={0}'.format(repo_name)}
            )
            self.assertEqual(len(repo_list), 1)
示例#43
0
    def test_positive_restore_from_online_and_incremental(self):
        """katello-restore from online and incremental backup

        :id: 8e564f44-06f4-47f0-8c0b-4e3a62af7915

        :Steps:

            1. Create a User
            2. Create an online backup
            3. Create another User
            4. Create an incremental backup
            5. Restore from online backup
            6. Restore from incremental backup

        :expectedresults: Both restores are successful. User 1
            is present after restoring from online backup, User 2
            is not. Both Users are present after restoring from
            incremental.

        """
        with get_connection() as connection:
            b1 = make_random_tmp_directory(connection)
            b2 = make_random_tmp_directory(connection)
            username1 = gen_string('alpha')
            username2 = gen_string('alpha')
            entities.User(login=username1).create()
            result = connection.run('katello-backup /tmp/{0} '
                                    '--online-backup '
                                    '--skip-pulp-content'.format(b1),
                                    output_format='plain')
            self.assertEqual(result.return_code, 0)
            entities.User(login=username2).create()
            result = connection.run('katello-backup '
                                    '--skip-pulp-content '
                                    '--online-backup /tmp/{0} '
                                    '--incremental /tmp/{1}/*'.format(b2, b1),
                                    output_format='plain')
            self.assertEqual(result.return_code, 0)

            # restore from the base backup
            result = connection.run(
                'katello-restore -y /tmp/{0}/katello-backup*'.format(b1))
            self.assertEqual(result.return_code, 0)
            user_list = entities.User().search()
            self.assertGreater(len(user_list), 0)
            username_list = [user.login for user in user_list]
            self.assertIn(username1, username_list)
            self.assertNotIn(username2, username_list)

            # restore from the incremental backup
            result = connection.run(
                'katello-restore -y /tmp/{0}/katello-backup*'.format(b2))
            self.assertEqual(result.return_code, 0)
            user_list = entities.User().search()
            self.assertGreater(len(user_list), 0)
            username_list = [user.login for user in user_list]
            self.assertIn(username1, username_list)
            self.assertIn(username2, username_list)
            tmp_directory_cleanup(connection, b1, b2)
    def test_positive_validate_capsule_certificate(self, file_setup):
        """Check that Capsules cert handles additional proxy names.

        :id: 8b53fc3d-704f-44f4-899e-74654529bfcf

        :customerscenario: true

        :steps:

            1. Generate a Capsule certificate
            2. Confirm proxy server's FQDN for DNS is present
            3. Confirm that format of alternative names does not include []

        :expectedresults: Capsule certs has valid DNS values

        :BZ: 1747581

        :CaseAutomation: Automated
        """
        DNS_Check = False
        with get_connection(timeout=200) as connection:
            # extract the cert from the tar file
            result = connection.run(
                'tar -xf {0}/capsule_certs.tar --directory {0}/ '.format(file_setup['tmp_dir'])
            )
            assert result.return_code == 0, 'Extraction to working directory failed.'
            # Extract raw data from RPM to a file
            result = connection.run(
                'rpm2cpio {0}/ssl-build/{1}/'
                '{1}-qpid-router-server*.rpm'
                '>> {0}/ssl-build/{1}/cert-raw-data'.format(
                    file_setup['tmp_dir'], file_setup['capsule_hostname']
                )
            )
            # Extract the cert data from file cert-raw-data and write to cert-data
            result = connection.run(
                'openssl x509 -noout -text -in {0}/ssl-build/{1}/cert-raw-data'
                '>> {0}/ssl-build/{1}/cert-data'.format(
                    file_setup['tmp_dir'], file_setup['capsule_hostname']
                )
            )
            # use same location on remote and local for cert_file
            download_file(file_setup['caps_cert_file'])
            # search the file for the line with DNS
            with open(file_setup['caps_cert_file']) as file:
                for line in file:
                    if re.search(r'\bDNS:', line):
                        match = re.search(r'{}'.format(file_setup['capsule_hostname']), line)
                        assert match, "No proxy name found."
                        if is_open('BZ:1747581'):
                            DNS_Check = True
                        else:
                            match = re.search(r'\[]', line)
                            assert not match, "Incorrect parsing of alternative proxy name."
                            DNS_Check = True
                        break
                    # if no match for "DNS:" found, then raise error.
            assert DNS_Check, "Cannot find Subject Alternative Name"
示例#45
0
 def tearDown(self):
     """Make sure services are started after each test"""
     with get_connection() as connection:
         result = connection.run('katello-service start',
                                 timeout=1600,
                                 output_format='plain')
         if result.return_code != 0:
             self.fail('Failed to start services')
     super(HotBackupTestCase, self).tearDown()
示例#46
0
    def test_positive_incremental(self):
        """Katello-backup with --incremental option

        :id: 3bd1e85c-8c95-4198-a126-35eaf14572ed

        :Steps:

            1. Run full backup
            2. Run incremental backup from the previous backup

        :expectedresults: Incremental backup is created. Services are
            started back again.

        :caseautomation: automated
        """
        with get_connection() as connection:
            b1_dir = make_random_tmp_directory(connection)
            # run full backup
            result_full = connection.run(
                'satellite-backup -y /tmp/{0} --online-backup'.format(b1_dir),
                output_format='plain',
                timeout=900
            )
            self.assertEqual(result_full.return_code, 0)
            self.assertIn(BCK_MSG.format(b1_dir), result_full.stdout)
            files = connection.run(
                    'ls -a /tmp/{0}/satellite-backup*'.format(b1_dir),
                    'list'
                    )
            # backup could have more files than the default so it is superset
            self.assertTrue(set(files.stdout).issuperset(
                set(HOT_BACKUP_FILES)))

            # run incremental backup
            b1_dest = make_random_tmp_directory(connection)
            timestamped_dir = connection.run(
                    'ls /tmp/{0}/'.format(b1_dir),
                    'list'
                    )
            result_inc = connection.run(
                'satellite-backup -y /tmp/{0} --incremental /tmp/{1}/{2}'
                .format(b1_dest, b1_dir, timestamped_dir.stdout[0]),
                output_format='plain',
                timeout=900
            )
            self.assertEqual(result_inc.return_code, 0)
            self.assertIn(BCK_MSG.format(b1_dest), result_inc.stdout)
            files = connection.run(
                    'ls -a /tmp/{0}/satellite-backup*'.format(b1_dest),
                    'list'
                    )
            self.assertTrue(set(files.stdout).issuperset(set(BACKUP_FILES)))
            # check if services are running correctly
            self.check_services_status()
            self.assertTrue(
                    directory_size_compare(connection, b1_dir, b1_dest))
            tmp_directory_cleanup(connection, b1_dir, b1_dest)
示例#47
0
 def test_execute_command(self, settings):
     ssh._call_paramiko_sshclient = MockSSHClient  # pylint:disable=W0212
     settings.server.hostname = 'example.com'
     settings.server.ssh_username = '******'
     settings.server.ssh_key = None
     settings.server.ssh_password = '******'
     with ssh.get_connection() as connection:  # pylint:disable=W0212
         ret = ssh.execute_command('ls -la', connection)
         self.assertEquals(ret.stdout, [u'ls -la'])
         self.assertIsInstance(ret, ssh.SSHCommandResult)
示例#48
0
 def tearDown(self):
     """Make sure services are started after each test"""
     with get_connection() as connection:
         result = connection.run(
             'katello-service start',
             timeout=1600,
             output_format='plain'
         )
         if result.return_code != 0:
             self.fail('Failed to start services')
     super(HotBackupTestCase, self).tearDown()
示例#49
0
 def tearDownClass(cls):
     """Make sure services are started after test run"""
     super(RestoreTestCase, cls).tearDownClass()
     with get_connection() as connection:
         result = connection.run(
             'katello-service start',
             timeout=1600,
             output_format='plain'
         )
         if result.return_code != 0:
             raise AssertionError("Failed to start services")
示例#50
0
    def test_execute_command_plain_output(self, settings):
        ssh._call_paramiko_sshclient = MockSSHClient  # pylint:disable=W0212
        settings.server.hostname = 'example.com'
        settings.server.ssh_username = '******'
        settings.server.ssh_key = None
        settings.server.ssh_password = '******'
        settings.ssh_client.command_timeout = 300
        settings.ssh_client.connection_timeout = 10

        with ssh.get_connection() as connection:  # pylint:disable=W0212
            ret = ssh.execute_command(
                'ls -la', connection, output_format='plain')
            self.assertEquals(ret.stdout, u'ls -la')
            self.assertIsInstance(ret, ssh.SSHCommandResult)
示例#51
0
    def test_positive_rename_satellite(self):
        """run katello-change-hostname on Satellite server

        :id: 9944bfb1-1440-4820-ada8-2e219f09c0be

        :setup: Satellite server with synchronized rh and custom
            repos and with a registered host

        :steps:

            1. Rename Satellite using katello-change-hostname
            2. Do basic checks for hostname change (hostnamctl)
            3. Run some existence tests, as in backup testing
            4. Verify certificates were properly recreated, check
                for instances of old hostname
                in etc/foreman-installer/scenarios.d/
            5. Check for updated repo urls, installation media paths,
                updated internal capsule
            6. Check usability of entities created before rename: refresh
                manifest, resync repos, republish CVs and re-register hosts
            7. Create new entities (run end-to-end test from robottelo)

        :bz: 1469466

        :expectedresults: Satellite hostname is successfully updated
            and the server functions correctly

        :caseautomation: automated
        """
        # Save original hostname, get credentials, eventually will
        # end up in setUpClass
        # original_name = settings.server.hostname
        username = settings.server.admin_username
        password = settings.server.admin_password
        # the rename part of the test, not necessary to run from robotello
        with get_connection() as connection:
            hostname = gen_string('alpha')
            result = connection.run(
                # use -y once implemented BZ#1469466
                'yes | katello-change-hostname -u {0} -p {1}\
                        --disable-system-checks\
                        --scenario satellite {2}'.format(
                    username, password, hostname),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG, result.stdout)
示例#52
0
    def test_positive_rename_capsule(self):
        """run katello-change-hostname on Capsule

        :id: 4aa9fd86-bba9-49e4-a67a-8685e1ab5a74

        :setup: Capsule server registered to Satellite, with common features
            enabled, with synchronized content and a host registered to it

        :steps:
            1. Rename Satellite using katello-change-hostname
            2. Do basic checks for hostname change (hostnamctl)
            3. Verify certificates were properly recreated, check
                for instances of old hostname
                in etc/foreman-installer/scenarios.d/
            4. Re-register Capsule to Satellite, resync content
            5. Re-register old host, register new one to Satellite,
            6. Check hosts can consume content, run basic REX command,
                import Puppet environments from hosts

        :BZ: 1469466, 1473614

        :expectedresults: Capsule hostname is successfully updated
            and the capsule fuctions correctly

        :caseautomation: automated
        """
        # Save original hostname, get credentials, eventually will
        # end up in setUpClass
        # original_name = settings.server.hostname
        username = settings.server.admin_username
        password = settings.server.admin_password
        # the rename part of the test, not necessary to run from robotello
        with get_connection() as connection:
            hostname = gen_string('alpha')
            result = connection.run(
                # use -y once implemented BZ#1469466
                'yes | katello-change-hostname -u {0} -p {1}\
                        --disable-system-checks\
                        --scenario capsule {2}'.format(
                    username, password, hostname),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG, result.stdout)
示例#53
0
    def test_positive_restore_from_offline_backup(self):
        """katello-restore from offline backup files

        :id: d270bf40-7999-4b80-a38e-1d861a966cd9

        :Steps:

            1. Add a new user
            2. Create an offline backup
            3. Add another user
            4. Restore from backup

        :bz: 1482135

        :expectedresults: Restore is successfull. User 1 is
            present after restoring, User 2 is not

        """
        with get_connection() as connection:
            username1 = gen_string('alpha')
            username2 = gen_string('alpha')
            dir_name = make_random_tmp_directory(connection)
            entities.User(login=username1).create()
            result = connection.run(
                'satellite-backup -y /tmp/{0} '
                '--skip-pulp-content'.format(dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 0)
            entities.User(login=username2).create()
            result = connection.run(
                'satellite-restore -y /tmp/{0}/satellite-backup*'
                .format(dir_name),
                timeout=1600)
            self.assertEqual(result.return_code, 0)
            user_list = entities.User().search()
            self.assertGreater(len(user_list), 0)
            username_list = [user.login for user in user_list]
            self.assertIn(username1, username_list)
            self.assertNotIn(username2, username_list)
            tmp_directory_cleanup(connection, dir_name)
示例#54
0
    def test_negative_incremental_with_no_dest_directory(self):
        """katello-backup --incremental with no destination directory

        :id: 183195df-b5df-4edf-814e-221bbcdcbde1

        :Steps:

            1. Run ``katello-backup --incremental /tmp``

        :expectedresults: The error message is shown, services are not
            stopped

        """
        with get_connection() as connection:
            result = connection.run(
                'katello-backup -y --incremental /tmp',
                output_format='plain'
            )
            self.assertEqual(result.return_code, 1)
            self.assertIn(NODIR_MSG, result.stderr)
            self.check_services_status()
示例#55
0
    def test_negative_rename_sat_wrong_passwd(self):
        """change hostname with wrong password on Satellite server

        :id: e6d84c5b-4bb1-4400-8022-d01cc9216936

        :bz: 1485884

        :expectedresults: script terminates with a message, hostname
            is not changed

        :caseautomation: automated
        """
        with get_connection() as connection:
            password = gen_string('alpha')
            result = connection.run(
                'katello-change-hostname -y \
                        {0} -u {1} -p {2}'.format(
                    self.hostname, self.username, password),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 1)
            self.assertIn(BAD_CREDS_MSG, result.stderr)
示例#56
0
    def test_negative_online_backup_with_no_directory(self):
        """katello-backup --online-backup with no directory

        :id: e5f58d05-1043-48c0-971f-8f30cc8642ed

        :Steps:

            1. Run ``katello-backup --online-backup``

        :expectedresults: The error message is shown, services are not
            stopped

        """
        with get_connection() as connection:
            connection.run('katello-service start')
            result = connection.run(
                'katello-backup -y --online-backup',
                output_format='plain'
            )
            self.assertEqual(result.return_code, 1)
            self.assertIn(NODIR_MSG, result.stderr)
            self.check_services_status()
示例#57
0
    def test_negative_backup_with_no_directory(self):
        """katello-backup with no directory specified

        :id: e229a4e0-4944-4369-ab7f-0f4e65480e47

        :Steps:

            1. Run ``katello-backup``

        :expectedresults: The error message is shown, services are not
            stopped

        """
        with get_connection() as connection:
            connection.run('katello-service start')
            result = connection.run(
                'katello-backup -y',
                output_format='plain'
            )
            self.assertEqual(result.return_code, 1)
            self.assertIn(NODIR_MSG, result.stderr)
            self.check_services_status()
示例#58
0
    def test_positive_logical_db_backup(self):
        """Katello-backup with --logical-db-backup option should
        dump full database schema during offline backup

        :id: a1386cfa-cd7e-4f22-9ebc-7c908d514ad4

        :Steps:

            1. Run online backup with --logical-db-backup option
            2. List contents of the destination

        :expectedresults: Backup is created and additional files are
            not present. Services are started back again.

        :caseautomation: automated
        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            result = connection.run(
                'satellite-backup -y /tmp/{0} '
                '--logical-db-backup'.format(dir_name),
                output_format='plain',
                timeout=900
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(BCK_MSG.format(dir_name), result.stdout)
            files = connection.run(
                    'ls -a /tmp/{0}/satellite-backup*'.format(dir_name),
                    'list'
                    )
            self.assertTrue(set(files.stdout).issuperset(
                set(BACKUP_FILES)))
            self.assertIn(u'candlepin.dump', files.stdout)
            self.assertIn(u'foreman.dump', files.stdout)
            self.assertIn(u'mongo_dump', files.stdout)
            self.assertIn(u'pg_globals.dump', files.stdout)
            # check if services are running correctly
            self.check_services_status()
            tmp_directory_cleanup(connection, dir_name)
示例#59
0
    def test_negative_restore_with_empty_directory(self):
        """katello-backup with no directory specified

        :id: e229a4e0-4944-4369-ab7f-0f4e65480e47

        :Steps:

            1. Run ``katello-backup`` empty_dir

        :expectedresults: The error message is shown, services are not
            stopped

        """
        with get_connection() as connection:
            dir_name = make_random_tmp_directory(connection)
            result = connection.run(
                'katello-restore -y /tmp/{}'.format(dir_name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 255)
            self.assertIn(NOFILES_MSG, result.stdout)
            self.check_services_status()
示例#60
0
    def test_negative_restore_nonexistent_directory(self):
        """run katello-restore with nonexistent directory specified

        :id: d825c43e-1be0-4aea-adcf-23fcf98e73c8

        :Steps:

            1. Run ``katello-restore`` fake_dir_name

        :expectedresults: The error message is shown, services are not
            stopped

        """
        with get_connection() as connection:
            name = gen_string('alpha')
            result = connection.run(
                'katello-restore {}'.format(name),
                output_format='plain'
            )
            self.assertEqual(result.return_code, 1)
            self.assertIn(NOEXIST_MSG, result.stderr)
            self.check_services_status()