Ejemplo n.º 1
0
    def _get_requested_networks(self, requested_networks):
        """Create a list of requested networks from the networks attribute."""
        networks = []
        for network in requested_networks:
            try:
                port_id = network.get('port', None)
                if port_id:
                    network_uuid = None
                    if not self._is_quantum_v2():
                        # port parameter is only for qunatum v2.0
                        msg = _("Unknown argment : port")
                        raise exc.HTTPBadRequest(explanation=msg)
                    if not utils.is_uuid_like(port_id):
                        msg = _("Bad port format: port uuid is "
                                "not in proper format "
                                "(%s)") % port_id
                        raise exc.HTTPBadRequest(explanation=msg)
                else:
                    network_uuid = network['uuid']

                if not port_id and not utils.is_uuid_like(network_uuid):
                    br_uuid = network_uuid.split('-', 1)[-1]
                    if not utils.is_uuid_like(br_uuid):
                        msg = _("Bad networks format: network uuid is "
                                "not in proper format "
                                "(%s)") % network_uuid
                        raise exc.HTTPBadRequest(explanation=msg)

                #fixed IP address is optional
                #if the fixed IP address is not provided then
                #it will use one of the available IP address from the network
                address = network.get('fixed_ip', None)
                if address is not None and not utils.is_valid_ipv4(address):
                    msg = _("Invalid fixed IP address (%s)") % address
                    raise exc.HTTPBadRequest(explanation=msg)

                # For quantumv2, requestd_networks
                # should be tuple of (network_uuid, fixed_ip, port_id)
                if self._is_quantum_v2():
                    networks.append((network_uuid, address, port_id))
                else:
                    # check if the network id is already present in the list,
                    # we don't want duplicate networks to be passed
                    # at the boot time
                    for id, ip in networks:
                        if id == network_uuid:
                            expl = (_("Duplicate networks"
                                      " (%s) are not allowed") %
                                    network_uuid)
                            raise exc.HTTPBadRequest(explanation=expl)
                    networks.append((network_uuid, address))
            except KeyError as key:
                expl = _('Bad network format: missing %s') % key
                raise exc.HTTPBadRequest(explanation=expl)
            except TypeError:
                expl = _('Bad networks format')
                raise exc.HTTPBadRequest(explanation=expl)

        return networks
Ejemplo n.º 2
0
    def _get_requested_networks(self, requested_networks):
        """Create a list of requested networks from the networks attribute."""
        networks = []
        for network in requested_networks:
            try:
                port_id = network.get('port', None)
                if port_id:
                    network_uuid = None
                    if not self._is_quantum_v2():
                        # port parameter is only for qunatum v2.0
                        msg = _("Unknown argment : port")
                        raise exc.HTTPBadRequest(explanation=msg)
                    if not utils.is_uuid_like(port_id):
                        msg = _("Bad port format: port uuid is "
                                "not in proper format "
                                "(%s)") % port_id
                        raise exc.HTTPBadRequest(explanation=msg)
                else:
                    network_uuid = network['uuid']

                if not port_id and not utils.is_uuid_like(network_uuid):
                    br_uuid = network_uuid.split('-', 1)[-1]
                    if not utils.is_uuid_like(br_uuid):
                        msg = _("Bad networks format: network uuid is "
                                "not in proper format "
                                "(%s)") % network_uuid
                        raise exc.HTTPBadRequest(explanation=msg)

                #fixed IP address is optional
                #if the fixed IP address is not provided then
                #it will use one of the available IP address from the network
                address = network.get('fixed_ip', None)
                if address is not None and not utils.is_valid_ipv4(address):
                    msg = _("Invalid fixed IP address (%s)") % address
                    raise exc.HTTPBadRequest(explanation=msg)

                # For quantumv2, requestd_networks
                # should be tuple of (network_uuid, fixed_ip, port_id)
                if self._is_quantum_v2():
                    networks.append((network_uuid, address, port_id))
                else:
                    # check if the network id is already present in the list,
                    # we don't want duplicate networks to be passed
                    # at the boot time
                    for id, ip in networks:
                        if id == network_uuid:
                            expl = (_("Duplicate networks"
                                      " (%s) are not allowed") % network_uuid)
                            raise exc.HTTPBadRequest(explanation=expl)
                    networks.append((network_uuid, address))
            except KeyError as key:
                expl = _('Bad network format: missing %s') % key
                raise exc.HTTPBadRequest(explanation=expl)
            except TypeError:
                expl = _('Bad networks format')
                raise exc.HTTPBadRequest(explanation=expl)

        return networks
