Exemplo n.º 1
0
class SecurityGroupList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              SecurityGroup <= version 1.1
    VERSION = '1.0'

    fields = {
        'objects': fields.ListOfObjectsField('SecurityGroup'),
    }

    def __init__(self, *args, **kwargs):
        super(SecurityGroupList, self).__init__(*args, **kwargs)
        self.objects = []
        self.obj_reset_changes()

    @base.remotable_classmethod
    def get_all(cls, context):
        groups = db.security_group_get_all(context)
        return base.obj_make_list(context, cls(context), objects.SecurityGroup,
                                  groups)

    @base.remotable_classmethod
    def get_by_project(cls, context, project_id):
        groups = db.security_group_get_by_project(context, project_id)
        return base.obj_make_list(context, cls(context), objects.SecurityGroup,
                                  groups)

    @base.remotable_classmethod
    def get_by_instance(cls, context, instance):
        groups = db.security_group_get_by_instance(context, instance.uuid)
        return base.obj_make_list(context, cls(context), objects.SecurityGroup,
                                  groups)
Exemplo n.º 2
0
class FlavorList(base.ObjectListBase, base.NovaObject):
    VERSION = '1.1'

    fields = {
        'objects': fields.ListOfObjectsField('Flavor'),
    }

    @base.remotable_classmethod
    def get_all(cls,
                context,
                inactive=False,
                filters=None,
                sort_key='flavorid',
                sort_dir='asc',
                limit=None,
                marker=None):
        db_flavors = db.flavor_get_all(context,
                                       inactive=inactive,
                                       filters=filters,
                                       sort_key=sort_key,
                                       sort_dir=sort_dir,
                                       limit=limit,
                                       marker=marker)
        return base.obj_make_list(context,
                                  cls(context),
                                  objects.Flavor,
                                  db_flavors,
                                  expected_attrs=['extra_specs'])
Exemplo n.º 3
0
class PciDeviceList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              PciDevice <= 1.1
    # Version 1.1: PciDevice 1.2
    # Version 1.2: PciDevice 1.3
    # Version 1.3: Adds get_by_parent_address
    VERSION = '1.3'

    fields = {
        'objects': fields.ListOfObjectsField('PciDevice'),
    }

    def __init__(self, *args, **kwargs):
        super(PciDeviceList, self).__init__(*args, **kwargs)
        self.objects = []
        self.obj_reset_changes()

    @base.remotable_classmethod
    def get_by_compute_node(cls, context, node_id):
        db_dev_list = db.pci_device_get_all_by_node(context, node_id)
        return base.obj_make_list(context, cls(context), objects.PciDevice,
                                  db_dev_list)

    @base.remotable_classmethod
    def get_by_instance_uuid(cls, context, uuid):
        db_dev_list = db.pci_device_get_all_by_instance_uuid(context, uuid)
        return base.obj_make_list(context, cls(context), objects.PciDevice,
                                  db_dev_list)

    @base.remotable_classmethod
    def get_by_parent_address(cls, context, node_id, parent_addr):
        db_dev_list = db.pci_device_get_all_by_parent_addr(
            context, node_id, parent_addr)
        return base.obj_make_list(context, cls(context), objects.PciDevice,
                                  db_dev_list)
Exemplo n.º 4
0
class VirtualInterfaceList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    VERSION = '1.0'
    fields = {
        'objects': fields.ListOfObjectsField('VirtualInterface'),
    }

    @base.remotable_classmethod
    def get_all(cls, context):
        db_vifs = db.virtual_interface_get_all(context)
        return base.obj_make_list(context, cls(context),
                                  objects.VirtualInterface, db_vifs)

    @staticmethod
    @db.select_db_reader_mode
    def _db_virtual_interface_get_by_instance(context,
                                              instance_uuid,
                                              use_slave=False):
        return db.virtual_interface_get_by_instance(context, instance_uuid)

    @base.remotable_classmethod
    def get_by_instance_uuid(cls, context, instance_uuid, use_slave=False):
        db_vifs = cls._db_virtual_interface_get_by_instance(
            context, instance_uuid, use_slave=use_slave)
        return base.obj_make_list(context, cls(context),
                                  objects.VirtualInterface, db_vifs)
Exemplo n.º 5
0
class BandwidthUsageList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: Add use_slave to get_by_uuids
    # Version 1.2: BandwidthUsage <= version 1.2
    VERSION = '1.2'
    fields = {
        'objects': fields.ListOfObjectsField('BandwidthUsage'),
    }

    @staticmethod
    @db.select_db_reader_mode
    def _db_bw_usage_get_by_uuids(context,
                                  uuids,
                                  start_period,
                                  use_slave=False):
        return db.bw_usage_get_by_uuids(context,
                                        uuids=uuids,
                                        start_period=start_period)

    @base.serialize_args
    @base.remotable_classmethod
    def get_by_uuids(cls, context, uuids, start_period=None, use_slave=False):
        db_bw_usages = cls._db_bw_usage_get_by_uuids(context,
                                                     uuids=uuids,
                                                     start_period=start_period,
                                                     use_slave=use_slave)
        return base.obj_make_list(context, cls(), BandwidthUsage, db_bw_usages)
