コード例 #1
0
ファイル: servers.py プロジェクト: migue/nova
    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
コード例 #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
コード例 #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)
コード例 #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)
コード例 #5
0
ファイル: floating_ips.py プロジェクト: paulmathews/nova
    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)
コード例 #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)
コード例 #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')
コード例 #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']))
コード例 #9
0
ファイル: test_wsgi.py プロジェクト: rbenali/nova
 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']))
コード例 #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')
コード例 #11
0
ファイル: ec2utils.py プロジェクト: Cerberus98/nova
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')
コード例 #12
0
ファイル: ec2utils.py プロジェクト: Cerberus98/nova
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)
コード例 #13
0
ファイル: servers.py プロジェクト: westmaas/nova
    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
コード例 #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
コード例 #15
0
ファイル: manager.py プロジェクト: AsylumCorp/nova
    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)
コード例 #16
0
ファイル: api.py プロジェクト: kavanista/nova
 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())
コード例 #17
0
ファイル: servers.py プロジェクト: mattstep/nova
    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
コード例 #18
0
ファイル: manager.py プロジェクト: NewpTone/stacklab-nova
    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)
コード例 #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
コード例 #20
0
ファイル: volumes.py プロジェクト: Cerberus98/nova
    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
コード例 #21
0
ファイル: manager.py プロジェクト: paulmathews/nova
    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)
コード例 #22
0
ファイル: api.py プロジェクト: 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)
コード例 #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)
コード例 #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)
コード例 #25
0
ファイル: api.py プロジェクト: 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)
コード例 #26
0
ファイル: servers.py プロジェクト: acomisario/nova
    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)
コード例 #27
0
ファイル: test_utils.py プロジェクト: rbenali/nova
 def assertUUIDLike(self, val, expected):
     result = utils.is_uuid_like(val)
     self.assertEqual(result, expected)
コード例 #28
0
ファイル: api.py プロジェクト: AsylumCorp/nova
 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
コード例 #29
0
ファイル: api.py プロジェクト: AsylumCorp/nova
 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
コード例 #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)
コード例 #31
0
ファイル: api.py プロジェクト: Nesrine85/nova
 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
コード例 #32
0
ファイル: api.py プロジェクト: Nesrine85/nova
 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
コード例 #33
0
ファイル: test_utils.py プロジェクト: baz-reddwarf/nova
 def assertUUIDLike(self, val, expected):
     result = utils.is_uuid_like(val)
     self.assertEqual(result, expected)
コード例 #34
0
ファイル: servers.py プロジェクト: renuka-apte/nova
    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)