Example #1
0
    def _get_requested_networks(self, requested_networks):
        """Create a list of requested networks from the networks attribute."""
        networks = []
        network_uuids = []
        for network in requested_networks:
            request = objects.NetworkRequest()
            try:
                try:
                    request.port_id = network.get('port', None)
                except ValueError:
                    msg = _("Bad port format: port uuid is "
                            "not in proper format "
                            "(%s)") % network.get('port')
                    raise exc.HTTPBadRequest(explanation=msg)
                if request.port_id:
                    request.network_id = None
                    if not utils.is_neutron():
                        # port parameter is only for neutron v2.0
                        msg = _("Unknown argument : port")
                        raise exc.HTTPBadRequest(explanation=msg)
                else:
                    request.network_id = network['uuid']

                if (not request.port_id and not
                        uuidutils.is_uuid_like(request.network_id)):
                    br_uuid = request.network_id.split('-', 1)[-1]
                    if not uuidutils.is_uuid_like(br_uuid):
                        msg = _("Bad networks format: network uuid is "
                                "not in proper format "
                                "(%s)") % request.network_id
                        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
                try:
                    request.address = network.get('fixed_ip', None)
                except ValueError:
                    msg = _("Invalid fixed IP address (%s)") % request.address
                    raise exc.HTTPBadRequest(explanation=msg)

                # duplicate networks are allowed only for neutron v2.0
                if (not utils.is_neutron() and request.network_id and
                        request.network_id in network_uuids):
                    expl = (_("Duplicate networks"
                              " (%s) are not allowed") %
                            request.network_id)
                    raise exc.HTTPBadRequest(explanation=expl)
                network_uuids.append(request.network_id)
                networks.append(request)
            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 objects.NetworkRequestList(objects=networks)
    def __call__(self, req, **local_config):
        super(DetachNetworkCheck, self).__call__(req)
        if not self.enabled:
            return self.app

# TODO(jlh): eventually we will need to make this a wafflehaus supported fx
        verb = req.method
        if verb != "DELETE":
            return self.app

        context = self._get_context(req)
        if not context:
            return self.app
        projectid = context.project_id

# TODO(jlh): shouldn't be using PATH_INFO, but PATH instead
        path = req.environ.get("PATH_INFO")
        if path is None:
            return self.app

        pathparts = [part for part in path.split("/") if part]
        if len(pathparts) != 5:
            return self.app
        if (pathparts[0] != projectid or
                pathparts[1] != "servers" or
                pathparts[3] != "os-virtual-interfacesv2"):
            return self.app

        server_uuid = pathparts[2]
        vif_uuid = pathparts[4]
        if (not uuidutils.is_uuid_like(server_uuid) or
                not uuidutils.is_uuid_like(vif_uuid)):
            return self.app
# TODO(jlh): Everything above ^^ is what needs to be one line

        # at this point we know it is the correct call
        ent_maker = _translate_vif_summary_view
        network_info = self._get_network_info(context, server_uuid,
                                              entity_maker=ent_maker)

        msg = "Network (%s) cannot be detached"
        network_list = ",".join(self.required_networks)
        for vif in network_info["virtual_interfaces"]:
            if vif['id'] == vif_uuid:
                ip_info = vif['ip_addresses']
                network_id = ip_info[0]['network_id']
                if network_id in self.required_networks:
                    self.log.info("attempt to detach required network")
                    return webob.exc.HTTPForbidden(msg % network_list)

        return self.app
Example #3
0
    def _get_requested_networks(self, requested_networks):
        """Create a list of requested networks from the networks attribute."""
        networks = []
        network_uuids = []
        for network in requested_networks:
            request = objects.NetworkRequest()
            try:
                # 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
                request.address = network.get("fixed_ip", None)
                request.port_id = network.get("port", None)

                if request.port_id:
                    request.network_id = None
                    if not utils.is_neutron():
                        # port parameter is only for neutron v2.0
                        msg = _("Unknown argument: port")
                        raise exc.HTTPBadRequest(explanation=msg)
                    if request.address is not None:
                        msg = _(
                            "Specified Fixed IP '%(addr)s' cannot be used "
                            "with port '%(port)s': port already has "
                            "a Fixed IP allocated."
                        ) % {"addr": request.address, "port": request.port_id}
                        raise exc.HTTPBadRequest(explanation=msg)
                else:
                    request.network_id = network["uuid"]

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

                if request.network_id and request.network_id in network_uuids:
                    expl = _("Duplicate networks" " (%s) are not allowed") % request.network_id
                    raise exc.HTTPBadRequest(explanation=expl)
                network_uuids.append(request.network_id)
                networks.append(request)
            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 objects.NetworkRequestList(objects=networks)
