Debian Codegraph @

influxdb/influxdb08/helper.py

raw ◀ ▶
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 """Helper class for InfluxDB for v0.8."""
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 warnings import warn
11
12
13
14 class SeriesHelper(object):
15 """Define the SeriesHelper object for InfluxDB v0.8.
16
17 Subclassing this helper eases writing data points in bulk.
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
22 Annotated example::
23
24 class MySeriesHelper(SeriesHelper):
25 class Meta:
26 # Meta class stores time series helper configuration.
27 series_name = 'events.stats.{server_name}'
28 # Series name must be a string, curly brackets for dynamic use.
29 fields = ['time', 'server_name']
30 # Defines all the fields in this time series.
31 ### Following attributes are optional. ###
32 client = TestSeriesHelper.client
33 # Client should be an instance of InfluxDBClient.
34 :warning: Only used if autocommit is True.
35 bulk_size = 5
36 # Defines the number of data points to write simultaneously.
37 # Only applicable if autocommit is True.
38 autocommit = True
39 # If True and no bulk_size, then will set bulk_size to 1.
40
41 """
42
43 __initialized__ = False
44
45 def __new__(cls, *args, **kwargs):
46 """Initialize class attributes for subsequent constructor calls.
47
48 :note: *args and **kwargs are not explicitly used in this function,
49 but needed for Python 2 compatibility.
50 """
51 if not cls.__initialized__:
52 cls.__initialized__ = True
53 try:
54 _meta = getattr(cls, 'Meta')
55 except AttributeError:
56 raise AttributeError(
57 'Missing Meta class in {0}.'.format(
58 cls.__name__))
59
60 for attr in ['series_name', 'fields']:
61 try:
62 setattr(cls, '_' + attr, getattr(_meta, attr))
63 except AttributeError:
64 raise AttributeError(
65 'Missing {0} in {1} Meta class.'.format(
66 attr,
67 cls.__name__))
68
69 cls._autocommit = getattr(_meta, 'autocommit', False)
70
71 cls._client = getattr(_meta, 'client', None)
72 if cls._autocommit and not cls._client:
73 raise AttributeError(
74 'In {0}, autocommit is set to True, but no client is set.'
75 .format(cls.__name__))
76
77 try:
78 cls._bulk_size = getattr(_meta, 'bulk_size')
79 if cls._bulk_size < 1 and cls._autocommit:
80 warn(
81 'Definition of bulk_size in {0} forced to 1, '
82 'was less than 1.'.format(cls.__name__))
83 cls._bulk_size = 1
84 except AttributeError:
85 cls._bulk_size = -1
86 else:
87 if not cls._autocommit:
88 warn(
89 'Definition of bulk_size in {0} has no affect because'
90 ' autocommit is false.'.format(cls.__name__))
91
92 cls._datapoints = defaultdict(list)
93 cls._type = namedtuple(cls.__name__, cls._fields)
94
95 return super(SeriesHelper, cls).__new__(cls)
96
97 def __init__(self, **kw):
98 """Create a new data point.
99
100 All fields must be present.
101
102 :note: Data points written when `bulk_size` is reached per Helper.
103 :warning: Data points are *immutable* (`namedtuples`).
104 """
105 cls = self.__class__
106
107 if sorted(cls._fields) != sorted(kw.keys()):
108 raise NameError(
109 'Expected {0}, got {1}.'.format(
110 cls._fields,
111 kw.keys()))
112
113 cls._datapoints[cls._series_name.format(**kw)].append(cls._type(**kw))
114
115 if cls._autocommit and \
116 sum(len(series) for series in cls._datapoints.values()) \
117 >= cls._bulk_size:
118 cls.commit()
119
120 @classmethod
121 def commit(cls, client=None):
122 """Commit everything from datapoints via the client.
123
124 :param client: InfluxDBClient instance for writing points to InfluxDB.
125 :attention: any provided client will supersede the class client.
126 :return: result of client.write_points.
127 """
128 if not client:
129 client = cls._client
130 rtn = client.write_points(cls._json_body_())
131 cls._reset_()
132 return rtn
133
134 @classmethod
135 def _json_body_(cls):
136 """Return JSON body of the datapoints.
137
138 :return: JSON body of the datapoints.
139 """
140 json = []
141 if not cls.__initialized__:
142 cls._reset_()
•143 for series_name, data in cls._datapoints.items():
144 json.append({'name': series_name,
145 'columns': cls._fields,
146 'points': [[getattr(point, k) for k in cls._fields]
147 for point in data]
148 })
149 return json
150
151 @classmethod
152 def _reset_(cls):
153 """Reset data storage."""
154 cls._datapoints = defaultdict(list)