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')

        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(mox.IgnoreArg(),
                                   mox.IgnoreArg()).AndReturn(flavor)
        self.mox.ReplayAll()

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

        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,
                     'multi_host': False,
                     'injected': 'DONTCARE',
                     'bridge_interface': 'fake_fa%s' % i,
                     'vlan': None}

            self.assertDictMatch(nw[0], check)

            check = {'broadcast': '192.168.%s.255' % i,
                     'dhcp_server': '192.168.%s.1' % 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,
                     'vif_uuid': ('00000000-0000-0000-0000-000000000000000%s' %
                                  i),
                     'rxtx_cap': 'DONTCARE',
                     'should_create_vlan': False,
                     'should_create_bridge': False}
            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 #2
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')

        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(mox.IgnoreArg(),
                                   mox.IgnoreArg()).AndReturn(flavor)
        self.mox.ReplayAll()

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

        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,
                     'multi_host': False,
                     'injected': 'DONTCARE',
                     'bridge_interface': 'fake_fa%s' % i,
                     'vlan': None}

            self.assertDictMatch(nw[0], check)

            check = {'broadcast': '192.168.%s.255' % i,
                     'dhcp_server': '192.168.%s.1' % 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,
                     'vif_uuid': ('00000000-0000-0000-0000-000000000000000%s' %
                                  i),
                     'rxtx_cap': 'DONTCARE',
                     'should_create_vlan': False,
                     'should_create_bridge': False}
            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 #3
0
    def delete(self, req, filesystem_id, id):
        """Detach an instance from a filesystem."""
        fs_name = filesystem_id
        instance_uuid = id

        context = req.environ['nova.context']

        instance = db.instance_get_by_uuid(context, instance_uuid)
        if not instance:
            msg = (_("Unable to find instance %s.") % instance_uuid)
            raise webob.exc.HTTPNotFound(msg)

        instance_id = instance.id

        try:
            ips = db.fixed_ip_get_by_instance(context, instance_id)
        except exception.FixedIpNotFound:
            msg = (_("Unable to get IP address for instance_id %s.") %
                     instance_id)
            raise webob.exc.HTTPNotFound(msg)

        for ip in ips:
            LOG.debug(_("unattaching ip %(ip)s from filesystem %(fs)s.") %
                      {'ip': ip, 'fs': fs_name})
            try:
                self.fs_driver.unattach(fs_name, ip['address'])
            except exception.NotAuthorized:
                msg = _("Filesystem detachment not permitted.")
                raise webob.exc.HTTPForbidden(msg)

        return webob.Response(status_int=202)
Exemple #4
0
    def update(self, req, filesystem_id, id, body):
        """Attach an instance to a filesystem."""
        fs_name = filesystem_id
        instance_uuid = id

        if body:
            LOG.warning(_("Unexpected body: %s") % body)
            raise webob.exc.HTTPUnprocessableEntity()

        context = req.environ['nova.context']

        instance = db.instance_get_by_uuid(context, instance_uuid)
        if not instance:
            msg = (_("Unable to find instance %s.") % instance_uuid)
            raise webob.exc.HTTPNotFound(msg)

        instance_id = instance.id

        try:
            fixed_ips = db.fixed_ip_get_by_instance(context, instance_id)
        except exception.FixedIpNotFound:
            msg = (_("Unable to get IP address for instance_id %s.") %
                     instance_id)
            raise webob.exc.HTTPNotFound(msg)

        for ip in fixed_ips:
            LOG.debug(_("attaching ip %(ip)s to filesystem %(fs)s.") %
                      {'ip': ip['address'], 'fs': fs_name})
            try:
                self.fs_driver.attach(fs_name, ip['address'])
            except exception.NotAuthorized:
                msg = _("Filesystem attachment not permitted.")
                raise webob.exc.HTTPForbidden(msg)

        return _translate_instance_view(instance_uuid)
