| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""Python client 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 |
import datetime |
| 10 |
import gzip |
| 11 |
import itertools |
| 12 |
import io |
| 13 |
import json |
| 14 |
import random |
| 15 |
import socket |
| 16 |
import struct |
| 17 |
import time |
| 18 |
from itertools import chain, islice |
| 19 |
|
| 20 |
import msgpack |
| 21 |
import requests |
| 22 |
import requests.exceptions |
| 23 |
from requests.adapters import HTTPAdapter |
| 24 |
from six.moves.urllib.parse import urlparse |
| 25 |
|
| 26 |
from influxdb.line_protocol import make_lines, quote_ident, quote_literal |
| 27 |
from influxdb.resultset import ResultSet |
| 28 |
from .exceptions import InfluxDBClientError |
| 29 |
from .exceptions import InfluxDBServerError |
| 30 |
|
| 31 |
|
| 32 |
class InfluxDBClient(object): |
| 33 |
"""InfluxDBClient primary client object to connect InfluxDB. |
| 34 |
|
| 35 |
The :class:`~.InfluxDBClient` object holds information necessary to |
| 36 |
connect to InfluxDB. Requests can be made to InfluxDB directly through |
| 37 |
the client. |
| 38 |
|
| 39 |
The client supports the use as a `context manager |
| 40 |
<https://docs.python.org/3/reference/datamodel.html#context-managers>`_. |
| 41 |
|
| 42 |
:param host: hostname to connect to InfluxDB, defaults to 'localhost' |
| 43 |
:type host: str |
| 44 |
:param port: port to connect to InfluxDB, defaults to 8086 |
| 45 |
:type port: int |
| 46 |
:param username: user to connect, defaults to 'root' |
| 47 |
:type username: str |
| 48 |
:param password: password of the user, defaults to 'root' |
| 49 |
:type password: str |
| 50 |
:param pool_size: urllib3 connection pool size, defaults to 10. |
| 51 |
:type pool_size: int |
| 52 |
:param database: database name to connect to, defaults to None |
| 53 |
:type database: str |
| 54 |
:param ssl: use https instead of http to connect to InfluxDB, defaults to |
| 55 |
False |
| 56 |
:type ssl: bool |
| 57 |
:param verify_ssl: verify SSL certificates for HTTPS requests, defaults to |
| 58 |
False |
| 59 |
:type verify_ssl: bool |
| 60 |
:param timeout: number of seconds Requests will wait for your client to |
| 61 |
establish a connection, defaults to None |
| 62 |
:type timeout: int |
| 63 |
:param retries: number of attempts your client will make before aborting, |
| 64 |
defaults to 3 |
| 65 |
0 - try until success |
| 66 |
1 - attempt only once (without retry) |
| 67 |
2 - maximum two attempts (including one retry) |
| 68 |
3 - maximum three attempts (default option) |
| 69 |
:type retries: int |
| 70 |
:param use_udp: use UDP to connect to InfluxDB, defaults to False |
| 71 |
:type use_udp: bool |
| 72 |
:param udp_port: UDP port to connect to InfluxDB, defaults to 4444 |
| 73 |
:type udp_port: int |
| 74 |
:param proxies: HTTP(S) proxy to use for Requests, defaults to {} |
| 75 |
:type proxies: dict |
| 76 |
:param path: path of InfluxDB on the server to connect, defaults to '' |
| 77 |
:type path: str |
| 78 |
:param cert: Path to client certificate information to use for mutual TLS |
| 79 |
authentication. You can specify a local cert to use |
| 80 |
as a single file containing the private key and the certificate, or as |
| 81 |
a tuple of both files’ paths, defaults to None |
| 82 |
:type cert: str |
| 83 |
:param gzip: use gzip content encoding to compress requests |
| 84 |
:type gzip: bool |
| 85 |
:param session: allow for the new client request to use an existing |
| 86 |
requests Session, defaults to None |
| 87 |
:type session: requests.Session |
| 88 |
:param headers: headers to add to Requests, will add 'Content-Type' |
| 89 |
and 'Accept' unless these are already present, defaults to {} |
| 90 |
:type headers: dict |
| 91 |
:param socket_options: use custom tcp socket options, |
| 92 |
If not specified, then defaults are loaded from |
| 93 |
``HTTPConnection.default_socket_options`` |
| 94 |
:type socket_options: list |
| 95 |
|
| 96 |
:raises ValueError: if cert is provided but ssl is disabled (set to False) |
| 97 |
""" |
| 98 |
|
| 99 |
def __init__(self, |
| 100 |
host='localhost', |
| 101 |
port=8086, |
| 102 |
username='root', |
| 103 |
password='root', |
| 104 |
database=None, |
| 105 |
ssl=False, |
| 106 |
verify_ssl=False, |
| 107 |
timeout=None, |
| 108 |
retries=3, |
| 109 |
use_udp=False, |
| 110 |
udp_port=4444, |
| 111 |
proxies=None, |
| 112 |
pool_size=10, |
| 113 |
path='', |
| 114 |
cert=None, |
| 115 |
gzip=False, |
| 116 |
session=None, |
| 117 |
headers=None, |
| 118 |
socket_options=None, |
| 119 |
): |
| 120 |
"""Construct a new InfluxDBClient object.""" |
| 121 |
self.__host = host |
| 122 |
self.__port = int(port) |
| 123 |
self._username = username |
| 124 |
self._password = password |
| 125 |
self._database = database |
| 126 |
self._timeout = timeout |
| 127 |
self._retries = retries |
| 128 |
|
| 129 |
self._verify_ssl = verify_ssl |
| 130 |
|
| 131 |
self.__use_udp = use_udp |
| 132 |
self.__udp_port = int(udp_port) |
| 133 |
|
| 134 |
if not session: |
| 135 |
session = requests.Session() |
| 136 |
|
| 137 |
self._session = session |
| 138 |
adapter = _SocketOptionsAdapter( |
| 139 |
pool_connections=int(pool_size), |
| 140 |
pool_maxsize=int(pool_size), |
| 141 |
socket_options=socket_options |
| 142 |
) |
| 143 |
|
| 144 |
if use_udp: |
| 145 |
self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 146 |
|
| 147 |
if not path: |
| 148 |
self.__path = '' |
| 149 |
elif path[0] == '/': |
| 150 |
self.__path = path |
| 151 |
else: |
| 152 |
self.__path = '/' + path |
| 153 |
|
| 154 |
self._scheme = "http" |
| 155 |
|
| 156 |
if ssl is True: |
| 157 |
self._scheme = "https" |
| 158 |
|
| 159 |
self._session.mount(self._scheme + '://', adapter) |
| 160 |
|
| 161 |
if proxies is None: |
| 162 |
self._proxies = {} |
| 163 |
else: |
| 164 |
self._proxies = proxies |
| 165 |
|
| 166 |
if cert: |
| 167 |
if not ssl: |
| 168 |
raise ValueError( |
| 169 |
"Client certificate provided but ssl is disabled." |
| 170 |
) |
| 171 |
else: |
| 172 |
self._session.cert = cert |
| 173 |
|
| 174 |
self.__baseurl = "{0}://{1}:{2}{3}".format( |
| 175 |
self._scheme, |
| 176 |
self._host, |
| 177 |
self._port, |
| 178 |
self._path) |
| 179 |
|
| 180 |
if headers is None: |
| 181 |
headers = {} |
| 182 |
headers.setdefault('Content-Type', 'application/json') |
| 183 |
headers.setdefault('Accept', 'application/x-msgpack') |
| 184 |
self._headers = headers |
| 185 |
|
| 186 |
self._gzip = gzip |
| 187 |
|
| 188 |
def __enter__(self): |
| 189 |
"""Enter function as used by context manager.""" |
| 190 |
return self |
| 191 |
|
| 192 |
def __exit__(self, _exc_type, _exc_value, _traceback): |
| 193 |
"""Exit function as used by context manager.""" |
| 194 |
self.close() |
| 195 |
|
| 196 |
@property |
| 197 |
def _baseurl(self): |
| 198 |
return self.__baseurl |
| 199 |
|
| 200 |
@property |
| 201 |
def _host(self): |
| 202 |
return self.__host |
| 203 |
|
| 204 |
@property |
| 205 |
def _port(self): |
| 206 |
return self.__port |
| 207 |
|
| 208 |
@property |
| 209 |
def _path(self): |
| 210 |
return self.__path |
| 211 |
|
| 212 |
@property |
| 213 |
def _udp_port(self): |
| 214 |
return self.__udp_port |
| 215 |
|
| 216 |
@property |
| 217 |
def _use_udp(self): |
| 218 |
return self.__use_udp |
| 219 |
|
| 220 |
@classmethod |
| 221 |
def from_dsn(cls, dsn, **kwargs): |
| 222 |
r"""Generate an instance of InfluxDBClient from given data source name. |
| 223 |
|
| 224 |
Return an instance of :class:`~.InfluxDBClient` from the provided |
| 225 |
data source name. Supported schemes are "influxdb", "https+influxdb" |
| 226 |
and "udp+influxdb". Parameters for the :class:`~.InfluxDBClient` |
| 227 |
constructor may also be passed to this method. |
| 228 |
|
| 229 |
:param dsn: data source name |
| 230 |
:type dsn: string |
| 231 |
:param kwargs: additional parameters for `InfluxDBClient` |
| 232 |
:type kwargs: dict |
| 233 |
:raises ValueError: if the provided DSN has any unexpected values |
| 234 |
|
| 235 |
:Example: |
| 236 |
|
| 237 |
:: |
| 238 |
|
| 239 |
>> cli = InfluxDBClient.from_dsn('influxdb://username:password@\ |
| 240 |
localhost:8086/databasename', timeout=5) |
| 241 |
>> type(cli) |
| 242 |
<class 'influxdb.client.InfluxDBClient'> |
| 243 |
>> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\ |
| 244 |
localhost:8086/databasename', timeout=5, udp_port=159) |
| 245 |
>> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli)) |
| 246 |
http://localhost:8086 - True 159 |
| 247 |
|
| 248 |
.. note:: parameters provided in `**kwargs` may override dsn parameters |
| 249 |
.. note:: when using "udp+influxdb" the specified port (if any) will |
| 250 |
be used for the TCP connection; specify the UDP port with the |
| 251 |
additional `udp_port` parameter (cf. examples). |
| 252 |
""" |
| 253 |
init_args = _parse_dsn(dsn) |
| 254 |
host, port = init_args.pop('hosts')[0] |
| 255 |
init_args['host'] = host |
| 256 |
init_args['port'] = port |
| 257 |
init_args.update(kwargs) |
| 258 |
|
| 259 |
return cls(**init_args) |
| 260 |
|
| 261 |
def switch_database(self, database): |
| 262 |
"""Change the client's database. |
| 263 |
|
| 264 |
:param database: the name of the database to switch to |
| 265 |
:type database: str |
| 266 |
""" |
| 267 |
self._database = database |
| 268 |
|
| 269 |
def switch_user(self, username, password): |
| 270 |
"""Change the client's username. |
| 271 |
|
| 272 |
:param username: the username to switch to |
| 273 |
:type username: str |
| 274 |
:param password: the password for the username |
| 275 |
:type password: str |
| 276 |
""" |
| 277 |
self._username = username |
| 278 |
self._password = password |
| 279 |
|
| 280 |
def request(self, url, method='GET', params=None, data=None, stream=False, |
| 281 |
expected_response_code=200, headers=None): |
| 282 |
"""Make a HTTP request to the InfluxDB API. |
| 283 |
|
| 284 |
:param url: the path of the HTTP request, e.g. write, query, etc. |
| 285 |
:type url: str |
| 286 |
:param method: the HTTP method for the request, defaults to GET |
| 287 |
:type method: str |
| 288 |
:param params: additional parameters for the request, defaults to None |
| 289 |
:type params: dict |
| 290 |
:param data: the data of the request, defaults to None |
| 291 |
:type data: str |
| 292 |
:param stream: True if a query uses chunked responses |
| 293 |
:type stream: bool |
| 294 |
:param expected_response_code: the expected response code of |
| 295 |
the request, defaults to 200 |
| 296 |
:type expected_response_code: int |
| 297 |
:param headers: headers to add to the request |
| 298 |
:type headers: dict |
| 299 |
:returns: the response from the request |
| 300 |
:rtype: :class:`requests.Response` |
| 301 |
:raises InfluxDBServerError: if the response code is any server error |
| 302 |
code (5xx) |
| 303 |
:raises InfluxDBClientError: if the response code is not the |
| 304 |
same as `expected_response_code` and is not a server error code |
| 305 |
""" |
| 306 |
url = "{0}/{1}".format(self._baseurl, url) |
| 307 |
|
| 308 |
if headers is None: |
| 309 |
headers = self._headers |
| 310 |
|
| 311 |
if params is None: |
| 312 |
params = {} |
| 313 |
|
| 314 |
if isinstance(data, (dict, list)): |
| 315 |
data = json.dumps(data) |
| 316 |
|
| 317 |
if self._gzip: |
| 318 |
# Receive and send compressed data |
| 319 |
headers.update({ |
| 320 |
'Accept-Encoding': 'gzip', |
| 321 |
'Content-Encoding': 'gzip', |
| 322 |
}) |
| 323 |
if data is not None: |
| 324 |
# For Py 2.7 compatability use Gzipfile |
| 325 |
compressed = io.BytesIO() |
| 326 |
with gzip.GzipFile( |
| 327 |
compresslevel=9, |
| 328 |
fileobj=compressed, |
| 329 |
mode='w' |
| 330 |
) as f: |
| 331 |
f.write(data) |
| 332 |
data = compressed.getvalue() |
| 333 |
|
| 334 |
# Try to send the request more than once by default (see #103) |
| 335 |
retry = True |
| 336 |
_try = 0 |
| 337 |
while retry: |
| 338 |
try: |
| 339 |
if "Authorization" in headers: |
| 340 |
auth = (None, None) |
| 341 |
else: |
| 342 |
auth = (self._username, self._password) |
| 343 |
response = self._session.request( |
| 344 |
method=method, |
| 345 |
url=url, |
| 346 |
auth=auth if None not in auth else None, |
| 347 |
params=params, |
| 348 |
data=data, |
| 349 |
stream=stream, |
| 350 |
headers=headers, |
| 351 |
proxies=self._proxies, |
| 352 |
verify=self._verify_ssl, |
| 353 |
timeout=self._timeout |
| 354 |
) |
| 355 |
break |
| 356 |
except (requests.exceptions.ConnectionError, |
| 357 |
requests.exceptions.HTTPError, |
| 358 |
requests.exceptions.Timeout): |
| 359 |
_try += 1 |
| 360 |
if self._retries != 0: |
| 361 |
retry = _try < self._retries |
| 362 |
if not retry: |
| 363 |
raise |
| 364 |
if method == "POST": |
| 365 |
time.sleep((2 ** _try) * random.random() / 100.0) |
| 366 |
|
| 367 |
type_header = response.headers and response.headers.get("Content-Type") |
| 368 |
if type_header == "application/x-msgpack" and response.content: |
| 369 |
response._msgpack = msgpack.unpackb( |
| 370 |
packed=response.content, |
| 371 |
ext_hook=_msgpack_parse_hook, |
| 372 |
raw=False) |
| 373 |
else: |
| 374 |
response._msgpack = None |
| 375 |
|
| 376 |
def reformat_error(response): |
| 377 |
if response._msgpack: |
| 378 |
return json.dumps(response._msgpack, separators=(',', ':')) |
| 379 |
else: |
| 380 |
return response.content |
| 381 |
|
| 382 |
# if there's not an error, there must have been a successful response |
| 383 |
if 500 <= response.status_code < 600: |
| 384 |
raise InfluxDBServerError(reformat_error(response)) |
| 385 |
elif response.status_code == expected_response_code: |
| 386 |
return response |
| 387 |
else: |
| 388 |
err_msg = reformat_error(response) |
| 389 |
raise InfluxDBClientError(err_msg, response.status_code) |
| 390 |
|
| 391 |
def write(self, data, params=None, expected_response_code=204, |
| 392 |
protocol='json'): |
| 393 |
"""Write data to InfluxDB. |
| 394 |
|
| 395 |
:param data: the data to be written |
| 396 |
:type data: (if protocol is 'json') dict |
| 397 |
(if protocol is 'line') sequence of line protocol strings |
| 398 |
or single string |
| 399 |
:param params: additional parameters for the request, defaults to None |
| 400 |
:type params: dict |
| 401 |
:param expected_response_code: the expected response code of the write |
| 402 |
operation, defaults to 204 |
| 403 |
:type expected_response_code: int |
| 404 |
:param protocol: protocol of input data, either 'json' or 'line' |
| 405 |
:type protocol: str |
| 406 |
:returns: True, if the write operation is successful |
| 407 |
:rtype: bool |
| 408 |
""" |
| 409 |
headers = self._headers.copy() |
| 410 |
headers['Content-Type'] = 'application/octet-stream' |
| 411 |
|
| 412 |
if params: |
| 413 |
precision = params.get('precision') |
| 414 |
else: |
| 415 |
precision = None |
| 416 |
|
| 417 |
if protocol == 'json': |
| 418 |
data = make_lines(data, precision).encode('utf-8') |
| 419 |
elif protocol == 'line': |
| 420 |
if isinstance(data, str): |
| 421 |
data = [data] |
| 422 |
data = ('\n'.join(data) + '\n').encode('utf-8') |
| 423 |
|
| 424 |
self.request( |
| 425 |
url="write", |
| 426 |
method='POST', |
| 427 |
params=params, |
| 428 |
data=data, |
| 429 |
expected_response_code=expected_response_code, |
| 430 |
headers=headers |
| 431 |
) |
| 432 |
return True |
| 433 |
|
| 434 |
@staticmethod |
| 435 |
def _read_chunked_response(response, raise_errors=True): |
| 436 |
for line in response.iter_lines(): |
| 437 |
if isinstance(line, bytes): |
| 438 |
line = line.decode('utf-8') |
| 439 |
data = json.loads(line) |
| 440 |
result_set = {} |
| 441 |
for result in data.get('results', []): |
| 442 |
for _key in result: |
| 443 |
if isinstance(result[_key], list): |
| 444 |
result_set.setdefault( |
| 445 |
_key, []).extend(result[_key]) |
| 446 |
yield ResultSet(result_set, raise_errors=raise_errors) |
| 447 |
|
| 448 |
def query(self, |
| 449 |
query, |
| 450 |
params=None, |
| 451 |
bind_params=None, |
| 452 |
epoch=None, |
| 453 |
expected_response_code=200, |
| 454 |
database=None, |
| 455 |
raise_errors=True, |
| 456 |
chunked=False, |
| 457 |
chunk_size=0, |
| 458 |
method="GET"): |
| 459 |
"""Send a query to InfluxDB. |
| 460 |
|
| 461 |
.. danger:: |
| 462 |
In order to avoid injection vulnerabilities (similar to `SQL |
| 463 |
injection <https://www.owasp.org/index.php/SQL_Injection>`_ |
| 464 |
vulnerabilities), do not directly include untrusted data into the |
| 465 |
``query`` parameter, use ``bind_params`` instead. |
| 466 |
|
| 467 |
:param query: the actual query string |
| 468 |
:type query: str |
| 469 |
|
| 470 |
:param params: additional parameters for the request, |
| 471 |
defaults to {} |
| 472 |
:type params: dict |
| 473 |
|
| 474 |
:param bind_params: bind parameters for the query: |
| 475 |
any variable in the query written as ``'$var_name'`` will be |
| 476 |
replaced with ``bind_params['var_name']``. Only works in the |
| 477 |
``WHERE`` clause and takes precedence over ``params['params']`` |
| 478 |
:type bind_params: dict |
| 479 |
|
| 480 |
:param epoch: response timestamps to be in epoch format either 'h', |
| 481 |
'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is |
| 482 |
RFC3339 UTC format with nanosecond precision |
| 483 |
:type epoch: str |
| 484 |
|
| 485 |
:param expected_response_code: the expected status code of response, |
| 486 |
defaults to 200 |
| 487 |
:type expected_response_code: int |
| 488 |
|
| 489 |
:param database: database to query, defaults to None |
| 490 |
:type database: str |
| 491 |
|
| 492 |
:param raise_errors: Whether or not to raise exceptions when InfluxDB |
| 493 |
returns errors, defaults to True |
| 494 |
:type raise_errors: bool |
| 495 |
|
| 496 |
:param chunked: Enable to use chunked responses from InfluxDB. |
| 497 |
With ``chunked`` enabled, one ResultSet is returned per chunk |
| 498 |
containing all results within that chunk |
| 499 |
:type chunked: bool |
| 500 |
|
| 501 |
:param chunk_size: Size of each chunk to tell InfluxDB to use. |
| 502 |
:type chunk_size: int |
| 503 |
|
| 504 |
:param method: the HTTP method for the request, defaults to GET |
| 505 |
:type method: str |
| 506 |
|
| 507 |
:returns: the queried data |
| 508 |
:rtype: :class:`~.ResultSet` |
| 509 |
""" |
| 510 |
if params is None: |
| 511 |
params = {} |
| 512 |
|
| 513 |
if bind_params is not None: |
| 514 |
params_dict = json.loads(params.get('params', '{}')) |
| 515 |
params_dict.update(bind_params) |
| 516 |
params['params'] = json.dumps(params_dict) |
| 517 |
|
| 518 |
params['q'] = query |
| 519 |
params['db'] = database or self._database |
| 520 |
|
| 521 |
if epoch is not None: |
| 522 |
params['epoch'] = epoch |
| 523 |
|
| 524 |
if chunked: |
| 525 |
params['chunked'] = 'true' |
| 526 |
if chunk_size > 0: |
| 527 |
params['chunk_size'] = chunk_size |
| 528 |
|
| 529 |
if query.lower().startswith("select ") and " into " in query.lower(): |
| 530 |
method = "POST" |
| 531 |
|
| 532 |
response = self.request( |
| 533 |
url="query", |
| 534 |
method=method, |
| 535 |
params=params, |
| 536 |
data=None, |
| 537 |
stream=chunked, |
| 538 |
expected_response_code=expected_response_code |
| 539 |
) |
| 540 |
|
| 541 |
data = response._msgpack |
| 542 |
if not data: |
| 543 |
if chunked: |
| 544 |
return self._read_chunked_response(response) |
| 545 |
data = response.json() |
| 546 |
|
| 547 |
results = [ |
| 548 |
ResultSet(result, raise_errors=raise_errors) |
| 549 |
for result |
| 550 |
in data.get('results', []) |
| 551 |
] |
| 552 |
|
| 553 |
# TODO(aviau): Always return a list. (This would be a breaking change) |
| 554 |
if len(results) == 1: |
| 555 |
return results[0] |
| 556 |
|
| 557 |
return results |
| 558 |
|
| 559 |
def write_points(self, |
| 560 |
points, |
| 561 |
time_precision=None, |
| 562 |
database=None, |
| 563 |
retention_policy=None, |
| 564 |
tags=None, |
| 565 |
batch_size=None, |
| 566 |
protocol='json', |
| 567 |
consistency=None |
| 568 |
): |
| 569 |
"""Write to multiple time series names. |
| 570 |
|
| 571 |
:param points: the list of points to be written in the database |
| 572 |
:type points: list of dictionaries, each dictionary represents a point |
| 573 |
:type points: (if protocol is 'json') list of dicts, where each dict |
| 574 |
represents a point. |
| 575 |
(if protocol is 'line') sequence of line protocol strings. |
| 576 |
:param time_precision: Either 's', 'm', 'ms' or 'u', defaults to None |
| 577 |
:type time_precision: str |
| 578 |
:param database: the database to write the points to. Defaults to |
| 579 |
the client's current database |
| 580 |
:type database: str |
| 581 |
:param tags: a set of key-value pairs associated with each point. Both |
| 582 |
keys and values must be strings. These are shared tags and will be |
| 583 |
merged with point-specific tags, defaults to None |
| 584 |
:type tags: dict |
| 585 |
:param retention_policy: the retention policy for the points. Defaults |
| 586 |
to None |
| 587 |
:type retention_policy: str |
| 588 |
:param batch_size: value to write the points in batches |
| 589 |
instead of all at one time. Useful for when doing data dumps from |
| 590 |
one database to another or when doing a massive write operation, |
| 591 |
defaults to None |
| 592 |
:type batch_size: int |
| 593 |
:param protocol: Protocol for writing data. Either 'line' or 'json'. |
| 594 |
:type protocol: str |
| 595 |
:param consistency: Consistency for the points. |
| 596 |
One of {'any','one','quorum','all'}. |
| 597 |
:type consistency: str |
| 598 |
:returns: True, if the operation is successful |
| 599 |
:rtype: bool |
| 600 |
|
| 601 |
.. note:: if no retention policy is specified, the default retention |
| 602 |
policy for the database is used |
| 603 |
""" |
| 604 |
if batch_size and batch_size > 0: |
| 605 |
for batch in self._batches(points, batch_size): |
| 606 |
self._write_points(points=batch, |
| 607 |
time_precision=time_precision, |
| 608 |
database=database, |
| 609 |
retention_policy=retention_policy, |
| 610 |
tags=tags, protocol=protocol, |
| 611 |
consistency=consistency) |
| 612 |
return True |
| 613 |
|
| 614 |
return self._write_points(points=points, |
| 615 |
time_precision=time_precision, |
| 616 |
database=database, |
| 617 |
retention_policy=retention_policy, |
| 618 |
tags=tags, protocol=protocol, |
| 619 |
consistency=consistency) |
| 620 |
|
| 621 |
def ping(self): |
| 622 |
"""Check connectivity to InfluxDB. |
| 623 |
|
| 624 |
:returns: The version of the InfluxDB the client is connected to |
| 625 |
""" |
| 626 |
response = self.request( |
| 627 |
url="ping", |
| 628 |
method='GET', |
| 629 |
expected_response_code=204 |
| 630 |
) |
| 631 |
|
| 632 |
return response.headers['X-Influxdb-Version'] |
| 633 |
|
| 634 |
@staticmethod |
| 635 |
def _batches(iterable, size): |
| 636 |
# Iterate over an iterable producing iterables of batches. Based on: |
| 637 |
# http://code.activestate.com/recipes/303279-getting-items-in-batches/ |
| 638 |
iterator = iter(iterable) |
| 639 |
while True: |
| 640 |
try: # Try get the first element in the iterator... |
| 641 |
head = (next(iterator),) |
| 642 |
except StopIteration: |
| 643 |
return # ...so that we can stop if there isn't one |
| 644 |
# Otherwise, lazily slice the rest of the batch |
| 645 |
rest = islice(iterator, size - 1) |
| 646 |
yield chain(head, rest) |
| 647 |
|
| 648 |
def _write_points(self, |
| 649 |
points, |
| 650 |
time_precision, |
| 651 |
database, |
| 652 |
retention_policy, |
| 653 |
tags, |
| 654 |
protocol='json', |
| 655 |
consistency=None): |
| 656 |
if time_precision not in ['n', 'u', 'ms', 's', 'm', 'h', None]: |
| 657 |
raise ValueError( |
| 658 |
"Invalid time precision is given. " |
| 659 |
"(use 'n', 'u', 'ms', 's', 'm' or 'h')") |
| 660 |
|
| 661 |
if consistency not in ['any', 'one', 'quorum', 'all', None]: |
| 662 |
raise ValueError('Invalid consistency: {}'.format(consistency)) |
| 663 |
|
| 664 |
if protocol == 'json': |
| 665 |
data = { |
| 666 |
'points': points |
| 667 |
} |
| 668 |
|
| 669 |
if tags is not None: |
| 670 |
data['tags'] = tags |
| 671 |
else: |
| 672 |
data = points |
| 673 |
|
| 674 |
params = { |
| 675 |
'db': database or self._database |
| 676 |
} |
| 677 |
|
| 678 |
if consistency is not None: |
| 679 |
params['consistency'] = consistency |
| 680 |
|
| 681 |
if time_precision is not None: |
| 682 |
params['precision'] = time_precision |
| 683 |
|
| 684 |
if retention_policy is not None: |
| 685 |
params['rp'] = retention_policy |
| 686 |
|
| 687 |
if self._use_udp: |
| 688 |
self.send_packet( |
| 689 |
data, protocol=protocol, time_precision=time_precision |
| 690 |
) |
| 691 |
else: |
| 692 |
self.write( |
| 693 |
data=data, |
| 694 |
params=params, |
| 695 |
expected_response_code=204, |
| 696 |
protocol=protocol |
| 697 |
) |
| 698 |
|
| 699 |
return True |
| 700 |
|
| 701 |
def get_list_database(self): |
| 702 |
"""Get the list of databases in InfluxDB. |
| 703 |
|
| 704 |
:returns: all databases in InfluxDB |
| 705 |
:rtype: list of dictionaries |
| 706 |
|
| 707 |
:Example: |
| 708 |
|
| 709 |
:: |
| 710 |
|
| 711 |
>> dbs = client.get_list_database() |
| 712 |
>> dbs |
| 713 |
[{u'name': u'db1'}, {u'name': u'db2'}, {u'name': u'db3'}] |
| 714 |
""" |
| 715 |
return list(self.query("SHOW DATABASES").get_points()) |
| 716 |
|
| 717 |
def get_list_series(self, database=None, measurement=None, tags=None): |
| 718 |
""" |
| 719 |
Query SHOW SERIES returns the distinct series in your database. |
| 720 |
|
| 721 |
FROM and WHERE clauses are optional. |
| 722 |
|
| 723 |
:param measurement: Show all series from a measurement |
| 724 |
:type id: string |
| 725 |
:param tags: Show all series that match given tags |
| 726 |
:type id: dict |
| 727 |
:param database: the database from which the series should be |
| 728 |
shows, defaults to client's current database |
| 729 |
:type database: str |
| 730 |
""" |
| 731 |
database = database or self._database |
| 732 |
query_str = 'SHOW SERIES' |
| 733 |
|
| 734 |
if measurement: |
| 735 |
query_str += ' FROM "{0}"'.format(measurement) |
| 736 |
|
| 737 |
if tags: |
| 738 |
query_str += ' WHERE ' + ' and '.join(["{0}='{1}'".format(k, v) |
| 739 |
for k, v in tags.items()]) |
| 740 |
|
| 741 |
return list( |
| 742 |
itertools.chain.from_iterable( |
| 743 |
[ |
| 744 |
x.values() |
| 745 |
for x in (self.query(query_str, database=database) |
| 746 |
.get_points()) |
| 747 |
] |
| 748 |
) |
| 749 |
) |
| 750 |
|
| 751 |
def create_database(self, dbname): |
| 752 |
"""Create a new database in InfluxDB. |
| 753 |
|
| 754 |
:param dbname: the name of the database to create |
| 755 |
:type dbname: str |
| 756 |
""" |
| 757 |
self.query("CREATE DATABASE {0}".format(quote_ident(dbname)), |
| 758 |
method="POST") |
| 759 |
|
| 760 |
def drop_database(self, dbname): |
| 761 |
"""Drop a database from InfluxDB. |
| 762 |
|
| 763 |
:param dbname: the name of the database to drop |
| 764 |
:type dbname: str |
| 765 |
""" |
| 766 |
self.query("DROP DATABASE {0}".format(quote_ident(dbname)), |
| 767 |
method="POST") |
| 768 |
|
| 769 |
def get_list_measurements(self): |
| 770 |
"""Get the list of measurements in InfluxDB. |
| 771 |
|
| 772 |
:returns: all measurements in InfluxDB |
| 773 |
:rtype: list of dictionaries |
| 774 |
|
| 775 |
:Example: |
| 776 |
|
| 777 |
:: |
| 778 |
|
| 779 |
>> dbs = client.get_list_measurements() |
| 780 |
>> dbs |
| 781 |
[{u'name': u'measurements1'}, |
| 782 |
{u'name': u'measurements2'}, |
| 783 |
{u'name': u'measurements3'}] |
| 784 |
""" |
| 785 |
return list(self.query("SHOW MEASUREMENTS").get_points()) |
| 786 |
|
| 787 |
def drop_measurement(self, measurement): |
| 788 |
"""Drop a measurement from InfluxDB. |
| 789 |
|
| 790 |
:param measurement: the name of the measurement to drop |
| 791 |
:type measurement: str |
| 792 |
""" |
| 793 |
self.query("DROP MEASUREMENT {0}".format(quote_ident(measurement)), |
| 794 |
method="POST") |
| 795 |
|
| 796 |
def create_retention_policy(self, name, duration, replication, |
| 797 |
database=None, |
| 798 |
default=False, shard_duration="0s"): |
| 799 |
"""Create a retention policy for a database. |
| 800 |
|
| 801 |
:param name: the name of the new retention policy |
| 802 |
:type name: str |
| 803 |
:param duration: the duration of the new retention policy. |
| 804 |
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported |
| 805 |
and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks, |
| 806 |
respectively. For infinite retention - meaning the data will |
| 807 |
never be deleted - use 'INF' for duration. |
| 808 |
The minimum retention period is 1 hour. |
| 809 |
:type duration: str |
| 810 |
:param replication: the replication of the retention policy |
| 811 |
:type replication: str |
| 812 |
:param database: the database for which the retention policy is |
| 813 |
created. Defaults to current client's database |
| 814 |
:type database: str |
| 815 |
:param default: whether or not to set the policy as default |
| 816 |
:type default: bool |
| 817 |
:param shard_duration: the shard duration of the retention policy. |
| 818 |
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported and |
| 819 |
mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks, |
| 820 |
respectively. Infinite retention is not supported. As a workaround, |
| 821 |
specify a "1000w" duration to achieve an extremely long shard group |
| 822 |
duration. Defaults to "0s", which is interpreted by the database |
| 823 |
to mean the default value given the duration. |
| 824 |
The minimum shard group duration is 1 hour. |
| 825 |
:type shard_duration: str |
| 826 |
""" |
| 827 |
query_string = \ |
| 828 |
"CREATE RETENTION POLICY {0} ON {1} " \ |
| 829 |
"DURATION {2} REPLICATION {3} SHARD DURATION {4}".format( |
| 830 |
quote_ident(name), quote_ident(database or self._database), |
| 831 |
duration, replication, shard_duration) |
| 832 |
|
| 833 |
if default is True: |
| 834 |
query_string += " DEFAULT" |
| 835 |
|
| 836 |
self.query(query_string, method="POST") |
| 837 |
|
| 838 |
def alter_retention_policy(self, name, database=None, |
| 839 |
duration=None, replication=None, |
| 840 |
default=None, shard_duration=None): |
| 841 |
"""Modify an existing retention policy for a database. |
| 842 |
|
| 843 |
:param name: the name of the retention policy to modify |
| 844 |
:type name: str |
| 845 |
:param database: the database for which the retention policy is |
| 846 |
modified. Defaults to current client's database |
| 847 |
:type database: str |
| 848 |
:param duration: the new duration of the existing retention policy. |
| 849 |
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported |
| 850 |
and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks, |
| 851 |
respectively. For infinite retention, meaning the data will |
| 852 |
never be deleted, use 'INF' for duration. |
| 853 |
The minimum retention period is 1 hour. |
| 854 |
:type duration: str |
| 855 |
:param replication: the new replication of the existing |
| 856 |
retention policy |
| 857 |
:type replication: int |
| 858 |
:param default: whether or not to set the modified policy as default |
| 859 |
:type default: bool |
| 860 |
:param shard_duration: the shard duration of the retention policy. |
| 861 |
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported and |
| 862 |
mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks, |
| 863 |
respectively. Infinite retention is not supported. As a workaround, |
| 864 |
specify a "1000w" duration to achieve an extremely long shard group |
| 865 |
duration. |
| 866 |
The minimum shard group duration is 1 hour. |
| 867 |
:type shard_duration: str |
| 868 |
|
| 869 |
.. note:: at least one of duration, replication, or default flag |
| 870 |
should be set. Otherwise the operation will fail. |
| 871 |
""" |
| 872 |
query_string = ( |
| 873 |
"ALTER RETENTION POLICY {0} ON {1}" |
| 874 |
).format(quote_ident(name), |
| 875 |
quote_ident(database or self._database)) |
| 876 |
if duration: |
| 877 |
query_string += " DURATION {0}".format(duration) |
| 878 |
if shard_duration: |
| 879 |
query_string += " SHARD DURATION {0}".format(shard_duration) |
| 880 |
if replication: |
| 881 |
query_string += " REPLICATION {0}".format(replication) |
| 882 |
if default is True: |
| 883 |
query_string += " DEFAULT" |
| 884 |
|
| 885 |
self.query(query_string, method="POST") |
| 886 |
|
| 887 |
def drop_retention_policy(self, name, database=None): |
| 888 |
"""Drop an existing retention policy for a database. |
| 889 |
|
| 890 |
:param name: the name of the retention policy to drop |
| 891 |
:type name: str |
| 892 |
:param database: the database for which the retention policy is |
| 893 |
dropped. Defaults to current client's database |
| 894 |
:type database: str |
| 895 |
""" |
| 896 |
query_string = ( |
| 897 |
"DROP RETENTION POLICY {0} ON {1}" |
| 898 |
).format(quote_ident(name), quote_ident(database or self._database)) |
| 899 |
self.query(query_string, method="POST") |
| 900 |
|
| 901 |
def get_list_retention_policies(self, database=None): |
| 902 |
"""Get the list of retention policies for a database. |
| 903 |
|
| 904 |
:param database: the name of the database, defaults to the client's |
| 905 |
current database |
| 906 |
:type database: str |
| 907 |
:returns: all retention policies for the database |
| 908 |
:rtype: list of dictionaries |
| 909 |
|
| 910 |
:Example: |
| 911 |
|
| 912 |
:: |
| 913 |
|
| 914 |
>> ret_policies = client.get_list_retention_policies('my_db') |
| 915 |
>> ret_policies |
| 916 |
[{u'default': True, |
| 917 |
u'duration': u'0', |
| 918 |
u'name': u'default', |
| 919 |
u'replicaN': 1}] |
| 920 |
""" |
| 921 |
if not (database or self._database): |
| 922 |
raise InfluxDBClientError( |
| 923 |
"get_list_retention_policies() requires a database as a " |
| 924 |
"parameter or the client to be using a database") |
| 925 |
|
| 926 |
rsp = self.query( |
| 927 |
"SHOW RETENTION POLICIES ON {0}".format( |
| 928 |
quote_ident(database or self._database)) |
| 929 |
) |
| 930 |
return list(rsp.get_points()) |
| 931 |
|
| 932 |
def get_list_users(self): |
| 933 |
"""Get the list of all users in InfluxDB. |
| 934 |
|
| 935 |
:returns: all users in InfluxDB |
| 936 |
:rtype: list of dictionaries |
| 937 |
|
| 938 |
:Example: |
| 939 |
|
| 940 |
:: |
| 941 |
|
| 942 |
>> users = client.get_list_users() |
| 943 |
>> users |
| 944 |
[{u'admin': True, u'user': u'user1'}, |
| 945 |
{u'admin': False, u'user': u'user2'}, |
| 946 |
{u'admin': False, u'user': u'user3'}] |
| 947 |
""" |
| 948 |
return list(self.query("SHOW USERS").get_points()) |
| 949 |
|
| 950 |
def create_user(self, username, password, admin=False): |
| 951 |
"""Create a new user in InfluxDB. |
| 952 |
|
| 953 |
:param username: the new username to create |
| 954 |
:type username: str |
| 955 |
:param password: the password for the new user |
| 956 |
:type password: str |
| 957 |
:param admin: whether the user should have cluster administration |
| 958 |
privileges or not |
| 959 |
:type admin: boolean |
| 960 |
""" |
| 961 |
text = "CREATE USER {0} WITH PASSWORD {1}".format( |
| 962 |
quote_ident(username), quote_literal(password)) |
| 963 |
if admin: |
| 964 |
text += ' WITH ALL PRIVILEGES' |
| 965 |
self.query(text, method="POST") |
| 966 |
|
| 967 |
def drop_user(self, username): |
| 968 |
"""Drop a user from InfluxDB. |
| 969 |
|
| 970 |
:param username: the username to drop |
| 971 |
:type username: str |
| 972 |
""" |
| 973 |
text = "DROP USER {0}".format(quote_ident(username)) |
| 974 |
self.query(text, method="POST") |
| 975 |
|
| 976 |
def set_user_password(self, username, password): |
| 977 |
"""Change the password of an existing user. |
| 978 |
|
| 979 |
:param username: the username who's password is being changed |
| 980 |
:type username: str |
| 981 |
:param password: the new password for the user |
| 982 |
:type password: str |
| 983 |
""" |
| 984 |
text = "SET PASSWORD FOR {0} = {1}".format( |
| 985 |
quote_ident(username), quote_literal(password)) |
| 986 |
self.query(text) |
| 987 |
|
| 988 |
def delete_series(self, database=None, measurement=None, tags=None): |
| 989 |
"""Delete series from a database. |
| 990 |
|
| 991 |
Series must be filtered by either measurement and tags. |
| 992 |
This method cannot be used to delete all series, use |
| 993 |
`drop_database` instead. |
| 994 |
|
| 995 |
:param database: the database from which the series should be |
| 996 |
deleted, defaults to client's current database |
| 997 |
:type database: str |
| 998 |
:param measurement: Delete all series from a measurement |
| 999 |
:type measurement: str |
| 1000 |
:param tags: Delete all series that match given tags |
| 1001 |
:type tags: dict |
| 1002 |
""" |
| 1003 |
database = database or self._database |
| 1004 |
query_str = 'DROP SERIES' |
| 1005 |
if measurement: |
| 1006 |
query_str += ' FROM {0}'.format(quote_ident(measurement)) |
| 1007 |
|
| 1008 |
if tags: |
| 1009 |
tag_eq_list = ["{0}={1}".format(quote_ident(k), quote_literal(v)) |
| 1010 |
for k, v in tags.items()] |
| 1011 |
query_str += ' WHERE ' + ' AND '.join(tag_eq_list) |
| 1012 |
self.query(query_str, database=database, method="POST") |
| 1013 |
|
| 1014 |
def grant_admin_privileges(self, username): |
| 1015 |
"""Grant cluster administration privileges to a user. |
| 1016 |
|
| 1017 |
:param username: the username to grant privileges to |
| 1018 |
:type username: str |
| 1019 |
|
| 1020 |
.. note:: Only a cluster administrator can create/drop databases |
| 1021 |
and manage users. |
| 1022 |
""" |
| 1023 |
text = "GRANT ALL PRIVILEGES TO {0}".format(quote_ident(username)) |
| 1024 |
self.query(text, method="POST") |
| 1025 |
|
| 1026 |
def revoke_admin_privileges(self, username): |
| 1027 |
"""Revoke cluster administration privileges from a user. |
| 1028 |
|
| 1029 |
:param username: the username to revoke privileges from |
| 1030 |
:type username: str |
| 1031 |
|
| 1032 |
.. note:: Only a cluster administrator can create/ drop databases |
| 1033 |
and manage users. |
| 1034 |
""" |
| 1035 |
text = "REVOKE ALL PRIVILEGES FROM {0}".format(quote_ident(username)) |
| 1036 |
self.query(text, method="POST") |
| 1037 |
|
| 1038 |
def grant_privilege(self, privilege, database, username): |
| 1039 |
"""Grant a privilege on a database to a user. |
| 1040 |
|
| 1041 |
:param privilege: the privilege to grant, one of 'read', 'write' |
| 1042 |
or 'all'. The string is case-insensitive |
| 1043 |
:type privilege: str |
| 1044 |
:param database: the database to grant the privilege on |
| 1045 |
:type database: str |
| 1046 |
:param username: the username to grant the privilege to |
| 1047 |
:type username: str |
| 1048 |
""" |
| 1049 |
text = "GRANT {0} ON {1} TO {2}".format(privilege, |
| 1050 |
quote_ident(database), |
| 1051 |
quote_ident(username)) |
| 1052 |
self.query(text, method="POST") |
| 1053 |
|
| 1054 |
def revoke_privilege(self, privilege, database, username): |
| 1055 |
"""Revoke a privilege on a database from a user. |
| 1056 |
|
| 1057 |
:param privilege: the privilege to revoke, one of 'read', 'write' |
| 1058 |
or 'all'. The string is case-insensitive |
| 1059 |
:type privilege: str |
| 1060 |
:param database: the database to revoke the privilege on |
| 1061 |
:type database: str |
| 1062 |
:param username: the username to revoke the privilege from |
| 1063 |
:type username: str |
| 1064 |
""" |
| 1065 |
text = "REVOKE {0} ON {1} FROM {2}".format(privilege, |
| 1066 |
quote_ident(database), |
| 1067 |
quote_ident(username)) |
| 1068 |
self.query(text, method="POST") |
| 1069 |
|
| 1070 |
def get_list_privileges(self, username): |
| 1071 |
"""Get the list of all privileges granted to given user. |
| 1072 |
|
| 1073 |
:param username: the username to get privileges of |
| 1074 |
:type username: str |
| 1075 |
|
| 1076 |
:returns: all privileges granted to given user |
| 1077 |
:rtype: list of dictionaries |
| 1078 |
|
| 1079 |
:Example: |
| 1080 |
|
| 1081 |
:: |
| 1082 |
|
| 1083 |
>> privileges = client.get_list_privileges('user1') |
| 1084 |
>> privileges |
| 1085 |
[{u'privilege': u'WRITE', u'database': u'db1'}, |
| 1086 |
{u'privilege': u'ALL PRIVILEGES', u'database': u'db2'}, |
| 1087 |
{u'privilege': u'NO PRIVILEGES', u'database': u'db3'}] |
| 1088 |
""" |
| 1089 |
text = "SHOW GRANTS FOR {0}".format(quote_ident(username)) |
| 1090 |
return list(self.query(text).get_points()) |
| 1091 |
|
| 1092 |
def get_list_continuous_queries(self): |
| 1093 |
"""Get the list of continuous queries in InfluxDB. |
| 1094 |
|
| 1095 |
:return: all CQs in InfluxDB |
| 1096 |
:rtype: list of dictionaries |
| 1097 |
|
| 1098 |
:Example: |
| 1099 |
|
| 1100 |
:: |
| 1101 |
|
| 1102 |
>> cqs = client.get_list_cqs() |
| 1103 |
>> cqs |
| 1104 |
[ |
| 1105 |
{ |
| 1106 |
u'db1': [] |
| 1107 |
}, |
| 1108 |
{ |
| 1109 |
u'db2': [ |
| 1110 |
{ |
| 1111 |
u'name': u'vampire', |
| 1112 |
u'query': u'CREATE CONTINUOUS QUERY vampire ON ' |
| 1113 |
'mydb BEGIN SELECT count(dracula) INTO ' |
| 1114 |
'mydb.autogen.all_of_them FROM ' |
| 1115 |
'mydb.autogen.one GROUP BY time(5m) END' |
| 1116 |
} |
| 1117 |
] |
| 1118 |
} |
| 1119 |
] |
| 1120 |
""" |
| 1121 |
query_string = "SHOW CONTINUOUS QUERIES" |
| 1122 |
return [{sk[0]: list(p)} for sk, p in self.query(query_string).items()] |
| 1123 |
|
| 1124 |
def create_continuous_query(self, name, select, database=None, |
| 1125 |
resample_opts=None): |
| 1126 |
r"""Create a continuous query for a database. |
| 1127 |
|
| 1128 |
:param name: the name of continuous query to create |
| 1129 |
:type name: str |
| 1130 |
:param select: select statement for the continuous query |
| 1131 |
:type select: str |
| 1132 |
:param database: the database for which the continuous query is |
| 1133 |
created. Defaults to current client's database |
| 1134 |
:type database: str |
| 1135 |
:param resample_opts: resample options |
| 1136 |
:type resample_opts: str |
| 1137 |
|
| 1138 |
:Example: |
| 1139 |
|
| 1140 |
:: |
| 1141 |
|
| 1142 |
>> select_clause = 'SELECT mean("value") INTO "cpu_mean" ' \ |
| 1143 |
... 'FROM "cpu" GROUP BY time(1m)' |
| 1144 |
>> client.create_continuous_query( |
| 1145 |
... 'cpu_mean', select_clause, 'db_name', 'EVERY 10s FOR 2m' |
| 1146 |
... ) |
| 1147 |
>> client.get_list_continuous_queries() |
| 1148 |
[ |
| 1149 |
{ |
| 1150 |
'db_name': [ |
| 1151 |
{ |
| 1152 |
'name': 'cpu_mean', |
| 1153 |
'query': 'CREATE CONTINUOUS QUERY "cpu_mean" ' |
| 1154 |
'ON "db_name" ' |
| 1155 |
'RESAMPLE EVERY 10s FOR 2m ' |
| 1156 |
'BEGIN SELECT mean("value") ' |
| 1157 |
'INTO "cpu_mean" FROM "cpu" ' |
| 1158 |
'GROUP BY time(1m) END' |
| 1159 |
} |
| 1160 |
] |
| 1161 |
} |
| 1162 |
] |
| 1163 |
""" |
| 1164 |
query_string = ( |
| 1165 |
"CREATE CONTINUOUS QUERY {0} ON {1}{2} BEGIN {3} END" |
| 1166 |
).format(quote_ident(name), quote_ident(database or self._database), |
| 1167 |
' RESAMPLE ' + resample_opts if resample_opts else '', select) |
| 1168 |
self.query(query_string) |
| 1169 |
|
| 1170 |
def drop_continuous_query(self, name, database=None): |
| 1171 |
"""Drop an existing continuous query for a database. |
| 1172 |
|
| 1173 |
:param name: the name of continuous query to drop |
| 1174 |
:type name: str |
| 1175 |
:param database: the database for which the continuous query is |
| 1176 |
dropped. Defaults to current client's database |
| 1177 |
:type database: str |
| 1178 |
""" |
| 1179 |
query_string = ( |
| 1180 |
"DROP CONTINUOUS QUERY {0} ON {1}" |
| 1181 |
).format(quote_ident(name), quote_ident(database or self._database)) |
| 1182 |
self.query(query_string) |
| 1183 |
|
| 1184 |
def send_packet(self, packet, protocol='json', time_precision=None): |
| 1185 |
"""Send an UDP packet. |
| 1186 |
|
| 1187 |
:param packet: the packet to be sent |
| 1188 |
:type packet: (if protocol is 'json') dict |
| 1189 |
(if protocol is 'line') list of line protocol strings |
| 1190 |
:param protocol: protocol of input data, either 'json' or 'line' |
| 1191 |
:type protocol: str |
| 1192 |
:param time_precision: Either 's', 'm', 'ms' or 'u', defaults to None |
| 1193 |
:type time_precision: str |
| 1194 |
""" |
| 1195 |
if protocol == 'json': |
| 1196 |
data = make_lines(packet, time_precision).encode('utf-8') |
| 1197 |
elif protocol == 'line': |
| 1198 |
data = ('\n'.join(packet) + '\n').encode('utf-8') |
| 1199 |
self.udp_socket.sendto(data, (self._host, self._udp_port)) |
| 1200 |
|
| 1201 |
def close(self): |
| 1202 |
"""Close http session.""" |
| 1203 |
if isinstance(self._session, requests.Session): |
| 1204 |
self._session.close() |
| 1205 |
|
| 1206 |
|
| 1207 |
def _parse_dsn(dsn): |
| 1208 |
"""Parse data source name. |
| 1209 |
|
| 1210 |
This is a helper function to split the data source name provided in |
| 1211 |
the from_dsn classmethod |
| 1212 |
""" |
| 1213 |
conn_params = urlparse(dsn) |
| 1214 |
init_args = {} |
| 1215 |
scheme_info = conn_params.scheme.split('+') |
| 1216 |
if len(scheme_info) == 1: |
| 1217 |
scheme = scheme_info[0] |
| 1218 |
modifier = None |
| 1219 |
else: |
| 1220 |
modifier, scheme = scheme_info |
| 1221 |
|
| 1222 |
if scheme != 'influxdb': |
| 1223 |
raise ValueError('Unknown scheme "{0}".'.format(scheme)) |
| 1224 |
|
| 1225 |
if modifier: |
| 1226 |
if modifier == 'udp': |
| 1227 |
init_args['use_udp'] = True |
| 1228 |
elif modifier == 'https': |
| 1229 |
init_args['ssl'] = True |
| 1230 |
else: |
| 1231 |
raise ValueError('Unknown modifier "{0}".'.format(modifier)) |
| 1232 |
|
| 1233 |
netlocs = conn_params.netloc.split(',') |
| 1234 |
|
| 1235 |
init_args['hosts'] = [] |
| 1236 |
for netloc in netlocs: |
| 1237 |
parsed = _parse_netloc(netloc) |
| 1238 |
init_args['hosts'].append((parsed['host'], int(parsed['port']))) |
| 1239 |
init_args['username'] = parsed['username'] |
| 1240 |
init_args['password'] = parsed['password'] |
| 1241 |
|
| 1242 |
if conn_params.path and len(conn_params.path) > 1: |
| 1243 |
init_args['database'] = conn_params.path[1:] |
| 1244 |
|
| 1245 |
return init_args |
| 1246 |
|
| 1247 |
|
| 1248 |
def _parse_netloc(netloc): |
| 1249 |
info = urlparse("http://{0}".format(netloc)) |
| 1250 |
return {'username': info.username or None, |
| 1251 |
'password': info.password or None, |
| 1252 |
'host': info.hostname or 'localhost', |
| 1253 |
'port': info.port or 8086} |
| 1254 |
|
| 1255 |
|
| 1256 |
def _msgpack_parse_hook(code, data): |
| 1257 |
if code == 5: |
| 1258 |
(epoch_s, epoch_ns) = struct.unpack(">QI", data) |
| 1259 |
timestamp = datetime.datetime.utcfromtimestamp(epoch_s) |
| 1260 |
timestamp += datetime.timedelta(microseconds=(epoch_ns / 1000)) |
| 1261 |
return timestamp.isoformat() + 'Z' |
| 1262 |
return msgpack.ExtType(code, data) |
| 1263 |
|
| 1264 |
|
| 1265 |
class _SocketOptionsAdapter(HTTPAdapter): |
| 1266 |
"""_SocketOptionsAdapter injects socket_options into HTTP Adapter.""" |
| 1267 |
|
| 1268 |
def __init__(self, *args, **kwargs): |
| 1269 |
self.socket_options = kwargs.pop("socket_options", None) |
| 1270 |
super(_SocketOptionsAdapter, self).__init__(*args, **kwargs) |
| 1271 |
|
| 1272 |
def init_poolmanager(self, *args, **kwargs): |
| 1273 |
if self.socket_options is not None: |
| 1274 |
kwargs["socket_options"] = self.socket_options |
| 1275 |
super(_SocketOptionsAdapter, self).init_poolmanager(*args, **kwargs) |