Debian Codegraph @

influxdb/helper.py

raw ◀ ▶
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 """Helper class for InfluxDB."""
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 collections import namedtuple, defaultdict
10 from datetime import datetime
11 from warnings import warn
12
13
14
15 class SeriesHelper(object):
16 """Subclass this helper eases writing data points in bulk.
17
18 All data points are immutable, ensuring they do not get overwritten.
19 Each subclass can write to its own database.
20 The time series names can also be based on one or more defined fields.
21 The field "time" can be specified when creating a point, and may be any of
22 the time types supported by the client (i.e. str, datetime, int).
23 If the time is not specified, the current system time (utc) will be used.
24
25 Annotated example::
26
27 class MySeriesHelper(SeriesHelper):
28 class Meta:
29 # Meta class stores time series helper configuration.
30 series_name = 'events.stats.{server_name}'
31 # Series name must be a string, curly brackets for dynamic use.
32 fields = ['time', 'server_name']
33 # Defines all the fields in this time series.
34 ### Following attributes are optional. ###
35 client = TestSeriesHelper.client
36 # Client should be an instance of InfluxDBClient.
37 :warning: Only used if autocommit is True.
38 bulk_size = 5
39 # Defines the number of data points to write simultaneously.
40 # Only applicable if autocommit is True.
41 autocommit = True
42 # If True and no bulk_size, then will set bulk_size to 1.
43 retention_policy = 'your_retention_policy'
44 # Specify the retention policy for the data points
45 time_precision = "h"|"m"|s"|"ms"|"u"|"ns"
46 # Default is ns (nanoseconds)
47 # Setting time precision while writing point
48 # You should also make sure time is set in the given precision
49
50 """
51
52 __initialized__ = False
53
54 def __new__(cls, *args, **kwargs):
55 """Initialize class attributes for subsequent constructor calls.
56
57 :note: *args and **kwargs are not explicitly used in this function,
58 but needed for Python 2 compatibility.
59 """
60 if not cls.__initialized__:
61 cls.__initialized__ = True
62 try:
63 _meta = getattr(cls, 'Meta')
64 except AttributeError:
65 raise AttributeError(
66 'Missing Meta class in {0}.'.format(
67 cls.__name__))
68
69 for attr in ['series_name', 'fields', 'tags']:
70 try:
71 setattr(cls, '_' + attr, getattr(_meta, attr))
72 except AttributeError:
73 raise AttributeError(
74 'Missing {0} in {1} Meta class.'.format(
75 attr,
76 cls.__name__))
77
78 cls._autocommit = getattr(_meta, 'autocommit', False)
79 cls._time_precision = getattr(_meta, 'time_precision', None)
80
81 allowed_time_precisions = ['h', 'm', 's', 'ms', 'u', 'ns', None]
82 if cls._time_precision not in allowed_time_precisions:
83 raise AttributeError(
84 'In {}, time_precision is set, but invalid use any of {}.'
85 .format(cls.__name__, ','.join(allowed_time_precisions)))
86
87 cls._retention_policy = getattr(_meta, 'retention_policy', None)
88
89 cls._client = getattr(_meta, 'client', None)
90 if cls._autocommit and not cls._client:
91 raise AttributeError(
92 'In {0}, autocommit is set to True, but no client is set.'
93 .format(cls.__name__))
94
95 try:
96 cls._bulk_size = getattr(_meta, 'bulk_size')
97 if cls._bulk_size < 1 and cls._autocommit:
98 warn(
99 'Definition of bulk_size in {0} forced to 1, '
100 'was less than 1.'.format(cls.__name__))
101 cls._bulk_size = 1
102 except AttributeError:
103 cls._bulk_size = -1
104 else:
105 if not cls._autocommit:
106 warn(
107 'Definition of bulk_size in {0} has no affect because'
108 ' autocommit is false.'.format(cls.__name__))
109
110 cls._datapoints = defaultdict(list)
111
112 if 'time' in cls._fields:
113 cls._fields.remove('time')
114 cls._type = namedtuple(cls.__name__,
115 ['time'] + cls._tags + cls._fields)
116 cls._type.__new__.__defaults__ = (None,) * len(cls._fields)
117
118 return super(SeriesHelper, cls).__new__(cls)
119
120 def __init__(self, **kw):
121 """Call to constructor creates a new data point.
122
123 :note: Data points written when `bulk_size` is reached per Helper.
124 :warning: Data points are *immutable* (`namedtuples`).
125 """
126 cls = self.__class__
127 timestamp = kw.pop('time', self._current_timestamp())
128 tags = set(cls._tags)
129 fields = set(cls._fields)
130 keys = set(kw.keys())
131
132 # all tags should be passed, and keys - tags should be a subset of keys
133 if not (tags <= keys):
134 raise NameError(
135 'Expected arguments to contain all tags {0}, instead got {1}.'
136 .format(cls._tags, kw.keys()))
137 if not (keys - tags <= fields):
138 raise NameError('Got arguments not in tags or fields: {0}'
139 .format(keys - tags - fields))
140
141 cls._datapoints[cls._series_name.format(**kw)].append(
142 cls._type(time=timestamp, **kw)
143 )
144
145 if cls._autocommit and \
146 sum(len(series) for series in cls._datapoints.values()) \
147 >= cls._bulk_size:
148 cls.commit()
149
150 @classmethod
151 def commit(cls, client=None):
152 """Commit everything from datapoints via the client.
153
154 :param client: InfluxDBClient instance for writing points to InfluxDB.
155 :attention: any provided client will supersede the class client.
156 :return: result of client.write_points.
157 """
158 if not client:
159 client = cls._client
160
161 rtn = client.write_points(
162 cls._json_body_(),
163 time_precision=cls._time_precision,
164 retention_policy=cls._retention_policy)
165 # will be None if not set and will default to ns
166 cls._reset_()
167 return rtn
168
169 @classmethod
170 def _json_body_(cls):
171 """Return the JSON body of given datapoints.
172
173 :return: JSON body of these datapoints.
174 """
175 json = []
176 if not cls.__initialized__:
177 cls._reset_()
•178 for series_name, data in cls._datapoints.items():
179 for point in data:
180 json_point = {
181 "measurement": series_name,
182 "fields": {},
183 "tags": {},
184 "time": getattr(point, "time")
185 }
186
187 for field in cls._fields:
188 value = getattr(point, field)
189 if value is not None:
190 json_point['fields'][field] = value
191
192 for tag in cls._tags:
193 json_point['tags'][tag] = getattr(point, tag)
194
195 json.append(json_point)
196 return json
197
198 @classmethod
199 def _reset_(cls):
200 """Reset data storage."""
201 cls._datapoints = defaultdict(list)
202
203 @staticmethod
204 def _current_timestamp():
205 return datetime.utcnow()