Exemple #1
0
def find_image(context, image_ident, image_tag):
    matches = find_images(context, image_ident, exact_match=True)
    LOG.debug('Found matches %s ', matches)

    # added for glance image tag and name support
    match = []
    for i in range(len(matches)):
        if matches[i]['tags']:
            if len(image_tag) < len(matches[i]['tags']):
                data1, data2 = image_tag, matches[i]['tags']
            else:
                data1, data2 = matches[i]['tags'], image_tag
            if all(map(lambda x: x in data1, data2)):
                match.append(matches[i])
        else:
            if matches[i]['tags'] == image_tag:
                match.append(matches[i])
    if len(match) == 0:
        raise exception.ImageNotFound(image=image_ident)
    if len(match) > 1:
        msg = ("Multiple images exist with same name "
               "%(image_ident)s. Please use the image id "
               "instead.") % {
                   'image_ident': image_ident
               }
        raise exception.Conflict(msg)
    return match[0]
Exemple #2
0
    def _check_security_group(self, context, security_group, container):
        if security_group.get("uuid"):
            security_group_id = security_group.get("uuid")
            if not uuidutils.is_uuid_like(security_group_id):
                raise exception.InvalidUUID(uuid=security_group_id)
            if security_group_id in container.security_groups:
                msg = _("security_group %s already present in container") % \
                    security_group_id
                raise exception.InvalidValue(msg)
        else:
            security_group_ids = utils.get_security_group_ids(
                context, [security_group['name']])
            if len(security_group_ids) > len(security_group):
                msg = _("Multiple security group matches "
                        "found for name %(name)s, use an ID "
                        "to be more specific. ") % security_group
                raise exception.Conflict(msg)
            else:
                security_group_id = security_group_ids[0]
        container_ports_detail = utils.list_ports(context, container)

        for container_port_detail in container_ports_detail:
            if security_group_id in container_port_detail['security_groups']:
                msg = _("security_group %s already present in container") % \
                    list(security_group.values())[0]
                raise exception.InvalidValue(msg)
        return security_group_id
Exemple #3
0
def handle_not_found(e, context, container, do_not_raise=False):
    container.status = consts.ERROR
    container.status_reason = six.text_type(e)
    container.save(context)
    if do_not_raise:
        return

    raise exception.Conflict(message=_('the container is in Error state'))
Exemple #4
0
 def get_available_network(self):
     search_opts = {'tenant_id': self.context.project_id, 'shared': False}
     nets = self.list_networks(**search_opts).get('networks', [])
     if not nets:
         raise exception.Conflict(
             _("There is no neutron network available"))
     nets.sort(key=lambda x: x['created_at'])
     return nets[0]
Exemple #5
0
 def get_image_by_name_or_id(self, image_ident):
     """Get an image by name or ID."""
     try:
         return self.client().glance.find_image(image_ident)
     except exceptions.NotFound as e:
         raise exception.ImageNotFound(six.text_type(e))
     except exceptions.NoUniqueMatch as e:
         raise exception.Conflict(six.text_type(e))
Exemple #6
0
 def get_compute_node_by_hostname(self, context, hostname):
     query = model_query(models.ComputeNode)
     query = query.filter_by(hostname=hostname)
     try:
         return query.one()
     except NoResultFound:
         raise exception.ComputeNodeNotFound(compute_node=hostname)
     except MultipleResultsFound:
         raise exception.Conflict('Multiple compute nodes exist with same '
                                  'hostname. Please use the uuid instead.')
Exemple #7
0
 def execute_run(self, exec_id, command):
     with docker_utils.docker_client() as docker:
         try:
             with eventlet.Timeout(CONF.docker.execute_timeout):
                 output = docker.exec_start(exec_id, False, False, False)
         except eventlet.Timeout:
             raise exception.Conflict(_(
                 "Timeout on executing command: %s") % command)
         inspect_res = docker.exec_inspect(exec_id)
         return output, inspect_res['ExitCode']
Exemple #8
0
 def decorated_function(*args, **kwargs):
     context = args[1]
     container = args[2]
     try:
         return function(*args, **kwargs)
     except exception.DockerError as e:
         if is_not_found(e):
             handle_not_found(e, context, container)
         if is_conflict(e):
             raise exception.Conflict(_("%s") % str(e))
         raise
