示例#1
0
 def refresh(self):
     """
     Re-pull the data for this stack
     """
     try:
         self.raw = self._api.describe_stacks(
             StackName=self._uuid)['Stacks'][0]
     except BotoServerError as error:
         if error.status == 404:
             raise NotFoundError('stack {}'.format(self._uuid))
         else:
             raise
     except IndexError:
         raise NotFoundError('stack {}'.format(self._uuid))
     return self.raw
示例#2
0
 def get_template(self, name, force=False):
     vm = self._get_vm_or_template(name, force)
     if not vm:
         raise NotFoundError("template: {}".format(name))
     if isinstance(vm, VMWareVirtualMachine):
         raise Exception("Looking for template but found VM of name '{}'".format(name))
     return vm
示例#3
0
 def get_cluster(self, cluster_name):
     try:
         return self.api.system_service().clusters_service().list(
             search='name={}'.format(cluster_name))[0]
     except IndexError:
         raise NotFoundError(
             'Cluster not found with name {}'.format(cluster_name))
示例#4
0
    def _nic_action(self, nic, network_name, interface='VIRTIO', on_boot=True,
                   vnic_profile=None, nic_service=None, action='add'):
        """Call an action on nic_service, could be a vmnic or vmnics service
        example, action 'add' on vmnicsservice, or 'update' on VmNicService
        currently written for nic actions on the service, though other actions are available

        Args:
            nic: the Nic object itself, could be existing on the vm or not
            network_name: string name of the network, also default for vnic_profile name if empty
            interface: string interface type for ovirt, interfaces are resolved to a specific type
            on_boot: boolean, kwarg for nic options
            vnic_profile: string name of the vnic_profile, network_name is used if empty
            nic_service: the VmNicsService or VmNicService, defaults to VmNicsService
            action: string action method to call on the service, defaults to add (VmNicsService)
        """
        # TODO take kwargs and match them to types.Nic attributes so callers can set any property
        service = nic_service or self.api.nics_service()
        nic.network = self._get_network(network_name)
        vnic_name = vnic_profile or network_name
        vnic_list = self.system.api.system_service().vnic_profiles_service().list()
        try:
            nic.vnic_profile = [v_nic for v_nic in vnic_list if v_nic.name == vnic_name][0]
        except IndexError:
            raise NotFoundError('Unable to find vnic_profile matching name {}'.format(vnic_name))
        nic.interface = getattr(types.NicInterface, interface)
        nic.on_boot = on_boot
        # service attribute should be method we can call and pass the nic to
        getattr(service, action)(nic)
示例#5
0
 def get_template_from_storage_domain(self, template_name,
                                      storage_domain_name):
     sds = self._get_storage_domain_service(storage_domain_name)
     for template in sds.templates_service().list(unregistered=False):
         if template.name == template_name:
             return RHEVMTemplate(system=self, uuid=template.id)
     raise NotFoundError('template {} in storage domain {}'.format(
         template_name, storage_domain_name))
示例#6
0
 def _get_nic_service(self, nic_name):
     for nic in self.api.nics_service().list():
         if nic.name == nic_name:
             return self.api.nics_service().nic_service(nic.id)
     else:
         raise NotFoundError(
             'Unable to find NicService for nic {} on {}'.format(
                 nic_name, self))
示例#7
0
 def _get_network(self, network_name):
     """retreive a network object by name"""
     networks = self.system.api.system_service().networks_service().list(
         search='name={}'.format(network_name))
     try:
         return networks[0]
     except IndexError:
         raise NotFoundError('No match for network by "name={}"'.format(network_name))
示例#8
0
 def get_vnic_profile(self, profile_name):
     """ The vnic_profiles that exist on the system, where the key is the vnic_profile name."""
     try:
         return next(vnic for vnic in self.list_vnic_profiles()
                     if vnic.name == profile_name)
     except StopIteration:
         raise NotFoundError(
             'Unable to find vnic_profile matching name {}'.format(
                 profile_name))
