mageml-singer-python 5.13.0.post3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mageml_singer_python-5.13.0.post3.dist-info/METADATA +14 -0
- mageml_singer_python-5.13.0.post3.dist-info/RECORD +19 -0
- mageml_singer_python-5.13.0.post3.dist-info/WHEEL +5 -0
- mageml_singer_python-5.13.0.post3.dist-info/licenses/LICENSE +177 -0
- mageml_singer_python-5.13.0.post3.dist-info/top_level.txt +1 -0
- singer/__init__.py +86 -0
- singer/bookmarks.py +46 -0
- singer/catalog.py +156 -0
- singer/exceptions.py +30 -0
- singer/logger.py +54 -0
- singer/logging.conf +24 -0
- singer/messages.py +287 -0
- singer/metadata.py +46 -0
- singer/metrics.py +248 -0
- singer/requests.py +6 -0
- singer/schema.py +111 -0
- singer/statediff.py +70 -0
- singer/transform.py +422 -0
- singer/utils.py +311 -0
singer/messages.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
import pytz
|
|
4
|
+
import simplejson as json
|
|
5
|
+
import ciso8601
|
|
6
|
+
|
|
7
|
+
import singer.utils as u
|
|
8
|
+
from .logger import get_logger
|
|
9
|
+
LOGGER = get_logger()
|
|
10
|
+
|
|
11
|
+
class Message():
|
|
12
|
+
'''Base class for messages.'''
|
|
13
|
+
|
|
14
|
+
def asdict(self): # pylint: disable=no-self-use
|
|
15
|
+
raise Exception('Not implemented')
|
|
16
|
+
|
|
17
|
+
def __eq__(self, other):
|
|
18
|
+
return isinstance(other, Message) and self.asdict() == other.asdict()
|
|
19
|
+
|
|
20
|
+
def __repr__(self):
|
|
21
|
+
pairs = ["{}={}".format(k, v) for k, v in self.asdict().items()]
|
|
22
|
+
attrstr = ", ".join(pairs)
|
|
23
|
+
return "{}({})".format(self.__class__.__name__, attrstr)
|
|
24
|
+
|
|
25
|
+
def __str__(self):
|
|
26
|
+
return str(self.asdict())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RecordMessage(Message):
|
|
30
|
+
'''RECORD message.
|
|
31
|
+
|
|
32
|
+
The RECORD message has these fields:
|
|
33
|
+
|
|
34
|
+
* stream (string) - The name of the stream the record belongs to.
|
|
35
|
+
* record (dict) - The raw data for the record
|
|
36
|
+
* version (optional, int) - For versioned streams, the version
|
|
37
|
+
number. Note that this feature is experimental and most Taps and
|
|
38
|
+
Targets should not need to use versioned streams.
|
|
39
|
+
|
|
40
|
+
msg = singer.RecordMessage(
|
|
41
|
+
stream='users',
|
|
42
|
+
record={'id': 1, 'name': 'Mary'})
|
|
43
|
+
|
|
44
|
+
'''
|
|
45
|
+
|
|
46
|
+
def __init__(self, stream, record, version=None, time_extracted=None):
|
|
47
|
+
self.stream = stream
|
|
48
|
+
self.record = record
|
|
49
|
+
self.version = version
|
|
50
|
+
self.time_extracted = time_extracted
|
|
51
|
+
if time_extracted and not time_extracted.tzinfo:
|
|
52
|
+
raise ValueError("'time_extracted' must be either None " +
|
|
53
|
+
"or an aware datetime (with a time zone)")
|
|
54
|
+
|
|
55
|
+
def asdict(self):
|
|
56
|
+
result = {
|
|
57
|
+
'type': 'RECORD',
|
|
58
|
+
'stream': self.stream,
|
|
59
|
+
'record': self.record,
|
|
60
|
+
}
|
|
61
|
+
if self.version is not None:
|
|
62
|
+
result['version'] = self.version
|
|
63
|
+
if self.time_extracted:
|
|
64
|
+
as_utc = self.time_extracted.astimezone(pytz.utc)
|
|
65
|
+
result['time_extracted'] = u.strftime(as_utc)
|
|
66
|
+
return result
|
|
67
|
+
|
|
68
|
+
def __str__(self):
|
|
69
|
+
return str(self.asdict())
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SchemaMessage(Message):
|
|
73
|
+
'''SCHEMA message.
|
|
74
|
+
|
|
75
|
+
The SCHEMA message has these fields:
|
|
76
|
+
|
|
77
|
+
* stream (string) - The name of the stream this schema describes.
|
|
78
|
+
* schema (dict) - The JSON schema.
|
|
79
|
+
* key_properties (list of strings) - List of primary key properties.
|
|
80
|
+
|
|
81
|
+
msg = singer.SchemaMessage(
|
|
82
|
+
stream='users',
|
|
83
|
+
schema={'type': 'object',
|
|
84
|
+
'properties': {
|
|
85
|
+
'id': {'type': 'integer'},
|
|
86
|
+
'name': {'type': 'string'}
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
key_properties=['id'])
|
|
90
|
+
|
|
91
|
+
'''
|
|
92
|
+
def __init__(self, stream, schema, key_properties, bookmark_properties=None):
|
|
93
|
+
self.stream = stream
|
|
94
|
+
self.schema = schema
|
|
95
|
+
self.key_properties = key_properties
|
|
96
|
+
|
|
97
|
+
if isinstance(bookmark_properties, (str, bytes)):
|
|
98
|
+
bookmark_properties = [bookmark_properties]
|
|
99
|
+
if bookmark_properties and not isinstance(bookmark_properties, list):
|
|
100
|
+
raise Exception("bookmark_properties must be a string or list of strings")
|
|
101
|
+
|
|
102
|
+
self.bookmark_properties = bookmark_properties
|
|
103
|
+
|
|
104
|
+
def asdict(self):
|
|
105
|
+
result = {
|
|
106
|
+
'type': 'SCHEMA',
|
|
107
|
+
'stream': self.stream,
|
|
108
|
+
'schema': self.schema,
|
|
109
|
+
'key_properties': self.key_properties
|
|
110
|
+
}
|
|
111
|
+
if self.bookmark_properties:
|
|
112
|
+
result['bookmark_properties'] = self.bookmark_properties
|
|
113
|
+
return result
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class StateMessage(Message):
|
|
117
|
+
'''STATE message.
|
|
118
|
+
|
|
119
|
+
The STATE message has one field:
|
|
120
|
+
|
|
121
|
+
* value (dict) - The value of the state.
|
|
122
|
+
|
|
123
|
+
msg = singer.StateMessage(
|
|
124
|
+
value={'users': '2017-06-19T00:00:00'})
|
|
125
|
+
|
|
126
|
+
'''
|
|
127
|
+
def __init__(self, value):
|
|
128
|
+
self.value = value
|
|
129
|
+
|
|
130
|
+
def asdict(self):
|
|
131
|
+
return {
|
|
132
|
+
'type': 'STATE',
|
|
133
|
+
'value': self.value
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class ActivateVersionMessage(Message):
|
|
138
|
+
'''ACTIVATE_VERSION message (EXPERIMENTAL).
|
|
139
|
+
|
|
140
|
+
The ACTIVATE_VERSION messages has these fields:
|
|
141
|
+
|
|
142
|
+
* stream - The name of the stream.
|
|
143
|
+
* version - The version number to activate.
|
|
144
|
+
|
|
145
|
+
This is a signal to the Target that it should delete all previously
|
|
146
|
+
seen data and replace it with all the RECORDs it has seen where the
|
|
147
|
+
record's version matches this version number.
|
|
148
|
+
|
|
149
|
+
Note that this feature is experimental. Most Taps and Targets should
|
|
150
|
+
not need to use the "version" field of "RECORD" messages or the
|
|
151
|
+
"ACTIVATE_VERSION" message at all.
|
|
152
|
+
|
|
153
|
+
msg = singer.ActivateVersionMessage(
|
|
154
|
+
stream='users',
|
|
155
|
+
version=2)
|
|
156
|
+
|
|
157
|
+
'''
|
|
158
|
+
def __init__(self, stream, version):
|
|
159
|
+
self.stream = stream
|
|
160
|
+
self.version = version
|
|
161
|
+
|
|
162
|
+
def asdict(self):
|
|
163
|
+
return {
|
|
164
|
+
'type': 'ACTIVATE_VERSION',
|
|
165
|
+
'stream': self.stream,
|
|
166
|
+
'version': self.version
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _required_key(msg, k):
|
|
171
|
+
if k not in msg:
|
|
172
|
+
raise Exception("Message is missing required key '{}': {}".format(k, msg))
|
|
173
|
+
|
|
174
|
+
return msg[k]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def parse_message(msg):
|
|
178
|
+
"""Parse a message string into a Message object."""
|
|
179
|
+
|
|
180
|
+
# We are not using Decimals for parsing here.
|
|
181
|
+
# We recognize that exposes data to potentially
|
|
182
|
+
# lossy conversions. However, this will affect
|
|
183
|
+
# very few data points and we have chosen to
|
|
184
|
+
# leave conversion as is for now.
|
|
185
|
+
obj = json.loads(msg, use_decimal=True)
|
|
186
|
+
msg_type = _required_key(obj, 'type')
|
|
187
|
+
|
|
188
|
+
if msg_type == 'RECORD':
|
|
189
|
+
time_extracted = obj.get('time_extracted')
|
|
190
|
+
if time_extracted:
|
|
191
|
+
try:
|
|
192
|
+
time_extracted = ciso8601.parse_datetime(time_extracted)
|
|
193
|
+
except:
|
|
194
|
+
LOGGER.warning("unable to parse time_extracted with ciso8601 library")
|
|
195
|
+
time_extracted = None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# time_extracted = dateutil.parser.parse(time_extracted)
|
|
199
|
+
return RecordMessage(stream=_required_key(obj, 'stream'),
|
|
200
|
+
record=_required_key(obj, 'record'),
|
|
201
|
+
version=obj.get('version'),
|
|
202
|
+
time_extracted=time_extracted)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
elif msg_type == 'SCHEMA':
|
|
206
|
+
return SchemaMessage(stream=_required_key(obj, 'stream'),
|
|
207
|
+
schema=_required_key(obj, 'schema'),
|
|
208
|
+
key_properties=_required_key(obj, 'key_properties'),
|
|
209
|
+
bookmark_properties=obj.get('bookmark_properties'))
|
|
210
|
+
|
|
211
|
+
elif msg_type == 'STATE':
|
|
212
|
+
return StateMessage(value=_required_key(obj, 'value'))
|
|
213
|
+
|
|
214
|
+
elif msg_type == 'ACTIVATE_VERSION':
|
|
215
|
+
return ActivateVersionMessage(stream=_required_key(obj, 'stream'),
|
|
216
|
+
version=_required_key(obj, 'version'))
|
|
217
|
+
else:
|
|
218
|
+
return None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def format_message(message):
|
|
222
|
+
return json.dumps(message.asdict(), use_decimal=True)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def write_message(message):
|
|
226
|
+
sys.stdout.write(format_message(message) + '\n')
|
|
227
|
+
sys.stdout.flush()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def write_record(stream_name, record, stream_alias=None, time_extracted=None):
|
|
231
|
+
"""Write a single record for the given stream.
|
|
232
|
+
|
|
233
|
+
write_record("users", {"id": 2, "email": "mike@stitchdata.com"})
|
|
234
|
+
"""
|
|
235
|
+
write_message(RecordMessage(stream=(stream_alias or stream_name),
|
|
236
|
+
record=record,
|
|
237
|
+
time_extracted=time_extracted))
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def write_records(stream_name, records):
|
|
241
|
+
"""Write a list of records for the given stream.
|
|
242
|
+
|
|
243
|
+
chris = {"id": 1, "email": "chris@stitchdata.com"}
|
|
244
|
+
mike = {"id": 2, "email": "mike@stitchdata.com"}
|
|
245
|
+
write_records("users", [chris, mike])
|
|
246
|
+
"""
|
|
247
|
+
for record in records:
|
|
248
|
+
write_record(stream_name, record)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def write_schema(stream_name, schema, key_properties, bookmark_properties=None, stream_alias=None):
|
|
252
|
+
"""Write a schema message.
|
|
253
|
+
|
|
254
|
+
stream = 'test'
|
|
255
|
+
schema = {'properties': {'id': {'type': 'integer'}, 'email': {'type': 'string'}}} # nopep8
|
|
256
|
+
key_properties = ['id']
|
|
257
|
+
write_schema(stream, schema, key_properties)
|
|
258
|
+
"""
|
|
259
|
+
if isinstance(key_properties, (str, bytes)):
|
|
260
|
+
key_properties = [key_properties]
|
|
261
|
+
if not isinstance(key_properties, list):
|
|
262
|
+
raise Exception("key_properties must be a string or list of strings")
|
|
263
|
+
|
|
264
|
+
write_message(
|
|
265
|
+
SchemaMessage(
|
|
266
|
+
stream=(stream_alias or stream_name),
|
|
267
|
+
schema=schema,
|
|
268
|
+
key_properties=key_properties,
|
|
269
|
+
bookmark_properties=bookmark_properties))
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def write_state(value):
|
|
273
|
+
"""Write a state message.
|
|
274
|
+
|
|
275
|
+
write_state({'last_updated_at': '2017-02-14T09:21:00'})
|
|
276
|
+
"""
|
|
277
|
+
write_message(StateMessage(value=value))
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def write_version(stream_name, version):
|
|
281
|
+
"""Write an activate version message.
|
|
282
|
+
|
|
283
|
+
stream = 'test'
|
|
284
|
+
version = int(time.time())
|
|
285
|
+
write_version(stream, version)
|
|
286
|
+
"""
|
|
287
|
+
write_message(ActivateVersionMessage(stream_name, version))
|
singer/metadata.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
def new():
|
|
2
|
+
return {}
|
|
3
|
+
|
|
4
|
+
def to_map(raw_metadata):
|
|
5
|
+
return {tuple(md['breadcrumb']): md['metadata'] for md in raw_metadata}
|
|
6
|
+
|
|
7
|
+
def to_list(compiled_metadata):
|
|
8
|
+
return [{'breadcrumb': k, 'metadata': v} for k, v in compiled_metadata.items()]
|
|
9
|
+
|
|
10
|
+
def delete(compiled_metadata, breadcrumb, k):
|
|
11
|
+
del compiled_metadata[breadcrumb][k]
|
|
12
|
+
|
|
13
|
+
def write(compiled_metadata, breadcrumb, k, val):
|
|
14
|
+
if val is None:
|
|
15
|
+
raise Exception()
|
|
16
|
+
if breadcrumb in compiled_metadata:
|
|
17
|
+
compiled_metadata.get(breadcrumb).update({k: val})
|
|
18
|
+
else:
|
|
19
|
+
compiled_metadata[breadcrumb] = {k: val}
|
|
20
|
+
return compiled_metadata
|
|
21
|
+
|
|
22
|
+
def get(compiled_metadata, breadcrumb, k):
|
|
23
|
+
return compiled_metadata.get(breadcrumb, {}).get(k)
|
|
24
|
+
|
|
25
|
+
def get_standard_metadata(schema=None, schema_name=None, key_properties=None,
|
|
26
|
+
valid_replication_keys=None, replication_method=None):
|
|
27
|
+
mdata = {}
|
|
28
|
+
|
|
29
|
+
if key_properties is not None:
|
|
30
|
+
mdata = write(mdata, (), 'table-key-properties', key_properties)
|
|
31
|
+
if replication_method:
|
|
32
|
+
mdata = write(mdata, (), 'forced-replication-method', replication_method)
|
|
33
|
+
if valid_replication_keys is not None:
|
|
34
|
+
mdata = write(mdata, (), 'valid-replication-keys', valid_replication_keys)
|
|
35
|
+
if schema:
|
|
36
|
+
mdata = write(mdata, (), 'inclusion', 'available')
|
|
37
|
+
|
|
38
|
+
if schema_name:
|
|
39
|
+
mdata = write(mdata, (), 'schema-name', schema_name)
|
|
40
|
+
for field_name in schema['properties'].keys():
|
|
41
|
+
if key_properties and field_name in key_properties:
|
|
42
|
+
mdata = write(mdata, ('properties', field_name), 'inclusion', 'automatic')
|
|
43
|
+
else:
|
|
44
|
+
mdata = write(mdata, ('properties', field_name), 'inclusion', 'available')
|
|
45
|
+
|
|
46
|
+
return to_list(mdata)
|
singer/metrics.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
'''Utilities for logging and parsing metrics.
|
|
2
|
+
|
|
3
|
+
A Tap should use this library to log structured messages about the read
|
|
4
|
+
operations it makes.
|
|
5
|
+
|
|
6
|
+
Counter is a general-purpose class that allows you to increment a
|
|
7
|
+
"counter"-type metric. You initialize a Counter as a context manager, with
|
|
8
|
+
a metric name and a dictionary of tags. The Counter will periodically emit
|
|
9
|
+
a metric that indicates the amount by which the counter was incremented
|
|
10
|
+
since the last time it reported. For example, to increment a record count
|
|
11
|
+
for records from a "users" endpoint, you could do:
|
|
12
|
+
|
|
13
|
+
with Counter('record_count', {'endpoint': 'users'}) as counter:
|
|
14
|
+
for record in my_records:
|
|
15
|
+
# Do stuff...
|
|
16
|
+
counter.increment()
|
|
17
|
+
|
|
18
|
+
Timer is class that allows you to track the timing of operations. Like
|
|
19
|
+
Counter, you initialize it as a context manager, with a metric name and a
|
|
20
|
+
dictionary of tags. When the context exits, the timer will emit a single
|
|
21
|
+
metric that indicates how long it took in seconds. The metric will
|
|
22
|
+
automatically include a tag called "status" that is set to "failed" if an
|
|
23
|
+
Exception was raised, or "succeeded" otherwise.
|
|
24
|
+
|
|
25
|
+
with Timer('http_request_duration', {'endpoint': 'users'}):
|
|
26
|
+
# Make a request, do some things
|
|
27
|
+
|
|
28
|
+
In order to encourage consistent metric and tag names, this module
|
|
29
|
+
provides several functions for creating Counters and Timers for very
|
|
30
|
+
commonly used metrics.
|
|
31
|
+
|
|
32
|
+
* record_counter - Increments a 'record_count' metric to track number of
|
|
33
|
+
records fetched from a source. Provides an "endpoint" tag.
|
|
34
|
+
|
|
35
|
+
* http_request_timer - Emits an 'http_request_duration' metric to time
|
|
36
|
+
HTTP requests. Provides "endpoint" tag.
|
|
37
|
+
|
|
38
|
+
* job_timer - Emits a 'job_duration' metric to track time of
|
|
39
|
+
asynchronous jobs. Provides "job_type" tag.
|
|
40
|
+
|
|
41
|
+
'''
|
|
42
|
+
|
|
43
|
+
import json
|
|
44
|
+
import re
|
|
45
|
+
import time
|
|
46
|
+
from collections import namedtuple
|
|
47
|
+
from singer.logger import get_logger
|
|
48
|
+
|
|
49
|
+
DEFAULT_LOG_INTERVAL = 60
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Status:
|
|
53
|
+
'''Constants for status codes'''
|
|
54
|
+
succeeded = 'succeeded'
|
|
55
|
+
failed = 'failed'
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Metric:
|
|
59
|
+
'''Constants for metric names'''
|
|
60
|
+
|
|
61
|
+
record_count = 'record_count'
|
|
62
|
+
job_duration = 'job_duration'
|
|
63
|
+
http_request_duration = 'http_request_duration'
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Tag:
|
|
67
|
+
'''Constants for commonly used tags'''
|
|
68
|
+
|
|
69
|
+
endpoint = 'endpoint'
|
|
70
|
+
job_type = 'job_type'
|
|
71
|
+
http_status_code = 'http_status_code'
|
|
72
|
+
status = 'status'
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
Point = namedtuple('Point', ['metric_type', 'metric', 'value', 'tags'])
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def log(logger, point):
|
|
80
|
+
'''Log a single data point.'''
|
|
81
|
+
result = {
|
|
82
|
+
'type': point.metric_type,
|
|
83
|
+
'metric': point.metric,
|
|
84
|
+
'value': point.value,
|
|
85
|
+
'tags': point.tags
|
|
86
|
+
}
|
|
87
|
+
logger.info('METRIC: %s', json.dumps(result))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Counter():
|
|
91
|
+
'''Increments a counter metric.
|
|
92
|
+
|
|
93
|
+
When you use Counter as a context manager, it will automatically emit
|
|
94
|
+
points for a "counter" metric periodically and also when the context
|
|
95
|
+
exits. The only thing you need to do is initialize the Counter and
|
|
96
|
+
then call increment().
|
|
97
|
+
|
|
98
|
+
with singer.metrics.Counter('record_count', {'endpoint': 'users'}) as counter:
|
|
99
|
+
for user in get_users(...):
|
|
100
|
+
# Print out the user
|
|
101
|
+
counter.increment()
|
|
102
|
+
|
|
103
|
+
This would print a metric like this:
|
|
104
|
+
|
|
105
|
+
{
|
|
106
|
+
"type": "counter",
|
|
107
|
+
"metric": "record_count",
|
|
108
|
+
"value": 12345,
|
|
109
|
+
"tags": {
|
|
110
|
+
"endpoint": "users",
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
'''
|
|
115
|
+
|
|
116
|
+
def __init__(self, metric, tags=None, log_interval=DEFAULT_LOG_INTERVAL):
|
|
117
|
+
self.metric = metric
|
|
118
|
+
self.value = 0
|
|
119
|
+
self.tags = tags if tags else {}
|
|
120
|
+
self.log_interval = log_interval
|
|
121
|
+
self.logger = get_logger()
|
|
122
|
+
self.last_log_time = time.time()
|
|
123
|
+
|
|
124
|
+
def __enter__(self):
|
|
125
|
+
self.last_log_time = time.time()
|
|
126
|
+
return self
|
|
127
|
+
|
|
128
|
+
def increment(self, amount=1):
|
|
129
|
+
'''Increments value by the specified amount.'''
|
|
130
|
+
self.value += amount
|
|
131
|
+
if self._ready_to_log():
|
|
132
|
+
self._pop()
|
|
133
|
+
|
|
134
|
+
def _pop(self):
|
|
135
|
+
log(self.logger, Point('counter', self.metric, self.value, self.tags))
|
|
136
|
+
self.value = 0
|
|
137
|
+
self.last_log_time = time.time()
|
|
138
|
+
|
|
139
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
140
|
+
self._pop()
|
|
141
|
+
|
|
142
|
+
def _ready_to_log(self):
|
|
143
|
+
return time.time() - self.last_log_time > self.log_interval
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class Timer(): # pylint: disable=too-few-public-methods
|
|
147
|
+
'''Produces metrics about the duration of operations.
|
|
148
|
+
|
|
149
|
+
You use a Timer as a context manager wrapping around some operation.
|
|
150
|
+
When the context exits, the Timer emits a metric that indicates how
|
|
151
|
+
long (in seconds) the operation took.
|
|
152
|
+
|
|
153
|
+
It will automatically include a "status" tag that is "failed" if the
|
|
154
|
+
context exits with an Exception or "success" if it exits cleanly. You
|
|
155
|
+
can override this by setting timer.status within the context.
|
|
156
|
+
|
|
157
|
+
with singer.metrics.Timer('request_duration', {'endpoint': 'users'}):
|
|
158
|
+
# Do some stuff
|
|
159
|
+
|
|
160
|
+
This produces a metric like this:
|
|
161
|
+
|
|
162
|
+
{
|
|
163
|
+
"type": "timer",
|
|
164
|
+
"metric": "request_duration",
|
|
165
|
+
"value": 1.23,
|
|
166
|
+
"tags": {
|
|
167
|
+
"endpoint": "users",
|
|
168
|
+
"status": "success"
|
|
169
|
+
}
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
'''
|
|
173
|
+
def __init__(self, metric, tags):
|
|
174
|
+
self.metric = metric
|
|
175
|
+
self.tags = tags if tags else {}
|
|
176
|
+
self.logger = get_logger()
|
|
177
|
+
self.start_time = None
|
|
178
|
+
|
|
179
|
+
def __enter__(self):
|
|
180
|
+
self.start_time = time.time()
|
|
181
|
+
return self
|
|
182
|
+
|
|
183
|
+
def elapsed(self):
|
|
184
|
+
'''Return elapsed time'''
|
|
185
|
+
return time.time() - self.start_time
|
|
186
|
+
|
|
187
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
188
|
+
if Tag.status not in self.tags:
|
|
189
|
+
if exc_type is None:
|
|
190
|
+
self.tags[Tag.status] = Status.succeeded
|
|
191
|
+
else:
|
|
192
|
+
self.tags[Tag.status] = Status.failed
|
|
193
|
+
log(self.logger, Point('timer', self.metric, self.elapsed(), self.tags))
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def record_counter(endpoint=None, log_interval=DEFAULT_LOG_INTERVAL):
|
|
197
|
+
'''Use for counting records retrieved from the source.
|
|
198
|
+
|
|
199
|
+
with singer.metrics.record_counter(endpoint="users") as counter:
|
|
200
|
+
for record in my_records:
|
|
201
|
+
# Do something with the record
|
|
202
|
+
counter.increment()
|
|
203
|
+
'''
|
|
204
|
+
tags = {}
|
|
205
|
+
if endpoint:
|
|
206
|
+
tags[Tag.endpoint] = endpoint
|
|
207
|
+
return Counter(Metric.record_count, tags, log_interval=log_interval)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def http_request_timer(endpoint):
|
|
211
|
+
'''Use for timing HTTP requests to an endpoint
|
|
212
|
+
|
|
213
|
+
with singer.metrics.http_request_timer("users") as timer:
|
|
214
|
+
# Make a request
|
|
215
|
+
'''
|
|
216
|
+
tags = {}
|
|
217
|
+
if endpoint:
|
|
218
|
+
tags[Tag.endpoint] = endpoint
|
|
219
|
+
return Timer(Metric.http_request_duration, tags)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def job_timer(job_type=None):
|
|
223
|
+
'''Use for timing asynchronous jobs
|
|
224
|
+
|
|
225
|
+
with singer.metrics.job_timer(job_type="users") as timer:
|
|
226
|
+
# Make a request
|
|
227
|
+
'''
|
|
228
|
+
tags = {}
|
|
229
|
+
if job_type:
|
|
230
|
+
tags[Tag.job_type] = job_type
|
|
231
|
+
return Timer(Metric.job_duration, tags)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def parse(line):
|
|
235
|
+
'''Parse a Point from a log line and return it, or None if no data point.'''
|
|
236
|
+
match = re.match(r'^INFO METRIC: (.*)$', line)
|
|
237
|
+
if match:
|
|
238
|
+
json_str = match.group(1)
|
|
239
|
+
try:
|
|
240
|
+
raw = json.loads(json_str)
|
|
241
|
+
return Point(
|
|
242
|
+
metric_type=raw.get('type'),
|
|
243
|
+
metric=raw.get('metric'),
|
|
244
|
+
value=raw.get('value'),
|
|
245
|
+
tags=raw.get('tags'))
|
|
246
|
+
except Exception as exc: # pylint: disable=broad-except
|
|
247
|
+
get_logger().warning('Error parsing metric: %s', exc)
|
|
248
|
+
return None
|
singer/requests.py
ADDED
singer/schema.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# pylint: disable=redefined-builtin, too-many-arguments, invalid-name
|
|
2
|
+
'''Provides an object model for JSON Schema'''
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
# These are standard keys defined in the JSON Schema spec
|
|
7
|
+
STANDARD_KEYS = [
|
|
8
|
+
'selected',
|
|
9
|
+
'inclusion',
|
|
10
|
+
'description',
|
|
11
|
+
'minimum',
|
|
12
|
+
'maximum',
|
|
13
|
+
'exclusiveMinimum',
|
|
14
|
+
'exclusiveMaximum',
|
|
15
|
+
'multipleOf',
|
|
16
|
+
'maxLength',
|
|
17
|
+
'minLength',
|
|
18
|
+
'format',
|
|
19
|
+
'type',
|
|
20
|
+
'additionalProperties',
|
|
21
|
+
'anyOf',
|
|
22
|
+
'patternProperties',
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Schema(): # pylint: disable=too-many-instance-attributes
|
|
27
|
+
'''Object model for JSON Schema.
|
|
28
|
+
|
|
29
|
+
Tap and Target authors may find this to be more convenient than
|
|
30
|
+
working directly with JSON Schema data structures.
|
|
31
|
+
|
|
32
|
+
'''
|
|
33
|
+
|
|
34
|
+
# pylint: disable=too-many-locals
|
|
35
|
+
def __init__(self, type=None, format=None, properties=None, items=None,
|
|
36
|
+
selected=None, inclusion=None, description=None, minimum=None,
|
|
37
|
+
maximum=None, exclusiveMinimum=None, exclusiveMaximum=None,
|
|
38
|
+
multipleOf=None, maxLength=None, minLength=None, additionalProperties=None,
|
|
39
|
+
anyOf=None, patternProperties=None):
|
|
40
|
+
|
|
41
|
+
self.type = type
|
|
42
|
+
self.properties = properties
|
|
43
|
+
self.items = items
|
|
44
|
+
self.selected = selected
|
|
45
|
+
self.inclusion = inclusion
|
|
46
|
+
self.description = description
|
|
47
|
+
self.minimum = minimum
|
|
48
|
+
self.maximum = maximum
|
|
49
|
+
self.exclusiveMinimum = exclusiveMinimum
|
|
50
|
+
self.exclusiveMaximum = exclusiveMaximum
|
|
51
|
+
self.multipleOf = multipleOf
|
|
52
|
+
self.maxLength = maxLength
|
|
53
|
+
self.minLength = minLength
|
|
54
|
+
self.anyOf = anyOf
|
|
55
|
+
self.format = format
|
|
56
|
+
self.additionalProperties = additionalProperties
|
|
57
|
+
self.patternProperties = patternProperties
|
|
58
|
+
|
|
59
|
+
def __str__(self):
|
|
60
|
+
return json.dumps(self.to_dict())
|
|
61
|
+
|
|
62
|
+
def __repr__(self):
|
|
63
|
+
pairs = [k + '=' + repr(v) for k, v in self.__dict__.items()]
|
|
64
|
+
args = ', '.join(pairs)
|
|
65
|
+
return 'Schema(' + args + ')'
|
|
66
|
+
|
|
67
|
+
def __eq__(self, other):
|
|
68
|
+
return self.__dict__ == other.__dict__
|
|
69
|
+
|
|
70
|
+
def to_dict(self):
|
|
71
|
+
'''Return the raw JSON Schema as a (possibly nested) dict.'''
|
|
72
|
+
result = {}
|
|
73
|
+
|
|
74
|
+
if self.properties is not None:
|
|
75
|
+
result['properties'] = {
|
|
76
|
+
k: v.to_dict()
|
|
77
|
+
for k, v
|
|
78
|
+
in self.properties.items() # pylint: disable=no-member
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
if self.items is not None:
|
|
83
|
+
result['items'] = self.items.to_dict() # pylint: disable=no-member
|
|
84
|
+
|
|
85
|
+
for key in STANDARD_KEYS:
|
|
86
|
+
if self.__dict__.get(key) is not None:
|
|
87
|
+
result[key] = self.__dict__[key]
|
|
88
|
+
|
|
89
|
+
return result
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def from_dict(cls, data, **schema_defaults):
|
|
93
|
+
'''Initialize a Schema object based on the JSON Schema structure.
|
|
94
|
+
|
|
95
|
+
:param schema_defaults: The default values to the Schema
|
|
96
|
+
constructor.'''
|
|
97
|
+
kwargs = schema_defaults.copy()
|
|
98
|
+
properties = data.get('properties')
|
|
99
|
+
items = data.get('items')
|
|
100
|
+
|
|
101
|
+
if properties is not None:
|
|
102
|
+
kwargs['properties'] = {
|
|
103
|
+
k: Schema.from_dict(v, **schema_defaults)
|
|
104
|
+
for k, v in properties.items()
|
|
105
|
+
}
|
|
106
|
+
if items is not None:
|
|
107
|
+
kwargs['items'] = Schema.from_dict(items, **schema_defaults)
|
|
108
|
+
for key in STANDARD_KEYS:
|
|
109
|
+
if key in data:
|
|
110
|
+
kwargs[key] = data[key]
|
|
111
|
+
return Schema(**kwargs)
|