示例#1
0
 def __init__(self, client, org_id, dashboard_id, cell_info):
   self.client = client
   self.cell_info = cell_info
   self.org_id = org_id
   self.dashboard_id = dashboard_id
   self.cs = CellsService(self.client.api_client)
   self.init_cell()
   self.init_queries()
   self.init_axes()
   self.init_colors()
    def test_create_dashboard_with_cell(self):
        unique_id = str(datetime.datetime.now().timestamp())

        dashboard = self.dashboards_service.post_dashboards(
            create_dashboard_request=CreateDashboardRequest(
                org_id=self.find_my_org().id,
                name=f"Dashboard_{unique_id}_IT"))
        self.assertEqual(dashboard.name, f"Dashboard_{unique_id}_IT")

        cells_service = CellsService(self.client.api_client)
        cell = cells_service.post_dashboards_id_cells(
            dashboard_id=dashboard.id,
            create_cell=CreateCell(name=f"Cell_{unique_id}_IT", h=3, w=12))
        self.assertIsNotNone(cell.id)
        view = cells_service.get_dashboards_id_cells_id_view(
            dashboard_id=dashboard.id, cell_id=cell.id)
        self.assertEqual(view.name, f"Cell_{unique_id}_IT")
    def test_get_dashboard_with_cell_with_properties(self):
        unique_id = str(datetime.datetime.now().timestamp())

        dashboard = self.dashboards_service.post_dashboards(
            create_dashboard_request=CreateDashboardRequest(
                org_id=self.find_my_org().id,
                name=f"Dashboard_{unique_id}_IT"))

        # create cell
        CellsService(self.client.api_client).post_dashboards_id_cells(
            dashboard_id=dashboard.id,
            create_cell=CreateCell(name=f"Cell_{unique_id}_IT", h=3, w=12))

        # retrieve dashboard
        dashboard = self.dashboards_service.get_dashboards_id(dashboard.id)

        from influxdb_client import DashboardWithViewProperties, CellWithViewProperties
        self.assertEqual(DashboardWithViewProperties, type(dashboard))
        self.assertEqual(1, len(dashboard.cells))
        self.assertEqual(CellWithViewProperties, type(dashboard.cells[0]))
示例#4
0
class InfluxDBDashboardCell:
  def __init__(self, client, org_id, dashboard_id, cell_info):
    self.client = client
    self.cell_info = cell_info
    self.org_id = org_id
    self.dashboard_id = dashboard_id
    self.cs = CellsService(self.client.api_client)
    self.init_cell()
    self.init_queries()
    self.init_axes()
    self.init_colors()

  def init_cell(self):
    self.id = self.cell_info.id
    self.x = self.cell_info.x
    self.y = self.cell_info.y
    self.w = self.cell_info.w
    self.h = self.cell_info.h
    self.yh = self.y + self.h
    self.info = self.cs.get_dashboards_id_cells_id_view(self.dashboard_id, self.id)
    self.type = self.info.properties.get('type', 'xy')
    self.name = self.info.name

  def init_queries(self):
    self.queries = map(lambda q: q['text'], self.info.properties['queries'])
    self.query_api = self.client.query_api()

  def init_axes(self):
    self.x_column = self.info.properties.get('xColumn', '_time')
    if self.x_column == '':
      self.x_column = '_time'
    self.y_column = self.info.properties.get('yColumn', '_value')
    if self.y_column == '':
      self.y_column = '_value'
    self.x_axis = self.info.properties.get('axes', {}).get('x', {})
    self.y_axis = self.info.properties.get('axes', {}).get('y', {})
    self.shade_below = self.info.properties.get('shadeBelow', False)
    decimal_places = self.info.properties.get('decimalPlaces', {'isEnforced': False})
    self.decimal_places = int(decimal_places['digits']) if decimal_places['isEnforced'] else None

  def init_colors(self):
    convert_color = lambda c: {**c, 'color': (int(c['hex'][1:3], 16), int(c['hex'][3:5], 16), int(c['hex'][5:7], 16))}
    text_colors = filter(lambda c: c['type'] == 'text', self.info.properties['colors'])
    scale_colors = filter(lambda c: c['type'] == 'scale', self.info.properties['colors'])
    self.text_colors = list(map(convert_color, text_colors))
    self.scale_colors = list(map(convert_color, scale_colors))

  def queries(self):
    return self.queries

  def results(self):
    return map(lambda q: self.query_api.query(q), self.queries)

  def flat_results(self):
    tables = []
    for result in self.results():
      tables += result
    return tables

  def cell_output(self):
    return InfluxDBDashboardCellOutput(self, self.flat_results())
