openstack-nova源码分析(十一)rebuild重建

本文详细分析了openstack-nova中rebuild重建的过程,从API入口到compute、conductor和compute rpcapi的交互,以及与spawn创建虚拟机的区别。主要涉及的函数包括compute_api.rebuild、conductor的rebuild_instance和compute_rpcapi.rebuild_instance。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

rebuild 重建:

虚拟重置为初始状态, 或者更换镜像等

一.API

API入口在nova/api/openstack/compute/servers.py

    @wsgi.action('rebuild')
    @validation.schema(schema_server_rebuild_v20, '2.0', '2.0')
    @validation.schema(schema_server_rebuild, '2.1', '2.18')
    @validation.schema(schema_server_rebuild_v219, '2.19')
    def _action_rebuild(self, req, id, body):
        """Rebuild an instance with the given attributes."""
        rebuild_dict = body['rebuild']

				// 重建的镜像参数
        image_href = rebuild_dict["imageRef"]

				// 重建指定密码
        password = self._get_server_admin_password(rebuild_dict)

				// 校验instance 以及 校验是否允许rebuild权限
        context = req.environ['nova.context']
        instance = self._get_server(context, req, id)
        context.can(server_policies.SERVERS % 'rebuild',
                    target={'user_id': instance.user_id,
                            'project_id': instance.project_id})
        attr_map = {
            'name': 'display_name',
            'description': 'display_description',
            'metadata': 'metadata',
        }

        kwargs = {}

        helpers.translate_attributes(helpers.REBUILD, rebuild_dict, kwargs)

        for request_attribute, instance_attribute in attr_map.items():
            try:
                if request_attribute == 'name':
                    kwargs[instance_attribute] = common.normalize_name(
                        rebuild_dict[request_attribute])
                else:
                    kwargs[instance_attribute] = rebuild_dict[
                        request_attribute]
            except (KeyError, TypeError):
                pass

        try:
        
        	// 重建
            self.compute_api.rebuild(context,
                                     instance,
                                     image_href,
                                     password,
                                     **kwargs)
        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'rebuild', id)
                    
				......

        instance = self._get_server(context, req, id, is_detail=True)

        view = self._view_builder.show(req, instance, extend_address=False)

        # Add on the admin_password attribute since the view doesn't do it
        # unless instance passwords are disabled
        if CONF.api.enable_instance_password:
            view['server']['adminPass'] = password

        robj = wsgi.ResponseObject(view)
        return self._add_location(robj)


二. compute rebuild

compute_api.rebuild 定义在nova/compute/api.py

该函数为一个长函数, 这里进行拆分查看

   @check_instance_lock
    @check_instance_cell
    
    // 校验虚拟机状态, 只允许在指定状态下进行
    @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED,
                                    vm_states.ERROR])
    def rebuild(self, context, instance, image_href, admin_password,
                files_to_inject=None, **kwargs):


				// 获取参数, 并进行参数校验
        files_to_inject = files_to_inject or []
        metadata = kwargs.get('metadata', {})
        preserve_ephemeral = kwargs.get('preserve_ephemeral', False)
        auto_disk_config = kwargs.get('auto_disk_config')

        image_id, image = self._get_image(context, image_href)
        self._check_auto_disk_config(image=image, **kwargs)

        flavor = instance.get_flavor()
        
        
        获取磁盘的mapping信息
        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
            context, instance.uuid)
        root_bdm = compute_utils.get_root_bdm(context, instance, bdms)


        # Check to see if the image is changing and we have a volume-backed
        # server.
        is_volume_backed = compute_utils.is_volume_backed_instance(
            context, instance, bdms)
        if is_volume_backed:
            # For boot from volume, instance.image_ref is empty, so we need to
            # query the image from the volume.
            if root_bdm is None:
                # This shouldn't happen and is an error, we need to fail. This
                # is not the users fault, it's an internal error. Without a
                # root BDM we have no way of knowing the backing volume (or
                # image in that volume) for this instance.
                raise exception.NovaException(
                    _('Unable to find root block device mapping for '
                      'volume-backed instance.'))

            volume = self.volume_api.get(context, root_bdm.volume_id)
 
### 安装 OpenStack Nova 组件 可以通过 `yum` 命令来安装 OpenStack Nova 的相关组件,具体命令如下: ```bash yum -y install openstack-nova-api openstack-nova-conductor openstack-nova-scheduler openstack-nova-novncproxy ``` 此命令将会自动下载并安装所需的依赖项以及指定的服务组件[^1]。 --- ### 配置 OpenStack Nova 服务 完成安装后,需要对这些服务进行必要的配置。以下是主要步骤说明: #### 修改主配置文件 编辑 `/etc/nova/nova.conf` 文件以调整调度器的行为。例如,为了实现定期扫描计算节点的功能,可以在 `[scheduler]` 节下添加以下参数: ```ini [scheduler] discover_hosts_in_cells_interval = 300 ``` 这表示每隔 300 秒(即 5 分钟)扫描一次计算节点中的主机状态[^4]。 保存更改后重启 API 服务以使新配置生效: ```bash systemctl restart openstack-nova-api.service ``` --- ### 启动与设置开机自启 安装完成后,需手动启动各个 Nova 相关服务,并将其设为随系统启动而运行: ```bash systemctl start openstack-nova-api openstack-nova-scheduler openstack-nova-conductor openstack-nova-novncproxy systemctl enable openstack-nova-api openstack-nova-scheduler openstack-nova-conductor openstack-nova-novncproxy ``` 以上操作确保了所有核心服务正常运行并能够在下次系统启动时自动加载[^2]。 --- ### 创建管理接口端点 如果尚未创建 Nova 的管理员服务端点,则可通过以下命令完成初始化工作: ```bash openstack endpoint create --region RegionOne nova admin http://<control_node_ip>:8774/v2.1 ``` 其中 `<control_node_ip>` 应替换为实际的控制器节点 IP 地址。成功执行该命令后,将返回包含字段及其对应值的结果表单,确认端点已正确注册到 Keystone 中[^3]。 --- ### 总结 综上所述,通过 Yum 源安装 OpenStack Nova 组件的过程涉及以下几个方面: 1. 使用 `yum` 工具批量安装所需软件包; 2. 编辑配置文件优化功能选项; 3. 手动激活各子服务并将它们加入系统的引导序列; 4. 注册相应的访问入口至身份验证框架内。 按照上述指导即可顺利完成基础环境搭建任务。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值