paths

package
v1.0.0-rc07 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package paths provides centralized path resolution for opencenter-cli clusters.

Overview

The paths package eliminates duplicate path construction logic throughout the codebase by providing a single source of truth for all cluster-related paths. It supports organization-based directory structures with caching, validation, and fallback strategies.

Architecture

The package is built around three core components:

1. PathResolver: Main entry point for path resolution 2. ResolutionStrategy: Pluggable strategies for different directory layouts 3. PathCache: Thread-safe caching for performance optimization

Directory Structure

The package supports organization-based directory structures:

~/.config/opencenter/clusters/
├── blueprints/<organization>/<cluster>/
│   └── <cluster>-config.yaml
├── gitops/<organization>/
│   ├── infrastructure/clusters/<cluster>/
│   │   ├── inventory/
│   │   ├── venv/
│   │   ├── kubespray/
│   │   └── .bin/
│   ├── applications/overlays/<cluster>/
│   └── .sops.yaml
└── secrets/<organization>/<cluster>/
    ├── age/keys/<cluster>-key.txt
    ├── ssh/<cluster>
    └── kubernetes/kubeconfig.yaml

Basic Usage

Create a resolver and resolve paths for a cluster:

resolver := paths.NewPathResolver("~/.config/opencenter/clusters")
clusterPaths, err := resolver.Resolve(context.Background(), "my-cluster", "myorg")
if err != nil {
    log.Fatal(err)
}

// Access resolved paths
configPath := clusterPaths.ConfigPath
secretsDir := clusterPaths.SecretsDir

Fallback Resolution

When the organization is unknown, use fallback resolution to search across all organizations:

clusterPaths, err := resolver.ResolveWithFallback(context.Background(), "my-cluster")
if err != nil {
    log.Fatal(err)
}

Custom Options

Configure the resolver with custom options:

options := paths.ResolutionOptions{
    Organization:  "myorg",
    CacheResults:  true,
    ValidatePaths: true,
}
resolver := paths.NewPathResolverWithOptions(baseDir, options)

Cache Management

The resolver includes built-in caching for performance:

// Invalidate cache for a specific cluster
resolver.InvalidateCache("my-cluster")

// Clear all cached entries
resolver.ClearCache()

// Get cache statistics
stats := resolver.GetCacheStats()
fmt.Printf("Cache hit rate: %.2f%%\n", stats.HitRate*100)

Directory Creation

Create all necessary directories for a new cluster:

err := resolver.CreateClusterDirectories(
    context.Background(),
    "my-cluster",
    "myorg",
)
if err != nil {
    log.Fatal(err)
}

Organization Detection

Detect the organization for an existing cluster:

org, err := resolver.GetOrganization(context.Background(), "my-cluster")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Cluster belongs to organization: %s\n", org)

Path Validation

Validate that paths are safe and accessible:

err := resolver.ValidatePath("/path/to/validate")
if err != nil {
    log.Printf("Invalid path: %v\n", err)
}

Thread Safety

All resolver operations are thread-safe and can be used concurrently:

var wg sync.WaitGroup
for _, cluster := range clusters {
    wg.Add(1)
    go func(name string) {
        defer wg.Done()
        paths, err := resolver.Resolve(ctx, name, "myorg")
        // Process paths...
    }(cluster)
}
wg.Wait()

Performance Characteristics

The resolver is optimized for performance:

  • Path resolution: <1ms (uncached)
  • Path resolution: <100μs (cached)
  • Cache hit rate: >90% in typical usage
  • Memory overhead: ~1KB per cached cluster

Error Handling

The package returns descriptive errors for common failure cases:

  • Invalid cluster names (format, length, special characters)
  • Missing directories
  • Permission issues
  • Path traversal attempts

Example error handling:

paths, err := resolver.Resolve(ctx, clusterName, org)
if err != nil {
    if os.IsNotExist(err) {
        // Cluster doesn't exist
    } else if strings.Contains(err.Error(), "invalid cluster name") {
        // Invalid name format
    } else {
        // Other error
    }
    return err
}

Migration from Legacy Code

Replace direct path construction with resolver calls:

// Old (duplicate logic)
configPath := filepath.Join(baseDir, org, "infrastructure", "clusters", cluster, "."+cluster+"-config.yaml")

// New (centralized)
paths, err := resolver.Resolve(ctx, cluster, org)
configPath := paths.ConfigPath

Best Practices

