Try to call f(*args, **kwargs) "n" times before giving up. Wait
    2**n seconds before retries.

def _retry(n, f, *args, **kwargs):
    '''Try to call f(*args, **kwargs) "n" times before giving up. Wait
    2**n seconds before retries.'''

    for i in range(n):
        try:
            return f(*args, **kwargs)
        except Exception as exc:
            if i == n - 1:
                log.error(
                    '%s permanently failed with %r', f.__name__, exc)
                raise
            else:
                log.warning(
                    '%s attempt #%d failed with %r', f.__name__, i, exc)
                time.sleep(2 ** i)
    raise RuntimeError('Should never get here!')