Exemple #1
0
def get_instance_type(id):
    """Retrieves single instance type by id."""
    if id is None:
        return get_default_instance_type()
    try:
        ctxt = context.get_admin_context()
        return db.instance_type_get_by_id(ctxt, id)
    except exception.DBError:
        raise exception.ApiError(_("Unknown instance type: %s") % name)
Exemple #2
0
def get_instance_type(id):
    """Retrieves single instance type by id."""
    if id is None:
        return get_default_instance_type()
    try:
        ctxt = context.get_admin_context()
        return db.instance_type_get_by_id(ctxt, id)
    except exception.DBError:
        raise exception.ApiError(_("Unknown instance type: %s") % name)
Exemple #3
0
    def test_get_instance_nw_info(self):
        self.mox.StubOutWithMock(db, "fixed_ip_get_by_instance")
        self.mox.StubOutWithMock(db, "virtual_interface_get_by_instance")
        self.mox.StubOutWithMock(db, "instance_type_get_by_id")

        db.fixed_ip_get_by_instance(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(fixed_ips)
        db.virtual_interface_get_by_instance(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(vifs)
        db.instance_type_get_by_id(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(flavor)
        self.mox.ReplayAll()

        nw_info = self.network.get_instance_nw_info(None, 0, 0)

        self.assertTrue(nw_info)

        for i, nw in enumerate(nw_info):
            i8 = i + 8
            check = {
                "bridge": "fa%s" % i,
                "cidr": "192.168.%s.0/24" % i,
                "cidr_v6": "2001:db%s::/64" % i8,
                "id": i,
                "injected": "DONTCARE",
            }

            self.assertDictMatch(nw[0], check)

            check = {
                "broadcast": "192.168.%s.255" % i,
                "dns": "DONTCARE",
                "gateway": "192.168.%s.1" % i,
                "gateway6": "2001:db%s::1" % i8,
                "ip6s": "DONTCARE",
                "ips": "DONTCARE",
                "label": "test%s" % i,
                "mac": "DE:AD:BE:EF:00:0%s" % i,
                "rxtx_cap": "DONTCARE",
            }
            self.assertDictMatch(nw[1], check)

            check = [{"enabled": "DONTCARE", "ip": "2001:db%s::dcad:beff:feef:%s" % (i8, i), "netmask": "64"}]
            self.assertDictListMatch(nw[1]["ip6s"], check)

            check = [{"enabled": "1", "ip": "192.168.%s.100" % i, "netmask": "255.255.255.0"}]
            self.assertDictListMatch(nw[1]["ips"], check)
Exemple #4
0
def get_network_info(instance):
    # TODO(tr3buchet): this function needs to go away! network info
    #                  MUST be passed down from compute
    # TODO(adiantum) If we will keep this function
    # we should cache network_info
    admin_context = context.get_admin_context()

    fixed_ips = db.fixed_ip_get_by_instance(admin_context, instance['id'])
    vifs = db.virtual_interface_get_by_instance(admin_context, instance['id'])
    networks = db.network_get_all_by_instance(admin_context,
                                              instance['id'])
    flavor = db.instance_type_get_by_id(admin_context,
                                        instance['instance_type_id'])
    network_info = []

    for vif in vifs:
        network = vif['network']

        # determine which of the instance's IPs belong to this network
        network_ips = [fixed_ip['address'] for fixed_ip in fixed_ips if
                       fixed_ip['network_id'] == network['id']]

        def ip_dict(ip):
            return {
                'ip': ip,
                'netmask': network['netmask'],
                'enabled': '1'}

        def ip6_dict():
            prefix = network['cidr_v6']
            mac = vif['address']
            project_id = instance['project_id']
            return  {
                'ip': ipv6.to_global(prefix, mac, project_id),
                'netmask': network['netmask_v6'],
                'enabled': '1'}

        mapping = {
            'label': network['label'],
            'gateway': network['gateway'],
            'broadcast': network['broadcast'],
            'mac': vif['address'],
            'rxtx_cap': flavor['rxtx_cap'],
            'dns': [network['dns']],
            'ips': [ip_dict(ip) for ip in network_ips]}

        if FLAGS.use_ipv6:
            mapping['ip6s'] = [ip6_dict()]
            mapping['gateway6'] = network['gateway_v6']

        network_info.append((network, mapping))
    return network_info
Exemple #5
0
def get_network_info(instance):
    # TODO(adiantum) If we will keep this function
    # we should cache network_info
    admin_context = context.get_admin_context()

    ip_addresses = db.fixed_ip_get_all_by_instance(admin_context,
                                                   instance['id'])
    networks = db.network_get_all_by_instance(admin_context,
                                              instance['id'])
    flavor = db.instance_type_get_by_id(admin_context,
                                        instance['instance_type_id'])
    network_info = []

    for network in networks:
        network_ips = [ip for ip in ip_addresses
                       if ip['network_id'] == network['id']]

        def ip_dict(ip):
            return {
                'ip': ip['address'],
                'netmask': network['netmask'],
                'enabled': '1'}

        def ip6_dict():
            prefix = network['cidr_v6']
            mac = instance['mac_address']
            project_id = instance['project_id']
            return  {
                'ip': ipv6.to_global(prefix, mac, project_id),
                'netmask': network['netmask_v6'],
                'enabled': '1'}

        mapping = {
            'label': network['label'],
            'gateway': network['gateway'],
            'broadcast': network['broadcast'],
            'mac': instance['mac_address'],
            'rxtx_cap': flavor['rxtx_cap'],
            'dns': [network['dns']],
            'ips': [ip_dict(ip) for ip in network_ips]}

        if FLAGS.use_ipv6:
            mapping['ip6s'] = [ip6_dict()]
            mapping['gateway6'] = network['gateway_v6']

        network_info.append((network, mapping))
    return network_info
Exemple #6
0
    def _get_network_info(self, instance):
        """Creates network info list for instance."""
        admin_context = context.get_admin_context()
        ips = db.fixed_ip_get_all_by_instance(admin_context,
                                              instance['id'])
        networks = db.network_get_all_by_instance(admin_context,
                                                  instance['id'])

        inst_type = db.instance_type_get_by_id(admin_context,
                                              instance['instance_type_id'])

        network_info = []
        for network in networks:
            network_ips = [ip for ip in ips if ip.network_id == network.id]

            def ip_dict(ip):
                return {
                    "ip": ip.address,
                    "netmask": network["netmask"],
                    "enabled": "1"}

            def ip6_dict():
                return {
                    "ip": ipv6.to_global(network['cidr_v6'],
                                         instance['mac_address'],
                                         instance['project_id']),
                    "netmask": network['netmask_v6'],
                    "enabled": "1"}

            info = {
                'label': network['label'],
                'gateway': network['gateway'],
                'broadcast': network['broadcast'],
                'mac': instance.mac_address,
                'rxtx_cap': inst_type['rxtx_cap'],
                'dns': [network['dns']],
                'ips': [ip_dict(ip) for ip in network_ips]}
            if network['cidr_v6']:
                info['ip6s'] = [ip6_dict()]
            if network['gateway_v6']:
                info['gateway6'] = network['gateway_v6']
            network_info.append((network, info))
        return network_info
Exemple #7
0
    def _get_network_info(self, instance):
        """Creates network info list for instance."""
        admin_context = context.get_admin_context()
        ips = db.fixed_ip_get_all_by_instance(admin_context,
                                              instance['id'])
        networks = db.network_get_all_by_instance(admin_context,
                                                  instance['id'])

        inst_type = db.instance_type_get_by_id(admin_context,
                                              instance['instance_type_id'])

        network_info = []
        for network in networks:
            network_ips = [ip for ip in ips if ip.network_id == network.id]

            def ip_dict(ip):
                return {
                    "ip": ip.address,
                    "netmask": network["netmask"],
                    "enabled": "1"}

            def ip6_dict():
                return {
                    "ip": utils.to_global_ipv6(network['cidr_v6'],
                                               instance['mac_address']),
                    "netmask": network['netmask_v6'],
                    "enabled": "1"}

            info = {
                'label': network['label'],
                'gateway': network['gateway'],
                'broadcast': network['broadcast'],
                'mac': instance.mac_address,
                'rxtx_cap': inst_type['rxtx_cap'],
                'dns': [network['dns']],
                'ips': [ip_dict(ip) for ip in network_ips]}
            if network['cidr_v6']:
                info['ip6s'] = [ip6_dict()]
            if network['gateway_v6']:
                info['gateway6'] = network['gateway_v6']
            network_info.append((network, info))
        return network_info
Exemple #8
0
    def _usage_for_period(self, context, period_start, period_stop, tenant_id=None):
        fields = ['id',
                  'image_ref',
                  'project_id',
                  'user_id',
                  'vcpus',
                  'hostname',
                  'display_name',
                  'host',
                  'state_description',
                  'instance_type_id',
                  'launched_at',
                  'terminated_at']

        tenant_clause = ''
        if tenant_id:
            tenant_clause = " and project_id='%s'" % tenant_id

        connection = get_session().connection()
        rows = connection.execute("select %s from instances where \
                                   (terminated_at is NULL or terminated_at > '%s') \
                                   and (launched_at < '%s') %s" %\
                                   (','.join(fields), period_start.isoformat(' '),\
                                   period_stop.isoformat(' '), tenant_clause
                                   )).fetchall()

        rval = {}

        for row in rows:
            o = {}
            for i in range(len(fields)):
                o[fields[i]] = row[i]
            o['hours'] = self._hours_for(o, period_start, period_stop)

            try:
                flavor = db.instance_type_get_by_id(context, o['instance_type_id'])
            except exception.InstanceTypeNotFound:
                # can't bill if there is no instance type
                continue

            o['name'] = o['display_name']
            del(o['display_name'])

            o['ram_size'] = flavor['memory_mb']
            o['disk_size'] = flavor['local_gb']

            o['tenant_id'] = o['project_id']
            del(o['project_id'])

            o['flavor'] = flavor['name']
            del(o['instance_type_id'])

            o['started_at'] = o['launched_at']
            del(o['launched_at'])

            o['ended_at'] = o['terminated_at']
            del(o['terminated_at'])

            if o['ended_at']:
                o['state'] = 'terminated'
            else:
                o['state'] = o['state_description']

            del(o['state_description'])

            now = datetime.utcnow()

            if o['state'] == 'terminated':
                delta = self._parse_datetime(o['ended_at'])\
                             - self._parse_datetime(o['started_at'])
            else:
                delta = now - self._parse_datetime(o['started_at'])

            o['uptime'] = delta.days * 24 * 60 + delta.seconds

            if not o['tenant_id'] in rval:
                summary = {}
                summary['tenant_id'] = o['tenant_id']
                summary['instances'] = []
                summary['total_disk_usage'] = 0
                summary['total_cpu_usage'] = 0
                summary['total_ram_usage'] = 0

                summary['total_active_ram_size'] = 0
                summary['total_active_disk_size'] = 0
                summary['total_active_vcpus'] = 0
                summary['total_active_instances'] = 0

                summary['total_hours'] = 0
                summary['begin'] = period_start
                summary['stop'] = period_stop
                rval[o['tenant_id']] = summary

            rval[o['tenant_id']]['total_disk_usage'] += o['disk_size'] * o['hours']
            rval[o['tenant_id']]['total_cpu_usage'] += o['vcpus'] * o['hours']
            rval[o['tenant_id']]['total_ram_usage'] += o['ram_size'] * o['hours']

            if o['state'] is not 'terminated':
                rval[o['tenant_id']]['total_active_ram_size'] += o['ram_size']
                rval[o['tenant_id']]['total_active_vcpus'] += o['vcpus']
                rval[o['tenant_id']]['total_active_disk_size'] += o['disk_size']
                rval[o['tenant_id']]['total_active_instances'] += 1

            rval[o['tenant_id']]['total_hours'] += o['hours']
            rval[o['tenant_id']]['instances'].append(o)

        return rval.values()
Exemple #9
0
    def _usage_for_period(self, context, period_start, period_stop, tenant_id=None):
        fields = ['id',
                  'image_ref',
                  'project_id',
                  'user_id',
                  'vcpus',
                  'hostname',
                  'display_name',
                  'host',
                  'vm_state',
                  'instance_type_id',
                  'launched_at',
                  'terminated_at']

        tenant_clause = ''
        if tenant_id:
            tenant_clause = " and project_id='%s'" % tenant_id

        connection = get_session().connection()
        rows = connection.execute("select %s from instances where \
                                   (terminated_at is NULL or terminated_at > '%s') \
                                   and (launched_at < '%s') %s" %\
                                   (','.join(fields), period_start.isoformat(' '),\
                                   period_stop.isoformat(' '), tenant_clause
                                   )).fetchall()

        rval = {}
        flavors = {}

        for row in rows:
            o = {}
            for i in range(len(fields)):
                o[fields[i]] = row[i]
            o['hours'] = self._hours_for(o, period_start, period_stop)
            flavor_type = o['instance_type_id']

            try:
                flavors[flavor_type] = \
                    db.instance_type_get_by_id(context, flavor_type)

            except AttributeError:
                # The most recent version of nova renamed this function
                flavors[flavor_type] = \
                    db.instance_type_get(context, flavor_type)
            except exception.InstanceTypeNotFound:
                # can't bill if there is no instance type
                continue

            flavor = flavors[flavor_type]

            o['name'] = o['display_name']
            del(o['display_name'])

            o['ram_size'] = flavor['memory_mb']
            o['disk_size'] = flavor['local_gb']

            o['tenant_id'] = o['project_id']
            del(o['project_id'])

            o['flavor'] = flavor['name']
            del(o['instance_type_id'])

            o['started_at'] = o['launched_at']
            del(o['launched_at'])

            o['ended_at'] = o['terminated_at']
            del(o['terminated_at'])

            if o['ended_at']:
                o['state'] = 'terminated'
            else:
                o['state'] = o['vm_state']

            del(o['vm_state'])

            now = datetime.utcnow()

            if o['state'] == 'terminated':
                delta = self._parse_datetime(o['ended_at'])\
                             - self._parse_datetime(o['started_at'])
            else:
                delta = now - self._parse_datetime(o['started_at'])

            o['uptime'] = delta.days * 24 * 60 + delta.seconds

            if not o['tenant_id'] in rval:
                summary = {}
                summary['tenant_id'] = o['tenant_id']
                summary['instances'] = []
                summary['total_disk_usage'] = 0
                summary['total_cpu_usage'] = 0
                summary['total_ram_usage'] = 0

                summary['total_active_ram_size'] = 0
                summary['total_active_disk_size'] = 0
                summary['total_active_vcpus'] = 0
                summary['total_active_instances'] = 0

                summary['total_hours'] = 0
                summary['begin'] = period_start
                summary['stop'] = period_stop
                rval[o['tenant_id']] = summary

            rval[o['tenant_id']]['total_disk_usage'] += o['disk_size'] * o['hours']
            rval[o['tenant_id']]['total_cpu_usage'] += o['vcpus'] * o['hours']
            rval[o['tenant_id']]['total_ram_usage'] += o['ram_size'] * o['hours']

            if o['state'] is not 'terminated':
                rval[o['tenant_id']]['total_active_ram_size'] += o['ram_size']
                rval[o['tenant_id']]['total_active_vcpus'] += o['vcpus']
                rval[o['tenant_id']]['total_active_disk_size'] += o['disk_size']
                rval[o['tenant_id']]['total_active_instances'] += 1

            rval[o['tenant_id']]['total_hours'] += o['hours']
            rval[o['tenant_id']]['instances'].append(o)

        return rval.values()
Exemple #10
0
    def _usage_for_period(self, context, period_start, period_stop, tenant_id=None):
        fields = [
            "id",
            "image_ref",
            "project_id",
            "user_id",
            "vcpus",
            "hostname",
            "display_name",
            "host",
            "task_state",
            "instance_type_id",
            "launched_at",
            "terminated_at",
        ]

        tenant_clause = ""
        if tenant_id:
            tenant_clause = " and project_id='%s'" % tenant_id

        connection = get_session().connection()
        rows = connection.execute(
            "select %s from instances where \
                                   (terminated_at is NULL or terminated_at > '%s') \
                                   and (launched_at < '%s') %s"
            % (",".join(fields), period_start.isoformat(" "), period_stop.isoformat(" "), tenant_clause)
        ).fetchall()

        rval = {}
        flavors = {}

        for row in rows:
            o = {}
            for i in range(len(fields)):
                o[fields[i]] = row[i]
            o["hours"] = self._hours_for(o, period_start, period_stop)
            flavor_type = o["instance_type_id"]

            try:
                flavors[flavor_type] = db.instance_type_get_by_id(context, flavor_type)

            except AttributeError:
                # The most recent version of nova renamed this function
                flavors[flavor_type] = db.instance_type_get(context, flavor_type)
            except exception.InstanceTypeNotFound:
                # can't bill if there is no instance type
                continue

            flavor = flavors[flavor_type]

            o["name"] = o["display_name"]
            del (o["display_name"])

            o["ram_size"] = flavor["memory_mb"]
            o["disk_size"] = flavor["local_gb"]

            o["tenant_id"] = o["project_id"]
            del (o["project_id"])

            o["flavor"] = flavor["name"]
            del (o["instance_type_id"])

            o["started_at"] = o["launched_at"]
            del (o["launched_at"])

            o["ended_at"] = o["terminated_at"]
            del (o["terminated_at"])

            if o["ended_at"]:
                o["state"] = "terminated"
            else:
                o["state"] = o["task_state"]

            del (o["task_state"])

            now = datetime.utcnow()

            if o["state"] == "terminated":
                delta = self._parse_datetime(o["ended_at"]) - self._parse_datetime(o["started_at"])
            else:
                delta = now - self._parse_datetime(o["started_at"])

            o["uptime"] = delta.days * 24 * 60 + delta.seconds

            if not o["tenant_id"] in rval:
                summary = {}
                summary["tenant_id"] = o["tenant_id"]
                summary["instances"] = []
                summary["total_disk_usage"] = 0
                summary["total_cpu_usage"] = 0
                summary["total_ram_usage"] = 0

                summary["total_active_ram_size"] = 0
                summary["total_active_disk_size"] = 0
                summary["total_active_vcpus"] = 0
                summary["total_active_instances"] = 0

                summary["total_hours"] = 0
                summary["begin"] = period_start
                summary["stop"] = period_stop
                rval[o["tenant_id"]] = summary

            rval[o["tenant_id"]]["total_disk_usage"] += o["disk_size"] * o["hours"]
            rval[o["tenant_id"]]["total_cpu_usage"] += o["vcpus"] * o["hours"]
            rval[o["tenant_id"]]["total_ram_usage"] += o["ram_size"] * o["hours"]

            if o["state"] is not "terminated":
                rval[o["tenant_id"]]["total_active_ram_size"] += o["ram_size"]
                rval[o["tenant_id"]]["total_active_vcpus"] += o["vcpus"]
                rval[o["tenant_id"]]["total_active_disk_size"] += o["disk_size"]
                rval[o["tenant_id"]]["total_active_instances"] += 1

            rval[o["tenant_id"]]["total_hours"] += o["hours"]
            rval[o["tenant_id"]]["instances"].append(o)

        return rval.values()