前面有篇《nova boot from volume代码分析》http://iceyao.blog.51cto.com/9426658/1770927今天这里看下针对nova boot from volume无法注入密码的简单hack。


nova/virt/libvirt/driver.py中_inject_data函数部分代码

if any((key, net, metadata, admin_pass, files)):
            injection_image = self.image_backend.image(
                instance,
                'disk' + suffix,
                image_type)
            img_id = instance.image_ref
            
            if not injection_image.check_image_exists():
                LOG.warn(_LW('Image %s not found on disk storage. '
                         'Continue without injecting data'),
                         injection_image.path, instance=instance)
                return

其实主要问题是,nova boot from rbd volume的时候,虚拟机的系统盘是在云硬盘那里的,所以必须先定位云硬盘的位置,才可以注入密码。默认情况下boot from image,系统盘名字是<instance-uuid>_disk,boot from volume名字是volume-<volume-uuid>。


nova/virt/libvirt/imagebackend.py

class Rbd(Image):
    SUPPORTS_CLONE = True
    def __init__(self, instance=None, disk_name=None, path=None, **kwargs):
        super(Rbd, self).__init__("block", "rbd", is_block_dev=False)
        if path:
            try:
                self.rbd_name = path.split('/')[1]
            except IndexError:
                raise exception.InvalidDevicePath(path=path)
        else:
            self.rbd_name = '%s_%s' % (instance.uuid, disk_name)
        if not CONF.libvirt.images_rbd_pool:
            raise RuntimeError(_('You should specify'
                                 ' images_rbd_pool'
                                 ' flag to use rbd images.'))
        self.pool = CONF.libvirt.images_rbd_pool
        self.discard_mode = CONF.libvirt.hw_disk_discard
        self.rbd_user = CONF.libvirt.rbd_user
        self.ceph_conf = CONF.libvirt.images_rbd_ceph_conf
        
        # 这里的判断逻辑不是很严谨,纯碎演示
        if not instance.image_ref:
            context = nova_context.get_admin_context()
            # 获取bdms
            bdms = (
                    objects.BlockDeviceMappingList.get_by_instance_uuid(
                            context, instance.uuid))
            connection_info = jsonutils.loads(bdms[0].connection_info)
            # 获得系统盘volume-id,cinder rbd pool
            self.rbd_name = connection_info['data']['name'].split('/')[1]
            self.pool = connection_info['data']['name'].split('/')[0]