分享

openstack nova 源码分析3-nova目录下的service.py、driver.py

sstutu 发表于 2014-11-18 14:44:19 [显示全部楼层] 只看大图 回帖奖励 阅读模式 关闭右栏 0 29769
问题导读





1.nova下的service.py的源码主要完成什么任务?
2.driver.py位于哪个目录下?





nova下的service.py的源码,有些地方不好或者是错了,希望大家帮我指出!

  1. import inspect  
  2. import os  
  3. import eventlet  
  4. import greenlet  
  5. from nova import context  
  6. from nova import db  
  7. from nova import exception  
  8. from nova import flags  
  9. from nova import log as logging  
  10. from nova import rpc  
  11. from nova import utils  
  12. from nova import version  
  13. from nova import wsgi  
  14. LOG = logging.getLogger('nova.service')  
  15. FLAGS = flags.FLAGS#flags.py中有一句 FLAGS = FlagValues(),那么直接查看FlagValues()这个类,会发现这个类是继承于gflags.FlagValues.  
  16. flags.DEFINE_integer('report_interval', 10,  
  17.                      'seconds between nodes reporting state to datastore',  
  18.                      lower_bound=1)#参数名称,默认值和简短说明  
  19. flags.DEFINE_integer('periodic_interval', 60,  
  20.                      'seconds between running periodic tasks',  
  21.                      lower_bound=1)  
  22. flags.DEFINE_string('ec2_listen', "0.0.0.0",  
  23.                     'IP address for EC2 API to listen')  
  24. flags.DEFINE_integer('ec2_listen_port', 8773, 'port for ec2 api to listen')  
  25. flags.DEFINE_string('osapi_listen', "0.0.0.0",  
  26.                     'IP address for OpenStack API to listen')  
  27. flags.DEFINE_integer('osapi_listen_port', 8774, 'port for os api to listen')  
  28. flags.DEFINE_string('api_paste_config', "api-paste.ini",  
  29.                     'File name for the paste.deploy config for nova-api')  
  30. #Launcher 类 包含run_server ,launch_server,stop,wait 4个函数,其实功能非常简单,首先初始化Launcher将self_services弄成一个空列表  
  31. #run_server就是开始和等待一个server的完成,launcher_server就是将该server加入到该类初始化的列表中,  
  32. #stop 就是for循环遍历self_services列表中的服务然后一个一个的kill掉  
  33. #wait 函数就是 Waits until all services have been stopped  
  34. class Launcher(object):  
  35.     """Launch one or more services and wait for them to complete."""
  36.     def __init__(self):  
  37.         """Initialize the service launcher.  
  38.         :returns: None  
  39.         """
  40.         self._services = []  
  41.     @staticmethod
  42.     def run_server(server):  
  43.         """Start and wait for a server to finish.  
  44.         :param service: Server to run and wait for.  
  45.         :returns: None  
  46.         """
  47.         server.start()  
  48.         server.wait()  
  49.     def launch_server(self, server):#在360行被调用  
  50.         """Load and start the given server.  
  51.         :param server: The server you would like to start.  
  52.         :returns: None  
  53.         """
  54.         gt = eventlet.spawn(self.run_server, server)  
  55.         self._services.append(gt)  
  56.     def stop(self):  
  57.         """Stop all services which are currently running.  
  58.         :returns: None  
  59.         """
  60.         for service in self._services:  
  61.             service.kill()  
  62.     def wait(self):  
  63.         """Waits until all services have been stopped, and then returns.  
  64.         :returns: None  
  65.         """
  66.         for service in self._services:  
  67.             try:  
  68.                 service.wait()  
  69.             except greenlet.GreenletExit:  
  70.                 pass
  71. class Service(object):  
  72.     """Service object for binaries running on hosts.  
  73.     A service takes a manager and enables rpc by listening to queues based  
  74.     on topic. It also periodically runs tasks on the manager and reports  
  75.     it state to the database services table."""
  76.     def __init__(self, host, binary, topic, manager, report_interval=None,  
  77.                  periodic_interval=None, *args, **kwargs):  
  78.         self.host = host  
  79.         self.binary = binary  
  80.         self.topic = topic  
  81.         #动态的生成manager类,并动态生成实例  
  82.         self.manager_class_name = manager#在create函数中指定  
  83.         manager_class = utils.import_class(self.manager_class_name)#动态的import该类  
  84.         self.manager = manager_class(host=self.host, *args, **kwargs)#动态的生成实例  
  85.         #  设置参数:应该是服务间隔时间之类的。  
  86.         self.report_interval = report_interval  
  87.         self.periodic_interval = periodic_interval  
  88.         #设置多出来的一些参数。  
  89.         super(Service, self).__init__(*args, **kwargs)  
  90.         self.saved_args, self.saved_kwargs = args, kwargs  
  91.         #设置一个列表 不知道是不是后面有需要用的地方 果然在185行 发现了  
  92.         self.timers = []  
  93.     def start(self):  
  94.         #设置版本  
  95.         vcs_string = version.version_string_with_vcs()  
  96.         logging.audit(_('Starting %(topic)s node (version %(vcs_string)s)'),  
  97.                       {'topic': self.topic, 'vcs_string': vcs_string})  
  98.         #初始化host  
  99.         self.manager.init_host()  
  100.          
  101.         self.model_disconnected = False
  102.         ctxt = context.get_admin_context()  
  103.         try:  
  104.             service_ref = db.service_get_by_args(ctxt,  
  105.                                                  self.host,  
  106.                                                  self.binary)  
  107.             self.service_id = service_ref['id']  
  108.         except exception.NotFound:  
  109.             self._create_service_ref(ctxt)#该函数位于187行  
  110.         if 'nova-compute' == self.binary:  
  111.             self.manager.update_available_resource(ctxt)  
  112.         self.conn = rpc.create_connection(new=True)  
  113.         logging.debug("Creating Consumer connection for Service %s" %  
  114.                       self.topic)  
  115.         # Share this same connection for these Consumers  
  116.         self.conn.create_consumer(self.topic, self, fanout=False)  
  117.         node_topic = '%s.%s' % (self.topic, self.host)#节点的topic 包括了topic 和 host  
  118.         self.conn.create_consumer(node_topic, self, fanout=False)  
  119.         self.conn.create_consumer(self.topic, self, fanout=True)  
  120.         # Consume from all consumers in a thread  
  121.         self.conn.consume_in_thread()  
  122.         if self.report_interval:  
  123.             pulse = utils.LoopingCall(self.report_state)#在265中可以找到report_state 他的作用是在存储中更新服务的状态  
  124.             pulse.start(interval=self.report_interval, now=False)  
  125.             self.timers.append(pulse)  
  126.         if self.periodic_interval:  
  127.             periodic = utils.LoopingCall(self.periodic_tasks)#在260行发现 Periodic_tasks任务在一个周期性间隔跑  
  128.             periodic.start(interval=self.periodic_interval, now=False)  
  129.             self.timers.append(periodic)  
  130.     def _create_service_ref(self, context):  
  131.         zone = FLAGS.node_availability_zone  
  132.         service_ref = db.service_create(context,  
  133.                                         {'host': self.host,  
  134.                                          'binary': self.binary,  
  135.                                          'topic': self.topic,  
  136.                                          'report_count': 0,  
  137.                                          'availability_zone': zone})  
  138.         self.service_id = service_ref['id']#猜测应该是获取当前服务的id  
  139.     def __getattr__(self, key):  
  140.         manager = self.__dict__.get('manager', None)  
  141.         return getattr(manager, key)  
  142.     @classmethod
  143.     def create(cls, host=None, binary=None, topic=None, manager=None,  
  144.                report_interval=None, periodic_interval=None):  
  145.         """Instantiates class and passes back application object.  
  146.         :param host: defaults to FLAGS.host  
  147.         :param binary: defaults to basename of executable  
  148.         :param topic: defaults to bin_name - 'nova-' part  
  149.         :param manager: defaults to FLAGS.<topic>_manager  
  150.         :param report_interval: defaults to FLAGS.report_interval  
  151.         :param periodic_interval: defaults to FLAGS.periodic_interval  
  152.         """
  153.         if not host:  
  154.             host = FLAGS.host  
  155.         if not binary:  
  156.             binary = os.path.basename(inspect.stack()[-1][1])  
  157.         if not topic:  
  158.             topic = binary.rpartition('nova-')[2]  
  159.         if not manager:  
  160.             manager = FLAGS.get('%s_manager' % topic, None)  
  161.         if not report_interval:  
  162.             report_interval = FLAGS.report_interval  
  163.         if not periodic_interval:  
  164.             periodic_interval = FLAGS.periodic_interval  
  165.         service_obj = cls(host, binary, topic, manager,  
  166.                           report_interval, periodic_interval)#此处 调用的是该类的init的默认函数      
  167.         return service_obj  
  168.     def kill(self):  
  169.         """Destroy the service object in the datastore."""
  170.         self.stop()  
  171.         try:  
  172.             db.service_destroy(context.get_admin_context(), self.service_id)  
  173.         except exception.NotFound:  
  174.             logging.warn(_('Service killed that has no database entry'))  
  175.     def stop(self):  
  176.         # Try to shut the connection down, but if we get any sort of  
  177.         # errors, go ahead and ignore them.. as we're shutting down anyway  
  178.         try:  
  179.             self.conn.close()  
  180.         except Exception:  
  181.             pass
  182.         for x in self.timers:   #遍历曾经添加到self.timers中的每一个“间隔”(不是很清楚) 然后将其stop  
  183.             try:  
  184.                 x.stop()  
  185.             except Exception:  
  186.                 pass
  187.         self.timers = [] #重新将self.timers置空  
  188.     def wait(self):  
  189.         for x in self.timers:  
  190.             try:  
  191.                 x.wait()  
  192.             except Exception:  
  193.                 pass
  194.     def periodic_tasks(self):  
  195.         """Tasks to be run at a periodic interval."""
  196.         #任务在一个周期性间隔跑  
  197.         self.manager.periodic_tasks(context.get_admin_context())  
  198.     def report_state(self):  
  199.         """Update the state of this service in the datastore."""
  200.         #在数据存储更新服务的状态。  
  201.         ctxt = context.get_admin_context()  
  202.         try:  
  203.             try:  
  204.                 service_ref = db.service_get(ctxt, self.service_id)  
  205.             except exception.NotFound:  
  206.                 logging.debug(_('The service database object disappeared, '
  207.                                 'Recreating it.'))  
  208.                 self._create_service_ref(ctxt)  
  209.                 service_ref = db.service_get(ctxt, self.service_id)  
  210.             db.service_update(ctxt,  
  211.                              self.service_id,  
  212.                              {'report_count': service_ref['report_count'] + 1})  
  213.             # TODO(termie): make this pattern be more elegant.  
  214.             if getattr(self, 'model_disconnected', False):  
  215.                 self.model_disconnected = False
  216.                 logging.error(_('Recovered model server connection!'))  
  217.         # TODO(vish): this should probably only catch connection errors  
  218.         except Exception:  # pylint: disable=W0702  
  219.             if not getattr(self, 'model_disconnected', False):  
  220.                 self.model_disconnected = True
  221.                 logging.exception(_('model server went away'))  
  222. class WSGIService(object):  
  223.     """Provides ability to launch API from a 'paste' configuration."""
  224.     #提供能够从一个‘paste’配置启动api的服务  
  225.     def __init__(self, name, loader=None):  
  226.         """Initialize, but do not start the WSGI server.  
  227.         :param name: The name of the WSGI server given to the loader.  
  228.         :param loader: Loads the WSGI application using the given name.  
  229.         :returns: None  
  230.         """
  231.         #初始化 但是并没有开是wsgi的服务。  
  232.         self.name = name  
  233.         self.loader = loader or wsgi.Loader()  
  234.         self.app = self.loader.load_app(name)#将wsgi服务的名字给到self.loader,然后用那名字将其 装载到wsgi application  
  235.         self.host = getattr(FLAGS, '%s_listen' % name, "0.0.0.0") #返回主机host getattr Found at: __builtin__  
  236.         #getattr(object, name[, default]) -> value得知返回的是value  
  237.         self.port = getattr(FLAGS, '%s_listen_port' % name, 0)#端口 port  
  238.         self.server = wsgi.Server(name,  
  239.                                   self.app,  
  240.                                   host=self.host,  
  241.                                   port=self.port)  
  242.     def start(self):  
  243.         """Start serving this service using loaded configuration.  
  244.         Also, retrieve updated port number in case '0' was passed in, which  
  245.         indicates a random port should be used.  
  246.         :returns: None  
  247.         """
  248.         self.server.start()  
  249.         self.port = self.server.port  
  250.     def stop(self):  
  251.         """Stop serving this API.  
  252.         :returns: None  
  253.         """
  254.         self.server.stop()  
  255.     def wait(self):  
  256.         """Wait for the service to stop serving this API.  
  257.         :returns: None  
  258.         """
  259.         self.server.wait()  
  260. # NOTE(vish): the global launcher is to maintain the existing  
  261. #             functionality of calling service.serve +  
  262. #             service.wait  
  263. _launcher = None
  264. def serve(*servers):  
  265.     global _launcher  
  266.     if not _launcher:  
  267.         _launcher = Launcher() #s实例化Launcher  
  268.     for server in servers:  
  269.         _launcher.launch_server(server)  
  270. def wait():  
  271.     # After we've loaded up all our dynamic bits, check  
  272.     # whether we should print help  
  273.       
  274.     #flags.py中 有一句  
  275.     #FLAGS = FlagValues(),那么直接查看FlagValues()这个类,这个类是继承于gflags.FlagValues.  
  276.     flags.DEFINE_flag(flags.HelpFlag())  
  277.     flags.DEFINE_flag(flags.HelpshortFlag())  
  278.     flags.DEFINE_flag(flags.HelpXMLFlag())  
  279.     FLAGS.ParseNewFlags()  
  280.     logging.debug(_('Full set of FLAGS:'))  
  281.     for flag in FLAGS:  
  282.         flag_get = FLAGS.get(flag, None)  
  283.         logging.debug('%(flag)s : %(flag_get)s' % locals())  
  284.     try:  
  285.         _launcher.wait()  
  286.     except KeyboardInterrupt:  
  287.         _launcher.stop()  