1. Create one resolver instance per application (singleton pattern) 2. Enable caching for production use (default: enabled) 3. Use Resolve() when organization is known 4. Use ResolveWithFallback() when organization is unknown 5. Invalidate cache after creating or deleting clusters 6. Enable path validation only when necessary (performance impact) 7. Handle errors appropriately (don't ignore path resolution failures)

Testing

The package includes comprehensive tests:

  • Unit tests: resolver_test.go, strategies_test.go, cache_test.go
  • Thread safety tests: thread_safety_test.go
  • Benchmark tests: benchmark_test.go

Run tests:

go test ./internal/core/paths/...

Run benchmarks:

go test -bench=. ./internal/core/paths/

Package Structure

The package is organized into focused modules:

  • resolver.go: Main PathResolver implementation
  • types.go: Core types (ClusterPaths, ResolutionOptions)
  • strategies.go: Resolution strategies (OrgBasedStrategy)
  • cache.go: Thread-safe caching (PathCache)
  • doc.go: Package documentation (this file)

Future Enhancements

Planned improvements:

  • Additional resolution strategies (legacy, flat)
  • Persistent cache (disk-backed)
  • Path watching (filesystem notifications)
  • Metrics and observability
  • Custom validation rules

See Also

  • Design document: .kiro/specs/architectural-refactoring/design.md
  • Requirements: .kiro/specs/architectural-refactoring/requirements.md
  • Migration guide: .kiro/specs/architectural-refactoring/01-path-resolver.md
Example (AllPathTypes)

Example_allPathTypes demonstrates accessing all path types.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	clusterPaths, err := resolver.Resolve(context.Background(), "my-cluster", "myorg")
	if err != nil {
		log.Fatal(err)
	}

	// Access all available paths
	fmt.Println("Organization Dir:", clusterPaths.OrganizationDir)
	fmt.Println("GitOps Dir:", clusterPaths.GitOpsDir)
	fmt.Println("Cluster Dir:", clusterPaths.ClusterDir)
	fmt.Println("Applications Dir:", clusterPaths.ApplicationsDir)
	fmt.Println("Secrets Dir:", clusterPaths.SecretsDir)
	fmt.Println("SOPS Key Path:", clusterPaths.SOPSKeyPath)
	fmt.Println("SOPS Config Path:", clusterPaths.SOPSConfigPath)
	fmt.Println("Kubeconfig Path:", clusterPaths.KubeconfigPath)
	fmt.Println("Inventory Path:", clusterPaths.InventoryPath)
	fmt.Println("Venv Path:", clusterPaths.VenvPath)
	fmt.Println("Bin Path:", clusterPaths.BinPath)
	fmt.Println("Config Path:", clusterPaths.ConfigPath)
	fmt.Println("SSH Key Path:", clusterPaths.SSHKeyPath)
}
Example (BasicUsage)

Example_basicUsage demonstrates basic path resolution.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	// Create a resolver with default options
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	// Resolve paths for a cluster
	clusterPaths, err := resolver.Resolve(context.Background(), "my-cluster", "myorg")
	if err != nil {
		log.Fatal(err)
	}

	// Access resolved paths
	fmt.Println("Config path:", clusterPaths.ConfigPath)
	fmt.Println("Secrets dir:", clusterPaths.SecretsDir)
	fmt.Println("GitOps dir:", clusterPaths.GitOpsDir)
}
Example (BatchResolution)

Example_batchResolution demonstrates resolving paths for multiple clusters.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	clusters := []struct {
		name string
		org  string
	}{
		{"cluster1", "org1"},
		{"cluster2", "org1"},
		{"cluster3", "org2"},
	}

	// Resolve all clusters
	for _, cluster := range clusters {
		clusterPaths, err := resolver.Resolve(
			context.Background(),
			cluster.name,
			cluster.org,
		)
		if err != nil {
			log.Printf("Failed to resolve %s: %v", cluster.name, err)
			continue
		}

		fmt.Printf("Resolved %s: %s\n", cluster.name, clusterPaths.ConfigPath)
	}

	// Check cache efficiency
	stats := resolver.GetCacheStats()
	fmt.Printf("Cache hit rate: %.2f%%\n", stats.HitRate*100)
}
Example (CacheManagement)

Example_cacheManagement demonstrates cache operations.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	// First resolution (cache miss)
	_, err := resolver.Resolve(context.Background(), "my-cluster", "myorg")
	if err != nil {
		log.Fatal(err)
	}

	// Second resolution (cache hit)
	_, err = resolver.Resolve(context.Background(), "my-cluster", "myorg")
	if err != nil {
		log.Fatal(err)
	}

	// Get cache statistics
	stats := resolver.GetCacheStats()
	fmt.Printf("Cache hit rate: %.2f%%\n", stats.HitRate*100)
	fmt.Printf("Total entries: %d\n", stats.Entries)

	// Invalidate cache for a specific cluster
	resolver.InvalidateCache("my-cluster")

	// Clear all cache entries
	resolver.ClearCache()
}
Example (ConcurrentUsage)