Exemplo n.º 6
0
class SecurityGroupRuleList(base.ObjectListBase, base.NovaObject):
    fields = {
        'objects': fields.ListOfObjectsField('SecurityGroupRule'),
    }
    VERSION = '1.2'

    @base.remotable_classmethod
    def get_by_security_group_id(cls, context, secgroup_id):
        db_rules = db.security_group_rule_get_by_security_group(
            context, secgroup_id, columns_to_join=['grantee_group'])
        return base.obj_make_list(context,
                                  cls(context),
                                  objects.SecurityGroupRule,
                                  db_rules,
                                  expected_attrs=['grantee_group'])

    @classmethod
    def get_by_security_group(cls, context, security_group):
        return cls.get_by_security_group_id(context, security_group.id)

    @base.remotable_classmethod
    def get_by_instance_uuid(cls, context, instance_uuid):
        db_rules = db.security_group_rule_get_by_instance(
            context, instance_uuid)
        return base.obj_make_list(context,
                                  cls(context),
                                  objects.SecurityGroupRule,
                                  db_rules,
                                  expected_attrs=['grantee_group'])

    @classmethod
    def get_by_instance(cls, context, instance):
        return cls.get_by_instance_uuid(context, instance.uuid)
Exemplo n.º 7
0
class InstanceGroupList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              InstanceGroup <= version 1.3
    # Version 1.1: InstanceGroup <= version 1.4
    # Version 1.2: InstanceGroup <= version 1.5
    # Version 1.3: InstanceGroup <= version 1.6
    # Version 1.4: InstanceGroup <= version 1.7
    # Version 1.5: InstanceGroup <= version 1.8
    # Version 1.6: InstanceGroup <= version 1.9
    # Version 1.7: InstanceGroup <= version 1.10
    VERSION = '1.7'

    fields = {
        'objects': fields.ListOfObjectsField('InstanceGroup'),
        }

    @base.remotable_classmethod
    def get_by_project_id(cls, context, project_id):
        groups = db.instance_group_get_all_by_project_id(context, project_id)
        return base.obj_make_list(context, cls(context), objects.InstanceGroup,
                                  groups)

    @base.remotable_classmethod
    def get_all(cls, context):
        groups = db.instance_group_get_all(context)
        return base.obj_make_list(context, cls(context), objects.InstanceGroup,
                                  groups)
Exemplo n.º 8
0
class PciDevicePoolList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              PciDevicePool <= 1.0
    # Version 1.1: PciDevicePool version 1.1
    VERSION = '1.1'
    fields = {
             'objects': fields.ListOfObjectsField('PciDevicePool'),
             }
Exemplo n.º 9
0
class ServiceList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              Service <= version 1.2
    # Version 1.1  Service version 1.3
    # Version 1.2: Service version 1.4
    # Version 1.3: Service version 1.5
    # Version 1.4: Service version 1.6
    # Version 1.5: Service version 1.7
    # Version 1.6: Service version 1.8
    # Version 1.7: Service version 1.9
    # Version 1.8: Service version 1.10
    # Version 1.9: Added get_by_binary() and Service version 1.11
    # Version 1.10: Service version 1.12
    # Version 1.11: Service version 1.13
    # Version 1.12: Service version 1.14
    # Version 1.13: Service version 1.15
    # Version 1.14: Service version 1.16
    # Version 1.15: Service version 1.17
    # Version 1.16: Service version 1.18
    # Version 1.17: Service version 1.19
    # Version 1.18: Added include_disabled parameter to get_by_binary()
    VERSION = '1.18'

    fields = {
        'objects': fields.ListOfObjectsField('Service'),
        }

    @base.remotable_classmethod
    def get_by_topic(cls, context, topic):
        db_services = db.service_get_all_by_topic(context, topic)
        return base.obj_make_list(context, cls(context), objects.Service,
                                  db_services)

    # NOTE(paul-carlton2): In v2.0 of the object the include_disabled flag
    # will be removed so both enabled and disabled hosts are returned
    @base.remotable_classmethod
    def get_by_binary(cls, context, binary, include_disabled=False):
        db_services = db.service_get_all_by_binary(
            context, binary, include_disabled=include_disabled)
        return base.obj_make_list(context, cls(context), objects.Service,
                                  db_services)

    @base.remotable_classmethod
    def get_by_host(cls, context, host):
        db_services = db.service_get_all_by_host(context, host)
        return base.obj_make_list(context, cls(context), objects.Service,
                                  db_services)

    @base.remotable_classmethod
    def get_all(cls, context, disabled=None, set_zones=False):
        db_services = db.service_get_all(context, disabled=disabled)
        if set_zones:
            db_services = availability_zones.set_availability_zones(
                context, db_services)
        return base.obj_make_list(context, cls(context), objects.Service,
                                  db_services)
Exemplo n.º 10
0
class MigrationList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              Migration <= 1.1
    # Version 1.1: Added use_slave to get_unconfirmed_by_dest_compute
    # Version 1.2: Migration version 1.2
    # Version 1.3: Added a new function to get in progress migrations
    #              for an instance.
    VERSION = '1.3'

    fields = {
        'objects': fields.ListOfObjectsField('Migration'),
    }

    @staticmethod
    @db.select_db_reader_mode
    def _db_migration_get_unconfirmed_by_dest_compute(context,
                                                      confirm_window,
                                                      dest_compute,
                                                      use_slave=False):
        return db.migration_get_unconfirmed_by_dest_compute(
            context, confirm_window, dest_compute)

    @base.remotable_classmethod
    def get_unconfirmed_by_dest_compute(cls,
                                        context,
                                        confirm_window,
                                        dest_compute,
                                        use_slave=False):
        db_migrations = cls._db_migration_get_unconfirmed_by_dest_compute(
            context, confirm_window, dest_compute, use_slave=use_slave)
        return base.obj_make_list(context, cls(context), objects.Migration,
                                  db_migrations)

    @base.remotable_classmethod
    def get_in_progress_by_host_and_node(cls, context, host, node):
        db_migrations = db.migration_get_in_progress_by_host_and_node(
            context, host, node)
        return base.obj_make_list(context, cls(context), objects.Migration,
                                  db_migrations)

    @base.remotable_classmethod
    def get_by_filters(cls, context, filters):
        db_migrations = db.migration_get_all_by_filters(context, filters)
        return base.obj_make_list(context, cls(context), objects.Migration,
                                  db_migrations)

    @base.remotable_classmethod
    def get_in_progress_by_instance(cls,
                                    context,
                                    instance_uuid,
                                    migration_type=None):
        db_migrations = db.migration_get_in_progress_by_instance(
            context, instance_uuid, migration_type)
        return base.obj_make_list(context, cls(context), objects.Migration,
                                  db_migrations)