复制代码






这个文件位于\nova\virt,是一个底层的driver.py,源代码如下(我 觉得比较重要的computerDriver类列出来 了,并将下面的每个函数分离 加以注释《见下面图片》!我看见后面好多函数都是继承的ComputerDriver比如nova\virt\libvirt下面的connection.py里面的class LibvirtConnection(driver.ComputeDriver):):

  1. """  
  2. Driver base-classes:  
  3.     (Beginning of) the contract that compute drivers must follow, and shared  
  4.     types that support that contract  
  5. """
  6. from nova.compute import power_state  
  7. class InstanceInfo(object):  
  8.     def __init__(self, name, state):  
  9.         self.name = name  
  10.         assert state in power_state.valid_states(), "Bad state: %s" % state  
  11.         self.state = state  
  12. def block_device_info_get_root(block_device_info):  
  13.     block_device_info = block_device_info or {}  
  14.     return block_device_info.get('root_device_name')  
  15. def block_device_info_get_swap(block_device_info):  
  16.     block_device_info = block_device_info or {}  
  17.     return block_device_info.get('swap') or {'device_name': None,  
  18.                                              'swap_size': 0}  
  19. def swap_is_usable(swap):  
  20.     return swap and swap['device_name'] and swap['swap_size'] > 0
  21. def block_device_info_get_ephemerals(block_device_info):  
  22.     block_device_info = block_device_info or {}  
  23.     ephemerals = block_device_info.get('ephemerals') or []  
  24.     return ephemerals  
  25. def block_device_info_get_mapping(block_device_info):  
  26.     block_device_info = block_device_info or {}  
  27.     block_device_mapping = block_device_info.get('block_device_mapping') or []  
  28.     return block_device_mapping  
  29. class ComputeDriver(object):  
  30.     """Base class for compute drivers.  
  31.     The interface to this class talks in terms of 'instances' (Amazon EC2 and  
  32.     internal Nova terminology), by which we mean 'running virtual machine'  
  33.     (XenAPI terminology) or domain (Xen or libvirt terminology).  
  34.     An instance has an ID, which is the identifier chosen by Nova to represent  
  35.     the instance further up the stack.  This is unfortunately also called a  
  36.     'name' elsewhere.  As far as this layer is concerned, 'instance ID' and  
  37.     'instance name' are synonyms.  
  38.     Note that the instance ID or name is not human-readable or  
  39.     customer-controlled -- it's an internal ID chosen by Nova.  At the  
  40.     nova.virt layer, instances do not have human-readable names at all -- such  
  41.     things are only known higher up the stack.  
  42.     Most virtualization platforms will also have their own identity schemes,  
  43.     to uniquely identify a VM or domain.  These IDs must stay internal to the  
  44.     platform-specific layer, and never escape the connection interface.  The  
  45.     platform-specific layer is responsible for keeping track of which instance  
  46.     ID maps to which platform-specific ID, and vice versa.  
  47.     In contrast, the list_disks and list_interfaces calls may return  
  48.     platform-specific IDs.  These identify a specific virtual disk or specific  
  49.     virtual network interface, and these IDs are opaque to the rest of Nova.  
  50.     Some methods here take an instance of nova.compute.service.Instance.  This  
  51.     is the datastructure used by nova.compute to store details regarding an  
  52.     instance, and pass them into this layer.  This layer is responsible for  
  53.     translating that generic datastructure into terms that are specific to the  
  54.     virtualization platform.  
  55.     """
  56.     #此处为了让大家看的明白 将 ComputerDriver的类图 列出来  
  57.     def init_host(self, host):  
  58.         """Initialize anything that is necessary for the driver to function,  
  59.         including catching up with currently running VM's on the given host."""
  60.         # TODO(Vek): Need to pass context in for access to auth_token  
  61.         raise NotImplementedError()  
  62.     def get_info(self, instance_name):  
  63.         """Get the current status of an instance, by name (not ID!)  
  64.         Returns a dict containing:  
  65.         :state:           the running state, one of the power_state codes  
  66.         :max_mem:         (int) the maximum memory in KBytes allowed  
  67.         :mem:             (int) the memory in KBytes used by the domain  
  68.         :num_cpu:         (int) the number of virtual CPUs for the domain  
  69.         :cpu_time:        (int) the CPU time used in nanoseconds  
  70.         """
  71.         # TODO(Vek): Need to pass context in for access to auth_token  
  72.         raise NotImplementedError()  
  73.     def list_instances(self):  
  74.         """  
  75.         Return the names of all the instances known to the virtualization  
  76.         layer, as a list.  
  77.         """
  78.         # TODO(Vek): Need to pass context in for access to auth_token  
  79.         raise NotImplementedError()  
  80.     def list_instances_detail(self):  
  81.         """Return a list of InstanceInfo for all registered VMs"""
  82.         # TODO(Vek): Need to pass context in for access to auth_token  
  83.         raise NotImplementedError()  
  84.     def spawn(self, context, instance,  
  85.               network_info=None, block_device_info=None):  
  86.         """  
  87.         Create a new instance/VM/domain on the virtualization platform.  
  88.         Once this successfully completes, the instance should be  
  89.         running (power_state.RUNNING).  
  90.         If this fails, any partial instance should be completely  
  91.         cleaned up, and the virtualization platform should be in the state  
  92.         that it was before this call began.  
  93.         :param context: security context  
  94.         :param instance: Instance object as returned by DB layer.  
  95.                          This function should use the data there to guide  
  96.                          the creation of the new instance.  
  97.         :param network_info:  
  98.            :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`  
  99.         :param block_device_info:  
  100.         """
  101.         raise NotImplementedError()  
  102.     def destroy(self, instance, network_info, cleanup=True):  
  103.         """Destroy (shutdown and delete) the specified instance.  
  104.         If the instance is not found (for example if networking failed), this  
  105.         function should still succeed.  It's probably a good idea to log a  
  106.         warning in that case.  
  107.         :param instance: Instance object as returned by DB layer.  
  108.         :param network_info:  
  109.            :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`  
  110.         :param cleanup:  
  111.         """
  112.         # TODO(Vek): Need to pass context in for access to auth_token  
  113.         raise NotImplementedError()  
  114.     def reboot(self, instance, network_info):  
  115.         """Reboot the specified instance.  
  116.         :param instance: Instance object as returned by DB layer.  
  117.         :param network_info:  
  118.            :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`  
  119.         """
  120.         # TODO(Vek): Need to pass context in for access to auth_token  
  121.         raise NotImplementedError()  
  122.     def snapshot_instance(self, context, instance_id, image_id):  
  123.         raise NotImplementedError()  
  124.     def get_console_pool_info(self, console_type):  
  125.         # TODO(Vek): Need to pass context in for access to auth_token  
  126.         raise NotImplementedError()  
  127.     def get_console_output(self, instance):  
  128.         # TODO(Vek): Need to pass context in for access to auth_token  
  129.         raise NotImplementedError()  
  130.     def get_ajax_console(self, instance):  
  131.         # TODO(Vek): Need to pass context in for access to auth_token  
  132.         raise NotImplementedError()  
  133.     def get_diagnostics(self, instance):  
  134.         """Return data about VM diagnostics"""
  135.         # TODO(Vek): Need to pass context in for access to auth_token  
  136.         raise NotImplementedError()  
  137.     def get_host_ip_addr(self):  
  138.         """  
  139.         Retrieves the IP address of the dom0  
  140.         """
  141.         # TODO(Vek): Need to pass context in for access to auth_token  
  142.         raise NotImplementedError()  
  143.     def attach_volume(self, context, instance_id, volume_id, mountpoint):  
  144.         """Attach the disk at device_path to the instance at mountpoint"""
  145.         raise NotImplementedError()  
  146.     def detach_volume(self, context, instance_id, volume_id):  
  147.         """Detach the disk attached to the instance at mountpoint"""
  148.         raise NotImplementedError()  
  149.     def compare_cpu(self, cpu_info):  
  150.         """Compares given cpu info against host 确保vm能运行  
  151.         Before attempting to migrate a VM to this host,  
  152.         compare_cpu is called to ensure that the VM will  
  153.         actually run here.  
  154.         :param cpu_info: (str) JSON structure describing the source CPU.  
  155.         :returns: None if migration is acceptable  
  156.         :raises: :py:class:`~nova.exception.InvalidCPUInfo` if migration  
  157.                  is not acceptable.  
  158.         """
  159.         raise NotImplementedError()  
  160.     def migrate_disk_and_power_off(self, instance, dest):  
  161.         """  
  162.         Transfers the disk of a running instance in multiple phases, turning  
  163.         off the instance before the end.  
  164.         """
  165.         # TODO(Vek): Need to pass context in for access to auth_token  
  166.         raise NotImplementedError()  
  167.     def snapshot(self, context, instance, image_id):  
  168.         """  
  169.         Snapshots the specified instance.  
  170.         :param context: security context  
  171.         :param instance: Instance object as returned by DB layer.  
  172.         :param image_id: Reference to a pre-created image that will  
  173.                          hold the snapshot.  
  174.         """
  175.         raise NotImplementedError()  
  176.     def finish_migration(self, context, instance, disk_info, network_info,  
  177.                          resize_instance):  
  178.         #打开一个迁移的实例,完成一个调整  
  179.         """Completes a resize, turning on the migrated instance  
  180.         :param network_info:  
  181.            :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`  
  182.         """
  183.         raise NotImplementedError()  
  184.     def revert_migration(self, instance):  
  185.         #返回一个调整,推动回到实例?  
  186.         """Reverts a resize, powering back on the instance"""
  187.         # TODO(Vek): Need to pass context in for access to auth_token  
  188.         raise NotImplementedError()  
  189.     def pause(self, instance, callback):  
  190.         """Pause the specified instance."""
  191.         # TODO(Vek): Need to pass context in for access to auth_token  
  192.         raise NotImplementedError()  
  193.     def unpause(self, instance, callback):  
  194.         """Unpause paused VM instance"""
  195.         # TODO(Vek): Need to pass context in for access to auth_token  
  196.         raise NotImplementedError()  
  197.     def suspend(self, instance, callback):  
  198.         # 挂起指定的实例  
  199.         """suspend the specified instance"""
  200.         # TODO(Vek): Need to pass context in for access to auth_token  
  201.         raise NotImplementedError()  
  202.     def resume(self, instance, callback):  
  203.         """resume the specified instance"""
  204.         # TODO(Vek): Need to pass context in for access to auth_token  
  205.         raise NotImplementedError()  
  206.     def rescue(self, context, instance, callback, network_info):  
  207.         #恢复指定的实例  
  208.         """Rescue the specified instance"""
  209.         raise NotImplementedError()  
  210.     def unrescue(self, instance, callback, network_info):  
  211.         """Unrescue the specified instance"""
  212.         # TODO(Vek): Need to pass context in for access to auth_token  
  213.         raise NotImplementedError()  
  214.     def update_available_resource(self, ctxt, host):  
  215.         #在computeNode表中更新电脑资源管理的信息  
  216.         """Updates compute manager resource info on ComputeNode table.  
  217.         This method is called when nova-compute launches, and  
  218.         whenever admin executes "nova-manage service update_resource".  
  219.         :param ctxt: security context  
  220.         :param host: hostname that compute manager is currently running  
  221.         """
  222.         # TODO(Vek): Need to pass context in for access to auth_token  
  223.         raise NotImplementedError()  
  224.     def live_migration(self, ctxt, instance_ref, dest,  
  225.                        post_method, recover_method):  
  226.         #分发处理高负荷,当有高负荷操作时候,大量生成 live_mirgration  
  227.         """Spawning live_migration operation for distributing high-load.  
  228.         :param ctxt: security context  
  229.         :param instance_ref:  
  230.             nova.db.sqlalchemy.models.Instance object  
  231.             instance object that is migrated.  
  232.         :param dest: destination host  
  233.         :param post_method:  
  234.             post operation method.  
  235.             expected nova.compute.manager.post_live_migration.  
  236.         :param recover_method:  
  237.             recovery method when any exception occurs.  
  238.             expected nova.compute.manager.recover_live_migration.  
  239.         """
  240.         # TODO(Vek): Need to pass context in for access to auth_token  
  241.         raise NotImplementedError()  
  242.     def refresh_security_group_rules(self, security_group_id):  
  243.         #改变安全组之后调用  
  244.         """This method is called after a change to security groups.  
  245.         All security groups and their associated rules live in the datastore,  
  246.         and calling this method should apply the updated rules to instances  
  247.         running the specified security group.  
  248.         An error should be raised if the operation cannot complete.  
  249.         """
  250.         # TODO(Vek): Need to pass context in for access to auth_token  
  251.         raise NotImplementedError()  
  252.     def refresh_security_group_members(self, security_group_id):  
  253.         #当一个安全组被添加到一个实例,这个方法被调用  
  254.         """This method is called when a security group is added to an instance.  
  255.         This message is sent to the virtualization drivers on hosts that are  
  256.         running an instance that belongs to a security group that has a rule  
  257.         that references the security group identified by `security_group_id`.  
  258.         It is the responsiblity of this method to make sure any rules  
  259.         that authorize traffic flow with members of the security group are  
  260.         updated and any new members can communicate, and any removed members  
  261.         cannot.  
  262.         Scenario:  
  263.             * we are running on host 'H0' and we have an instance 'i-0'.  
  264.             * instance 'i-0' is a member of security group 'speaks-b'  
  265.             * group 'speaks-b' has an ingress rule that authorizes group 'b'  
  266.             * another host 'H1' runs an instance 'i-1'  
  267.             * instance 'i-1' is a member of security group 'b'  
  268.             When 'i-1' launches or terminates we will recieve the message  
  269.             to update members of group 'b', at which time we will make  
  270.             any changes needed to the rules for instance 'i-0' to allow  
  271.             or deny traffic coming from 'i-1', depending on if it is being  
  272.             added or removed from the group.  
  273.         In this scenario, 'i-1' could just as easily have been running on our  
  274.         host 'H0' and this method would still have been called.  The point was  
  275.         that this method isn't called on the host where instances of that  
  276.         group are running (as is the case with  
  277.         :method:`refresh_security_group_rules`) but is called where references  
  278.         are made to authorizing those instances.  
  279.         An error should be raised if the operation cannot complete.  
  280.         """
  281.         # TODO(Vek): Need to pass context in for access to auth_token  
  282.         raise NotImplementedError()  
  283.     def refresh_provider_fw_rules(self, security_group_id):  
  284.         #这触发一个基于数据库改变的防火墙的更新  
  285.         """This triggers a firewall update based on database changes.  
  286.         When this is called, rules have either been added or removed from the  
  287.         datastore.  You can retrieve rules with  
  288.         :method:`nova.db.api.provider_fw_rule_get_all`.  
  289.         Provider rules take precedence over security group rules.  If an IP  
  290.         would be allowed by a security group ingress rule, but blocked by  
  291.         a provider rule, then packets from the IP are dropped.  This includes  
  292.         intra-project traffic in the case of the allow_project_net_traffic  
  293.         flag for the libvirt-derived classes.  
  294.         """
  295.         # TODO(Vek): Need to pass context in for access to auth_token  
  296.         raise NotImplementedError()  
  297.     def reset_network(self, instance):  
  298.         """reset networking for specified instance"""
  299.         # TODO(Vek): Need to pass context in for access to auth_token  
  300.         pass
  301.     def ensure_filtering_rules_for_instance(self, instance_ref, network_info):  
  302.         #设置过滤规则,并等待它完成  
  303.         """Setting up filtering rules and waiting for its completion.  
  304.         To migrate an instance, filtering rules to hypervisors  
  305.         and firewalls are inevitable on destination host.  
  306.         ( Waiting only for filtering rules to hypervisor,  
  307.         since filtering rules to firewall rules can be set faster).  
  308.         Concretely, the below method must be called.  
  309.         - setup_basic_filtering (for nova-basic, etc.)  
  310.         - prepare_instance_filter(for nova-instance-instance-xxx, etc.)  
  311.         to_xml may have to be called since it defines PROJNET, PROJMASK.  
  312.         but libvirt migrates those value through migrateToURI(),  
  313.         so , no need to be called.  
  314.         Don't use thread for this method since migration should  
  315.         not be started when setting-up filtering rules operations  
  316.         are not completed.  
  317.         :params instance_ref: nova.db.sqlalchemy.models.Instance object  
  318.         """
  319.         # TODO(Vek): Need to pass context in for access to auth_token  
  320.         raise NotImplementedError()  
  321.     def unfilter_instance(self, instance, network_info):  
  322.         """Stop filtering instance"""
  323.         # TODO(Vek): Need to pass context in for access to auth_token  
  324.         raise NotImplementedError()  
  325.     def set_admin_password(self, context, instance_id, new_pass=None):  
  326.         """  
  327.         Set the root password on the specified instance.  
  328.         The first parameter is an instance of nova.compute.service.Instance,  
  329.         and so the instance is being specified as instance.name. The second  
  330.         parameter is the value of the new password.  
  331.         """
  332.         raise NotImplementedError()  
  333.     def inject_file(self, instance, b64_path, b64_contents):  
  334.         """在指定的实例上写文件  
  335.         Writes a file on the specified instance.  
  336.         The first parameter is an instance of nova.compute.service.Instance,  
  337.         and so the instance is being specified as instance.name. The second  
  338.         parameter is the base64-encoded path to which the file is to be  
  339.         written on the instance; the third is the contents of the file, also  
  340.         base64-encoded.  
  341.         """
  342.         # TODO(Vek): Need to pass context in for access to auth_token  
  343.         raise NotImplementedError()  
  344.     def agent_update(self, instance, url, md5hash):  
  345.         #在指定的实例中更新代理  
  346.         """  
  347.         Update agent on the specified instance.  
  348.         The first parameter is an instance of nova.compute.service.Instance,  
  349.         and so the instance is being specified as instance.name. The second  
  350.         parameter is the URL of the agent to be fetched and updated on the  
  351.         instance; the third is the md5 hash of the file for verification  
  352.         purposes.  
  353.         """
  354.         # TODO(Vek): Need to pass context in for access to auth_token  
  355.         raise NotImplementedError()  
  356.     def inject_network_info(self, instance, nw_info):  
  357.         #为指定的实例注入网络信息  
  358.         """inject network info for specified instance"""
  359.         # TODO(Vek): Need to pass context in for access to auth_token  
  360.         pass
  361.     def poll_rescued_instances(self, timeout):  
  362.         #轮询已经恢复的实例  
  363.         """Poll for rescued instances"""
  364.         # TODO(Vek): Need to pass context in for access to auth_token  
  365.         raise NotImplementedError()  
  366.     def host_power_action(self, host, action):  
  367.         """Reboots, shuts down or powers up the host."""
  368.         raise NotImplementedError()  
  369.     def set_host_enabled(self, host, enabled):  
  370.         #设置指定的主机有能力接受新的实例  
  371.         """Sets the specified host's ability to accept new instances."""
  372.         # TODO(Vek): Need to pass context in for access to auth_token  
  373.         raise NotImplementedError()  
  374.     def plug_vifs(self, instance, network_info):  
  375.         """Plugs in VIFs to networks."""
  376.         # TODO(Vek): Need to pass context in for access to auth_token  
  377.         raise NotImplementedError()  
  378.     def update_host_status(self):  
  379.         """Refresh host stats"""
  380.         raise NotImplementedError()  
  381.     def get_host_stats(self, refresh=False):  
  382.         """Return currently known host stats"""
  383.         raise NotImplementedError()  
  384.     def list_disks(self, instance_name):  
  385.         """  
  386.         Return the IDs of all the virtual disks attached to the specified  
  387.         instance, as a list.  These IDs are opaque to the caller (they are  
  388.         only useful for giving back to this layer as a parameter to  
  389.         disk_stats).  These IDs only need to be unique for a given instance.  
  390.         Note that this function takes an instance ID.  
  391.         """
  392.         raise NotImplementedError()  
  393.     def list_interfaces(self, instance_name):  
  394.         """  
  395.         Return the IDs of all the virtual network interfaces attached to the  
  396.         specified instance, as a list.  These IDs are opaque to the caller  
  397.         (they are only useful for giving back to this layer as a parameter to  
  398.         interface_stats).  These IDs only need to be unique for a given  
  399.         instance.  
  400.         Note that this function takes an instance ID.  
  401.         """
  402.         raise NotImplementedError()  
  403.     def resize(self, instance, flavor):  
  404.         """  
  405.         Resizes/Migrates the specified instance.  
  406.         The flavor parameter determines whether or not the instance RAM and  
  407.         disk space are modified, and if so, to what size.  
  408.         """
  409.         raise NotImplementedError()  
  410.     def block_stats(self, instance_name, disk_id):  
  411.         """  
  412.         Return performance counters associated with the given disk_id on the  
  413.         given instance_name.  These are returned as [rd_req, rd_bytes, wr_req,  
  414.         wr_bytes, errs], where rd indicates read, wr indicates write, req is  
  415.         the total number of I/O requests made, bytes is the total number of  
  416.         bytes transferred, and errs is the number of requests held up due to a  
  417.         full pipeline.  
  418.         All counters are long integers.  
  419.         This method is optional.  On some platforms (e.g. XenAPI) performance  
  420.         statistics can be retrieved directly in aggregate form, without Nova  
  421.         having to do the aggregation.  On those platforms, this method is  
  422.         unused.  
  423.         Note that this function takes an instance ID.  
  424.         """
  425.         raise NotImplementedError()  
  426.     def interface_stats(self, instance_name, iface_id):  
  427.         """  
  428.         Return performance counters associated with the given iface_id on the  
  429.         given instance_id.  These are returned as [rx_bytes, rx_packets,  
  430.         rx_errs, rx_drop, tx_bytes, tx_packets, tx_errs, tx_drop], where rx  
  431.         indicates receive, tx indicates transmit, bytes and packets indicate  
  432.         the total num
  433. ber of bytes or packets transferred, and errs and dropped  
  434.         is the total number of packets failed / dropped.  
  435.         All counters are long integers.  
  436.         This method is optional.  On some platforms (e.g. XenAPI) performance  
  437.         statistics can be retrieved directly in aggregate form, without Nova  
  438.         having to do the aggregation.  On those platforms, this method is  
  439.         unused.  
  440.         Note that this function takes an instance ID.  
  441.         """
  442.         raise NotImplementedError()  
复制代码



1.png

2.png

3.png

4.png





相关内容:

openstack nova 源码分析1-setup脚本
http://www.aboutyun.com/thread-10090-1-1.html


openstack nova 源码分析2之nova-api,nova-compute
http://www.aboutyun.com/thread-10091-1-1.html




openstack nova 源码分析4-1 -nova/virt/libvirt目录下的connection.py
http://www.aboutyun.com/thread-10094-1-1.html


openstack nova 源码分析4-2 -nova/virt/libvirt目录下的connection.py
http://www.aboutyun.com/thread-10095-1-1.html








没找到任何评论,期待你打破沉寂

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条