예제 #1
0
def get_appliance(provider):
    '''Fixture to provision appliance to the provider being tested if necessary'''
    global appliance_list
    global appliance_vm_name
    if provider not in appliance_list:
        if ('appliances_provider' not in cfme_data['basic_info'].keys() or
                provider != cfme_data['basic_info']['appliances_provider']):
            appliance_list[provider] = provision_appliance(provider)
        else:
            appliance_list[provider] = re.findall(r'[0-9]+(?:\.[0-9]+){3}', conf.env['base_url'])[0]

            prov_data = cfme_data['management_systems'][provider]
            if prov_data['type'] == 'virtualcenter':
                # ssh in and see if vddk already present, if not, install
                ssh_kwargs = {
                    'username': conf.credentials['ssh']['username'],
                    'password': conf.credentials['ssh']['password'],
                    'hostname': appliance_list[provider]
                }
                # Init SSH client
                client = SSHClient(**ssh_kwargs)
                if int(client.run_command("ldconfig -p | grep vix | wc -l")[1]) < 1:
                    install_vddk(appliance_list[provider])
                client.close()
            elif prov_data['type'] == 'rhevm':
                add_rhev_direct_lun_disk(provider, appliance_vm_name)
    return appliance_list[provider]
def disable_forgery_protection():
    starttime = time.time()
    ssh_client = SSHClient()
    logger.info('Turning off "allow_forgery_protection"')

    ssh_client.run_command(
        "sed -i \'s/allow_forgery_protection = true/allow_forgery_protection = false/\' "
        "/var/www/miq/vmdb/config/environments/production.rb")
    ssh_client.run_command("service evmserverd restart")

    ssh_client.close()
    timediff = time.time() - starttime
    logger.info('Turned off "allow_forgery_protection" in: {}'.format(timediff))

    yield

    starttime = time.time()
    ssh_client = SSHClient()
    logger.info('Turning on "allow_forgery_protection"')

    ssh_client.run_command(
        "sed -i \'s/allow_forgery_protection = false/allow_forgery_protection = true/\' "
        "/var/www/miq/vmdb/config/environments/production.rb")
    ssh_client.run_command("service evmserverd restart")

    ssh_client.close()
    timediff = time.time() - starttime
    logger.info('Turned on "allow_forgery_protection" in: {}'.format(timediff))
예제 #3
0
def disable_forgery_protection():
    starttime = time.time()
    ssh_client = SSHClient()
    logger.info('Turning off "allow_forgery_protection"')

    ssh_client.run_command(
        "sed -i \'s/allow_forgery_protection = true/allow_forgery_protection = false/\' "
        "/var/www/miq/vmdb/config/environments/production.rb")
    ssh_client.run_command("service evmserverd restart")

    ssh_client.close()
    timediff = time.time() - starttime
    logger.info(
        'Turned off "allow_forgery_protection" in: {}'.format(timediff))

    yield

    starttime = time.time()
    ssh_client = SSHClient()
    logger.info('Turning on "allow_forgery_protection"')

    ssh_client.run_command(
        "sed -i \'s/allow_forgery_protection = false/allow_forgery_protection = true/\' "
        "/var/www/miq/vmdb/config/environments/production.rb")
    ssh_client.run_command("service evmserverd restart")

    ssh_client.close()
    timediff = time.time() - starttime
    logger.info('Turned on "allow_forgery_protection" in: {}'.format(timediff))
예제 #4
0
def get_vm_config_modified_time(name, vm_name, datastore_url, provider_key):
    try:
        providers_data = cfme_data.get("management_systems", {})
        hosts = providers_data[provider_key]['hosts']
        host_creds = providers_data[provider_key].get('host_credentials', 'host_default')
        hostname = [host['name'] for host in hosts if name in host['name']]
        if not hostname:
            hostname = re.findall(r'[0-9]+(?:\.[0-9]+){3}', name)
        connect_kwargs = {
            'username': credentials[host_creds]['username'],
            'password': credentials[host_creds]['password'],
            'hostname': hostname[0]
        }
        datastore_path = re.findall(r'([^ds:`/*].*)', str(datastore_url))
        ssh_client = SSHClient(**connect_kwargs)
        command = 'find ~/{}/{} -name {} | xargs  date -r'.format(
            datastore_path[0], str(vm_name), str(vm_name) + '.vmx')
        exit_status, output = ssh_client.run_command(command)
        ssh_client.close()
        modified_time = parser.parse(output.rstrip())
        modified_time = modified_time.astimezone(pytz.timezone(str(get_localzone())))
        return modified_time.replace(tzinfo=None)
    except Exception as e:
        logger.error(e)
        return False