Exemple #5
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()

    try:
        fixed_ips = db.fixed_ip_get_by_instance(admin_context, instance['id'])
    except exception.FixedIpNotFoundForInstance:
        fixed_ips = []

    vifs = db.virtual_interface_get_by_instance(admin_context, instance['id'])
    flavor = db.instance_type_get(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'],
            'dhcp_server': network['gateway'],
            'mac': vif['address'],
            'rxtx_cap': flavor['rxtx_cap'],
            'dns': [],
            'ips': [ip_dict(ip) for ip in network_ips]}

        if network['dns1']:
            mapping['dns'].append(network['dns1'])
        if network['dns2']:
            mapping['dns'].append(network['dns2'])

        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(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()

    try:
        fixed_ips = db.fixed_ip_get_by_instance(admin_context, instance['id'])
    except exception.FixedIpNotFoundForInstance:
        fixed_ips = []

    vifs = db.virtual_interface_get_by_instance(admin_context, instance['id'])
    flavor = db.instance_type_get(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'],
            'dhcp_server': network['gateway'],
            'mac': vif['address'],
            'rxtx_cap': flavor['rxtx_cap'],
            'dns': [],
            'ips': [ip_dict(ip) for ip in network_ips]
        }

        if network['dns1']:
            mapping['dns'].append(network['dns1'])
        if network['dns2']:
            mapping['dns'].append(network['dns2'])

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

        network_info.append((network, mapping))
    return network_info
def list_vms(host=None):
    """
      make a list of vms and expand out their fixed_ip and floating ips sensibly
    """
    flags.parse_args([])
    my_instances  = []
    if host is None:
        instances = db.instance_get_all(context.get_admin_context())
    else:
        instances = db.instance_get_all_by_host(
                      context.get_admin_context(), host)

    for instance in instances:
        my_inst = {}
        my_inst = dict(instance).copy()
        for (k,v) in my_inst.items():
            try:
                json.encoder(v)
            except TypeError, e:
                v = str(v)
                my_inst[k] = v

        ec2_id = db.get_ec2_instance_id_by_uuid(context.get_admin_context(), instance.uuid)
        ec2_id = 'i-' + hex(int(ec2_id)).replace('0x', '').zfill(8)
        my_inst['ec2_id'] = ec2_id
        try:
                fixed_ips = db.fixed_ip_get_by_instance(context.get_admin_context(), instance.uuid)
        except:
                pass
        my_inst['fixed_ips'] = [ ip.address for ip in fixed_ips ]
        my_inst['floating_ips'] = []
        for ip in fixed_ips:
            my_inst['floating_ips'].extend([ f_ip.address for f_ip in db.floating_ip_get_by_fixed_address(context.get_admin_context(), ip.address)])

        my_instances.append(my_inst)
Exemple #8
0
 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)
Exemple #9
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 #10
0
    def update(self, req, id, body):
        """Add new filesystem."""
        name = id
        try:
            entry = body['fs_entry']
            size = entry['size']
            scope = entry['scope']
        except (TypeError, KeyError):
            raise webob.exc.HTTPUnprocessableEntity()
        if scope not in ['project', 'instance', 'global']:
            LOG.error(_("scope must be one of project, instance, or global"))
            raise webob.exc.HTTPUnprocessableEntity()

        context = req.environ['nova.context']
        project = context.project_id

        try:
            if self.has_db_support:
                sharedfs_db.filesystem_add(context, name, scope, project)

            self.fs_driver.create_fs(name, project, size)
        except exception.NotAuthorized:
            msg = _("Filesystem creation requires admin permissions.")
            raise webob.exc.HTTPForbidden(msg)

        if self.has_db_support:
            # Attach global or project-wide shares immediately.
            instance_list = []
            if scope == 'global':
                instance_list = db.instance_get_all(context)
            elif scope == 'project':
                instance_list = db.instance_get_all_by_project(context,
                                                               project)

            for instance in instance_list:
                try:
                    fixed_ips = db.fixed_ip_get_by_instance(context,
                                                            instance.id)
                    for ip in fixed_ips:
                        LOG.debug(_("attaching %(ip)s to filesystem %(fs)s.")
                                  % {'ip': ip['address'], 'fs': name})
                        try:
                            self.fs_driver.attach(name, ip['address'])
                        except exception.NotAuthorized:
                            LOG.warning(_("Insufficient permissions to attach"
                                       " %(instance)s to filesystem %(fs)s.") %
                                       {'instance': instance.name, 'fs': name})
                except exception.FixedIpNotFound:
                    LOG.warning(_("Unable to get IP address for %s.")
                              % instance.id)

        return _translate_fs_entry_view({'name': name,
                                         'size': size,
                                         'scope': scope,
                                         'project': project})