Example_concurrentUsage demonstrates thread-safe concurrent usage.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	clusters := []string{"cluster1", "cluster2", "cluster3"}
	results := make(chan *paths.ClusterPaths, len(clusters))

	// Resolve paths concurrently
	for _, cluster := range clusters {
		go func(name string) {
			clusterPaths, err := resolver.Resolve(context.Background(), name, "myorg")
			if err != nil {
				log.Printf("Failed to resolve %s: %v", name, err)
				return
			}
			results <- clusterPaths
		}(cluster)
	}

	// Collect results
	for i := 0; i < len(clusters); i++ {
		clusterPaths := <-results
		fmt.Printf("Resolved: %s\n", clusterPaths.ClusterDir)
	}
}
Example (ContextCancellation)

Example_contextCancellation demonstrates context cancellation support.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	// Create a cancellable context
	ctx, cancel := context.WithCancel(context.Background())

	// Simulate cancellation
	go func() {
		// In real code, this would be triggered by user action or timeout
		cancel()
	}()

	// Resolve with cancellable context
	_, err := resolver.Resolve(ctx, "my-cluster", "myorg")
	if err != nil {
		if ctx.Err() == context.Canceled {
			fmt.Println("Resolution cancelled")
			return
		}
		log.Fatal(err)
	}
}
Example (CustomOptions)

Example_customOptions demonstrates using custom resolution options.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	// Configure custom options
	options := paths.ResolutionOptions{
		Organization:  "myorg",
		CacheResults:  true,
		ValidatePaths: true, // Enable path validation
	}

	resolver := paths.NewPathResolverWithOptions(
		"~/.config/opencenter/clusters",
		options,
	)

	clusterPaths, err := resolver.Resolve(context.Background(), "my-cluster", "myorg")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Resolved with validation:", clusterPaths.ConfigPath)
}
Example (DirectoryCreation)

Example_directoryCreation demonstrates creating cluster directories.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	// Create all necessary directories for a new cluster
	err := resolver.CreateClusterDirectories(
		context.Background(),
		"new-cluster",
		"myorg",
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Created all cluster directories")
}
Example (ErrorHandling)

Example_errorHandling demonstrates proper error handling.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	clusterPaths, err := resolver.Resolve(context.Background(), "my-cluster", "myorg")
	if err != nil {
		// Check for specific error types
		if os.IsNotExist(err) {
			fmt.Println("Cluster directory does not exist")
			return
		}

		// Check for validation errors
		if err.Error() == "invalid cluster name" {
			fmt.Println("Cluster name format is invalid")
			return
		}

		// Other errors
		log.Fatal(err)
	}

	fmt.Println("Successfully resolved:", clusterPaths.ConfigPath)
}
Example (FallbackResolution)

Example_fallbackResolution demonstrates fallback resolution when organization is unknown.

package main

import (
	"context"
	"fmt"
	"log"
	"path/filepath"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	// Search for cluster across all organizations
	clusterPaths, err := resolver.ResolveWithFallback(context.Background(), "my-cluster")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found cluster in organization: %s\n", filepath.Base(clusterPaths.OrganizationDir))
}
Example (MigrationFromLegacy)

Example_migrationFromLegacy demonstrates migrating from legacy path construction.

package main

import (
	"context"
	"fmt"
	"log"
	"path/filepath"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	// Old approach (duplicate logic, error-prone)
	oldConfigPath := func(baseDir, org, cluster string) string {
		return filepath.Join(
			baseDir,
			org,
			"infrastructure",
			"clusters",
			cluster,
			"."+cluster+"-config.yaml",
		)
	}

	// New approach (centralized, cached, validated)
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")
	clusterPaths, err := resolver.Resolve(context.Background(), "my-cluster", "myorg")
	if err != nil {
		log.Fatal(err)
	}

	// Compare paths
	oldPath := oldConfigPath("~/.config/opencenter/clusters", "myorg", "my-cluster")
	newPath := clusterPaths.ConfigPath

	fmt.Println("Old path:", oldPath)
	fmt.Println("New path:", newPath)
}
Example (OrganizationDetection)

