grafanalib package

Submodules

grafanalib.cloudwatch module

Helpers to create Cloudwatch-specific Grafana queries.

class grafanalib.cloudwatch.CloudwatchLogsInsightsTarget(expression='', id='', logGroupNames=[], namespace='', refId='', region='default', statsGroups=[], hide=False)

Bases: object

Generates Cloudwatch Logs Insights target JSON structure.

Grafana docs on using Cloudwatch: https://grafana.com/docs/grafana/latest/datasources/cloudwatch/

AWS docs on Cloudwatch Logs Insights: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html

Parameters
  • expression – Cloudwatch Logs Insights expressions

  • id – unique id

  • logGroupNames – List of Cloudwatch log groups to query

  • namespace – Cloudwatch namespace

  • refId – target reference id

  • region – Cloudwatch region

  • statsGroups – Cloudwatch statsGroups

  • hide – controls if given metric is displayed on visualization

to_json_data()
class grafanalib.cloudwatch.CloudwatchMetricsTarget(alias='', dimensions={}, expression='', id='', matchExact=True, metricName='', namespace='', period='', refId='', region='default', statistics=['Average'], hide=False)

Bases: object

Generates Cloudwatch target JSON structure.

Grafana docs on using Cloudwatch: https://grafana.com/docs/grafana/latest/datasources/cloudwatch/

AWS docs on Cloudwatch metrics: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-services-cloudwatch-metrics.html

Parameters
  • alias – legend alias

  • dimensions – Cloudwatch dimensions dict

  • expression – Cloudwatch Metric math expressions

  • id – unique id

  • matchExact – Only show metrics that exactly match all defined dimension names.

  • metricName – Cloudwatch metric name

  • namespace – Cloudwatch namespace

  • period – Cloudwatch data period

  • refId – target reference id

  • region – Cloudwatch region

  • statistics – Cloudwatch mathematic statistic

  • hide – controls if given metric is displayed on visualization

to_json_data()

grafanalib.core module

Low-level functions for building Grafana dashboards.

The functions in this module don’t enforce Weaveworks policy, and only mildly encourage it by way of some defaults. Rather, they are ways of building arbitrary Grafana JSON.

class grafanalib.core.Alert(name, message, alertConditions, executionErrorState='alerting', frequency='60s', handler=1, noDataState='no_data', notifications=NOTHING, gracePeriod='5m', alertRuleTags=NOTHING)

Bases: object

Parameters

alertRuleTags – Key Value pairs to be sent with Alert notifications.

to_json_data()
class grafanalib.core.AlertCondition(target, evaluator, timeRange, operator, reducerType, *, type='query')

Bases: object

A condition on an alert.

Parameters
  • target (Target) – Metric the alert condition is based on.

  • evaluator (Evaluator) – How we decide whether we should alert on the metric. e.g. GreaterThan(5) means the metric must be greater than 5 to trigger the condition. See GreaterThan, LowerThan, WithinRange, OutsideRange, NoValue.

  • timeRange (TimeRange) – How long the condition must be true for before we alert.

  • operator – One of OP_AND or OP_OR. How this condition combines with other conditions.

  • reducerType – RTYPE_*

  • type – CTYPE_*

to_json_data()
class grafanalib.core.AlertList(dashboardTags=NOTHING, description='', gridPos=None, id=None, limit=10, links=NOTHING, nameFilter='', onlyAlertsOnDashboard=True, show='current', sortOrder=1, span=6, stateFilter=NOTHING, title='', transparent=False)

Bases: object

Generates the AlertList Panel.

Parameters
  • dashboardTags – A list of tags (strings) for the panel.

  • description – Panel description, supports markdown and links.

  • gridPos – describes the panel size and position in grid coordinates.

  • id – panel id

  • limit – Max number of alerts that can be displayed in the list.

  • nameFilter – Show only alerts that contain nameFilter in their name.

  • onlyAlertsOnDashboard – If true, shows only alerts from the current dashboard.

  • links – Additional web links to be presented in the panel. A list of instantiation of DataLink objects.

  • show – Show the current alert list (ALERTLIST_SHOW_CURRENT) or only the alerts that were changed (ALERTLIST_SHOW_CHANGES).

  • sortOrder – Defines the sorting order of the alerts. Gets one of the following values as input: SORT_ASC, SORT_DESC and SORT_IMPORTANCE.

  • span – Defines the number of spans that will be used for the panel.

  • stateFilter – Show alerts with statuses from the stateFilter list. The list can contain a subset of the following statuses: [ALERTLIST_STATE_ALERTING, ALERTLIST_STATE_OK, ALERTLIST_STATE_NO_DATA, ALERTLIST_STATE_PAUSED, ALERTLIST_STATE_EXECUTION_ERROR, ALERTLIST_STATE_PENDING]. An empty list means all alerts.

  • title – The panel title.

  • transparent – If true, display the panel without a background.

to_json_data()
class grafanalib.core.Annotations(list=NOTHING)

Bases: object

to_json_data()
class grafanalib.core.BarGauge(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, allValues=False, calc='mean', dataLinks=NOTHING, decimals=None, displayMode='lcd', format='none', label=None, limit=None, max=100, min=0, orientation='horizontal', rangeMaps=NOTHING, thresholdLabels=False, thresholdMarkers=True, thresholds=NOTHING, valueMaps=NOTHING)

Bases: grafanalib.core.Panel

Generates Bar Gauge panel json structure

Parameters
  • allValue – If All values should be shown or a Calculation

  • calc – Calculation to perform on metrics

  • dataLinks – list of data links hooked to datapoints on the graph

  • decimals – override automatic decimal precision for legend/tooltips

  • displayMode – style to display bar gauge in

  • format – defines value units

  • labels – option to show gauge level labels

  • limit – limit of number of values to show when not Calculating

  • max – maximum value of the gauge

  • min – minimum value of the gauge

  • orientation – orientation of the bar gauge

  • rangeMaps – the list of value to text mappings

  • thresholdLabel – label for gauge. Template Variables: “$__series_namei” “$__field_name” “$__cell_{N} / $__calc”

  • thresholdMarkers – option to show marker of level on gauge

  • thresholds – single stat thresholds

  • valueMaps – the list of value to text mappings

to_json_data()
class grafanalib.core.Column(text='Avg', value='avg')

Bases: object

Details of an aggregation column in a table panel.

Parameters
  • text – name of column

  • value – aggregation function

to_json_data()
class grafanalib.core.ColumnSort(col=None, desc=False)

Bases: object

to_json_data()
class grafanalib.core.ColumnStyle(alias='', pattern='', align='auto', link=False, linkOpenInNewTab=False, linkUrl='', linkTooltip='', type=NOTHING)

Bases: object

to_json_data()
class grafanalib.core.ConstantInput(name, label, value, description='')

Bases: object

to_json_data()
class grafanalib.core.Dashboard(title, annotations=NOTHING, description='', editable=True, gnetId=None, hideControls=False, id=None, inputs=NOTHING, links=NOTHING, panels=NOTHING, refresh='10s', rows=NOTHING, schemaVersion=12, sharedCrosshair=False, style='dark', tags=NOTHING, templating=NOTHING, time=NOTHING, timePicker=NOTHING, timezone='utc', version=0, uid=None)

Bases: object

auto_panel_ids()

Give unique IDs all the panels without IDs.

Returns a new Dashboard that is the same as this one, except all of the panels have their id property set. Any panels which had an id property set will keep that property, all others will have auto-generated IDs provided for them.

to_json_data()

Bases: object

to_json_data()
class grafanalib.core.DashboardList(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, showHeadings=True, showSearch=False, showRecent=False, showStarred=True, maxItems=10, searchQuery='', searchTags=NOTHING, overrides=NOTHING)

Bases: grafanalib.core.Panel

Generates Dashboard list panel json structure Grafana doc on Dashboard list: https://grafana.com/docs/grafana/latest/panels/visualizations/dashboard-list-panel/

