Debian Codegraph @

influxdb/line_protocol.py

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