• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
导航菜单
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • windows
  • 服务器硬件
  • 服务器运维
  • 云计算
  • 虚拟化
  • IIS教程
  • Linux
  • Apache
  • Ftp
  • DNS
  • Nginx
您的位置:首页 > 服务器 >虚拟化 > OpenStack之虚机热迁移的代码详细解析

OpenStack之虚机热迁移的代码详细解析

作者:尛鱼 字体:[增加 减小] 来源:互联网

本文主要包含openstack,热迁移,openstack,虚拟机迁移等服务器相关知识,尛鱼 希望可以进行参考

话说虚机迁移分为冷迁移以及热迁移,所谓热迁移用度娘的话说即是:热迁移(Live Migration,又叫动态迁移、实时迁移),即虚机保存/恢复(Save/Restore):将整个虚拟机的运行状态完整保存下来,同时可以快速的恢复到原有硬件平台甚至是不同硬件平台上。恢复以后,虚机仍旧平滑运行,用户不会察觉到任何差异。OpenStack的虚机迁移是基于Libvirt实现的,下面来看看Openstack虚机热迁移的具体代码实现。

首先,由API入口进入到nova/api/openstack/compute/contrib/admin_actions.py

@wsgi.action('os-migrateLive')
  def _migrate_live(self, req, id, body):
    """Permit admins to (live) migrate a server to a new host."""
    context = req.environ["nova.context"]
    authorize(context, 'migrateLive')

    try:
      block_migration = body["os-migrateLive"]["block_migration"]
      disk_over_commit = body["os-migrateLive"]["disk_over_commit"]
      host = body["os-migrateLive"]["host"]
    except (TypeError, KeyError):
      msg = _("host, block_migration and disk_over_commit must "
          "be specified for live migration.")
      raise exc.HTTPBadRequest(explanation=msg)

    try:
      block_migration = strutils.bool_from_string(block_migration,
                            strict=True)
      disk_over_commit = strutils.bool_from_string(disk_over_commit,
                             strict=True)
    except ValueError as err:
      raise exc.HTTPBadRequest(explanation=str(err))

    try:
      instance = self.compute_api.get(context, id, want_objects=True)
      self.compute_api.live_migrate(context, instance, block_migration,
                     disk_over_commit, host)
    except (exception.ComputeServiceUnavailable,
        exception.InvalidHypervisorType,
        exception.UnableToMigrateToSelf,
        exception.DestinationHypervisorTooOld,
        exception.NoValidHost,
        exception.InvalidLocalStorage,
        exception.InvalidSharedStorage,
        exception.MigrationPreCheckError) as ex:
      raise exc.HTTPBadRequest(explanation=ex.format_message())
    except exception.InstanceNotFound as e:
      raise exc.HTTPNotFound(explanation=e.format_message())
    except exception.InstanceInvalidState as state_error:
      common.raise_http_conflict_for_instance_invalid_state(state_error,
          'os-migrateLive')
    except Exception:
      if host is None:
        msg = _("Live migration of instance %s to another host "
            "failed") % id
      else:
        msg = _("Live migration of instance %(id)s to host %(host)s "
            "failed") % {'id': id, 'host': host}
      LOG.exception(msg)
      # Return messages from scheduler
      raise exc.HTTPBadRequest(explanation=msg)

    return webob.Response(status_int=202)

   这里第一行可以看到是与API文档的第二行照应的:
  

 {
  "os-migrateLive": {
    "host": "0443e9a1254044d8b99f35eace132080",
    "block_migration": false,
    "disk_over_commit": false
  }
}

好了,源码中其实执行迁移工作的就是第26、27行的一条语句:

self.compute_api.live_migrate(context, instance, block_migration,
                 disk_over_commit, host)

由这句进入到nova/compute/api.py中,源码如下:

@check_instance_cell
  @check_instance_state(vm_state=[vm_states.ACTIVE])
  def live_migrate(self, context, instance, block_migration,
           disk_over_commit, host_name):
    """Migrate a server lively to a new host."""
    LOG.debug(_("Going to try to live migrate instance to %s"),
         host_name or "another host", instance=instance)

    instance.task_state = task_states.MIGRATING
    instance.save(expected_task_state=[None])

    self.compute_task_api.live_migrate_instance(context, instance,
        host_name, block_migration=block_migration,
        disk_over_commit=disk_over_commit)

第2行是一个装饰器,用于在进入API方法之前,检测虚拟机和/或任务的状态, 如果实例处于错误的状态,将会引发异常;接下来实时迁移虚机到新的主机,并将虚机状态置于“migrating”,然后由12行进入nova/conductor/api.py

def live_migrate_instance(self, context, instance, host_name,
                block_migration, disk_over_commit):
     scheduler_hint = {'host': host_name}
     self._manager.migrate_server(
       context, instance, scheduler_hint, True, False, None,
       block_migration, disk_over_commit, None)

