Dashboard Migrations: V13 no-op, remove 28 and v24 as they are autoMigrations; and remove dead code from DashboardMigrator (#110008)

* migrate to v19

* migrate to v18

* Migration to be verified: v17 Convert minSpan to maxPerRow in panels

* Migration to be verified: 16 Grid layout migration

* Refactor v17 and v19 migrations to use shared helper functions

* Migration to be verified: 15 No-op migration for schema consistency

* Migration to be verified: 14 Shared crosshair to graph tooltip migration

* cleanup

* wip

* complete migration

* fix lint issues

* refactor and test with minimal graph config

* update tests

* extract defaults outside the func

* lint

* lint

* add missing showValues prop

* add context and fix latest version

* generate snapshots

* v13 should be no-op

* clean up

* remove v28

* remove singlestat migraiton from frontend migrator because this is an automigration

* remove unused function

* Remove v24 table plugin logic

* cleanup

* remove plugin version for automigrate as it was used only in v24 and v28 that have been removed

* cleanup

---------

Co-authored-by: Dominik Prokop <dominik.prokop@grafana.com>
This commit is contained in:
Haris Rozajac
2025-10-09 11:14:02 -06:00
committed by GitHub
co-authored by Dominik Prokop
parent 5eb295d850
commit 4d3c5d1550
45 changed files with 3555 additions and 6766 deletions
@@ -1,89 +0,0 @@
package schemaversion
var notPersistedProperties = []string{
"events",
"isViewing",
"isEditing",
"isInView",
"hasRefreshed",
"cachedPluginOptions",
"plugin",
"queryRunner",
"replaceVariables",
"configRev",
"hasSavedPanelEditChange",
"getDisplayTitle",
"dataSupport",
"key",
"isNew",
"refreshWhenInView",
}
var mustKeepProperties = []string{
"id",
"gridPos",
"type",
"title",
"scopedVars",
"repeat",
"repeatPanelId",
"repeatDirection",
"repeatedByRow",
"minSpan",
"collapsed",
"panels",
"targets",
"datasource",
"timeFrom",
"timeShift",
"hideTimeOverride",
"description",
"links",
"fullscreen",
"isEditing",
"isViewing",
"hasRefreshed",
"events",
"cacheTimeout",
"queryCachingTTL",
"cachedPluginOptions",
"transparent",
"pluginVersion",
"queryRunner",
"transformations",
"fieldConfig",
"maxDataPoints",
"interval",
"replaceVariables",
"libraryPanel",
"getDisplayTitle",
"configRev",
"key",
}
// getOptionsToRemember returns a map of panel properties that should be remembered
// during panel type changes, excluding notPersistedProperties and mustKeepProperties
func getOptionsToRemember(panel map[string]interface{}) map[string]interface{} {
// Create sets for faster lookup
notPersistedSet := make(map[string]bool)
for _, prop := range notPersistedProperties {
notPersistedSet[prop] = true
}
mustKeepSet := make(map[string]bool)
for _, prop := range mustKeepProperties {
mustKeepSet[prop] = true
}
// Filter the panel properties
result := make(map[string]interface{})
for key, value := range panel {
// Skip properties that are in notPersistedProperties or mustKeepProperties
if notPersistedSet[key] || mustKeepSet[key] {
continue
}
result[key] = value
}
return result
}
@@ -7,11 +7,8 @@ import (
)
const (
MIN_VERSION = 13
MIN_VERSION = 12
LATEST_VERSION = 42
// The pluginVersion to set after simulating auto-migrate for angular panels
pluginVersionForAutoMigrate = "12.1.0"
)
type SchemaVersionMigrationFunc func(context.Context, map[string]interface{}) error
@@ -38,6 +35,7 @@ type PanelPluginInfo struct {
func GetMigrations(dsInfoProvider DataSourceInfoProvider) map[int]SchemaVersionMigrationFunc {
return map[int]SchemaVersionMigrationFunc{
13: V13,
14: V14,
15: V15,
16: V16,
@@ -0,0 +1,11 @@
package schemaversion
import (
"context"
)
// V13 is a no-op migration
func V13(_ context.Context, dashboard map[string]interface{}) error {
dashboard["schemaVersion"] = 13
return nil
}
@@ -0,0 +1,38 @@
package schemaversion_test
import (
"testing"
"github.com/grafana/grafana/apps/dashboard/pkg/migration/schemaversion"
)
func TestV13(t *testing.T) {
tests := []migrationTestCase{
{
name: "v13 no-op migration, updates schema version only",
input: map[string]interface{}{
"title": "V13 No-Op Migration Test Dashboard",
"schemaVersion": 12,
"panels": []interface{}{
map[string]interface{}{
"type": "graph",
"title": "Panel remains unchanged",
"id": 1,
},
},
},
expected: map[string]interface{}{
"title": "V13 No-Op Migration Test Dashboard",
"schemaVersion": 13,
"panels": []interface{}{
map[string]interface{}{
"type": "graph",
"title": "Panel remains unchanged",
"id": 1,
},
},
},
},
}
runMigrationTests(t, tests, schemaversion.V13)
}
+54 -572
View File
@@ -2,189 +2,59 @@ package schemaversion
import (
"context"
"strconv"
)
// V24 migration migrates the angular table panel to the standard table panel
// In the frontend, this is an auto-migration meaning that this angular panel is always migrated to table panel.
// The backend replicates the complete frontend auto-migration logic since it cannot rely on frontend auto-migration.
//
// This migration performs:
// 1. Converts 'styles' array to 'fieldConfig' with 'defaults' and 'overrides'
// 2. Migrates thresholds and colors to new threshold format
// 3. Converts column-specific styles to field overrides
// 4. Migrates transformations from old format to new transformation system
// 5. Handles various style properties: unit, decimals, alignment, color modes, links, date formatting, hidden columns
// 6. Removes deprecated properties: styles, transform, columns
// V24 migration handles setting autoMigrateFrom
// This is a hacky way that matches frontend's logic
// For reason see https://github.com/grafana/grafana/pull/102146
// The issue is that if panel is "table" and it has styles, it should be migrated to "table-old"
// Example 1: Basic table with defaults
// Before migration:
// Example before migration:
// {
// "panels": [
// {
// "id": 1,
// "type": "table",
// "title": "Basic Table",
// "styles": [
// {
// "pattern": "/.*/",
// "thresholds": ["10", "20", "30"],
// "colors": ["green", "yellow", "red"],
// "unit": "bytes",
// "decimals": 2
// }
// ],
// "targets": [{ "refId": "A" }]
// }
// ]
// "id": 4,
// "type": "table",
// "title": "Table with Timeseries to Rows Transform",
// "description": "Tests migration of timeseries_to_rows transform to seriesToRows transformation.",
// "styles": [
// {
// "pattern": "/.*/",
// "unit": "short"
// }
// ],
// "transform": "timeseries_to_rows",
// "targets": [{ "refId": "A" }]
// }
//
// After migration:
// Example after migration:
// {
// "panels": [
// {
// "id": 1,
// "type": "table",
// "title": "Basic Table",
// "fieldConfig": {
// "defaults": {
// "unit": "bytes",
// "decimals": 2,
// "custom": {},
// "thresholds": {
// "mode": "absolute",
// "steps": [
// { "color": "green", "value": null },
// { "color": "green", "value": 10 },
// { "color": "yellow", "value": 20 },
// { "color": "red", "value": 30 }
// ]
// }
// },
// "overrides": []
// },
// "transformations": [],
// "targets": [{ "refId": "A" }],
// "pluginVersion": "{current_grafana_version}"
// }
// ]
// }
// Example 2: Complex table with overrides and transformations
// Before migration:
// {
// "panels": [
// {
// "id": 2,
// "type": "table",
// "title": "Complex Table",
// "styles": [
// {
// "pattern": "/.*/",
// "unit": "percent",
// "align": "center",
// "colorMode": "cell"
// },
// {
// "pattern": "Status",
// "alias": "Current Status",
// "colorMode": "value",
// "align": "left"
// },
// {
// "pattern": "/Error.*/",
// "link": true,
// "linkUrl": "http://example.com/errors",
// "linkTooltip": "View errors",
// "linkTargetBlank": true
// },
// {
// "pattern": "Time",
// "type": "date",
// "dateFormat": "YYYY-MM-DD HH:mm:ss",
// "alias": "Timestamp"
// },
// {
// "pattern": "Hidden",
// "type": "hidden"
// }
// ],
// "transform": "timeseries_aggregations",
// "columns": [
// { "value": "avg", "text": "Average" },
// { "value": "max", "text": "Maximum" }
// ],
// "targets": [{ "refId": "A" }]
// }
// ]
// }
//
// After migration:
// {
// "panels": [
// {
// "id": 2,
// "type": "table",
// "title": "Complex Table",
// "fieldConfig": {
// "defaults": {
// "unit": "percent",
// "custom": {
// "align": "center",
// "cellOptions": { "type": "color-background" }
// }
// },
// "overrides": [
// {
// "matcher": { "id": "byName", "options": "Status" },
// "properties": [
// { "id": "displayName", "value": "Current Status" },
// { "id": "custom.cellOptions", "value": { "type": "color-text" } },
// { "id": "custom.align", "value": "left" }
// ]
// },
// {
// "matcher": { "id": "byRegexp", "options": "/Error.*/" },
// "properties": [
// {
// "id": "links",
// "value": [{
// "title": "View errors",
// "url": "http://example.com/errors",
// "targetBlank": true
// }]
// }
// ]
// },
// {
// "matcher": { "id": "byName", "options": "Time" },
// "properties": [
// { "id": "displayName", "value": "Timestamp" },
// { "id": "unit", "value": "time: YYYY-MM-DD HH:mm:ss" }
// ]
// },
// {
// "matcher": { "id": "byName", "options": "Hidden" },
// "properties": [
// { "id": "custom.hideFrom.viz", "value": true }
// ]
// }
// ]
// },
// "transformations": [
// {
// "id": "reduce",
// "options": {
// "reducers": ["mean", "max"],
// "includeTimeField": false
// }
// }
// ],
// "targets": [{ "refId": "A" }],
// "pluginVersion": "{current_grafana_version}"
// }
// ]
// }
// "autoMigrateFrom": "table-old",
// "datasource": {
// "apiVersion": "v1",
// "type": "prometheus",
// "uid": "default-ds-uid"
// },
// "description": "Tests migration of timeseries_to_rows transform to seriesToRows transformation.",
// "id": 4,
// "styles": [
// {
// "pattern": "/.*/",
// "unit": "short"
// }
// ],
// "targets": [
// {
// "datasource": {
// "apiVersion": "v1",
// "type": "prometheus",
// "uid": "default-ds-uid"
// },
// "refId": "A"
// }
// ],
// "title": "Table with Timeseries to Rows Transform",
// "transform": "timeseries_to_rows",
// "type": "table"
// }
func V24(_ context.Context, dashboard map[string]interface{}) error {
dashboard["schemaVersion"] = 24
@@ -211,406 +81,18 @@ func V24(_ context.Context, dashboard map[string]interface{}) error {
continue
}
// The grafana version that matches the hardcoded autoMigrate plugins
panelMap["pluginVersion"] = pluginVersionForAutoMigrate
err := tablePanelChangedHandler(panelMap)
if err != nil {
return err
}
}
return nil
}
func tablePanelChangedHandler(panel map[string]interface{}) error {
prevOptions := getOptionsToRemember(panel)
transformations := migrateTransformations(panel, prevOptions)
prevDefaults := findDefaultStyle(prevOptions)
defaults := migrateDefaults(prevDefaults)
overrides := findNonDefaultStyles(prevOptions)
if len(overrides) == 0 {
overrides = []interface{}{}
}
// Only add transformations if they're not empty - frontend omits empty arrays
if len(transformations) > 0 {
panel["transformations"] = transformations
}
panel["fieldConfig"] = map[string]interface{}{
"defaults": defaults,
"overrides": overrides,
}
// Add minimal table panel options to match frontend behavior
// Frontend doesn't add default footer options, so we don't either
panel["options"] = map[string]interface{}{
"cellHeight": "sm",
"showHeader": true,
}
// Remove deprecated properties
delete(panel, "styles")
delete(panel, "transform")
delete(panel, "columns")
// Remove legend property - frontend table panel migration doesn't preserve it
delete(panel, "legend")
return nil
}
// findDefaultStyle finds the style with pattern '/.*/' (default style)
func findDefaultStyle(prevOptions map[string]interface{}) map[string]interface{} {
if styles, ok := prevOptions["styles"].([]interface{}); ok {
for _, style := range styles {
if styleMap, ok := style.(map[string]interface{}); ok {
if pattern, ok := styleMap["pattern"].(string); ok && pattern == "/.*/" {
return styleMap
}
}
}
}
return nil
}
// findNonDefaultStyles finds all styles that don't have pattern '/.*/'
func findNonDefaultStyles(prevOptions map[string]interface{}) []interface{} {
var overrides []interface{}
if styles, ok := prevOptions["styles"].([]interface{}); ok {
for _, style := range styles {
if styleMap, ok := style.(map[string]interface{}); ok {
if pattern, ok := styleMap["pattern"].(string); ok && pattern != "/.*/" {
override := migrateTableStyleToOverride(styleMap)
overrides = append(overrides, override)
}
}
}
}
return overrides
}
// migrateTransformations converts old table transformations to new format
func migrateTransformations(panel map[string]interface{}, oldOpts map[string]interface{}) []interface{} {
transformations := []interface{}{}
if existing, ok := panel["transformations"].([]interface{}); ok {
transformations = existing
}
// Check if oldOpts has a transform that we can map
if transform, ok := oldOpts["transform"].(string); ok {
if newTransformID, exists := transformsMap[transform]; exists {
opts := map[string]interface{}{
"reducers": []interface{}{},
}
// Handle timeseries_aggregations specifically
if transform == "timeseries_aggregations" {
opts["includeTimeField"] = false
// Map columns to reducers
if columns, ok := oldOpts["columns"].([]interface{}); ok {
var reducers []interface{}
for _, column := range columns {
if columnMap, ok := column.(map[string]interface{}); ok {
if value, ok := columnMap["value"].(string); ok {
if reducer, exists := columnsMap[value]; exists {
reducers = append(reducers, reducer)
}
}
}
}
opts["reducers"] = reducers
}
}
// Add the transformation
transformation := map[string]interface{}{
"id": newTransformID,
"options": opts,
}
transformations = append(transformations, transformation)
}
}
return transformations
}
// transformsMap maps old transform names to new transformation IDs
var transformsMap = map[string]string{
"timeseries_to_rows": "seriesToRows",
"timeseries_to_columns": "seriesToColumns",
"timeseries_aggregations": "reduce",
"table": "merge",
}
// columnsMap maps old column values to new reducer names
var columnsMap = map[string]string{
"avg": "mean",
"min": "min",
"max": "max",
"total": "sum",
"current": "lastNotNull",
"count": "count",
}
// migrateTableStyleToOverride converts a table style to a field config override
func migrateTableStyleToOverride(style map[string]interface{}) map[string]interface{} {
pattern, _ := style["pattern"].(string)
// Determine field matcher ID based on pattern
fieldMatcherID := "byName"
if pattern != "" && len(pattern) >= 2 && pattern[0] == '/' && pattern[len(pattern)-1] == '/' {
fieldMatcherID = "byRegexp"
}
override := map[string]interface{}{
"matcher": map[string]interface{}{
"id": fieldMatcherID,
"options": pattern,
},
"properties": []interface{}{},
}
properties := override["properties"].([]interface{})
// Add display name
if alias, ok := style["alias"].(string); ok && alias != "" {
properties = append(properties, map[string]interface{}{
"id": "displayName",
"value": alias,
})
}
// Add unit
if unit, ok := style["unit"].(string); ok && unit != "" {
properties = append(properties, map[string]interface{}{
"id": "unit",
"value": unit,
})
}
// Add decimals
if decimals := GetIntValue(style, "decimals", -1); decimals != -1 {
properties = append(properties, map[string]interface{}{
"id": "decimals",
"value": decimals,
})
}
// Handle date type
if styleType, ok := style["type"].(string); ok && styleType == "date" {
if dateFormat, ok := style["dateFormat"].(string); ok {
properties = append(properties, map[string]interface{}{
"id": "unit",
"value": "time: " + dateFormat,
})
}
}
// Handle hidden type
if styleType, ok := style["type"].(string); ok && styleType == "hidden" {
properties = append(properties, map[string]interface{}{
"id": "custom.hideFrom.viz",
"value": true,
})
}
// Handle links
if link, ok := style["link"].(bool); ok && link {
linkTooltip, _ := style["linkTooltip"].(string)
linkUrl, _ := style["linkUrl"].(string)
linkTargetBlank, _ := style["linkTargetBlank"].(bool)
properties = append(properties, map[string]interface{}{
"id": "links",
"value": []interface{}{
map[string]interface{}{
"title": linkTooltip,
"url": linkUrl,
"targetBlank": linkTargetBlank,
},
},
})
}
// Handle color mode
if colorMode, ok := style["colorMode"].(string); ok && colorMode != "" {
if newColorMode, exists := colorModeMap[colorMode]; exists {
properties = append(properties, map[string]interface{}{
"id": "custom.cellOptions",
"value": map[string]interface{}{
"type": newColorMode,
},
})
}
}
// Handle alignment
if align, ok := style["align"].(string); ok && align != "" {
var alignValue interface{}
if align == "auto" {
alignValue = nil // Frontend sets to null and filters it out
var currentType string
if wasAngularTable {
currentType = "table-old"
} else {
alignValue = align
currentType = "table"
}
properties = append(properties, map[string]interface{}{
"id": "custom.align",
"value": alignValue,
})
}
// Handle thresholds
if thresholds, ok := style["thresholds"].([]interface{}); ok && len(thresholds) > 0 {
if colors, ok := style["colors"].([]interface{}); ok && len(colors) > 0 {
steps := generateThresholds(thresholds, colors)
properties = append(properties, map[string]interface{}{
"id": "thresholds",
"value": map[string]interface{}{
"mode": "absolute",
"steps": steps,
},
})
if currentType == "table-old" {
panelMap["autoMigrateFrom"] = "table-old"
panelMap["type"] = "table"
}
}
override["properties"] = properties
return override
}
// migrateDefaults converts default table styles to field config defaults
func migrateDefaults(prevDefaults map[string]interface{}) map[string]interface{} {
defaults := map[string]interface{}{
"custom": map[string]interface{}{
"align": "auto",
"cellOptions": map[string]interface{}{
"type": "auto",
},
"inspect": false,
"footer": map[string]interface{}{
"reducers": []interface{}{},
},
},
"mappings": []interface{}{},
}
// Add default thresholds for all table panels to match frontend behavior
// The frontend applies the table panel's default field config which includes thresholds
hasThresholds := false
if prevDefaults != nil {
if thresholds, ok := prevDefaults["thresholds"].([]interface{}); ok && len(thresholds) > 0 {
hasThresholds = true
}
}
// Add default thresholds for all table panels (when prevDefaults exists) without existing thresholds
if !hasThresholds {
defaults["thresholds"] = map[string]interface{}{
"mode": "absolute",
"steps": []interface{}{
map[string]interface{}{"color": "green", "value": (*float64)(nil)},
map[string]interface{}{"color": "red", "value": 80},
},
}
}
if prevDefaults == nil {
return defaults
}
if unit := GetStringValue(prevDefaults, "unit"); unit != "" {
defaults["unit"] = unit
}
if decimals := GetIntValue(prevDefaults, "decimals", -1); decimals != -1 {
defaults["decimals"] = decimals
}
if alias, ok := prevDefaults["alias"].(string); ok {
defaults["displayName"] = alias
}
if align, ok := prevDefaults["align"].(string); ok && align != "" {
var alignValue interface{}
if align == "auto" {
alignValue = nil // Frontend sets to null and filters it out
} else {
alignValue = align
}
defaults["custom"].(map[string]interface{})["align"] = alignValue
}
if thresholds, ok := prevDefaults["thresholds"].([]interface{}); ok && len(thresholds) > 0 {
if colors, ok := prevDefaults["colors"].([]interface{}); ok && len(colors) > 0 {
steps := generateThresholds(thresholds, colors)
defaults["thresholds"] = map[string]interface{}{
"mode": "absolute",
"steps": steps,
}
}
}
if colorMode, ok := prevDefaults["colorMode"].(string); ok && colorMode != "" {
if newColorMode, exists := colorModeMap[colorMode]; exists {
defaults["custom"].(map[string]interface{})["cellOptions"] = map[string]interface{}{
"type": newColorMode,
}
}
}
return defaults
}
func generateThresholds(thresholds []interface{}, colors []interface{}) []interface{} {
steps := []interface{}{}
// Add the base step (equivalent to -Infinity)
var baseColor interface{} = "red" // default fallback
if len(colors) > 0 && colors[0] != nil {
baseColor = colors[0]
}
steps = append(steps, map[string]interface{}{
"color": baseColor,
"value": (*float64)(nil),
})
// Add threshold steps
for i, threshold := range thresholds {
var value float64
switch v := threshold.(type) {
case string:
if parsed, err := strconv.ParseFloat(v, 64); err == nil {
value = parsed
}
case float64:
value = v
case int:
value = float64(v)
}
step := map[string]interface{}{
"value": value,
}
// Only add color if there's a corresponding color in the colors array
// This matches the frontend behavior where colors[idx] might be undefined
if i+1 < len(colors) && colors[i+1] != nil {
step["color"] = colors[i+1]
}
steps = append(steps, step)
}
return steps
}
var colorModeMap = map[string]string{
"cell": "color-background",
"row": "color-background",
"value": "color-text",
return nil
}
@@ -44,6 +44,16 @@ func TestV24TablePanelMigration(t *testing.T) {
},
description: "V24 migration should not add empty transformations arrays to table panels",
},
{
name: "migrate_table_old_to_table",
input: map[string]interface{}{
"type": "table-old",
},
expected: map[string]interface{}{
"type": "table",
},
description: "V24 migration should migrate table-old to table",
},
}
for _, tt := range tests {
+13 -829
View File
@@ -2,61 +2,32 @@ package schemaversion
import (
"context"
"fmt"
"strconv"
"strings"
)
// V28 migrates singlestat panels to stat/gauge panels and removes deprecated variable properties.
//
// The migration performs two main tasks:
// 1. Migrates singlestat panels to either stat or gauge panels based on their configuration
// 2. Removes deprecated variable properties (tags, tagsQuery, tagValuesQuery, useTags)
//
// The migration includes comprehensive logic from the frontend:
// - Panel type migration (singlestat -> stat/gauge)
// - Field config migration with thresholds, mappings, and display options
// - Options migration including reduceOptions, orientation, and other panel-specific settings
// - Support for both angular singlestat and grafana-singlestat-panel migrations
// V28 removes deprecated variable properties (tags, tagsQuery, tagValuesQuery, useTags)
//
// Example before migration:
//
// "panels": [
// {
// "type": "singlestat",
// "gauge": { "show": true },
// "targets": [{ "refId": "A" }]
// }
// ],
// "templating": {
// "list": [
// { "name": "var1", "tags": ["tag1"], "tagsQuery": "query", "tagValuesQuery": "values", "useTags": true }
// ]
// {
// "templating": {
// "list": [
// { "name": "var1", "tags": ["tag1"], "tagsQuery": "query", "tagValuesQuery": "values", "useTags": true }
// ]
// }
// }
//
// Example after migration:
//
// "panels": [
// {
// "type": "gauge",
// "targets": [{ "refId": "A" }]
// }
// ],
// "templating": {
// "list": [
// { "name": "var1" }
// ]
// {
// "templating": {
// "list": [
// { "name": "var1" }
// ]
// }
// }
func V28(_ context.Context, dashboard map[string]interface{}) error {
dashboard["schemaVersion"] = 28
// Migrate singlestat panels
if panels, ok := dashboard["panels"].([]interface{}); ok {
if err := processPanels(panels); err != nil {
return err
}
}
// Remove deprecated variable properties
if templating, ok := dashboard["templating"].(map[string]interface{}); ok {
if list, ok := templating["list"].([]interface{}); ok {
@@ -71,751 +42,6 @@ func V28(_ context.Context, dashboard map[string]interface{}) error {
return nil
}
func processPanels(panels []interface{}) error {
for _, panel := range panels {
p, ok := panel.(map[string]interface{})
if !ok {
continue
}
// Process nested panels if this is a row panel
if p["type"] == "row" {
if nestedPanels, ok := p["panels"].([]interface{}); ok {
if err := processPanels(nestedPanels); err != nil {
return err
}
}
continue
}
// Migrate singlestat panels (including those already auto-migrated to stat)
if p["type"] == "singlestat" || p["type"] == "grafana-singlestat-panel" ||
p["autoMigrateFrom"] == "singlestat" || p["autoMigrateFrom"] == "grafana-singlestat-panel" {
if err := migrateSinglestatPanel(p); err != nil {
return err
}
}
// Note: Panel defaults (including options object) are already applied
// by applyPanelDefaults() in the main migration flow for ALL panels
// No need for stat-specific normalization
}
return nil
}
func migrateSinglestatPanel(panel map[string]interface{}) error {
targetType := "stat"
// NOTE: The legacy types "singlestat" and "gauge" are both angular only
// This are not supported by any version that could run this migration, so there is
// no need to maintain a distinction or fallback to the non-stat version
// NOTE: DashboardMigrator's migrateSinglestat function has some logic that never gets called
// migrateSinglestat will only run if (panel.type === 'singlestat')
// but this will not be the case because PanelModel runs restoreModel in the constructor
// and since singlestat is in the autoMigrateAngular map, it will be migrated to stat,
// and therefore migrateSinglestat will never run so this logic inside of it will never apply
// if ((panel as any).gauge?.show) {
// gaugePanelPlugin.meta = config.panels['gauge']
// panel.changePlugin(gaugePanelPlugin)
// Store original type for migration context (only for stat/gauge migration)
// Set autoMigrateFrom to track the original type for proper migration logic
originalType := panel["type"].(string)
// Only set autoMigrateFrom if it doesn't already exist (preserve frontend defaults)
if _, exists := panel["autoMigrateFrom"]; !exists {
panel["autoMigrateFrom"] = originalType
}
panel["type"] = targetType
panel["pluginVersion"] = pluginVersionForAutoMigrate
// Migrate panel options and field config
migrateSinglestatOptions(panel, originalType)
return nil
}
// migrateSinglestatOptions handles the complete migration of singlestat panel options and field config
func migrateSinglestatOptions(panel map[string]interface{}, originalType string) {
// Preserve important panel-level properties that should not be removed
// These properties are preserved by the frontend's getSaveModel() method
var maxDataPoints interface{}
if mdp, exists := panel["maxDataPoints"]; exists {
maxDataPoints = mdp
}
// Initialize field config if not present
if panel["fieldConfig"] == nil {
panel["fieldConfig"] = map[string]interface{}{
"defaults": map[string]interface{}{},
"overrides": []interface{}{},
}
}
fieldConfig := panel["fieldConfig"].(map[string]interface{})
defaults := fieldConfig["defaults"].(map[string]interface{})
// Migrate from angular singlestat configuration using appropriate strategy
// Use autoMigrateFrom if available, otherwise use originalType
migrationType := originalType
if autoMigrateFrom, exists := panel["autoMigrateFrom"].(string); exists {
migrationType = autoMigrateFrom
}
if migrationType == "grafana-singlestat-panel" {
migrateGrafanaSinglestatPanel(panel, defaults)
} else {
migratetSinglestat(panel, defaults)
}
// Apply shared migration logic
applySharedSinglestatMigration(defaults)
// Apply complete stat panel defaults (matches frontend getPanelOptionsWithDefaults)
// The frontend applies these defaults after migration via applyPluginOptionDefaults
applyCompleteStatPanelDefaults(panel)
// Create proper fieldConfig structure from defaults
createFieldConfigFromDefaults(panel, defaults)
// Restore preserved panel-level properties
if maxDataPoints != nil {
panel["maxDataPoints"] = maxDataPoints
}
// Clean up old angular properties after migration
cleanupAngularProperties(panel)
}
// getDefaultStatOptions returns the default options structure for stat panels
// This matches the frontend's stat panel defaultOptions exactly
func getDefaultStatOptions() map[string]interface{} {
// For now, return the explicit defaults until we integrate the centralized system
return map[string]interface{}{
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"percentChangeColorMode": "standard",
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true,
"reduceOptions": map[string]interface{}{
"calcs": []string{"lastNotNull"}, // Matches frontend: ReducerID.lastNotNull
"fields": "",
"values": false,
},
"orientation": "auto",
}
}
// migratetSinglestat handles explicit migration from 'singlestat' panels
// Based on frontend migrateFromAngularSinglestat function
func migratetSinglestat(panel map[string]interface{}, defaults map[string]interface{}) {
angularOpts := extractAngularOptions(panel)
// Extract valueName for reducer mapping (matches frontend migrateFromAngularSinglestat)
var valueName string
if vn, ok := angularOpts["valueName"].(string); ok {
valueName = vn
}
// Set calcs based on valueName (matches frontend: calcs: [reducer ? reducer.id : ReducerID.mean])
var calcs []string
if reducer := getReducerForValueName(valueName); reducer != "" {
calcs = []string{reducer}
} else {
// Use mean as fallback (matches frontend migrateFromAngularSinglestat: ReducerID.mean)
calcs = []string{"mean"}
}
// Create options exactly like frontend migrateFromAngularSinglestat
options := map[string]interface{}{
"reduceOptions": map[string]interface{}{
"calcs": calcs,
"fields": "",
"values": false,
},
"orientation": "horizontal", // Matches frontend migrateFromAngularSinglestat: VizOrientation.Horizontal
}
// Migrate thresholds FIRST (consolidated: both panel types create DEFAULT_THRESHOLDS for empty strings)
migrateThresholds(angularOpts, defaults)
// If no thresholds were set from angular migration, add default stat panel thresholds
// This matches the behavior of frontend pluginLoaded which adds default thresholds
if _, hasThresholds := defaults["thresholds"]; !hasThresholds {
defaults["thresholds"] = map[string]interface{}{
"mode": "absolute",
"steps": []interface{}{
map[string]interface{}{
"color": "green",
"value": (*float64)(nil),
},
map[string]interface{}{
"color": "red",
"value": 80,
},
},
}
}
// Apply common angular option migrations (value mappings can now use threshold colors)
applyCommonAngularMigration(panel, defaults, options, angularOpts)
// Merge new options with existing panel options to preserve properties like maxDataPoints
if existingOptions, exists := panel["options"].(map[string]interface{}); exists {
for key, value := range options {
existingOptions[key] = value
}
} else {
panel["options"] = options
}
}
// migrateGrafanaSinglestatPanel handles auto-migration from 'grafana-singlestat-panel'
// Uses the same migration logic as singlestat panels since the frontend applies
// migrateFromAngularSinglestat to both panel types.
func migrateGrafanaSinglestatPanel(panel map[string]interface{}, defaults map[string]interface{}) {
migratetSinglestat(panel, defaults)
}
// migrateThresholds handles threshold migration for both singlestat panel types
// Both panel types now create DEFAULT_THRESHOLDS when threshold string is empty (consolidated behavior)
func migrateThresholds(angularOpts map[string]interface{}, defaults map[string]interface{}) {
if thresholds, ok := angularOpts["thresholds"].(string); ok {
if colors, ok := angularOpts["colors"].([]interface{}); ok {
if thresholds != "" {
// Non-empty thresholds: use normal migration
migrateThresholdsAndColors(defaults, thresholds, colors)
} else {
// Empty thresholds: use frontend DEFAULT_THRESHOLDS fallback (both panel types)
defaults["thresholds"] = map[string]interface{}{
"mode": "absolute",
"steps": []interface{}{
map[string]interface{}{
"color": "green",
"value": (*float64)(nil), // Use pointer to ensure field is present in JSON
},
map[string]interface{}{
"color": "red",
"value": 80,
},
},
}
}
}
}
}
// applyCommonAngularMigration applies migrations common to both singlestat types
func applyCommonAngularMigration(panel map[string]interface{}, defaults map[string]interface{}, options map[string]interface{}, angularOpts map[string]interface{}) {
// Migrate table column
// Based on sharedSingleStatPanelChangedHandler line ~125: options.reduceOptions.fields = `/^${prevPanel.tableColumn}$/`
if tableColumn, ok := angularOpts["tableColumn"].(string); ok && tableColumn != "" {
options["reduceOptions"].(map[string]interface{})["fields"] = "/^" + tableColumn + "$/"
}
// Migrate unit from format property (matches frontend sharedSingleStatPanelChangedHandler)
if format, ok := angularOpts["format"].(string); ok {
defaults["unit"] = format
}
// Migrate decimals
if decimals, ok := angularOpts["decimals"]; ok {
defaults["decimals"] = decimals
}
// Note: Frontend migrateFromAngularSinglestat does migrate nullPointMode to nullValueMode
// but the frontend's getSaveModel() method removes it, so we don't add it here
// if nullPointMode, ok := angularOpts["nullPointMode"]; ok {
// defaults["nullValueMode"] = nullPointMode
// }
// Migrate null text
if nullText, ok := angularOpts["nullText"].(string); ok {
defaults["noValue"] = nullText
}
// Migrate value mappings (thresholds should already be migrated)
valueMaps, _ := angularOpts["valueMaps"].([]interface{})
migrateValueMappings(angularOpts, defaults, valueMaps)
// Migrate sparkline configuration
// Based on statPanelChangedHandler lines ~20-23: sparkline migration logic
if sparkline, ok := angularOpts["sparkline"].(map[string]interface{}); ok {
if show, ok := sparkline["show"].(bool); ok && show {
options["graphMode"] = "area"
} else {
options["graphMode"] = "none"
}
} else {
// Default to no graph mode if no sparkline configuration
options["graphMode"] = "none"
}
// Migrate color configuration
// Based on statPanelChangedHandler lines ~25-38: colorBackground and colorValue migration
colorMode := determineColorMode(angularOpts)
options["colorMode"] = colorMode
// Sparkline color migration only happens when colorMode is "none"
if colorMode == "none" {
migrateSparklineColor(angularOpts, defaults, options)
}
// Migrate text mode
// Based on statPanelChangedHandler lines ~45-47: valueName === 'name' migration
if valueName, ok := angularOpts["valueName"].(string); ok && valueName == "name" {
options["textMode"] = "name"
}
if angularOpts["gauge"] != nil && angularOpts["gauge"].(map[string]interface{})["show"] == true {
defaults["min"] = angularOpts["gauge"].(map[string]interface{})["minValue"]
defaults["max"] = angularOpts["gauge"].(map[string]interface{})["maxValue"]
}
}
// applyCompleteStatPanelDefaults applies the complete stat panel defaults
// This matches the frontend's getPanelOptionsWithDefaults behavior after migration
func applyCompleteStatPanelDefaults(panel map[string]interface{}) {
// Get or create options object
options, exists := panel["options"].(map[string]interface{})
if !exists {
options = map[string]interface{}{}
panel["options"] = options
}
defaultOptions := getDefaultStatOptions()
// Merge defaults with existing options, but don't override existing values
// This matches the frontend's getPanelOptionsWithDefaults behavior
for key, defaultValue := range defaultOptions {
if _, exists := options[key]; !exists {
options[key] = defaultValue
}
}
}
// applySharedSinglestatMigration applies shared migration logic for all singlestat panels
// Based on sharedSingleStatMigrationHandler in packages/grafana-ui/src/components/SingleStatShared/SingleStatBaseOptions.ts
func applySharedSinglestatMigration(defaults map[string]interface{}) {
// Ensure thresholds have proper structure
if thresholds, ok := defaults["thresholds"].(map[string]interface{}); ok {
if steps, ok := thresholds["steps"].([]interface{}); ok {
// Ensure first threshold is -Infinity (represented as null in JSON)
if len(steps) > 0 {
if firstStep, ok := steps[0].(map[string]interface{}); ok {
if firstStep["value"] == nil {
firstStep["value"] = nil // Use null instead of -math.Inf(1)
}
}
}
}
}
// Handle percent/percentunit units
// Based on sharedSingleStatMigrationHandler lines ~280-300: percent/percentunit min/max handling
if unit, ok := defaults["unit"].(string); ok {
switch unit {
case "percent":
if defaults["min"] == nil {
defaults["min"] = 0
}
if defaults["max"] == nil {
defaults["max"] = 100
}
case "percentunit":
if defaults["min"] == nil {
defaults["min"] = 0
}
if defaults["max"] == nil {
defaults["max"] = 1
}
}
}
}
// Helper functions
func extractAngularOptions(panel map[string]interface{}) map[string]interface{} {
// Some panels might have angular options directly in the root
// Check for common angular properties
angularProps := []string{
"valueName", "tableColumn", "format", "decimals", "nullPointMode", "nullText",
"thresholds", "colors", "valueMaps", "gauge", "sparkline", "colorBackground", "colorValue",
}
for _, prop := range angularProps {
if _, exists := panel[prop]; exists {
return panel
}
}
return map[string]interface{}{}
}
// getReducerForValueName returns the mapped reducer or empty string for invalid values
func getReducerForValueName(valueName string) string {
reducerMap := map[string]string{
"min": "min",
"max": "max",
"mean": "mean",
"avg": "mean", // avg maps to mean
"median": "median",
"sum": "sum",
"count": "count",
"first": "firstNotNull",
"last": "lastNotNull",
"name": "lastNotNull",
"current": "lastNotNull",
"total": "sum",
}
if reducer, ok := reducerMap[valueName]; ok {
return reducer
}
return ""
}
func migrateThresholdsAndColors(defaults map[string]interface{}, thresholdsStr string, colors []interface{}) {
// Parse thresholds string (e.g., "10,20,30")
// Based on sharedSingleStatPanelChangedHandler lines ~145-165: Convert thresholds and color values
thresholds := []interface{}{}
thresholdValues := strings.Split(thresholdsStr, ",")
// Create threshold steps
for i, color := range colors {
step := map[string]interface{}{
"color": color,
}
if i == 0 {
// Frontend expects explicit null value for first step, not omitted field
// Use a pointer to ensure the field is present in JSON with null value
var nullValue *float64
step["value"] = nullValue
} else if i-1 < len(thresholdValues) {
if val, err := strconv.ParseFloat(strings.TrimSpace(thresholdValues[i-1]), 64); err == nil {
step["value"] = val
}
}
thresholds = append(thresholds, step)
}
defaults["thresholds"] = map[string]interface{}{
"mode": "absolute",
"steps": thresholds,
}
}
func migrateValueMappings(panel map[string]interface{}, defaults map[string]interface{}, valueMappings []interface{}) {
mappings := []interface{}{}
mappingType := panel["mappingType"]
// Check for inconsistent mapping configuration
// If panel has rangeMaps but mappingType is 1, or vice versa, fix it
hasValueMaps := panel["valueMaps"] != nil && IsArray(panel["valueMaps"]) && len(panel["valueMaps"].([]interface{})) > 0
hasRangeMaps := panel["rangeMaps"] != nil && IsArray(panel["rangeMaps"]) && len(panel["rangeMaps"].([]interface{})) > 0
if hasRangeMaps && mappingType == float64(1) {
mappingType = 2
} else if hasValueMaps && mappingType == float64(2) {
mappingType = 1
} else if mappingType == nil {
if hasValueMaps {
mappingType = 1
} else if hasRangeMaps {
mappingType = 2
}
}
switch mappingType {
case 1:
for _, valueMap := range valueMappings {
valueMapping := valueMap.(map[string]interface{})
upgradedMapping := upgradeOldAngularValueMapping(valueMapping, defaults["thresholds"])
if upgradedMapping != nil {
mappings = append(mappings, upgradedMapping)
}
}
case 2:
// Handle range mappings
if rangeMaps, ok := panel["rangeMaps"].([]interface{}); ok {
for _, rangeMap := range rangeMaps {
rangeMapping := rangeMap.(map[string]interface{})
upgradedMapping := upgradeOldAngularValueMapping(rangeMapping, defaults["thresholds"])
if upgradedMapping != nil {
mappings = append(mappings, upgradedMapping)
}
}
}
}
defaults["mappings"] = mappings
}
// upgradeOldAngularValueMapping converts old angular value mappings to new format
// Based on upgradeOldAngularValueMapping in packages/grafana-data/src/utils/valueMappings.ts
func upgradeOldAngularValueMapping(old map[string]interface{}, thresholds interface{}) map[string]interface{} {
valueMaps := map[string]interface{}{
"type": "value",
"options": map[string]interface{}{},
}
newMappings := []interface{}{}
// Use the color we would have picked from thresholds
// Frontend uses old.text to determine color, not old.value
var color interface{}
if text, ok := old["text"].(string); ok {
if numeric, err := parseNumericValue(text); err == nil {
if thresholdsMap, ok := thresholds.(map[string]interface{}); ok {
if steps, ok := thresholdsMap["steps"].([]interface{}); ok {
level := getActiveThreshold(numeric, steps)
if level != nil {
if levelColor, ok := level["color"]; ok {
color = levelColor
}
}
}
}
}
}
// Determine mapping type
mappingType := old["type"]
if mappingType == nil {
// Try to guess from available properties
if old["value"] != nil {
mappingType = 1 // ValueToText
} else if old["from"] != nil || old["to"] != nil {
mappingType = 2 // RangeToText
}
}
switch mappingType {
case 1: // ValueToText
if value, ok := old["value"]; ok && value != nil {
if valueStr, ok := value.(string); ok && valueStr == "null" {
newMappings = append(newMappings, map[string]interface{}{
"type": "special",
"options": map[string]interface{}{
"match": "null",
"result": map[string]interface{}{"text": old["text"], "color": color},
},
})
} else {
valueMaps["options"].(map[string]interface{})[fmt.Sprintf("%v", value)] = map[string]interface{}{
"text": old["text"],
"color": color,
}
}
}
case 2: // RangeToText
from := old["from"]
to := old["to"]
if (from != nil && fmt.Sprintf("%v", from) == "null") || (to != nil && fmt.Sprintf("%v", to) == "null") {
newMappings = append(newMappings, map[string]interface{}{
"type": "special",
"options": map[string]interface{}{
"match": "null",
"result": map[string]interface{}{"text": old["text"], "color": color},
},
})
} else {
var fromVal, toVal interface{}
if from != nil {
if fromStr, ok := from.(string); ok {
if fromFloat, err := strconv.ParseFloat(fromStr, 64); err == nil {
fromVal = fromFloat
}
} else {
fromVal = from
}
}
if to != nil {
if toStr, ok := to.(string); ok {
if toFloat, err := strconv.ParseFloat(toStr, 64); err == nil {
toVal = toFloat
}
} else {
toVal = to
}
}
newMappings = append(newMappings, map[string]interface{}{
"type": "range",
"options": map[string]interface{}{
"from": fromVal,
"to": toVal,
"result": map[string]interface{}{"text": old["text"], "color": color},
},
})
}
}
// Add valueMaps if it has options
if len(valueMaps["options"].(map[string]interface{})) > 0 {
newMappings = append([]interface{}{valueMaps}, newMappings...)
}
if len(newMappings) > 0 {
return newMappings[0].(map[string]interface{})
}
return nil
}
// getActiveThreshold finds the active threshold for a given value
// Based on getActiveThreshold in packages/grafana-data/src/field/thresholds.ts
func getActiveThreshold(value float64, steps []interface{}) map[string]interface{} {
for i := len(steps) - 1; i >= 0; i-- {
if step, ok := steps[i].(map[string]interface{}); ok {
if stepValue, ok := step["value"]; ok {
if stepValue == nil {
// First step with null value (represents -Infinity)
return step
}
if stepFloat, ok := stepValue.(float64); ok && value >= stepFloat {
return step
}
}
}
}
return nil
}
// parseNumericValue converts various types to float64 for threshold calculations
func parseNumericValue(value interface{}) (float64, error) {
switch v := value.(type) {
case string:
return strconv.ParseFloat(v, 64)
case float64:
return v, nil
case float32:
return float64(v), nil
case int:
return float64(v), nil
case int32:
return float64(v), nil
case int64:
return float64(v), nil
default:
return 0, fmt.Errorf("cannot convert %T to numeric value", value)
}
}
// createFieldConfigFromDefaults creates the proper fieldConfig structure from defaults
// and removes all legacy properties from the panel
func createFieldConfigFromDefaults(panel map[string]interface{}, defaults map[string]interface{}) {
// Ensure fieldConfig exists
if panel["fieldConfig"] == nil {
panel["fieldConfig"] = map[string]interface{}{
"defaults": map[string]interface{}{},
"overrides": []interface{}{},
}
}
fieldConfig := panel["fieldConfig"].(map[string]interface{})
fieldDefaults := fieldConfig["defaults"].(map[string]interface{})
// Copy all defaults to fieldConfig.defaults
for key, value := range defaults {
fieldDefaults[key] = value
}
// Note: Frontend doesn't add these extra fieldConfig defaults
// Color is handled in sparkline migration logic
// nullValueMode and unit are not added by frontend
// Remove all legacy properties from the panel
legacyProperties := []string{
"colors", "thresholds", "valueMaps", "grid", "legend", "mappingTypes", "gauge",
"autoMigrateFrom", "colorBackground", "colorValue", "format", "mappingType",
"nullPointMode", "postfix", "postfixFontSize", "prefix",
"prefixFontSize", "rangeMaps", "sparkline", "tableColumn", "valueFontSize",
"valueName", "aliasYAxis", "bars", "dashLength", "dashes", "fill", "fillGradient",
"lineInterpolation", "lineWidth", "pointRadius", "points", "spaceLength",
"stack", "steppedLine", "xAxis", "yAxes", "yAxis", "zIndex",
}
for _, prop := range legacyProperties {
delete(panel, prop)
}
}
// cleanupAngularProperties removes old angular properties after migration
// Based on PanelModel.clearPropertiesBeforePluginChange in public/app/features/dashboard/state/PanelModel.ts
// This function removes ALL properties except those in mustKeepProps to match frontend behavior exactly
func cleanupAngularProperties(panel map[string]interface{}) {
// Properties that must be kept (matching frontend mustKeepProps)
mustKeepProps := map[string]bool{
"id": true, "gridPos": true, "type": true, "title": true, "scopedVars": true,
"repeat": true, "repeatPanelId": true, "repeatDirection": true, "repeatedByRow": true,
"minSpan": true, "collapsed": true, "panels": true, "targets": true, "datasource": true,
"timeFrom": true, "timeShift": true, "hideTimeOverride": true, "description": true,
"links": true, "fullscreen": true, "isEditing": true, "isViewing": true,
"hasRefreshed": true, "events": true, "cacheTimeout": true, "queryCachingTTL": true,
"cachedPluginOptions": true, "transparent": true, "pluginVersion": true,
"fieldConfig": true, "options": true, // These are set by migration
"maxDataPoints": true, "interval": true, // Panel-level properties preserved by frontend
"autoMigrateFrom": true, // Preserve autoMigrateFrom for proper migration logic
}
// Remove ALL properties except those in mustKeepProps (matching frontend behavior)
for key := range panel {
if !mustKeepProps[key] {
delete(panel, key)
}
}
// Ensure all targets have refIds (matching frontend ensureQueryIds behavior)
ensureTargetRefIds(panel)
}
// ensureTargetRefIds assigns refIds to targets that don't have them
// This matches the frontend PanelModel.ensureQueryIds() behavior
func ensureTargetRefIds(panel map[string]interface{}) {
targets, ok := panel["targets"].([]interface{})
if !ok || len(targets) == 0 {
return
}
// Find existing refIds
existingRefIds := make(map[string]bool)
for _, targetInterface := range targets {
if target, ok := targetInterface.(map[string]interface{}); ok {
if refId, ok := target["refId"].(string); ok {
existingRefIds[refId] = true
}
}
}
// Assign refIds to targets that don't have them
letters := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIndex := 0
for _, targetInterface := range targets {
if target, ok := targetInterface.(map[string]interface{}); ok {
refId, hasRefId := target["refId"].(string)
if !hasRefId || refId == "" {
// Find next available refId
for letterIndex < len(letters) {
refId := string(letters[letterIndex])
if !existingRefIds[refId] {
target["refId"] = refId
existingRefIds[refId] = true
break
}
letterIndex++
}
letterIndex++
}
}
}
}
// removeDeprecatedVariableProperties removes deprecated properties from variables
// Based on DashboardMigrator.ts v28 migration: variable property cleanup
func removeDeprecatedVariableProperties(variable map[string]interface{}) {
@@ -843,45 +69,3 @@ func removeDeprecatedVariableProperties(variable map[string]interface{}) {
}
}
}
// determineColorMode determines the color mode based on angular options
func determineColorMode(angularOpts map[string]interface{}) string {
if colorBackground, ok := angularOpts["colorBackground"].(bool); ok && colorBackground {
return "background"
}
if colorValue, ok := angularOpts["colorValue"].(bool); ok && colorValue {
return "value"
}
return "none"
}
// migrateSparklineColor migrates sparkline color configuration when colorMode is "none"
// Based on statPanelChangedHandler lines 31-38
func migrateSparklineColor(angularOpts map[string]interface{}, defaults map[string]interface{}, options map[string]interface{}) {
sparkline, ok := angularOpts["sparkline"].(map[string]interface{})
if !ok {
return
}
show, ok := sparkline["show"].(bool)
if !ok || !show {
return
}
graphMode, ok := options["graphMode"].(string)
if !ok || graphMode != "area" {
return
}
lineColor, ok := sparkline["lineColor"].(string)
if !ok {
return
}
defaults["color"] = map[string]interface{}{
"mode": "fixed",
"fixedColor": lineColor,
}
}
@@ -5,101 +5,186 @@ import (
"testing"
)
func TestV28SinglestatMigration(t *testing.T) {
tests := []struct {
name string
input map[string]interface{}
expected map[string]interface{}
description string
}{
{
name: "migrate_range_maps_to_field_config_mappings",
input: map[string]interface{}{
"type": "singlestat",
"rangeMaps": []interface{}{
map[string]interface{}{
"from": "null",
"to": "N/A",
},
},
"mappingType": 1, // Inconsistent - should be 2 for rangeMaps
},
expected: map[string]interface{}{
"type": "stat",
"fieldConfig": map[string]interface{}{
"defaults": map[string]interface{}{
"mappings": []interface{}{
map[string]interface{}{
"options": map[string]interface{}{
"match": "null",
"result": map[string]interface{}{
"text": "N/A",
},
},
"type": "special",
},
},
},
},
},
description: "RangeMaps should migrate to fieldConfig.mappings, and inconsistent mappingType should be fixed to 2 (RangeToText)",
},
{
name: "migrate_sparkline_color_when_color_mode_none",
input: map[string]interface{}{
"type": "singlestat",
"colorMode": "None",
"sparkline": map[string]interface{}{
"lineColor": "rgb(31, 120, 193)",
},
},
expected: map[string]interface{}{
"type": "stat",
"fieldConfig": map[string]interface{}{
"defaults": map[string]interface{}{
"color": map[string]interface{}{
"mode": "fixed",
"fixedColor": "rgb(31, 120, 193)",
},
},
},
},
description: "Sparkline lineColor should migrate to fieldConfig.defaults.color only when colorMode is None",
},
}
type migrationTestCase struct {
name string
input map[string]interface{}
expected map[string]interface{}
}
func runMigrationTests(t *testing.T, tests []migrationTestCase, migrationFunc func(context.Context, map[string]interface{}) error) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dashboard := map[string]interface{}{
"schemaVersion": 27,
"panels": []interface{}{tt.input},
// Create a copy of the input
dashboard := make(map[string]interface{})
for k, v := range tt.input {
dashboard[k] = v
}
err := V28(context.Background(), dashboard)
err := migrationFunc(context.Background(), dashboard)
if err != nil {
t.Fatalf("V28 migration failed: %v", err)
t.Fatalf("Migration failed: %v", err)
}
if dashboard["schemaVersion"] != 28 {
t.Errorf("Expected schemaVersion to be 28, got %v", dashboard["schemaVersion"])
// Verify the result matches expected
if !deepEqual(dashboard, tt.expected) {
t.Errorf("Migration result doesn't match expected.\nExpected: %+v\nGot: %+v", tt.expected, dashboard)
}
panels, ok := dashboard["panels"].([]interface{})
if !ok || len(panels) == 0 {
t.Fatalf("Expected panels array with at least one panel")
}
panel, ok := panels[0].(map[string]interface{})
if !ok {
t.Fatalf("Expected panel to be a map")
}
// Verify panel type was changed to stat
if panel["type"] != "stat" {
t.Errorf("Expected panel type to be 'stat', got %v", panel["type"])
}
t.Logf("✓ %s: %s", tt.name, tt.description)
})
}
}
func deepEqual(a, b interface{}) bool {
// Simple deep comparison for test purposes
// This is a simplified version - in production you'd use reflect.DeepEqual or similar
switch aVal := a.(type) {
case map[string]interface{}:
bVal, ok := b.(map[string]interface{})
if !ok || len(aVal) != len(bVal) {
return false
}
for k, v := range aVal {
if !deepEqual(v, bVal[k]) {
return false
}
}
return true
case []interface{}:
bVal, ok := b.([]interface{})
if !ok || len(aVal) != len(bVal) {
return false
}
for i, v := range aVal {
if !deepEqual(v, bVal[i]) {
return false
}
}
return true
default:
return a == b
}
}
func TestV28(t *testing.T) {
tests := []migrationTestCase{
{
name: "v28 removes deprecated variable properties",
input: map[string]interface{}{
"title": "V28 Variable Properties Migration Test Dashboard",
"schemaVersion": 27,
"templating": map[string]interface{}{
"list": []interface{}{
map[string]interface{}{
"name": "var1",
"tags": []interface{}{"tag1", "tag2"},
"tagsQuery": "query_string",
"tagValuesQuery": "values_query",
"useTags": true,
"type": "query",
},
map[string]interface{}{
"name": "var2",
"tags": []interface{}{},
"tagsQuery": "", // Empty string should not be removed
"tagValuesQuery": "", // Empty string should not be removed
"useTags": false, // False should not be removed
"type": "custom",
},
},
},
"panels": []interface{}{
map[string]interface{}{
"type": "singlestat",
"title": "Singlestat Panel (unchanged by v28)",
"id": 1,
},
},
},
expected: map[string]interface{}{
"title": "V28 Variable Properties Migration Test Dashboard",
"schemaVersion": 28,
"templating": map[string]interface{}{
"list": []interface{}{
map[string]interface{}{
"name": "var1",
"type": "query",
// tags, tagsQuery, tagValuesQuery, useTags should be removed
},
map[string]interface{}{
"name": "var2",
"tagsQuery": "", // Empty string preserved
"tagValuesQuery": "", // Empty string preserved
"useTags": false, // False preserved
"type": "custom",
// only tags should be removed
},
},
},
"panels": []interface{}{
map[string]interface{}{
"type": "singlestat",
"title": "Singlestat Panel (unchanged by v28)",
"id": 1,
},
},
},
},
{
name: "v28 handles dashboard without templating",
input: map[string]interface{}{
"title": "Dashboard without templating",
"schemaVersion": 27,
"panels": []interface{}{
map[string]interface{}{
"type": "singlestat",
"title": "Singlestat Panel",
"id": 1,
},
},
},
expected: map[string]interface{}{
"title": "Dashboard without templating",
"schemaVersion": 28,
"panels": []interface{}{
map[string]interface{}{
"type": "singlestat",
"title": "Singlestat Panel",
"id": 1,
},
},
},
},
{
name: "v28 handles empty templating list",
input: map[string]interface{}{
"title": "Dashboard with empty templating",
"schemaVersion": 27,
"templating": map[string]interface{}{
"list": []interface{}{},
},
"panels": []interface{}{
map[string]interface{}{
"type": "singlestat",
"title": "Singlestat Panel",
"id": 1,
},
},
},
expected: map[string]interface{}{
"title": "Dashboard with empty templating",
"schemaVersion": 28,
"templating": map[string]interface{}{
"list": []interface{}{},
},
"panels": []interface{}{
map[string]interface{}{
"type": "singlestat",
"title": "Singlestat Panel",
"id": 1,
},
},
},
},
}
runMigrationTests(t, tests, V28)
}