Skip to content

Commit

Permalink
added retry logic to tklbam stsagent command
Browse files Browse the repository at this point in the history
  • Loading branch information
lirazsiri committed Oct 6, 2016
1 parent 204f59d commit d34d79b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
8 changes: 7 additions & 1 deletion cmd_internals/cmd_stsagent.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
import sys
from registry import hub_backups
import hub
from retry import retry

@retry(5, backoff=2)
def get_credentials(hb):
return hb.get_credentials()

def usage(e=None):
if e:
Expand All @@ -31,6 +36,7 @@ def format(creds):
values = [ creds[k] for k in ('accesskey', 'secretkey', 'sessiontoken', 'expiration') ]
return " ".join(values)


def main():
args = sys.argv[1:]
if args:
Expand All @@ -41,7 +47,7 @@ def main():
except hub.Backups.NotInitialized, e:
print >> sys.stderr, "error: " + str(e)

creds = hb.get_credentials()
creds = get_credentials(hb)
if creds.type != 'iamrole':
fatal("STS agent incompatible with '%s' type credentials" % creds.type)

Expand Down
44 changes: 44 additions & 0 deletions retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""
Usage examples:
@retry(3) # will retry 3 times (total 4 attempts), no backoff
@retry(3, backoff=1) # will retry 3 times, increasing delay by 100% each attempt
@retry(3, backoff=2) # will retry 3 times, increasing delay by 200% each attempt
"""
from time import sleep

def retry(retries, delay=1, backoff=0, fatal_exceptions=None):
"""
Argument:
retries how many times to retry if exception is raised
delay how many seconds to delay in case of failure
backoff linear backoff factor (e.g., 0 = no backoff, 1 = 100% step increase)
fatal_exc fatal exceptions are unrecoverable, raised immediately
"""
def decorator(func):

_fatal_exceptions = (SyntaxError, KeyboardInterrupt, SystemExit)
if fatal_exceptions:

if issubclass(fatal_exceptions, Exception):
_fatal_exceptions += (fatal_exceptions,)
else:
_fatal_exceptions += fatal_exceptions

def wrapper(*args, **kwargs):
for attempt in range(retries + 1):
try:
return func(*args, **kwargs)
except _fatal_exceptions:
raise
except:
if attempt < retries and delay:
sleep(delay + delay * attempt * backoff)
else:
raise

return wrapper
return decorator

0 comments on commit d34d79b

Please sign in to comment.