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