Example_organizationDetection demonstrates detecting cluster organization.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	// Detect organization for an existing cluster
	org, err := resolver.GetOrganization(context.Background(), "my-cluster")
	if err != nil {
		log.Fatal(err)
	}

	if org == "" {
		fmt.Println("Cluster uses legacy structure")
	} else {
		fmt.Printf("Cluster belongs to organization: %s\n", org)
	}
}
Example (PathValidation)

Example_pathValidation demonstrates path validation.

package main

import (
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	// Validate a safe path
	err := resolver.ValidatePath("/home/user/.config/opencenter/clusters/myorg")
	if err != nil {
		fmt.Println("Invalid path:", err)
	} else {
		fmt.Println("Path is valid")
	}

	// Validate a path with traversal attempt
	err = resolver.ValidatePath("/home/user/../../../etc/passwd")
	if err != nil {
		fmt.Println("Invalid path:", err)
	}
}
Example (SingletonPattern)

Example_singletonPattern demonstrates the recommended singleton pattern.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	// Create a single resolver instance for the application
	var (
		resolverInstance *paths.PathResolver
		resolverOnce     = &struct{}{}
	)

	getResolver := func() *paths.PathResolver {
		// In real code, use sync.Once for thread-safe initialization
		if resolverInstance == nil {
			resolverInstance = paths.NewPathResolver("~/.config/opencenter/clusters")
		}
		return resolverInstance
	}

	// Use the singleton throughout the application
	resolver := getResolver()
	clusterPaths, err := resolver.Resolve(context.Background(), "my-cluster", "myorg")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Config path:", clusterPaths.ConfigPath)
	_ = resolverOnce // Suppress unused warning
}
Example (StructureDetection)

Example_structureDetection demonstrates detecting directory structure type.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/paths"
)

