|
| 1 | +import logging |
| 2 | + |
| 3 | +from django.utils.functional import cached_property |
| 4 | +from influxdb_client import InfluxDBClient, Point |
| 5 | +from influxdb_client.client.exceptions import InfluxDBError |
| 6 | +from influxdb_client.client.write_api import SYNCHRONOUS |
| 7 | + |
| 8 | +from openwisp_monitoring.utils import retry |
| 9 | + |
| 10 | +from ...exceptions import TimeseriesWriteException |
| 11 | +from .. import TIMESERIES_DB |
| 12 | +from ..base import BaseDatabaseClient |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class DatabaseClient(BaseDatabaseClient): |
| 18 | + backend_name = 'influxdb2' |
| 19 | + |
| 20 | + def __init__(self, db_name=None): |
| 21 | + super().__init__(db_name) |
| 22 | + self.client_error = InfluxDBError |
| 23 | + |
| 24 | + @cached_property |
| 25 | + def db(self): |
| 26 | + return InfluxDBClient( |
| 27 | + url=f"http://{TIMESERIES_DB['HOST']}:{TIMESERIES_DB['PORT']}", |
| 28 | + token=TIMESERIES_DB['TOKEN'], |
| 29 | + org=TIMESERIES_DB['ORG'], |
| 30 | + bucket=self.db_name, |
| 31 | + ) |
| 32 | + |
| 33 | + @retry |
| 34 | + def create_database(self): |
| 35 | + self.write_api = self.db.write_api(write_options=SYNCHRONOUS) |
| 36 | + self.query_api = self.db.query_api() |
| 37 | + logger.debug('Initialized APIs for InfluxDB 2.0') |
| 38 | + |
| 39 | + @retry |
| 40 | + def drop_database(self): |
| 41 | + pass # Implement as needed for InfluxDB 2.0 |
| 42 | + |
| 43 | + @retry |
| 44 | + def query(self, query): |
| 45 | + return self.query_api.query(query) |
| 46 | + |
| 47 | + def write(self, name, values, **kwargs): |
| 48 | + point = Point(name).time(self._get_timestamp(kwargs.get('timestamp'))) |
| 49 | + tags = kwargs.get('tags', {}) |
| 50 | + for tag, value in tags.items(): |
| 51 | + point.tag(tag, value) |
| 52 | + for field, value in values.items(): |
| 53 | + point.field(field, value) |
| 54 | + try: |
| 55 | + self.write_api.write(bucket=self.db_name, record=point) |
| 56 | + except InfluxDBError as e: |
| 57 | + raise TimeseriesWriteException(str(e)) |
| 58 | + |
| 59 | + @retry |
| 60 | + def get_list_retention_policies(self, name=None): |
| 61 | + bucket = self.db.buckets_api().find_bucket_by_name(name) |
| 62 | + if bucket: |
| 63 | + return bucket.retention_rules |
| 64 | + return [] |
| 65 | + |
| 66 | + @retry |
| 67 | + def create_or_alter_retention_policy(self, name, duration): |
| 68 | + bucket = self.db.buckets_api().find_bucket_by_name(name) |
| 69 | + retention_rules = [{"type": "expire", "everySeconds": duration}] |
| 70 | + if bucket: |
| 71 | + bucket.retention_rules = retention_rules |
| 72 | + self.db.buckets_api().update_bucket(bucket=bucket) |
| 73 | + else: |
| 74 | + self.db.buckets_api().create_bucket( |
| 75 | + bucket_name=name, |
| 76 | + retention_rules=retention_rules, |
| 77 | + org=TIMESERIES_DB["ORG"], |
| 78 | + ) |
0 commit comments