migrate

package
v0.20.0-rc.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	GMPAPIVersion = "monitoring.googleapis.com/v1"

	KindPodMonitoring        = "PodMonitoring"
	KindClusterPodMonitoring = "ClusterPodMonitoring"
	KindOperatorConfig       = "OperatorConfig"
	KindPodMonitor           = "PodMonitor"
	KindServiceMonitor       = "ServiceMonitor"
	KindPrometheus           = "Prometheus"
	KindService              = "Service"
	KindConfigMap            = "ConfigMap"
	KindSecret               = "Secret"
)
View Source
const (
	AnnotationTodoPrefix = "gmp.googleapis.com/todo-"
)

Variables

This section is empty.

Functions

func AddMigrationTodo

func AddMigrationTodo(u *unstructured.Unstructured, category, reason, action string)

AddMigrationTodo appends a sequential TODO annotation to the unstructured resource.

func BuildTypeMeta

func BuildTypeMeta(kind string) metav1.TypeMeta

BuildTypeMeta constructs standard TypeMeta for a GMP resource Kind.

func CopyObjectMeta

func CopyObjectMeta(src metav1.ObjectMeta, targetNamespace string, logger *slog.Logger) metav1.ObjectMeta

CopyObjectMeta copies Name and Namespace from source to target, and strips labels and annotations.

Types

type CachedResource

type CachedResource struct {
	Unstructured *unstructured.Unstructured
	TypedService *corev1.Service
}

CachedResource holds the raw unstructured object and optional pre-converted typed struct.

type ConsoleHandler

type ConsoleHandler struct {
	// contains filtered or unexported fields
}

ConsoleHandler is a thread-safe slog.Handler that formats logs for the console (Stderr) and tracks the highest log level seen per resource (for statistics).

func NewConsoleHandler

func NewConsoleHandler(out io.Writer) *ConsoleHandler

NewConsoleHandler creates a new ConsoleHandler.

func (*ConsoleHandler) Enabled

func (h *ConsoleHandler) Enabled(_ context.Context, _ slog.Level) bool

func (*ConsoleHandler) Handle

func (h *ConsoleHandler) Handle(_ context.Context, r slog.Record) error

func (*ConsoleHandler) ResourceStatuses

func (h *ConsoleHandler) ResourceStatuses() map[string]ResourceStatus

ResourceStatuses returns a thread-safe copy of the tracked resource statuses.

func (*ConsoleHandler) WithAttrs

func (h *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*ConsoleHandler) WithGroup

func (h *ConsoleHandler) WithGroup(_ string) slog.Handler

type MigrationReport

type MigrationReport struct {
	SuccessCount     int                          // Successfully migrated with no warnings or action items.
	WarningsCount    int                          // Migrated with non-blocking warnings (e.g. dropped unsupported fields).
	ActionItemsCount int                          // Successfully migrated but had TODO annotations.
	SkippedCount     int                          // Bypassed because resource is unsupported/out-of-scope.
	FailedCount      int                          // Fatal failure, resource skipped.
	Outputs          []*unstructured.Unstructured // All converted GMP manifests in-memory.
	ReadyOutputs     []*unstructured.Unstructured // Only 100% ready manifests (0 TODO annotations).
}

MigrationReport accumulates the statistics and payloads of the migration run.

type Migrator

type Migrator struct {

	// Decoupled streams (defaults to os.Stdin/os.Stdout/os.Stderr).
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

Migrator orchestrates the migration process.

func NewMigrator

func NewMigrator() *Migrator

NewMigrator creates a new Migrator.

func (*Migrator) PrintSummary

func (m *Migrator) PrintSummary(r *MigrationReport, emitAll bool)

PrintSummary formats and writes the standardized migration report summary.

func (*Migrator) RegisterConverter

func (m *Migrator) RegisterConverter(c ResourceConverter)

RegisterConverter registers a converter for a specific resource Kind.

func (*Migrator) Run

func (m *Migrator) Run(inputPaths ...string) (*MigrationReport, error)

Run executes the migration flow and returns the summary report across multiple inputs.

Example

ExampleMigrator_Run demonstrates migrating a ServiceMonitor with a backing Service. This example is tested automatically during 'go test'.

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/GoogleCloudPlatform/prometheus-engine/pkg/migrate"
)

