1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
5
# not use this file except in compliance with the License. You may obtain
6
# a copy of the License at
8
# http://www.apache.org/licenses/LICENSE-2.0
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
# License for the specific language governing permissions and limitations
16
from quantum.openstack.common.gettextutils import _
17
from quantum.openstack.common import log as logging
19
LOG = logging.getLogger(__name__)
22
def periodic_task(*args, **kwargs):
23
"""Decorator to indicate that a method is a periodic task.
25
This decorator can be used in two ways:
27
1. Without arguments '@periodic_task', this will be run on every tick
28
of the periodic scheduler.
30
2. With arguments, @periodic_task(ticks_between_runs=N), this will be
31
run on every N ticks of the periodic scheduler.
34
f._periodic_task = True
35
f._ticks_between_runs = kwargs.pop('ticks_between_runs', 0)
38
# NOTE(sirp): The `if` is necessary to allow the decorator to be used with
41
# In the 'with-parens' case (with kwargs present), this function needs to
42
# return a decorator function since the interpreter will invoke it like:
44
# periodic_task(*args, **kwargs)(f)
46
# In the 'without-parens' case, the original function will be passed
47
# in as the first argument, like:
53
return decorator(args[0])
56
class _PeriodicTasksMeta(type):
57
def __init__(cls, names, bases, dict_):
58
"""Metaclass that allows us to collect decorated periodic tasks."""
59
super(_PeriodicTasksMeta, cls).__init__(names, bases, dict_)
61
# NOTE(sirp): if the attribute is not present then we must be the base
62
# class, so, go ahead and initialize it. If the attribute is present,
63
# then we're a subclass so make a copy of it so we don't step on our
66
cls._periodic_tasks = cls._periodic_tasks[:]
67
except AttributeError:
68
cls._periodic_tasks = []
71
cls._ticks_to_skip = cls._ticks_to_skip.copy()
72
except AttributeError:
73
cls._ticks_to_skip = {}
75
# This uses __dict__ instead of
76
# inspect.getmembers(cls, inspect.ismethod) so only the methods of the
77
# current class are added when this class is scanned, and base classes
78
# are not added redundantly.
79
for value in cls.__dict__.values():
80
if getattr(value, '_periodic_task', False):
83
cls._periodic_tasks.append((name, task))
84
cls._ticks_to_skip[name] = task._ticks_between_runs
87
class PeriodicTasks(object):
88
__metaclass__ = _PeriodicTasksMeta
90
def run_periodic_tasks(self, context, raise_on_error=False):
91
"""Tasks to be run at a periodic interval."""
92
for task_name, task in self._periodic_tasks:
93
full_task_name = '.'.join([self.__class__.__name__, task_name])
95
ticks_to_skip = self._ticks_to_skip[task_name]
97
LOG.debug(_("Skipping %(full_task_name)s, %(ticks_to_skip)s"
98
" ticks left until next run"), locals())
99
self._ticks_to_skip[task_name] -= 1
102
self._ticks_to_skip[task_name] = task._ticks_between_runs
103
LOG.debug(_("Running periodic task %(full_task_name)s"), locals())
107
except Exception as e:
110
LOG.exception(_("Error during %(full_task_name)s: %(e)s"),