예제 #5
0
def get_appliance(provider):
    '''Fixture to provision appliance to the provider being tested if necessary'''
    global appliance_list
    global appliance_vm_name
    if provider not in appliance_list:
        if ('appliances_provider' not in cfme_data['basic_info'].keys()
                or provider != cfme_data['basic_info']['appliances_provider']):
            appliance_list[provider] = provision_appliance(provider)
        else:
            appliance_list[provider] = re.findall(r'[0-9]+(?:\.[0-9]+){3}',
                                                  conf.env['base_url'])[0]

            prov_data = cfme_data['management_systems'][provider]
            if prov_data['type'] == 'virtualcenter':
                # ssh in and see if vddk already present, if not, install
                ssh_kwargs = {
                    'username': conf.credentials['ssh']['username'],
                    'password': conf.credentials['ssh']['password'],
                    'hostname': appliance_list[provider]
                }
                # Init SSH client
                client = SSHClient(**ssh_kwargs)
                if int(
                        client.run_command("ldconfig -p | grep vix | wc -l")
                    [1]) < 1:
                    install_vddk(appliance_list[provider])
                client.close()
            elif prov_data['type'] == 'rhevm':
                add_rhev_direct_lun_disk(provider, appliance_vm_name)
    return appliance_list[provider]
예제 #6
0
def get_appliance(provider):
    """Fixture to provision appliance to the provider being tested if necessary"""
    global appliance_list
    global appliance_vm_name
    if provider not in appliance_list:
        if (
            "appliances_provider" not in cfme_data["basic_info"].keys()
            or provider != cfme_data["basic_info"]["appliances_provider"]
        ):
            appliance_list[provider] = provision_appliance(provider)
        else:
            appliance_list[provider] = re.findall(r"[0-9]+(?:\.[0-9]+){3}", conf.env["base_url"])[0]

            prov_data = cfme_data["management_systems"][provider]
            if prov_data["type"] == "virtualcenter":
                # ssh in and see if vddk already present, if not, install
                ssh_kwargs = {
                    "username": conf.credentials["ssh"]["username"],
                    "password": conf.credentials["ssh"]["password"],
                    "hostname": appliance_list[provider],
                }
                # Init SSH client
                client = SSHClient(**ssh_kwargs)
                if int(client.run_command("ldconfig -p | grep vix | wc -l")[1]) < 1:
                    install_vddk(appliance_list[provider])
                client.close()
            elif prov_data["type"] == "rhevm":
                add_rhev_direct_lun_disk(provider, appliance_vm_name)
    return appliance_list[provider]
예제 #7
0
def setup_external_auth_openldap(**data):
    """Sets up the appliance for an external authentication with OpenLdap.

    Keywords:
        get_groups: Get User Groups from External Authentication (httpd).
        ipaserver: IPA server address.
        iparealm: Realm.
        credentials: Key of the credential in credentials.yaml
    """
    connect_kwargs = {
        'username': credentials['host_default']['username'],
        'password': credentials['host_default']['password'],
        'hostname': data['ipaddress'],
    }
    appliance_obj = appliance.IPAppliance()
    appliance_name = 'cfmeappliance{}'.format(fauxfactory.gen_alpha(7).lower())
    appliance_address = appliance_obj.address
    appliance_fqdn = '{}.{}'.format(appliance_name, data['domain_name'])
    ldapserver_ssh = SSHClient(**connect_kwargs)
    # updating the /etc/hosts is a workaround due to the
    # https://bugzilla.redhat.com/show_bug.cgi?id=1360928
    command = 'echo "{}\t{}" >> /etc/hosts'.format(appliance_address,
                                                   appliance_fqdn)
    ldapserver_ssh.run_command(command)
    ldapserver_ssh.get_file(remote_file=data['cert_filepath'],
                            local_path=conf_path.strpath)
    ldapserver_ssh.close()
    ensure_browser_open()
    login_admin()
    auth = ExternalAuthSetting(get_groups=data.pop("get_groups", True))
    auth.setup()
    appliance_obj.configure_appliance_for_openldap_ext_auth(appliance_fqdn)
    logout()