Exemple #11
0
    def refresh_instance_security_rules(self, instance):
        LOG.debug(_('refresh iptables filter for instance %s') %
                    instance['id'])
        self.do_refresh_instance_rules(instance)
        self.iptables.apply()

        if FLAGS.del_sec_rule_conntracks:
            ctxt = context.get_admin_context()
            fixed_ip = db.fixed_ip_get_by_instance(ctxt, instance['uuid'])
            fip = fixed_ip[0]['address']
            linux_net.del_conntrack_entries(fip)
    def unattach(self, ctxt, instance_uuid, fs_name):
        LOG.debug(_("unattaching %(instance)s from filesystem %(fs)s.") %
                  {'instance': instance_uuid, 'fs': fs_name})

        instance = db.instance_get_by_uuid(ctxt, instance_uuid)
        instance_id = instance.id

        fixed_ips = db.fixed_ip_get_by_instance(ctxt, instance_id)
        for ip in fixed_ips:
            LOG.debug(_("auto unattaching %(ip)s from filesystem %(fs)s.") %
                      {'ip': ip['address'], 'fs': fs_name})
            self.fs_driver.unattach(fs_name, ip['address'])
Exemple #13
0
    def delete(self, req, id):
        """Delete the filesystem identified by id."""
        name = id

        if self.has_db_support:
            # Unattach global or project-wide shares immediately.
            context = req.environ['nova.context']
            fs_entry = sharedfs_db.filesystem_get(context, name)
            if not fs_entry:
                msg = _("Filesystem %s not found.") % name
                raise webob.exc.HTTPNotFound(msg)
            scope = fs_entry.scope
            project = fs_entry.project_id
            instance_list = []
            if scope == 'global':
                instance_list = db.instance_get_all(context)
            elif scope == 'project':
                instance_list = db.instance_get_all_by_project(context,
                                                               project)

            for instance in instance_list:
                try:
                    fixed_ips = db.fixed_ip_get_by_instance(context,
                                                            instance.id)
                    for ip in fixed_ips:
                        LOG.debug(_("unattaching %(ip)s from fs %(fs)s.") %
                                  {'ip': ip['address'], 'fs': name})
                        try:
                            self.fs_driver.unattach(name, ip['address'])
                        except exception.NotAuthorized:
                            LOG.warning(_("Insufficient permission to unattach"
                                     " %(instance)s from filesystem %(fs)s.") %
                                          {'instance': instance.name,
                                           'fs': name})
                except exception.FixedIpNotFound:
                    LOG.warning(_("Unable to get IP address for %s.")
                              % instance.id)

            sharedfs_db.filesystem_delete(context, name)

        try:
            self.fs_driver.delete_fs(name, project)
        except exception.NotAuthorized:
            msg = _("Filesystem deletion requires admin permissions.")
            raise webob.exc.HTTPForbidden(msg)
        except exception.NotFound:
            msg = _("Filesystem %s does not exist.") % name
            raise webob.exc.HTTPNotFound(msg)

        return webob.Response(status_int=202)
Exemple #14
0
    def do_refresh_security_group_rules(self, security_group):
        ctxt = context.get_admin_context()
        res = []
        for instance in self.instances.values():
            self.remove_filters_for_instance(instance)
            self.add_filters_for_instance(instance)

            try:
                fixed_ip = db.fixed_ip_get_by_instance(ctxt, instance['uuid'])
                fip = fixed_ip[0]['address']
                res.append(fip)
            except Exception:
                pass

        return res
