|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import Optional, Final |
| 3 | + |
| 4 | +from grafanalib.core import Row, Dashboard, Target, TimeSeries, GridPos |
| 5 | + |
| 6 | +from common import PROMETHEUS_DATASOURCE_NAME |
| 7 | + |
| 8 | + |
| 9 | +class RefIdGenerator: |
| 10 | + STARTING_CHAR_INTEGER = ord("A") |
| 11 | + |
| 12 | + def __init__(self): |
| 13 | + self.offset = 0 |
| 14 | + |
| 15 | + def next(self) -> str: |
| 16 | + result = chr(self.STARTING_CHAR_INTEGER + self.offset) |
| 17 | + self.offset += 1 |
| 18 | + return result |
| 19 | + |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class ExpressionAndLegendPair: |
| 23 | + expression: str |
| 24 | + legend: Optional[str] = None |
| 25 | + |
| 26 | + |
| 27 | +class SceGrafanalibWrapper: |
| 28 | + MAX_WIDTH: Final[int] = 24 |
| 29 | + |
| 30 | + def __init__(self, title, panel_width=12, panel_height=8): |
| 31 | + self.rows = [] |
| 32 | + self.panels = [] |
| 33 | + self.title = title |
| 34 | + self.current_x = 0 |
| 35 | + self.current_y = 0 |
| 36 | + self.panel_width = min(panel_width, self.MAX_WIDTH) |
| 37 | + self.panel_height = panel_height |
| 38 | + |
| 39 | + def AddPanel(self, title, queries: list[ExpressionAndLegendPair]): |
| 40 | + targets = [] |
| 41 | + iterator = RefIdGenerator() |
| 42 | + for query in queries: |
| 43 | + query_text = query.expression |
| 44 | + query_label = query.legend |
| 45 | + refId = iterator.next() |
| 46 | + targets.append( |
| 47 | + Target( |
| 48 | + expr=query_text, |
| 49 | + legendFormat=query_label, |
| 50 | + refId=refId, |
| 51 | + datasource=PROMETHEUS_DATASOURCE_NAME, |
| 52 | + ) |
| 53 | + ) |
| 54 | + self.panels.append( |
| 55 | + TimeSeries( |
| 56 | + title=title, |
| 57 | + targets=targets, |
| 58 | + gridPos=GridPos( |
| 59 | + h=self.panel_height, |
| 60 | + w=self.panel_width, |
| 61 | + x=self.current_x, |
| 62 | + y=self.current_y, |
| 63 | + ), |
| 64 | + ) |
| 65 | + ) |
| 66 | + self.current_x += self.panel_width |
| 67 | + if self.current_x >= self.MAX_WIDTH / 2: |
| 68 | + self.current_y += self.panel_height |
| 69 | + self.current_x = 0 |
| 70 | + |
| 71 | + def Render(self): |
| 72 | + return Dashboard( |
| 73 | + title=self.title, rows=self.rows, panels=self.panels |
| 74 | + ).auto_panel_ids() |
0 commit comments