def get_vm_config_modified_time(name, vm_name, datastore_url, provider_key):
    try:
        providers_data = cfme_data.get("management_systems", {})
        hosts = providers_data[provider_key]['hosts']
        host_creds = providers_data[provider_key].get('host_credentials',
                                                      'host_default')
        hostname = [host['name'] for host in hosts if name in host['name']]
        if not hostname:
            hostname = re.findall(r'[0-9]+(?:\.[0-9]+){3}', name)
        connect_kwargs = {
            'username': credentials[host_creds]['username'],
            'password': credentials[host_creds]['password'],
            'hostname': hostname[0]
        }
        datastore_path = re.findall(r'([^ds:`/*].*)', str(datastore_url))
        ssh_client = SSHClient(**connect_kwargs)
        command = 'find ~/{}/{} -name {} | xargs  date -r'.format(
            datastore_path[0], str(vm_name),
            str(vm_name) + '.vmx')
        exit_status, output = ssh_client.run_command(command)
        ssh_client.close()
        modified_time = parser.parse(output.rstrip())
        modified_time = modified_time.astimezone(
            pytz.timezone(str(get_localzone())))
        return modified_time.replace(tzinfo=None)
    except Exception as e:
        logger.error(e)
        return False
예제 #9
0
def setup_external_auth_openldap(**data):
    """Sets up the appliance for an external authentication with OpenLdap.

    Keywords:
        get_groups: Get User Groups from External Authentication (httpd).
        ipaserver: IPA server address.
        iparealm: Realm.
        credentials: Key of the credential in credentials.yaml
    """
    connect_kwargs = {
        'username': credentials['host_default']['username'],
        'password': credentials['host_default']['password'],
        'hostname': data['ipaddress'],
    }
    appliance_obj = appliance.IPAppliance()
    appliance_name = 'cfmeappliance{}'.format(fauxfactory.gen_alpha(7).lower())
    appliance_address = appliance_obj.address
    appliance_fqdn = '{}.{}'.format(appliance_name, data['domain_name'])
    ldapserver_ssh = SSHClient(**connect_kwargs)
    # updating the /etc/hosts is a workaround due to the
    # https://bugzilla.redhat.com/show_bug.cgi?id=1360928
    command = 'echo "{}\t{}" >> /etc/hosts'.format(appliance_address, appliance_fqdn)
    ldapserver_ssh.run_command(command)
    ldapserver_ssh.get_file(remote_file=data['cert_filepath'],
                            local_path=conf_path.strpath)
    ldapserver_ssh.close()
    ensure_browser_open()
    login_admin()
    auth = ExternalAuthSetting(get_groups=data.pop("get_groups", True))
    auth.setup()
    appliance_obj.configure_appliance_for_openldap_ext_auth(appliance_fqdn)
    logout()