Exemple #15
0
def list_vms(host=None):
    """
      make a list of vms and expand out their fixed_ip and floating ips sensibly
    """
    flags.parse_args([])
    my_instances = []
    if host is None:
        instances = db.instance_get_all(context.get_admin_context())
    else:
        instances = db.instance_get_all_by_host(context.get_admin_context(),
                                                host)

    for instance in instances:
        my_inst = {}
        my_inst = dict(instance).copy()
        for (k, v) in my_inst.items():
            try:
                json.encoder(v)
            except TypeError, e:
                v = str(v)
                my_inst[k] = v

        ec2_id = db.get_ec2_instance_id_by_uuid(context.get_admin_context(),
                                                instance.uuid)
        ec2_id = 'i-' + hex(int(ec2_id)).replace('0x', '').zfill(8)
        my_inst['ec2_id'] = ec2_id
        try:
            fixed_ips = db.fixed_ip_get_by_instance(
                context.get_admin_context(), instance.uuid)
        except:
            pass
        my_inst['fixed_ips'] = [ip.address for ip in fixed_ips]
        my_inst['floating_ips'] = []
        for ip in fixed_ips:
            my_inst['floating_ips'].extend([
                f_ip.address for f_ip in db.floating_ip_get_by_fixed_address(
                    context.get_admin_context(), ip.address)
            ])

        my_instances.append(my_inst)
Exemple #16
0
 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)