Exemplo n.º 11
0
class InstanceActionEventList(base.ObjectListBase, base.NovaObject):
    VERSION = '1.1'
    fields = {
        'objects': fields.ListOfObjectsField('InstanceActionEvent'),
        }

    @base.remotable_classmethod
    def get_by_action(cls, context, action_id):
        db_events = db.action_events_get(context, action_id)
        return base.obj_make_list(context, cls(context),
                                  objects.InstanceActionEvent, db_events)
Exemplo n.º 12
0
class AgentList(base.ObjectListBase, base.NovaObject):
    VERSION = '1.0'

    fields = {
        'objects': fields.ListOfObjectsField('Agent'),
    }

    @base.remotable_classmethod
    def get_all(cls, context, hypervisor=None):
        db_agents = db.agent_build_get_all(context, hypervisor=hypervisor)
        return base.obj_make_list(context, cls(), objects.Agent, db_agents)
Exemplo n.º 13
0
class InstanceActionList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              InstanceAction <= version 1.1
    VERSION = '1.0'
    fields = {
        'objects': fields.ListOfObjectsField('InstanceAction'),
        }

    @base.remotable_classmethod
    def get_by_instance_uuid(cls, context, instance_uuid):
        db_actions = db.actions_get(context, instance_uuid)
        return base.obj_make_list(context, cls(), InstanceAction, db_actions)
Exemplo n.º 14
0
class DNSDomainList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    VERSION = '1.0'
    fields = {
        'objects': fields.ListOfObjectsField('DNSDomain'),
    }

    @base.remotable_classmethod
    def get_all(cls, context):
        db_domains = db.dnsdomain_get_all(context)
        return base.obj_make_list(context, cls(context), objects.DNSDomain,
                                  db_domains)
Exemplo n.º 15
0
class InstanceFaultList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              InstanceFault <= version 1.1
    # Version 1.1: InstanceFault version 1.2
    VERSION = '1.1'

    fields = {
        'objects': fields.ListOfObjectsField('InstanceFault'),
    }

    @base.remotable_classmethod
    def get_by_instance_uuids(cls, context, instance_uuids):
        db_faultdict = db.instance_fault_get_by_instance_uuids(
            context, instance_uuids)
        db_faultlist = itertools.chain(*db_faultdict.values())
        return base.obj_make_list(context, cls(context), objects.InstanceFault,
                                  db_faultlist)
Exemplo n.º 16
0
class NUMATopology(base.NovaObject, base.NovaObjectDictCompat):
    # Version 1.0: Initial version
    # Version 1.1: Update NUMACell to 1.1
    # Version 1.2: Update NUMACell to 1.2
    VERSION = '1.2'

    fields = {
        'cells': fields.ListOfObjectsField('NUMACell'),
    }

    @classmethod
    def obj_from_primitive(cls, primitive, context=None):
        if 'jacket_object.name' in primitive:
            obj_topology = super(NUMATopology,
                                 cls).obj_from_primitive(primitive,
                                                         context=context)
        else:
            # NOTE(sahid): This compatibility code needs to stay until we can
            # guarantee that there are no cases of the old format stored in
            # the database (or forever, if we can never guarantee that).
            obj_topology = NUMATopology._from_dict(primitive)
        return obj_topology

    def _to_json(self):
        return jsonutils.dumps(self.obj_to_primitive())

    @classmethod
    def obj_from_db_obj(cls, db_obj):
        return cls.obj_from_primitive(jsonutils.loads(db_obj))

    def __len__(self):
        """Defined so that boolean testing works the same as for lists."""
        return len(self.cells)

    def _to_dict(self):
        # TODO(sahid): needs to be removed.
        return {'cells': [cell._to_dict() for cell in self.cells]}

    @classmethod
    def _from_dict(cls, data_dict):
        return cls(cells=[
            NUMACell._from_dict(cell_dict)
            for cell_dict in data_dict.get('cells', [])
        ])
Exemplo n.º 17
0
class AggregateList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: Added key argument to get_by_host()
    #              Aggregate <= version 1.1
    # Version 1.2: Added get_by_metadata_key
    VERSION = '1.2'

    fields = {
        'objects': fields.ListOfObjectsField('Aggregate'),
    }

    @classmethod
    def _filter_db_aggregates(cls, db_aggregates, hosts):
        if not isinstance(hosts, set):
            hosts = set(hosts)
        filtered_aggregates = []
        for db_aggregate in db_aggregates:
            for host in db_aggregate['hosts']:
                if host in hosts:
                    filtered_aggregates.append(db_aggregate)
                    break
        return filtered_aggregates

    @base.remotable_classmethod
    def get_all(cls, context):
        db_aggregates = db.aggregate_get_all(context)
        return base.obj_make_list(context, cls(context), objects.Aggregate,
                                  db_aggregates)

    @base.remotable_classmethod
    def get_by_host(cls, context, host, key=None):
        db_aggregates = db.aggregate_get_by_host(context, host, key=key)
        return base.obj_make_list(context, cls(context), objects.Aggregate,
                                  db_aggregates)

    @base.remotable_classmethod
    def get_by_metadata_key(cls, context, key, hosts=None):
        db_aggregates = db.aggregate_get_by_metadata_key(context, key=key)
        if hosts is not None:
            db_aggregates = cls._filter_db_aggregates(db_aggregates, hosts)
        return base.obj_make_list(context, cls(context), objects.Aggregate,
                                  db_aggregates)