Exemple #9
0
 def _get_resource_provider_by_name(self, context, provider_name):
     query = model_query(models.ResourceProvider)
     query = query.filter_by(name=provider_name)
     try:
         return query.one()
     except NoResultFound:
         raise exception.ResourceProviderNotFound(
             resource_provider=provider_name)
     except MultipleResultsFound:
         raise exception.Conflict('Multiple resource providers exist with '
                                  'same name. Please use the uuid instead.')
Exemple #10
0
def find_image(context, image_ident):
    matches = find_images(context, image_ident, exact_match=True)
    LOG.debug('Found matches %s ' % matches)
    if len(matches) == 0:
        raise exception.ImageNotFound(image=image_ident)
    if len(matches) > 1:
        msg = ("Multiple images exist with same name "
               "%(image_ident)s. Please use the image id "
               "instead.") % {'image_ident': image_ident}
        raise exception.Conflict(msg)
    return matches[0]
Exemple #11
0
 def get_container_by_name(self, context, container_name):
     query = model_query(models.Container)
     query = self._add_tenant_filters(context, query)
     query = query.filter_by(name=container_name)
     try:
         return query.one()
     except NoResultFound:
         raise exception.ContainerNotFound(container=container_name)
     except MultipleResultsFound:
         raise exception.Conflict('Multiple containers exist with same '
                                  'name. Please use the container uuid '
                                  'instead.')
Exemple #12
0
 def get_capsule_by_meta_name(self, context, capsule_name):
     query = model_query(models.Capsule)
     query = self._add_project_filters(context, query)
     query = query.filter_by(meta_name=capsule_name)
     try:
         return query.one()
     except NoResultFound:
         raise exception.CapsuleNotFound(capsule=capsule_name)
     except MultipleResultsFound:
         raise exception.Conflict('Multiple capsules exist with same '
                                  'name. Please use the capsule uuid '
                                  'instead.')
Exemple #13
0
def handle_not_found(e, context, container, do_not_raise=False):
    if container.auto_remove:
        container.status = consts.DELETED
    else:
        container.status = consts.ERROR
        container.status_reason = six.text_type(e)
    container.save(context)
    if do_not_raise:
        return

    raise exception.Conflict(
        message=_("Cannot act on container in '%s' state") % container.status)
Exemple #14
0
    def container_create(self, context, new_container, extra_spec,
                         requested_networks, requested_volumes, run,
                         pci_requests=None):
        try:
            host_state = self._schedule_container(context, new_container,
                                                  extra_spec)
        except exception.NoValidHost:
            new_container.status = consts.ERROR
            new_container.status_reason = _(
                "There are not enough hosts available.")
            new_container.save(context)
            return
        except Exception:
            new_container.status = consts.ERROR
            new_container.status_reason = _("Unexpected exception occurred.")
            new_container.save(context)
            raise

        # NOTE(mkrai): Intent here is to check the existence of image
        # before proceeding to create container. If image is not found,
        # container create will fail with 400 status.
        if CONF.api.enable_image_validation:
            try:
                images = self.rpcapi.image_search(
                    context, new_container.image,
                    new_container.image_driver, True, new_container.registry,
                    host_state['host'])
                if not images:
                    raise exception.ImageNotFound(image=new_container.image)
                if len(images) > 1:
                    raise exception.Conflict('Multiple images exist with same '
                                             'name. Please use the container '
                                             'uuid instead.')
            except exception.OperationNotSupported:
                LOG.info("Skip validation since search is not supported for "
                         "image '%(image)s' and image driver '%(driver)s'.",
                         {'image': new_container.image,
                          'driver': new_container.image_driver})
            except exception.ReferenceInvalidFormat:
                raise exception.InvalidValue(_("The format of image name '%s' "
                                               "is invalid.")
                                             % new_container.image)
            except Exception as e:
                LOG.warning("Skip validation since image search failed with "
                            "unexpected exception: %s", str(e))

        self._record_action_start(context, new_container,
                                  container_actions.CREATE)
        self.rpcapi.container_create(context, host_state['host'],
                                     new_container, host_state['limits'],
                                     requested_networks, requested_volumes,
                                     run, pci_requests)