Exemple #17
0
    def notify(self, message):

        ctxt = context.get_admin_context()
        event_type = message.get('event_type')
        if event_type in FLAGS.wiki_eventtype_blacklist:
            return
        if event_type not in FLAGS.wiki_eventtype_whitelist:
            LOG.debug("Ignoring message type %s" % event_type)
            return

        payload = message['payload']
        instance_name = payload['display_name']
        uuid = payload['instance_id']

        if FLAGS.wiki_instance_dns_domain:
            fqdn = "%s.%s" % (instance_name, FLAGS.wiki_instance_dns_domain)
        else:
            fqdn = instance_name

        template_param_dict = {}
        for field in self.RawTemplateFields:
            template_param_dict[field] = payload[field]

        tenant_id = payload['tenant_id']
        if (FLAGS.wiki_use_keystone and
            self._keystone_login(tenant_id, ctxt)):
            tenant_obj = self.tenant_manager[tenant_id].get(tenant_id)
            user_obj = self.user_manager[tenant_id].get(payload['user_id'])
            tenant_name = tenant_obj.name
            user_name = user_obj.name
            template_param_dict['tenant'] = tenant_name
            template_param_dict['username'] = user_name

        inst = db.instance_get_by_uuid(ctxt, uuid)
        old_school_id = inst.id
        ec2_id = 'i-%08x' % old_school_id

        template_param_dict['cpu_count'] = inst.vcpus
        template_param_dict['disk_gb_current'] = inst.ephemeral_gb
        template_param_dict['host'] = inst.host
        template_param_dict['reservation_id'] = inst.reservation_id
        template_param_dict['availability_zone'] = inst.availability_zone
        template_param_dict['original_host'] = inst.launched_on
        template_param_dict['fqdn'] = fqdn
        template_param_dict['ec2_id'] = ec2_id
        template_param_dict['project_name'] = inst.project_id
        template_param_dict['region'] = FLAGS.wiki_instance_region

        try:
            fixed_ips = db.fixed_ip_get_by_instance(ctxt, old_school_id)
        except exception.FixedIpNotFoundForInstance:
            fixed_ips = []
	ips = []
	floating_ips = []
	for fixed_ip in fixed_ips:
	    ips.append(fixed_ip.address)
	    for floating_ip in db.floating_ip_get_by_fixed_ip_id(ctxt, fixed_ip.id):
	        floating_ips.append(floating_ip.address)

        template_param_dict['private_ip'] = ','.join(ips)
        template_param_dict['public_ip'] = ','.join(floating_ips)

        sec_groups = db.security_group_get_by_instance(ctxt, old_school_id)
        grps = [grp.name for grp in sec_groups]
        template_param_dict['security_group'] = ','.join(grps)

        fields_string = ""
        for key in template_param_dict:
            fields_string += "\n|%s=%s" % (key, template_param_dict[key])

        if event_type == 'compute.instance.delete.start':
            page_string = "\n%s\nThis instance has been deleted.\n%s\n" % (begin_comment,
                                                                           end_comment)
        else:
            page_string = "\n%s\n{{InstanceStatus%s}}\n%s\n" % (begin_comment,
                                                                fields_string,
                                                                end_comment)

        self._wiki_login()
        pagename = "%s%s" % (FLAGS.wiki_page_prefix, ec2_id)
        LOG.debug("wikistatus:  Writing instance info"
                  " to page http://%s/wiki/%s" %
                  (FLAGS.wiki_host, pagename))

        page = self.site.Pages[pagename]
        try:
            pText = page.edit()
            start_replace_index = pText.find(begin_comment)
            if start_replace_index == -1:
                # Just stick it at the end.
                newText = "%s%s" % (page_string, pText)
            else:
                # Replace content between comment tags.
                end_replace_index = pText.find(end_comment, start_replace_index)
                if end_replace_index == -1:
                    end_replace_index = start_replace_index + len(begin_comment)
                else:
                    end_replace_index += len(end_comment)
                newText = "%s%s%s" % (pText[:start_replace_index],
                                      page_string,
                                      pText[end_replace_index:])
            page.save(newText, "Auto update of instance info.")
        except (mwclient.errors.InsufficientPermission,
                mwclient.errors.LoginError):
            LOG.debug("Failed to update wiki page..."
                      " trying to re-login next time.")
            self._wiki_logged_in = False
    def index(self, req):
        """Return all flavors in brief."""
        #flavors = self._get_flavors(req)
        #return self._view_builder.index(req, flavors)
	project_id=str(req.environ['HTTP_X_TENANT_ID'])
	context = req.environ['nova.context']
	context = context.elevated()

        networks = db.network_get_all(context)
        nets=[dict(network.iteritems()) for network in networks]

	virtual_interfaces = db.virtual_interface_get_all(context)
	vifs=[dict(vif.iteritems()) for vif in virtual_interfaces]
	
	#make a dict of relationships between Network_IDs and Instance_IDs {1:[1,2],...}
	net_vm_dict = {}
	for vif in vifs:
	    net_id=int(vif['network_id'])	
	    vm_id=int(vif['instance_id'])
	    if net_id in net_vm_dict:
		net_vm_dict[net_id].append(vm_id)
	    else:
		net_vm_dict[net_id] = [vm_id]
	print net_vm_dict
	#Go through the dict , filter by this project and get detailed infos	
	#instance_get(context, instance_id)
	net_list = []
	for netID in net_vm_dict:
	    networks= db.network_get(context, netID)
	    net = dict(networks.iteritems())
	    print str(net['project_id'])
	    if net['project_id']==None or net['project_id']==project_id:
		print "my precious~~"
		net_info = {}
		net_info['id']=str(net['uuid'])
		net_info['name']=str(net['label'])
		net_info['cidr']=str(net['cidr'])
		net_info['vm']=[]
		net_list.append(net_info)	
		for vmID in  net_vm_dict[netID]:
		    vms = db.instance_get(context, vmID)
		    vm = dict(vms.iteritems())
		    if vm['project_id']==project_id:
		        print "My VM"
			vm_info = {}
			#Get vm infos for each VM
			vm_info['name']=str(vm['hostname'])
			vm_info['id']=str(vm['uuid'])
			vm_info['vm_state']=str(vm['vm_state'])
			#Get fixed_ips for each VM
			fixed_ips = db.fixed_ip_get_by_instance(context, vmID)
			fixed_ip_info = []
			for ip in fixed_ips:
			    fixed_ip_info.append(str(dict(ip.iteritems())['address']))
			vm_info['fixed_ips'] = fixed_ip_info
			#Get Floating_ips for each VM
			floating_ip_info = []
			for fixed_ip in fixed_ip_info:
			    
			    try:
			        floating_ips = db.floating_ip_get_by_address(context, fixed_ip)
			    except exception.FloatingIpNotFoundForAddress:
				print "floating not found"
				continue
			    if floating_ips != None:
			        for floating_ip in floating_ips:
				    floating_ip_info.append(str(dict(ip.floating_ip.iteritems()['address'])))
			vm_info['floating_ips']=floating_ip_info
			net_info['vm'].append(vm_info)

	ret_net_list={}
	ret_net_list['networks']=net_list
	print ret_net_list

	return ret_net_list
    def notify(self, ctxt, message):
        event_type = message.get('event_type')
        if event_type in FLAGS.wiki_eventtype_blacklist:
            return
        if event_type not in FLAGS.wiki_eventtype_whitelist:
            LOG.debug("Ignoring message type %s" % event_type)
            return

        payload = message['payload']
        instance = payload['instance_id']
        instance_name = payload['display_name']

        pagename = "%s%s" % (FLAGS.wiki_page_prefix, instance_name)
        LOG.debug("wikistatus:  Writing instance info"
                  " to page http://%s/wiki/%s" %
                  (self.host, pagename))

        if event_type == 'compute.instance.delete.end':
            page_string = _("This instance has been deleted.")
        else:
            template_param_dict = {}
            for field in self.RawTemplateFields:
                template_param_dict[field] = payload[field]

            tenant_id = payload['tenant_id']
            if (FLAGS.wiki_use_keystone and
                self._keystone_login(tenant_id, ctxt)):
                tenant_obj = self.tenant_manager[tenant_id].get(tenant_id)
                user_obj = self.user_manager[tenant_id].get(payload['user_id'])
                tenant_name = tenant_obj.name
                user_name = user_obj.name
                template_param_dict['tenant'] = tenant_name
                template_param_dict['username'] = user_name

            inst = db.instance_get_by_uuid(ctxt, payload['instance_id'])

            simple_id = inst.id
            template_param_dict['cpu_count'] = inst.vcpus
            template_param_dict['disk_gb_current'] = inst.ephemeral_gb
            template_param_dict['host'] = inst.host
            template_param_dict['reservation_id'] = inst.reservation_id
            template_param_dict['availability_zone'] = inst.availability_zone
            template_param_dict['original_host'] = inst.launched_on
            template_param_dict['public_ip'] = inst.access_ip_v4

            try:
                fixed_ips = db.fixed_ip_get_by_instance(ctxt, payload['instance_id'])
            except exception.FixedIpNotFoundForInstance:
                fixed_ips = []
            ips = [ip.address for ip in fixed_ips]
            template_param_dict['private_ip'] = ','.join(ips)

            sec_groups = db.security_group_get_by_instance(ctxt, simple_id)
            grps = [grp.name for grp in sec_groups]
            template_param_dict['security_group'] = ','.join(grps)

            image = self._image_service.show(ctxt, inst.image_ref)
            image_name = image.get('name', inst.image_ref)
            template_param_dict['image_name'] = image_name

            fields_string = ""
            for key in template_param_dict:
                fields_string += "\n|%s=%s" % (key, template_param_dict[key])

            page_string = "{{InstanceStatus%s}}" % fields_string

        self._wiki_login()
        page = self.site.Pages[pagename]
        try:
            page.edit()
            page.save(page_string, "Auto update of instance info.")
        except (mwclient.errors.InsufficientPermission,
                mwclient.errors.LoginError):
            LOG.debug("Failed to update wiki page..."
                      " trying to re-login next time.")
            self._wiki_logged_in = False
