Beispiel #1
0
    def _launch_instance(self):
        """
        Create new test instance in a resource group with the same name.
        """
        self.running_instance_id = ipa_utils.generate_instance_name(
            'azure-img-proof-test'
        )
        self.logger.debug('ID of instance: %s' % self.running_instance_id)
        self._set_default_resource_names()

        try:
            # Try block acts as a transaction. If an exception is raised
            # attempt to cleanup the resource group and all created resources.

            # Create resource group.
            self._create_resource_group(self.region, self.running_instance_id)

            if self.subnet_id:
                # Use existing vnet/subnet.
                subnet = self.network.subnets.get(
                    self.vnet_resource_group, self.vnet_name, self.subnet_id
                )
            else:
                self.subnet_id = ''.join([self.running_instance_id, '-subnet'])
                self.vnet_name = ''.join([self.running_instance_id, '-vnet'])

                # Create new vnet
                self._create_virtual_network(
                    self.region, self.running_instance_id, self.vnet_name
                )

                # Create new subnet in new vnet
                subnet = self._create_subnet(
                    self.running_instance_id, self.subnet_id, self.vnet_name
                )

            # Setup interface and public ip in resource group.
            public_ip = self._create_public_ip(
                self.public_ip_name, self.running_instance_id, self.region
            )
            interface = self._create_network_interface(
                self.ip_config_name, self.nic_name, public_ip, self.region,
                self.running_instance_id, subnet, self.accelerated_networking
            )

            # Get dictionary of VM parameters and create instance.
            vm_config = self._create_vm_config(interface)
            self._create_vm(vm_config)
        except Exception:
            try:
                self._terminate_instance()
            except Exception:
                pass
            raise
        else:
            # Ensure VM is in the running state.
            self._wait_on_instance('VM running', timeout=self.timeout)
Beispiel #2
0
    def _launch_instance(self):
        """Launch an instance of the given image."""
        self.display_name = ipa_utils.generate_instance_name('oci-ipa-test')

        try:
            if not self.subnet_id:
                self.vcn = self._create_vcn(self.display_name)
                subnet = self._create_subnet(
                    self.compartment_id,
                    self.availability_domain,
                    self.vcn,
                    self.display_name
                )
                self._create_internet_gateway(
                    self.compartment_id,
                    self.vcn,
                    self.display_name
                )
                self.subnet_id = subnet.id

            instance_metadata = {
                'ssh_authorized_keys': self._get_ssh_public_key()
            }

            launch_instance_details = oci.core.models.LaunchInstanceDetails(
                display_name=self.display_name,
                compartment_id=self.compartment_id,
                availability_domain=self.availability_domain,
                shape=self.instance_type or OCI_DEFAULT_TYPE,
                metadata=instance_metadata,
                source_details=oci.core.models.InstanceSourceViaImageDetails(
                    image_id=self.image_id
                ),
                create_vnic_details=oci.core.models.CreateVnicDetails(
                    subnet_id=self.subnet_id
                )
            )

            response = self.compute_client.launch_instance(
                launch_instance_details
            )
            instance = response.data
        except Exception as error:
            try:
                self._terminate_instance()
            except Exception:
                pass

            if hasattr(error, 'message'):
                raise OCICloudException(error.message)
            else:
                raise
        else:
            self.running_instance_id = instance.id
            self.logger.debug('ID of instance: %s' % self.running_instance_id)
            self._wait_on_instance('RUNNING', self.timeout)
Beispiel #3
0
    def _generate_instance_name(self):
        """
        Generate a new instance name with a random string appended.

        If a prefix is supplied add to the beginning of instance name.
        """
        instance_name = ipa_utils.generate_instance_name('img-proof')

        if self.prefix_name:
            instance_name = '-'.join([self.prefix_name, instance_name])

        return instance_name
Beispiel #4
0
    def _launch_instance(self):
        """Launch an instance of the given image."""
        resource = self._connect()

        instance_name = ipa_utils.generate_instance_name('ec2-img-proof-test')
        kwargs = {
            'InstanceType':
            self.instance_type or EC2_DEFAULT_TYPE,
            'ImageId':
            self.image_id,
            'MaxCount':
            1,
            'MinCount':
            1,
            'TagSpecifications': [{
                'ResourceType':
                'instance',
                'Tags': [{
                    'Key': 'Name',
                    'Value': instance_name
                }]
            }]
        }

        if self.zone:
            kwargs['Placement'] = {'AvailabilityZone': self.zone}

        if self.ssh_key_name:
            kwargs['KeyName'] = self.ssh_key_name
        else:
            kwargs['UserData'] = self._get_user_data()

        if self.subnet_id:
            kwargs['SubnetId'] = self.subnet_id

        if self.security_group_id:
            kwargs['SecurityGroupIds'] = [self.security_group_id]

        try:
            instances = resource.create_instances(**kwargs)
        except Exception as error:
            raise EC2CloudException(
                'Unable to create instance: {0}.'.format(error))

        self.running_instance_id = instances[0].instance_id
        self.logger.debug('ID of instance: %s' % self.running_instance_id)
        self._wait_on_instance('running', self.timeout)
Beispiel #5
0
    def _launch_instance(self):
        """Launch an instance of the given image."""
        self.running_instance_id = ipa_utils.generate_instance_name(
            'gce-img-proof-test')
        self.logger.debug('ID of instance: %s' % self.running_instance_id)

        machine_type = self._get_instance_type(self.instance_type
                                               or GCE_DEFAULT_TYPE)['selfLink']
        source_image = self._get_image(self.image_id)['selfLink']
        network_interfaces = [self._get_network_config(self.subnet_id)]

        kwargs = {
            'instance_name': self.running_instance_id,
            'machine_type': machine_type,
            'service_account_email': self.service_account_email,
            'source_image': source_image,
            'ssh_key': self.ssh_public_key,
            'network_interfaces': network_interfaces
        }

        if self.enable_uefi:
            kwargs['shielded_instance_config'] = \
                self.get_shielded_instance_config(
                    enable_secure_boot=self.enable_secure_boot
                )

        try:
            response = self.compute_driver.instances().insert(
                project=self.service_account_project,
                zone=self.region,
                body=self.get_instance_config(**kwargs)).execute()
        except Exception as error:
            with suppress(AttributeError):
                # In python 3.5 content is bytes
                error.content = error.content.decode()

            error_obj = json.loads(error.content)['error']

            try:
                message = error_obj['message']
            except (AttributeError, KeyError):
                message = 'Unknown exception.'

            if error_obj['code'] == 412:
                # 412 is conditionNotmet
                error_class = IpaRetryableError
            else:
                error_class = GCECloudException

            raise error_class('Failed to launch instance: {message}'.format(
                message=message)) from error

        operation = self._wait_on_operation(response['name'])

        if 'error' in operation and operation['error'].get('errors'):
            error = operation['error']['errors'][0]

            if error['code'] in ('QUOTA_EXCEEDED', 'PRECONDITION_FAILED'):
                error_class = IpaRetryableError
            else:
                error_class = GCECloudException

            raise error_class('Failed to launch instance: {message}'.format(
                message=error['message']))

        self._wait_on_instance('RUNNING', timeout=self.timeout)
Beispiel #6
0
def test_utils_generate_instance_name():
    """Test generate instance name method."""
    name = ipa_utils.generate_instance_name('azure-img-proof-test')
    assert len(name) == 26
    assert name.startswith('azure-img-proof-test-')