Exemple #15
0
    def search_volume(self, volume):
        if uuidutils.is_uuid_like(volume):
            volume = self.cinder.volumes.get(volume)
        else:
            try:
                volume = self.cinder.volumes.find(name=volume)
            except cinder_exception.NotFound:
                raise exception.VolumeNotFound(volume=volume)
            except cinder_exception.NoUniqueMatch:
                raise exception.Conflict(
                    _('Multiple cinder volumes exist with same name. '
                      'Please use the uuid instead.'))

        return volume
Exemple #16
0
    def rename(self, container_id, name):
        """rename an existing container.

        :param patch: a json PATCH document to apply to this container.
        """
        container = _get_container(container_id)
        check_policy_on_container(container.as_dict(), "container:rename")
        if container.name == name:
            raise exception.Conflict('The new name for the container is the '
                                     'same as the old name.')
        container.name = name
        context = pecan.request.context
        container.save(context)
        return view.format_container(pecan.request.host_url, container)
Exemple #17
0
    def container_create(self,
                         context,
                         new_container,
                         extra_spec,
                         requested_networks,
                         requested_volumes,
                         run,
                         pci_requests=None):
        try:
            host_state = self._schedule_container(context, new_container,
                                                  extra_spec)
        except exception.NoValidHost:
            new_container.status = consts.ERROR
            new_container.status_reason = _(
                "There are not enough hosts available.")
            new_container.save(context)
            return
        except Exception:
            new_container.status = consts.ERROR
            new_container.status_reason = _("Unexpected exception occurred.")
            new_container.save(context)
            raise

        # NOTE(mkrai): Intent here is to check the existence of image
        # before proceeding to create container. If image is not found,
        # container create will fail with 400 status.
        if CONF.api.enable_image_validation:
            try:
                images = self.rpcapi.image_search(context, new_container.image,
                                                  new_container.image_driver,
                                                  True, host_state['host'])
                if not images:
                    raise exception.ImageNotFound(image=new_container.image)
                if len(images) > 1:
                    raise exception.Conflict('Multiple images exist with same '
                                             'name. Please use the container '
                                             'uuid instead.')
            except Exception as e:
                new_container.status = consts.ERROR
                new_container.status_reason = str(e)
                new_container.save(context)
                raise

        self._record_action_start(context, new_container,
                                  container_actions.CREATE)
        self.rpcapi.container_create(context, host_state['host'],
                                     new_container, host_state['limits'],
                                     requested_networks, requested_volumes,
                                     run, pci_requests)
Exemple #18
0
    def get_neutron_port(self, port):
        if uuidutils.is_uuid_like(port):
            ports = self.list_ports(id=port)['ports']
        else:
            ports = self.list_ports(name=port)['ports']

        if len(ports) == 0:
            raise exception.PortNotFound(port=port)
        elif len(ports) > 1:
            raise exception.Conflict(_(
                'Multiple neutron ports exist with same name. '
                'Please use the uuid instead.'))

        port = ports[0]
        return port
Exemple #19
0
    def get_neutron_network(self, network):
        if uuidutils.is_uuid_like(network):
            networks = self.list_networks(id=network)['networks']
        else:
            networks = self.list_networks(name=network)['networks']

        if len(networks) == 0:
            raise exception.NetworkNotFound(network=network)
        elif len(networks) > 1:
            raise exception.Conflict(_(
                'Multiple neutron networks exist with same name. '
                'Please use the uuid instead.'))

        network = networks[0]
        return network
Exemple #20
0
    def rename(self, container_ident, name):
        """Rename an existing container.

        :param container_ident: UUID or Name of a container.
        :param name: a new name for this container.
        """
        container = utils.get_container(container_ident)
        check_policy_on_container(container.as_dict(), "container:rename")
        if container.name == name:
            raise exception.Conflict('The new name for the container is the '
                                     'same as the old name.')
        container.name = name
        context = pecan.request.context
        container.save(context)
        return view.format_container(context, pecan.request.host_url,
                                     container)