Ejemplo n.º 3
0
    def attach_volume(self, context, volume_id, instance_uuid, mountpoint):
        """Updates db to show volume is attached"""
        # TODO(vish): refactor this into a more general "reserve"
        if not utils.is_uuid_like(instance_uuid):
            raise exception.InvalidUUID(instance_uuid)

        self.db.volume_attached(context, volume_id, instance_uuid, mountpoint)
Ejemplo n.º 4
0
    def _remove_floating_ip(self, req, id, body):
        """Dissociate floating_ip from an instance."""
        context = req.environ['nova.context']
        authorize(context)

        try:
            address = body['removeFloatingIp']['address']
        except TypeError:
            msg = _("Missing parameter dict")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except KeyError:
            msg = _("Address not specified")

        # get the floating ip from db directly, not via rpc
        floating_ip = dict(
            self.db.floating_ip_get_by_address(context, address).iteritems())

        instance = get_instance_by_floating_ip(self, context, address,
                                               floating_ip)

        # disassociate if associated
        if (instance and floating_ip.get('fixed_ip_id')
                and (utils.is_uuid_like(id) and [instance['uuid'] == id]
                     or [instance['id'] == id])[0]):
            try:
                disassociate_floating_ip(self, context, instance, address)
            except exception.FloatingIpNotAssociated:
                msg = _('Floating ip is not associated')
                raise webob.exc.HTTPBadRequest(explanation=msg)
            return webob.Response(status_int=202)
        else:
            msg = _("Floating ip %(address)s is not associated with instance "
                    "%(id)s.") % locals()
            raise webob.exc.HTTPUnprocessableEntity(explanation=msg)
Ejemplo n.º 5
0
    def _remove_floating_ip(self, req, id, body):
        """Dissociate floating_ip from an instance."""
        context = req.environ['nova.context']
        authorize(context)

        try:
            address = body['removeFloatingIp']['address']
        except TypeError:
            msg = _("Missing parameter dict")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except KeyError:
            msg = _("Address not specified")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        # get the floating ip object
        floating_ip = self.network_api.get_floating_ip_by_address(context,
                                                                  address)
        # get the associated instance object (if any)
        instance = get_instance_by_floating_ip_addr(self, context, address)

        # disassociate if associated
        if (instance and
            floating_ip.get('fixed_ip_id') and
            (utils.is_uuid_like(id) and
             [instance['uuid'] == id] or
             [instance['id'] == id])[0]):
            disassociate_floating_ip(self, context, instance, address)
            return webob.Response(status_int=202)
        else:
            return webob.Response(status_int=404)
Ejemplo n.º 6
0
def id_to_ec2_inst_id(instance_id):
    """Get or create an ec2 instance ID (i-[base 16 number]) from uuid."""
    if utils.is_uuid_like(instance_id):
        ctxt = context.get_admin_context()
        int_id = get_int_id_from_instance_uuid(ctxt, instance_id)
        return id_to_ec2_id(int_id)
    else:
        return id_to_ec2_id(instance_id)
Ejemplo n.º 7
0
def id_to_ec2_snap_id(snapshot_id):
    """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid."""
    if utils.is_uuid_like(snapshot_id):
        ctxt = context.get_admin_context()
        int_id = get_int_id_from_snapshot_uuid(ctxt, snapshot_id)
        return id_to_ec2_id(int_id)
    else:
        return id_to_ec2_id(snapshot_id, 'snap-%08x')
Ejemplo n.º 8
0
 def test_request_id(self):
     serializer = wsgi.ResponseHeadersSerializer()
     context = nova.context.get_admin_context()
     req = webob.Request.blank('/', environ={'nova.context': context})
     res = webob.Response(request=req)
     serializer.serialize(res, {}, 'foo')
     self.assertTrue(utils.is_uuid_like(
         res.headers['X-Compute-Request-Id']))
Ejemplo n.º 9
0
 def test_request_id(self):
     serializer = wsgi.ResponseHeadersSerializer()
     context = nova.context.get_admin_context()
     req = webob.Request.blank('/', environ={'nova.context': context})
     res = webob.Response(request=req)
     serializer.serialize(res, {}, 'foo')
     self.assertTrue(
         utils.is_uuid_like(res.headers['X-Compute-Request-Id']))