Exemple #20
0
 def get_by_instance_uuid(cls, context, instance_uuid):
     db_fixedips = db.fixed_ip_get_by_instance(context, instance_uuid)
     return obj_base.obj_make_list(context, cls(context),
                                   objects.FixedIP, db_fixedips)
Exemple #21
0
    def notify(self, message):

        ctxt = context.get_admin_context()
        event_type = message.get('event_type')
        if event_type in FLAGS.wiki_eventtype_blacklist:
            return
        if event_type not in FLAGS.wiki_eventtype_whitelist:
            LOG.debug("Ignoring message type %s" % event_type)
            return

        payload = message['payload']
        instance_name = payload['display_name']
        uuid = payload['instance_id']

        if FLAGS.wiki_instance_dns_domain:
            fqdn = "%s.%s" % (instance_name, FLAGS.wiki_instance_dns_domain)
        else:
            fqdn = instance_name

        template_param_dict = {}
        for field in self.RawTemplateFields:
            template_param_dict[field] = payload[field]

        tenant_id = payload['tenant_id']
        if (FLAGS.wiki_use_keystone and self._keystone_login(tenant_id, ctxt)):
            tenant_obj = self.tenant_manager[tenant_id].get(tenant_id)
            user_obj = self.user_manager[tenant_id].get(payload['user_id'])
            tenant_name = tenant_obj.name
            user_name = user_obj.name
            template_param_dict['tenant'] = tenant_name
            template_param_dict['username'] = user_name

        inst = db.instance_get_by_uuid(ctxt, uuid)
        old_school_id = inst.id
        ec2_id = 'i-%08x' % old_school_id

        template_param_dict['cpu_count'] = inst.vcpus
        template_param_dict['disk_gb_current'] = inst.ephemeral_gb
        template_param_dict['host'] = inst.host
        template_param_dict['reservation_id'] = inst.reservation_id
        template_param_dict['availability_zone'] = inst.availability_zone
        template_param_dict['original_host'] = inst.launched_on
        template_param_dict['fqdn'] = fqdn
        template_param_dict['ec2_id'] = ec2_id
        template_param_dict['project_name'] = inst.project_id
        template_param_dict['region'] = FLAGS.wiki_instance_region

        try:
            fixed_ips = db.fixed_ip_get_by_instance(ctxt, old_school_id)
        except exception.FixedIpNotFoundForInstance:
            fixed_ips = []
        ips = []
        floating_ips = []
        for fixed_ip in fixed_ips:
            ips.append(fixed_ip.address)
            for floating_ip in db.floating_ip_get_by_fixed_ip_id(
                    ctxt, fixed_ip.id):
                floating_ips.append(floating_ip.address)

        template_param_dict['private_ip'] = ','.join(ips)
        template_param_dict['public_ip'] = ','.join(floating_ips)

        sec_groups = db.security_group_get_by_instance(ctxt, old_school_id)
        grps = [grp.name for grp in sec_groups]
        template_param_dict['security_group'] = ','.join(grps)

        fields_string = ""
        for key in template_param_dict:
            fields_string += "\n|%s=%s" % (key, template_param_dict[key])

        if event_type == 'compute.instance.delete.start':
            page_string = "\n%s\nThis instance has been deleted.\n%s\n" % (
                begin_comment, end_comment)
        else:
            page_string = "\n%s\n{{InstanceStatus%s}}\n%s\n" % (
                begin_comment, fields_string, end_comment)

        self._wiki_login()
        pagename = "%s%s" % (FLAGS.wiki_page_prefix, ec2_id)
        LOG.debug("wikistatus:  Writing instance info"
                  " to page http://%s/wiki/%s" % (FLAGS.wiki_host, pagename))

        page = self.site.Pages[pagename]
        try:
            pText = page.edit()
            start_replace_index = pText.find(begin_comment)
            if start_replace_index == -1:
                # Just stick it at the end.
                newText = "%s%s" % (page_string, pText)
            else:
                # Replace content between comment tags.
                end_replace_index = pText.find(end_comment,
                                               start_replace_index)
                if end_replace_index == -1:
                    end_replace_index = start_replace_index + len(
                        begin_comment)
                else:
                    end_replace_index += len(end_comment)
                newText = "%s%s%s" % (pText[:start_replace_index], page_string,
                                      pText[end_replace_index:])
            page.save(newText, "Auto update of instance info.")
        except (mwclient.errors.InsufficientPermission,
                mwclient.errors.LoginError):
            LOG.debug("Failed to update wiki page..."
                      " trying to re-login next time.")
            self._wiki_logged_in = False