-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathutils.py
171 lines (127 loc) · 4.33 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import argparse
import collections
import datetime
import functools
import json
import time
import dateutil
import pytz
import backoff as backoff_module
from singer.catalog import Catalog
DATETIME_PARSE = "%Y-%m-%dT%H:%M:%SZ"
DATETIME_FMT = "%Y-%m-%dT%H:%M:%S.%fZ"
def now():
return datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
def strptime_with_tz(dtime):
d_object = dateutil.parser.parse(dtime)
if d_object.tzinfo is None:
return d_object.replace(tzinfo=pytz.UTC)
return d_object
def strptime(dtime):
try:
return datetime.datetime.strptime(dtime, DATETIME_FMT)
except Exception:
return datetime.datetime.strptime(dtime, DATETIME_PARSE)
def strftime(dtime, format_str=DATETIME_FMT):
if dtime.utcoffset() != datetime.timedelta(0):
raise Exception("datetime must be pegged at UTC tzoneinfo")
return dtime.strftime(format_str)
def ratelimit(limit, every):
def limitdecorator(func):
times = collections.deque()
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(times) >= limit:
tim0 = times.pop()
tim = time.time()
sleep_time = every - (tim - tim0)
if sleep_time > 0:
time.sleep(sleep_time)
times.appendleft(time.time())
return func(*args, **kwargs)
return wrapper
return limitdecorator
def chunk(array, num):
for i in range(0, len(array), num):
yield array[i:i + num]
def load_json(path):
with open(path) as fil:
return json.load(fil)
def update_state(state, entity, dtime):
if dtime is None:
return
if isinstance(dtime, datetime.datetime):
dtime = strftime(dtime)
if entity not in state:
state[entity] = dtime
if dtime >= state[entity]:
state[entity] = dtime
def parse_args(required_config_keys):
'''Parse standard command-line args.
Parses the command-line arguments mentioned in the SPEC and the
BEST_PRACTICES documents:
-c,--config Config file
-s,--state State file
-d,--discover Run in discover mode
-p,--properties Properties file: DEPRECATED, please use --catalog instead
--catalog Catalog file
Returns the parsed args object from argparse. For each argument that
point to JSON files (config, state, properties), we will automatically
load and parse the JSON file.
'''
parser = argparse.ArgumentParser()
parser.add_argument(
'-c', '--config',
help='Config file',
required=True)
parser.add_argument(
'-s', '--state',
help='State file')
parser.add_argument(
'-p', '--properties',
help='Property selections: DEPRECATED, Please use --catalog instead')
parser.add_argument(
'--catalog',
help='Catalog file')
parser.add_argument(
'-d', '--discover',
action='store_true',
help='Do schema discovery')
args = parser.parse_args()
if args.config:
args.config = load_json(args.config)
if args.state:
args.state = load_json(args.state)
else:
args.state = {}
if args.properties:
args.properties = load_json(args.properties)
if args.catalog:
args.catalog = Catalog.load(args.catalog)
check_config(args.config, required_config_keys)
return args
def check_config(config, required_keys):
missing_keys = [key for key in required_keys if key not in config]
if missing_keys:
raise Exception("Config is missing required keys: {}".format(missing_keys))
def backoff(exceptions, giveup):
"""Decorates a function to retry up to 5 times using an exponential backoff
function.
exceptions is a tuple of exception classes that are retried
giveup is a function that accepts the exception and returns True to retry
"""
return backoff_module.on_exception(
backoff_module.expo,
exceptions,
max_tries=5,
giveup=giveup,
factor=2)
def exception_is_4xx(exception):
"""Returns True if exception is in the 4xx range."""
if not hasattr(exception, "response"):
return False
if exception.response is None:
return False
if not hasattr(exception.response, "status_code"):
return False
return 400 <= exception.response.status_code < 500