示例#1
0
 def add_item(self, context, name, body, scope=None):
     # expected that either network is provided in parameters or
     # default network exists (as in Google)
     network = self._get_network_by_url(
         context, body.get('network', CONF.default_network_name))
     self._check_rules(body)
     default_description = _("Firewall rules for network {}")
     group_description = body.get(
         "description", default_description.format(network['name']))
     client = clients.nova(context)
     operation_util.start_operation(context)
     sg = client.security_groups.create(body['name'], group_description)
     try:
         rules = self._convert_to_secgroup_rules(body)
         for rule in rules:
             client.security_group_rules.create(
                 sg.id,
                 ip_protocol=rule["protocol"],
                 from_port=rule["from_port"],
                 to_port=rule["to_port"],
                 cidr=rule["cidr"],
             )
     except Exception:
         client.security_groups.delete(sg)
         raise
     new_firewall = utils.to_dict(client.security_groups.get(sg.id))
     new_firewall = self._prepare_firewall(new_firewall)
     new_firewall["network_name"] = network["name"]
     new_firewall = self._add_db_item(context, new_firewall)
     self._process_callbacks(context, base_api._callback_reasons.post_add,
                             new_firewall)
     return new_firewall
示例#2
0
 def delete_item(self, context, name, scope=None):
     routes, aliased_routes = self._sync_routes(context)
     route = routes[name]
     if route.get("nexthop") is None:
         raise exception.InvalidInput(
             _("The local route cannot be deleted."))
     destination = route["destination"]
     nexthop = route["nexthop"]
     # NOTE(ft): delete OS route only if it doesn't have aliases
     # at the moment
     client = clients.neutron(context)
     operation_util.start_operation(context)
     if self._get_route_key(route) not in aliased_routes:
         dummy, router = self._get_network_objects(client, route["network"])
         if "external_gateway_info" in route:
             client.remove_gateway_router(router["id"])
         else:
             routes = [
                 r for r in router["routes"]
                 if (destination != r["destination"]
                     or nexthop != r["nexthop"])
             ]
             client.update_router(router["id"], {
                 "router": {
                     "routes": routes,
                 },
             })
     self._delete_db_item(context, route)
示例#3
0
 def delete_item(self, context, name, scope=None):
     routes, aliased_routes = self._sync_routes(context)
     route = routes[name]
     if route.get("nexthop") is None:
         raise exception.InvalidInput(
                 _("The local route cannot be deleted."))
     destination = route["destination"]
     nexthop = route["nexthop"]
     # NOTE(ft): delete OS route only if it doesn't have aliases
     # at the moment
     client = clients.neutron(context)
     operation_util.start_operation(context)
     if self._get_route_key(route) not in aliased_routes:
         dummy, router = self._get_network_objects(client,
                                                   route["network"])
         if "external_gateway_info" in route:
             client.remove_gateway_router(router["id"])
         else:
             routes = [r for r in router["routes"]
                       if (destination != r["destination"] or
                           nexthop != r["nexthop"])]
             client.update_router(
                     router["id"],
                     {"router": {"routes": routes, }, })
     self._delete_db_item(context, route)
示例#4
0
    def add_item(self, context, name, body, scope=None):
        routes, dummy = self._sync_routes(context)
        if name in routes:
            raise exception.InvalidInput(
                    _("The resource '%s' already exists.") % name)

        # NOTE(ft): check network is plugged to router
        network_name = utils._extract_name_from_url(body["network"])
        network = network_api.API().get_item(context, network_name)

        nexthop = body.get("nextHopGateway")
        if (nexthop is not None and
                (utils._extract_name_from_url(nexthop) ==
                 "default-internet-gateway") and
                # NOTE(ft): OS doesn't support IP mask for external gateway
                body.get("destRange") == ALL_IP_CIDR):
            operation_util.start_operation(context)
            return self._create_internet_route(context, network, body)

        nexthop = body.get("nextHopIp")
        if nexthop is not None:
            operation_util.start_operation(context)
            return self._create_custom_route(context, network, body)

        raise exception.InvalidInput(_("Unsupported route."))
示例#5
0
 def delete_item(self, context, name, scope=None):
     """Delete an image, if allowed."""
     image = self.get_item(context, name, scope)
     image_service = clients.glance(context).images
     operation_util.start_operation(context, self._get_delete_item_progress, image["id"])
     image_service.delete(image["id"])
     self._delete_db_item(context, image)
示例#6
0
 def add_item(self, context, name, body, scope=None):
     network = self._get_network_by_url(context, body['network'])
     self._check_rules(body)
     group_description = body.get("description", "")
     client = clients.nova(context)
     operation_util.start_operation(context)
     sg = client.security_groups.create(body['name'], group_description)
     try:
         rules = self._convert_to_secgroup_rules(body)
         for rule in rules:
             client.security_group_rules.create(
                 sg.id, ip_protocol=rule["protocol"],
                 from_port=rule["from_port"], to_port=rule["to_port"],
                 cidr=rule["cidr"], )
     except Exception:
         client.security_groups.delete(sg)
         raise
     new_firewall = utils.to_dict(client.security_groups.get(sg.id))
     new_firewall = self._prepare_firewall(new_firewall)
     new_firewall["creationTimestamp"] = 1
     new_firewall["network_name"] = network["name"]
     new_firewall = self._add_db_item(context, new_firewall)
     self._process_callbacks(
         context, base_api._callback_reasons.post_add, new_firewall)
     return new_firewall