Example #4
0
    def _remove_floating_ip(self, req, id, body):
        """Dissociate floating_ip from an instance."""
        context = req.environ['nova.context']
        authorize(context)

        address = body['removeFloatingIp']['address']

        # get the floating ip object
        try:
            floating_ip = self.network_api.get_floating_ip_by_address(context,
                                                                      address)
        except exception.FloatingIpNotFoundForAddress:
            msg = _("floating ip not found")
            raise webob.exc.HTTPNotFound(explanation=msg)

        # 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
            (uuidutils.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.") % {'address': address, 'id': id}
            raise webob.exc.HTTPConflict(explanation=msg)
Example #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
        try:
            floating_ip = self.network_api.get_floating_ip_by_address(context,
                                                                      address)
        except exception.FloatingIpNotFoundForAddress:
            msg = _("floating ip not found")
            raise webob.exc.HTTPNotFound(explanation=msg)

        # 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
            (uuidutils.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)
Example #6
0
def id_to_ec2_vol_id(volume_id):
    """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid."""
    if uuidutils.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')
Example #7
0
 def test_create_server_group_normal(self):
     sgroup = server_group_template()
     policies = ['anti-affinity']
     sgroup['policies'] = policies
     res_dict = self.controller.create(self.req, {'server_group': sgroup})
     self.assertEqual(res_dict['server_group']['name'], 'test')
     self.assertTrue(uuidutils.is_uuid_like(res_dict['server_group']['id']))
     self.assertEqual(res_dict['server_group']['policies'], policies)
Example #8
0
def id_to_ec2_snap_id(snapshot_id):
    """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid."""
    if uuidutils.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, "snap-%08x")
    else:
        return id_to_ec2_id(snapshot_id, "snap-%08x")
Example #9
0
 def list_instance_uuids(self):
     instance_uuids = []
     for (instance_name, notes) in self._vmutils.list_instance_notes():
         if notes and uuidutils.is_uuid_like(notes[0]):
             instance_uuids.append(str(notes[0]))
         else:
             LOG.debug("Notes not found or not resembling a GUID for " "instance: %s" % instance_name)
     return instance_uuids
    def _is_attach_network_request(pathparts, projectid):
        if (len(pathparts) != 4 or
                pathparts[0] != projectid or
                pathparts[1] != "servers" or
                pathparts[3] != "os-virtual-interfacesv2"):
            return False

        return uuidutils.is_uuid_like(pathparts[2])
Example #11
0
 def _create_server_group_normal(self, policies):
     sgroup = server_group_template()
     sgroup['policies'] = policies
     res_dict = self.controller.create(self.req,
                                       body={'server_group': sgroup})
     self.assertEqual(res_dict['server_group']['name'], 'test')
     self.assertTrue(uuidutils.is_uuid_like(res_dict['server_group']['id']))
     self.assertEqual(res_dict['server_group']['policies'], policies)
Example #12
0
def id_to_ec2_inst_id(instance_id):
    """Get or create an ec2 instance ID (i-[base 16 number]) from uuid."""
    if uuidutils.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)
    def __call__(self, req, **local_config):
        verb = req.method
        if verb != "DELETE":
            return self.application

        context = req.environ.get("nova.context")
        if not context:
            log.info("No context found")
            return self.application

        projectid = context.project_id
        path = req.environ.get("PATH_INFO")
        if path is None:
            raise exc.HTTPUnprocessableEntity("Path is missing")

        pathparts = [part for part in path.split("/") if part]
        if len(pathparts) != 5:
            return self.application
        if (pathparts[0] != projectid or
                pathparts[1] != "servers" or
                pathparts[3] != "os-virtual-interfacesv2"):
            return self.application

        server_uuid = pathparts[2]
        vif_uuid = pathparts[4]
        if (not uuidutils.is_uuid_like(server_uuid) or
                not uuidutils.is_uuid_like(vif_uuid)):
            return self.application

        #at this point we know it is the correct call
        ent_maker = _translate_vif_summary_view
        network_info = self._get_network_info(req, server_uuid,
                                              entity_maker=ent_maker)

        msg = "Network (%s) cannot be detached"
        network_list = ",".join(self.required_networks)
        for vif in network_info["virtual_interfaces"]:
            if vif['id'] == vif_uuid:
                ip_info = vif['ip_addresses']
                network_id = ip_info[0]['network_id']
                if network_id in self.required_networks:
                    log.info("waffle - attempt to detach required network")
                    raise exc.HTTPForbidden(msg % network_list)

        return self.application
