OpenStack Nova-scheduler组件的源码解析(2)

本文深入解析了OpenStack中Nova调度器的工作原理,重点介绍了如何选取最优主机节点来部署虚拟机实例的过程。文章详细分析了调度器的核心代码实现,包括如何过滤和评估潜在主机,以及如何最终确定合适的主机。

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

这篇博客中,我会针对建立虚拟机实例的请求,来解析Nova调度器选取最优主机节点的过程。

首先来看方法/nova/scheduler/manager.py----def run_instance:

  1. def run_instance(self, context, request_spec, admin_password,  
  2.             injected_files, requested_networks, is_first_time,  
  3.             filter_properties):  
  4.         """ 
  5.         在驱动上尝试调用schedule_run_instance; 
  6.         当引发异常的时候设置实例vm_state为ERROR; 
  7.         context:上下文信息; 
  8.         request_spec:请求规范; 
  9.         admin_password:admin用户密码; 
  10.         injected_files:注入的文件; 
  11.         requested_networks:请求的网络信息; 
  12.         is_first_time:标志是否是第一次; 
  13.         filter_properties:过滤器属性信息; 
  14.         """  
  15.           
  16.         # 获取要运行的实例UUID值;  
  17.         instance_uuids = request_spec['instance_uuids']  
  18.         # EventReporter:上下文管理类;  
  19.         # 获取EventReporter类的对象;  
  20.         with compute_utils.EventReporter(context, conductor_api.LocalAPI(),  
  21.                                          'schedule', *instance_uuids):  
  22.               
  23.             # schedule_run_instance这个方法在/nova/scheduler/chance.py和/nova/scheduler/filter_scheduler.py中都有定义;  
  24.             # 这里具体调用的是哪一个方法,要看driver的定义;  
  25.             # 这个类的初始化方法中定义了self.driver = importutils.import_object(scheduler_driver);  
  26.             # 也就是说,调用哪一个方法,是由scheduler_driver来具体指定的;  
  27.             # 初始化类中具体定义了,如果scheduler_driver没有被定义,则采用配置参数来给它赋值;  
  28.             # 也就是scheduler_driver = CONF.scheduler_driver;  
  29.             # 而配置参数CONF.scheduler_driver默认的值是nova.scheduler.filter_scheduler.FilterScheduler;  
  30.             # 从而可以知道,当没有指明scheduler_driver的值时,默认调用/nova/scheduler/filter_scheduler.py中的schedule_run_instance方法;  
  31.             # 这里我会把两个方法都分别跟踪进行分析的;  
  32.               
  33.             # /nova/scheduler/filter_scheduler.py中的schedule_run_instance方法完成了以下的操作;  
  34.             # 获取要建立实例的数目;  
  35.             # 循环每一个实例;  
  36.             # 获取分配给这个实例的主机;  
  37.             # 拨备创建实例请求的各种资源;  
  38.             # 远程发送运行实例的消息到队列;  
  39.             # 发布调度运行实例结束这个事件的通知;    
  40.               
  41.             # /nova/scheduler/chance.py中的schedule_run_instance方法完成了以下的操作;  
  42.             # 循环遍历每个实例;  
  43.             # 为每个实例随机挑选一个主机;  
  44.             # 在一个实例上设置给定的属性并更新实例相关的数据;     
  45.             # 远程发送建立实例的消息到队列;  
  46.               
  47.             #注:研究一下这两个方法的实现有什么不同;  
  48.             #研究这两个方法之后会对很多东西学的明白许多;  
  49.             try:  
  50.                 # driver = nova.scheduler.filter_scheduler.FilterScheduler  
  51.                 return self.driver.schedule_run_instance(context,  
  52.                         request_spec, admin_password, injected_files,  
  53.                         requested_networks, is_first_time, filter_properties)  
  54.   
  55.             except exception.NoValidHost as ex:  
  56.                 # don't re-raise  
  57.                 self._set_vm_state_and_notify('run_instance',  
  58.                                               {'vm_state': vm_states.ERROR,  
  59.                                               'task_state'None},  
  60.                                               context, ex, request_spec)  
  61.             except Exception as ex:  
  62.                 with excutils.save_and_reraise_exception():  
  63.                     self._set_vm_state_and_notify('run_instance',  
  64.                                                   {'vm_state': vm_states.ERROR,  
  65.                                                   'task_state'None},  
  66.                                                   context, ex, request_spec)  
我们来看语句return self.driver.schedule_run_instance(context,request_spec, admin_password, injected_files,requested_networks, is_first_time, filter_properties)