示例#7
0
    def add_item(self, context, name, body, scope=None):
        sizeGb = int(body['sizeGb']) if 'sizeGb' in body else None

        snapshot_uri = body.get("sourceSnapshot")
        image_uri = body.get("sourceImage")
        snapshot_id = None
        image_id = None

        client = clients.cinder(context)
        if snapshot_uri:
            snapshot_name = utils._extract_name_from_url(snapshot_uri)
            snapshots = client.volume_snapshots.list(
                search_opts={"display_name": snapshot_name})
            if not snapshots or len(snapshots) != 1:
                raise exception.NotFound
            snapshot_id = snapshots[0].id
        elif image_uri:
            image_name = utils._extract_name_from_url(image_uri)
            image = image_api.API().get_item(context, image_name, scope)
            image_id = image['id']
            # Cinder API doesn't get size from image, so we do this
            image_size_in_gb = (int(image['size']) + GB - 1) / GB
            if not sizeGb or sizeGb < image_size_in_gb:
                sizeGb = image_size_in_gb

        operation_util.start_operation(context, self._get_add_item_progress)
        volume = client.volumes.create(
            sizeGb, snapshot_id=snapshot_id,
            display_name=body.get('name'),
            display_description=body.get('description'),
            imageRef=image_id,
            availability_zone=scope.get_name())
        operation_util.set_item_id(context, volume.id)

        return self._prepare_item(client, utils.to_dict(volume))
示例#8
0
 def add_item(self, context, name, body, scope=None):
     # expected that either network is provided in parameters or
     # default network exists (as in Google)
     network = self._get_network_by_url(
         context,
         body.get('network', CONF.default_network_name)
     )
     self._check_rules(body)
     default_description = _("Firewall rules for network {}")
     group_description = body.get(
         "description",
         default_description.format(network['name'])
     )
     client = clients.nova(context)
     operation_util.start_operation(context)
     sg = client.security_groups.create(body['name'], group_description)
     try:
         rules = self._convert_to_secgroup_rules(body)
         for rule in rules:
             client.security_group_rules.create(
                 sg.id, ip_protocol=rule["protocol"],
                 from_port=rule["from_port"], to_port=rule["to_port"],
                 cidr=rule["cidr"], )
     except Exception:
         client.security_groups.delete(sg)
         raise
     new_firewall = utils.to_dict(client.security_groups.get(sg.id))
     new_firewall = self._prepare_firewall(new_firewall)
     new_firewall["network_name"] = network["name"]
     new_firewall = self._add_db_item(context, new_firewall)
     self._process_callbacks(
         context, base_api._callback_reasons.post_add, new_firewall)
     return new_firewall
示例#9
0
 def delete_item(self, context, name, scope=None):
     client = clients.cinder(context).volume_snapshots
     snapshots = client.list(search_opts={"display_name": name})
     if not snapshots or len(snapshots) != 1:
         raise exception.NotFound
     operation_util.start_operation(context, self._get_delete_item_progress,
                                    snapshots[0].id)
     client.delete(snapshots[0])
示例#10
0
 def delete_item(self, context, name, scope=None):
     client = clients.cinder(context).volume_snapshots
     snapshots = client.list(search_opts={"display_name": name})
     if not snapshots or len(snapshots) != 1:
         raise exception.NotFound
     operation_util.start_operation(context,
                                    self._get_delete_item_progress,
                                    snapshots[0].id)
     client.delete(snapshots[0])
示例#11
0
 def delete_item(self, context, name, scope=None):
     """Delete an image, if allowed."""
     image = self.get_item(context, name, scope)
     image_service = clients.glance(context).images
     operation_util.start_operation(context,
                                    self._get_delete_item_progress,
                                    image["id"])
     image_service.delete(image["id"])
     self._delete_db_item(context, image)
示例#12
0
 def set_common_instance_metadata(self, context, metadata_list):
     instance_metadata = dict([(x['key'], x['value'])
                               for x in metadata_list])
     operation_util.start_operation(context)
     ssh_keys = instance_metadata.pop('sshKeys', None)
     if ssh_keys:
         nova_client = clients.nova(context)
         for key_data in ssh_keys.split('\n'):
             user_name, ssh_key = key_data.split(":")
             self._update_key(nova_client, user_name, ssh_key)
示例#13
0
 def set_common_instance_metadata(self, context, metadata_list):
     instance_metadata = dict(
         [(x['key'], x['value']) for x in metadata_list])
     operation_util.start_operation(context)
     ssh_keys = instance_metadata.pop('sshKeys', None)
     if ssh_keys:
         nova_client = clients.nova(context)
         for key_data in ssh_keys.split('\n'):
             user_name, ssh_key = key_data.split(":")
             self._update_key(nova_client, user_name, ssh_key)
示例#14
0
 def delete_item(self, context, name, scope=None):
     network = self.get_item(context, name)
     self._process_callbacks(
         context, base_api._callback_reasons.check_delete, network)
     operation_util.start_operation(context)
     self._delete_db_item(context, network)
     self._process_callbacks(
         context, base_api._callback_reasons.pre_delete, network)
     client = clients.nova(context)
     client.networks.delete(network["id"])
示例#15
0
 def reset_instance(self, context, scope, name):
     client = clients.nova(context)
     instances = client.servers.list(search_opts={"name": name})
     if not instances or len(instances) != 1:
         raise exception.NotFound
     instance = instances[0]
     operation_util.start_operation(context,
                                    self._get_reset_instance_progress,
                                    instance.id)
     instance.reboot("HARD")