示例#5
0
class InfluxDBDashboardCell:
    def __init__(self, client, org_id, dashboard_id, cell_info):
        self._results = None
        self.client = client
        self.cell_info = cell_info
        self.org_id = org_id
        self.dashboard_id = dashboard_id
        self.cs = CellsService(self.client.api_client)
        self.init_cell()
        self.init_queries()
        self.init_axes()
        self.init_colors()
        self.init_params()

    def init_cell(self):
        self.id = self.cell_info.id
        self.x = self.cell_info.x
        self.y = self.cell_info.y
        self.w = self.cell_info.w
        self.h = self.cell_info.h
        self.yh = self.y + self.h
        self.info = self.cs.get_dashboards_id_cells_id_view(
            self.dashboard_id, self.id)
        self.type = self.info.properties.get('type', 'xy')
        self.value_prefix = self.info.properties.get('prefix', '')
        self.value_suffix = self.info.properties.get('suffix', '')
        self.name = self.info.name

    def init_queries(self):
        self.queries = map(lambda q: q['text'],
                           self.info.properties.get('queries', []))
        self.query_api = self.client.query_api()
        self.query_service = QueryService(self.client.api_client)

    def init_axes(self):
        self.x_column = self.info.properties.get('xColumn', '_time')
        if self.x_column == '':
            self.x_column = '_time'
        self.y_column = self.info.properties.get('yColumn', '_value')
        if self.y_column == '':
            self.y_column = '_value'
        self.x_axis = self.info.properties.get('axes', {}).get('x', {})
        self.y_axis = self.info.properties.get('axes', {}).get('y', {})
        self.shade_below = self.info.properties.get('shadeBelow', False)
        decimal_places = self.info.properties.get('decimalPlaces',
                                                  {'isEnforced': False})
        self.decimal_places = int(
            decimal_places['digits']) if decimal_places['isEnforced'] else None

    def init_colors(self):
        convert_color = lambda c: {
            **c, 'color': (int(c['hex'][1:3], 16), int(c['hex'][3:5], 16),
                           int(c['hex'][5:7], 16))
        }
        self.colors = list(
            map(convert_color, self.info.properties.get('colors', [])))
        self.color_map = {}
        for c in self.colors:
            t = c['type']
            if not t in self.color_map:
                self.color_map[t] = []
            self.color_map[t] += [c]

    def init_params(self):
        self._extern_obj = InfluxDBDashboardExtern('v')
        self.set_time_range()

    def set_time_range(self,
                       start_offset=-(7 * 24 * 60),
                       end_offset=0,
                       window_period=15,
                       offset_unit='m'):
        self._extern_obj.add_time_offset_variable('timeRangeStart',
                                                  start_offset,
                                                  offset_unit=offset_unit)
        self._extern_obj.add_time_offset_variable('timeRangeStop',
                                                  end_offset,
                                                  offset_unit=offset_unit)
        self._extern_obj.add_duration_variable('windowPeriod',
                                               window_period,
                                               offset_unit=offset_unit)
        self._extern = self._extern_obj.serialize()
        # invalidate any previously stored results
        self._results = None

    def set_string_literval_variable(self, name, value):
        # TODO: handle duplicated values
        self._extern_obj.add_string_literal(name, value)
        self._extern = self._extern_obj.serialize()
        # invalidate any previously stored results
        self._results = None

    def queries(self):
        return self.queries

    def retrieve_result(self, query_string):
        # TODO: this method is hopefully temporary until InfluxDB /api/v2/query API simplifies passing

        # mimic default dialect
        dialect = Dialect(header=True,
                          delimiter=",",
                          comment_prefix="#",
                          annotations=["datatype", "group", "default"],
                          date_time_format="RFC3339")

        query = Query(query=query_string, dialect=dialect, extern=self._extern)
        try:
            response = self.query_service.post_query(
                org=self.client.org,
                query=query,
                async_req=False,
                _preload_content=False,
                _return_http_data_only=False)
            _parser = FluxCsvParser(
                response=response,
                serialization_mode=FluxSerializationMode.tables)
            list(_parser.generator())
            tables = _parser.tables
        except rest.ApiException as error:
            # TODO: log error
            print('Error while retrieving data:', error)
            tables = []
        return tables

    def results(self):
        if self._results == None:
            self._results = list(map(self.retrieve_result, self.queries))
        return self._results

    def flat_results(self):
        tables = []
        for result in self.results():
            tables += result
        return tables

    def cell_output(self):
        return InfluxDBDashboardCellOutput(self, self.flat_results())