### Grafana Alert Provisioning Example Source: https://grafanalib.readthedocs.io/en/stable/getting-started This snippet demonstrates the import of necessary classes from grafanalib for file-based provisioning of Grafana alerts, specifically for Grafana v9.x and later. ```python from grafanalib.core import ( AlertGroup, AlertRulev9, Target, AlertCondition, AlertExpression, AlertFileBasedProvisioning, GreaterThan, OP_AND, RTYPE_LAST, EXP_TYPE_CLASSIC, EXP_TYPE_REDUCE, EXP_TYPE_MATH ) ``` -------------------------------- ### grafanalib Installation and Development Source: https://grafanalib.readthedocs.io/en/stable/getting-started Instructions for installing the grafanalib Python package using pip and setting up a development environment. It also mentions compatibility with Python versions 3.7-3.11 and the retirement of the `gfdatasource` tool. ```Shell $ pip install grafanalib ``` ```Shell $ virtualenv venv $ . venv/bin/activate $ pip install -r requirements.txt $ python setup.py install ``` -------------------------------- ### Grafana v9+ Alert Configuration Example Source: https://grafanalib.readthedocs.io/en/stable/getting-started This snippet provides the necessary imports for configuring alerts in Grafana v9.x+, including AlertGroup, AlertRulev9, Target, AlertCondition, and various expression types and operators. ```Python from grafanalib.core import ( AlertGroup, AlertRulev9, Target, AlertCondition, AlertExpression, GreaterThan, OP_AND, RTYPE_LAST, EXP_TYPE_CLASSIC, EXP_TYPE_REDUCE, EXP_TYPE_MATH ) ``` -------------------------------- ### Python Grafana Dashboard Configuration Source: https://grafanalib.readthedocs.io/en/stable/getting-started Configures a Grafana dashboard with TimeSeries and GaugePanel using grafanalib. It includes setting titles, data sources, targets, and panel positions. ```Python from grafanalib.core import ( Dashboard, TimeSeries, GaugePanel, Target, GridPos, OPS_FORMAT ) dashboard = Dashboard( title="Python generated example dashboard", description="Example dashboard using the Random Walk and default Prometheus datasource", tags=[ 'example' ], timezone="browser", panels=[ TimeSeries( title="Random Walk", dataSource='default', targets=[ Target( datasource='grafana', expr='example', ), ], gridPos=GridPos(h=8, w=16, x=0, y=0), ), GaugePanel( title="Random Walk", dataSource='default', targets=[ Target( datasource='grafana', expr='example', ), ], gridPos=GridPos(h=4, w=4, x=17, y=0), ), TimeSeries( title="Prometheus http requests", dataSource='prometheus', targets=[ Target( expr='rate(prometheus_http_requests_total[5m])', legendFormat="{{ handler }}", refId='A', ), ], unit=OPS_FORMAT, gridPos=GridPos(h=8, w=16, x=0, y=10), ), ], ).auto_panel_ids() ``` -------------------------------- ### Grafana AlertGroup with AlertRulev9 Examples Source: https://grafanalib.readthedocs.io/en/stable/getting-started Demonstrates creating an AlertGroup containing two AlertRulev9 instances. The first rule uses a classic condition (greater than 3) based on a target expression. The second rule uses a reduce function (mean) and a math expression to trigger an alert. ```Python from grafanalib.alerting import AlertGroup, AlertRulev9, Target, AlertExpression, EXP_TYPE_CLASSIC, EXP_TYPE_REDUCE, EXP_TYPE_MATH, AlertCondition, GreaterThan, OP_AND, RTYPE_LAST alertgroup = AlertGroup( name="Production Alerts", rules=[ AlertRulev9( title="Alert for something 3", uid='alert3', condition='B', triggers=[ Target( expr="from(bucket: \"sensors\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"remote_cpu\")\n |> filter(fn: (r) => r[\"_field\"] == \"usage_system\")\n |> filter(fn: (r) => r[\"cpu\"] == \"cpu-total\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> yield(name: \"mean\")", datasource="influxdb", refId="A", ), AlertExpression( refId="B", expressionType=EXP_TYPE_CLASSIC, expression='A', conditions=[ AlertCondition( evaluator=GreaterThan(3), operator=OP_AND, reducerType=RTYPE_LAST ) ] ) ], annotations={ "summary": "The database is down", "runbook_url": "runbook-for-this-scenario.com/foo", }, labels={ "environment": "prod", "slack": "prod-alerts", }, evaluateFor="3m", ), AlertRulev9( title="Alert for something 4", uid='alert4', condition='C', triggers=[ Target( expr="from(bucket: \"sensors\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"remote_cpu\")\n |> filter(fn: (r) => r[\"_field\"] == \"usage_system\")\n |> filter(fn: (r) => r[\"cpu\"] == \"cpu-total\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> yield(name: \"mean\")", datasource="influxdb", refId="A", ), AlertExpression( refId="B", expressionType=EXP_TYPE_REDUCE, expression='A', reduceFunction='mean', reduceMode='dropNN' ), AlertExpression( refId="C", expressionType=EXP_TYPE_MATH, expression='$B < 3' ) ], annotations={ "summary": "The database is down", "runbook_url": "runbook-for-this-scenario.com/foo", }, labels={ "environment": "prod", "slack": "prod-alerts", }, evaluateFor="3m", ) ] ) alertfilebasedprovisioning = AlertFileBasedProvisioning([alertgroup]) ``` -------------------------------- ### Generate and Upload Grafana Dashboards Source: https://grafanalib.readthedocs.io/en/stable/getting-started This snippet demonstrates how to create a Grafana dashboard using grafanalib, convert it to JSON, and upload it to a Grafana server using the Grafana API. It includes functions for JSON generation and API uploading, along with environment variable loading for API keys and server details. ```Python from grafanalib.core import Dashboard from grafanalib._gen import DashboardEncoder import json import requests from os import getenv def get_dashboard_json(dashboard, overwrite=False, message="Updated by grafanlib"): ''' get_dashboard_json generates JSON from grafanalib Dashboard object :param dashboard - Dashboard() created via grafanalib ''' # grafanalib generates json which need to pack to "dashboard" root element return json.dumps( { "dashboard": dashboard.to_json_data(), "overwrite": overwrite, "message": message }, sort_keys=True, indent=2, cls=DashboardEncoder) def upload_to_grafana(json, server, api_key, verify=True): ''' upload_to_grafana tries to upload dashboard to grafana and prints response :param json - dashboard json generated by grafanalib :param server - grafana server name :param api_key - grafana api key with read and write privileges ''' headers = {'Authorization': f"Bearer {api_key}", 'Content-Type': 'application/json'} r = requests.post(f"https://{server}/api/dashboards/db", data=json, headers=headers, verify=verify) # TODO: add error handling print(f"{r.status_code} - {r.content}") grafana_api_key = getenv("GRAFANA_API_KEY") grafana_server = getenv("GRAFANA_SERVER") my_dashboard = Dashboard(title="My awesome dashboard", uid='abifsd') my_dashboard_json = get_dashboard_json(my_dashboard, overwrite=True) upload_to_grafana(my_dashboard_json, grafana_server, grafana_api_key) ``` -------------------------------- ### Grafana v8 Alerts Configuration Source: https://grafanalib.readthedocs.io/en/stable/getting-started This snippet shows how to configure alerts within a group for Grafana v8.x and later. It imports necessary components from grafanalib for defining alert rules, targets, conditions, and operators. ```Python """Example grafana 8.x+ Alert""" from grafanalib.core import ( AlertGroup, AlertRulev8, Target, AlertCondition, LowerThan, OP_OR, OP_AND, RTYPE_LAST ) ``` -------------------------------- ### Configure Grafana AlertGroup with AlertRulev8 Source: https://grafanalib.readthedocs.io/en/stable/getting-started This snippet shows how to create an AlertGroup containing multiple AlertRulev8 instances. Each rule defines a target query, an alert condition, evaluation intervals, and annotations/labels for production alerts. ```Python from grafanalib.core import ( AlertGroup, AlertRulev8, Target, AlertCondition, OP_OR, RTYPE_LAST ) alertgroup = AlertGroup( name="Production Alerts", rules=[ AlertRulev8( title="Database is unresponsive", triggers=[ ( Target( expr='sum(kube_pod_container_status_ready{exported_pod=~"database-/*"})', datasource="VictoriaMetrics", refId="A", ), AlertCondition( evaluator=LowerThan(1), operator=OP_OR, reducerType=RTYPE_LAST ) ), ( Target( expr='sum by (app) (count_over_time({app="database"}[5m]))', datasource="Loki", refId="B", ), AlertCondition( evaluator=LowerThan(1000), operator=OP_OR, reducerType=RTYPE_LAST ) ) ], annotations={ "summary": "The database is down", "runbook_url": "runbook-for-this-scenario.com/foo", }, labels={ "environment": "prod", "slack": "prod-alerts", }, evaluateInterval="1m", evaluateFor="3m", ), AlertRulev8( title="Service API blackbox failure", triggers=[ ( Target( expr='probe_success{instance="my-service.foo.com/ready"}', datasource="VictoriaMetrics", refId="A", ), AlertCondition( evaluator=LowerThan(1), operator=OP_AND, reducerType=RTYPE_LAST, ) ) ], annotations={ "summary": "Service API has been unavailable for 3 minutes", "runbook_url": "runbook-for-this-scenario.com/foo", }, labels={ "environment": "prod", "slack": "prod-alerts", }, evaluateInterval="1m", evaluateFor="3m", ) ] ) ``` -------------------------------- ### Define Grafana AlertGroup with Alert Rules Source: https://grafanalib.readthedocs.io/en/stable/getting-started This snippet demonstrates how to create a Grafana AlertGroup containing multiple AlertRulev9 instances. Each rule includes a Target for data querying and AlertExpressions for defining alert conditions using classic, reduce, and math operations. It also shows how to configure annotations, labels, and evaluation periods. ```python from grafanalib.alerting import AlertGroup, AlertRulev9, Target, AlertExpression, AlertCondition, EXP_TYPE_CLASSIC, EXP_TYPE_REDUCE, EXP_TYPE_MATH, OP_AND, RTYPE_LAST, GreaterThan alertgroup = AlertGroup( name="Production Alerts", rules=[ AlertRulev9( title="Alert for something 1", uid='alert1', condition='B', triggers=[ Target( expr="from(bucket: \"sensors\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"remote_cpu\")\n |> filter(fn: (r) => r[\"_field\"] == \"usage_system\")\n |> filter(fn: (r) => r[\"cpu\"] == \"cpu-total\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> yield(name: \"mean\")", datasource="influxdb", refId="A", ), AlertExpression( refId="B", expressionType=EXP_TYPE_CLASSIC, expression='A', conditions=[ AlertCondition( evaluator=GreaterThan(3), operator=OP_AND, reducerType=RTYPE_LAST ) ] ) ], annotations={ "summary": "The database is down", "runbook_url": "runbook-for-this-scenario.com/foo", }, labels={ "environment": "prod", "slack": "prod-alerts", }, evaluateFor="3m", ), AlertRulev9( title="Alert for something 2", uid='alert2', condition='C', triggers=[ Target( expr="from(bucket: \"sensors\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r[\"_measurement\"] == \"remote_cpu\")\n |> filter(fn: (r) => r[\"_field\"] == \"usage_system\")\n |> filter(fn: (r) => r[\"cpu\"] == \"cpu-total\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> yield(name: \"mean\")", datasource="influxdb", refId="A", ), AlertExpression( refId="B", expressionType=EXP_TYPE_REDUCE, expression='A', reduceFunction='mean', reduceMode='dropNN' ), AlertExpression( refId="C", expressionType=EXP_TYPE_MATH, expression='$B < 3' ) ], annotations={ "summary": "The database is down", "runbook_url": "runbook-for-this-scenario.com/foo", }, labels={ "environment": "prod", "slack": "prod-alerts", }, evaluateFor="3m", ) ] ) ``` -------------------------------- ### Generate Grafana Dashboard JSON Source: https://grafanalib.readthedocs.io/en/stable/getting-started Command to generate the JSON representation of a Grafana dashboard from a Python script. The Python file must have the `.dashboard.py` suffix. ```Shell $ generate-dashboard ``` -------------------------------- ### Update README Example Source: https://grafanalib.readthedocs.io/en/stable/CHANGELOG Corrects the example in README.rst to ensure it functions properly, improving the usability of the documentation. ```Python Update README.rst to make the example work ``` -------------------------------- ### Automate Documentation Example Testing Source: https://grafanalib.readthedocs.io/en/stable/CHANGELOG Implements automated testing for documentation examples, ensuring that code examples provided in the documentation are accurate and functional. ```Python Automatically test documentation examples. ``` -------------------------------- ### Upload Alert Group to Grafana via REST API Source: https://grafanalib.readthedocs.io/en/stable/getting-started This function uploads a generated AlertGroup JSON to a specified Grafana server and folder using the REST API. It handles authentication via API key or session cookie, deletes existing alert groups with the same name, and creates the target folder if it doesn't exist. ```python import requests from os import getenv import json def upload_to_grafana(alertjson, folder, server, api_key, session_cookie, verify=True): ''' upload_to_grafana tries to upload the AlertGroup to grafana and prints response WARNING: This will first delete all alerts in the AlertGroup before replacing them with the provided AlertGroup. :param alertjson - AlertGroup json generated by grafanalib :param folder - Folder to upload the AlertGroup into :param server - grafana server name :param api_key - grafana api key with read and write privileges ''' groupName = json.loads(alertjson)['name'] headers = {} if api_key: print("using bearer auth") headers['Authorization'] = f"Bearer {api_key}" if session_cookie: print("using session cookie") headers['Cookie'] = session_cookie print(f"deleting AlertGroup {groupName} in folder {folder}") r = requests.delete(f"https://{server}/api/ruler/grafana/api/v1/rules/{folder}/{groupName}", headers=headers, verify=verify) print(f"{r.status_code} - {r.content}") headers['Content-Type'] = 'application/json' print(f"ensuring folder {folder} exists") r = requests.post(f"https://{server}/api/folders", data={"title": folder}, headers=headers) print(f"{r.status_code} - {r.content}") print(f"uploading AlertGroup {groupName} to folder {folder}") r = requests.post(f"https://{server}/api/ruler/grafana/api/v1/rules/{folder}", data=alertjson, headers=headers, verify=verify) # TODO: add error handling print(f"{r.status_code} - {r.content}") grafana_api_key = getenv("GRAFANA_API_KEY") grafana_server = getenv("GRAFANA_SERVER") grafana_cookie = getenv("GRAFANA_COOKIE") # Generate an alert from the example my_alergroup_json = get_alert_json(loader("./grafanalib/tests/examples/example.alertgroup.py")) upload_to_grafana(my_alergroup_json, "testfolder", grafana_server, grafana_api_key, grafana_cookie) ``` -------------------------------- ### Generate Alert Group JSON Source: https://grafanalib.readthedocs.io/en/stable/getting-started This function takes a grafanalib AlertGroup object and converts it into a JSON string suitable for uploading to Grafana. It uses a custom encoder for proper formatting. ```python from grafanalib.core import AlertGroup from grafanalib._gen import DashboardEncoder, loader import json def get_alert_json(alert: AlertGroup): ''' get_alert_json generates JSON from grafanalib AlertGroup object :param alert - AlertGroup created via grafanalib ''' return json.dumps(alert.to_json_data(), sort_keys=True, indent=4, cls=DashboardEncoder) ``` -------------------------------- ### grafanalib Core Components (T) Source: https://grafanalib.readthedocs.io/en/stable/genindex This section lists core classes and attributes from the grafanalib.core module starting with 'T'. These include components for building dashboards like Table, Target, Template, Templating, Text, Threshold, Time, TimePicker, TimeRange, and TimeSeries. ```python from grafanalib.core import ( Table, TableSortByField, Target, Template, Templating, Text, Threshold, Time, TimePicker, TimeRange, TimeSeries, DashboardLink ) # Example usage (conceptual): # table_panel = Table(columns=[...]) # time_series_panel = TimeSeries(dataSource='...', targets=[...]) # dashboard_link = DashboardLink(type='link', title='My Link', url='http://example.com', targetBlank=True, tags=['example']) ``` -------------------------------- ### Pre-release Steps for grafanalib Source: https://grafanalib.readthedocs.io/en/stable/releasing Steps to prepare for a new release, including version number selection, updating the changelog, and modifying setup.py. ```Python # Pick a new version number (e.g. `X.Y.Z`) # Update CHANGELOG with that number # Update setup.py with that number ``` -------------------------------- ### Releasing grafanalib to PyPI Source: https://grafanalib.readthedocs.io/en/stable/releasing Steps for releasing a new version of grafanalib to the Python Package Index (PyPI) using GitHub Releases and verifying the deployment. ```Shell # Head to https://github.com/weaveworks/grafanalib/releases/new and create the release there. # Wait for GitHub Actions to complete the build and release. # Confirm on https://pypi.org/project/grafanalib/ that the release made it there. ``` -------------------------------- ### Follow-up Actions after grafanalib Release Source: https://grafanalib.readthedocs.io/en/stable/releasing Post-release verification steps for grafanalib, including upgrading the package with pip and re-running tests to confirm the upgrade was successful. ```Shell $ pip ``` ```Shell # Check if the upgrade worked and the test above still passes. ``` -------------------------------- ### Running Tests with Make Source: https://grafanalib.readthedocs.io/en/stable/CONTRIBUTING This command executes the test suite for the grafanalib project using the 'make' utility. It's a standard way to ensure code changes meet the project's quality standards. ```bash $ make ``` -------------------------------- ### RangeMap Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Defines a mapping for a range, associating a start and end value with a specific text representation. ```Python class grafanalib.core.RangeMap(_start_ , _end_ , _text_) Bases: `object` to_json_data() ``` -------------------------------- ### Smoke-testing grafanalib Releases Source: https://grafanalib.readthedocs.io/en/stable/releasing Instructions for smoke-testing a new release of grafanalib to ensure it functions correctly. This involves running Python and checking the generated dashboard utility. ```Shell $ python ``` ```Shell # Check `~/.local/bin/generate-dashboard` for the update version. # Try the example on README. ``` -------------------------------- ### Color Code Validator Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Validates if an attribute value is a valid color code, which must start with '#' followed by hexadecimal characters. ```Python grafanalib.validators.is_color_code(_instance_ , _attribute_ , _value_) A validator that raises a `ValueError` if attribute value is not valid color code. Value considered as valid color code if it starts with # char followed by hexadecimal. ``` -------------------------------- ### grafanalib Elasticsearch Components (T) Source: https://grafanalib.readthedocs.io/en/stable/genindex This section lists core classes and attributes from the grafanalib.elasticsearch module starting with 'T'. These include components for configuring Elasticsearch data sources and targets, such as TermsGroupBy and ElasticsearchTarget. ```python from grafanalib.elasticsearch import ( TermsGroupBy, ElasticsearchTarget, Filter ) # Example usage (conceptual): # es_target = ElasticsearchTarget(query='...', bucketAggs=[TermsGroupBy(field='@timestamp', interval='auto')], metrics=[...]) ``` -------------------------------- ### grafanalib Alerting Components Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib This section covers components related to alerting in grafanalib, including alert definitions, conditions, and provisioning. ```python from grafanalib.core import ( Alert, AlertCondition, AlertExpression, AlertFileBasedProvisioning, AlertGroup, AlertList, AlertRulev8, AlertRulev9 ) # Example usage: # AlertGroup.group_rules() # AlertGroup.to_json_data() # AlertList.to_json_data() # AlertRulev8.to_json_data() # AlertRulev9.to_json_data() ``` -------------------------------- ### Grafanalib Core Classes and Methods Source: https://grafanalib.readthedocs.io/en/stable/genindex Documentation for various classes and methods within the grafanalib.core module, including Panel, Row, and Svg related functionalities. ```python class Mapping(grafanalib.core) class News(grafanalib.core) class Notification(grafanalib.core) NoValue() (in module grafanalib.core) class NumberColumnStyleType(grafanalib.core) class Panel(grafanalib.core) panel_json() (grafanalib.core.Panel method) class Percent(grafanalib.core) class PieChart(grafanalib.core) class PieChartv2(grafanalib.core) class Pixels(grafanalib.core) class RangeMap(grafanalib.core) read_file() (grafanalib.core.Svg static method) class Repeat(grafanalib.core) class RGB(grafanalib.core) class RGBA(grafanalib.core) class Row(grafanalib.core) class RowPanel(grafanalib.core) class SeriesOverride(grafanalib.core) single_y_axis() (in module grafanalib.core) class SingleStat(grafanalib.core) span (grafanalib.core.Table attribute) class SparkLine(grafanalib.core) class SqlTarget(grafanalib.core) class Stat(grafanalib.core) class StateTimeline(grafanalib.core) class StatMapping(grafanalib.core) class StatRangeMapping(grafanalib.core) class StatRangeMappings(grafanalib.core) class Statusmap(grafanalib.core) class StatusmapColor(grafanalib.core) class StatValueMapping(grafanalib.core) class StatValueMappingItem(grafanalib.core) class StatValueMappings(grafanalib.core) class StringColumnStyleType(grafanalib.core) class Svg(grafanalib.core) OutsideRange() (in module grafanalib.core) ``` -------------------------------- ### Core Methods Source: https://grafanalib.readthedocs.io/en/stable/genindex Includes core methods for dashboard configuration, such as converting to Y-axes and applying styled columns. ```Python from grafanalib.core import to_y_axes, with_styled_columns ``` -------------------------------- ### grafanalib Core Methods Source: https://grafanalib.readthedocs.io/en/stable/genindex Core methods and attributes within the grafanalib library, including those for data source targets and panel configurations. ```python auto_bucket_agg_ids() auto_panel_ids() auto_ref_ids() group_rules() asDropdown icon includeVars keepTime heatmap ``` -------------------------------- ### Core Dashboard Components Source: https://grafanalib.readthedocs.io/en/stable/genindex Includes core classes for building Grafana dashboards, such as axes, tooltips, value mapping, and column styling. ```Python from grafanalib.core import Tooltip, ValueMap, XAxis, YAxes, YAxis, WithinRange, Worldmap ``` -------------------------------- ### Grafanalib Weave Classes Source: https://grafanalib.readthedocs.io/en/stable/genindex Documentation for classes related to Weave visualizations in Grafanalib. ```python PercentUnitAxis() (in module grafanalib.weave) PromGraph() (in module grafanalib.prometheus) QPSGraph() (in module grafanalib.weave) stacked() (in module grafanalib.weave) ``` -------------------------------- ### Automate PyPI Publishing Source: https://grafanalib.readthedocs.io/en/stable/CHANGELOG Automates the process of publishing new releases to PyPI using GitHub Actions, ensuring efficient and reliable distribution. ```Python Automate publishing to PyPI with GitHub Actions ``` -------------------------------- ### Grafana Panel Configuration Options Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib This section details various configuration options for Grafana panels, including color mapping, legend display, time formatting, and value display settings. These options allow for fine-grained control over how data is presented in Grafana. ```APIDOC colorMaps: list of DiscreteColorMappingItem, to color values (note these apply **after** value mappings) backgroundColor: dito lineColor: Separator line color between rows metricNameColor: dito timeTextColor: dito valueTextColor: dito decimals: number of decimals to display rowHeight: dito units: defines value units legendSortBy: time (desc: ‘-ms’, asc: ‘ms), count (desc: ‘-count’, asc: ‘count’) highlightOnMouseover: whether to highlight the state of hovered time falls in. showLegend: dito showLegendPercent: whether to show percentage of time spent in each state/value showLegendNames: showLegendValues: whether to values in legend legendPercentDecimals: number of decimals for legend showTimeAxis: dito use12HourClock: dito writeMetricNames: dito writeLastValue: dito writeAllValues: whether to show all values showDistinctCount: whether to show distinct values count showLegendCounts: whether to show value occurrence count showLegendTime: whether to show of each state showTransitionCount: whether to show transition count colorMaps: list of DiscreteColorMappingItem rangeMaps: list of RangeMap valueMaps: list of ValueMap ``` -------------------------------- ### Grafana Worldmap Panel Configuration Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Configuration for the Grafana Worldmap panel, which visualizes data on a world map. Supports various options for data aggregation, circle sizing, location data formatting, map centering, and thresholding. ```python class grafanalib.core.Worldmap: def __init__(self, aggregation: str = 'total', circleMaxSize: int = 30, circleMinSize: int = 2, decimals: int = 0, geoPoint: str = 'geohash', locationData: str = 'countries', locationName: str = '', metric: str = 'Value', mapCenter: str = '(0°, 0°)', mapCenterLatitude: float = 0, mapCenterLongitude: float = 0, hideEmpty: bool = False, hideZero: bool = False, initialZoom: int = 1, jsonUrl: str = '', jsonpCallback: str = '', mouseWheelZoom: bool = False, stickyLabels: bool = False, thresholds: str = '0,100,150', thresholdsColors: list[str] = ['#73BF69', '#73BF69', '#FADE2A', '#C4162A'], unitPlural: str = '', unitSingular: str = '', **kwargs): # aggregation: 'min', 'max', 'avg', 'current', 'total' # geoPoint: Name of the geo_point/geohash column # locationData: Format of location data (e.g., 'countries', 'autocomp-countries') # locationName: Name of the Location Name column for labels # metric: Name of the metric column for circle size # mapCenter: Initial map center ('North America', 'Europe', etc. or custom lat/lon) # thresholds: String of thresholds (e.g., '0,10,20') # thresholdsColors: List of colors for thresholds pass ``` -------------------------------- ### grafanalib Panel Components Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib This section details various components used in grafanalib for creating Grafana panels, including data targets, display options, and layout configurations. ```python from grafanalib.core import ( CloudwatchLogsInsightsTarget, CloudwatchMetricsTarget, Ae3ePlotly, Alert, AlertCondition, AlertExpression, AlertFileBasedProvisioning, AlertGroup, AlertList, AlertRulev8, AlertRulev9, Annotations, BarChart, BarGauge, Column, ColumnSort, ColumnStyle, ConstantInput, Dashboard, DashboardLink, DashboardList, DataLink, DataSourceInput, DateColumnStyleType, Discrete, DiscreteColorMappingItem, Evaluator, ExternalLink, Gauge, GaugePanel, Graph, GraphThreshold, Grid, GridPos, Heatmap, HeatmapColor, HiddenColumnStyleType, Histogram, Legend, Logs, Mapping, News, Notification, NumberColumnStyleType, Panel, Percent, PieChart, PieChartv2, Pixels, RGB, RGBA, RangeMap, Repeat, Row, RowPanel, SeriesOverride, SingleStat, SparkLine, SqlTarget, Stat, StatMapping, StatRangeMapping, StatRangeMappings, StatValueMapping, StatValueMappingItem, StatValueMappings, StateTimeline, Statusmap, StatusmapColor ) # Example usage for a few components: # CloudwatchLogsInsightsTarget.to_json_data() # Dashboard.auto_panel_ids() # DashboardLink.asDropdown # Graph.auto_ref_ids() # GridPos.to_json_data() # Panel.panel_json() # Row.to_json_data() # SingleStat.to_json_data() # SqlTarget.to_json_data() # Stat.to_json_data() # Statusmap.to_json_data() ``` -------------------------------- ### Grafanalib Modules Source: https://grafanalib.readthedocs.io/en/stable/genindex List of available modules within the Grafanalib library. ```python module grafanalib module grafanalib.cloudwatch module grafanalib.core module grafanalib.elasticsearch module grafanalib.formatunits module grafanalib.influxdb module grafanalib.opentsdb module grafanalib.prometheus module grafanalib.validators module grafanalib.weave module grafanalib.zabbix ``` -------------------------------- ### Use Github Actions for CI Source: https://grafanalib.readthedocs.io/en/stable/CHANGELOG Migrates the Continuous Integration process to GitHub Actions, streamlining build, test, and deployment workflows. ```Python Use Github Actions for CI. ``` -------------------------------- ### ePict Panel Configuration Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Generates JSON structure for the ePict panel plugin in Grafana. Allows displaying images with data overlays, including auto-scaling and background image URLs. ```APIDOC grafanalib.core.ePict(_dataSource =None_, _targets =_Nothing.NOTHING_, _title =''_, _cacheTimeout =None_, _description =None_, _editable =True_, _error =False_, _height =None_, _gridPos =None_, _hideTimeOverride =False_, _id =None_, _interval =None_, _links =_Nothing.NOTHING_, _maxDataPoints =100_, _minSpan =None_, _repeat =_Nothing.NOTHING_, _span =None_, _thresholds =_Nothing.NOTHING_, _thresholdType ='absolute'_, _timeFrom =None_, _timeShift =None_, _transparent =False_, _transformations =_Nothing.NOTHING_, _extraJson =None_, _bgURL =''_, _autoScale =True_, _boxes =_Nothing.NOTHING_) Description: Generates ePict panel json structure. https://grafana.com/grafana/plugins/larona-epict-panel/ Parameters: * **autoScale**: Whether to auto scale image to panel size. * **bgURL**: Where to load the image from. * **boxes**: The info boxes to be placed on the image. ``` -------------------------------- ### Grafana Templating Options Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Describes options for Grafana templating variables, including multi-select, type, and visibility settings. ```Python multi: If enabled, the variable will support the selection of multiple options at the same time. type: The template type, can be one of: query (default), interval, datasource, custom, constant, adhoc. hide: Hide this variable in the dashboard, can be one of: SHOW (default), HIDE_LABEL, HIDE_VARIABLE auto: Interval will be dynamically calculated by dividing time range by the count specified in auto_count. autoCount: Number of intervals for dividing the time range. autoMin: Smallest interval for auto interval generator. ``` -------------------------------- ### Weave Visualization Components Source: https://grafanalib.readthedocs.io/en/stable/api/modules Components for creating specific visualizations like PercentUnitAxis and QPSGraph using the Weave integration. ```python PercentUnitAxis() QPSGraph() stacked() ``` -------------------------------- ### grafanalib Module Index Source: https://grafanalib.readthedocs.io/en/stable/genindex Lists the available modules within the grafanalib library. ```python grafanalib.cloudwatch grafanalib.core grafanalib.elasticsearch grafanalib.formatunits grafanalib.influxdb grafanalib.opentsdb grafanalib.prometheus grafanalib.validators grafanalib.weave grafanalib.zabbix ``` -------------------------------- ### grafanalib Data Source and Target Components Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib This section details components for specifying data sources and targets within Grafana panels, such as CloudWatch and SQL. ```python from grafanalib.core import ( CloudwatchLogsInsightsTarget, CloudwatchMetricsTarget, SqlTarget ) # Example usage: # CloudwatchLogsInsightsTarget.to_json_data() # CloudwatchMetricsTarget.to_json_data() # SqlTarget.to_json_data() ``` -------------------------------- ### grafanalib Table and Column Styling Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib This section covers components for configuring table panels, including column definitions, sorting, and custom styling. ```python from grafanalib.core import ( Column, ColumnSort, ColumnStyle, DateColumnStyleType, HiddenColumnStyleType, NumberColumnStyleType ) # Example usage: # Column.to_json_data() # ColumnSort.to_json_data() # ColumnStyle.to_json_data() # DateColumnStyleType.to_json_data() # HiddenColumnStyleType.to_json_data() # NumberColumnStyleType.to_json_data() ``` -------------------------------- ### DataSourceInput Class Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Defines an input for selecting a data source in Grafana. Requires a name, label, and plugin information, with an optional description. ```Python _class_ grafanalib.core.DataSourceInput(_name_ , _label_ , _pluginId_ , _pluginName_ , _description =''_) Bases: `object` to_json_data() ``` -------------------------------- ### Grafanalib OpenTSDB Classes Source: https://grafanalib.readthedocs.io/en/stable/genindex Documentation for OpenTSDB related classes in Grafanalib, including filters and targets. ```python class OpenTSDBFilter(grafanalib.opentsdb) class OpenTSDBTarget(grafanalib.opentsdb) ``` -------------------------------- ### Weave QPSGraph Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Creates a graph visualizing Queries Per Second (QPS) broken down by response code, drawing data from Prometheus. Requires a specific number of Prometheus expressions. ```Python grafanalib.weave.QPSGraph(_data_source_ , _title_ , _expressions_ , _** kwargs_) Create a graph of QPS, broken up by response code. Data is drawn from Prometheus. Parameters: * **title** – Title of the graph. * **expressions** – List of Prometheus expressions. Must be 5. * **kwargs** – Passed on to Graph. ``` -------------------------------- ### Prometheus Graph Configuration Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Creates a Grafana graph that renders Prometheus data. Requires data source, title, and a list of Prometheus expressions. ```Python grafanalib.prometheus.PromGraph(_data_source_ , _title_ , _expressions_ , _** kwargs_) Parameters: data_source: The name of the data source that provides Prometheus data. title: The title of the graph. expressions: List of tuples of (legend, expr), where ‘expr’ is a Prometheus expression. Or a list of dict where keys are Target’s args. kwargs: Passed on to Graph. ``` -------------------------------- ### grafanalib Dashboard Creation Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib This section focuses on the core `Dashboard` object in grafanalib, including methods for automatic panel ID assignment and converting the dashboard to JSON. ```python from grafanalib.core import Dashboard # Example usage: # dashboard = Dashboard(title="My Dashboard", rows=[...]) # dashboard.auto_panel_ids() # dashboard_json = dashboard.to_json_data() ``` -------------------------------- ### Grafanalib Core Components Source: https://grafanalib.readthedocs.io/en/stable/api/modules Provides core components for building Grafana dashboards, including various panel types, data source targets, and utility functions. ```python StringColumnStyleType.TYPE StringColumnStyleType.to_json_data() Svg.read_file() Svg.to_json_data() Table.span Table.to_json_data() Table.with_styled_columns() TableSortByField.to_json_data() Target.to_json_data() Template.to_json_data() Templating.to_json_data() Text.to_json_data() Threshold.to_json_data() Time.to_json_data() TimePicker.to_json_data() TimeRange.to_json_data() TimeSeries.to_json_data() Tooltip.to_json_data() ValueMap.to_json_data() WithinRange() XAxis.to_json_data() YAxes.to_json_data() YAxis.to_json_data() ePict.to_json_data() ePictBox.to_json_data() is_valid_max_per_row() is_valid_target() is_valid_triggers() is_valid_triggersv9() is_valid_xaxis_mode() single_y_axis() to_y_axes() ``` -------------------------------- ### grafanalib InfluxDB Target Source: https://grafanalib.readthedocs.io/en/stable/genindex Class for configuring InfluxDB as a data source. ```python from grafanalib.influxdb import InfluxDBTarget ``` -------------------------------- ### Data Target Configuration Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Specifies a data target for a Grafana panel, defining how to fetch metrics. Supports various data sources and formats, including Graphite query syntax. ```python class grafanalib.core.Target( _expr='', _format='time_series', _hide=False, _legendFormat='', _interval='', _intervalFactor=2, _metric='', _refId='', _step=10, _target='', _instant=False, _datasource=None ) Parameters: target: Graphite way to select data to_json_data() ``` -------------------------------- ### Statusmap Panel Configuration Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Generates the JSON structure for the flant-statusmap-panel visualization plugin. This panel displays data in a status map format. It allows configuration of cards, colors, legends, tooltips, and axes. ```python class grafanalib.core.Statusmap(_dataSource =None_, _targets =_Nothing.NOTHING_, _title =''_, _cacheTimeout =None_, _description =None_, _editable =True_, _error =False_, _height =None_, _gridPos =None_, _hideTimeOverride =False_, _id =None_, _interval =None_, _links =_Nothing.NOTHING_, _maxDataPoints =100_, _minSpan =None_, _repeat =_Nothing.NOTHING_, _span =None_, _thresholds =_Nothing.NOTHING_, _thresholdType ='absolute'_, _timeFrom =None_, _timeShift =None_, _transparent =False_, _transformations =_Nothing.NOTHING_, _extraJson =None_, _alert =None_, _cards ={'cardHSpacing': 2, 'cardMinWidth': 5, 'cardRound': None, 'cardVSpacing': 2}_, _color =_Nothing.NOTHING_, _isNew =True_, _legend =_Nothing.NOTHING_, _nullPointMode ='null as zero'_, _tooltip =_Nothing.NOTHING_, _xAxis =_Nothing.NOTHING_, _yAxis =_Nothing.NOTHING_) Generates json structure for the flant-statusmap-panel visualisation plugin (https://grafana.com/grafana/plugins/flant-statusmap-panel/). Parameters: alert – Alert cards – A statusmap card object: keys ‘cardRound’, ‘cardMinWidth’, ‘cardHSpacing’, ‘cardVSpacing’ color – A StatusmapColor object isNew – isNew legend – Legend object nullPointMode – null tooltip – Tooltip object xAxis – XAxis object yAxis – YAxis object ``` -------------------------------- ### Dashboard Creation and Management Source: https://grafanalib.readthedocs.io/en/stable/api/grafanalib Represents a Grafana dashboard, allowing configuration of title, panels, rows, templating, and other dashboard-level settings. Includes a method to automatically assign unique IDs to panels. ```Python grafanalib.core.Dashboard( title_, annotations=None, description='', editable=True, gnetId=None, graphTooltip=0, hideControls=False, id=None, inputs=None, links=None, panels=None, refresh='10s', rows=None, schemaVersion=12, sharedCrosshair=False, style='dark', tags=None, templating=None, time=None, timePicker=None, timezone='utc', version=0, uid=None ) ```