示例#16
0
    def add_item(self, context, instance_name, params, source, name,
                 auto_delete, scope):
        # NOTE(apavlov): name is a 'device_name' here
        if not name:
            msg = _("There is no name to assign.")
            raise exception.InvalidRequest(msg)

        nova_client = clients.nova(context)
        instances = nova_client.servers.list(
            search_opts={"name": instance_name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]

        devices = list()
        volumes_client = nova_client.volumes
        for server_volume in volumes_client.get_server_volumes(instance.id):
            devices.append(server_volume.device)
        device_name = None
        for letter in string.ascii_lowercase[1:]:
            device_name = "vd" + letter
            for device in devices:
                if device_name in device:
                    break
            else:
                break
        else:
            raise exception.OverQuota
        context.operation_data["device_name"] = device_name

        if source:
            volume_name = utils._extract_name_from_url(source)
            if not volume_name:
                msg = _("There is no volume to assign.")
                raise exception.NotFound(msg)
            volume = disk_api.API().get_item(context, volume_name, scope)
            context.operation_data["volume_id"] = volume["id"]
        elif params:
            params.setdefault("diskName", instance_name)
            context.operation_data["params"] = params
            context.operation_data["scope"] = scope
        else:
            msg = _('Disk config must contain either "source" or '
                    '"initializeParams".')
            raise exception.InvalidRequest(msg)

        context.operation_data["instance_id"] = instance.id
        context.operation_data["register_args"] = [
            instance_name, name, auto_delete
        ]
        operation_util.start_operation(
            context, base_api.API._get_complex_operation_progress)
        operation_util.continue_operation(context,
                                          lambda: self._attach_volume(context),
                                          timeout=0)
示例#17
0
 def delete_item(self, context, name, scope=None):
     firewall = self.get_item(context, name)
     operation_util.start_operation(context)
     self._process_callbacks(
         context, base_api._callback_reasons.pre_delete, firewall)
     client = clients.nova(context)
     try:
         client.security_groups.delete(firewall["id"])
         self._delete_db_item(context, firewall)
     except clients.novaclient.exceptions.ClientException as ex:
         raise exception.GceapiException(message=ex.message, code=ex.code)
示例#18
0
 def delete_item(self, context, name, scope=None):
     firewall = self.get_item(context, name)
     operation_util.start_operation(context)
     self._process_callbacks(context, base_api._callback_reasons.pre_delete,
                             firewall)
     client = clients.nova(context)
     try:
         client.security_groups.delete(firewall["id"])
         self._delete_db_item(context, firewall)
     except clients.novaclient.exceptions.ClientException as ex:
         raise exception.GceapiException(message=ex.message, code=ex.code)
示例#19
0
 def delete_item(self, context, name, scope=None):
     network = self.get_item(context, name)
     self._process_callbacks(context,
                             base_api._callback_reasons.check_delete,
                             network)
     operation_util.start_operation(context)
     self._delete_db_item(context, network)
     self._process_callbacks(context, base_api._callback_reasons.pre_delete,
                             network)
     client = clients.nova(context)
     client.networks.delete(network["id"])
示例#20
0
    def add_item(self, context, instance_name, params, source, name,
                 auto_delete, scope):
        # NOTE(apavlov): name is a 'device_name' here
        if not name:
            msg = _("There is no name to assign.")
            raise exception.InvalidRequest(msg)

        nova_client = clients.nova(context)
        instances = nova_client.servers.list(
            search_opts={"name": instance_name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]

        devices = list()
        volumes_client = nova_client.volumes
        for server_volume in volumes_client.get_server_volumes(instance.id):
            devices.append(server_volume.device)
        device_name = None
        for letter in string.ascii_lowercase[1:]:
            device_name = "vd" + letter
            for device in devices:
                if device_name in device:
                    break
            else:
                break
        else:
            raise exception.OverQuota
        context.operation_data["device_name"] = device_name

        if source:
            volume_name = utils._extract_name_from_url(source)
            if not volume_name:
                msg = _("There is no volume to assign.")
                raise exception.NotFound(msg)
            volume = disk_api.API().get_item(context, volume_name, scope)
            context.operation_data["volume_id"] = volume["id"]
        elif params:
            params.setdefault("diskName", instance_name)
            context.operation_data["params"] = params
            context.operation_data["scope"] = scope
        else:
            msg = _('Disk config must contain either "source" or '
                    '"initializeParams".')
            raise exception.InvalidRequest(msg)

        context.operation_data["instance_id"] = instance.id
        context.operation_data["register_args"] = [instance_name, name,
                                                   auto_delete]
        operation_util.start_operation(
            context, base_api.API._get_complex_operation_progress)
        operation_util.continue_operation(
            context, lambda: self._attach_volume(context), timeout=0)
示例#21
0
    def delete_item(self, context, instance_name, name):
        client = clients.nova(context)
        instances = client.servers.list(search_opts={"name": instance_name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]

        item = self.get_item(context, instance_name, name)
        floating_ip = item["addr"]
        operation_util.start_operation(context)
        instance.remove_floating_ip(floating_ip)
        self._delete_db_item(context, item)
示例#22
0
    def delete_item(self, context, instance_name, name):
        client = clients.nova(context)
        instances = client.servers.list(search_opts={"name": instance_name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]

        item = self.get_item(context, instance_name, name)
        floating_ip = item["addr"]
        operation_util.start_operation(context)
        instance.remove_floating_ip(floating_ip)
        self._delete_db_item(context, item)
示例#23
0
 def add_item(self, context, name, body, scope=None):
     client = clients.nova(context)
     if any(x["name"] == name
            for x in self._get_floating_ips(client, context, scope)):
         raise exception.InvalidInput(
                 _("The resource '%s' already exists.") % name)
     operation_util.start_operation(context)
     result = client.floating_ips.create()
     floating_ip = self._prepare_floating_ip(client, context, result, scope)
     floating_ip["name"] = body["name"]
     if "description" in body:
         floating_ip["description"] = body["description"]
     floating_ip = self._add_db_item(context, floating_ip)
     return floating_ip
示例#24
0
 def add_item(self, context, name, body, scope=None):
     client = clients.nova(context)
     if any(x["name"] == name
            for x in self._get_floating_ips(client, context, scope)):
         raise exception.InvalidInput(
             _("The resource '%s' already exists.") % name)
     operation_util.start_operation(context)
     result = client.floating_ips.create()
     floating_ip = self._prepare_floating_ip(client, context, result, scope)
     floating_ip["name"] = body["name"]
     if "description" in body:
         floating_ip["description"] = body["description"]
     floating_ip = self._add_db_item(context, floating_ip)
     return floating_ip
示例#25
0
    def add_item(self, context, body, scope=None):
        name = body["name"]
        disk_name = body["disk_name"]
        client = clients.cinder(context)
        volumes = client.volumes.list(search_opts={"display_name": disk_name})
        if not volumes or len(volumes) != 1:
            raise exception.NotFound

        operation_util.start_operation(context, self._get_add_item_progress)
        snapshot = client.volume_snapshots.create(volumes[0].id, True, name,
                                                  body.get("description"))
        operation_util.set_item_id(context, snapshot.id, self.KIND)

        return self._prepare_item(client, utils.to_dict(snapshot))
示例#26
0
    def add_item(self, context, body, scope=None):
        name = body["name"]
        disk_name = body["disk_name"]
        client = clients.cinder(context)
        volumes = client.volumes.list(search_opts={"display_name": disk_name})
        if not volumes or len(volumes) != 1:
            raise exception.NotFound

        operation_util.start_operation(context, self._get_add_item_progress)
        snapshot = client.volume_snapshots.create(
            volumes[0].id, True, name, body["description"])
        operation_util.set_item_id(context, snapshot.id)

        return self._prepare_item(client, utils.to_dict(snapshot))
示例#27
0
 def add_item(self, context, name, body, scope=None):
     if any(x["name"] == name
            for x in self._get_floating_ips(context, scope)):
         raise exception.InvalidInput(
                 _("The resource '%s' already exists.") % name)
     public_network_id = network_api.API().get_public_network_id(context)
     operation_util.start_operation(context)
     floating_ip = clients.neutron(context).create_floatingip(
         {"floatingip": {"floating_network_id": public_network_id}})
     floating_ip = self._prepare_floating_ip(
         clients.nova(context), floating_ip["floatingip"], scope)
     floating_ip["name"] = body["name"]
     if "description" in body:
         floating_ip["description"] = body["description"]
     floating_ip = self._add_db_item(context, floating_ip)
     return floating_ip
示例#28
0
    def delete_item(self, context, instance_name, name):
        item = self.get_item(context, instance_name, name)
        volume_id = item["volume_id"]

        nova_client = clients.nova(context)
        instances = nova_client.servers.list(
            search_opts={"name": instance_name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]

        operation_util.start_operation(context, self._get_delete_item_progress,
                                       item["id"])
        nova_client.volumes.delete_server_volume(instance.id, volume_id)

        self._delete_db_item(context, item)
示例#29
0
    def delete_item(self, context, instance_name, name):
        item = self.get_item(context, instance_name, name)
        volume_id = item["volume_id"]

        nova_client = clients.nova(context)
        instances = nova_client.servers.list(
            search_opts={"name": instance_name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]

        operation_util.start_operation(context,
                                       self._get_delete_item_progress,
                                       item["id"])
        nova_client.volumes.delete_server_volume(instance.id, volume_id)

        self._delete_db_item(context, item)
示例#30
0
 def add_item(self, context, name, body, scope=None):
     if any(x["name"] == name
            for x in self._get_floating_ips(context, scope)):
         raise exception.InvalidInput(
             _("The resource '%s' already exists.") % name)
     public_network_id = network_api.API().get_public_network_id(context)
     operation_util.start_operation(context)
     floating_ip = clients.neutron(context).create_floatingip(
         {"floatingip": {
             "floating_network_id": public_network_id
         }})
     floating_ip = self._prepare_floating_ip(clients.nova(context),
                                             floating_ip["floatingip"],
                                             scope)
     floating_ip["name"] = body["name"]
     if "description" in body:
         floating_ip["description"] = body["description"]
     floating_ip = self._add_db_item(context, floating_ip)
     return floating_ip
示例#31
0
    def delete_item(self, context, name, scope=None):
        client = clients.nova(context)
        instances = client.servers.list(search_opts={"name": name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]
        operation_util.start_operation(
            context, base_api.API._get_complex_operation_progress)

        ads = instance_disk_api.API().get_items(context, instance.name)
        disks_to_delete = []
        for ad in ads:
            if ad["auto_delete"]:
                disks_to_delete.append(ad)

        if not disks_to_delete:
            operation_util.set_item_id(context, instance.id, self.KIND)

        client = clients.nova(context)
        instance.delete()
        instance = utils.to_dict(instance)
        instance = self._prepare_instance(client, context, instance)
        self._delete_db_item(context, instance)

        ads = instance_disk_api.API().get_items(context, instance["name"])
        for ad in ads:
            ad = instance_disk_api.API().unregister_item(context,
                instance["name"], ad["name"])

        acs = instance_address_api.API().get_items(context, instance["name"])
        for ac in acs:
            ac = instance_address_api.API().unregister_item(context,
                instance["name"], ac["name"])

        if not disks_to_delete:
            return

        context.operation_data["scope"] = scope
        context.operation_data["count"] = 1 + len(disks_to_delete)
        context.operation_data["instance"] = instance
        context.operation_data["disks"] = disks_to_delete
        operation_util.continue_operation(
            context, lambda: self._delete_instance(context))
示例#32
0
 def add_item(self, context, name, body, scope=None):
     ip_range = body.get('IPv4Range', CONF.default_network_ip_range)
     gateway = body.get('gatewayIPv4')
     if gateway is None:
         network_cidr = netaddr.IPNetwork(ip_range)
         gateway_ip = netaddr.IPAddress(network_cidr.first + 1)
         gateway = str(gateway_ip)
     client = clients.neutron(context)
     network = None
     try:
         network = self.get_item(context, name)
     except exception.NotFound:
         pass
     if network is not None:
         raise exception.DuplicateVlan
     network_body = {}
     network_body["network"] = {"name": name}
     operation_util.start_operation(context)
     network = client.create_network(network_body)
     network = network["network"]
     if ip_range:
         subnet_body = {}
         subnet_body["subnet"] = {
             # NOTE(Alex) "name": name + ".default_subnet",
             # Won't give it a name for now
             "network_id": network["id"],
             "ip_version": "4",
             "cidr": ip_range,
             "gateway_ip": gateway
         }
         result_data = client.create_subnet(subnet_body)
         subnet_id = result_data["subnet"]["id"]
     network = self._prepare_network(client, network)
     if 'description' in body:
         network["description"] = body["description"]
     network = self._add_db_item(context, network)
     self._process_callbacks(context,
                             base_api._callback_reasons.post_add,
                             network,
                             subnet_id=subnet_id)
     return network
示例#33
0
    def add_item(self, context, name, body, scope=None):
        name = body["name"]
        image_ref = body["rawDisk"]["source"]
        meta = {
            "name": name,
            "disk_format": "raw",
            "container_format": "bare",
            "min_disk": 0,
            "min_ram": 0,
            "copy_from": image_ref,
        }
        image_service = clients.glance(context).images
        operation_util.start_operation(context, self._get_add_item_progress)
        image = image_service.create(**meta)
        operation_util.set_item_id(context, image.id, self.KIND)

        new_image = self._prepare_image(utils.to_dict(image))
        new_image["description"] = body.get("description", "")
        new_image["image_ref"] = image_ref
        new_image = self._add_db_item(context, new_image)
        return new_image
示例#34
0
    def add_item(self, context, name, body, scope=None):
        name = body['name']
        image_ref = body['rawDisk']['source']
        meta = {
            'name': name,
            'disk_format': 'raw',
            'container_format': 'bare',
            'min_disk': 0,
            'min_ram': 0,
            'copy_from': image_ref,
        }
        image_service = clients.glance(context).images
        operation_util.start_operation(context, self._get_add_item_progress)
        image = image_service.create(**meta)
        operation_util.set_item_id(context, image.id)

        new_image = self._prepare_image(utils.to_dict(image))
        new_image["description"] = body.get("description", "")
        new_image["image_ref"] = image_ref
        new_image = self._add_db_item(context, new_image)
        return new_image
示例#35
0
    def add_item(self, context, name, body, scope=None):
        name = body['name']
        image_ref = body['rawDisk']['source']
        meta = {
            'name': name,
            'disk_format': 'raw',
            'container_format': 'bare',
            'min_disk': 0,
            'min_ram': 0,
            'copy_from': image_ref,
        }
        image_service = clients.glance(context).images
        operation_util.start_operation(context, self._get_add_item_progress)
        image = image_service.create(**meta)
        operation_util.set_item_id(context, image.id, self.KIND)

        new_image = self._prepare_image(utils.to_dict(image))
        new_image["description"] = body.get("description", "")
        new_image["image_ref"] = image_ref
        new_image = self._add_db_item(context, new_image)
        return new_image
示例#36
0
 def add_item(self, context, name, body, scope=None):
     ip_range = body.get('IPv4Range', CONF.default_network_ip_range)
     gateway = body.get('gatewayIPv4')
     if gateway is None:
         network_cidr = netaddr.IPNetwork(ip_range)
         gateway_ip = netaddr.IPAddress(network_cidr.first + 1)
         gateway = str(gateway_ip)
     client = clients.neutron(context)
     network = None
     try:
         network = self.get_item(context, name)
     except exception.NotFound:
         pass
     if network is not None:
         raise exception.DuplicateVlan
     network_body = {}
     network_body["network"] = {"name": name}
     operation_util.start_operation(context)
     network = client.create_network(network_body)
     network = network["network"]
     if ip_range:
         subnet_body = {}
         subnet_body["subnet"] = {
             # NOTE(Alex) "name": name + ".default_subnet",
             # Won't give it a name for now
             "network_id": network["id"],
             "ip_version": "4",
             "cidr": ip_range,
             "gateway_ip": gateway}
         result_data = client.create_subnet(subnet_body)
         subnet_id = result_data["subnet"]["id"]
     network = self._prepare_network(client, network)
     if 'description' in body:
         network["description"] = body["description"]
     network = self._add_db_item(context, network)
     self._process_callbacks(
         context, base_api._callback_reasons.post_add,
         network, subnet_id=subnet_id)
     return network
示例#37
0
    def add_item(self, context, name, body, scope=None):
        sizeGb = body.get("sizeGb")
        sizeGb = int(sizeGb) if sizeGb else None

        snapshot_uri = body.get("sourceSnapshot")
        image_uri = body.get("sourceImage")
        snapshot_id = None
        image_id = None

        client = clients.cinder(context)
        if snapshot_uri:
            snapshot_name = utils._extract_name_from_url(snapshot_uri)
            snapshots = client.volume_snapshots.list(
                search_opts={"display_name": snapshot_name})
            if not snapshots or len(snapshots) != 1:
                raise exception.NotFound
            snapshot_id = snapshots[0].id
        elif image_uri:
            image_name = utils._extract_name_from_url(image_uri)
            image = image_api.API().get_item(context, image_name, scope)
            image_id = image['id']
            # Cinder API doesn't get size from image, so we do this
            image_size_in_gb = (int(image['size']) + GB - 1) / GB
            if not sizeGb or sizeGb < image_size_in_gb:
                sizeGb = image_size_in_gb
        else:
            if not sizeGb:
                sizeGb = CONF.default_volume_size_gb

        operation_util.start_operation(context, self._get_add_item_progress)
        volume = client.volumes.create(
            sizeGb, snapshot_id=snapshot_id,
            display_name=body.get('name', name),
            display_description=body.get('description'),
            imageRef=image_id,
            availability_zone=scope.get_name())
        operation_util.set_item_id(context, volume.id, self.KIND)

        return self._prepare_item(client, utils.to_dict(volume))
示例#38
0
 def add_item(self, context, name, body, scope=None):
     ip_range = body.get('IPv4Range', CONF.default_network_ip_range)
     gateway = body.get('gatewayIPv4')
     if gateway is None:
         network_cidr = netaddr.IPNetwork(ip_range)
         gateway_ip = netaddr.IPAddress(network_cidr.first + 1)
         gateway = str(gateway_ip)
     network = None
     try:
         network = self.get_item(context, name)
     except exception.NotFound:
         pass
     if network is not None:
         raise exception.DuplicateVlan
     kwargs = {'label': name, 'cidr': ip_range, 'gateway': gateway}
     client = clients.nova(context)
     operation_util.start_operation(context)
     network = client.networks.create(**kwargs)
     network = self._prepare_network(utils.to_dict(network))
     if "description" in body:
         network["description"] = body["description"]
     return self._add_db_item(context, network)
示例#39
0
 def add_item(self, context, name, body, scope=None):
     ip_range = body.get('IPv4Range', CONF.default_network_ip_range)
     gateway = body.get('gatewayIPv4')
     if gateway is None:
         network_cidr = netaddr.IPNetwork(ip_range)
         gateway_ip = netaddr.IPAddress(network_cidr.first + 1)
         gateway = str(gateway_ip)
     network = None
     try:
         network = self.get_item(context, name)
     except exception.NotFound:
         pass
     if network is not None:
         raise exception.DuplicateVlan
     kwargs = {'label': name, 'cidr': ip_range, 'gateway': gateway}
     client = clients.nova(context)
     operation_util.start_operation(context)
     network = client.networks.create(**kwargs)
     network = self._prepare_network(utils.to_dict(network))
     if "description" in body:
         network["description"] = body["description"]
     return self._add_db_item(context, network)
示例#40
0
    def delete_item(self, context, name, scope=None):
        client = clients.nova(context)
        instances = client.servers.list(search_opts={"name": name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]
        operation_util.start_operation(context,
                                       self._get_delete_item_progress,
                                       instance.id)
        instance.delete()
        instance = utils.to_dict(instance)
        instance = self._prepare_instance(client, context, instance)
        self._delete_db_item(context, instance)

        ads = instance_disk_api.API().get_items(context, instance["name"])
        for ad in ads:
            ad = instance_disk_api.API().unregister_item(context,
                instance["name"], ad["name"])

        acs = instance_address_api.API().get_items(context, instance["name"])
        for ac in acs:
            ac = instance_address_api.API().unregister_item(context,
                instance["name"], ac["name"])
示例#41
0
    def add_item(self, context, name, body, scope=None):
        routes, dummy = self._sync_routes(context)
        if name in routes:
            raise exception.InvalidInput(
                _("The resource '%s' already exists.") % name)

        # NOTE(ft): check network is plugged to router
        network_name = utils._extract_name_from_url(body["network"])
        network = network_api.API().get_item(context, network_name)

        nexthop = body.get("nextHopGateway")
        if (nexthop is not None and (utils._extract_name_from_url(nexthop)
                                     == "default-internet-gateway") and
                # NOTE(ft): OS doesn't support IP mask for external gateway
                body.get("destRange") == ALL_IP_CIDR):
            operation_util.start_operation(context)
            return self._create_internet_route(context, network, body)

        nexthop = body.get("nextHopIp")
        if nexthop is not None:
            operation_util.start_operation(context)
            return self._create_custom_route(context, network, body)

        raise exception.InvalidInput(_("Unsupported route."))
示例#42
0
    def add_item(self, context, instance_name, nic, addr, addr_type, name):
        if not nic:
            msg = _("Network interface is invalid or empty")
            raise exception.InvalidRequest(msg)

        if addr_type is None:
            addr_type = self.DEFAULT_ACCESS_CONFIG_TYPE
        elif addr_type != self.DEFAULT_ACCESS_CONFIG_TYPE:
            msg = _("Only '%s' type of access config currently supported.")\
                    % self.DEFAULT_ACCESS_CONFIG_TYPE
            raise exception.InvalidRequest(msg)

        client = clients.nova(context)
        instances = client.servers.list(search_opts={"name": instance_name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]

        fixed_ip = None
        for network in instance.addresses:
            if nic != network:
                continue
            for address in instance.addresses[network]:
                atype = address["OS-EXT-IPS:type"]
                if atype == "floating":
                    msg = _('At most one access config currently supported.')
                    raise exception.InvalidRequest(msg)
                if atype == "fixed":
                    fixed_ip = address["addr"]

        if not fixed_ip:
            msg = _('Network interface not found')
            raise exception.InvalidRequest(msg)

        floating_ips = client.floating_ips.list()
        if addr is None:
            # NOTE(apavlov): try to find unused
            for floating_ip in floating_ips:
                if floating_ip.instance_id is None:
                    addr = floating_ip.ip
                    break
            else:
                msg = _('There is no unused floating ips.')
                raise exception.InvalidRequest(msg)
        else:
            for floating_ip in floating_ips:
                if floating_ip.ip != addr:
                    continue
                if floating_ip.instance_id is None:
                    break
                msg = _("Floating ip '%s' is already associated") % floating_ip
                raise exception.InvalidRequest(msg)
            else:
                msg = _("There is no such floating ip '%s'.") % addr
                raise exception.InvalidRequest(msg)

        operation_util.start_operation(context)
        instance.add_floating_ip(addr, fixed_ip)

        return self.register_item(context, instance_name, nic, addr, addr_type,
                                  name)
示例#43
0
    def add_item(self, context, name, body, scope=None):
        name = body['name']
        client = clients.nova(context)

        flavor_name = utils._extract_name_from_url(body['machineType'])
        flavor_id = machine_type_api.API().get_item(
            context, flavor_name, scope)["id"]

        nics = []
        #NOTE(ft) 'default' security group contains output rules
        #but output rules doesn't configurable by GCE API
        #all outgoing traffic permitted
        #so we support this behaviour
        groups_names = set(['default'])
        acs = dict()
        for net_iface in body['networkInterfaces']:
            net_name = utils._extract_name_from_url(net_iface["network"])
            ac = net_iface.get("accessConfigs")
            if ac:
                if len(ac) > 1:
                    msg = _('At most one access config currently supported.')
                    raise exception.InvalidRequest(msg)
                else:
                    acs[net_name] = ac[0]

            network = network_api.API().get_item(context, net_name, None)
            nics.append({"net-id": network["id"]})
            for sg in firewall_api.API().get_network_firewalls(
                    context, net_name):
                groups_names.add(sg["name"])
        groups_names = list(groups_names)

        try:
            metadatas = body['metadata']['items']
        except KeyError:
            metadatas = []
        instance_metadata = dict([(x['key'], x['value']) for x in metadatas])

        disks = body.get('disks', [])
        for disk in disks:
            disk["boot"] = True if "initializeParams" in disk else False
            if "source" in disk:
                volume_name = utils._extract_name_from_url(disk["source"])
                volume = disk_api.API().get_item(context, volume_name, scope)
                disk["id"] = volume["id"]
            elif "initializeParams" not in disk:
                msg = _('Disk config must contain either "source" or '
                        '"initializeParams".')
                raise exception.InvalidRequest(msg)
        disks.sort(None, lambda x: x.get("boot", False), True)

        ssh_keys = instance_metadata.pop('sshKeys', None)
        if ssh_keys is not None:
            key = ssh_keys.split('\n')[0].split(":")
            key_name = key[0] + "-" + str(random.randint(10000, 99999))
            key_data = key[1]
            client.keypairs.create(key_name, key_data)
        else:
            key_name = project_api.API().get_gce_user_keypair_name(context)

        operation_util.start_operation(
            context, base_api.API._get_complex_operation_progress)

        context.operation_data["acs"] = acs
        context.operation_data["ssh_keys"] = ssh_keys

        context.operation_data["bdm"] = dict()
        context.operation_data["disk_device"] = 0
        context.operation_data["disks"] = disks

        context.operation_data["scope"] = scope
        context.operation_data["args"] = [name, None, flavor_id]
        context.operation_data["kwargs"] = {"meta": instance_metadata,
            "min_count": 1, "max_count": 1, "nics": nics,
            "security_groups": groups_names, "key_name": key_name}
        context.operation_data["description"] = body.get("description")

        operation_util.continue_operation(
            context, lambda: self._create_instance(context))
示例#44
0
    def add_item(self, context, name, body, scope=None):
        name = body['name']
        client = clients.nova(context)

        flavor_name = utils._extract_name_from_url(body['machineType'])
        flavor_id = machine_type_api.API().get_item(
            context, flavor_name, scope)["id"]

        try:
            metadatas = body['metadata']['items']
        except KeyError:
            metadatas = []
        instance_metadata = dict([(x['key'], x['value']) for x in metadatas])

        ssh_keys = instance_metadata.pop('sshKeys', None)
        if ssh_keys is not None:
            key_name = ssh_keys.split('\n')[0].split(":")[0]
        else:
            key_name = project_api.API().get_gce_user_keypair_name(context)

        disks = body.get('disks', [])
        disks.sort(None, lambda x: x.get("boot", False), True)
        bdm = dict()
        diskDevice = 0
        for disk in disks:
            device_name = "vd" + string.ascii_lowercase[diskDevice]
            volume_name = utils._extract_name_from_url(disk["source"])
            volume = disk_api.API().get_item(context, volume_name, scope)
            disk["id"] = volume["id"]
            bdm[device_name] = volume["id"]
            diskDevice += 1

        nics = []
        #NOTE(ft) 'default' security group contains output rules
        #but output rules doesn't configurable by GCE API
        #all outgoing traffic permitted
        #so we support this behaviour
        groups_names = set(['default'])
        acs = dict()
        for net_iface in body['networkInterfaces']:
            net_name = utils._extract_name_from_url(net_iface["network"])
            ac = net_iface.get("accessConfigs")
            if ac:
                if len(ac) > 1:
                    msg = _('At most one access config currently supported.')
                    raise exception.InvalidRequest(msg)
                else:
                    acs[net_name] = ac[0]

            network = network_api.API().get_item(context, net_name, None)
            nics.append({"net-id": network["id"]})
            for sg in firewall_api.API().get_network_firewalls(
                    context, net_name):
                groups_names.add(sg["name"])
        groups_names = list(groups_names)

        operation_util.start_operation(context, self._get_add_item_progress)
        instance = client.servers.create(name, None, flavor_id,
            meta=instance_metadata, min_count=1, max_count=1,
            security_groups=groups_names, key_name=key_name,
            availability_zone=scope.get_name(), block_device_mapping=bdm,
            nics=nics)
        if not acs:
            operation_util.set_item_id(context, instance.id)

        for disk in disks:
            instance_disk_api.API().register_item(context, name,
                disk["id"], disk["deviceName"])

        instance = utils.to_dict(client.servers.get(instance.id))
        instance = self._prepare_instance(client, context, instance)
        if "descripton" in body:
            instance["description"] = body["description"]
        instance = self._add_db_item(context, instance)

        if acs:
            operation_util.continue_operation(
                    context,
                    lambda: self._add_access_config(context, instance,
                                                    scope, acs))

        return instance
示例#45
0
 def delete_item(self, context, name, scope=None):
     floating_ip = self._get_floating_ips(context, scope, name)[0]
     operation_util.start_operation(context)
     self._delete_db_item(context, floating_ip)
     clients.neutron(context).delete_floatingip(floating_ip["id"])
示例#46
0
 def delete_item(self, context, name, scope=None):
     client = clients.nova(context)
     floating_ip = self._get_floating_ips(client, context, scope, name)[0]
     operation_util.start_operation(context)
     self._delete_db_item(context, floating_ip)
     client.floating_ips.delete(floating_ip["id"])
示例#47
0
 def delete_item(self, context, name, scope=None):
     client = clients.nova(context)
     floating_ip = self._get_floating_ips(client, context, scope, name)[0]
     operation_util.start_operation(context)
     self._delete_db_item(context, floating_ip)
     client.floating_ips.delete(floating_ip["id"])
示例#48
0
 def delete_item(self, context, name, scope=None):
     floating_ip = self._get_floating_ips(context, scope, name)[0]
     operation_util.start_operation(context)
     self._delete_db_item(context, floating_ip)
     clients.neutron(context).delete_floatingip(floating_ip["id"])
示例#49
0
    def add_item(self, context, instance_name, nic, addr, addr_type, name):
        if not nic:
            msg = _("Network interface is invalid or empty")
            raise exception.InvalidRequest(msg)

        if addr_type is None:
            addr_type = self.DEFAULT_ACCESS_CONFIG_TYPE
        elif addr_type != self.DEFAULT_ACCESS_CONFIG_TYPE:
            msg = _("Only '%s' type of access config currently supported.")\
                    % self.DEFAULT_ACCESS_CONFIG_TYPE
            raise exception.InvalidRequest(msg)

        client = clients.nova(context)
        instances = client.servers.list(search_opts={"name": instance_name})
        if not instances or len(instances) != 1:
            raise exception.NotFound
        instance = instances[0]

        fixed_ip = None
        for network in instance.addresses:
            if nic != network:
                continue
            for address in instance.addresses[network]:
                atype = address["OS-EXT-IPS:type"]
                if atype == "floating":
                    msg = _('At most one access config currently supported.')
                    raise exception.InvalidRequest(msg)
                if atype == "fixed":
                    fixed_ip = address["addr"]

        if not fixed_ip:
            msg = _('Network interface not found')
            raise exception.InvalidRequest(msg)

        floating_ips = client.floating_ips.list()
        if addr is None:
            # NOTE(apavlov): try to find unused
            for floating_ip in floating_ips:
                if floating_ip.instance_id is None:
                    addr = floating_ip.ip
                    break
            else:
                msg = _('There is no unused floating ips.')
                raise exception.InvalidRequest(msg)
        else:
            for floating_ip in floating_ips:
                if floating_ip.ip != addr:
                    continue
                if floating_ip.instance_id is None:
                    break
                msg = _("Floating ip '%s' is already associated") % floating_ip
                raise exception.InvalidRequest(msg)
            else:
                msg = _("There is no such floating ip '%s'.") % addr
                raise exception.InvalidRequest(msg)

        operation_util.start_operation(context)
        instance.add_floating_ip(addr, fixed_ip)

        return self.register_item(context, instance_name,
                                  nic, addr, addr_type, name)