func main() {
	resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

	// Detect structure type for a cluster
	structureType, err := resolver.DetectStructureType(context.Background(), "my-cluster")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Structure type: %s\n", structureType)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExpandPath

func ExpandPath(path string) string

ExpandPath expands environment variables and tilde in a path. This is a public utility function that can be used by other packages.

func ParseClusterIdentifier

func ParseClusterIdentifier(identifier string, validateClusterName func(string) error) (organization string, clusterName string, err error)

ParseClusterIdentifier parses a cluster identifier in the format "organization/cluster" or a bare "cluster" name. If no organization is specified, "opencenter" is used as default.

Types

type CacheEntry

type CacheEntry struct {
	// Paths contains the resolved cluster paths
	Paths *ClusterPaths

	// Timestamp is when the entry was cached
	Timestamp time.Time

	// Organization is the organization used for resolution
	Organization string

	// Strategy is the strategy that resolved the paths
	Strategy string
}

CacheEntry represents a cached path resolution result.

type CacheStats

type CacheStats struct {
	// Entries is the current number of cached entries
	Entries int

	// Hits is the total number of cache hits
	Hits uint64

	// Misses is the total number of cache misses
	Misses uint64

	// HitRate is the cache hit rate (0.0 to 1.0)
	HitRate float64

	// MaxSize is the maximum number of entries
	MaxSize int

	// TTL is the time-to-live for cache entries
	TTL time.Duration
}

CacheStats contains cache statistics.

func (CacheStats) String

func (s CacheStats) String() string

String returns a string representation of cache statistics.

type ClusterPaths

type ClusterPaths struct {
	// OrganizationDir is the effective organization GitOps repository root.
	// Example: ~/.config/opencenter/clusters/gitops/<organization>
	OrganizationDir string

	// GitOpsDir is the root directory for GitOps manifests
	// Example: ~/.config/opencenter/clusters/gitops/<organization>
	GitOpsDir string

	// ClusterStateDir is the local state directory for this cluster.
	// Example: ~/.config/opencenter/clusters/state/<organization>/<cluster>
	ClusterStateDir string

	// ClusterDir is the directory containing cluster-specific infrastructure
	// Example: ~/.config/opencenter/clusters/gitops/<organization>/infrastructure/clusters/<cluster>
	ClusterDir string

	// ApplicationsDir is the directory containing cluster-specific application overlays
	// Example: ~/.config/opencenter/clusters/gitops/<organization>/applications/overlays/<cluster>
	ApplicationsDir string

	// SecretsDir is the local secrets directory for this cluster.
	// Example: ~/.config/opencenter/clusters/secrets/<organization>/<cluster>
	SecretsDir string

	// SOPSKeyPath is the path to the SOPS Age encryption key
	// Example: ~/.config/opencenter/clusters/secrets/<organization>/<cluster>/age/keys/<cluster>-key.txt
	SOPSKeyPath string

	// SOPSConfigPath is the path to the SOPS configuration file
	// Example: ~/.config/opencenter/clusters/gitops/<organization>/.sops.yaml
	SOPSConfigPath string

	// KubeconfigPath is the path to the cluster kubeconfig file
	// Example: ~/.config/opencenter/clusters/secrets/<organization>/<cluster>/kubernetes/kubeconfig.yaml
	KubeconfigPath string

	// InventoryPath is the path to the Ansible inventory directory
	// Example: ~/.config/opencenter/clusters/gitops/<organization>/infrastructure/clusters/<cluster>/inventory
	InventoryPath string

	// VenvPath is the path to the Python virtual environment
	// Example: ~/.config/opencenter/clusters/gitops/<organization>/infrastructure/clusters/<cluster>/venv
	VenvPath string

	// BinPath is the path to cluster-specific binaries
	// Example: ~/.config/opencenter/clusters/gitops/<organization>/infrastructure/clusters/<cluster>/.bin
	BinPath string

	// ConfigPath is the path to the cluster configuration file (blueprint)
	// Example: ~/.config/opencenter/clusters/blueprints/<organization>/<cluster>/<cluster>-config.yaml
	ConfigPath string

	// SSHKeyPath is the path to the cluster SSH key
	// Example: ~/.config/opencenter/clusters/secrets/<organization>/<cluster>/ssh/<cluster>-<env>-<region>
	SSHKeyPath string
}

ClusterPaths contains all organization-aware paths for a cluster. GitOps, local state, and secrets are separate zones. GitOps paths are safe to commit; state and secrets must never resolve into the GitOps worktree.

func (*ClusterPaths) Validate

func (p *ClusterPaths) Validate() error

Validate enforces that blueprints, secrets, and credentials cannot resolve into the GitOps worktree, including through pre-existing symlinked parents.

type LegacyLayoutError

type LegacyLayoutError struct {
	Path string
}

LegacyLayoutError indicates that a command encountered the old unsafe org-root Git repository layout. Only the explicit migration command should read from this layout.

func (*LegacyLayoutError) Error

func (e *LegacyLayoutError) Error() string

type OrgBasedStrategy

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

OrgBasedStrategy implements organization-based path resolution across the secure GitOps, cluster-state, and secrets zones.

func NewOrgBasedStrategy

func NewOrgBasedStrategy(baseDir string) *OrgBasedStrategy

NewOrgBasedStrategy creates a new organization-based strategy.

func NewOrgBasedStrategyWithRoots

func NewOrgBasedStrategyWithRoots(roots PathRoots) *OrgBasedStrategy

NewOrgBasedStrategyWithRoots creates a strategy with explicit zone roots.

func (*OrgBasedStrategy) CanResolve

func (s *OrgBasedStrategy) CanResolve(ctx context.Context, clusterName, organization string) (bool, error)

CanResolve checks if the cluster blueprint exists. Either the blueprint directory or its config file counts: init creates the directory before the first save, so the directory must stay resolvable between those steps. Listing is stricter (config file only, see ConfigurationManager.discoverClustersInBlueprints) so that bare blueprint directories left behind by destroy - sidecar files like .backup outlive the config file - never surface as phantom clusters.

func (*OrgBasedStrategy) Name

func (s *OrgBasedStrategy) Name() string

Name returns the strategy name.

func (*OrgBasedStrategy) Resolve

func (s *OrgBasedStrategy) Resolve(ctx context.Context, clusterName, organization string) (*ClusterPaths, error)

Resolve resolves paths using organization-based structure.

type PathCache

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

PathCache provides thread-safe caching for path resolution results.

func DefaultPathCache

func DefaultPathCache() *PathCache

DefaultPathCache creates a path cache with default settings. Default TTL: 5 minutes Default max size: 100 entries

func NewPathCache

func NewPathCache(ttl time.Duration, maxSize int) *PathCache

NewPathCache creates a new path cache with the given TTL and max size.

func (*PathCache) CleanupExpired

func (c *PathCache) CleanupExpired() int

CleanupExpired removes all expired cache entries.

func (*PathCache) Clear

func (c *PathCache) Clear()

Clear removes all cache entries.

func (*PathCache) Get

func (c *PathCache) Get(clusterName, organization string) *ClusterPaths

Get retrieves a cached path resolution result. Returns nil if the entry is not found or has expired.

func (*PathCache) Invalidate

func (c *PathCache) Invalidate(clusterName, organization string)

Invalidate removes a specific cache entry.

func (*PathCache) InvalidateCluster

func (c *PathCache) InvalidateCluster(clusterName string)

InvalidateCluster removes all cache entries for a cluster (across all organizations).

func (*PathCache) Set

func (c *PathCache) Set(clusterName, organization, strategy string, paths *ClusterPaths)

Set stores a path resolution result in the cache.

func (*PathCache) Size

func (c *PathCache) Size() int

Size returns the current number of cache entries.

func (*PathCache) Stats

func (c *PathCache) Stats() CacheStats

Stats returns cache statistics.

type PathResolver

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

PathResolver manages dynamic path resolution with organization support. It provides a single source of truth for all cluster path resolution, with caching and fallback strategies for backward compatibility.

PathResolver is thread-safe and can be used concurrently from multiple goroutines. It uses a read-write mutex to protect internal state and a thread-safe cache for resolved paths.

Example usage:

resolver := paths.NewPathResolver("~/.config/opencenter/clusters")
paths, err := resolver.Resolve(ctx, "my-cluster", "my-org")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Config path:", paths.ConfigPath)

For clusters without a known organization, use ResolveWithFallback:

paths, err := resolver.ResolveWithFallback(ctx, "my-cluster")

The resolver automatically caches results for performance. To invalidate:

resolver.InvalidateCache("my-cluster")

func NewPathResolver

func NewPathResolver(baseDir string) *PathResolver

NewPathResolver creates a new path resolver with the given base directory.

The base directory is the root directory containing organization subdirectories. Typically this is "~/.config/opencenter/clusters".

The resolver is created with default options:

  • Organization: "opencenter"
  • CacheResults: true
  • ValidatePaths: false

Example:

resolver := paths.NewPathResolver("~/.config/opencenter/clusters")

For custom options, use NewPathResolverWithOptions.

func NewPathResolverWithOptions

func NewPathResolverWithOptions(baseDir string, options ResolutionOptions) *PathResolver

NewPathResolverWithOptions creates a new path resolver with custom options.

This constructor allows fine-grained control over resolver behavior:

  • Organization: Default organization name when not specified
  • CacheResults: Enable/disable result caching
  • ValidatePaths: Enable/disable path validation (expensive)

Example:

opts := paths.ResolutionOptions{
    Organization: "my-company",
    CacheResults: true,
    ValidatePaths: true,
}
resolver := paths.NewPathResolverWithOptions("~/.config/opencenter/clusters", opts)

func NewPathResolverWithRoots

func NewPathResolverWithRoots(baseDir, blueprintsRoot, gitopsRoot, clusterStateRoot, secretsRoot string, options ResolutionOptions) *PathResolver

NewPathResolverWithRoots creates a resolver with explicit secure zone roots.

func (*PathResolver) ClearCache

func (r *PathResolver) ClearCache()

ClearCache clears all cached path resolutions.

Use this to force fresh resolution for all clusters, typically:

  • After bulk operations
  • During testing
  • When directory structure changes

Example:

resolver.ClearCache() // Clear all cached paths

func (*PathResolver) CreateClusterDirectories

func (r *PathResolver) CreateClusterDirectories(ctx context.Context, clusterName, organization string) error

CreateClusterDirectories creates all necessary directories for a cluster.

This method creates the complete directory structure required for a cluster:

  • Organization directory
  • Infrastructure/clusters/<cluster>
  • Applications/overlays/<cluster>
  • Secrets directories (age, ssh)
  • Inventory and bin directories

All directories are created with 0755 permissions. If ValidatePaths option is enabled, write permissions are verified for each directory.

Parameters:

  • ctx: Context for cancellation
  • clusterName: Name of the cluster
  • organization: Organization name (uses default if empty)

Returns:

  • error: Directory creation or validation failure

Example:

err := resolver.CreateClusterDirectories(ctx, "new-cluster", "my-org")
if err != nil {
    return fmt.Errorf("failed to create directories: %w", err)
}

func (*PathResolver) DetectStructureType

func (r *PathResolver) DetectStructureType(ctx context.Context, clusterName string) (StructureType, error)

DetectStructureType detects the directory structure type for a cluster.

func (*PathResolver) GetBaseDir

func (r *PathResolver) GetBaseDir() string

GetBaseDir returns the base directory for clusters.

func (*PathResolver) GetCacheStats

func (r *PathResolver) GetCacheStats() CacheStats

GetCacheStats returns cache statistics for monitoring and debugging.

Returns:

  • CacheStats: Hit rate, miss rate, and entry count

Example:

stats := resolver.GetCacheStats()
fmt.Printf("Cache hit rate: %.2f%%\n", stats.HitRate()*100)

func (*PathResolver) GetOptions

func (r *PathResolver) GetOptions() ResolutionOptions

GetOptions returns the current resolution options.

func (*PathResolver) GetOrganization

func (r *PathResolver) GetOrganization(ctx context.Context, clusterName string) (string, error)

GetOrganization determines the organization for a cluster by scanning the blueprints zone for the cluster's blueprint config file. A bare blueprint directory does not count as an existing cluster. Returns empty string if the cluster cannot be found in the secure layout.

func (*PathResolver) GetRoots

func (r *PathResolver) GetRoots() PathRoots

GetRoots returns the configured secure zone roots.

func (*PathResolver) GetStrategies

func (r *PathResolver) GetStrategies() []ResolutionStrategy

GetStrategies returns all registered resolution strategies.

func (*PathResolver) InvalidateCache

func (r *PathResolver) InvalidateCache(clusterName string)

InvalidateCache invalidates the cache for a specific cluster.

Call this method after:

  • Creating new cluster directories
  • Moving a cluster to a different organization
  • Modifying cluster structure

Example:

resolver.CreateClusterDirectories(ctx, "new-cluster", "my-org")
resolver.InvalidateCache("new-cluster") // Force fresh resolution

func (*PathResolver) Resolve

func (r *PathResolver) Resolve(ctx context.Context, clusterName, organization string) (*ClusterPaths, error)

Resolve resolves all paths for the given cluster and organization. This is the primary method for path resolution.

The method performs the following steps:

  1. Validates cluster name and organization name
  2. Checks cache for existing resolution (if caching enabled)
  3. Uses organization-based strategy to resolve paths
  4. Caches the result for future calls

Parameters:

  • ctx: Context for cancellation and timeouts
  • clusterName: Name of the cluster (must be valid DNS label)
  • organization: Organization name (uses default if empty)

Returns:

  • *ClusterPaths: Resolved paths for the cluster
  • error: Validation error or resolution failure

Example:

paths, err := resolver.Resolve(ctx, "prod-cluster", "acme-corp")
if err != nil {
    return fmt.Errorf("failed to resolve paths: %w", err)
}
// Use paths.ConfigPath, paths.SecretsDir, etc.

func (*PathResolver) ResolveWithFallback

func (r *PathResolver) ResolveWithFallback(ctx context.Context, clusterName string) (*ClusterPaths, error)

ResolveWithFallback resolves paths for a cluster without knowing its organization. It searches only the secure cluster-state zone. Legacy org-root layouts are not a compatibility path.

The search process:

  1. Checks cache first
  2. Scans all organization directories in baseDir
  3. Returns paths for the first matching cluster found
  4. Caches the result with empty organization key

Parameters:

  • ctx: Context for cancellation and timeouts
  • clusterName: Name of the cluster to find

Returns:

  • *ClusterPaths: Resolved paths for the cluster
  • error: Cluster not found or validation error

Example:

// When you don't know the organization
paths, err := resolver.ResolveWithFallback(ctx, "my-cluster")
if err != nil {
    return fmt.Errorf("cluster not found: %w", err)
}

func (*PathResolver) ValidatePath

func (r *PathResolver) ValidatePath(path string) error

ValidatePath validates that a path is safe and accessible.

Validation checks:

  • Path is not empty
  • No directory traversal attempts (..)
  • Path is absolute after expansion

Parameters:

  • path: Path to validate (can contain ~ and environment variables)

Returns:

  • error: Validation failure with specific reason

Example:

if err := resolver.ValidatePath("~/.config/opencenter"); err != nil {
    return fmt.Errorf("invalid path: %w", err)
}

type PathRoots

type PathRoots struct {
	ClustersDir     string
	BlueprintsDir   string
	GitOpsDir       string
	ClusterStateDir string
	SecretsDir      string
}

PathRoots contains the zone root directories used by PathResolver.

func DefaultPathRoots

func DefaultPathRoots(baseDir string) PathRoots

DefaultPathRoots derives secure zone roots from the historical clusters root.

type PathType

type PathType int

PathType represents the type of path being resolved.

const (
	// PathTypeConfig represents a cluster configuration file path
	PathTypeConfig PathType = iota

	// PathTypeSecrets represents a secrets directory path
	PathTypeSecrets

	// PathTypeGitOps represents a GitOps directory path
	PathTypeGitOps

	// PathTypeCluster represents a cluster directory path
	PathTypeCluster

	// PathTypeApplications represents an applications directory path
	PathTypeApplications

	// PathTypeSOPS represents a SOPS key or config path
	PathTypeSOPS

	// PathTypeKubeconfig represents a kubeconfig file path
	PathTypeKubeconfig

	// PathTypeInventory represents an Ansible inventory path
	PathTypeInventory

	// PathTypeSSH represents an SSH key path
	PathTypeSSH
)

func (PathType) String

func (pt PathType) String() string

String returns the string representation of a PathType.

type ResolutionOptions

type ResolutionOptions struct {
	// Organization is the organization name for the cluster
	// If empty, defaults to "opencenter"
	Organization string

	// CacheResults enables caching of resolved paths
	// Default: true
	CacheResults bool

	// ValidatePaths validates that resolved paths are safe and accessible
	// Default: false (validation is expensive)
	ValidatePaths bool
}

ResolutionOptions contains options for path resolution.

These options control the behavior of PathResolver:

  • Organization: Default organization when not specified in Resolve()
  • CacheResults: Enable caching for performance (recommended: true)
  • ValidatePaths: Validate write permissions (expensive, use in tests)

Example:

opts := paths.ResolutionOptions{
    Organization: "my-company",
    CacheResults: true,
    ValidatePaths: false, // Skip expensive validation
}

func DefaultResolutionOptions

func DefaultResolutionOptions() ResolutionOptions

DefaultResolutionOptions returns the default resolution options.

Defaults:

  • Organization: "opencenter"
  • CacheResults: true (caching enabled for performance)
  • ValidatePaths: false (validation disabled for performance)

Example:

opts := paths.DefaultResolutionOptions()
opts.Organization = "my-company" // Override default

type ResolutionStrategy

type ResolutionStrategy interface {
	// Name returns the name of the strategy
	//
	// The name should be unique and descriptive (e.g., "org-based", "legacy").
	// It's used for logging, debugging, and cache keys.
	Name() string

	// CanResolve checks if this strategy can resolve paths for the given cluster
	//
	// This method should be fast and only check for existence, not perform
	// full path resolution. It's called during strategy selection.
	//
	// Parameters:
	//   - ctx: Context for cancellation
	//   - clusterName: Name of the cluster
	//   - organization: Organization name (may be empty)
	//
	// Returns:
	//   - bool: true if this strategy can resolve the cluster
	//   - error: Check failure (not found is not an error)
	CanResolve(ctx context.Context, clusterName, organization string) (bool, error)

	// Resolve resolves all paths for the given cluster
	//
	// This method performs the actual path resolution and returns a complete
	// ClusterPaths structure with all paths populated.
	//
	// Parameters:
	//   - ctx: Context for cancellation
	//   - clusterName: Name of the cluster
	//   - organization: Organization name (may be empty)
	//
	// Returns:
	//   - *ClusterPaths: Resolved paths for the cluster
	//   - error: Resolution failure
	Resolve(ctx context.Context, clusterName, organization string) (*ClusterPaths, error)
}

ResolutionStrategy defines the interface for path resolution strategies. Currently only supports organization-based structure.

Implementations must:

  • Provide a unique strategy name
  • Detect if they can resolve paths for a cluster
  • Resolve all paths for a cluster

Thread Safety:

Implementations must be thread-safe and support concurrent calls to all methods.

Example implementation:

type MyStrategy struct {
    baseDir string
}

func (s *MyStrategy) Name() string {
    return "my-strategy"
}

func (s *MyStrategy) CanResolve(ctx context.Context, clusterName, organization string) (bool, error) {
    // Check if cluster exists in this strategy's structure
    clusterDir := filepath.Join(s.baseDir, organization, clusterName)
    _, err := os.Stat(clusterDir)
    return err == nil, nil
}

func (s *MyStrategy) Resolve(ctx context.Context, clusterName, organization string) (*ClusterPaths, error) {
    // Resolve all paths for the cluster
    return &ClusterPaths{
        ClusterDir: filepath.Join(s.baseDir, organization, clusterName),
        // ... other paths
    }, nil
}

type StructureType

type StructureType int

StructureType represents the type of directory structure.

const (
	// StructureTypeOrganization represents the organization-based structure
	StructureTypeOrganization StructureType = iota

	// StructureTypeUnknown represents an unknown structure type
	StructureTypeUnknown
)

func (StructureType) String

func (st StructureType) String() string

String returns the string representation of a StructureType.

Jump to

Keyboard shortcuts

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