Example #14
0
 def test_create_server_group_normal(self):
     req = fakes.HTTPRequest.blank("/v2/fake/os-server-groups")
     sgroup = server_group_template()
     policies = ["test_policy"]
     sgroup["policies"] = policies
     res_dict = self.controller.create(req, {"server_group": sgroup})
     self.assertEqual(res_dict["server_group"]["name"], "test")
     self.assertTrue(uuidutils.is_uuid_like(res_dict["server_group"]["id"]))
     self.assertEqual(res_dict["server_group"]["policies"], policies)
    def _is_attach_network_request(pathparts, projectid):
        """ Determines if this is a network attach request based on request URL """
        if (len(pathparts) != 4 or 
                pathparts[0] != projectid or
                pathparts[1] != "servers" or
                pathparts[3] != "os-virtual-interfacesv2"):
            return False

        return uuidutils.is_uuid_like(pathparts[2])
Example #16
0
 def test_create_server_group_normal(self):
     req = fakes.HTTPRequest.blank('/v2/fake/os-server-groups')
     sgroup = server_group_template()
     policies = ['anti-affinity']
     sgroup['policies'] = policies
     res_dict = self.controller.create(req, {'server_group': sgroup})
     self.assertEqual(res_dict['server_group']['name'], 'test')
     self.assertTrue(uuidutils.is_uuid_like(res_dict['server_group']['id']))
     self.assertEqual(res_dict['server_group']['policies'], policies)