Exemplo n.º 18
0
class InstanceMappingList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    VERSION = '1.0'

    fields = {
        'objects': fields.ListOfObjectsField('InstanceMapping'),
    }

    @staticmethod
    @db_api.api_context_manager.reader
    def _get_by_project_id_from_db(context, project_id):
        return context.session.query(
            api_models.InstanceMapping).filter_by(project_id=project_id).all()

    @base.remotable_classmethod
    def get_by_project_id(cls, context, project_id):
        db_mappings = cls._get_by_project_id_from_db(context, project_id)

        return base.obj_make_list(context, cls(), objects.InstanceMapping,
                                  db_mappings)
Exemplo n.º 19
0
class InventoryList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial Version
    VERSION = '1.0'

    fields = {
        'objects': fields.ListOfObjectsField('Inventory'),
    }

    @staticmethod
    @db_api.main_context_manager.reader
    def _get_all_by_resource_provider(context, rp_uuid):
        return context.session.query(models.Inventory).\
            options(joinedload('resource_provider')).\
            filter(models.ResourceProvider.uuid == rp_uuid).all()

    @base.remotable_classmethod
    def get_all_by_resource_provider_uuid(cls, context, rp_uuid):
        db_inventory_list = cls._get_all_by_resource_provider(context, rp_uuid)
        return base.obj_make_list(context, cls(context), objects.Inventory,
                                  db_inventory_list)
Exemplo n.º 20
0
class TagList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: Tag <= version 1.1
    VERSION = '1.1'

    fields = {
        'objects': fields.ListOfObjectsField('Tag'),
    }

    @base.remotable_classmethod
    def get_by_resource_id(cls, context, resource_id):
        db_tags = db.instance_tag_get_by_instance_uuid(context, resource_id)
        return base.obj_make_list(context, cls(), objects.Tag, db_tags)

    @base.remotable_classmethod
    def create(cls, context, resource_id, tags):
        db_tags = db.instance_tag_set(context, resource_id, tags)
        return base.obj_make_list(context, cls(), objects.Tag, db_tags)

    @base.remotable_classmethod
    def destroy(cls, context, resource_id):
        db.instance_tag_delete_all(context, resource_id)
Exemplo n.º 21
0
class TaskLogList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    VERSION = '1.0'
    fields = {
        'objects': fields.ListOfObjectsField('TaskLog'),
    }

    @base.serialize_args
    @base.remotable_classmethod
    def get_all(cls,
                context,
                task_name,
                period_beginning,
                period_ending,
                host=None,
                state=None):
        db_task_logs = db.task_log_get_all(context,
                                           task_name,
                                           period_beginning,
                                           period_ending,
                                           host=host,
                                           state=state)
        return base.obj_make_list(context, cls(context), TaskLog, db_task_logs)
Exemplo n.º 22
0
class MonitorMetricList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: MonitorMetric version 1.1
    VERSION = '1.1'

    fields = {
        'objects': fields.ListOfObjectsField('MonitorMetric'),
    }

    @classmethod
    def from_json(cls, metrics):
        """Converts a legacy json object into a list of MonitorMetric objs
        and finally returns of MonitorMetricList

        :param metrics: a string of json serialized objects
        :returns: a MonitorMetricList Object.
        """
        metrics = jsonutils.loads(metrics) if metrics else []

        # NOTE(suro-patz): While instantiating the MonitorMetric() from
        #                  JSON-ified string, we need to re-convert the
        #                  normalized metrics to avoid truncation to 0 by
        #                  typecasting into an integer.
        metric_list = []
        for metric in metrics:
            if ('value' in metric and metric['name'] in
                                      FIELDS_REQUIRING_CONVERSION):
                metric['value'] = metric['value'] * 100
            metric_list.append(MonitorMetric(**metric))

        return MonitorMetricList(objects=metric_list)

    # NOTE(jaypipes): This method exists to convert the object to the
    # format expected by the RPC notifier for metrics events.
    def to_list(self):
        return [m.to_dict() for m in self.objects]