예제 #10
0
def setup_external_auth_ipa(**data):
    """Sets up the appliance for an external authentication with IPA.

    Keywords:
        get_groups: Get User Groups from External Authentication (httpd).
        ipaserver: IPA server address.
        iparealm: Realm.
        credentials: Key of the credential in credentials.yaml
    """
    connect_kwargs = {
        'username': credentials['host_default']['username'],
        'password': credentials['host_default']['password'],
        'hostname': data['ipaserver'],
    }
    import fauxfactory
    appliance_name = 'cfmeappliance'.format(fauxfactory.gen_alpha(7).lower())
    appliance_address = appliance.IPAppliance().address
    appliance_fqdn = '{}.{}'.format(appliance_name, data['iparealm'].lower())
    ipaserver_ssh = SSHClient(**connect_kwargs)
    # updating the /etc/hosts is a workaround due to the
    # https://bugzilla.redhat.com/show_bug.cgi?id=1360928
    command = 'echo "{}\t{}" >> /etc/hosts'.format(appliance_address, appliance_fqdn)
    ipaserver_ssh.run_command(command)
    ipaserver_ssh.close()
    ssh = SSHClient()
    rc, out = ssh.run_command('appliance_console_cli --host {}'.format(appliance_fqdn))
    assert rc == 0, out
    ssh.run_command('echo "127.0.0.1\t{}" > /etc/hosts'.format(appliance_fqdn))
    ensure_browser_open()
    login_admin()
    if data["ipaserver"] not in get_ntp_servers():
        set_ntp_servers(data["ipaserver"])
        sleep(120)
    auth = ExternalAuthSetting(get_groups=data.pop("get_groups", False))
    auth.setup()
    logout()
    creds = credentials.get(data.pop("credentials"), {})
    data.update(**creds)
    rc, out = ssh.run_command(
        "appliance_console_cli --ipaserver {ipaserver} --iparealm {iparealm} "
        "--ipaprincipal {principal} --ipapassword {password}".format(**data)
    )
    assert rc == 0, out
    assert "failed" not in out.lower(), "External auth setup failed:\n{}".format(out)
    login_admin()
예제 #11
0
def setup_external_auth_ipa(**data):
    """Sets up the appliance for an external authentication with IPA.

    Keywords:
        get_groups: Get User Groups from External Authentication (httpd).
        ipaserver: IPA server address.
        iparealm: Realm.
        credentials: Key of the credential in credentials.yaml
    """
    connect_kwargs = {
        'username': credentials['host_default']['username'],
        'password': credentials['host_default']['password'],
        'hostname': data['ipaserver'],
    }
    appliance_name = 'cfmeappliance{}'.format(fauxfactory.gen_alpha(7).lower())
    appliance_address = appliance.IPAppliance().address
    appliance_fqdn = '{}.{}'.format(appliance_name, data['iparealm'].lower())
    ipaserver_ssh = SSHClient(**connect_kwargs)
    ipaserver_ssh.run_command('cp /etc/hosts /etc/hosts_bak')
    ipaserver_ssh.run_command(
        "sed -i -r '/^{}/d' /etc/hosts".format(appliance_address))
    command = 'echo "{}\t{}" >> /etc/hosts'.format(appliance_address,
                                                   appliance_fqdn)
    ipaserver_ssh.run_command(command)
    ipaserver_ssh.close()
    ssh = SSHClient()
    assert ssh.run_command(
        'appliance_console_cli --host {}'.format(appliance_fqdn))
    ensure_browser_open()
    login_admin()
    if data["ipaserver"] not in get_ntp_servers():
        set_ntp_servers(data["ipaserver"])
        sleep(120)
    auth = ExternalAuthSetting(get_groups=data.pop("get_groups", False))
    auth.setup()
    creds = credentials.get(data.pop("credentials"), {})
    data.update(**creds)
    assert ssh.run_command(
        "appliance_console_cli --ipaserver {ipaserver} --iparealm {iparealm} "
        "--ipaprincipal {principal} --ipapassword {password}".format(**data))
    login_admin()
예제 #12
0
def generate_version_files():
    yield
    starttime = time.time()
    ssh_client = SSHClient()
    relative_path = os.path.relpath(str(results_path), str(os.getcwd()))
    relative_string = relative_path + '/{}*'.format(test_ts)
    directory_list = glob.glob(relative_string)

    for directory in directory_list:
        module_path = os.path.join(directory, 'version_info')
        if os.path.exists(str(module_path)):
            return
        else:
            os.mkdir(str(module_path))
        generate_system_file(ssh_client, module_path)
        generate_processes_file(ssh_client, module_path)
        generate_gems_file(ssh_client, module_path)
        generate_rpms_file(ssh_client, module_path)

    timediff = time.time() - starttime
    logger.info('Generated all version files in {}'.format(timediff))
    ssh_client.close()
예제 #13
0
class OcpCli(object):
    """This class provides CLI functionality for Openshift provider.
    """
    def __init__(self, provider):

        provider_cfme_data = provider.get_yaml_data()
        self.hostname = provider_cfme_data['hostname']
        creds = conf.configuration.yaycl_config.credentials
        if hasattr(creds, provider.key):
            prov_creds = getattr(creds, provider.key)
            self.username = prov_creds.username
            self.password = prov_creds.password
            self.ssh_client = SSHClient(hostname=self.hostname,
                                        username=self.username,
                                        password=self.password)
        else:
            # Try with known hosts
            self.ssh_client = SSHClient()
            self.ssh_client.load_system_host_keys()
            self.ssh_client.connect(self.hostname)
        self._command_counter = 0
        self.log_line_limit = 500

    def run_command(self, *args, **kwargs):
        logger.info('{} - Running SSH Command#{} : {}'.format(
            self.hostname, self._command_counter, args[0]))
        results = self.ssh_client.run_command(*args, **kwargs)
        results_short = results[:max((self.log_line_limit, len(results)))]
        if results.success:
            logger.info('{} - Command#{} - Succeed: {}'.format(
                self.hostname, self._command_counter, results_short))
        else:
            logger.warning('{} - Command#{} - Failed: {}'.format(
                self.hostname, self._command_counter, results_short))
        self._command_counter += 1
        return results

    def close(self):
        self.ssh_client.close()
예제 #14
0
def generate_version_files():
    yield
    starttime = time.time()
    ssh_client = SSHClient()
    relative_path = os.path.relpath(str(results_path), str(os.getcwd()))
    relative_string = relative_path + '/{}*'.format(test_ts)
    directory_list = glob.glob(relative_string)

    for directory in directory_list:
        module_path = os.path.join(directory, 'version_info')
        if os.path.exists(str(module_path)):
            return
        else:
            os.mkdir(str(module_path))
        generate_system_file(ssh_client, module_path)
        generate_processes_file(ssh_client, module_path)
        generate_gems_file(ssh_client, module_path)
        generate_rpms_file(ssh_client, module_path)

    timediff = time.time() - starttime
    logger.info('Generated all version files in {}'.format(timediff))
    ssh_client.close()
예제 #15
0
def setup_external_auth_ipa(**data):
    """Sets up the appliance for an external authentication with IPA.

    Keywords:
        get_groups: Get User Groups from External Authentication (httpd).
        ipaserver: IPA server address.
        iparealm: Realm.
        credentials: Key of the credential in credentials.yaml
    """
    connect_kwargs = {
        'username': credentials['host_default']['username'],
        'password': credentials['host_default']['password'],
        'hostname': data['ipaserver'],
    }
    appliance_name = 'cfmeappliance{}'.format(fauxfactory.gen_alpha(7).lower())
    appliance_address = appliance.IPAppliance().address
    appliance_fqdn = '{}.{}'.format(appliance_name, data['iparealm'].lower())
    ipaserver_ssh = SSHClient(**connect_kwargs)
    ipaserver_ssh.run_command('cp /etc/hosts /etc/hosts_bak')
    ipaserver_ssh.run_command("sed -i -r '/^{}/d' /etc/hosts".format(appliance_address))
    command = 'echo "{}\t{}" >> /etc/hosts'.format(appliance_address, appliance_fqdn)
    ipaserver_ssh.run_command(command)
    ipaserver_ssh.close()
    ssh = SSHClient()
    assert ssh.run_command('appliance_console_cli --host {}'.format(appliance_fqdn))
    ensure_browser_open()
    login_admin()
    if data["ipaserver"] not in get_ntp_servers():
        set_ntp_servers(data["ipaserver"])
        sleep(120)
    auth = ExternalAuthSetting(get_groups=data.pop("get_groups", False))
    auth.setup()
    creds = credentials.get(data.pop("credentials"), {})
    data.update(**creds)
    assert ssh.run_command(
        "appliance_console_cli --ipaserver {ipaserver} --iparealm {iparealm} "
        "--ipaprincipal {principal} --ipapassword {password}".format(**data)
    )
    login_admin()
