github.com/juju/juju@v0.0.0-20240327075706-a90865de2538/acceptancetests/reporting.py (about)

     1  """Reporting helper class for communicating with influx db."""
     2  import datetime
     3  try:
     4      import urlparse
     5  except ImportError:
     6      import urllib.parse as urlparse
     7  
     8  from influxdb import InfluxDBClient
     9  
    10  __metaclass__ = type
    11  
    12  DBNAME = 'juju'
    13  POLICYNAME = 'txn_metric'
    14  
    15  
    16  class _Reporting:
    17      """_Reporting represents a class to report metrics upon"""
    18  
    19      def __init__(self, client):
    20          self.client = client
    21  
    22  
    23  class InfluxClient(_Reporting):
    24      """InfluxClient represents a influx db reporting client"""
    25  
    26      def __init__(self, *args, **kwargs):
    27          super(InfluxClient, self).__init__(*args, **kwargs)
    28  
    29      def report(self, metrics, tags):
    30          """Report the metrics to the underlying reporting client
    31          """
    32  
    33          now = datetime.datetime.today().isoformat()
    34          series = []
    35          for key, value in metrics.items():
    36              series.append({
    37                  "measurement": key,
    38                  "tags": tags,
    39                  "time": now,
    40                  "fields": {
    41                      "value": value,
    42                  },
    43              })
    44  
    45          self.client.write_points(
    46              series, retention_policy=POLICYNAME, time_precision='s')
    47  
    48  
    49  def get_reporting_client(uri):
    50      """Reporting client returns a client for reporting metrics to.  It expects
    51      that the uri can be parsed and sent to the client constructor.
    52  
    53      :param uri: URI to connect to the client.
    54      """
    55      # Extract the uri
    56      parsed_uri = urlparse.urlsplit(uri)
    57      client = InfluxDBClient(
    58          host=parsed_uri.hostname,
    59          port=parsed_uri.port,
    60          username=parsed_uri.username,
    61          password=parsed_uri.password,
    62          database=DBNAME,
    63      )
    64  
    65      # Create DB/retention schema and switch to it. If the
    66      # DB already exists then the following calls are no-ops.
    67      client.create_database(DBNAME)
    68      client.create_retention_policy(POLICYNAME, 'INF', '1', DBNAME, True)
    69  
    70      client.switch_database(DBNAME)
    71      return InfluxClient(client)