func main() {
	inputYAML := `
apiVersion: v1
kind: Service
metadata:
  name: frontend-svc
  namespace: web
  labels:
    app: frontend
spec:
  selector:
    app: frontend-pod
  ports:
  - name: web-metrics
    port: 80
    targetPort: 8080
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: frontend-monitor
  namespace: web
  labels:
    app: frontend
spec:
  selector:
    matchLabels:
      app: frontend
  endpoints:
  - port: web-metrics
    interval: 30s
    path: /metrics
`

	migrator := migrate.NewMigrator()
	migrator.Stdin = strings.NewReader(inputYAML)
	migrator.Stdout = os.Stdout
	migrator.Stderr = os.Stdout // Direct logs to stdout for testable example capture.
	migrator.RegisterConverter(&migrate.ServiceMonitorConverter{})

	report, err := migrator.Run("-")
	if err != nil {
		fmt.Printf("Migration failed: %v\n", err)
		return
	}

	if err := migrator.WriteOutputs(report.ReadyOutputs); err != nil {
		fmt.Printf("Failed to write outputs: %v\n", err)
		return
	}

	migrator.PrintSummary(report, false)

}
Output:
[INFO] [ServiceMonitor:web/frontend-monitor] Successfully decoded ServiceMonitor
[INFO] [ServiceMonitor:web/frontend-monitor] Stripped all metadata labels and annotations. Reconfigure them manually if needed
[SUCCESS] [ServiceMonitor:web/frontend-monitor] Converted successfully
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  name: frontend-monitor
  namespace: web
spec:
  endpoints:
  - interval: 30s
    path: /metrics
    port: 8080
  selector:
    matchLabels:
      app: frontend-pod
  targetLabels:
    metadata: null
status:
  observedGeneration: 0

=========================================
Migration Complete Summary:
  Successfully Migrated:      1
  Migrated with Warnings:     0
  Migrated with Action Items: 0
  Skipped (Unsupported):      0
  Failed:                     0
=========================================

func (*Migrator) WriteOutputs

func (m *Migrator) WriteOutputs(outputs []*unstructured.Unstructured) error

WriteOutputs serializes and writes the converted manifests to the migrator's Stdout stream. in standard Kubernetes multi-document YAML format (separated by "---").

type PodMonitorConverter

type PodMonitorConverter struct{}

PodMonitorConverter implements ResourceConverter for PodMonitor resources.

func (*PodMonitorConverter) Convert

Convert translates a Prometheus Operator PodMonitor into GMP resources.

func (*PodMonitorConverter) ImportKey

func (c *PodMonitorConverter) ImportKey() string

ImportKey returns the Kind of the resource this converter handles.

type ResourceCache

type ResourceCache struct {
	// contains filtered or unexported fields
}

ResourceCache stores parsed Kubernetes resources for cross-resource resolution.

func NewResourceCache

func NewResourceCache() *ResourceCache

NewResourceCache creates a new initialized ResourceCache.

func (*ResourceCache) Add

Add adds a resource to the cache, returning an error if inputs are invalid.

func (*ResourceCache) Get

func (c *ResourceCache) Get(kind, namespace, name string) (*unstructured.Unstructured, bool)

Get retrieves a resource from the cache by kind, namespace, and name.

func (*ResourceCache) ListByKind

func (c *ResourceCache) ListByKind(kind string) []*unstructured.Unstructured

ListByKind returns a sorted slice of unstructured resources for a specified kind.

func (*ResourceCache) ListKinds

func (c *ResourceCache) ListKinds() []string

ListKinds returns a sorted slice of all resource kinds currently in the cache.

type ResourceConverter

type ResourceConverter interface {
	// ImportKey returns the Kind of the resource this converter handles (e.g., "PodMonitor").
	ImportKey() string
	// Convert translates the input unstructured resource to one or more GMP resources.
	Convert(ctx context.Context, logger *slog.Logger, unstruct *unstructured.Unstructured, cache *ResourceCache) (outputs []*unstructured.Unstructured, err error)
}

ResourceConverter defines the interface for converting a specific Prometheus Operator resource kind.

type ResourceStatus

type ResourceStatus int

ResourceStatus defines the final migration state of an ingested resource.

const (
	StatusSuccess     ResourceStatus = iota // 0 (Migrated Successfully).
	StatusSkipped                           // 1 (Skipped / Unsupported).
	StatusWarnings                          // 2 (Migrated with Warnings).
	StatusActionItems                       // 3 (Migrated with Action Items).
	StatusFailed                            // 4 (Failed).
)

type ServiceMonitorConverter

type ServiceMonitorConverter struct{}

ServiceMonitorConverter implements ResourceConverter for ServiceMonitor resources.

func (*ServiceMonitorConverter) Convert

Convert translates a Prometheus Operator ServiceMonitor into GMP resources.

func (*ServiceMonitorConverter) ImportKey

func (c *ServiceMonitorConverter) ImportKey() string

ImportKey returns the Kind of the resource this converter handles.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL