<commit_before>#!/usr/bin/env python

# Copyright (c) 2018 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0

"""Ease deploying a single VM reachable via ssh

It offers a simple way to create all tenant network ressources + a VM for
advanced testcases (e.g. deploying an orchestrator).
"""

import logging
import tempfile
import time

import paramiko
from xtesting.core import testcase

from functest.core import tenantnetwork
from functest.utils import config


class VmReady1(tenantnetwork.TenantNetwork1):
    """Prepare a single VM (scenario1)

    It inherits from TenantNetwork1 which creates all network resources and
    prepares a future VM attached to that network.

    It ensures that all testcases inheriting from SingleVm1 could work
    without specific configurations (or at least read the same config data).
    """
    # pylint: disable=too-many-instance-attributes

    __logger = logging.getLogger(__name__)
    filename = '/home/opnfv/functest/images/cirros-0.4.0-x86_64-disk.img'
    image_format = 'qcow2'
    filename_alt = None
    image_alt_format = image_format
    visibility = 'private'
    extra_properties = None
    flavor_ram = 512
    flavor_vcpus = 1
    flavor_disk = 1
    flavor_alt_ram = 1024
    flavor_alt_vcpus = 1
    flavor_alt_disk = 1
    create_server_timeout = 60

    def __init__(self, **kwargs):
        if "case_name" not in kwargs:
            kwargs["case_name"] = 'vmready1'
        super(VmReady1, self).__init__(**kwargs)
        self.orig_cloud = self.cloud
        self.image = None
        self.flavor = None

    def publish_image(self, name=None):
        """Publish image

        It allows publishing multiple images for the child testcases. It forces
        the same configuration for all subtestcases.

        Returns: image

        Raises: expection on error
        """
        assert self.cloud
        image = self.cloud.create_image(
            name if name else '{}-img_{}'.format(self.case_name, self.guid),
            filename=getattr(
                config.CONF, '{}_image'.format(self.case_name),
                self.filename),
            meta=getattr(
                config.CONF, '{}_extra_properties'.format(self.case_name),
                self.extra_properties),
            disk_format=getattr(
                config.CONF, '{}_image_format'.format(self.case_name),
                self.image_format),
            visibility=getattr(
                config.CONF, '{}_visibility'.format(self.case_name),
                self.visibility))
        self.__logger.debug("image: %s", image)
        return image

    def publish_image_alt(self, name=None):
        """Publish alternative image

        It allows publishing multiple images for the child testcases. It forces
        the same configuration for all subtestcases.

        Returns: image

        Raises: expection on error
        """
        assert self.cloud
        image = self.cloud.create_image(
            name if name else '{}-img_alt_{}'.format(
                self.case_name, self.guid),
            filename=getattr(
                config.CONF, '{}_image_alt'.format(self.case_name),
                self.filename_alt),
            meta=getattr(
                config.CONF, '{}_extra_properties'.format(self.case_name),
                self.extra_properties),
            disk_format=getattr(
                config.CONF, '{}_image_alt_format'.format(self.case_name),
                self.image_format),
            visibility=getattr(
                config.CONF, '{}_visibility'.format(self.case_name),
                self.visibility))
        self.__logger.debug("image: %s", image)
        return image

    def create_flavor(self, name=None):
        """Create flavor

        It allows creating multiple flavors for the child testcases. It forces
        the same configuration for all subtestcases.

        Returns: flavor

        Raises: expection on error
        """
        assert self.orig_cloud
        flavor = self.orig_cloud.create_flavor(
            name if name else '{}-flavor_{}'.format(self.case_name, self.guid),
            getattr(config.CONF, '{}_flavor_ram'.format(self.case_name),
                    self.flavor_ram),
            getattr(config.CONF, '{}_flavor_vcpus'.format(self.case_name),
                    self.flavor_vcpus),
            getattr(config.CONF, '{}_flavor_disk'.format(self.case_name),
                    self.flavor_disk))
        self.__logger.debug("flavor: %s", flavor)
        self.orig_cloud.set_flavor_specs(
            flavor.id, getattr(config.CONF, 'flavor_extra_specs', {}))
        return flavor

    def create_flavor_alt(self, name=None):
        """Create flavor

        It allows creating multiple alt flavors for the child testcases. It
        forces the same configuration for all subtestcases.

        Returns: flavor

        Raises: expection on error
        """
        assert self.orig_cloud
        flavor = self.orig_cloud.create_flavor(
            name if name else '{}-flavor_alt_{}'.format(
                self.case_name, self.guid),
            getattr(config.CONF, '{}_flavor_alt_ram'.format(self.case_name),
                    self.flavor_alt_ram),
            getattr(config.CONF, '{}_flavor_alt_vcpus'.format(self.case_name),
                    self.flavor_alt_vcpus),
            getattr(config.CONF, '{}_flavor_alt_disk'.format(self.case_name),
                    self.flavor_alt_disk))
        self.__logger.debug("flavor: %s", flavor)
        self.orig_cloud.set_flavor_specs(
            flavor.id, getattr(config.CONF, 'flavor_extra_specs', {}))
        return flavor

    def boot_vm(self, name=None, **kwargs):
        """Boot the virtual machine

        It allows booting multiple machines for the child testcases. It forces
        the same configuration for all subtestcases.

        Returns: vm

        Raises: expection on error
        """
        assert self.cloud
        vm1 = self.cloud.create_server(
            name if name else '{}-vm_{}'.format(self.case_name, self.guid),
            image=self.image.id, flavor=self.flavor.id,
            auto_ip=False, wait=True, network=self.network.id,
            timeout=self.create_server_timeout, **kwargs)
        vm1 = self.cloud.wait_for_server(vm1, auto_ip=False)
        self.__logger.debug("vm: %s", vm1)
        return vm1

    def run(self, **kwargs):
        """Boot the new VM

        Here are the main actions:
        - publish the image
        - create the flavor

        Returns:
        - TestCase.EX_OK
        - TestCase.EX_RUN_ERROR on error
        """
        status = testcase.TestCase.EX_RUN_ERROR
        try:<commit_msg>Add helper to find string in console<commit_after>#!/usr/bin/env python

# Copyright (c) 2018 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0

"""Ease deploying a single VM reachable via ssh

It offers a simple way to create all tenant network ressources + a VM for
advanced testcases (e.g. deploying an orchestrator).
"""

import logging
import re
import tempfile
import time

import paramiko
from xtesting.core import testcase

from functest.core import tenantnetwork
from functest.utils import config


class VmReady1(tenantnetwork.TenantNetwork1):
    """Prepare a single VM (scenario1)

    It inherits from TenantNetwork1 which creates all network resources and
    prepares a future VM attached to that network.

    It ensures that all testcases inheriting from SingleVm1 could work
    without specific configurations (or at least read the same config data).
    """
    # pylint: disable=too-many-instance-attributes

    __logger = logging.getLogger(__name__)
    filename = '/home/opnfv/functest/images/cirros-0.4.0-x86_64-disk.img'
    image_format = 'qcow2'
    filename_alt = None
    image_alt_format = image_format
    visibility = 'private'
    extra_properties = None
    flavor_ram = 512
    flavor_vcpus = 1
    flavor_disk = 1
    flavor_alt_ram = 1024
    flavor_alt_vcpus = 1
    flavor_alt_disk = 1
    create_server_timeout = 60

    def __init__(self, **kwargs):
        if "case_name" not in kwargs:
            kwargs["case_name"] = 'vmready1'
        super(VmReady1, self).__init__(**kwargs)
        self.orig_cloud = self.cloud
        self.image = None
        self.flavor = None

    def publish_image(self, name=None):
        """Publish image

        It allows publishing multiple images for the child testcases. It forces
        the same configuration for all subtestcases.

        Returns: image

        Raises: expection on error
        """
        assert self.cloud
        image = self.cloud.create_image(
            name if name else '{}-img_{}'.format(self.case_name, self.guid),
            filename=getattr(
                config.CONF, '{}_image'.format(self.case_name),
                self.filename),
            meta=getattr(
                config.CONF, '{}_extra_properties'.format(self.case_name),
                self.extra_properties),
            disk_format=getattr(
                config.CONF, '{}_image_format'.format(self.case_name),
                self.image_format),
            visibility=getattr(
                config.CONF, '{}_visibility'.format(self.case_name),
                self.visibility))
        self.__logger.debug("image: %s", image)
        return image

    def publish_image_alt(self, name=None):
        """Publish alternative image

        It allows publishing multiple images for the child testcases. It forces
        the same configuration for all subtestcases.

        Returns: image

        Raises: expection on error
        """
        assert self.cloud
        image = self.cloud.create_image(
            name if name else '{}-img_alt_{}'.format(
                self.case_name, self.guid),
            filename=getattr(
                config.CONF, '{}_image_alt'.format(self.case_name),
                self.filename_alt),
            meta=getattr(
                config.CONF, '{}_extra_properties'.format(self.case_name),
                self.extra_properties),
            disk_format=getattr(
                config.CONF, '{}_image_alt_format'.format(self.case_name),
                self.image_format),
            visibility=getattr(
                config.CONF, '{}_visibility'.format(self.case_name),
                self.visibility))
        self.__logger.debug("image: %s", image)
        return image

    def create_flavor(self, name=None):
        """Create flavor

        It allows creating multiple flavors for the child testcases. It forces
        the same configuration for all subtestcases.

        Returns: flavor

        Raises: expection on error
        """
        assert self.orig_cloud
        flavor = self.orig_cloud.create_flavor(
            name if name else '{}-flavor_{}'.format(self.case_name, self.guid),
            getattr(config.CONF, '{}_flavor_ram'.format(self.case_name),
                    self.flavor_ram),
            getattr(config.CONF, '{}_flavor_vcpus'.format(self.case_name),
                    self.flavor_vcpus),
            getattr(config.CONF, '{}_flavor_disk'.format(self.case_name),
                    self.flavor_disk))
        self.__logger.debug("flavor: %s", flavor)
        self.orig_cloud.set_flavor_specs(
            flavor.id, getattr(config.CONF, 'flavor_extra_specs', {}))
        return flavor

    def create_flavor_alt(self, name=None):
        """Create flavor

        It allows creating multiple alt flavors for the child testcases. It
        forces the same configuration for all subtestcases.

        Returns: flavor

        Raises: expection on error
        """
        assert self.orig_cloud
        flavor = self.orig_cloud.create_flavor(
            name if name else '{}-flavor_alt_{}'.format(
                self.case_name, self.guid),
            getattr(config.CONF, '{}_flavor_alt_ram'.format(self.case_name),
                    self.flavor_alt_ram),
            getattr(config.CONF, '{}_flavor_alt_vcpus'.format(self.case_name),
                    self.flavor_alt_vcpus),
            getattr(config.CONF, '{}_flavor_alt_disk'.format(self.case_name),
                    self.flavor_alt_disk))
        self.__logger.debug("flavor: %s", flavor)
        self.orig_cloud.set_flavor_specs(
            flavor.id, getattr(config.CONF, 'flavor_extra_specs', {}))
        return flavor

    def boot_vm(self, name=None, **kwargs):
        """Boot the virtual machine

        It allows booting multiple machines for the child testcases. It forces
        the same configuration for all subtestcases.

        Returns: vm

        Raises: expection on error
        """
        assert self.cloud
        vm1 = self.cloud.create_server(
            name if name else '{}-vm_{}'.format(self.case_name, self.guid),
            image=self.image.id, flavor=self.flavor.id,
            auto_ip=False, wait=True, network=self.network.id,
            timeout=self.create_server_timeout, **kwargs)
        vm1 = self.cloud.wait_for_server(vm1, auto_ip=False)
        self.__logger.debug("vm: %s", vm1)
        return vm1

    def check_regex_in_console(self, name, regex=' login: ', loop=1):
        """Wait for specific message in console

        Returns: True or False on errors
        """
        assert self.cloud
        for iloop in range(loop):
            console = self.cloud.get_server_console(name)
            self.__logger.debug("console: \n%s", console)
            if re.search(regex, console):
                self.__logger.debug("regex found: ''%s' in console", regex)
                return True
            else:
                self.__logger.debug(
                    "try %s: cannot find regex '%s' in console",
                    iloop + 1, regex)
                time.sleep(10)
        self.__logger.error("cannot find regex '%s' in console", regex)
        return False

    def run(self, **kwargs):
        """Boot the new VM

        Here are the main actions:
        - publish the image
        - create the flavor

        Returns:
        - TestCase.EX_OK
        - TestCase.EX_RUN_ERROR on error
        """
        status = testcase.TestCase.EX_RUN_ERROR
        try:
{'fraction_non_alphanumeric': 0.09484649122807018, 'fraction_numerical': 0.005893640350877193, 'mean_word_length': 2.211487676056338, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3275729', 'n_tokens_mistral': 4210, 'n_tokens_neox': 4036, 'n_words': 1063}