~ibm-charms/charms/trusty/nova-compute-power/trunk

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/core/decorators.py

  • Committer: james.page at ubuntu
  • Date: 2015-06-17 09:08:47 UTC
  • mfrom: (74.2.46 nova-compute-power)
  • Revision ID: james.page@ubuntu.com-20150617090847-ork7zgglosiiqs7y
Merge updates for OpenStack Kilo release

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2014-2015 Canonical Limited.
 
2
#
 
3
# This file is part of charm-helpers.
 
4
#
 
5
# charm-helpers is free software: you can redistribute it and/or modify
 
6
# it under the terms of the GNU Lesser General Public License version 3 as
 
7
# published by the Free Software Foundation.
 
8
#
 
9
# charm-helpers is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU Lesser General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU Lesser General Public License
 
15
# along with charm-helpers.  If not, see <http://www.gnu.org/licenses/>.
 
16
 
 
17
#
 
18
# Copyright 2014 Canonical Ltd.
 
19
#
 
20
# Authors:
 
21
#  Edward Hope-Morley <opentastic@gmail.com>
 
22
#
 
23
 
 
24
import time
 
25
 
 
26
from charmhelpers.core.hookenv import (
 
27
    log,
 
28
    INFO,
 
29
)
 
30
 
 
31
 
 
32
def retry_on_exception(num_retries, base_delay=0, exc_type=Exception):
 
33
    """If the decorated function raises exception exc_type, allow num_retries
 
34
    retry attempts before raise the exception.
 
35
    """
 
36
    def _retry_on_exception_inner_1(f):
 
37
        def _retry_on_exception_inner_2(*args, **kwargs):
 
38
            retries = num_retries
 
39
            multiplier = 1
 
40
            while True:
 
41
                try:
 
42
                    return f(*args, **kwargs)
 
43
                except exc_type:
 
44
                    if not retries:
 
45
                        raise
 
46
 
 
47
                delay = base_delay * multiplier
 
48
                multiplier += 1
 
49
                log("Retrying '%s' %d more times (delay=%s)" %
 
50
                    (f.__name__, retries, delay), level=INFO)
 
51
                retries -= 1
 
52
                if delay:
 
53
                    time.sleep(delay)
 
54
 
 
55
        return _retry_on_exception_inner_2
 
56
 
 
57
    return _retry_on_exception_inner_1