Ejemplo n.º 10
0
def id_to_ec2_vol_id(volume_id):
    """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid."""
    if utils.is_uuid_like(volume_id):
        ctxt = context.get_admin_context()
        int_id = get_int_id_from_volume_uuid(ctxt, volume_id)
        return id_to_ec2_id(int_id, 'vol-%08x')
    else:
        return id_to_ec2_id(volume_id, 'vol-%08x')
Ejemplo n.º 11
0
def id_to_ec2_vol_id(volume_id):
    """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid."""
    if utils.is_uuid_like(volume_id):
        ctxt = context.get_admin_context()
        int_id = get_int_id_from_volume_uuid(ctxt, volume_id)
        return id_to_ec2_id(int_id, 'vol-%08x')
    else:
        return id_to_ec2_id(volume_id, 'vol-%08x')
Ejemplo n.º 12
0
def id_to_ec2_inst_id(instance_id):
    """Get or create an ec2 instance ID (i-[base 16 number]) from uuid."""
    if utils.is_uuid_like(instance_id):
        ctxt = context.get_admin_context()
        int_id = get_int_id_from_instance_uuid(ctxt, instance_id)
        return id_to_ec2_id(int_id)
    else:
        return id_to_ec2_id(instance_id)
Ejemplo n.º 13
0
    def _image_uuid_from_href(self, image_href):
        # If the image href was generated by nova api, strip image_href
        # down to an id and use the default glance connection params
        image_uuid = image_href.split('/').pop()

        if not utils.is_uuid_like(image_uuid):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        return image_uuid
Ejemplo n.º 14
0
    def _image_uuid_from_href(self, image_href):
        # If the image href was generated by nova api, strip image_href
        # down to an id and use the default glance connection params
        image_uuid = image_href.split('/').pop()

        if not utils.is_uuid_like(image_uuid):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        return image_uuid
Ejemplo n.º 15
0
    def attach_volume(self, context, volume_id, instance_uuid, mountpoint):
        """Updates db to show volume is attached"""
        # TODO(vish): refactor this into a more general "reserve"
        if not utils.is_uuid_like(instance_uuid):
            raise exception.InvalidUUID(instance_uuid)

        self.db.volume_attached(context,
                                volume_id,
                                instance_uuid,
                                mountpoint)
Ejemplo n.º 16
0
 def get(self, context, instance_id):
     """Get a single instance with the given instance_id."""
     # NOTE(sirp): id used to be exclusively integer IDs; now we're
     # accepting both UUIDs and integer IDs. The handling of this
     # is done in db/sqlalchemy/api/instance_get
     if utils.is_uuid_like(instance_id):
         uuid = instance_id
         instance = self.db.instance_get_by_uuid(context, uuid)
     else:
         instance = self.db.instance_get(context, instance_id)
     return dict(instance.iteritems())
Ejemplo n.º 17
0
    def _get_requested_networks(self, requested_networks):
        """Create a list of requested networks from the networks attribute."""
        networks = []
        for network in requested_networks:
            try:
                network_uuid = network['uuid']

                if not utils.is_uuid_like(network_uuid):
                    br_uuid = network_uuid.split('-', 1)[-1]
                    if not utils.is_uuid_like(br_uuid):
                        msg = _("Bad networks format: network uuid is "
                                "not in proper format "
                                "(%s)") % network_uuid
                        raise exc.HTTPBadRequest(explanation=msg)

                #fixed IP address is optional
                #if the fixed IP address is not provided then
                #it will use one of the available IP address from the network
                address = network.get('fixed_ip', None)
                if address is not None and not utils.is_valid_ipv4(address):
                    msg = _("Invalid fixed IP address (%s)") % address
                    raise exc.HTTPBadRequest(explanation=msg)
                # check if the network id is already present in the list,
                # we don't want duplicate networks to be passed
                # at the boot time
                for id, ip in networks:
                    if id == network_uuid:
                        expl = (_("Duplicate networks (%s) are not allowed") %
                                network_uuid)
                        raise exc.HTTPBadRequest(explanation=expl)

                networks.append((network_uuid, address))
            except KeyError as key:
                expl = _('Bad network format: missing %s') % key
                raise exc.HTTPBadRequest(explanation=expl)
            except TypeError:
                expl = _('Bad networks format')
                raise exc.HTTPBadRequest(explanation=expl)

        return networks