def list_orphaned_files_per_host(host_name, host_datastore_urls, provider_key, vm_registered_files,
                                 unregistered_files):
    try:
        providers_data = cfme_data.get("management_systems", {})
        hosts = providers_data[provider_key]['hosts']
        hostname = [host['name'] for host in hosts if host_name in host['name']]
        # check if hostname returned is ipaddress
        if not hostname:
            hostname = re.findall(r'[0-9]+(?:\.[0-9]+){3}', host_name)
        connect_kwargs = {
            'username': credentials['host_default']['username'],
            'password': credentials['host_default']['password'],
            'hostname': hostname[0]
        }
        for datastore_url in host_datastore_urls:
            datastore_path = re.findall(r'([^ds:`/*].*)', str(datastore_url))
            ssh_client = SSHClient(**connect_kwargs)
            command = 'ls ~/{}'.format(datastore_path[0])
            exit_status, output = ssh_client.run_command(command)
            ssh_client.close()
            files_in_datastore = output.splitlines() if exit_status == 0 else []
            for fil in files_in_datastore:
                if fil not in vm_registered_files:
                    file_type = 'UNKNOWN'
                    number_of_files = 0
                    command = 'test -d ~/{}/{}; echo $?'.format(datastore_path[0], fil)
                    exit_status, output = ssh_client.run_command(command)
                    ssh_client.close()
                    file_extension = re.findall(r'.*\.(\w*)', fil)
                    if file_extension:
                        file_type = file_extension[0]
                        number_of_files = 1
                    if int(output.strip()) == 0:
                        command = 'ls ~/{}/{} | wc -l'.format(datastore_path[0], fil)
                        exit_status, output = ssh_client.run_command(command)
                        number_of_files = output.strip()
                        command = 'find ~/{}/{} -name "*.vmx" | wc -l'.format(
                            datastore_path[0], fil)
                        vmx_status, vmx_output = ssh_client.run_command(command)
                        command = 'find ~/{}/{} -name "*.vmtx" | wc -l'.format(
                            datastore_path[0], fil)
                        vmtx_status, vmtx_output = ssh_client.run_command(command)
                        command = 'find ~/{}/{} -name "*.vmdk" | wc -l'.format(
                            datastore_path[0], fil)
                        vmdk_status, vmdk_output = ssh_client.run_command(command)

                        ssh_client.close()
                        if int(vmx_output.strip()) > 0:
                            file_type = 'VirtualMachine'
                        elif int(vmtx_output.strip()) > 0:
                            file_type = 'Template'
                        elif int(vmdk_output.strip()) > 0:
                            file_type = 'VMDK'
                            # delete_this = '~/' + datastore_path[0] + fil
                            # command = 'rm -rf {}'.format(delete_this)
                            # exit_status, output = ssh_client.run_command(command)
                            # logger.info(output)

                    file_path = '~/' + datastore_path[0] + fil
                    if file_path not in unregistered_files:
                        unregistered_files.append(file_path)
                        print('{}\t\t{}\t\t{}\t\t{}'.format(
                            hostname[0], file_path, file_type, number_of_files))

    except Exception as e:
        logger.error(e)
        return False