Exemplo n.º 23
0
class NetworkList(obj_base.ObjectListBase, obj_base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: Added get_by_project()
    # Version 1.2: Network <= version 1.2
    VERSION = '1.2'

    fields = {
        'objects': fields.ListOfObjectsField('Network'),
    }

    @obj_base.remotable_classmethod
    def get_all(cls, context, project_only='allow_none'):
        db_networks = db.network_get_all(context, project_only)
        return obj_base.obj_make_list(context, cls(context), objects.Network,
                                      db_networks)

    @obj_base.remotable_classmethod
    def get_by_uuids(cls, context, network_uuids, project_only='allow_none'):
        db_networks = db.network_get_all_by_uuids(context, network_uuids,
                                                  project_only)
        return obj_base.obj_make_list(context, cls(context), objects.Network,
                                      db_networks)

    @obj_base.remotable_classmethod
    def get_by_host(cls, context, host):
        db_networks = db.network_get_all_by_host(context, host)
        return obj_base.obj_make_list(context, cls(context), objects.Network,
                                      db_networks)

    @obj_base.remotable_classmethod
    def get_by_project(cls, context, project_id, associate=True):
        db_networks = db.project_get_networks(context,
                                              project_id,
                                              associate=associate)
        return obj_base.obj_make_list(context, cls(context), objects.Network,
                                      db_networks)
Exemplo n.º 24
0
class FloatingIPList(obj_base.ObjectListBase, obj_base.NovaObject):
    # Version 1.3: FloatingIP 1.2
    # Version 1.4: FloatingIP 1.3
    # Version 1.5: FloatingIP 1.4
    # Version 1.6: FloatingIP 1.5
    # Version 1.7: FloatingIP 1.6
    # Version 1.8: FloatingIP 1.7
    # Version 1.9: FloatingIP 1.8
    # Version 1.10: FloatingIP 1.9
    # Version 1.11: FloatingIP 1.10
    fields = {
        'objects': fields.ListOfObjectsField('FloatingIP'),
        }
    VERSION = '1.11'

    @obj_base.remotable_classmethod
    def get_all(cls, context):
        db_floatingips = db.floating_ip_get_all(context)
        return obj_base.obj_make_list(context, cls(context),
                                      objects.FloatingIP, db_floatingips)

    @obj_base.remotable_classmethod
    def get_by_host(cls, context, host):
        db_floatingips = db.floating_ip_get_all_by_host(context, host)
        return obj_base.obj_make_list(context, cls(context),
                                      objects.FloatingIP, db_floatingips)

    @obj_base.remotable_classmethod
    def get_by_project(cls, context, project_id):
        db_floatingips = db.floating_ip_get_all_by_project(context, project_id)
        return obj_base.obj_make_list(context, cls(context),
                                      objects.FloatingIP, db_floatingips)

    @obj_base.remotable_classmethod
    def get_by_fixed_address(cls, context, fixed_address):
        db_floatingips = db.floating_ip_get_by_fixed_address(
            context, str(fixed_address))
        return obj_base.obj_make_list(context, cls(context),
                                      objects.FloatingIP, db_floatingips)

    @obj_base.remotable_classmethod
    def get_by_fixed_ip_id(cls, context, fixed_ip_id):
        db_floatingips = db.floating_ip_get_by_fixed_ip_id(context,
                                                           fixed_ip_id)
        return obj_base.obj_make_list(context, cls(), FloatingIP,
                                      db_floatingips)

    @staticmethod
    def make_ip_info(address, pool, interface):
        return {'address': str(address),
                'pool': pool,
                'interface': interface}

    @obj_base.remotable_classmethod
    def create(cls, context, ip_info, want_result=False):
        db_floatingips = db.floating_ip_bulk_create(context, ip_info,
                                                    want_result=want_result)
        if want_result:
            return obj_base.obj_make_list(context, cls(), FloatingIP,
                                          db_floatingips)

    @obj_base.remotable_classmethod
    def destroy(cls, context, ips):
        db.floating_ip_bulk_destroy(context, ips)
Exemplo n.º 25
0
class LibvirtLiveMigrateData(LiveMigrateData):
    # Version 1.0: Initial version
    # Version 1.1: Added target_connect_addr
    VERSION = '1.1'

    fields = {
        'filename': fields.StringField(),
        # FIXME: image_type should be enum?
        'image_type': fields.StringField(),
        'block_migration': fields.BooleanField(),
        'disk_over_commit': fields.BooleanField(),
        'disk_available_mb': fields.IntegerField(nullable=True),
        'is_shared_instance_path': fields.BooleanField(),
        'is_shared_block_storage': fields.BooleanField(),
        'instance_relative_path': fields.StringField(),
        'graphics_listen_addr_vnc': fields.IPAddressField(nullable=True),
        'graphics_listen_addr_spice': fields.IPAddressField(nullable=True),
        'serial_listen_addr': fields.StringField(nullable=True),
        'bdms': fields.ListOfObjectsField('LibvirtLiveMigrateBDMInfo'),
        'target_connect_addr': fields.StringField(nullable=True),
    }

    def obj_make_compatible(self, primitive, target_version):
        super(LibvirtLiveMigrateData, self).obj_make_compatible(
            primitive, target_version)
        target_version = versionutils.convert_version_to_tuple(target_version)
        if target_version < (1, 1) and 'target_connect_addr' in primitive:
            del primitive['target_connect_addr']

    def _bdms_to_legacy(self, legacy):
        if not self.obj_attr_is_set('bdms'):
            return
        legacy['volume'] = {}
        for bdmi in self.bdms:
            legacy['volume'][bdmi.serial] = {
                'disk_info': bdmi.as_disk_info(),
                'connection_info': bdmi.connection_info}

    def _bdms_from_legacy(self, legacy_pre_result):
        self.bdms = []
        volume = legacy_pre_result.get('volume', {})
        for serial in volume:
            vol = volume[serial]
            bdmi = objects.LibvirtLiveMigrateBDMInfo(serial=serial)
            bdmi.connection_info = vol['connection_info']
            bdmi.bus = vol['disk_info']['bus']
            bdmi.dev = vol['disk_info']['dev']
            bdmi.type = vol['disk_info']['type']
            if 'format' in vol:
                bdmi.format = vol['disk_info']['format']
            if 'boot_index' in vol:
                bdmi.boot_index = int(vol['disk_info']['boot_index'])
            self.bdms.append(bdmi)

    def to_legacy_dict(self, pre_migration_result=False):
        LOG.debug('Converting to legacy: %s' % self)
        legacy = super(LibvirtLiveMigrateData, self).to_legacy_dict()
        keys = (set(self.fields.keys()) -
                set(LiveMigrateData.fields.keys()) - {'bdms'})
        legacy.update({k: getattr(self, k) for k in keys
                       if self.obj_attr_is_set(k)})

        graphics_vnc = legacy.pop('graphics_listen_addr_vnc', None)
        graphics_spice = legacy.pop('graphics_listen_addr_spice', None)
        transport_target = legacy.pop('target_connect_addr', None)
        live_result = {
            'graphics_listen_addrs': {
                'vnc': graphics_vnc and str(graphics_vnc),
                'spice': graphics_spice and str(graphics_spice),
                },
            'serial_listen_addr': legacy.pop('serial_listen_addr', None),
            'target_connect_addr': transport_target,
        }

        if pre_migration_result:
            legacy['pre_live_migration_result'] = live_result
            self._bdms_to_legacy(live_result)

        LOG.debug('Legacy result: %s' % legacy)
        return legacy

    def from_legacy_dict(self, legacy):
        LOG.debug('Converting legacy dict to obj: %s' % legacy)
        super(LibvirtLiveMigrateData, self).from_legacy_dict(legacy)
        keys = set(self.fields.keys()) - set(LiveMigrateData.fields.keys())
        for k in keys - {'bdms'}:
            if k in legacy:
                setattr(self, k, legacy[k])
        if 'pre_live_migration_result' in legacy:
            pre_result = legacy['pre_live_migration_result']
            self.graphics_listen_addr_vnc = \
                pre_result['graphics_listen_addrs'].get('vnc')
            self.graphics_listen_addr_spice = \
                pre_result['graphics_listen_addrs'].get('spice')
            self.target_connect_addr = pre_result.get('target_connect_addr')
            if 'serial_listen_addr' in pre_result:
                self.serial_listen_addr = pre_result['serial_listen_addr']
            self._bdms_from_legacy(pre_result)
        LOG.debug('Converted object: %s' % self)

    def is_on_shared_storage(self):
        return self.is_shared_block_storage or self.is_shared_instance_path
Exemplo n.º 26
0
class FixedIPList(obj_base.ObjectListBase, obj_base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: Added get_by_network()
    # Version 1.2: FixedIP <= version 1.2
    # Version 1.3: FixedIP <= version 1.3
    # Version 1.4: FixedIP <= version 1.4
    # Version 1.5: FixedIP <= version 1.5, added expected attrs to gets
    # Version 1.6: FixedIP <= version 1.6
    # Version 1.7: FixedIP <= version 1.7
    # Version 1.8: FixedIP <= version 1.8
    # Version 1.9: FixedIP <= version 1.9
    # Version 1.10: FixedIP <= version 1.10
    # Version 1.11: FixedIP <= version 1.11
    # Version 1.12: FixedIP <= version 1.12
    # Version 1.13: FixedIP <= version 1.13
    # Version 1.14: FixedIP <= version 1.14
    VERSION = '1.14'

    fields = {
        'objects': fields.ListOfObjectsField('FixedIP'),
    }

    @obj_base.remotable_classmethod
    def get_all(cls, context):
        db_fixedips = db.fixed_ip_get_all(context)
        return obj_base.obj_make_list(context, cls(context), objects.FixedIP,
                                      db_fixedips)

    @obj_base.remotable_classmethod
    def get_by_instance_uuid(cls, context, instance_uuid):
        expected_attrs = ['network', 'virtual_interface', 'floating_ips']
        db_fixedips = db.fixed_ip_get_by_instance(context, instance_uuid)
        return obj_base.obj_make_list(context,
                                      cls(context),
                                      objects.FixedIP,
                                      db_fixedips,
                                      expected_attrs=expected_attrs)

    @obj_base.remotable_classmethod
    def get_by_host(cls, context, host):
        db_fixedips = db.fixed_ip_get_by_host(context, host)
        return obj_base.obj_make_list(context, cls(context), objects.FixedIP,
                                      db_fixedips)

    @obj_base.remotable_classmethod
    def get_by_virtual_interface_id(cls, context, vif_id):
        expected_attrs = ['network', 'floating_ips']
        db_fixedips = db.fixed_ips_by_virtual_interface(context, vif_id)
        return obj_base.obj_make_list(context,
                                      cls(context),
                                      objects.FixedIP,
                                      db_fixedips,
                                      expected_attrs=expected_attrs)

    @obj_base.remotable_classmethod
    def get_by_network(cls, context, network, host=None):
        ipinfo = db.network_get_associated_fixed_ips(context,
                                                     network['id'],
                                                     host=host)
        if not ipinfo:
            return []

        fips = cls(context=context, objects=[])

        for info in ipinfo:
            inst = objects.Instance(context=context,
                                    uuid=info['instance_uuid'],
                                    hostname=info['instance_hostname'],
                                    created_at=info['instance_created'],
                                    updated_at=info['instance_updated'])
            vif = objects.VirtualInterface(context=context,
                                           id=info['vif_id'],
                                           address=info['vif_address'])
            fip = objects.FixedIP(context=context,
                                  address=info['address'],
                                  instance_uuid=info['instance_uuid'],
                                  network_id=info['network_id'],
                                  virtual_interface_id=info['vif_id'],
                                  allocated=info['allocated'],
                                  leased=info['leased'],
                                  default_route=info['default_route'],
                                  instance=inst,
                                  virtual_interface=vif)
            fips.objects.append(fip)
        fips.obj_reset_changes()
        return fips

    @obj_base.remotable_classmethod
    def bulk_create(self, context, fixed_ips):
        ips = []
        for fixedip in fixed_ips:
            ip = obj_base.obj_to_primitive(fixedip)
            if 'id' in ip:
                raise exception.ObjectActionError(action='create',
                                                  reason='already created')
            ips.append(ip)
        db.fixed_ip_bulk_create(context, ips)
Exemplo n.º 27
0
class BlockDeviceMappingList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: BlockDeviceMapping <= version 1.1
    # Version 1.2: Added use_slave to get_by_instance_uuid
    # Version 1.3: BlockDeviceMapping <= version 1.2
    # Version 1.4: BlockDeviceMapping <= version 1.3
    # Version 1.5: BlockDeviceMapping <= version 1.4
    # Version 1.6: BlockDeviceMapping <= version 1.5
    # Version 1.7: BlockDeviceMapping <= version 1.6
    # Version 1.8: BlockDeviceMapping <= version 1.7
    # Version 1.9: BlockDeviceMapping <= version 1.8
    # Version 1.10: BlockDeviceMapping <= version 1.9
    # Version 1.11: BlockDeviceMapping <= version 1.10
    # Version 1.12: BlockDeviceMapping <= version 1.11
    # Version 1.13: BlockDeviceMapping <= version 1.12
    # Version 1.14: BlockDeviceMapping <= version 1.13
    # Version 1.15: BlockDeviceMapping <= version 1.14
    # Version 1.16: BlockDeviceMapping <= version 1.15
    # Version 1.17: Add get_by_instance_uuids()
    VERSION = '1.17'

    fields = {
        'objects': fields.ListOfObjectsField('BlockDeviceMapping'),
    }

    @property
    def instance_uuids(self):
        return set(
            bdm.instance_uuid for bdm in self
            if bdm.obj_attr_is_set('instance_uuid')
        )

    @classmethod
    def bdms_by_instance_uuid(cls, context, instance_uuids):
        bdms = cls.get_by_instance_uuids(context, instance_uuids)
        return base.obj_make_dict_of_lists(
                context, cls, bdms, 'instance_uuid')

    @staticmethod
    @db.select_db_reader_mode
    def _db_block_device_mapping_get_all_by_instance_uuids(
            context, instance_uuids, use_slave=False):
        return db.block_device_mapping_get_all_by_instance_uuids(
                context, instance_uuids)

    @base.remotable_classmethod
    def get_by_instance_uuids(cls, context, instance_uuids, use_slave=False):
        db_bdms = cls._db_block_device_mapping_get_all_by_instance_uuids(
            context, instance_uuids, use_slave=use_slave)
        return base.obj_make_list(
                context, cls(), objects.BlockDeviceMapping, db_bdms or [])

    @staticmethod
    @db.select_db_reader_mode
    def _db_block_device_mapping_get_all_by_instance(
            context, instance_uuid, use_slave=False):
        return db.block_device_mapping_get_all_by_instance(
            context, instance_uuid)

    @base.remotable_classmethod
    def get_by_instance_uuid(cls, context, instance_uuid, use_slave=False):
        db_bdms = cls._db_block_device_mapping_get_all_by_instance(
            context, instance_uuid, use_slave=use_slave)
        return base.obj_make_list(
                context, cls(), objects.BlockDeviceMapping, db_bdms or [])

    def root_bdm(self):
        """It only makes sense to call this method when the
        BlockDeviceMappingList contains BlockDeviceMappings from
        exactly one instance rather than BlockDeviceMappings from
        multiple instances.

        For example, you should not call this method from a
        BlockDeviceMappingList created by get_by_instance_uuids(),
        but you may call this method from a BlockDeviceMappingList
        created by get_by_instance_uuid().
        """

        if len(self.instance_uuids) > 1:
            raise exception.UndefinedRootBDM()
        try:
            return next(bdm_obj for bdm_obj in self if bdm_obj.is_root)
        except StopIteration:
            return
Exemplo n.º 28
0
class NUMACell(base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: Added pinned_cpus and siblings fields
    # Version 1.2: Added mempages field
    VERSION = '1.2'

    fields = {
        'id': fields.IntegerField(read_only=True),
        'cpuset': fields.SetOfIntegersField(),
        'memory': fields.IntegerField(),
        'cpu_usage': fields.IntegerField(default=0),
        'memory_usage': fields.IntegerField(default=0),
        'pinned_cpus': fields.SetOfIntegersField(),
        'siblings': fields.ListOfSetsOfIntegersField(),
        'mempages': fields.ListOfObjectsField('NUMAPagesTopology'),
    }

    def __eq__(self, other):
        return all_things_equal(self, other)

    def __ne__(self, other):
        return not (self == other)

    @property
    def free_cpus(self):
        return self.cpuset - self.pinned_cpus or set()

    @property
    def free_siblings(self):
        return [sibling_set & self.free_cpus for sibling_set in self.siblings]

    @property
    def avail_cpus(self):
        return len(self.free_cpus)

    @property
    def avail_memory(self):
        return self.memory - self.memory_usage

    def pin_cpus(self, cpus):
        if cpus - self.cpuset:
            raise exception.CPUPinningUnknown(requested=list(cpus),
                                              cpuset=list(self.pinned_cpus))
        if self.pinned_cpus & cpus:
            raise exception.CPUPinningInvalid(requested=list(cpus),
                                              pinned=list(self.pinned_cpus))
        self.pinned_cpus |= cpus

    def unpin_cpus(self, cpus):
        if cpus - self.cpuset:
            raise exception.CPUPinningUnknown(requested=list(cpus),
                                              cpuset=list(self.pinned_cpus))
        if (self.pinned_cpus & cpus) != cpus:
            raise exception.CPUPinningInvalid(requested=list(cpus),
                                              pinned=list(self.pinned_cpus))
        self.pinned_cpus -= cpus

    def pin_cpus_with_siblings(self, cpus):
        pin_siblings = set()
        for sib in self.siblings:
            if cpus & sib:
                pin_siblings.update(sib)
        self.pin_cpus(pin_siblings)

    def unpin_cpus_with_siblings(self, cpus):
        pin_siblings = set()
        for sib in self.siblings:
            if cpus & sib:
                pin_siblings.update(sib)
        self.unpin_cpus(pin_siblings)

    def _to_dict(self):
        return {
            'id': self.id,
            'cpus': hardware.format_cpu_spec(self.cpuset, allow_ranges=False),
            'mem': {
                'total': self.memory,
                'used': self.memory_usage
            },
            'cpu_usage': self.cpu_usage
        }

    @classmethod
    def _from_dict(cls, data_dict):
        cpuset = hardware.parse_cpu_spec(data_dict.get('cpus', ''))
        cpu_usage = data_dict.get('cpu_usage', 0)
        memory = data_dict.get('mem', {}).get('total', 0)
        memory_usage = data_dict.get('mem', {}).get('used', 0)
        cell_id = data_dict.get('id')
        return cls(id=cell_id,
                   cpuset=cpuset,
                   memory=memory,
                   cpu_usage=cpu_usage,
                   memory_usage=memory_usage,
                   mempages=[],
                   pinned_cpus=set([]),
                   siblings=[])

    def can_fit_hugepages(self, pagesize, memory):
        """Returns whether memory can fit into hugepages size

        :param pagesize: a page size in KibB
        :param memory: a memory size asked to fit in KiB

        :returns: whether memory can fit in hugepages
        :raises: MemoryPageSizeNotSupported if page size not supported
        """
        for pages in self.mempages:
            if pages.size_kb == pagesize:
                return (memory <= pages.free_kb
                        and (memory % pages.size_kb) == 0)
        raise exception.MemoryPageSizeNotSupported(pagesize=pagesize)
Exemplo n.º 29
0
class InstancePCIRequests(base.NovaObject, base.NovaObjectDictCompat):
    # Version 1.0: Initial version
    # Version 1.1: InstancePCIRequest 1.1
    VERSION = '1.1'

    fields = {
        'instance_uuid': fields.UUIDField(),
        'requests': fields.ListOfObjectsField('InstancePCIRequest'),
    }

    def obj_make_compatible(self, primitive, target_version):
        target_version = versionutils.convert_version_to_tuple(target_version)
        if target_version < (1, 1) and 'requests' in primitive:
            for index, request in enumerate(self.requests):
                request.obj_make_compatible(
                    primitive['requests'][index]['jacket_object.data'], '1.0')
                primitive['requests'][index]['jacket_object.version'] = '1.0'

    @classmethod
    def obj_from_db(cls, context, instance_uuid, db_requests):
        self = cls(context=context, requests=[], instance_uuid=instance_uuid)
        if db_requests is not None:
            requests = jsonutils.loads(db_requests)
        else:
            requests = []
        for request in requests:
            request_obj = InstancePCIRequest(count=request['count'],
                                             spec=request['spec'],
                                             alias_name=request['alias_name'],
                                             is_new=request['is_new'],
                                             request_id=request['request_id'])
            request_obj.obj_reset_changes()
            self.requests.append(request_obj)
        self.obj_reset_changes()
        return self

    @base.remotable_classmethod
    def get_by_instance_uuid(cls, context, instance_uuid):
        db_pci_requests = db.instance_extra_get_by_instance_uuid(
            context, instance_uuid, columns=['pci_requests'])
        if db_pci_requests is not None:
            db_pci_requests = db_pci_requests['pci_requests']
        return cls.obj_from_db(context, instance_uuid, db_pci_requests)

    @classmethod
    def get_by_instance_uuid_and_newness(cls, context, instance_uuid, is_new):
        requests = cls.get_by_instance_uuid(context, instance_uuid)
        requests.requests = [x for x in requests.requests if x.new == is_new]
        return requests

    @staticmethod
    def _load_legacy_requests(sysmeta_value, is_new=False):
        if sysmeta_value is None:
            return []
        requests = []
        db_requests = jsonutils.loads(sysmeta_value)
        for db_request in db_requests:
            request = InstancePCIRequest(count=db_request['count'],
                                         spec=db_request['spec'],
                                         alias_name=db_request['alias_name'],
                                         is_new=is_new)
            request.obj_reset_changes()
            requests.append(request)
        return requests

    @classmethod
    def get_by_instance(cls, context, instance):
        # NOTE (baoli): not all callers are passing instance as object yet.
        # Therefore, use the dict syntax in this routine
        if 'pci_requests' in instance['system_metadata']:
            # NOTE(danms): This instance hasn't been converted to use
            # instance_extra yet, so extract the data from sysmeta
            sysmeta = instance['system_metadata']
            _requests = (cls._load_legacy_requests(sysmeta['pci_requests']) +
                         cls._load_legacy_requests(
                             sysmeta.get('new_pci_requests'), is_new=True))
            requests = cls(instance_uuid=instance['uuid'], requests=_requests)
            requests.obj_reset_changes()
            return requests
        else:
            return cls.get_by_instance_uuid(context, instance['uuid'])

    def to_json(self):
        blob = [{
            'count': x.count,
            'spec': x.spec,
            'alias_name': x.alias_name,
            'is_new': x.is_new,
            'request_id': x.request_id
        } for x in self.requests]
        return jsonutils.dumps(blob)

    @classmethod
    def from_request_spec_instance_props(cls, pci_requests):
        objs = [
            InstancePCIRequest(**request)
            for request in pci_requests['requests']
        ]
        return cls(requests=objs, instance_uuid=pci_requests['instance_uuid'])