Parameters
  • showHeadings – The chosen list selection (Starred, Recently viewed, Search) is shown as a heading

  • showSearch – Display dashboards by search query or tags. Requires you to enter at least one value in Query or Tags

  • showRecent – Display recently viewed dashboards in alphabetical order

  • showStarred – Display starred dashboards in alphabetical order

  • maxItems – Sets the maximum number of items to list per section

  • searchQuery – Enter the query you want to search by

  • searchTags – List of tags you want to search by

  • overrides – To override the base characteristics of certain data

to_json_data()

Bases: object

to_json_data()
class grafanalib.core.DataSourceInput(name, label, pluginId, pluginName, description='')

Bases: object

to_json_data()
class grafanalib.core.DateColumnStyleType(dateFormat='YYYY-MM-DD HH:mm:ss')

Bases: object

TYPE = 'date'
to_json_data()
class grafanalib.core.Discrete(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, backgroundColor=RGBA(r=128, g=128, b=128, a=0.1), lineColor=RGBA(r=0, g=0, b=0, a=0.1), metricNameColor='#000000', timeTextColor='#d8d9da', valueTextColor='#000000', decimals=0, legendPercentDecimals=0, rowHeight=50, textSize=24, textSizeTime=12, units='none', legendSortBy='-ms', highlightOnMouseover=True, showLegend=True, showLegendPercent=True, showLegendNames=True, showLegendValues=True, showTimeAxis=True, use12HourClock=False, writeMetricNames=False, writeLastValue=True, writeAllValues=False, showDistinctCount=None, showLegendCounts=None, showLegendTime=None, showTransitionCount=None, colorMaps=[], rangeMaps=[], valueMaps=[])

Bases: grafanalib.core.Panel

Generates Discrete panel json structure. https://grafana.com/grafana/plugins/natel-discrete-panel/

Parameters
  • 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

to_json_data()
class grafanalib.core.DiscreteColorMappingItem(text, color=RGBA(r=216, g=200, b=27, a=0.27))

Bases: object

Generates json structure for the value mapping item for the StatValueMappings class:

Parameters
  • text – String to color

  • color – To color the text with

to_json_data()
class grafanalib.core.Evaluator(type, params)

Bases: object

to_json_data()

Bases: object

ExternalLink creates a top-level link attached to a dashboard.

Parameters
  • url – the URL to link to

  • title – the text of the link

  • keepTime – if true, the URL params for the dashboard’s current time period are appended

to_json_data()
class grafanalib.core.Gauge(minValue=0, maxValue=100, show=False, thresholdLabels=False, thresholdMarkers=True)

Bases: object

to_json_data()
class grafanalib.core.GaugePanel(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, allValues=False, calc='mean', dataLinks=NOTHING, decimals=None, format='none', label=None, limit=None, max=100, min=0, rangeMaps=NOTHING, thresholdLabels=False, thresholdMarkers=True, thresholds=NOTHING, valueMaps=NOTHING)

Bases: grafanalib.core.Panel

Generates Gauge panel json structure

Parameters
  • allValue – If All values should be shown or a Calculation

  • calc – Calculation to perform on metrics

  • dataLinks – list of data links hooked to datapoints on the graph

  • decimals – override automatic decimal precision for legend/tooltips

  • format – defines value units

  • labels – option to show gauge level labels

  • limit – limit of number of values to show when not Calculating

  • max – maximum value of the gauge

  • min – minimum value of the gauge

  • rangeMaps – the list of value to text mappings

  • thresholdLabel – label for gauge. Template Variables: “$__series_namei” “$__field_name” “$__cell_{N} / $__calc”

  • thresholdMarkers – option to show marker of level on gauge

  • thresholds – single stat thresholds

  • valueMaps – the list of value to text mappings

to_json_data()
class grafanalib.core.Graph(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, alert=None, alertThreshold=True, aliasColors=NOTHING, align=False, alignLevel=0, bars=False, dataLinks=NOTHING, error=False, fill=1, fillGradient=0, grid=NOTHING, isNew=True, legend=NOTHING, lines=True, lineWidth=2, nullPointMode='connected', percentage=False, pointRadius=5, points=False, renderer='flot', seriesOverrides=NOTHING, stack=False, steppedLine=False, tooltip=NOTHING, thresholds=NOTHING, xAxis=NOTHING, yAxes=NOTHING)

Bases: grafanalib.core.Panel

Generates Graph panel json structure.

Parameters
  • alert – List of AlertConditions

  • align – Select to align left and right Y-axes by value

  • alignLevel – Available when Align is selected. Value to use for alignment of left and right Y-axes

  • bars – Display values as a bar chart

  • dataLinks – List of data links hooked to datapoints on the graph

  • fill – Area fill, amount of color fill for a series. (default 1, 0 is none)

  • fillGradient – Degree of gradient on the area fill. (0 is no gradient, 10 is a steep gradient. Default is 0.)

  • lines – Display values as a line graph

  • points – Display points for values (default False)

  • pointRadius – Controls how large the points are

  • stack – Each series is stacked on top of another

  • percentage – Available when Stack is selected. Each series is drawn as a percentage of the total of all series

  • thresholds – List of GraphThresholds - Only valid when alert not defined

auto_ref_ids()

Give unique IDs all the panels without IDs.

Returns a new Graph that is the same as this one, except all of the metrics have their refId property set. Any panels which had an refId property set will keep that property, all others will have auto-generated IDs provided for them.

to_json_data()
class grafanalib.core.GraphThreshold(value, colorMode='critical', fill=True, line=True, op='gt', yaxis='left', fillColor=RGBA(r=245, g=54, b=54, a=0.9), lineColor=RGBA(r=245, g=54, b=54, a=0.9))

Bases: object