Ejemplo n.º 18
0
    def attach_volume(self, context, volume_id, instance_uuid, mountpoint):
        """Updates db to show volume is attached"""
        # TODO(vish): refactor this into a more general "reserve"
        if not utils.is_uuid_like(instance_uuid):
            raise exception.InvalidUUID(instance_uuid)

        try:
            self.driver.attach_volume(context, volume_id, instance_uuid, mountpoint)
        except Exception:
            with excutils.save_and_reraise_exception():
                self.db.volume_update(context, volume_id, {"status": "error_attaching"})

        self.db.volume_attached(context, volume_id, instance_uuid, mountpoint)
Ejemplo n.º 19
0
    def _image_uuid_from_href(self, image_href):
        # If the image href was generated by nova api, strip image_href
        # down to an id.
        try:
            image_uuid = image_href.split('/').pop()
        except (TypeError, AttributeError):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        if not utils.is_uuid_like(image_uuid):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        return image_uuid
Ejemplo n.º 20
0
    def _image_uuid_from_href(self, image_href):
        # If the image href was generated by nova api, strip image_href
        # down to an id.
        try:
            image_uuid = image_href.split('/').pop()
        except (TypeError, AttributeError):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        if not utils.is_uuid_like(image_uuid):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        return image_uuid
Ejemplo n.º 21
0
    def attach_volume(self, context, volume_id, instance_uuid, mountpoint):
        """Updates db to show volume is attached"""
        # TODO(vish): refactor this into a more general "reserve"
        if not utils.is_uuid_like(instance_uuid):
            raise exception.InvalidUUID(instance_uuid)

        try:
            self.driver.attach_volume(context, volume_id, instance_uuid,
                                      mountpoint)
        except Exception:
            with excutils.save_and_reraise_exception():
                self.db.volume_update(context, volume_id,
                                      {'status': 'error_attaching'})

        self.db.volume_attached(context, volume_id, instance_uuid, mountpoint)
Ejemplo n.º 22
0
Archivo: api.py Proyecto: NewpTone/nova
    def _get_floating_ip_pool_id_by_name_or_id(self, client, name_or_id):
        search_opts = {NET_EXTERNAL: True, 'fields': 'id'}
        if utils.is_uuid_like(name_or_id):
            search_opts.update({'id': name_or_id})
        else:
            search_opts.update({'name': name_or_id})
        data = client.list_networks(**search_opts)
        nets = data['networks']

        if len(nets) == 1:
            return nets[0]['id']
        elif len(nets) == 0:
            raise exception.FloatingIpPoolNotFound()
        else:
            msg = (_("Multiple floating IP pools matches found for name '%s'")
                   % name_or_id)
            raise exception.NovaException(message=msg)
Ejemplo n.º 23
0
    def _get_floating_ip_pool_id_by_name_or_id(self, client, name_or_id):
        search_opts = {NET_EXTERNAL: True, 'fields': 'id'}
        if utils.is_uuid_like(name_or_id):
            search_opts.update({'id': name_or_id})
        else:
            search_opts.update({'name': name_or_id})
        data = client.list_networks(**search_opts)
        nets = data['networks']

        if len(nets) == 1:
            return nets[0]['id']
        elif len(nets) == 0:
            raise exception.FloatingIpPoolNotFound()
        else:
            msg = (
                _("Multiple floating IP pools matches found for name '%s'") %
                name_or_id)
            raise exception.NovaException(message=msg)
Ejemplo n.º 24
0
        def wrapped_f(*args, **kwargs):
            collection, context, item_id_or_uuid = \
                            self.get_collection_context_and_id(args, kwargs)

            attempt_reroute = False
            if utils.is_uuid_like(item_id_or_uuid):
                item_uuid = item_id_or_uuid
                try:
                    instance = db.instance_get_by_uuid(context, item_uuid)
                except exception.InstanceNotFound, e:
                    # NOTE(sirp): since a UUID was passed in, we can attempt
                    # to reroute to a child zone
                    attempt_reroute = True
                    LOG.debug(_("Instance %(item_uuid)s not found "
                                        "locally: '%(e)s'" % locals()))
                else:
                    # NOTE(sirp): since we're not re-routing in this case, and
                    # we we were passed a UUID, we need to replace that UUID
                    # with an integer ID in the argument list so that the
                    # zone-local code can continue to use integer IDs.
                    item_id = instance['id']
                    args = list(args)      # needs to be mutable to replace
                    self.replace_uuid_with_id(args, kwargs, item_id)
