Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
### 3.0 Cleanup

* [CHANGE] **BREAKING CHANGE** Disable legacy (flat, unscoped) overrides by default. Tempo will refuse to start if legacy overrides are detected. Set `enable_legacy_overrides: true` or `-config.enable-legacy-overrides=true` to opt back in temporarily. Legacy overrides will be removed in a future release. [#6741](https://github.com/grafana/tempo/pull/6741) (@electron0zero)
* [CHANGE] tempo-cli: Rewrite `migrate overrides-config` and add `migrate overrides-per-tenant` command to help migrate legacy flat overrides to the new scoped format. [#6793](https://github.com/grafana/tempo/pull/6793) (@electron0zero)
* [CHANGE] **BREAKING CHANGE** Remove remaining app ingester config [#6667](https://github.com/grafana/tempo/pull/6667) (@javiermolinar)
* [CHANGE] **BREAKING CHANGE** Remove span-metrics leftovers and lazy-init generator clients [#6618](https://github.com/grafana/tempo/pull/6618) (@javiermolinar)
* [CHANGE] **BREAKING CHANGE** Decommission livestore MetricsGenerator query service [#6615](https://github.com/grafana/tempo/pull/6615) (@javiermolinar)
Expand Down
162 changes: 107 additions & 55 deletions cmd/tempo-cli/cmd-migrate-overrides-config.go
Original file line number Diff line number Diff line change
@@ -1,107 +1,159 @@
package main

import (
"bytes"
"context"
"flag"
"fmt"
"net/http"
"net/url"
"io"
"os"
"reflect"

"github.com/grafana/dskit/services"
"github.com/prometheus/client_golang/prometheus"
"go.yaml.in/yaml/v2"

"github.com/grafana/tempo/cmd/tempo/app"
"github.com/grafana/tempo/modules/overrides"
)

type migrateOverridesConfigCmd struct {
ConfigFile string `arg:"" help:"Path to tempo config file"`
ConfigFile string `arg:"" help:"Path to the full tempo config file"`

ConfigDest string `type:"path" short:"d" help:"Path to tempo config file. If not specified, output to stdout"`
OverridesDest string `type:"path" short:"o" help:"Path to tempo overrides file. If not specified, output to stdout"`
ConfigDest string `type:"path" short:"d" help:"Path to write the migrated overrides section. If not specified, output to stdout"`
Comment thread
electron0zero marked this conversation as resolved.
}

func (cmd *migrateOverridesConfigCmd) Run(*globalOptions) error {
// Defaults
cfg := app.Config{}
cfg.RegisterFlagsAndApplyDefaults("", &flag.FlagSet{})

// Existing config
// Build the default overrides config for comparison from a separate instance
// to avoid shared pointers between defaultOverrides and cfg.Overrides.
defaultCfg := app.Config{}
defaultCfg.RegisterFlagsAndApplyDefaults("", &flag.FlagSet{})
defaultOverrides := defaultCfg.Overrides

buff, err := os.ReadFile(cmd.ConfigFile)
if err != nil {
return fmt.Errorf("failed to read configFile %s: %w", cmd.ConfigFile, err)
}

// Legacy overrides are automatically converted to a new format during unmarshaling
// via Config.UnmarshalYAML.
if err := yaml.UnmarshalStrict(buff, &cfg); err != nil {
Comment thread
electron0zero marked this conversation as resolved.
return fmt.Errorf("failed to parse configFile %s: %w", cmd.ConfigFile, err)
}

// The migration command needs to read legacy overrides to convert them,
// so force-enable legacy overrides regardless of the config setting.
cfg.Overrides.EnableLegacyOverrides = true

o, err := overrides.NewOverrides(cfg.Overrides, nil, prometheus.DefaultRegisterer)
// Marshal both configs to maps so we can diff them.
loadedMap, err := toMap(cfg.Overrides)
if err != nil {
return fmt.Errorf("failed to load overrides module: %w", err)
return fmt.Errorf("failed to convert loaded overrides to map: %w", err)

Check notice on line 45 in cmd/tempo-cli/cmd-migrate-overrides-config.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered line

Line 45 is not covered by tests
}

if err := services.StartAndAwaitRunning(context.Background(), o); err != nil {
return fmt.Errorf("failed to start overrides module: %w", err)
defaultMap, err := toMap(defaultOverrides)
if err != nil {
return fmt.Errorf("failed to convert default overrides to map: %w", err)

Check notice on line 50 in cmd/tempo-cli/cmd-migrate-overrides-config.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered line

Line 50 is not covered by tests
}

buffer := bytes.NewBuffer(make([]byte, 0))
if err := o.WriteStatusRuntimeConfig(buffer, &http.Request{URL: &url.URL{}}); err != nil {
return fmt.Errorf("failed to output runtime config: %w", err)
}
// Remove keys that match the defaults so we only output user-set values.
removeDefaults(loadedMap, defaultMap)

var runtimeConfig struct {
Defaults overrides.Overrides `yaml:"defaults"`
PerTenantOverrides map[string]overrides.Config `yaml:"overrides"`
}
if err := yaml.UnmarshalStrict(buffer.Bytes(), &runtimeConfig); err != nil {
return fmt.Errorf("failed parsing overrides config: %w", err)
result := map[string]interface{}{
"overrides": loadedMap,
Comment thread
electron0zero marked this conversation as resolved.
}

cfg.Overrides.Defaults = runtimeConfig.Defaults
cfg.Overrides.EnableLegacyOverrides = false // reset - migrated config doesn't need this
configBytes, err := yaml.Marshal(cfg)
outputBytes, err := yaml.Marshal(result)
if err != nil {
return fmt.Errorf("failed to marshal config: %w", err)
return fmt.Errorf("failed to marshal overrides: %w", err)

Check notice on line 62 in cmd/tempo-cli/cmd-migrate-overrides-config.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered line

Line 62 is not covered by tests
}

printWarnings(os.Stderr)

if cmd.ConfigDest != "" {
if err := os.WriteFile(cmd.ConfigDest, configBytes, 0o600); err != nil {
return fmt.Errorf("failed to write config file: %w", err)
if err := os.WriteFile(cmd.ConfigDest, outputBytes, 0o600); err != nil {
return fmt.Errorf("failed to write output file: %w", err)

Check notice on line 69 in cmd/tempo-cli/cmd-migrate-overrides-config.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered line

Line 69 is not covered by tests
}
fmt.Fprintf(os.Stderr, "Migrated overrides written to %s\n", cmd.ConfigDest)
fmt.Fprintln(os.Stderr, "Replace the overrides section in your config file with the contents of this file.")
} else {
fmt.Println(cmd.ConfigFile)
// Only print the overrides block
partialCfg := struct {
Overrides overrides.Config `yaml:"overrides"`
}{Overrides: cfg.Overrides}
overridesBytes, err := yaml.Marshal(partialCfg)
if err != nil {
return fmt.Errorf("failed to marshal overrides: %w", err)
}
fmt.Println(string(overridesBytes))
fmt.Fprintln(os.Stderr, "Migrated overrides config. Replace the overrides section in your config file with the output below:")
fmt.Fprintln(os.Stderr, "---")
fmt.Print(string(outputBytes))

Check notice on line 76 in cmd/tempo-cli/cmd-migrate-overrides-config.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered lines

Lines 74-76 are not covered by tests
}

overridesBytes, err := yaml.Marshal(runtimeConfig.PerTenantOverrides)
return nil
}

// toMap converts a struct to a normalized map[string]interface{} via yaml round-trip.
// All nested maps are normalized to map[string]interface{}.
func toMap(v interface{}) (map[string]interface{}, error) {
b, err := yaml.Marshal(v)
if err != nil {
return fmt.Errorf("failed to marshal overrides: %w", err)
return nil, err
}

Check notice on line 88 in cmd/tempo-cli/cmd-migrate-overrides-config.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered lines

Lines 87-88 are not covered by tests
var m map[string]interface{}
if err := yaml.Unmarshal(b, &m); err != nil {
return nil, err
}

Check notice on line 92 in cmd/tempo-cli/cmd-migrate-overrides-config.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered lines

Lines 91-92 are not covered by tests
return normalizeMap(m), nil
}

// normalizeMap recursively converts all map[interface{}]interface{} to map[string]interface{}.
func normalizeMap(m map[string]interface{}) map[string]interface{} {
for k, v := range m {
m[k] = normalizeValue(v)
}
return m
}

if cmd.OverridesDest != "" {
if err := os.WriteFile(cmd.OverridesDest, overridesBytes, 0o600); err != nil {
return fmt.Errorf("failed to write overrides file: %w", err)
func normalizeValue(v interface{}) interface{} {
switch val := v.(type) {
case map[interface{}]interface{}:
out := make(map[string]interface{}, len(val))
for k, v := range val {
out[fmt.Sprintf("%v", k)] = normalizeValue(v)
}
} else {
fmt.Println(cfg.Overrides.PerTenantOverrideConfig)
fmt.Println(string(overridesBytes))
return out
case map[string]interface{}:
return normalizeMap(val)

Check notice on line 113 in cmd/tempo-cli/cmd-migrate-overrides-config.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered lines

Lines 112-113 are not covered by tests
case []interface{}:
for i, item := range val {
val[i] = normalizeValue(item)
}
return val
default:
return v
}
}

return nil
// removeDefaults recursively removes keys from loaded where the value matches the default.
func removeDefaults(loaded, defaults map[string]interface{}) {
for key, defaultVal := range defaults {
loadedVal, ok := loaded[key]
if !ok {
continue
}

loadedChild, loadedIsMap := loadedVal.(map[string]interface{})
defaultChild, defaultIsMap := defaultVal.(map[string]interface{})

if loadedIsMap && defaultIsMap {
removeDefaults(loadedChild, defaultChild)
if len(loadedChild) == 0 {
delete(loaded, key)
}
continue
}

if reflect.DeepEqual(loadedVal, defaultVal) {
delete(loaded, key)
}
}
}

func printWarnings(w io.Writer) {
fmt.Fprintln(w, "WARNING: Please verify the migrated output carefully before using it.")
fmt.Fprintln(w, "- Fields set to Go zero values (false, 0, \"\") may be silently dropped")
fmt.Fprintln(w, " due to omitempty tags. Compare against your original config to ensure nothing is lost.")
fmt.Fprintln(w, "- Secret values (e.g. remote_write_headers) are masked as '<secret>' in the output.")
fmt.Fprintln(w, " You must manually restore the original values.")
fmt.Fprintln(w, "- Some struct fields without omitempty may appear with zero values (e.g. 'exclude: null')")
fmt.Fprintln(w, " that were not in your original config. These can be removed.")
fmt.Fprintln(w, "NOTE: This tool is provided for convenience only. Always double check the output against your original config.")
fmt.Fprintln(w, "For full details on overrides configuration, see: https://grafana.com/docs/tempo/latest/configuration/#overrides")
}
83 changes: 83 additions & 0 deletions cmd/tempo-cli/cmd-migrate-overrides-config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package main

import (
"os"
"sort"
"testing"

"github.com/stretchr/testify/require"
"go.yaml.in/yaml/v2"
)

func TestMigrateOverridesConfig(t *testing.T) {
tests := []struct {
name string
inputFile string
expectedFile string
}{
{
name: "legacy config is migrated to new scoped format",
inputFile: "test-data/migrate-overrides-config/legacy-input.yaml",
expectedFile: "test-data/migrate-overrides-config/legacy-expected.yaml",
},
{
name: "new format config is passed through unchanged",
inputFile: "test-data/migrate-overrides-config/new-format-input.yaml",
expectedFile: "test-data/migrate-overrides-config/new-format-expected.yaml",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
expectedBytes, err := os.ReadFile(tt.expectedFile)
require.NoError(t, err)

outputPath := t.TempDir() + "/output.yaml"
cmd := migrateOverridesConfigCmd{
ConfigFile: tt.inputFile,
ConfigDest: outputPath,
}

err = cmd.Run(nil)
require.NoError(t, err)

actualBytes, err := os.ReadFile(outputPath)
require.NoError(t, err)

// Compare as parsed YAML maps to avoid flaky failures from
// non-deterministic map iteration order (e.g. ListToMap processors).
var expectedMap, actualMap interface{}
require.NoError(t, yaml.Unmarshal(expectedBytes, &expectedMap))
require.NoError(t, yaml.Unmarshal(actualBytes, &actualMap))

sortStringSlices(expectedMap)
sortStringSlices(actualMap)

require.Equal(t, expectedMap, actualMap)
})
}
}

// sortStringSlices recursively sorts []interface{} slices that contain only strings
// to handle non-deterministic ordering from map-backed types like ListToMap.
func sortStringSlices(v interface{}) {
switch val := v.(type) {
case map[interface{}]interface{}:
for _, v := range val {
sortStringSlices(v)
}
case []interface{}:
allStrings := true
for _, item := range val {
if _, ok := item.(string); !ok {
allStrings = false
}
sortStringSlices(item)
}
if allStrings && len(val) > 0 {
sort.Slice(val, func(i, j int) bool {
return val[i].(string) < val[j].(string)
})
}
}
}
75 changes: 75 additions & 0 deletions cmd/tempo-cli/cmd-migrate-overrides-per-tenant.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package main

import (
"fmt"
"os"

"go.yaml.in/yaml/v2"

"github.com/grafana/tempo/modules/overrides"
)

type migrateOverridesPerTenantCmd struct {
OverridesFile string `arg:"" help:"Path to the per-tenant overrides file"`

OutputDest string `type:"path" short:"d" help:"Path to write the migrated per-tenant overrides. If not specified, output to stdout"`
}

func (cmd *migrateOverridesPerTenantCmd) Run(*globalOptions) error {
buff, err := os.ReadFile(cmd.OverridesFile)
if err != nil {
return fmt.Errorf("failed to read overrides file %s: %w", cmd.OverridesFile, err)
}

Check notice on line 22 in cmd/tempo-cli/cmd-migrate-overrides-per-tenant.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered lines

Lines 21-22 are not covered by tests

// Legacy per-tenant overrides are automatically converted to the new format
// during unmarshaling via perTenantOverrides.UnmarshalYAML.
tenantOverrides, err := overrides.UnmarshalPerTenantOverrides(buff)
if err != nil {
return fmt.Errorf("failed to parse overrides file %s: %w", cmd.OverridesFile, err)
}

Check notice on line 29 in cmd/tempo-cli/cmd-migrate-overrides-per-tenant.go

View workflow job for this annotation

GitHub Actions / Coverage Annotations

Uncovered lines

Lines 28-29 are not covered by tests

// Diff each tenant's overrides against a zero-value Overrides to strip defaults.
defaultMap, err := toMap(overrides.Overrides{})
if err != nil {
return fmt.Errorf("failed to convert default overrides to map: %w", err)
}

result := make(map[string]interface{}, len(tenantOverrides))
for tenant, o := range tenantOverrides {
if o == nil {
continue
}
tenantMap, err := toMap(o)
if err != nil {
return fmt.Errorf("failed to convert overrides for tenant %s to map: %w", tenant, err)
}
removeDefaults(tenantMap, defaultMap)
if len(tenantMap) > 0 {
result[tenant] = tenantMap
}
}

output := map[string]interface{}{
"overrides": result,
}

outputBytes, err := yaml.Marshal(output)
Comment thread
electron0zero marked this conversation as resolved.
if err != nil {
return fmt.Errorf("failed to marshal per-tenant overrides: %w", err)
}

printWarnings(os.Stderr)

if cmd.OutputDest != "" {
if err := os.WriteFile(cmd.OutputDest, outputBytes, 0o600); err != nil {
return fmt.Errorf("failed to write output file: %w", err)
}
fmt.Fprintf(os.Stderr, "Migrated per-tenant overrides written to %s\n", cmd.OutputDest)
} else {
fmt.Fprintln(os.Stderr, "Migrated per-tenant overrides. Replace your per-tenant overrides file with the output below:")
fmt.Fprintln(os.Stderr, "---")
fmt.Print(string(outputBytes))
}

return nil
}
Loading
Loading