Threshold for for Graph panel (https://grafana.com/docs/grafana/latest/panels/thresholds/)

Parameters
  • colorMode – Color mode of the threshold, value can be ok, warning, critical or custom. If custom is selcted a lineColor and fillColor should be provided

  • fill – Display threshold fill, defaults to True

  • line – Display threshold line, defaults to True

  • value – When to use this color will be null if index is 0

  • op – EVAL_LT for less than or EVAL_GT for greater than to indicate what the threshold applies to.

  • yaxis – Choose left or right for Graph panels

  • fillColor – Fill color of the threshold, when colorMode = “custom”

  • lineColor – Line color of the threshold, when colorMode = “custom”

Example:
thresholds = [

GraphThreshold(colorMode=”ok”, value=10.0), GraphThreshold(colorMode=”critical”, value=90.0) ]

to_json_data()
grafanalib.core.GreaterThan(value)
class grafanalib.core.Grid(threshold1=None, threshold1Color=NOTHING, threshold2=None, threshold2Color=NOTHING)

Bases: object

to_json_data()
class grafanalib.core.GridPos(h, w, x, y)

Bases: object

GridPos describes the panel size and position in grid coordinates.

Parameters
  • h – height of the panel, grid height units each represents 30 pixels

  • w – width of the panel 1-24 (the width of the dashboard is divided into 24 columns)

  • x – x cordinate of the panel, in same unit as w

  • y – y cordinate of the panel, in same unit as h

to_json_data()
class grafanalib.core.Heatmap(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, legend={'show': False}, tooltip=NOTHING, cards={'cardPadding': None, 'cardRound': None}, color=NOTHING, dataFormat='timeseries', hideZeroBuckets=False, highlightCards=True, options=None, xAxis=NOTHING, xBucketNumber=None, xBucketSize=None, yAxis=NOTHING, yBucketBound=None, yBucketNumber=None, yBucketSize=None, reverseYBuckets=False)

Bases: grafanalib.core.Panel

Generates Heatmap panel json structure (https://grafana.com/docs/grafana/latest/features/panels/heatmap/)

Parameters
  • heatmap – dict

  • cards – A heatmap card object: keys “cardPadding”, “cardRound”

  • color – Heatmap color object

  • dataFormat – ‘timeseries’ or ‘tsbuckets’

  • yBucketBound – ‘auto’, ‘upper’, ‘middle’, ‘lower’

  • reverseYBuckets – boolean

  • xBucketSize – Size

  • xBucketNumber – Number

  • yBucketSize – Size

  • yBucketNumber – Number

  • highlightCards – boolean

  • hideZeroBuckets – boolean

  • transparent – defines if the panel should be transparent

heatmap = {}
to_json_data()
class grafanalib.core.HeatmapColor(cardColor='#b4ff00', colorScale='sqrt', colorScheme='interpolateOranges', exponent=0.5, mode='spectrum', max=None, min=None)

Bases: object

A Color object for heatmaps

Parameters
  • cardColor – color

  • colorScale – scale

  • colorScheme – scheme

  • exponent – exponent

  • max – max

  • min – min

  • mode – mode

to_json_data()
class grafanalib.core.HiddenColumnStyleType

Bases: object

TYPE = 'hidden'
to_json_data()
class grafanalib.core.Legend(avg=False, current=False, max=False, min=False, show=True, total=False, values=None, alignAsTable=False, hideEmpty=False, hideZero=False, rightSide=False, sideWidth=None, sort=None, sortDesc=False)

Bases: object

to_json_data()
class grafanalib.core.Logs(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, showLabels=False, showCommonLabels=False, showTime=False, wrapLogMessages=False, sortOrder='Descending', dedupStrategy='none', enableLogDetails=False, overrides=NOTHING, prettifyLogMessage=False)

Bases: grafanalib.core.Panel

Generates Logs panel json structure Grafana doc on Logs panel: https://grafana.com/docs/grafana/latest/panels/visualizations/logs-panel/

Parameters
  • showLabels – Show or hide the unique labels column, which shows only non-common labels

  • showCommonLabels – Show or hide the common labels.

  • showTime – Show or hide the log timestamp column

  • wrapLogMessages – Toggle line wrapping

  • sortOrder – Display results in ‘Descending’ or ‘Ascending’ time order. The default is Descending, showing the newest logs first.

  • dedupStrategy – One of none, exact, numbers, signature. Default is none

  • enableLogDetails – Set this to True to see the log details view for each log row.

  • overrides – To override the base characteristics of certain data

  • prettifyLogMessage – Set this to true to pretty print all JSON logs. This setting does not affect logs in any format other than JSON.

to_json_data()
grafanalib.core.LowerThan(value)
class grafanalib.core.Mapping(name, value)

Bases: object

to_json_data()
class grafanalib.core.News(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, feedUrl='', showImage=True, useProxy=False)

Bases: grafanalib.core.Panel

Generates News panel json structure Grafana docs on State Timeline panel: https://grafana.com/docs/grafana/next/visualizations/news-panel/

Parameters
  • feedUrl – URL to query, only RSS feed formats are supported (not Atom).

  • showImage – Controls if the news item social (og:image) image is shown above text content

  • useProxy – If the feed is unable to connect, consider a CORS proxy

to_json_data()
grafanalib.core.NoValue()
class grafanalib.core.Notification(uid)

Bases: object

to_json_data()
class grafanalib.core.NumberColumnStyleType(colorMode=None, colors=NOTHING, thresholds=NOTHING, decimals=2, unit='short')

Bases: object

TYPE = 'number'
to_json_data()
grafanalib.core.OutsideRange(from_value, to_value)
class grafanalib.core.Panel(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None)

Bases: object

Generic panel for shared defaults

Parameters
  • cacheTimeout – metric query result cache ttl

  • dataSource – Grafana datasource name

  • description – optional panel description

  • editable – defines if panel is editable via web interfaces

  • height – defines panel height

  • hideTimeOverride – hides time overrides

  • id – panel id

  • interval – defines time interval between metric queries

  • links – additional web links

  • maxDataPoints – maximum metric query results, that will be used for rendering

  • minSpan – minimum span number

  • repeat – Template’s name to repeat Graph on

  • span – defines the number of spans that will be used for panel

  • targets – list of metric requests for chosen datasource

  • timeFrom – time range that Override relative time

  • title – of the panel

  • transparent – defines if panel should be transparent

  • transformations – defines transformations applied to the table

  • extraJson – raw JSON additions or overrides added to the JSON output of this panel, can be used for using unsupported features

panel_json(overrides)
class grafanalib.core.Percent(num=100)

Bases: object

to_json_data()
class grafanalib.core.PieChart(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, aliasColors=NOTHING, format='none', legendType='Right side', overrides=NOTHING, pieType='pie', percentageDecimals=0, showLegend=True, showLegendValues=True, showLegendPercentage=False, thresholds='')

Bases: grafanalib.core.Panel

Generates Pie Chart panel json structure

This panel was deprecated in Grafana 8.0, please use PieChartv2 instead

Grafana doc on Pie Chart: https://grafana.com/grafana/plugins/grafana-piechart-panel

Parameters
  • aliasColors – dictionary of color overrides

  • format – defines value units

  • legendType – defines where the legend position

  • overrides – To override the base characteristics of certain data

  • pieType – defines the shape of the pie chart (pie or donut)

  • percentageDecimals – Number of decimal places to show if percentages shown in legned

  • showLegend – defines if the legend should be shown

  • showLegendValues – defines if the legend should show values

  • showLegendPercentage – Show percentages in the legend

  • thresholds – defines thresholds

to_json_data()
class grafanalib.core.PieChartv2(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, custom={}, colorMode='palette-classic', legendDisplayMode='list', legendPlacement='bottom', legendValues=[], mappings=NOTHING, overrides=[], pieType='pie', reduceOptionsCalcs=['lastNotNull'], reduceOptionsFields='', reduceOptionsValues=False, tooltipMode='single', unit='')

Bases: grafanalib.core.Panel

Generates Pie Chart panel json structure Grafana docs on Pie Chart: https://grafana.com/docs/grafana/latest/visualizations/pie-chart-panel/

Parameters
  • custom – Custom overides

  • colorMode – Color mode palette-classic (Default),

  • legendDisplayMode – Display mode of legend: list, table or hidden

  • legendPlacement – Location of the legend in the panel: bottom or right

  • legendValues – List of value to be shown in legend eg. [‘value’, ‘percent’]

  • mappings – To assign colors to boolean or string values, use Value mappings

  • overrides – Overrides

  • pieType – Pie chart type pie (Default), donut

  • reduceOptionsCalcs – Reducer function / calculation

  • reduceOptionsFields – Fields that should be included in the panel

  • reduceOptionsValues – Calculate a single value per column or series or show each row

  • tooltipMode – Tooltip mode single (Default), multi, none

  • unit – units

to_json_data()
class grafanalib.core.Pixels(num)

Bases: object

to_json_data()
class grafanalib.core.RGB(r, g, b)

Bases: object

to_json_data()
class grafanalib.core.RGBA(r, g, b, a)

Bases: object

to_json_data()
class grafanalib.core.RangeMap(start, end, text)

Bases: object

to_json_data()
class grafanalib.core.Repeat(direction=None, variable=None, maxPerRow=None)

Bases: object

Panel repetition settings.

Parameters
  • direction – The direction into which to repeat (‘h’ or ‘v’)

  • variable – The name of the variable over whose values to repeat

  • maxPerRow – The maximum number of panels per row in horizontal repetition

class grafanalib.core.Row(panels=NOTHING, collapse=False, editable=True, height=NOTHING, showTitle=None, title=None, repeat=None)

Bases: object

Legacy support for old row, when not used with gridpos

to_json_data()
class grafanalib.core.RowPanel(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, panels=NOTHING, collapsed=False)

Bases: grafanalib.core.Panel

Generates Row panel json structure.

Parameters
  • title – title of the panel

  • collapsed – set True if row should be collapsed

  • panels – list of panels in the row, only to be used when collapsed=True

to_json_data()
class grafanalib.core.SeriesOverride(alias, bars=False, lines=True, yaxis=1, color=None)

Bases: object

to_json_data()
class grafanalib.core.SingleStat(dataSource=None, targets=NOTHING, title='', description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, cacheTimeout=None, colors=NOTHING, colorBackground=False, colorValue=False, decimals=None, format='none', gauge=NOTHING, mappingType=1, mappingTypes=NOTHING, minSpan=None, nullText=None, nullPointMode='connected', postfix='', postfixFontSize='50%', prefix='', prefixFontSize='50%', rangeMaps=NOTHING, sparkline=NOTHING, thresholds='', valueFontSize='80%', valueName='avg', valueMaps=NOTHING)

Bases: grafanalib.core.Panel

Generates Single Stat panel json structure

This panel was deprecated in Grafana 7.0, please use Stat instead

Grafana doc on singlestat: https://grafana.com/docs/grafana/latest/features/panels/singlestat/

Parameters
  • cacheTimeout – metric query result cache ttl

  • colors – the list of colors that can be used for coloring panel value or background. Additional info on coloring in docs: https://grafana.com/docs/grafana/latest/features/panels/singlestat/#coloring

  • colorBackground – defines if grafana will color panel background

  • colorValue – defines if grafana will color panel value

  • decimals – override automatic decimal precision for legend/tooltips

  • format – defines value units

  • gauge – draws and additional speedometer-like gauge based

  • mappingType – defines panel mapping type. Additional info can be found in docs: https://grafana.com/docs/grafana/latest/features/panels/singlestat/#value-to-text-mapping

  • mappingTypes – the list of available mapping types for panel

  • nullText – defines what to show if metric query result is undefined

  • nullPointMode – defines how to render undefined values

  • postfix – defines postfix that will be attached to value

  • postfixFontSize – defines postfix font size

  • prefix – defines prefix that will be attached to value

  • prefixFontSize – defines prefix font size

  • rangeMaps – the list of value to text mappings

  • sparkline – defines if grafana should draw an additional sparkline. Sparkline grafana documentation: https://grafana.com/docs/grafana/latest/features/panels/singlestat/#spark-lines

  • thresholds – single stat thresholds

  • valueFontSize – defines value font size

  • valueName – defines value type. possible values are: min, max, avg, current, total, name, first, delta, range

  • valueMaps – the list of value to text mappings

to_json_data()
class grafanalib.core.SparkLine(fillColor=NOTHING, full=False, lineColor=NOTHING, show=False)

Bases: object

to_json_data()
class grafanalib.core.SqlTarget(expr='', format='time_series', hide=False, legendFormat='', interval='', intervalFactor=2, metric='', refId='', step=10, target='', instant=False, datasource=None, rawSql='', rawQuery=True)

Bases: grafanalib.core.Target

Metric target to support SQL queries

to_json_data()

Override the Target to_json_data to add additional fields. rawSql: this will contain the actual SQL queries rawQuery: this is set to True by default as in case of False

the rawSql would be unused

class grafanalib.core.Stat(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, alignment='auto', colorMode='value', decimals=None, format='none', graphMode='area', mappings=NOTHING, noValue='none', orientation='auto', overrides=NOTHING, reduceCalc: str = 'mean', textMode='auto', thresholds='')

Bases: grafanalib.core.Panel

Generates Stat panel json structure

Grafana doc on stat: https://grafana.com/docs/grafana/latest/panels/visualizations/stat-panel/

Parameters
  • alignment – defines value & title positioning: keys ‘auto’ ‘centre’

  • colorMode – defines if Grafana will color panel background: keys “value” “background”

  • decimals – number of decimals to display

  • format – defines value units

  • graphMode – defines if Grafana will draw graph: keys ‘area’ ‘none’

  • noValue – define the default value if no value is found

  • mappings – the list of values to text mappings This should be a list of StatMapping objects https://grafana.com/docs/grafana/latest/panels/field-configuration-options/#value-mapping

  • orientation – Stacking direction in case of multiple series or fields: keys ‘auto’ ‘horizontal’ ‘vertical’

  • overrides – To override the base characteristics of certain timeseries data

  • reduceCalc – algorithm for reduction to a single value: keys ‘mean’ ‘lastNotNull’ ‘last’ ‘first’ ‘firstNotNull’ ‘min’ ‘max’ ‘sum’ ‘total’

  • textMode – define Grafana will show name or value: keys: ‘auto’ ‘name’ ‘none’ ‘value’ ‘value_and_name’

  • thresholds – single stat thresholds

to_json_data()
class grafanalib.core.StatMapping(text, mapValue='', startValue='', endValue='', id=None)

Bases: object

Deprecated Grafana v8 Generates json structure for the value mapping for the Stat panel:

Parameters
  • text – Sting that will replace input value

  • value – Value to be replaced

  • startValue – When using a range, the start value of the range

  • endValue – When using a range, the end value of the range

  • id – panel id

to_json_data()
class grafanalib.core.StatRangeMapping(text, startValue='', endValue='', id=None)

Bases: object

Deprecated Grafana v8 Generates json structure for the range mappings for the StatPanel:

Parameters
  • text – Sting that will replace input value

  • startValue – When using a range, the start value of the range

  • endValue – When using a range, the end value of the range

  • id – panel id

to_json_data()
class grafanalib.core.StatRangeMappings(text, startValue=0, endValue=0, color='', index=None)

Bases: object

Generates json structure for the range mappings for the StatPanel:

Parameters
  • text – Sting that will replace input value

  • startValue – When using a range, the start value of the range

  • endValue – When using a range, the end value of the range

  • color – How to color the text if mapping occurs

  • index – index

to_json_data()
class grafanalib.core.StatValueMapping(text, mapValue='', id=None)

Bases: object

Deprecated Grafana v8 Generates json structure for the value mappings for the StatPanel:

Parameters
  • text – Sting that will replace input value

  • mapValue – Value to be replaced

  • id – panel id

to_json_data()
class grafanalib.core.StatValueMappingItem(text, mapValue='', color='', index=None)

Bases: object

Generates json structure for the value mapping item for the StatValueMappings class:

Parameters
  • text – String that will replace input value

  • mapValue – Value to be replaced

  • color – How to color the text if mapping occurs

  • index – index

to_json_data()
class grafanalib.core.StatValueMappings(*mappings: grafanalib.core.StatValueMappingItem)

Bases: object

Generates json structure for the value mappings for the StatPanel:

Parameters

mappingItems – List of StatValueMappingItem objects

mappings=[
core.StatValueMappings(

core.StatValueMappingItem(‘Offline’, ‘0’, ‘red’), # Value must a string core.StatValueMappingItem(‘Online’, ‘1’, ‘green’)

),

],

to_json_data()
class grafanalib.core.StateTimeline(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, alignValue='left', colorMode='thresholds', fillOpacity=70, legendDisplayMode='list', legendPlacement='bottom', lineWidth=0, mappings=NOTHING, overrides=NOTHING, mergeValues=True, rowHeight=0.9, showValue='auto', tooltipMode='single', thresholds=NOTHING)

Bases: grafanalib.core.Panel

Generates State Timeline panel json structure Grafana docs on State Timeline panel: https://grafana.com/docs/grafana/latest/visualizations/state-timeline/

Parameters
  • alignValue – Controls value alignment inside state regions, default left

  • colorMode – Default thresholds

  • fillOpacity – Controls the opacity of state regions, default 0.9

  • legendDisplayMode – refine how the legend appears, list, table or hidden

  • legendPlacement – bottom or top

  • lineWidth – Controls line width of state regions

  • mappings – To assign colors to boolean or string values, use Value mappings

  • overrides – To override the base characteristics of certain data

  • mergeValues – Controls whether Grafana merges identical values if they are next to each other, default True

  • rowHeight – Controls how much space between rows there are. 1 = no space = 0.5 = 50% space

  • showValue – Controls whether values are rendered inside the state regions. Auto will render values if there is sufficient space.

  • tooltipMode – Default single

  • thresholds – Thresholds are used to turn the time series into discrete colored state regions

to_json_data()
class grafanalib.core.Statusmap(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, alert=None, cards={'cardHSpacing': 2, 'cardMinWidth': 5, 'cardRound': None, 'cardVSpacing': 2}, color=NOTHING, isNew=True, legend=NOTHING, nullPointMode='null as zero', tooltip=NOTHING, xAxis=NOTHING, yAxis=NOTHING)

Bases: grafanalib.core.Panel

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

to_json_data()
class grafanalib.core.StatusmapColor(cardColor='#b4ff00', colorScale='sqrt', colorScheme='GnYlRd', exponent=0.5, mode='spectrum', thresholds=[], max=None, min=None)

Bases: object

A Color object for Statusmaps

Parameters
  • cardColor – colour

  • colorScale – scale

  • colorScheme – scheme

  • exponent – exponent

  • max – max

  • min – min

  • mode – mode

  • thresholds – threshold

to_json_data()
class grafanalib.core.StringColumnStyleType(decimals=2, colorMode=None, colors=NOTHING, thresholds=NOTHING, preserveFormat=False, sanitize=False, unit='short', mappingType=1, valueMaps=NOTHING, rangeMaps=NOTHING)

Bases: object

TYPE = 'string'
to_json_data()
class grafanalib.core.Svg(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, format='none', jsCodeFilePath='', jsCodeInitFilePath='', height=None, svgFilePath='')

Bases: grafanalib.core.Panel

Generates SVG panel json structure Grafana doc on SVG: https://grafana.com/grafana/plugins/marcuscalidus-svg-panel

Parameters
  • format – defines value units

  • jsCodeFilePath – path to javascript file to be run on dashboard refresh

  • jsCodeInitFilePath – path to javascript file to be run after the first initialization of the SVG

  • reduceCalc – algorithm for reduction to a single value, keys ‘mean’ ‘lastNotNull’ ‘last’ ‘first’ ‘firstNotNull’ ‘min’ ‘max’ ‘sum’ ‘total’

  • svgFilePath – path to SVG image file to be displayed

static read_file(file_path)
to_json_data()
class grafanalib.core.Table(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, align='auto', colorMode='thresholds', columns=NOTHING, displayMode='auto', fontSize='100%', filterable=False, mappings=NOTHING, overrides=NOTHING, showHeader=True, span=6, thresholds=NOTHING)

Bases: grafanalib.core.Panel

Generates Table panel json structure

Now supports Grafana v8+ Grafana doc on table: https://grafana.com/docs/grafana/latest/visualizations/table/

Parameters
  • align – Align cell contents; auto (default), left, center, right

  • colorMode – Default thresholds

  • columns – Table columns for Aggregations view

  • displayMode – By default, Grafana automatically chooses display settings, you can choose; color-text, color-background, color-background-solid, gradient-gauge, lcd-gauge, basic, json-view

  • fontSize – Defines value font size

  • filterable – Allow user to filter columns, default False

  • mappings – To assign colors to boolean or string values, use Value mappings

  • overrides – To override the base characteristics of certain data

  • showHeader – Show the table header

  • thresholds – List of thresholds

to_json_data()
classmethod with_styled_columns(columns, styles=None, **kwargs)

Styled columns is not support in Grafana v8 Table

class grafanalib.core.Target(expr='', format='time_series', hide=False, legendFormat='', interval='', intervalFactor=2, metric='', refId='', step=10, target='', instant=False, datasource=None)

Bases: object

Metric to show.

Parameters

target – Graphite way to select data

to_json_data()
class grafanalib.core.Template(name, query, default=None, dataSource=None, label=None, allValue=None, includeAll=False, multi=False, options=NOTHING, regex=None, useTags=False, tagsQuery=None, tagValuesQuery=None, refresh=1, type='query', hide=0, sort=1, auto=False, autoCount=30, autoMin='10s')

Bases: object

Template create a new ‘variable’ for the dashboard, defines the variable name, human name, query to fetch the values and the default value.

Parameters
  • default – the default value for the variable

  • dataSource – where to fetch the values for the variable from

  • label – the variable’s human label

  • name – the variable’s name

  • query – the query users to fetch the valid values of the variable

  • refresh – Controls when to update values in the dropdown

  • allValue – specify a custom all value with regex, globs or lucene syntax.

  • includeAll – Add a special All option whose value includes all options.

  • regex – Regex to filter or capture specific parts of the names return by your data source query.

  • 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.

to_json_data()
class grafanalib.core.Templating(list=NOTHING)

Bases: object

to_json_data()
class grafanalib.core.Text(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, content='', error=False, mode='markdown')

Bases: grafanalib.core.Panel

Generates a Text panel.

to_json_data()
class grafanalib.core.Threshold(color, index, value, line=True, op='gt', yaxis='left')

Bases: object

Threshold for for panels (https://grafana.com/docs/grafana/latest/panels/thresholds/)

Parameters
  • color – Color of threshold

  • index – Index of color in panel

  • line – Display Threshold line, defaults to True

  • value – When to use this color will be null if index is 0

  • op – EVAL_LT for less than or EVAL_GT for greater than to indicate what the threshold applies to.

  • yaxis – Choose left or right for panels

Care must be taken in the order in which the Threshold objects are specified, Grafana expects the value to increase.

Example::
thresholds = [

Threshold(‘green’, 0, 0.0), Threshold(‘red’, 1, 80.0)]

to_json_data()
class grafanalib.core.Time(start, end)

Bases: object

to_json_data()
class grafanalib.core.TimePicker(refreshIntervals, timeOptions, hidden=False)

Bases: object

Time Picker

Parameters
  • refreshIntervals – dashboard auto-refresh interval options

  • timeOptions – dashboard time range options

  • hidden – hide the time picker from dashboard

to_json_data()
class grafanalib.core.TimeRange(from_time, to_time)

Bases: object

A time range for an alert condition.

A condition has to hold for this length of time before triggering.

Parameters
  • from_time (str) – Either a number + unit (s: second, m: minute, h: hour, etc) e.g. "5m" for 5 minutes, or "now".

  • to_time (str) – Either a number + unit (s: second, m: minute, h: hour, etc) e.g. "5m" for 5 minutes, or "now".

to_json_data()
class grafanalib.core.TimeSeries(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, axisPlacement='auto', axisLabel='', barAlignment=0, colorMode='palette-classic', drawStyle='line', fillOpacity=0, gradientMode='none', legendDisplayMode='list', legendPlacement='bottom', lineInterpolation='linear', lineWidth=1, mappings=NOTHING, overrides=NOTHING, pointSize=5, scaleDistributionType='linear', scaleDistributionLog=2, spanNulls=False, showPoints='auto', stacking={}, thresholds=NOTHING, tooltipMode='single', unit='')

Bases: grafanalib.core.Panel

Generates Time Series panel json structure added in Grafana v8

Grafana doc on time series: https://grafana.com/docs/grafana/latest/panels/visualizations/time-series/

Parameters
  • axisPlacement – auto(Default), left. right, hidden

  • axisLabel – axis label string

  • barAlignment – bar alignment -1 (left), 0 (centre, default), 1

  • colorMode – Color mode palette-classic (Default),

  • drawStyle – how to display your time series data line (Default), bars, points

  • fillOpacity – fillOpacity

  • gradientMode – gradientMode

  • legendDisplayMode – refine how the legend appears in your visualization list (Default), table, hidden

  • legendPlacement – bottom (Default), right

  • lineInterpolation – line interpolation linear (Default), smooth, stepBefore, stepAfter

  • lineWidth – line width, default 1

  • mappings – To assign colors to boolean or string values, use Value mappings

  • overrides – To override the base characteristics of certain timeseries data

  • pointSize – point size, default 5

  • scaleDistributionType – axis scale linear or log

  • scaleDistributionLog – Base of if logarithmic scale type set, default 2

  • spanNulls – connect null values, default False

  • showPoints – show points auto (Default), always, never

  • stacking – dict to enable stacking, {“mode”: “normal”, “group”: “A”}

  • thresholds – single stat thresholds

  • tooltipMode – When you hover your cursor over the visualization, Grafana can display tooltips single (Default), multi, none

  • unit – units

to_json_data()
class grafanalib.core.Tooltip(msResolution=True, shared=True, sort=0, valueType='cumulative')

Bases: object

to_json_data()
class grafanalib.core.ValueMap(text, value, op='=')

Bases: object

Generates json structure for a value mapping item.

Parameters
  • op – comparison operator

  • value – value to map to text

  • text – text to map the value to

to_json_data()
grafanalib.core.WithinRange(from_value, to_value)
class grafanalib.core.Worldmap(dataSource=None, targets=NOTHING, title='', cacheTimeout=None, description=None, editable=True, error=False, height=None, gridPos=None, hideTimeOverride=False, id=None, interval=None, links=NOTHING, maxDataPoints=100, minSpan=None, repeat=NOTHING, span=None, timeFrom=None, timeShift=None, transparent=False, transformations=NOTHING, extraJson=None, circleMaxSize=30, circleMinSize=2, decimals=0, geoPoint='geohash', locationData='countries', locationName='', hideEmpty=False, hideZero=False, initialZoom=1, jsonUrl='', jsonpCallback='', mapCenter='(0°, 0°)', mapCenterLatitude=0, mapCenterLongitude=0, metric='Value', mouseWheelZoom=False, stickyLabels=False, thresholds='0,100,150', thresholdColors=['#73BF69', '#73BF69', '#FADE2A', '#C4162A'], unitPlural='', unitSingle='', unitSingular='', aggregation='total')

Bases: grafanalib.core.Panel

Generates Worldmap panel json structure Grafana doc on Worldmap: https://grafana.com/grafana/plugins/grafana-worldmap-panel/

Parameters
  • aggregation – metric aggregation: min, max, avg, current, total

  • circleMaxSize – Maximum map circle size

  • circleMinSize – Minimum map circle size

  • decimals – Number of decimals to show

  • geoPoint – Name of the geo_point/geohash column. This is used to calculate where the circle should be drawn.

  • locationData – Format of the location data, options in WORLDMAP_LOCATION_DATA

  • locationName – Name of the Location Name column. Used to label each circle on the map. If it is empty then the geohash value is used.

  • metric – Name of the metric column. This is used to give the circle a value - this determines how large the circle is.

  • mapCenter – Where to centre the map, default center (0°, 0°). Options: North America, Europe, West Asia, SE Asia, Last GeoHash, custom

  • mapCenterLatitude – If mapCenter=custom set the initial map latitude

  • mapCenterLongitude – If mapCenter=custom set the initial map longitude

  • hideEmpty – Hide series with only nulls

  • hideZero – Hide series with only zeros

  • initialZoom – Initial map zoom

  • jsonUrl – URL for JSON location data if json_endpoint or jsonp endpoint used

  • jsonpCallback – Callback if jsonp endpoint used

  • mouseWheelZoom – Zoom map on scroll of mouse wheel

  • stickyLabels – Sticky map labels

  • thresholds – String of thresholds eg. ‘0,10,20’

  • thresholdsColors – List of colors to be used in each threshold

  • unitPlural – Units plural

  • unitSingle – Units single

  • unitSingular – Units singular

to_json_data()
class grafanalib.core.XAxis(mode='time', name=None, values=NOTHING, show=True)

Bases: object

X Axis

Parameters
  • mode – Mode of axis can be time, series or histogram

  • name – X axis name

  • value – list of values eg. [“current”] or [“avg”]

  • show – show X axis

to_json_data()
class grafanalib.core.YAxes(left=NOTHING, right=NOTHING)

Bases: object

The pair of Y axes on a Grafana graph.

Each graph has two Y Axes, a left one and a right one.

to_json_data()
class grafanalib.core.YAxis(decimals=None, format=None, label=None, logBase=1, max=None, min=None, show=True)

Bases: object

A single Y axis.

Grafana graphs have two Y axes: one on the left and one on the right.

Parameters
  • decimals – Defines how many decimals are displayed for Y value. (default auto)

  • format – The display unit for the Y value

  • label – The Y axis label. (default “”)

  • logBase – The scale to use for the Y value, linear, or logarithmic. (default linear)

  • max – The maximum Y value

  • min – The minimum Y value

  • show – Show or hide the axis

to_json_data()
grafanalib.core.is_valid_max_per_row(instance, attribute, value)
grafanalib.core.is_valid_target(instance, attribute, value)

Check if a given attribute is a valid target

grafanalib.core.is_valid_xaxis_mode(instance, attribute, value)
grafanalib.core.single_y_axis(**kwargs)

Specify that a graph has a single Y axis.

Parameters are those passed to YAxis. Returns a YAxes object (i.e. a pair of axes) that can be used as the yAxes parameter of a graph.

grafanalib.core.to_y_axes(data)

Backwards compatibility for ‘YAxes’.

In grafanalib 0.1.2 and earlier, Y axes were specified as a list of two elements. Now, we have a dedicated YAxes type.

This function converts a list of two YAxis values to a YAxes value, silently passes through YAxes values, warns about doing things the old way, and errors when there are invalid values.

grafanalib.elasticsearch module

Helpers to create Elasticsearch-specific Grafana queries.

class grafanalib.elasticsearch.AverageMetricAgg(field='', id=0, hide=False, inline='')

Bases: object

An aggregator that provides the average. value among the values.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-avg-aggregation.html

Parameters
  • field – name of elasticsearch field to provide the maximum for

  • id – id of the metric

  • hide – show/hide the metric in the final panel display

  • inline – script to apply to the data, using ‘_value’

to_json_data()
class grafanalib.elasticsearch.BucketScriptAgg(fields={}, id=0, hide=False, script='')

Bases: object

An aggregator that applies a bucket script to the results of previous aggregations. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-script-aggregation.html

Parameters
  • fields – dictionary of field names mapped to aggregation IDs to be used in the bucket script e.g. { “field1”:1 }, which allows the output of aggregate ID 1 to be referenced as params.field1 in the bucket script

  • script – script to apply to the data using the variables specified in ‘fields’

  • id – id of the aggregator

  • hide – show/hide the metric in the final panel display

to_json_data()
class grafanalib.elasticsearch.CardinalityMetricAgg(field='', id=0, hide=False, inline='')

Bases: object

An aggregator that provides the cardinality. value among the values.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html

Parameters
  • field – name of elasticsearch field to provide the maximum for

  • id – id of the metric

  • hide – show/hide the metric in the final panel display

  • inline – script to apply to the data, using ‘_value’

to_json_data()
class grafanalib.elasticsearch.CountMetricAgg(id=0, hide=False, inline='')

Bases: object

An aggregator that counts the number of values.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html

It’s the default aggregator for elasticsearch queries. :param hide: show/hide the metric in the final panel display :param id: id of the metric :param inline: script to apply to the data, using ‘_value’

to_json_data()
class grafanalib.elasticsearch.DateHistogramGroupBy(id=0, field='time_iso8601', interval='auto', minDocCount=0)

Bases: object

A bucket aggregator that groups results by date.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-datehistogram-aggregation.html

Parameters
  • id – ascending unique number per GroupBy clause

  • field – name of the elasticsearch field to group by

  • interval – interval to group by

  • minDocCount – min. amount of records in the timespan to return a result

to_json_data()
class grafanalib.elasticsearch.DerivativeMetricAgg(field='', hide=False, id=0, pipelineAgg=1, unit='')

Bases: object

An aggregator that takes the derivative of another metric aggregator.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-derivative-aggregation.html

Parameters
  • field – id of elasticsearch metric aggregator to provide the derivative of

  • hide – show/hide the metric in the final panel display

  • id – id of the metric

  • pipelineAgg – pipeline aggregator id

  • unit – derivative units

to_json_data()
class grafanalib.elasticsearch.ElasticsearchAlertCondition(evaluator, timeRange, operator, reducerType, target, *, type='query')

Bases: grafanalib.core.AlertCondition

Override alert condition to support Elasticseach target.

See AlertCondition for more information.

Parameters
  • target (Target) – Metric the alert condition is based on.

  • evaluator (Evaluator) – How we decide whether we should alert on the metric. e.g. GreaterThan(5) means the metric must be greater than 5 to trigger the condition. See GreaterThan, LowerThan, WithinRange, OutsideRange, NoValue.

  • timeRange (TimeRange) – How long the condition must be true for before we alert.

  • operator – One of OP_AND or OP_OR. How this condition combines with other conditions.

  • reducerType – RTYPE_*

  • type – CTYPE_*

class grafanalib.elasticsearch.ElasticsearchTarget(alias=None, bucketAggs=NOTHING, metricAggs=NOTHING, query='', refId='', timeField='@timestamp')

Bases: object

Generates Elasticsearch target JSON structure.

Grafana docs on using Elasticsearch: http://docs.grafana.org/features/datasources/elasticsearch/ Elasticsearch docs on querying or reading data: https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html

Parameters
  • alias – legend alias

  • bucketAggs – Bucket aggregators

  • metricAggs – Metric Aggregators

  • query – query

  • refId – target reference id

  • timeField – name of the elasticsearch time field

auto_bucket_agg_ids()

Give unique IDs all bucketAggs without ID.

Returns a new ElasticsearchTarget that is the same as this one, except all of the bucketAggs have their id property set. Any panels which had an id property set will keep that property, all others will have auto-generated IDs provided for them.

If the bucketAggs don’t have unique ID associated with it, the generated graph will be broken.

to_json_data()
class grafanalib.elasticsearch.Filter(label='', query='')

Bases: object

A Filter for a FilterGroupBy aggregator.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html

Parameters
  • label – label for the metric that is shown in the graph

  • query – the query to filter by

to_json_data()
class grafanalib.elasticsearch.FiltersGroupBy(id=0, filters=NOTHING)

Bases: object

A bucket aggregator that groups records by a filter expression.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html

Parameters
  • id – ascending unique number per GroupBy clause

  • filters – list of Filter objects

to_json_data()
class grafanalib.elasticsearch.MaxMetricAgg(field='', id=0, hide=False, inline='')

Bases: object

An aggregator that provides the max. value among the values.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-max-aggregation.html

Parameters
  • field – name of elasticsearch field to provide the maximum for

  • hide – show/hide the metric in the final panel display

  • id – id of the metric

  • inline – script to apply to the data, using ‘_value’

to_json_data()
class grafanalib.elasticsearch.MinMetricAgg(field='', id=0, hide=False, inline='')

Bases: object

An aggregator that provides the min. value among the values. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-min-aggregation.html :param field: name of elasticsearch field to provide the maximum for :param hide: show/hide the metric in the final panel display :param id: id of the metric :param inline: script to apply to the data, using ‘_value’

to_json_data()
class grafanalib.elasticsearch.PercentilesMetricAgg(field='', id=0, hide=False, inline='', percents=NOTHING, settings={})

Bases: object

A multi-value metrics aggregation that calculates one or more percentiles over numeric values extracted from the aggregated documents https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-percentile-aggregation.html :param field: name of elasticsearch field to provide the maximum for :param hide: show/hide the metric in the final panel display :param id: id of the metric :param inline: script to apply to the data, using ‘_value’ :param percents: list of percentiles, like [95,99]

to_json_data()
class grafanalib.elasticsearch.SumMetricAgg(field='', id=0, hide=False, inline='')

Bases: object

An aggregator that provides the sum of the values. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html :param field: name of elasticsearch field to provide the sum over :param hide: show/hide the metric in the final panel display :param id: id of the metric :param inline: script to apply to the data, using ‘_value’

to_json_data()
class grafanalib.elasticsearch.TermsGroupBy(field, id=0, minDocCount=1, order='desc', orderBy='_term', size=0)

Bases: object

A multi-bucket aggregator based on field values.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html

Parameters
  • id – ascending unique number per GroupBy clause

  • field – name of the field to group by

  • minDocCount – min. amount of matching records to return a result

  • order – ORDER_ASC or ORDER_DESC

  • orderBy – term to order the bucket Term value: ‘_term’, Doc Count: ‘_count’ or to use metric function use the string value “2”

  • size – how many buckets are returned

to_json_data()

grafanalib.formatunits module

Grafana unit formats (https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts)

To use: from grafanalib import formatunits as UNITS

format = UNITS.BYTES

grafanalib.influxdb module

Helpers to create InfluxDB-specific Grafana queries.

class grafanalib.influxdb.InfluxDBTarget(alias='', format='time_series', measurement='', query='', rawQuery=True, refId='')

Bases: object

Generates InfluxDB target JSON structure.

Grafana docs on using InfluxDB: https://grafana.com/docs/features/datasources/influxdb/ InfluxDB docs on querying or reading data: https://v2.docs.influxdata.com/v2.0/query-data/

Parameters
  • alias – legend alias

  • format – Bucket aggregators

  • measurement – Metric Aggregators

  • query – query

  • rawQuery – target reference id

  • refId – target reference id

to_json_data()

grafanalib.opentsdb module

Support for OpenTSDB.

class grafanalib.opentsdb.OpenTSDBFilter(value, tag, type='literal_or', groupBy=False)

Bases: object

to_json_data()
class grafanalib.opentsdb.OpenTSDBTarget(metric, refId='', aggregator='sum', alias=None, isCounter=False, counterMax=None, counterResetValue=None, disableDownsampling=False, downsampleAggregator='sum', downsampleFillPolicy='none', downsampleInterval=None, filters=NOTHING, shouldComputeRate=False, currentFilterGroupBy=False, currentFilterKey='', currentFilterType='literal_or', currentFilterValue='')

Bases: object

Generates OpenTSDB target JSON structure.

Grafana docs on using OpenTSDB: http://docs.grafana.org/features/datasources/opentsdb/ OpenTSDB docs on querying or reading data: http://opentsdb.net/docs/build/html/user_guide/query/index.html

Parameters
to_json_data()

grafanalib.prometheus module

Helpers for Prometheus-driven graphs.

grafanalib.prometheus.PromGraph(data_source, title, expressions, **kwargs)

Create a graph that renders Prometheus data.

Parameters
  • data_source (str) – 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.validators module

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.validators.is_in(choices)

A validator that raises a ValueError if the attribute value is not in a provided list.

Parameters

choices – List of valid choices

grafanalib.validators.is_interval(instance, attribute, value)

A validator that raises a ValueError if the attribute value is not matching regular expression.

grafanalib.validators.is_list_of(etype)

A validator that raises a ValueError if the attribute value is not in a provided list.

Parameters

choices – List of valid choices

grafanalib.weave module

Weave-specific dashboard configuration.

Unlike ‘core’, which has logic for building generic Grafana dashboards, this has our Weave-specific preferences.

grafanalib.weave.PercentUnitAxis(label=None)

A Y axis that shows a percentage based on a unit value.

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.

grafanalib.weave.stacked(graph)

Turn a graph into a stacked graph.

grafanalib.zabbix module

class grafanalib.zabbix.ZabbixAggregateByFunction(added=False, interval='1m', function='avg')

Bases: object

Takes all timeseries and consolidate all its points falled in given interval into one point using function, which can be one of: avg, min, max, median. http://docs.grafana-zabbix.org/reference/functions/#aggregateBy

to_json_data()
class grafanalib.zabbix.ZabbixAverageFunction(added=False, interval='1m')

Bases: object

Deprecated, use aggregateBy(interval, avg) instead. http://docs.grafana-zabbix.org/reference/functions/#average

to_json_data()
class grafanalib.zabbix.ZabbixBottomFunction(added=False, number=5, function='avg')

Bases: object

to_json_data()
class grafanalib.zabbix.ZabbixColor(color, priority, severity, show=True)

Bases: object

to_json_data()
class grafanalib.zabbix.ZabbixDeltaFunction(added=False)

Bases: object

Convert absolute values to delta, for example, bits to bits/sec http://docs.grafana-zabbix.org/reference/functions/#delta

to_json_data()
class grafanalib.zabbix.ZabbixGroupByFunction(added=False, interval='1m', function='avg')

Bases: object

Takes each timeseries and consolidate its points falled in given interval into one point using function, which can be one of: avg, min, max, median. http://docs.grafana-zabbix.org/reference/functions/#groupBy

to_json_data()
class grafanalib.zabbix.ZabbixMaxFunction(added=False, interval='1m')

Bases: object

Deprecated, use aggregateBy(interval, max) instead. http://docs.grafana-zabbix.org/reference/functions/#max

to_json_data()
class grafanalib.zabbix.ZabbixMedianFunction(added=False, interval='1m')

Bases: object

Deprecated, use aggregateBy(interval, median) instead. http://docs.grafana-zabbix.org/reference/functions/#median

to_json_data()
class grafanalib.zabbix.ZabbixMinFunction(added=False, interval='1m')

Bases: object

Deprecated, use aggregateBy(interval, min) instead. http://docs.grafana-zabbix.org/reference/functions/#min

to_json_data()
class grafanalib.zabbix.ZabbixScaleFunction(added=False, factor=100)

Bases: object

Takes timeseries and multiplies each point by the given factor. http://docs.grafana-zabbix.org/reference/functions/#scale

to_json_data()
class grafanalib.zabbix.ZabbixSetAliasByRegexFunction(regexp, added=False)

Bases: object

Returns part of the metric name matched by regex. http://docs.grafana-zabbix.org/reference/functions/#setAliasByRegex

to_json_data()
class grafanalib.zabbix.ZabbixSetAliasFunction(alias, added=False)

Bases: object

Returns given alias instead of the metric name. http://docs.grafana-zabbix.org/reference/functions/#setAlias

to_json_data()
class grafanalib.zabbix.ZabbixSumSeriesFunction(added=False)

Bases: object

This will add metrics together and return the sum at each datapoint. This method required interpolation of each timeseries so it may cause high CPU load. Try to combine it with groupBy() function to reduce load. http://docs.grafana-zabbix.org/reference/functions/#sumSeries

to_json_data()
class grafanalib.zabbix.ZabbixTarget(application='', expr='', functions=NOTHING, group='', host='', intervalFactor=2, item='', itService='', mode=0, options=NOTHING, refId='', slaProperty=NOTHING, textFilter='', useCaptureGroups=False)

Bases: object

Generates Zabbix datasource target JSON structure.

Grafana-Zabbix is a plugin for Grafana allowing to visualize monitoring data from Zabbix and create dashboards for analyzing metrics and realtime monitoring.

Grafana docs on using Zabbix pluging: http://docs.grafana-zabbix.org/

Parameters
  • application – zabbix application name

  • expr – zabbix arbitary query

  • functions – list of zabbix aggregation functions

  • group – zabbix host group

  • host – hostname

  • intervalFactor – defines interval between metric queries

  • item – regexp that defines which metric to query

  • itService – zabbix it service name

  • mode – query mode type

  • options – additional query options

  • refId – target reference id

  • slaProperty – zabbix it service sla property. Zabbix returns the following availability information about IT service Status - current status of the IT service SLA - SLA for the given time interval OK time - time the service was in OK state, in seconds Problem time - time the service was in problem state, in seconds Down time - time the service was in scheduled downtime, in seconds

  • textFilter – query text filter. Use regex to extract a part of the returned value.

  • useCaptureGroups – defines if capture groups should be used during metric query

to_json_data()
class grafanalib.zabbix.ZabbixTargetField(filter='')

Bases: object

to_json_data()
class grafanalib.zabbix.ZabbixTargetOptions(showDisabledItems=False)

Bases: object

to_json_data()
class grafanalib.zabbix.ZabbixTimeShiftFunction(added=False, interval='24h')

Bases: object

Draws the selected metrics shifted in time. If no sign is given, a minus sign ( - ) is implied which will shift the metric back in time. If a plus sign ( + ) is given, the metric will be shifted forward in time. http://docs.grafana-zabbix.org/reference/functions/#timeShift

to_json_data()
class grafanalib.zabbix.ZabbixTopFunction(added=False, number=5, function='avg')

Bases: object

to_json_data()
class grafanalib.zabbix.ZabbixTrendValueFunction(added=False, type='avg')

Bases: object

Specifying type of trend value returned by Zabbix when trends are used (avg, min or max). http://docs.grafana-zabbix.org/reference/functions/#trendValue

to_json_data()
class grafanalib.zabbix.ZabbixTrigger(application='', group='', host='', trigger='')

Bases: object

to_json_data()
class grafanalib.zabbix.ZabbixTriggersPanel(dataSource, title, ackEventColor=NOTHING, ageField=True, customLastChangeFormat=False, description='', fontSize=NOTHING, height=Pixels(num=250), hideHostsInMaintenance=False, hostField=True, hostTechNameField=False, id=None, infoField=True, lastChangeField=True, lastChangeFormat='', limit=10, links=NOTHING, markAckEvents=False, minSpan=None, okEventColor=NOTHING, pageSize=10, repeat=None, scroll=True, severityField=False, showEvents=NOTHING, showTriggers='all triggers', sortTriggersBy=NOTHING, span=None, statusField=False, transparent=False, triggerSeverity=(('#B7DBAB', 'Not classified'), ('#82B5D8', 'Information'), ('#E5AC0E', 'Warning'), ('#C15C17', 'Average'), ('#BF1B00', 'High'), ('#890F02', 'Disaster')), triggers=NOTHING)

Bases: object

Parameters
  • dataSource – query datasource name

  • title – panel title

  • ackEventColor – acknowledged triggers color

  • customLastChangeFormat – defines last change field data format. See momentjs docs for time format: http://momentjs.com/docs/#/displaying/format/

  • description – additional panel description

  • fontSize – panel font size

  • height – panel height in Pixels

  • hideHostsInMaintenance – defines if triggers form hosts in maintenance should be shown

  • hostField – defines if host field should be shown

  • hostTechNameField – defines if field with host technical name should be shown

  • id – panel identificator

  • infoField – defines if field with host info should be shown

  • lastChangeField – defines if field with last change time should be shown

  • limit – defines number of queried triggers

  • links – list of dashboard links

  • markAckEvents – defines if acknowledged triggers should be colored with different color

  • minSpan – defines panel minimum spans

  • okEventColor – defines color for triggers with Ok status

  • pageSize – defines number of triggers per panel page

  • scroll – defines if scroll should be shown

  • severityField – defines if severity field should be shown

  • showEvents – defines event type to query (Ok, Problems, All)

  • showTriggers – defines trigger type to query (all, acknowledged, unacknowledged)

  • sortTriggersBy – defines trigger sort policy

  • span – defines span number for panel

  • statusField – defines if status field should be shown

  • transparent – defines if panel should be transparent

  • triggerSeverity – defines colors for trigger severity,

  • triggers – trigger query

to_json_data()
grafanalib.zabbix.convertZabbixSeverityColors(colors)
grafanalib.zabbix.zabbixMetricTarget(application, group, host, item, functions=[])
grafanalib.zabbix.zabbixServiceTarget(service, sla={'name': 'Status', 'property': 'status'})
grafanalib.zabbix.zabbixTextTarget(application, group, host, item, text, useCaptureGroups=False)

Module contents

Routines for building Grafana dashboards.