将主机名存入字典scheduler_hint中,然后调用nova/conductor/manager.py方法migrate_server,

def migrate_server(self, context, instance, scheduler_hint, live, rebuild,
      flavor, block_migration, disk_over_commit, reservations=None):
    if instance and not isinstance(instance, instance_obj.Instance):
      # NOTE(danms): Until v2 of the RPC API, we need to tolerate
      # old-world instance objects here
      attrs = ['metadata', 'system_metadata', 'info_cache',
           'security_groups']
      instance = instance_obj.Instance._from_db_object(
        context, instance_obj.Instance(), instance,
        expected_attrs=attrs)
    if live and not rebuild and not flavor:
      self._live_migrate(context, instance, scheduler_hint,
                block_migration, disk_over_commit)
    elif not live and not rebuild and flavor:
      instance_uuid = instance['uuid']
      with compute_utils.EventReporter(context, self.db,
                     'cold_migrate', instance_uuid):
        self._cold_migrate(context, instance, flavor,
                  scheduler_hint['filter_properties'],
                  reservations)
    else:
      raise NotImplementedError()

由于在nova/conductor/api.py中传过来的参数是

self._manager.migrate_server(
       context, instance, scheduler_hint, True, False, None,
       block_migration, disk_over_commit, None)

因此live是True,rebuild是Flase,flavor是None,执行第12、13行代码:

 if live and not rebuild and not flavor:
       self._live_migrate(context, instance, scheduler_hint,
                block_migration, disk_over_commit) 
 _live_migrate代码如下:
def _live_migrate(self, context, instance, scheduler_hint,
           block_migration, disk_over_commit):
    destination = scheduler_hint.get("host")
    try:
      live_migrate.execute(context, instance, destination,
               block_migration, disk_over_commit)
    except (exception.NoValidHost,
        exception.ComputeServiceUnavailable,
        exception.InvalidHypervisorType,
        exception.InvalidCPUInfo,
        exception.UnableToMigrateToSelf,
        exception.DestinationHypervisorTooOld,
        exception.InvalidLocalStorage,
        exception.InvalidSharedStorage,
        exception.HypervisorUnavailable,
        exception.MigrationPreCheckError) as ex:
      with excutils.save_and_reraise_exception():
        #TODO(johngarbutt) - eventually need instance actions here
        request_spec = {'instance_properties': {
          'uuid': instance['uuid'], },
        }
        scheduler_utils.set_vm_state_and_notify(context,
            'compute_task', 'migrate_server',
            dict(vm_state=instance['vm_state'],
               task_state=None,
               expected_task_state=task_states.MIGRATING,),
            ex, request_spec, self.db)
    except Exception as ex:
      LOG.error(_('Migration of instance %(instance_id)s to host'
            ' %(dest)s unexpectedly failed.'),
            {'instance_id': instance['uuid'], 'dest': destination},
            exc_info=True)
      raise exception.MigrationError(reason=ex)

首先,第三行中将主机名赋给destination,然后执行迁移,后面的都是异常的捕捉,执行迁移的代码分为两部分,先看第一部分,在nova/conductor/tasks/live_migrate.py的184行左右:




 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • KVM与OpenStack的前世今生(1)
  • 浅谈openstack中使用linux_bridge实现vxlan网络
  • openstack使用openvswitch实现vxlan的方法
  • 详解OpenStack之服务端口号
  • openstack共享80、443端口的实例代码
  • Centos7环境准备openstack pike的安装
  • openstack pike单机一键安装shell的方法
  • Openstack安装过程中遇到的问题汇总
  • 详解Openstack使用ubuntu镜像启动虚拟机实例
  • 详解Openstack环境准备

相关文章

  • Vmware虚拟机安装Ubuntu 16.04 LTS(长期支持)版本+VMware tools安装的图文教程
  • 详解Docker守护进程的配置及日志
  • VMware的三种网络连接方式区别
  • XenServer 6.5 安装配置图文教程
  • Docker 学习文档(知识结构整理)
  • 什么是Docker? Docker入门教程
  • 如何为Go程序创建一个最小的Docker Image详解
  • ubuntu docker搭建Hadoop集群环境的方法
  • 详解consul的安装和配置
  • CoreOS配置Docker镜像加速器的方法

文章分类

  • windows
  • 服务器硬件
  • 服务器运维
  • 云计算
  • 虚拟化
  • IIS教程
  • Linux
  • Apache
  • Ftp
  • DNS
  • Nginx

最近更新的内容

    • Win10上VMware workstation安装图文教程
    • 详解如何查看 docker 容器使用的资源
    • Docker简单安装与应用入门教程
    • docker指令收集整理(收藏)
    • 详解docker搭建redis集群的环境搭建
    • Centos 6.5中安装docker的步骤(简洁版)
    • Windows10下安装Docker的步骤图文教程
    • docker官方mysql镜像自定义配置详解
    • 详解Docker 数据卷管理
    • Docker到底是什么?Docker为什么它这么火!

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有