weaveworks / grafanalib

Python library for building Grafana dashboards
Apache License 2.0
1.85k stars 307 forks source link

Testing grafanalib with static mock data #639

Closed ccamacho closed 7 months ago

ccamacho commented 7 months ago

Hi!

Im playing with grafanalib and one of the examples I will like to try is to mock some data in the Dashboard definition

from grafanalib.core import (
  Dashboard, Stat, Target, GridPos, Template, Graph, Templating, Time, Repeat
)

import json

# Define your data
data_source = "YourDataSource"  # Replace with your actual data source name
dashboard_title = "Time Series Dashboard"

# Hardcoded time series data
time_series_data = [
    {"timestamp": 1638200000000, "value": 10},
    {"timestamp": 1638203600000, "value": 15},
    {"timestamp": 1638207200000, "value": 12},
    # Add more data points as needed
]

# Create targets for each time series
targets = [
    Target(
        expr=f'{value["value"]}',
        legendFormat=f'Time Series {index}',
        refId=f'TimeSeries{index}',
    )
    for index, value in enumerate(time_series_data)
]

# Create a simple time series dashboard
dashboard = Dashboard(
    title=dashboard_title,
    uid='5640',
    rows=[
        Graph(
            title='Time Series Graph',
            dataSource=data_source,
            targets=targets,
        ),
    ],
)

# Convert the dashboard to JSON
#dashboard_json = json.dumps(dashboard.to_json_data(), indent=2)

# Print the JSON or save it to a file
#print(dashboard_json)

# If you want to save the dashboard to a file
# with open('dashboard.json', 'w') as f:
#     f.write(dashboard_json)

For example like the above example, this is not working, do you have by any chance a similar example? Also ideally I would like to use TimeSeries instead of Graph but I didnt manage to find any docs about it.

When running generate-dashboard -o my.dashboard.py.json my.dashboard.py the script works, but then in Grafana it fails with Dashboard init failed and the logs say:

logger=provisioning.dashboard type=file name="A dashboard provider" t=2023-12-22T10:20:06.773573196Z level=error msg="failed to save dashboard" file=/etc/grafana/provisioning/dashboards/my.dashboard.py.json error="Unique identifier needed to be able to get a dashboard"

After assigned an arbitrary uid still cant see the dashboard.

Thanks!