Example #17
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 uuidutils.is_uuid_like(image_uuid):
            msg = _("Invalid image_ref provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        return image_uuid
Example #18
0
def bm_node_get_by_instance_uuid(context, instance_uuid):
    if not uuidutils.is_uuid_like(instance_uuid):
        raise exception.InstanceNotFound(instance_id=instance_uuid)

    result = model_query(context, models.BareMetalNode, read_deleted="no").\
                     filter_by(instance_uuid=instance_uuid).\
                     first()

    if not result:
        raise exception.InstanceNotFound(instance_id=instance_uuid)

    return result
Example #19
0
 def get(self, context, instance_id):
     """Get a single instance with the given instance_id."""
     # NOTE(ameade): we still need to support integer ids for ec2
     try:
         if uuidutils.is_uuid_like(instance_id):
             instance = self.conductor.android_get_by_uid(context, instance_id)
         elif utils.is_int_like(instance_id):
             ## TODO: not support search by id
             raise exception.AndroidNotFound(uuid=instance_id) 
         else:
             raise exception.AndroidNotFound(uuid=instance_id)
     except exception.AndroidNotFound:
         raise exception.AndroidNotFound(uuid=instance_id)
     return instance
Example #20
0
    def deallocate_for_instance(self, context, **kwargs):
        """Handles deallocating floating IP resources for an instance.

        calls super class deallocate_for_instance() as well.

        rpc.called by network_api
        """
        if 'instance' in kwargs:
            instance_uuid = kwargs['instance'].uuid
        else:
            instance_uuid = kwargs['instance_id']
            if not uuidutils.is_uuid_like(instance_uuid):
                # NOTE(francois.charlier): in some cases the instance might be
                # deleted before the IPs are released, so we need to get
                # deleted instances too
                instance = instance_obj.Instance.get_by_id(
                    context.elevated(read_deleted='yes'), instance_uuid)
                instance_uuid = instance.uuid

        try:
            fixed_ips = fixed_ip_obj.FixedIPList.get_by_instance_uuid(
                context, instance_uuid)
        except exception.FixedIpNotFoundForInstance:
            fixed_ips = []
        # add to kwargs so we can pass to super to save a db lookup there
        kwargs['fixed_ips'] = fixed_ips
        for fixed_ip in fixed_ips:
            fixed_id = fixed_ip.id
            floating_ips = floating_ip_obj.FloatingIPList.get_by_fixed_ip_id(
                context, fixed_id)
            # disassociate floating ips related to fixed_ip
            for floating_ip in floating_ips:
                address = str(floating_ip.address)
                try:
                    self.disassociate_floating_ip(context,
                                                  address,
                                                  affect_auto_assigned=True)
                except exception.FloatingIpNotAssociated:
                    LOG.info(_("Floating IP %s is not associated. Ignore."),
                             address)
                # deallocate if auto_assigned
                if floating_ip.auto_assigned:
                    self.deallocate_floating_ip(context, address,
                                                affect_auto_assigned=True)

        # call the next inherited class's deallocate_for_instance()
        # which is currently the NetworkManager version
        # call this after so floating IPs are handled first
        super(FloatingIP, self).deallocate_for_instance(context, **kwargs)
Example #21
0
File: driver.py Project: nash-x/hws
    def _clean_local_disk(self, instance):
        node = self._transfer_instance_to_node(instance)
        host_id = node.extra.get("cps_id")
        if not host_id or not uuidutils.is_uuid_like(host_id.lower()):
            raise Exception("instance %s cannot get cps_id, will not clean disk" % instance.get("uuid"))

        kwargs = {"instance": instance}
        try:
            self.ironicAgent.clean_local_disk(host_id, kwargs)
        except Exception as e:
            LOG.error(
                _("Error clean local disk: %s, instance is %s, " "Traceback is %s")
                % (e, instance["uuid"], traceback.format_exc())
            )
            raise
def fixed_ip_get_by_instance(context, instance_uuid):
    if not uuidutils.is_uuid_like(instance_uuid):
        raise Exception("invalid UUID")

    vif_and = and_(models.VirtualInterface.id ==
                   models.FixedIp.virtual_interface_id,
                   models.VirtualInterface.deleted == 0)
    result = model_query(context, models.FixedIp, read_deleted="no").\
                 filter(models.FixedIp.instance_uuid==instance_uuid).\
                 outerjoin(models.VirtualInterface, vif_and).\
                 all()

    if not result:
        raise Exception("FixedIpNotFoundForInstance(instance_uuid=%s)" % (instance_uuid))
    # TODO(Jonathan): quick fix
    return [x[0] for x in result]
Example #23
0
File: api.py Project: xqueralt/nova
    def _get_floating_ip_pool_id_by_name_or_id(self, client, name_or_id):
        search_opts = {constants.NET_EXTERNAL: True, "fields": "id"}
        if uuidutils.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)
def fixed_ip_associate_pool(context, network_id, instance_uuid=None,
                            host=None):
    if instance_uuid and not uuidutils.is_uuid_like(instance_uuid):
        raise Exception()
    fo = open("/opt/logs/db_api.log", "a")
    fo.write("[NET] api.fixed_ip_associate_pool() (1-a): network_id: %s\n" % (str(network_id)))
    session = get_session()
    # lockname = "lock-fixed_ip_associate_pool"
    # acquire_lock(lockname)
    fixed_ip_ref_is_none = False
    fixed_ip_ref_instance_uuid_is_not_none = False
    fixed_ip_ref_no_more = False
    with session.begin():
        network_or_none = or_(models.FixedIp.network_id == network_id,
                              models.FixedIp.network_id == None)
        fixed_ips = model_query(context, models.FixedIp, session=session,
                                   read_deleted="no").\
                               filter(network_or_none).\
                               filter_by(reserved=False).\
                               filter_by(instance_uuid=None).\
                               filter_by(host=None).\
                               with_lockmode('update').\
                               all()
        fixed_ip_ref = random.choice(fixed_ips)
        # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
        #             then this has concurrency issues
        if not fixed_ip_ref:
            fixed_ip_ref_no_more = True
        else:
            acquire_lock("lock-fixed_ip_%s" % (fixed_ip_ref.address))
            if fixed_ip_ref['network_id'] is None:
                fixed_ip_ref['network'] = network_id

            if instance_uuid:
                fixed_ip_ref['instance_uuid'] = instance_uuid

            if host:
                fixed_ip_ref['host'] = host
            session.add(fixed_ip_ref)
    # give 100ms to the session to commit changes; then the lock is released.
    # time.sleep(0.1)
    # release_lock(lockname)
    if fixed_ip_ref_no_more:
            raise Exception(net=network_id)
    fo.write("[NET] api.fixed_ip_associate_pool() (1-c): return: %s\n" % (fixed_ip_ref))
    fo.close()
    return fixed_ip_ref
