62 lines
1.4 KiB
Django/Jinja
62 lines
1.4 KiB
Django/Jinja
#!/usr/bin/env python3
|
|
|
|
from sys import argv
|
|
from datetime import datetime, timezone
|
|
from influxdb import InfluxDBClient
|
|
|
|
dbs = {
|
|
'metrics': "{{ influxdb_pass['metrics'] }}"
|
|
}
|
|
|
|
TAG_HOST = {
|
|
"host": "{{ inventory_hostname }}"
|
|
}
|
|
|
|
def now_isoformat():
|
|
return datetime.now(tz=timezone.utc).isoformat()
|
|
|
|
def datapoint(measurement, tags, fields):
|
|
return {
|
|
"measurement": measurement,
|
|
"tags": tags,
|
|
"time": now_isoformat(),
|
|
"fields": {k: int_if_bool(v) for k, v in fields.items()}
|
|
}
|
|
|
|
def int_if_bool(value):
|
|
if isinstance(value, bool):
|
|
return int(value)
|
|
else:
|
|
return value
|
|
|
|
def write_datapoint(measurement, tags, fields, db="metrics", precision="m"):
|
|
return write(
|
|
datapoint(measurement, tags, fields),
|
|
db=db,
|
|
precision=precision
|
|
)
|
|
|
|
|
|
def write(datapoints, db="metrics", precision='m', dry_run=False, passwd=None):
|
|
if passwd is None:
|
|
passwd = dbs[db]
|
|
|
|
client = InfluxDBClient(
|
|
host='{{ influxdb_url }}',
|
|
port=443,
|
|
username=db,
|
|
password=passwd,
|
|
ssl=True,
|
|
verify_ssl=True,
|
|
database=db)
|
|
|
|
if not isinstance(datapoints, list):
|
|
datapoints = [datapoints]
|
|
|
|
if dry_run or "-v" in argv:
|
|
import pprint
|
|
pprint.pprint(datapoints)
|
|
|
|
if not dry_run:
|
|
return client.write_points(datapoints, time_precision=precision)
|