Ejemplo n.º 25
0
Archivo: api.py Proyecto: Willtech/nova
        def wrapped_f(*args, **kwargs):
            collection, context, item_id_or_uuid = \
                            self.get_collection_context_and_id(args, kwargs)

            attempt_reroute = False
            if utils.is_uuid_like(item_id_or_uuid):
                item_uuid = item_id_or_uuid
                try:
                    instance = db.instance_get_by_uuid(context, item_uuid)
                except exception.InstanceNotFound, e:
                    # NOTE(sirp): since a UUID was passed in, we can attempt
                    # to reroute to a child zone
                    attempt_reroute = True
                    LOG.debug(_("Instance %(item_uuid)s not found "
                                        "locally: '%(e)s'" % locals()))
                else:
                    # NOTE(sirp): since we're not re-routing in this case, and
                    # we we were passed a UUID, we need to replace that UUID
                    # with an integer ID in the argument list so that the
                    # zone-local code can continue to use integer IDs.
                    item_id = instance['id']
                    args = list(args)      # needs to be mutable to replace
                    self.replace_uuid_with_id(args, kwargs, item_id)
Ejemplo n.º 26
0
    def create(self, req, body):
        """ Creates a new server for a given user """
        if not body:
            raise exc.HTTPUnprocessableEntity()

        if not 'server' in body:
            raise exc.HTTPUnprocessableEntity()

        body['server']['key_name'] = self._get_key_name(req, body)

        context = req.environ['nova.context']
        server_dict = body['server']
        password = self._get_server_admin_password(server_dict)

        if not 'name' in server_dict:
            msg = _("Server name is not defined")
            raise exc.HTTPBadRequest(explanation=msg)

        name = server_dict['name']
        self._validate_server_name(name)
        name = name.strip()

        image_href = self._image_ref_from_req_data(body)

        # If the image href was generated by nova api, strip image_href
        # down to an id and use the default glance connection params
        image_href = image_href.split('/').pop()

        if not utils.is_uuid_like(str(image_href)):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        personality = server_dict.get('personality')
        config_drive = server_dict.get('config_drive')

        injected_files = []
        if personality:
            injected_files = self._get_injected_files(personality)

        sg_names = []
        security_groups = server_dict.get('security_groups')
        if security_groups is not None:
            sg_names = [sg['name'] for sg in security_groups if sg.get('name')]
        if not sg_names:
            sg_names.append('default')

        sg_names = list(set(sg_names))

        requested_networks = server_dict.get('networks')
        if requested_networks is not None:
            requested_networks = self._get_requested_networks(
                                                    requested_networks)

        (access_ip_v4, ) = server_dict.get('accessIPv4'),
        if access_ip_v4 is not None:
            self._validate_access_ipv4(access_ip_v4)

        (access_ip_v6, ) = server_dict.get('accessIPv6'),
        if access_ip_v6 is not None:
            self._validate_access_ipv6(access_ip_v6)

        try:
            flavor_id = self._flavor_id_from_req_data(body)
        except ValueError as error:
            msg = _("Invalid flavorRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        zone_blob = server_dict.get('blob')

        # optional openstack extensions:
        key_name = server_dict.get('key_name')
        user_data = server_dict.get('user_data')
        self._validate_user_data(user_data)

        availability_zone = server_dict.get('availability_zone')
        name = server_dict['name']
        self._validate_server_name(name)
        name = name.strip()

        block_device_mapping = self._get_block_device_mapping(server_dict)

        # Only allow admins to specify their own reservation_ids
        # This is really meant to allow zones to work.
        reservation_id = server_dict.get('reservation_id')
        if all([reservation_id is not None,
                reservation_id != '',
                not context.is_admin]):
            reservation_id = None

        ret_resv_id = server_dict.get('return_reservation_id', False)

        min_count = server_dict.get('min_count')
        max_count = server_dict.get('max_count')
        # min_count and max_count are optional.  If they exist, they come
        # in as strings.  We want to default 'min_count' to 1, and default
        # 'max_count' to be 'min_count'.
        min_count = int(min_count) if min_count else 1
        max_count = int(max_count) if max_count else min_count
        if min_count > max_count:
            min_count = max_count

        auto_disk_config = server_dict.get('auto_disk_config')
        scheduler_hints = server_dict.get('scheduler_hints', {})

        try:
            inst_type = \
                    instance_types.get_instance_type_by_flavor_id(flavor_id)

            (instances, resv_id) = self.compute_api.create(context,
                            inst_type,
                            image_href,
                            display_name=name,
                            display_description=name,
                            key_name=key_name,
                            metadata=server_dict.get('metadata', {}),
                            access_ip_v4=access_ip_v4,
                            access_ip_v6=access_ip_v6,
                            injected_files=injected_files,
                            admin_password=password,
                            zone_blob=zone_blob,
                            reservation_id=reservation_id,
                            min_count=min_count,
                            max_count=max_count,
                            requested_networks=requested_networks,
                            security_group=sg_names,
                            user_data=user_data,
                            availability_zone=availability_zone,
                            config_drive=config_drive,
                            block_device_mapping=block_device_mapping,
                            auto_disk_config=auto_disk_config,
                            scheduler_hints=scheduler_hints)
        except exception.QuotaError as error:
            self._handle_quota_error(error)
        except exception.InstanceTypeMemoryTooSmall as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except exception.InstanceTypeDiskTooSmall as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except exception.ImageNotFound as error:
            msg = _("Can not find requested image")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.FlavorNotFound as error:
            msg = _("Invalid flavorRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.KeypairNotFound as error:
            msg = _("Invalid key_name provided.")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.SecurityGroupNotFound as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except rpc_common.RemoteError as err:
            msg = "%(err_type)s: %(err_msg)s" % \
                  {'err_type': err.exc_type, 'err_msg': err.value}
            raise exc.HTTPBadRequest(explanation=msg)
        # Let the caller deal with unhandled exceptions.

        # If the caller wanted a reservation_id, return it
        if ret_resv_id:
            return {'reservation_id': resv_id}

        server = self._view_builder.create(req, instances[0])

        if '_is_precooked' in server['server'].keys():
            del server['server']['_is_precooked']
        else:
            if FLAGS.enable_instance_password:
                server['server']['adminPass'] = password

        robj = wsgi.ResponseObject(server)

        return self._add_location(robj)
Ejemplo n.º 27
0
 def assertUUIDLike(self, val, expected):
     result = utils.is_uuid_like(val)
     self.assertEqual(result, expected)
Ejemplo n.º 28
0
 def _translate_uuid_if_necessary(self, context, instance_id):
     if utils.is_uuid_like(instance_id):
         instance = self.db.instance_get_by_uuid(context, instance_id)
         instance_id = instance['id']
     return instance_id
Ejemplo n.º 29
0
 def _get_instance(self, context, instance_id):
     if utils.is_uuid_like(instance_id):
         instance = self.db.instance_get_by_uuid(context, instance_id)
     else:
         instance = self.db.instance_get(context, instance_id)
     return instance
Ejemplo n.º 30
0
    def create(self, req, body):
        """ Creates a new server for a given user """
        if not body:
            raise exc.HTTPUnprocessableEntity()

        if not 'server' in body:
            raise exc.HTTPUnprocessableEntity()

        body['server']['key_name'] = self._get_key_name(req, body)

        context = req.environ['nova.context']
        server_dict = body['server']
        password = self._get_server_admin_password(server_dict)

        if not 'name' in server_dict:
            msg = _("Server name is not defined")
            raise exc.HTTPBadRequest(explanation=msg)

        name = server_dict['name']
        self._validate_server_name(name)
        name = name.strip()

        image_href = self._image_ref_from_req_data(body)

        # If the image href was generated by nova api, strip image_href
        # down to an id and use the default glance connection params
        image_href = image_href.split('/').pop()

        if not utils.is_uuid_like(str(image_href)):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        personality = server_dict.get('personality')
        config_drive = server_dict.get('config_drive')

        injected_files = []
        if personality:
            injected_files = self._get_injected_files(personality)

        sg_names = []
        security_groups = server_dict.get('security_groups')
        if security_groups is not None:
            sg_names = [sg['name'] for sg in security_groups if sg.get('name')]
        if not sg_names:
            sg_names.append('default')

        sg_names = list(set(sg_names))

        requested_networks = server_dict.get('networks')
        if requested_networks is not None:
            requested_networks = self._get_requested_networks(
                requested_networks)

        (access_ip_v4, ) = server_dict.get('accessIPv4'),
        if access_ip_v4 is not None:
            self._validate_access_ipv4(access_ip_v4)

        (access_ip_v6, ) = server_dict.get('accessIPv6'),
        if access_ip_v6 is not None:
            self._validate_access_ipv6(access_ip_v6)

        try:
            flavor_id = self._flavor_id_from_req_data(body)
        except ValueError as error:
            msg = _("Invalid flavorRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        # optional openstack extensions:
        key_name = server_dict.get('key_name')
        user_data = server_dict.get('user_data')
        self._validate_user_data(user_data)

        availability_zone = server_dict.get('availability_zone')
        name = server_dict['name']
        self._validate_server_name(name)
        name = name.strip()

        block_device_mapping = self._get_block_device_mapping(server_dict)

        ret_resv_id = server_dict.get('return_reservation_id', False)

        min_count = server_dict.get('min_count')
        max_count = server_dict.get('max_count')
        # min_count and max_count are optional.  If they exist, they come
        # in as strings.  We want to default 'min_count' to 1, and default
        # 'max_count' to be 'min_count'.
        min_count = int(min_count) if min_count else 1
        max_count = int(max_count) if max_count else min_count
        if min_count > max_count:
            min_count = max_count

        auto_disk_config = server_dict.get('auto_disk_config')
        scheduler_hints = server_dict.get('scheduler_hints', {})

        try:
            _get_inst_type = instance_types.get_instance_type_by_flavor_id
            inst_type = _get_inst_type(flavor_id)

            (instances, resv_id) = self.compute_api.create(
                context,
                inst_type,
                image_href,
                display_name=name,
                display_description=name,
                key_name=key_name,
                metadata=server_dict.get('metadata', {}),
                access_ip_v4=access_ip_v4,
                access_ip_v6=access_ip_v6,
                injected_files=injected_files,
                admin_password=password,
                min_count=min_count,
                max_count=max_count,
                requested_networks=requested_networks,
                security_group=sg_names,
                user_data=user_data,
                availability_zone=availability_zone,
                config_drive=config_drive,
                block_device_mapping=block_device_mapping,
                auto_disk_config=auto_disk_config,
                scheduler_hints=scheduler_hints)
        except exception.QuotaError as error:
            self._handle_quota_error(error)
        except exception.InstanceTypeMemoryTooSmall as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except exception.InstanceTypeDiskTooSmall as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except exception.ImageNotFound as error:
            msg = _("Can not find requested image")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.FlavorNotFound as error:
            msg = _("Invalid flavorRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.KeypairNotFound as error:
            msg = _("Invalid key_name provided.")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.SecurityGroupNotFound as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except rpc_common.RemoteError as err:
            msg = "%(err_type)s: %(err_msg)s" % {
                'err_type': err.exc_type,
                'err_msg': err.value
            }
            raise exc.HTTPBadRequest(explanation=msg)
        # Let the caller deal with unhandled exceptions.

        # If the caller wanted a reservation_id, return it
        if ret_resv_id:
            return {'reservation_id': resv_id}

        server = self._view_builder.create(req, instances[0])

        if '_is_precooked' in server['server'].keys():
            del server['server']['_is_precooked']
        else:
            if FLAGS.enable_instance_password:
                server['server']['adminPass'] = password

        robj = wsgi.ResponseObject(server)

        return self._add_location(robj)
Ejemplo n.º 31
0
 def _translate_uuid_if_necessary(self, context, instance_id):
     if utils.is_uuid_like(instance_id):
         instance = self.db.instance_get_by_uuid(context, instance_id)
         instance_id = instance['id']
     return instance_id
Ejemplo n.º 32
0
 def _get_instance(self, context, instance_id):
     if utils.is_uuid_like(instance_id):
         instance = self.db.instance_get_by_uuid(context, instance_id)
     else:
         instance = self.db.instance_get(context, instance_id)
     return instance
Ejemplo n.º 33
0
 def assertUUIDLike(self, val, expected):
     result = utils.is_uuid_like(val)
     self.assertEqual(result, expected)
Ejemplo n.º 34
0
    def create(self, req, body):
        """ Creates a new server for a given user """
        if not body:
            raise exc.HTTPUnprocessableEntity()

        if not "server" in body:
            raise exc.HTTPUnprocessableEntity()

        body["server"]["key_name"] = self._get_key_name(req, body)

        context = req.environ["nova.context"]
        server_dict = body["server"]
        password = self._get_server_admin_password(server_dict)

        if not "name" in server_dict:
            msg = _("Server name is not defined")
            raise exc.HTTPBadRequest(explanation=msg)

        name = server_dict["name"]
        self._validate_server_name(name)
        name = name.strip()

        image_href = self._image_ref_from_req_data(body)

        # If the image href was generated by nova api, strip image_href
        # down to an id and use the default glance connection params
        image_href = image_href.split("/").pop()

        if not utils.is_uuid_like(str(image_href)):
            msg = _("Invalid imageRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        personality = server_dict.get("personality")
        config_drive = server_dict.get("config_drive")

        injected_files = []
        if personality:
            injected_files = self._get_injected_files(personality)

        sg_names = []
        security_groups = server_dict.get("security_groups")
        if security_groups is not None:
            sg_names = [sg["name"] for sg in security_groups if sg.get("name")]
        if not sg_names:
            sg_names.append("default")

        sg_names = list(set(sg_names))

        requested_networks = server_dict.get("networks")
        if requested_networks is not None:
            requested_networks = self._get_requested_networks(requested_networks)

        (access_ip_v4,) = (server_dict.get("accessIPv4"),)
        if access_ip_v4 is not None:
            self._validate_access_ipv4(access_ip_v4)

        (access_ip_v6,) = (server_dict.get("accessIPv6"),)
        if access_ip_v6 is not None:
            self._validate_access_ipv6(access_ip_v6)

        try:
            flavor_id = self._flavor_id_from_req_data(body)
        except ValueError as error:
            msg = _("Invalid flavorRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        # optional openstack extensions:
        key_name = server_dict.get("key_name")
        user_data = server_dict.get("user_data")
        self._validate_user_data(user_data)

        availability_zone = server_dict.get("availability_zone")
        name = server_dict["name"]
        self._validate_server_name(name)
        name = name.strip()

        block_device_mapping = self._get_block_device_mapping(server_dict)

        ret_resv_id = server_dict.get("return_reservation_id", False)

        min_count = server_dict.get("min_count")
        max_count = server_dict.get("max_count")
        # min_count and max_count are optional.  If they exist, they come
        # in as strings.  We want to default 'min_count' to 1, and default
        # 'max_count' to be 'min_count'.
        min_count = int(min_count) if min_count else 1
        max_count = int(max_count) if max_count else min_count
        if min_count > max_count:
            min_count = max_count

        auto_disk_config = server_dict.get("auto_disk_config")
        scheduler_hints = server_dict.get("scheduler_hints", {})

        try:
            _get_inst_type = instance_types.get_instance_type_by_flavor_id
            inst_type = _get_inst_type(flavor_id)

            (instances, resv_id) = self.compute_api.create(
                context,
                inst_type,
                image_href,
                display_name=name,
                display_description=name,
                key_name=key_name,
                metadata=server_dict.get("metadata", {}),
                access_ip_v4=access_ip_v4,
                access_ip_v6=access_ip_v6,
                injected_files=injected_files,
                admin_password=password,
                min_count=min_count,
                max_count=max_count,
                requested_networks=requested_networks,
                security_group=sg_names,
                user_data=user_data,
                availability_zone=availability_zone,
                config_drive=config_drive,
                block_device_mapping=block_device_mapping,
                auto_disk_config=auto_disk_config,
                scheduler_hints=scheduler_hints,
            )
        except exception.QuotaError as error:
            self._handle_quota_error(error)
        except exception.InstanceTypeMemoryTooSmall as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except exception.InstanceTypeDiskTooSmall as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except exception.ImageNotFound as error:
            msg = _("Can not find requested image")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.FlavorNotFound as error:
            msg = _("Invalid flavorRef provided.")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.KeypairNotFound as error:
            msg = _("Invalid key_name provided.")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.SecurityGroupNotFound as error:
            raise exc.HTTPBadRequest(explanation=unicode(error))
        except rpc_common.RemoteError as err:
            msg = "%(err_type)s: %(err_msg)s" % {"err_type": err.exc_type, "err_msg": err.value}
            raise exc.HTTPBadRequest(explanation=msg)
        # Let the caller deal with unhandled exceptions.

        # If the caller wanted a reservation_id, return it
        if ret_resv_id:
            return {"reservation_id": resv_id}

        server = self._view_builder.create(req, instances[0])

        if "_is_precooked" in server["server"].keys():
            del server["server"]["_is_precooked"]
        else:
            if FLAGS.enable_instance_password:
                server["server"]["adminPass"] = password

        robj = wsgi.ResponseObject(server)

        return self._add_location(robj)