Merge "run ipv6 test case on more pods"
[yardstick.git] / third_party / influxdb / influxdb_line_protocol.py
1 # The MIT License (MIT)
2
3 # Copyright (c) 2013 InfluxDB
4
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in
8 # the Software without restriction, including without limitation the rights to
9 # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 # of the Software, and to permit persons to whom the Software is furnished to
11 # do so, subject to the following conditions:
12
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 # SOFTWARE.
23
24 # yardstick comment: this file is a modified copy of
25 # influxdb-python/influxdb/line_protocol.py
26
27 from __future__ import unicode_literals
28 from copy import copy
29
30 from six import binary_type, text_type, integer_types
31
32
33 def _escape_tag(tag):
34     tag = _get_unicode(tag, force=True)
35     return tag.replace(
36         "\\", "\\\\"
37     ).replace(
38         " ", "\\ "
39     ).replace(
40         ",", "\\,"
41     ).replace(
42         "=", "\\="
43     )
44
45
46 def _escape_value(value):
47     value = _get_unicode(value)
48     if isinstance(value, text_type) and value != '':
49         return "\"{}\"".format(
50             value.replace(
51                 "\"", "\\\""
52             ).replace(
53                 "\n", "\\n"
54             )
55         )
56     elif isinstance(value, integer_types) and not isinstance(value, bool):
57         return str(value) + 'i'
58     else:
59         return str(value)
60
61
62 def _get_unicode(data, force=False):
63     """
64     Try to return a text aka unicode object from the given data.
65     """
66     if isinstance(data, binary_type):
67         return data.decode('utf-8')
68     elif data is None:
69         return ''
70     elif force:
71         return str(data)
72     else:
73         return data
74
75
76 def make_lines(data):
77     """
78     Extracts the points from the given dict and returns a Unicode string
79     matching the line protocol introduced in InfluxDB 0.9.0.
80
81     line protocol format:
82         <measurement>[,<tag-key>=<tag-value>...] <field-key>=<field-value>\
83             [,<field2-key>=<field2-value>...] [unix-nano-timestamp]
84
85     Ref:
86         https://influxdb.com/docs/v0.9/write_protocols/write_syntax.html
87         https://influxdb.com/docs/v0.9/write_protocols/line.html
88     """
89     lines = []
90     static_tags = data.get('tags', None)
91     for point in data['points']:
92         elements = []
93
94         # add measurement name
95         measurement = _escape_tag(_get_unicode(
96             point.get('measurement', data.get('measurement'))
97         ))
98         key_values = [measurement]
99
100         # add tags
101         if static_tags is None:
102             tags = point.get('tags', {})
103         else:
104             tags = copy(static_tags)
105             tags.update(point.get('tags', {}))
106
107         # tags should be sorted client-side to take load off server
108         for tag_key in sorted(tags.keys()):
109             key = _escape_tag(tag_key)
110             value = _escape_tag(tags[tag_key])
111
112             if key != '' and value != '':
113                 key_values.append("{key}={value}".format(key=key, value=value))
114         key_values = ','.join(key_values)
115         elements.append(key_values)
116
117         # add fields
118         field_values = []
119         for field_key in sorted(point['fields'].keys()):
120             key = _escape_tag(field_key)
121             value = _escape_value(point['fields'][field_key])
122             if key != '' and value != '':
123                 field_values.append("{key}={value}".format(
124                     key=key,
125                     value=value
126                 ))
127         field_values = ','.join(field_values)
128         elements.append(field_values)
129
130         # add timestamp
131         if 'time' in point:
132             elements.append(point['time'])
133
134         line = ' '.join(elements)
135         lines.append(line)
136     lines = '\n'.join(lines)
137     return lines + '\n'