来看这个方法所处的类SchedulerManager的初始化方法:

  1. class SchedulerManager(manager.Manager):  
  2.     """ 
  3.     选择一个主机来运行实例; 
  4.     """  
  5.   
  6.     RPC_API_VERSION = '2.6'  
  7.   
  8.     def __init__(self, scheduler_driver=None, *args, **kwargs):  
  9.           
  10.         # 如果scheduler_driver没有定义,则赋值CONF.scheduler_driver给scheduler_driver;  
  11.         # scheduler_driver:这个配置参数默认值为nova.scheduler.filter_scheduler.FilterScheduler;  
  12.         if not scheduler_driver:  
  13.             scheduler_driver = CONF.scheduler_driver  
  14.           
  15.         # import_object:导入一个类,然后返回这个类的实例对象;  
  16.         # 导入scheduler_driver指定的类;  
  17.         # 例如scheduler_driver的值为nova.scheduler.filter_scheduler.FilterScheduler;  
  18.         # 则导入nova.scheduler.filter_scheduler.FilterScheduler这个类;  
  19.         # 这样也就实现了类的动态的导入;  
  20.         self.driver = importutils.import_object(scheduler_driver)  
  21.         super(SchedulerManager, self).__init__(*args, **kwargs)  
再来看scheduler_driver的定义:
  1. scheduler_driver_opt = cfg.StrOpt('scheduler_driver',  
  2.         default='nova.scheduler.filter_scheduler.FilterScheduler',  
  3.         help='Default driver to use for the scheduler')  
我们可以看到调度器所应用的选取主机方法是动态导入的,默认是应用nova.scheduler.filter_scheduler.FilterScheduler类所定义的基于主机过滤器的调度器方法。

再来看方法schedule_run_instance的代码实现:

  1. def schedule_run_instance(self, context, request_spec,  
  2.                               admin_password, injected_files,  
  3.                               requested_networks, is_first_time,  
  4.                               filter_properties):  
  5.         """ 
  6.         这个方法被从nova.compute.api调用,来提供实例; 
  7.         返回创建的实例的列表; 
  8.                       
  9.         获取要建立实例的数目; 
  10.         循环每一个实例,获取分配给这个实例的主机; 
  11.         拨备创建实例请求的各种资源; 
  12.         远程发送运行实例的消息到队列; 
  13.         发布调度运行实例结束这个事件的通知;    
  14.         """  
  15.         # request_spec:请求规范;  
  16.         # 这个参数的格式字典化;  
  17.         payload = dict(request_spec=request_spec)  
  18.           
  19.         # notifier.publisher_id("scheduler"):获取信息发布者ID;  
  20.         # 返回值为"scheduler.host";  
  21.         # notify:使用指定的驱动程序发布通知;(这个方法需要进一步分析它的具体实现过程)  
  22.         notifier.notify(context, notifier.publisher_id("scheduler"),'scheduler.run_instance.start', notifier.INFO, payload)  
  23.   
  24.         # 从request_spec当中获取instance_uuids值;  
  25.         instance_uuids = request_spec.pop('instance_uuids')  
  26.         # 获取要建立实例的数目;  
  27.         num_instances = len(instance_uuids)  
  28.         LOG.debug(_("Attempting to build %(num_instances)d instance(s)") % locals())  
  29.   
  30.         # 返回满足要求规格的主机列表;  
  31.         # 循环为每一个实例获取合适的主机后,返回选择的主机列表;  
  32.         weighed_hosts = self._schedule(context, request_spec, filter_properties, instance_uuids)  
  33.   
  34.         # @@@这个语句没有弄明白,后面要继续看一下;  
  35.         filter_properties.pop('context'None)  
  36.   
  37.         # 循环遍历instance_uuids;  
  38.         for num, instance_uuid in enumerate(instance_uuids):  
  39.             request_spec['instance_properties']['launch_index'] = num  
  40.   
  41.             try:  
  42.                 # 获取分配给这个实例的主机;  
  43.                 try:  
  44.                     weighed_host = weighed_hosts.pop(0)  
  45.                 except IndexError:  
  46.                     raise exception.NoValidHost(reason="")  
  47.   
  48.                 # context:上下文信息;  
  49.                 # weighed_host:获取分配给这个实例的主机;  
  50.                 # request_spec:请求规范;  
  51.                 # filter_properties:过滤器属性信息;  
  52.                 # requested_networks:请求的网络信息;  
  53.                 # injected_files:注入文件;  
  54.                 # admin_password:admin密码;  
  55.                 # is_first_time:标志是否是第一次;  
  56.                 # instance_uuid:每个实例的UUID;  
  57.                 # _provision_resource:在这个区域内拨备创建请求的各种资源;  
  58.                 # 远程发送建立实例的消息到队列;  
  59.                 self._provision_resource(context, weighed_host,  
  60.                                          request_spec,  
  61.                                          filter_properties,  
  62.                                          requested_networks,  
  63.                                          injected_files, admin_password,  
  64.                                          is_first_time,  
  65.                                          instance_uuid=instance_uuid)  
  66.             except Exception as ex:  
  67.                 driver.handle_schedule_error(context, ex, instance_uuid, request_spec)  
  68.             retry = filter_properties.get('retry', {})  
  69.             retry['hosts'] = []  
  70.   
  71.         # @@@notify:使用指定的驱动程序发布通知;  
  72.         # 应该是发布调度运行实例结束这个事件的通知;  
  73.         notifier.notify(context, notifier.publisher_id("scheduler"),  
  74.                         'scheduler.run_instance.end', notifier.INFO, payload)  