예제 #17
0
def test_verify_revert_snapshot(test_vm, provider, soft_assert, register_event, request):
    """Tests revert snapshot

    Metadata:
        test_flag: snapshot, provision
    """
    if provider.one_of(RHEVMProvider):
        snapshot1 = new_snapshot(test_vm, has_name=False)
    else:
        snapshot1 = new_snapshot(test_vm)

    ssh_kwargs = {
        'hostname': snapshot1.vm.provider.mgmt.get_ip_address(snapshot1.vm.name),
        'username': credentials[provider.data['full_template']['creds']]['username'],
        'password': credentials[provider.data['full_template']['creds']]['password']
    }

    ssh_client = SSHClient(**ssh_kwargs)
    # We need to wait for ssh to become available on the vm, it can take a while. Without
    # this wait, the ssh command would fail with 'port 22 not available' error.
    # Easiest way to solve this is just mask the exception with 'handle_exception = True'
    # and wait for successful completition of the ssh command.
    # The 'fail_func' ensures we close the connection that failed with exception.
    # Without this, the connection would hang there and wait_for would fail with timeout.
    wait_for(lambda: ssh_client.run_command('touch snapshot1.txt').rc == 0, num_sec=300,
             delay=20, handle_exception=True, fail_func=ssh_client.close())
    snapshot1.create()
    register_event(target_type='VmOrTemplate', target_name=test_vm.name,
                   event_type='vm_snapshot_complete')
    register_event(target_type='VmOrTemplate', target_name=test_vm.name,
                   event_type='vm_snapshot')
    ssh_client.run_command('touch snapshot2.txt')

    if provider.one_of(RHEVMProvider):
        snapshot2 = new_snapshot(test_vm, has_name=False)
    else:
        snapshot2 = new_snapshot(test_vm)
    snapshot2.create()

    if provider.one_of(RHEVMProvider):
        test_vm.power_control_from_cfme(option=test_vm.POWER_OFF, cancel=False)
        test_vm.wait_for_vm_state_change(
            desired_state=test_vm.STATE_OFF, timeout=900)

    snapshot1.revert_to()

    # Wait for the snapshot to become active
    logger.info('Waiting for vm %s to become active', snapshot1.name)
    wait_for(lambda: snapshot1.active, num_sec=300, delay=20, fail_func=sel.refresh)
    test_vm.wait_for_vm_state_change(desired_state=test_vm.STATE_OFF, timeout=720)
    test_vm.power_control_from_cfme(option=test_vm.POWER_ON, cancel=False)
    test_vm.wait_for_vm_state_change(desired_state=test_vm.STATE_ON, timeout=900)
    current_state = test_vm.find_quadicon().state
    soft_assert(current_state.startswith('currentstate-on'),
                "Quadicon state is {}".format(current_state))
    soft_assert(test_vm.provider.mgmt.is_vm_running(test_vm.name), "vm not running")
    wait_for(lambda: ssh_client.run_command('test -e snapshot1.txt').rc == 0,
             num_sec=400, delay=20, handle_exception=True, fail_func=ssh_client.close())
    try:
        result = ssh_client.run_command('test -e snapshot1.txt')
        assert not result.rc
        result = ssh_client.run_command('test -e snapshot2.txt')
        assert result.rc
        logger.info('Revert to snapshot %s successful', snapshot1.name)
    except:
        logger.exception('Revert to snapshot %s Failed', snapshot1.name)
    ssh_client.close()
def list_orphaned_files_per_host(host_name, host_datastore_urls, provider_key,
                                 vm_registered_files, unregistered_files):
    try:
        providers_data = cfme_data.get("management_systems", {})
        hosts = providers_data[provider_key]['hosts']
        hostname = [
            host['name'] for host in hosts if host_name in host['name']
        ]
        # check if hostname returned is ipaddress
        if not hostname:
            hostname = re.findall(r'[0-9]+(?:\.[0-9]+){3}', host_name)
        connect_kwargs = {
            'username': credentials['host_default']['username'],
            'password': credentials['host_default']['password'],
            'hostname': hostname[0]
        }
        for datastore_url in host_datastore_urls:
            datastore_path = re.findall(r'([^ds:`/*].*)', str(datastore_url))
            ssh_client = SSHClient(**connect_kwargs)
            command = 'ls ~/{}'.format(datastore_path[0])
            exit_status, output = ssh_client.run_command(command)
            ssh_client.close()
            files_in_datastore = output.splitlines(
            ) if exit_status == 0 else []
            for fil in files_in_datastore:
                if fil not in vm_registered_files:
                    file_type = 'UNKNOWN'
                    number_of_files = 0
                    command = 'test -d ~/{}/{}; echo $?'.format(
                        datastore_path[0], fil)
                    exit_status, output = ssh_client.run_command(command)
                    ssh_client.close()
                    file_extension = re.findall(r'.*\.(\w*)', fil)
                    if file_extension:
                        file_type = file_extension[0]
                        number_of_files = 1
                    if int(output.strip()) == 0:
                        command = 'ls ~/{}/{} | wc -l'.format(
                            datastore_path[0], fil)
                        exit_status, output = ssh_client.run_command(command)
                        number_of_files = output.strip()
                        command = 'find ~/{}/{} -name "*.vmx" | wc -l'.format(
                            datastore_path[0], fil)
                        vmx_status, vmx_output = ssh_client.run_command(
                            command)
                        command = 'find ~/{}/{} -name "*.vmtx" | wc -l'.format(
                            datastore_path[0], fil)
                        vmtx_status, vmtx_output = ssh_client.run_command(
                            command)
                        command = 'find ~/{}/{} -name "*.vmdk" | wc -l'.format(
                            datastore_path[0], fil)
                        vmdk_status, vmdk_output = ssh_client.run_command(
                            command)

                        ssh_client.close()
                        if int(vmx_output.strip()) > 0:
                            file_type = 'VirtualMachine'
                        elif int(vmtx_output.strip()) > 0:
                            file_type = 'Template'
                        elif int(vmdk_output.strip()) > 0:
                            file_type = 'VMDK'
                            # delete_this = '~/' + datastore_path[0] + fil
                            # command = 'rm -rf {}'.format(delete_this)
                            # exit_status, output = ssh_client.run_command(command)
                            # logger.info(output)

                    file_path = '~/' + datastore_path[0] + fil
                    if file_path not in unregistered_files:
                        unregistered_files.append(file_path)
                        print('{}\t\t{}\t\t{}\t\t{}'.format(
                            hostname[0], file_path, file_type,
                            number_of_files))

    except Exception as e:
        logger.error(e)
        return False