Exemple #21
0
    def _get_resource_class_by_name(self, context, name):
        try:
            rcs = self.list_resource_classes(context, filters={'name': name})
        except etcd.EtcdKeyNotFound:
            raise exception.ResourceClassNotFound(resource_class=name)
        except Exception as e:
            LOG.error('Error occurred while retriving resource class: %s',
                      six.text_type(e))
            raise

        if len(rcs) > 1:
            raise exception.Conflict('Multiple resource classes exist with '
                                     'same name. Please use uuid instead.')
        elif len(rcs) == 0:
            raise exception.ResourceClassNotFound(resource_class=name)

        return rcs[0]
Exemple #22
0
 def get_available_network(self):
     #search_opts = {'tenant_id': self.context.project_id, 'shared': False}
     search_opts = {'tenant_id': self.context.project_id}
     #nets = self.list_networks(**search_opts).get('networks', [])
     #nets_return = self.list_networks("")
     #LOG.debug('get_available_network return=%s' % (nets_return.__dict__))
     #nets_return2=self.list_networks(**search_opts)['networks']
     #for p in nets_return2:
     #    LOG.debug('get_available_network nets_subnet=%s' % (p))
     nets = self.list_networks().get('networks', [])
     for p in nets:
         LOG.debug('get_available_network nets=%s' % (p))
     if not nets:
         raise exception.Conflict(
             _("There is no neutron network available"))
     nets.sort(key=lambda x: x['created_at'])
     return nets[0]
Exemple #23
0
 def _check_security_group(self, context, security_group):
     neutron_api = neutron.NeutronAPI(context)
     try:
         return neutron_api.find_resourceid_by_name_or_id(
             'security_group', security_group['name'], context.project_id)
     except n_exc.NeutronClientNoUniqueMatch as e:
         msg = _("Multiple security group matches found for name "
                 "%(name)s, use an ID to be more specific.") % {
             'name': security_group['name']}
         raise exception.Conflict(msg)
     except n_exc.NeutronClientException as e:
         if e.status_code == 404:
             msg = _("Security group %(name)s not found.") % {
                 'name': security_group['name']}
             raise exception.InvalidValue(msg)
         else:
             raise
Exemple #24
0
    def get_container_by_name(self, context, container_name):
        try:
            filters = self._add_project_filters(context,
                                                {'name': container_name})
            containers = self.list_containers(context, filters=filters)
        except etcd.EtcdKeyNotFound:
            raise exception.ContainerNotFound(container=container_name)
        except Exception as e:
            LOG.error('Error occurred while retrieving container: %s',
                      six.text_type(e))
            raise

        if len(containers) > 1:
            raise exception.Conflict('Multiple containers exist with same '
                                     'name. Please use the container uuid '
                                     'instead.')
        elif len(containers) == 0:
            raise exception.ContainerNotFound(container=container_name)

        return containers[0]
Exemple #25
0
    def get_capsule_by_meta_name(self, context, capsule_meta_name):
        try:
            filters = self._add_project_filters(
                context, {'meta_name': capsule_meta_name})
            capsules = self.list_capsules(context, filters=filters)
        except etcd.EtcdKeyNotFound:
            raise exception.CapsuleNotFound(capsule=capsule_meta_name)
        except Exception as e:
            LOG.error('Error occurred while retrieving capsule: %s',
                      six.text_type(e))
            raise

        if len(capsules) > 1:
            raise exception.Conflict('Multiple capsules exist with same '
                                     'meta name. Please use the capsule uuid '
                                     'instead.')
        elif len(capsules) == 0:
            raise exception.CapsuleNotFound(capsule=capsule_meta_name)

        return capsules[0]
 def _wait_for_volumes_available(self,
                                 context,
                                 volumes,
                                 container,
                                 timeout=60,
                                 poll_interval=1):
     start_time = time.time()
     try:
         volumes = itertools.chain(volumes)
         volume = next(volumes)
         while time.time() - start_time < timeout:
             if self.driver.is_volume_available(context, volume):
                 volume = next(volumes)
             time.sleep(poll_interval)
     except StopIteration:
         return
     msg = _("Volumes did not reach available status after"
             "%d seconds") % (timeout)
     self._fail_container(context, container, msg, unset_host=True)
     raise exception.Conflict(msg)