Debian Codegraph @

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