예제 #19
0
def test_verify_revert_snapshot(test_vm, provider, soft_assert, register_event,
                                request):
    """Tests revert snapshot

    Metadata:
        test_flag: snapshot, provision
    """
    snapshot1 = new_snapshot(test_vm)
    ip = snapshot1.vm.provider.mgmt.get_ip_address(snapshot1.vm.name)
    ssh_kwargs = {
        'username':
        credentials[provider.data['full_template']['creds']]['username'],
        'password':
        credentials[provider.data['full_template']['creds']]['password'],
        'hostname':
        ip
    }
    ssh_client = SSHClient(**ssh_kwargs)
    # We need to wait for ssh to become available on the vm, it can take a while. Without
    # this wait, the ssh command would fail with 'port 22 not available' error.
    # Easiest way to solve this is just mask the exception with 'handle_exception = True'
    # and wait for successful completition of the ssh command.
    # The 'fail_func' ensures we close the connection that failed with exception.
    # Without this, the connection would hang there and wait_for would fail with timeout.
    wait_for(lambda: ssh_client.run_command('touch snapshot1.txt').rc == 0,
             num_sec=300,
             delay=20,
             handle_exception=True,
             fail_func=ssh_client.close())
    snapshot1.create()
    register_event(target_type='VmOrTemplate',
                   target_name=test_vm.name,
                   event_type='vm_snapshot_complete')
    register_event(target_type='VmOrTemplate',
                   target_name=test_vm.name,
                   event_type='vm_snapshot')
    ssh_client.run_command('touch snapshot2.txt')
    snapshot2 = new_snapshot(test_vm)
    snapshot2.create()
    snapshot1.revert_to()
    # Wait for the snapshot to become active
    logger.info('Waiting for vm %s to become active', snapshot1.name)
    wait_for(snapshot1.wait_for_snapshot_active,
             num_sec=300,
             delay=20,
             fail_func=sel.refresh)
    test_vm.wait_for_vm_state_change(desired_state=test_vm.STATE_OFF,
                                     timeout=720)
    test_vm.power_control_from_cfme(option=test_vm.POWER_ON, cancel=False)
    navigate_to(test_vm.provider, 'Details')
    test_vm.wait_for_vm_state_change(desired_state=test_vm.STATE_ON,
                                     timeout=900)
    current_state = test_vm.find_quadicon().state
    soft_assert(current_state.startswith('currentstate-on'),
                "Quadicon state is {}".format(current_state))
    soft_assert(test_vm.provider.mgmt.is_vm_running(test_vm.name),
                "vm not running")
    wait_for(lambda: ssh_client.run_command('test -e snapshot1.txt').rc == 0,
             num_sec=400,
             delay=20,
             handle_exception=True,
             fail_func=ssh_client.close())
    try:
        result = ssh_client.run_command('test -e snapshot1.txt')
        assert not result.rc
        result = ssh_client.run_command('test -e snapshot2.txt')
        assert result.rc
        logger.info('Revert to snapshot %s successful', snapshot1.name)
    except:
        logger.exception('Revert to snapshot %s Failed', snapshot1.name)