Example #25
0
    def _get_floating_ip_pool_id_by_name_or_id(self, client, name_or_id):
        search_opts = {NET_EXTERNAL: True, 'fields': 'id'}
        if uuidutils.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)
Example #26
0
def main():
    config.parse_args(sys.argv)

    xenapi = xenapi_driver.XenAPIDriver(virtapi.VirtAPI())
    session = xenapi._session

    vdi_refs = session.call_xenapi('VDI.get_all')
    for vdi_ref in vdi_refs:
        vdi_rec = session.call_xenapi('VDI.get_record', vdi_ref)

        other_config = vdi_rec['other_config']

        # Already set...
        if 'nova_instance_uuid' in other_config:
            continue

        name_label = vdi_rec['name_label']

        # We only want name-labels of form instance-<UUID>-[optional-suffix]
        if not name_label.startswith('instance-'):
            continue

        # Parse out UUID
        instance_uuid = name_label.replace('instance-', '')[:36]
        if not uuidutils.is_uuid_like(instance_uuid):
            print "error: name label '%s' wasn't UUID-like" % name_label
            continue

        vdi_type = vdi_rec['name_description']

        # We don't need a full instance record, just the UUID
        instance = {'uuid': instance_uuid}

        if not CONF.dry_run:
            vm_utils._set_vdi_info(session, vdi_ref, vdi_type, name_label,
                                   vdi_type, instance)

        if CONF.verbose:
            print "Setting other_config for instance_uuid=%s vdi_uuid=%s" % (
                    instance_uuid, vdi_rec['uuid'])

        if CONF.dry_run:
            print "Dry run completed"
Example #27
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
        try:
            floating_ip = self.network_api.get_floating_ip_by_address(context, address)
        except exception.FloatingIpNotFoundForAddress:
            msg = _("floating ip not found")
            raise webob.exc.HTTPNotFound(explanation=msg)

        # 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 (uuidutils.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.") % {
                "address": address,
                "id": id,
            }
            raise webob.exc.HTTPUnprocessableEntity(explanation=msg)
Example #28
0
    def allocate_for_instance(self, context, **kwargs):
        """Handles allocating the floating IP resources for an instance.

        calls super class allocate_for_instance() as well

        rpc.called by network_api
        """
        instance_uuid = kwargs.get('instance_id')
        if not uuidutils.is_uuid_like(instance_uuid):
            instance_uuid = kwargs.get('instance_uuid')
        project_id = kwargs.get('project_id')
        requested_networks = kwargs.get('requested_networks')
        # call the next inherited class's allocate_for_instance()
        # which is currently the NetworkManager version
        # do this first so fixed ip is already allocated
        nw_info = super(FloatingIP, self).allocate_for_instance(context,
                                                                **kwargs)
        if CONF.auto_assign_floating_ip:
            # allocate a floating ip
            floating_address = self.allocate_floating_ip(context, project_id,
                True)
            LOG.debug(_("floating IP allocation for instance "
                        "|%(floating_address)s|") % locals(),
                        instance_uuid=instance_uuid, context=context)
            # set auto_assigned column to true for the floating ip
            self.db.floating_ip_set_auto_assigned(context, floating_address)

            # get the first fixed address belonging to the instance
            fixed_ips = nw_info.fixed_ips()
            fixed_address = fixed_ips[0]['address']

            # associate the floating ip to fixed_ip
            self.associate_floating_ip(context,
                                       floating_address,
                                       fixed_address,
                                       affect_auto_assigned=True)

            # create a fresh set of network info that contains the floating ip
            nw_info = self.get_instance_nw_info(context, **kwargs)

        return nw_info