我们比较关注语句weighed_hosts = self._schedule(context, request_spec, filter_properties, instance_uuids),这条语句通过调用方法_schedule实现了循环为每一个实例获取合适的主机后,返回可用的主机列表。具体来看方法_schedule的代码实现:
  1. def _schedule(self, context, request_spec, filter_properties, instance_uuids=None):  
  2.         """ 
  3.         返回满足要求规格的主机列表; 
  4.         循环为每一个实例获取合适的主机后,返回选择的主机列表; 
  5.          
  6.         对主机进行过滤; 
  7.         FilterManager类继承自Scheduler类; 
  8.         在Scheduler类的初始化中,加载了所有可用的filter类; 
  9.         根据配置文件中scheduler_default_filters字段的定义选择默认使用的一个或多个filter; 
  10.         依次对每个主机调用filter类的host_passes()方法,如果返回都为True,则主机通过过滤; 
  11.          
  12.         对所有通过过滤的主机计算权值; 
  13.         """  
  14.         # elevated:返回带有admin标志设置的context的版本;  
  15.         elevated = context.elevated()  
  16.         # 获取实例属性信息(instance_properties);  
  17.         instance_properties = request_spec['instance_properties']  
  18.         # 获取实例类型信息(instance_type);  
  19.         instance_type = request_spec.get("instance_type"None)  
  20.   
  21.         update_group_hosts = False  
  22.         # 获取scheduler_hints;  
  23.         scheduler_hints = filter_properties.get('scheduler_hints'or {}  
  24.         # 获取group信息;  
  25.         group = scheduler_hints.get('group'None)  
  26.         if group:  
  27.             # group_hosts:获取group中所有具有经过过滤后符合过滤条件的主机的列表;  
  28.             group_hosts = self.group_hosts(elevated, group)  
  29.             # 表示已经更新过group_hosts;  
  30.             update_group_hosts = True  
  31.             # 如果filter_properties中不包含'group_hosts',则增加'group_hosts'到filter_properties中;  
  32.             if 'group_hosts' not in filter_properties:  
  33.                 filter_properties.update({'group_hosts': []})  
  34.                   
  35.             # 获取filter_properties中原有的'group_hosts';  
  36.             # 把两部分'group_hosts'加在一起;(@@@应该都是符合条件的,自己的理解;)  
  37.             configured_hosts = filter_properties['group_hosts']  
  38.             filter_properties['group_hosts'] = configured_hosts + group_hosts  
  39.   
  40.         # 获取配置选项;  
  41.         config_options = self._get_configuration_options()  
  42.           
  43.         # 要建立实例的属性信息对象拷贝;  
  44.         properties = instance_properties.copy()  
  45.           
  46.         # 从instance_uuids获取properties['uuid'];  
  47.         if instance_uuids:  
  48.             properties['uuid'] = instance_uuids[0]  
  49.         # 记录尝试次数;  
  50.         self._populate_retry(filter_properties, properties)  
  51.   
  52.         # 更新过滤器属性信息;  
  53.         filter_properties.update({'context': context,  
  54.                                   'request_spec': request_spec,  
  55.                                   'config_options': config_options,  
  56.                                   'instance_type': instance_type})  
  57.   
  58.         # 从request_spec获取有用的信息,填充到过滤器属性当中;  
  59.         # 分别是filter_properties['os_type']和filter_properties['project_id'];  
  60.         self.populate_filter_properties(request_spec, filter_properties)  
  61.   
  62.         # 寻找可以接受的本地主机列表通过对我们的选项进行反复的过滤和称重;  
  63.         # 这里我们使用了迭代,所以只遍历了一次这个列表;  
  64.         # 获取并返回HostStates列表;  
  65.           
  66.         # 过滤掉不满足要求的主机;   
  67.         hosts = self.host_manager.get_all_host_states(elevated)  
  68.   
  69.         selected_hosts = []  
  70.           
  71.         # 获取要建立的实例数目;  
  72.         if instance_uuids:  
  73.             num_instances = len(instance_uuids)  
  74.         else:  
  75.             num_instances = request_spec.get('num_instances'1)  
  76.               
  77.         # 遍历num_instances个实例,为每个实例选取合适的运行主机;  
  78.         for num in xrange(num_instances):  
  79.             # Filter local hosts based on requirements ...  
  80.             # 基于具体要求过滤本地主机;  
  81.             # get_filtered_hosts:过滤主机,返回那些通过所有过滤器的主机;  
  82.             hosts = self.host_manager.get_filtered_hosts(hosts, filter_properties)  
  83.             if not hosts:  
  84.                 break  
  85.   
  86.             LOG.debug(_("Filtered %(hosts)s") % locals())  
  87.               
  88.             # 对主机进行称重;  
  89.             # 获取并返回一个WeighedObjects的主机排序列表(最高分排在第一);  
  90.             weighed_hosts = self.host_manager.get_weighed_hosts(hosts, filter_properties)  
  91.   
  92.             # scheduler_host_subset_size:这个参数定义了新的实例将会被调度到一个主机上,这个主机是随机的从最好的(分数最高的)N个主机组成的子集中选择出来的;  
  93.             # 这个参数定义了这个子集的大小,供选择最好的主机使用;  
  94.             # 如果值为1,则由称重函数返回第一个主机;  
  95.             # 这个值至少为1,任何小于1的值都会被忽略,而且会被1所代替;  
  96.             # 这个参数的默认值为1;  
  97.             scheduler_host_subset_size = CONF.scheduler_host_subset_size  
  98.             if scheduler_host_subset_size > len(weighed_hosts):  
  99.                 scheduler_host_subset_size = len(weighed_hosts)  
  100.             if scheduler_host_subset_size < 1:  
  101.                 scheduler_host_subset_size = 1  
  102.   
  103.             # 按照上面的解释,从分数最高的若干主机组成的子集中,随机的选择一个主机出来;  
  104.             # 新的实例将会被调度到这个主机上;  
  105.             chosen_host = random.choice(  
  106.                 weighed_hosts[0:scheduler_host_subset_size])  
  107.             LOG.debug(_("Choosing host %(chosen_host)s") % locals())  
  108.             # 把选好的主机增加到selected_hosts列表中;  
  109.             selected_hosts.append(chosen_host)  
  110.   
  111.             # 因为已经选好了一个主机,所以要在下一个实例选择主机前,更新主机资源信息;  
  112.             chosen_host.obj.consume_from_instance(instance_properties)  
  113.             if update_group_hosts is True:  
  114.                 filter_properties['group_hosts'].append(chosen_host.obj.host)  
  115.           
  116.         # 循环为每一个实例获取合适的主机后,返回选择的主机列表;  
  117.         return selected_hosts  
在这个方法的实现过程中,主要就是三步:

1.语句:hosts = self.host_manager.get_all_host_states(elevated)

实现了过滤掉不可用的主机节点,获取可用的主机节点列表;

2 语句:hosts = self.host_manager.get_filtered_hosts(hosts, filter_properties)

针对建立一个虚拟机实例的要求,实现了用系统指定的过滤器对上面获取的可用主机节点列表进行过滤,进一步得到符合过滤器要求的主机列表;

3 语句:weighed_hosts = self.host_manager.get_weighed_hosts(hosts, filter_properties)

实现了对过滤后的主机列表中的每一个主机节点进行称重操作,选取某个标准下最优的主机节点作为建立虚拟机实例的目标主机;

好了,具体来对这些语句进行解析。

1.hosts = self.host_manager.get_all_host_states(elevated)

具体来看方法get_all_host_states的代码实现:

  1. def get_all_host_states(self, context):  
  2.         """ 
  3.         获取并返回HostStates列表; 
  4.         HostStates代表了所有HostManager知道的主机; 
  5.         另外,HostState中的每个consumable resources都是预填充的; 
  6.         基于数据库中的数据进行调整;        
  7.         过滤掉不满足要求的主机;      
  8.         """  
  9.   
  10.         # 获取可用计算节点的资源使用情况;  
  11.         # 获取所有computeNodes(计算节点);  
  12.         compute_nodes = db.compute_node_get_all(context)  
  13.         # 集合;  
  14.         seen_nodes = set()  
  15.         for compute in compute_nodes:  
  16.             service = compute['service']  
  17.             if not service:  
  18.                 LOG.warn(_("No service for compute ID %s") % compute['id'])  
  19.                 continue  
  20.             # 获取主机host;  
  21.             host = service['host']  
  22.             # 获取hypervisor_hostname作为节点名;  
  23.             node = compute.get('hypervisor_hostname')  
  24.             # 组成state_key;  
  25.             state_key = (host, node)  
  26.             # 获取capabilities;  
  27.             capabilities = self.service_states.get(state_key, None)  
  28.             # 获取host_state;  
  29.             host_state = self.host_state_map.get(state_key)  
  30.               
  31.             # 更新只读的capabilities字典;  
  32.             if host_state:  
  33.                 host_state.update_capabilities(capabilities, dict(service.iteritems()))  
  34.             # @@@跟踪一台主机的可变和不可变的信息;  
  35.             # 还试图删除以前使用的数据结构,并锁定访问;  
  36.             else:  
  37.                 host_state = self.host_state_cls(host, node,capabilities=capabilities,service=dict(service.iteritems()))  
  38.                 self.host_state_map[state_key] = host_state  
  39.                   
  40.             # update_from_compute_node:从compute信息更新它的主机信息;  
  41.             host_state.update_from_compute_node(compute)  
  42.             # 更新集合seen_nodes;  
  43.             seen_nodes.add(state_key)  
  44.   
  45.         # 从host_state_map中删除状态不是活跃的计算节点;  
  46.         # 获取并删除状态不活跃的计算节点;  
  47.         dead_nodes = set(self.host_state_map.keys()) - seen_nodes  
  48.         for state_key in dead_nodes:  
  49.             host, node = state_key  
  50.             LOG.info(_("Removing dead compute node %(host)s:%(node)s "  
  51.                        "from scheduler") % locals())  
  52.             del self.host_state_map[state_key]  
  53.   
  54.         return self.host_state_map.itervalues()  
1.1 compute_nodes = db.compute_node_get_all(context)

这条语句实现了从数据库获取所有computeNodes(计算节点),具体来看方法compute_node_get_all的代码实现:

  1. def compute_node_get_all(context):  
  2.     """ 
  3.     通过查询数据库所有所有ComputeNode(数据节点); 
  4.     """  
  5.     return model_query(context, models.ComputeNode).\  
  6.             options(joinedload('service')).\  
  7.             options(joinedload('stats')).\  
  8.             all()  

1.2 host_state = self.host_state_cls(host, node,capabilities=capabilities,service=dict(service.iteritems()))

这条语句实现了初始化主机的一些参数,具体来看代码:

  1. host_state_cls = HostState  
  2. class HostState(object):  
  3.     def __init__(self, host, node, capabilities=None, service=None):  
  4.         self.host = host  
  5.         self.nodename = node  
  6.         self.update_capabilities(capabilities, service)  
  7.   
  8.         # Mutable available resources.  
  9.         # These will change as resources are virtually "consumed".  
  10.         self.total_usable_disk_gb = 0  
  11.         self.disk_mb_used = 0  
  12.         self.free_ram_mb = 0  
  13.         self.free_disk_mb = 0  
  14.         self.vcpus_total = 0  
  15.         self.vcpus_used = 0  
  16.         # Valid vm types on this host: 'pv', 'hvm' or 'all'  
  17.         if 'allowed_vm_type' in self.capabilities:  
  18.             self.allowed_vm_type = self.capabilities['allowed_vm_type']  
  19.         else:  
  20.             self.allowed_vm_type = 'all'  
  21.   
  22.         # Additional host information from the compute node stats:  
  23.         self.vm_states = {}  
  24.         self.task_states = {}  
  25.         self.num_instances = 0  
  26.         self.num_instances_by_project = {}  
  27.         self.num_instances_by_os_type = {}  
  28.         self.num_io_ops = 0  
  29.   
  30.         # Resource oversubscription values for the compute host:  
  31.         self.limits = {}  
  32.   
  33.         self.updated = None  

1.3 host_state.update_from_compute_node(compute)

这条语句实现了从compute信息更新主机信息,具体来看代码:

  1. def update_from_compute_node(self, compute):  
  2.         """ 
  3.         从compute_node信息更新它的主机信息; 
  4.         """  
  5.           
  6.         # 若果已经更新过,则直接返回;  
  7.         if (self.updated and compute['updated_at'and self.updated > compute['updated_at']):  
  8.             return  
  9.         # 获取all_ram_mb;  
  10.         all_ram_mb = compute['memory_mb']  
  11.   
  12.         # 假设如果使用qcow2磁盘,则虚拟磁盘大小都被实例所消耗;  
  13.         least = compute.get('disk_available_least')  
  14.         # 获取剩余的磁盘空间free_disk_mb;  
  15.         free_disk_mb = least if least is not None else compute['free_disk_gb']  
  16.         free_disk_mb *= 1024  
  17.   
  18.         # 获取使用的磁盘空间;  
  19.         self.disk_mb_used = compute['local_gb_used'] * 1024  
  20.   
  21.         # free_ram_mb可以是负值;  
  22.         self.free_ram_mb = compute['free_ram_mb']  
  23.         # 获取total_usable_ram_mb;  
  24.         self.total_usable_ram_mb = all_ram_mb  
  25.         # 获取total_usable_disk_gb;  
  26.         self.total_usable_disk_gb = compute['local_gb']  
  27.         self.free_disk_mb = free_disk_mb  
  28.         self.vcpus_total = compute['vcpus']  
  29.         self.vcpus_used = compute['vcpus_used']  
  30.         self.updated = compute['updated_at']  
  31.   
  32.         stats = compute.get('stats', [])  
  33.         statmap = self._statmap(stats)  
  34.   
  35.         # 追踪主机上的实例数目;  
  36.         self.num_instances = int(statmap.get('num_instances'0))  
  37.   
  38.         # 通过project_id获取实例数目;  
  39.         project_id_keys = [k for k in statmap.keys() if  
  40.                 k.startswith("num_proj_")]  
  41.         for key in project_id_keys:  
  42.             project_id = key[9:]  
  43.             self.num_instances_by_project[project_id] = int(statmap[key])  
  44.   
  45.         # 在一定的vm_states中追踪实例的数目;  
  46.         vm_state_keys = [k for k in statmap.keys() if k.startswith("num_vm_")]  
  47.         for key in vm_state_keys:  
  48.             vm_state = key[7:]  
  49.             self.vm_states[vm_state] = int(statmap[key])  
  50.   
  51.         # 在一定的task_states中追踪实例的数目;  
  52.         task_state_keys = [k for k in statmap.keys() if  
  53.                 k.startswith("num_task_")]  
  54.         for key in task_state_keys:  
  55.             task_state = key[9:]  
  56.             self.task_states[task_state] = int(statmap[key])  
  57.   
  58.         # 通过host_type追踪实例数目;  
  59.         os_keys = [k for k in statmap.keys() if k.startswith("num_os_type_")]  
  60.         for key in os_keys:  
  61.             os = key[12:]  
  62.             self.num_instances_by_os_type[os] = int(statmap[key])  
  63.   
  64.         # 获取num_io_ops;  
  65.         self.num_io_ops = int(statmap.get('io_workload'0))  
2.hosts = self.host_manager.get_filtered_hosts(hosts, filter_properties)

具体来看方法get_filtered_hosts的代码实现:

  1. def get_filtered_hosts(self, hosts, filter_properties, filter_class_names=None):  
  2.         """ 
  3.         过滤主机,返回那些通过所有过滤器的主机; 
  4.         """  
  5.   
  6.         def _strip_ignore_hosts(host_map, hosts_to_ignore):  
  7.             ignored_hosts = []  
  8.             for host in hosts_to_ignore:  
  9.                 if host in host_map:  
  10.                     del host_map[host]  
  11.                     ignored_hosts.append(host)  
  12.             ignored_hosts_str = ', '.join(ignored_hosts)  
  13.             msg = _('Host filter ignoring hosts: %(ignored_hosts_str)s')  
  14.             LOG.debug(msg, locals())  
  15.   
  16.         def _match_forced_hosts(host_map, hosts_to_force):  
  17.             for host in host_map.keys():  
  18.                 if host not in hosts_to_force:  
  19.                     del host_map[host]  
  20.             if not host_map:  
  21.                 forced_hosts_str = ', '.join(hosts_to_force)  
  22.                 msg = _("No hosts matched due to not matching 'force_hosts'"  
  23.                         "value of '%(forced_hosts_str)s'")  
  24.                 LOG.debug(msg, locals())  
  25.                 return  
  26.             forced_hosts_str = ', '.join(host_map.iterkeys())  
  27.             msg = _('Host filter forcing available hosts to '  
  28.                     '%(forced_hosts_str)s')  
  29.             LOG.debug(msg, locals())  
  30.   
  31.         # 返回经过验证的可用的过滤器;  
  32.         filter_classes = self._choose_host_filters(filter_class_names)  
  33.         ignore_hosts = filter_properties.get('ignore_hosts', [])  
  34.         force_hosts = filter_properties.get('force_hosts', [])  
  35.         if ignore_hosts or force_hosts:  
  36.             name_to_cls_map = dict([(x.host, x) for x in hosts])  
  37.             if ignore_hosts:  
  38.                 _strip_ignore_hosts(name_to_cls_map, ignore_hosts)  
  39.                 if not name_to_cls_map:  
  40.                     return []  
  41.             if force_hosts:  
  42.                 _match_forced_hosts(name_to_cls_map, force_hosts)  
  43.                 # NOTE(vish): Skip filters on forced hosts.  
  44.                 if name_to_cls_map:  
  45.                     return name_to_cls_map.values()  
  46.             hosts = name_to_cls_map.itervalues()  
  47.         return self.filter_handler.get_filtered_objects(filter_classes, hosts, filter_properties)  
2.1 filter_classes = self._choose_host_filters(filter_class_names)

这条语句实现了返回经过验证的可用的过滤器,具体来看方法_choose_host_filters的代码实现:

  1. def _choose_host_filters(self, filter_cls_names):  
  2.         """         
  3.         返回经过验证的可用的过滤器; 
  4.         """  
  5.         # 使用默认过滤器;  
  6.         if filter_cls_names is None:  
  7.             # CONF.scheduler_default_filters:这个参数定义了当请求中没有指定特定的过滤器类的时候,默认应用的用于过滤主机的过滤器类的名称列表;  
  8.             # 参数的默认值为:  
  9.             # ['RetryFilter','AvailabilityZoneFilter','RamFilter','ComputeFilter','ComputeCapabilitiesFilter','ImagePropertiesFilter']  
  10.             filter_cls_names = CONF.scheduler_default_filters  
  11.         if not isinstance(filter_cls_names, (list, tuple)):  
  12.             filter_cls_names = [filter_cls_names]  
  13.         good_filters = []  
  14.         bad_filters = []  
  15.           
  16.         # 遍历所有配置的过滤器(我们使用的是默认过滤器);  
  17.         for filter_name in filter_cls_names:  
  18.             found_class = False  
  19.             # 遍历所有可用的过滤器;  
  20.             for cls in self.filter_classes:  
  21.                 # 如果在可用过滤器中找到配置的过滤器,则认为它可以使用;  
  22.                 if cls.__name__ == filter_name:  
  23.                     good_filters.append(cls)  
  24.                     found_class = True  
  25.                     break  
  26.             if not found_class:  
  27.                 bad_filters.append(filter_name)  
  28.         if bad_filters:  
  29.             msg = ", ".join(bad_filters)  
  30.             raise exception.SchedulerHostFilterNotFound(filter_name=msg)  
  31.         return good_filters  

2.2 return self.filter_handler.get_filtered_objects(filter_classes, hosts, filter_properties)

  1. def get_filtered_objects(self, filter_classes, objs, filter_properties):  
  2.     for filter_cls in filter_classes:  
  3.         objs = filter_cls().filter_all(objs, filter_properties)  
  4.     return list(objs)  
  1. def filter_all(self, filter_obj_list, filter_properties):  
  2.         for obj in filter_obj_list:  
  3.             if self._filter_one(obj, filter_properties):  
  4.                 yield obj  
  1. def _filter_one(self, obj, filter_properties):  
  2.         """ 
  3.         如果通过过滤器则返回TRUE,否则返回FALSE; 
  4.         """  
  5.         return self.host_passes(obj, filter_properties)  
3. weighed_hosts = self.host_manager.get_weighed_hosts(hosts, filter_properties)
  1. def get_weighed_hosts(self, hosts, weight_properties):  
  2.     """ 
  3.     对主机进行称重; 
  4.     返回一个WeighedObjects的主机排序列表(最高分排在第一); 
  5.     """        
  6.     # get_weighed_objects:返回一个WeighedObjects的主机排序列表(最高分排在第一);  
  7.     return self.weight_handler.get_weighed_objects(self.weight_classes, hosts, weight_properties)  
  1. # scheduler_weight_classes:这个参数定义了使用哪个称重类来称重主机;  
  2. # 默认值是nova.scheduler.weights.all_weighers;  
  3. # 从名称列表CONF.scheduler_available_filters获取可装载的类;  
  4. # 返回类的列表;  
  5. # 所以这条语句的意思就是获取nova.scheduler.weights.all_weighers指定的所有的类;  
  6. self.weight_classes = self.weight_handler.get_matching_classes(CONF.scheduler_weight_classes)  
  1. cfg.ListOpt('scheduler_weight_classes',  
  2.             default=['nova.scheduler.weights.all_weighers'],  
  3.             help='Which weight class names to use for weighing hosts'),  
  4. # 这个参数定义了使用哪个称重类来称重主机;  
  5. # 默认值是nova.scheduler.weights.all_weighers;  
  1. def all_weighers():  
  2.     """ 
  3.     Return a list of weight plugin classes found in this directory. 
  4.     """  
  5.   
  6.     # least_cost_functions:这个参数定义了是否应用称重方法LeastCostScheduler;  
  7.     # 参数的默认值为None;  
  8.     # compute_fill_first_cost_fn_weight:参数的默认值为None;  
  9.     if (CONF.least_cost_functions is not None or  
  10.             CONF.compute_fill_first_cost_fn_weight is not None):  
  11.         LOG.deprecated(('least_cost has been deprecated in favor of the RAM Weigher.'))  
  12.         return least_cost.get_least_cost_weighers()  
  13.     return HostWeightHandler().get_all_classes()  
  1. def get_weighed_objects(self, weigher_classes, obj_list, weighing_properties):  
  2.     """ 
  3.     返回一个WeighedObjects的排序列表(最高分排在第一); 
  4.     """  
  5.   
  6.     if not obj_list:  
  7.         return []  
  8.   
  9.     # object_class = WeighedObject  
  10.     weighed_objs = [self.object_class(obj, 0.0for obj in obj_list]  
  11.     for weigher_cls in weigher_classes:  
  12.         weigher = weigher_cls()  
  13.         weigher.weigh_objects(weighed_objs, weighing_properties)  
  14.   
  15.     return sorted(weighed_objs, key=lambda x: x.weight, reverse=True)  
  16.   
  17. object_class = WeighedObject  
  1. class WeighedObject(object):  
  2.     """ 
  3.     权重信息对象类; 
  4.     """  
  5.     def __init__(self, obj, weight):  
  6.         self.obj = obj  
  7.         self.weight = weight  
  1. def get_least_cost_weighers():  
  2.     cost_functions = _get_cost_functions()  
  3.   
  4.     # Unfortunately we need to import this late so we don't have an  
  5.     # import loop.  
  6.     from nova.scheduler import weights  
  7.   
  8.     class _LeastCostWeigher(weights.BaseHostWeigher):  
  9.         def weigh_objects(self, weighted_hosts, weight_properties):  
  10.             for host in weighted_hosts:  
  11.                 host.weight = sum(weight * fn(host.obj, weight_properties)  
  12.                             for weight, fn in cost_functions)  
  13.   
  14.     return [_LeastCostWeigher]  
  1. def _get_cost_functions():  
  2.     """ 
  3.     Returns a list of tuples containing weights and cost functions to 
  4.     use for weighing hosts 
  5.     """  
  6.     cost_fns_conf = CONF.least_cost_functions  
  7.     if cost_fns_conf is None:  
  8.         # The old default.  This will get fixed up below.  
  9.         fn_str = 'nova.scheduler.least_cost.compute_fill_first_cost_fn'  
  10.         cost_fns_conf = [fn_str]  
  11.     cost_fns = []  
  12.     for cost_fn_str in cost_fns_conf:  
  13.         short_name = cost_fn_str.split('.')[-1]  
  14.         if not (short_name.startswith('compute_'or  
  15.                 short_name.startswith('noop')):  
  16.             continue  
  17.         # Fix up any old paths to the new paths  
  18.         if cost_fn_str.startswith('nova.scheduler.least_cost.'):  
  19.             cost_fn_str = ('nova.scheduler.weights.least_cost' +  
  20.                        cost_fn_str[25:])  
  21.         try:  
  22.             # NOTE: import_class is somewhat misnamed since  
  23.             # the weighing function can be any non-class callable  
  24.             # (i.e., no 'self')  
  25.             cost_fn = importutils.import_class(cost_fn_str)  
  26.         except ImportError:  
  27.             raise exception.SchedulerCostFunctionNotFound(  
  28.                     cost_fn_str=cost_fn_str)  
  29.   
  30.         try:  
  31.             flag_name = "%s_weight" % cost_fn.__name__  
  32.             weight = getattr(CONF, flag_name)  
  33.         except AttributeError:  
  34.             raise exception.SchedulerWeightFlagNotFound(  
  35.                     flag_name=flag_name)  
  36.         # Set the original default.  
  37.         if (flag_name == 'compute_fill_first_cost_fn_weight' and  
  38.                 weight is None):  
  39.             weight = -1.0  
  40.         cost_fns.append((weight, cost_fn))  
  41.     return cost_fns  
其实,流程是比较简单的,就是过滤和称重的过程的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值