作为个人学习笔记分享,有任何问题欢迎交流!
本文主要分析nova中periodic task的实现过程,周期性任务有如跟踪资源的变化,虚拟机状态的变化等。它的实现使用的python中的metaclass,要了解metaclass可以参考:http://jianpx.iteye.com/blog/908121,该文对metaclass做了较为全面的说明。总而言之,metaclass是一种可以控制类创建过程的机制,实现原理是重写type的__new()__ 或 __init()__函数。此外,还想说的一点就是:metaclass与mixin的区别是,metaclass可以动态的改变类或实例的属性或方法,而mixin只能通过__bases__属性来动态的改变其基类(个人理解)
1 periodic task实现原理
主要实现的代码在/nova/openstack/common/periodic_task.py中文件中,其中包括三个部分:
1.1 def periodic_task(*args, **kwargs)
该函数实现的是一个装饰器,详情可以参考:http://blog.youkuaiyun.com/epugv/article/details/42612261
主要用来说明被装饰的函数需要周期性的执行,如nova/compute/manager.py中:
@periodic_task.periodic_task
def update_available_resource(self, context)
该装饰器有两种使用方法,在注释中已说明:
def periodic_task(*args, **kwargs):
"""Decorator to indicate that a method is a periodic task.
This decorator can be used in two ways:
1. Without arguments '@periodic_task', this will be run on the default
interval of 60 seconds.
2. With arguments:
@periodic_task(spacing=N [, run_immediately=[True|False]])
this will be run on approximately every N seconds. If this number is
negative the periodic task will be disabled. If the run_immediately
argument is provided and has a value of 'True', the first run of the
task will be shortly after task scheduler starts. If
run_immediately is omitted or set to 'False', the first time the
task runs will be approximately N seconds after the task scheduler
starts.
"""
def decorator(f):
# Test for old style invocation
if 'ticks_between_runs' in kwargs:
raise InvalidPeriodicTaskArg(arg='ticks_between_runs')