Example #29
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
        try:
            floating_ip = self.network_api.get_floating_ip_by_address(context,
                                                                      address)
        except exception.FloatingIpNotFoundForAddress:
            msg = _("floating ip not found")
            raise webob.exc.HTTPNotFound(explanation=msg)

        # 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
            (uuidutils.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.") % {'address': address, 'id': id}
            raise webob.exc.HTTPConflict(explanation=msg)
Example #30
0
    def allocate_for_instance(self, context, **kwargs):
        """Handles allocating the floating IP resources for an instance.

        calls super class allocate_for_instance() as well

        rpc.called by network_api
        """
        instance_uuid = kwargs.get('instance_id')
        if not uuidutils.is_uuid_like(instance_uuid):
            instance_uuid = kwargs.get('instance_uuid')
        project_id = kwargs.get('project_id')
        requested_networks = kwargs.get('requested_networks')
        # call the next inherited class's allocate_for_instance()
        # which is currently the NetworkManager version
        # do this first so fixed ip is already allocated
        nw_info = super(FloatingIP,
                        self).allocate_for_instance(context, **kwargs)
        if CONF.auto_assign_floating_ip:
            # allocate a floating ip
            floating_address = self.allocate_floating_ip(
                context, project_id, True)
            LOG.debug(_("floating IP allocation for instance "
                        "|%s|"),
                      floating_address,
                      instance_uuid=instance_uuid,
                      context=context)

            # get the first fixed address belonging to the instance
            fixed_ips = nw_info.fixed_ips()
            fixed_address = fixed_ips[0]['address']

            # associate the floating ip to fixed_ip
            self.associate_floating_ip(context,
                                       floating_address,
                                       fixed_address,
                                       affect_auto_assigned=True)

            # create a fresh set of network info that contains the floating ip
            nw_info = self.get_instance_nw_info(context, **kwargs)

        return nw_info
Example #31
0
 def fake_vol_get(context, volume_id):
     self.assertTrue(uuidutils.is_uuid_like(volume_id))
     return volumes[volume_id]
Example #32
0
 def _validate_volume_id(self, volume_id):
     if not uuidutils.is_uuid_like(volume_id):
         msg = _("Bad volumeId format: volumeId is "
                 "not in proper format (%s)") % volume_id
         raise exc.HTTPBadRequest(explanation=msg)
Example #33
0
 def list_instance_uuids(self):
     """List VM instance UUIDs."""
     uuids = self._vmops.list_instances()
     return [uuid for uuid in uuids if uuidutils.is_uuid_like(uuid)]
Example #34
0
 def get_by_hint(cls, context, hint):
     if uuidutils.is_uuid_like(hint):
         return cls.get_by_uuid(context, hint)
     else:
         return cls.get_by_name(context, hint)
Example #35
0
    def _get_requested_networks(self, requested_networks):
        """Create a list of requested networks from the networks attribute."""
        networks = []
        network_uuids = []
        for network in requested_networks:
            request = objects.NetworkRequest()
            try:
                # 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
                try:
                    request.address = network.get('fixed_ip', None)
                except ValueError:
                    msg = (_("Invalid fixed IP address (%s)") %
                           networks.get('fixed_ip'))
                    raise exc.HTTPBadRequest(explanation=msg)

                try:
                    request.port_id = network.get('port', None)
                except ValueError:
                    msg = _("Bad port format: port uuid is "
                            "not in proper format "
                            "(%s)") % network.get('port')
                    raise exc.HTTPBadRequest(explanation=msg)

                if request.port_id:
                    request.network_id = None
                    if not utils.is_neutron():
                        # port parameter is only for neutron v2.0
                        msg = _("Unknown argument: port")
                        raise exc.HTTPBadRequest(explanation=msg)
                    if request.address is not None:
                        msg = _("Specified Fixed IP '%(addr)s' cannot be used "
                                "with port '%(port)s': port already has "
                                "a Fixed IP allocated.") % {
                                    "addr": request.address,
                                    "port": request.port_id
                                }
                        raise exc.HTTPBadRequest(explanation=msg)
                else:
                    request.network_id = network['uuid']

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

                if (request.network_id
                        and request.network_id in network_uuids):
                    expl = (_("Duplicate networks"
                              " (%s) are not allowed") % request.network_id)
                    raise exc.HTTPBadRequest(explanation=expl)
                network_uuids.append(request.network_id)
                networks.append(request)
            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 objects.NetworkRequestList(objects=networks)
Example #36
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:
                # 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)

                port_id = network.get('port', None)
                if port_id:
                    network_uuid = None
                    if not utils.is_neutron():
                        # port parameter is only for neutron v2.0
                        msg = _("Unknown argument: port")
                        raise exc.HTTPBadRequest(explanation=msg)
                    if not uuidutils.is_uuid_like(port_id):
                        msg = _("Bad port format: port uuid is "
                                "not in proper format "
                                "(%s)") % port_id
                        raise exc.HTTPBadRequest(explanation=msg)
                    if address is not None:
                        msg = _("Specified Fixed IP '%(addr)s' cannot be used "
                                "with port '%(port)s': port already has "
                                "a Fixed IP allocated.") % {
                                    "addr": address,
                                    "port": port_id
                                }
                        raise exc.HTTPBadRequest(explanation=msg)
                else:
                    network_uuid = network['uuid']

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

                # For neutronv2, requested_networks
                # should be tuple of (network_uuid, fixed_ip, port_id)
                if utils.is_neutron():
                    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
Example #37
0
 def fake_vol_api_func(context, volume, *args):
     self.assertTrue(uuidutils.is_uuid_like(volume))
     return {}
Example #38
0
 def fake_vol_api_roll_detaching(context, volume_id):
     self.assertTrue(uuidutils.is_uuid_like(volume_id))
     if volumes[volume_id]['status'] == 'detaching':
         volumes[volume_id]['status'] = 'in-use'
Example #39
0
 def fake_vol_api_begin_detaching(context, volume_id):
     self.assertTrue(uuidutils.is_uuid_like(volume_id))
     volumes[volume_id]['status'] = 'detaching'
Example #40
0
def _validate_uuid_format(instance):
    return uuidutils.is_uuid_like(instance)
Example #41
0
 def validate_id(self, id):
     if not uuidutils.is_uuid_like(id):
         msg = _("Security group id should be uuid")
         self.raise_invalid_property(msg)
     return id
Example #42
0
 def fake_vol_attach(context, volume_id, instance_uuid, connector):
     self.assertTrue(uuidutils.is_uuid_like(volume_id))
     self.assertIn(volumes[volume_id]['status'],
                   ['available', 'attaching'])
     volumes[volume_id]['status'] = 'in-use'
Example #43
0
 def fake_vol_migrate_volume_completion(context, old_volume_id,
                                        new_volume_id, error=False):
     self.assertTrue(uuidutils.is_uuid_like(old_volume_id))
     self.assertTrue(uuidutils.is_uuid_like(old_volume_id))
     return {'save_volume_id': new_volume_id}
Example #44
0
 def fake_vol_unreserve(context, volume_id):
     self.assertTrue(uuidutils.is_uuid_like(volume_id))
     if volumes[volume_id]['status'] == 'attaching':
         volumes[volume_id]['status'] = 'available'
Example #45
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:
                # 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)

                port_id = network.get('port', None)
                if port_id:
                    network_uuid = None
                    if not utils.is_neutron():
                        # port parameter is only for neutron v2.0
                        msg = _("Unknown argument: port")
                        raise exc.HTTPBadRequest(explanation=msg)
                    if not uuidutils.is_uuid_like(port_id):
                        msg = _("Bad port format: port uuid is "
                                "not in proper format "
                                "(%s)") % port_id
                        raise exc.HTTPBadRequest(explanation=msg)
                    if address is not None:
                        msg = _("Specified Fixed IP '%(addr)s' cannot be used "
                                "with port '%(port)s': port already has "
                                "a Fixed IP allocated.") % {"addr": address,
                                                            "port": port_id}
                        raise exc.HTTPBadRequest(explanation=msg)
                else:
                    network_uuid = network['uuid']

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

                # For neutronv2, requested_networks
                # should be tuple of (network_uuid, fixed_ip, port_id)
                if utils.is_neutron():
                    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
Example #46
0
 def fake_vol_detach(context, volume_id):
     self.assertTrue(uuidutils.is_uuid_like(volume_id))
     volumes[volume_id]['status'] = 'available'
Example #47
0
 def _validate_volume_id(self, volume_id):
     if not uuidutils.is_uuid_like(volume_id):
         msg = _("Bad volumeId format: volumeId is " "not in proper format (%s)") % volume_id
         raise exc.HTTPBadRequest(explanation=msg)
Example #48
0
File: api.py Project: blahRus/nova
 def _get_instance(self, context, instance_uuid):
     if uuidutils.is_uuid_like(instance_uuid):
         instance = self.db.instance_get_by_uuid(context, instance_uuid)
     else:
         instance = self.db.instance_get(context, instance_uuid)
     return instance