示例#9
0
    def upload_file_to_bucket(self, bucket_name, file_path):
        def handle_progressless_iter(error, progressless_iters):
            if progressless_iters > NUM_RETRIES:
                self.logger.info(
                    'Failed to make progress for too many consecutive iterations.'
                )
                raise error

            sleeptime = random.random() * (2**progressless_iters)
            self.logger.info(
                'Caught exception (%s). Sleeping for %d seconds before retry #%d.',
                str(error), sleeptime, progressless_iters)

            time.sleep(sleeptime)

        self.logger.info('Building upload request...')
        media = MediaFileUpload(file_path, chunksize=CHUNKSIZE, resumable=True)
        if not media.mimetype():
            media = MediaFileUpload(file_path,
                                    DEFAULT_MIMETYPE,
                                    resumable=True)

        blob_name = os.path.basename(file_path)
        if not self.bucket_exists(bucket_name):
            self.logger.error("Bucket '%s' doesn't exist", bucket_name)
            raise NotFoundError("bucket {}".format(bucket_name))

        request = self._storage.objects().insert(bucket=bucket_name,
                                                 name=blob_name,
                                                 media_body=media)
        self.logger.info('Uploading file: %s, to bucket: %s, blob: %s',
                         file_path, bucket_name, blob_name)

        progressless_iters = 0
        response = None
        while response is None:
            error = None
            try:
                progress, response = request.next_chunk()
                if progress:
                    self.logger.info('Upload progress: %d%%',
                                     100 * progress.progress())
            except errors.HttpError as error:
                if error.resp.status < 500:
                    raise
            except RETRYABLE_ERRORS as error:
                if error:
                    progressless_iters += 1
                    handle_progressless_iter(error, progressless_iters)
                else:
                    progressless_iters = 0

        self.logger.info('Upload complete!')
        self.logger.info('Uploaded Object:')
        self.logger.info(json_dumps(response, indent=2))
        return (True, blob_name)
示例#10
0
 def get_network(self, name=None, id=None):
     if not name and not id or name and id:
         raise ValueError("Either name or id must be set and not both!")
     networks = self.find_networks(name=name, id=id)
     name_or_id = name if name else id
     if not networks:
         raise NotFoundError(
             "Network with name {} not found".format(name_or_id))
     elif len(networks) > 1:
         raise MultipleItemsError(
             "Multiple networks with name {} found".format(name_or_id))
     return networks[0]
示例#11
0
    def get_registry_data(self):
        # Returns dict with docker registry url and token
        data = self.ecr_connection.get_authorization_token()
        if data['ResponseMetadata']['HTTPStatusCode'] >= 400:
            raise NotFoundError(
                "couldn't get registry details. please check environment setup"
            )

        try:
            first_registry = data['authorizationData'][0]
            username, password = base64.b64decode(
                first_registry['authorizationToken']).split(':')
            return {
                'username': username,
                'password': password,
                'registry': first_registry['proxyEndpoint']
            }
        except (IndexError, KeyError):
            raise NotFoundError(
                "couldn't get registry details. please check environment setup"
            )
示例#12
0
    def get_stack(self, name):
        """
        Get single stack if it exists

        Args:
            name: unique name or id of the stack
        Returns:
            CloudFormationStack object
        """
        stacks = self.find_stacks(name)
        if not stacks:
            raise NotFoundError("Stack with name {} not found".format(name))
        elif len(stacks) > 1:
            raise MultipleItemsError(
                "Multiple stacks with name {} found".format(name))
        return stacks[0]
示例#13
0
    def get_template(self, name=None, uuid=None):
        """
        Get a single template by name or ID

        Returns:
            wrapanapi.systems.rhevm.RHEVMTemplate
        Raises:
            MultipleItemsError if multiple templates found with this name/id
            NotFoundError if template not found with this name/id
        """
        matches = self.find_templates(name=name, uuid=uuid)
        if not matches:
            raise NotFoundError('Template with name={}, id={}'.format(
                name, uuid))
        if len(matches) > 1:
            raise MultipleItemsError(
                'Found multiple matches for template with name={}, id={}'.
                format(name, uuid))
        return matches[0]