| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""Define the line_protocol handler.""" |
| 3 |
|
| 4 |
from __future__ import absolute_import |
| 5 |
from __future__ import division |
| 6 |
from __future__ import print_function |
| 7 |
from __future__ import unicode_literals |
| 8 |
|
| 9 |
from datetime import datetime |
| 10 |
from numbers import Integral |
| 11 |
|
| 12 |
from pytz import UTC |
| 13 |
from dateutil.parser import parse |
| 14 |
|
| 15 |
EPOCH = UTC.localize(datetime.utcfromtimestamp(0)) |
| 16 |
|
| 17 |
|
| 18 |
def _to_nanos(timestamp): |
| 19 |
delta = timestamp - EPOCH |
| 20 |
nanos_in_days = delta.days * 86400 * 10 ** 9 |
| 21 |
nanos_in_seconds = delta.seconds * 10 ** 9 |
| 22 |
nanos_in_micros = delta.microseconds * 10 ** 3 |
| 23 |
return nanos_in_days + nanos_in_seconds + nanos_in_micros |
| 24 |
|
| 25 |
|
| 26 |
def _convert_timestamp(timestamp, precision=None): |
| 27 |
if isinstance(timestamp, Integral): |
| 28 |
return timestamp # assume precision is correct if timestamp is int |
| 29 |
|
| •30 |
if isinstance(_get_unicode(timestamp), str): |
| 31 |
timestamp = parse(timestamp) |
| 32 |
|
| 33 |
if isinstance(timestamp, datetime): |
| 34 |
if not timestamp.tzinfo: |
| 35 |
timestamp = UTC.localize(timestamp) |
| 36 |
|
| 37 |
ns = _to_nanos(timestamp) |
| 38 |
if precision is None or precision == 'n': |
| 39 |
return ns |
| 40 |
|
| 41 |
if precision == 'u': |
| 42 |
return ns / 10**3 |
| 43 |
|
| 44 |
if precision == 'ms': |
| 45 |
return ns / 10**6 |
| 46 |
|
| 47 |
if precision == 's': |
| 48 |
return ns / 10**9 |
| 49 |
|
| 50 |
if precision == 'm': |
| 51 |
return ns / 10**9 / 60 |
| 52 |
|
| 53 |
if precision == 'h': |
| 54 |
return ns / 10**9 / 3600 |
| 55 |
|
| 56 |
raise ValueError(timestamp) |
| 57 |
|
| 58 |
|
| 59 |
def _escape_tag(tag): |
| 60 |
tag = _get_unicode(tag, force=True) |
| 61 |
return tag.replace( |
| 62 |
"\\", "\\\\" |
| 63 |
).replace( |
| 64 |
" ", "\\ " |
| 65 |
).replace( |
| 66 |
",", "\\," |
| 67 |
).replace( |
| 68 |
"=", "\\=" |
| 69 |
).replace( |
| 70 |
"\n", "\\n" |
| 71 |
) |
| 72 |
|
| 73 |
|
| 74 |
def _escape_tag_value(value): |
| 75 |
ret = _escape_tag(value) |
| 76 |
if ret.endswith('\\'): |
| 77 |
ret += ' ' |
| 78 |
return ret |
| 79 |
|
| 80 |
|
| 81 |
def quote_ident(value): |
| 82 |
"""Indent the quotes.""" |
| 83 |
return "\"{}\"".format(value |
| 84 |
.replace("\\", "\\\\") |
| 85 |
.replace("\"", "\\\"") |
| 86 |
.replace("\n", "\\n")) |
| 87 |
|
| 88 |
|
| 89 |
def quote_literal(value): |
| 90 |
"""Quote provided literal.""" |
| 91 |
return "'{}'".format(value |
| 92 |
.replace("\\", "\\\\") |
| 93 |
.replace("'", "\\'")) |
| 94 |
|
| 95 |
|
| 96 |
def _is_float(value): |
| 97 |
try: |
| 98 |
float(value) |
| 99 |
except (TypeError, ValueError): |
| 100 |
return False |
| 101 |
|
| 102 |
return True |
| 103 |
|
| 104 |
|
| 105 |
def _escape_value(value): |
| 106 |
if value is None: |
| 107 |
return '' |
| 108 |
|
| 109 |
value = _get_unicode(value) |
| •110 |
if isinstance(value, str): |
| 111 |
return quote_ident(value) |
| 112 |
|
| •113 |
if isinstance(value, int) and not isinstance(value, bool): |
| 114 |
return str(value) + 'i' |
| 115 |
|
| 116 |
if isinstance(value, bool): |
| 117 |
return str(value) |
| 118 |
|
| 119 |
if _is_float(value): |
| 120 |
return repr(float(value)) |
| 121 |
|
| 122 |
return str(value) |
| 123 |
|
| 124 |
|
| 125 |
def _get_unicode(data, force=False): |
| 126 |
"""Try to return a text aka unicode object from the given data.""" |
| •127 |
if isinstance(data, bytes): |
| 128 |
return data.decode('utf-8') |
| 129 |
|
| 130 |
if data is None: |
| 131 |
return '' |
| 132 |
|
| 133 |
if force: |
| 134 |
return str(data) |
| 135 |
|
| 136 |
return data |
| 137 |
|
| 138 |
|
| 139 |
def make_line(measurement, tags=None, fields=None, time=None, precision=None): |
| 140 |
"""Extract the actual point from a given measurement line.""" |
| 141 |
tags = tags or {} |
| 142 |
fields = fields or {} |
| 143 |
|
| 144 |
line = _escape_tag(_get_unicode(measurement)) |
| 145 |
|
| 146 |
# tags should be sorted client-side to take load off server |
| 147 |
tag_list = [] |
| 148 |
for tag_key in sorted(tags.keys()): |
| 149 |
key = _escape_tag(tag_key) |
| 150 |
value = _escape_tag(tags[tag_key]) |
| 151 |
|
| 152 |
if key != '' and value != '': |
| 153 |
tag_list.append( |
| 154 |
"{key}={value}".format(key=key, value=value) |
| 155 |
) |
| 156 |
|
| 157 |
if tag_list: |
| 158 |
line += ',' + ','.join(tag_list) |
| 159 |
|
| 160 |
field_list = [] |
| 161 |
for field_key in sorted(fields.keys()): |
| 162 |
key = _escape_tag(field_key) |
| 163 |
value = _escape_value(fields[field_key]) |
| 164 |
|
| 165 |
if key != '' and value != '': |
| 166 |
field_list.append("{key}={value}".format( |
| 167 |
key=key, |
| 168 |
value=value |
| 169 |
)) |
| 170 |
|
| 171 |
if field_list: |
| 172 |
line += ' ' + ','.join(field_list) |
| 173 |
|
| 174 |
if time is not None: |
| 175 |
timestamp = _get_unicode(str(int( |
| 176 |
_convert_timestamp(time, precision) |
| 177 |
))) |
| 178 |
line += ' ' + timestamp |
| 179 |
|
| 180 |
return line |
| 181 |
|
| 182 |
|
| 183 |
def make_lines(data, precision=None): |
| 184 |
"""Extract points from given dict. |
| 185 |
|
| 186 |
Extracts the points from the given dict and returns a Unicode string |
| 187 |
matching the line protocol introduced in InfluxDB 0.9.0. |
| 188 |
""" |
| 189 |
lines = [] |
| 190 |
static_tags = data.get('tags') |
| 191 |
for point in data['points']: |
| 192 |
if static_tags: |
| 193 |
tags = dict(static_tags) # make a copy, since we'll modify |
| 194 |
tags.update(point.get('tags') or {}) |
| 195 |
else: |
| 196 |
tags = point.get('tags') or {} |
| 197 |
|
| 198 |
line = make_line( |
| 199 |
point.get('measurement', data.get('measurement')), |
| 200 |
tags=tags, |
| 201 |
fields=point.get('fields'), |
| 202 |
precision=precision, |
| 203 |
time=point.get('time') |
| 204 |
) |
| 205 |
lines.append(line) |
| 206 |
|
| 207 |
return '\n'.join(lines) + '\n' |