Documentation
¶
Overview ¶
Package gitops provides functionality for managing GitOps templates.
This package is responsible for copying and rendering embedded templates into the target GitOps repository. It uses Go's `embed` package to include the templates in the binary.
When to use ¶
This package is used internally by opencenter to set up the GitOps repository for a cluster. It is invoked as part of the `cluster generate` command.
Index ¶
- Constants
- Variables
- func CopyBase(cfg v2.Config, render bool) error
- func CopyBaseAtomic(cfg v2.Config, render bool, workspace *GitOpsWorkspace) error
- func GitRepositoryURLVariants(repositoryURL string) (tokenURL, sshURL string, err error)
- func IsGitOpsInitialized(gitDir string) (bool, error)
- func IsServiceDisabled(serviceCfg any) bool
- func IsServiceExternal(serviceCfg any) bool
- func RenderClusterApps(cfg v2.Config) error
- func RenderClusterAppsAtomic(cfg v2.Config, workspace *GitOpsWorkspace) error
- func RenderClusterAppsWithEncryption(ctx context.Context, cfg v2.Config, encrypt OverlayEncryptor) error
- func RenderClusterFluxBridge(cfg v2.Config) error
- func RenderClusterFluxBridgeAtomic(cfg v2.Config, workspace *GitOpsWorkspace) error
- func RenderInfrastructureCluster(cfg v2.Config) error
- func RenderInfrastructureClusterAtomic(cfg v2.Config, workspace *GitOpsWorkspace) error
- func RenderSingleService(cfg v2.Config, serviceName string, isManaged bool) error
- func RenderSingleServiceWithEncryption(ctx context.Context, cfg v2.Config, serviceName string, isManaged bool, ...) error
- func RenderSourceAuthBlock(params SourceAuthParams) string
- func ShouldRenderService(serviceCfg any) bool
- type ActionDiagnostic
- type AdoptionMode
- type AdoptionSettings
- type AtomicWriter
- func (aw *AtomicWriter) CopyFile(srcPath, destRelativePath string, perm os.FileMode) error
- func (aw *AtomicWriter) IsDryRun() bool
- func (aw *AtomicWriter) MkdirAll(relativePath string, perm os.FileMode) error
- func (aw *AtomicWriter) RemoveFile(relativePath string) error
- func (aw *AtomicWriter) SetStage(stageName string)
- func (aw *AtomicWriter) WriteFile(relativePath string, data []byte, perm os.FileMode) error
- func (aw *AtomicWriter) WriteFileString(relativePath string, content string, perm os.FileMode) error
- type DefaultWorkspaceManager
- func (m *DefaultWorkspaceManager) CleanupOrphanedWorkspaces(ctx context.Context) error
- func (m *DefaultWorkspaceManager) CleanupWorkspace(ctx context.Context, workspace *GitOpsWorkspace) error
- func (m *DefaultWorkspaceManager) CreateWorkspace(ctx context.Context, cfg v2.Config) (*GitOpsWorkspace, error)
- func (m *DefaultWorkspaceManager) GetActiveWorkspaceCount() int
- func (m *DefaultWorkspaceManager) GetWorkspace(ctx context.Context, workspaceID string) (*GitOpsWorkspace, error)
- func (m *DefaultWorkspaceManager) ListActiveWorkspaces() []string
- func (m *DefaultWorkspaceManager) Shutdown(ctx context.Context) error
- type DescriptorDecision
- type DryRunAtomicWriter
- func (w *DryRunAtomicWriter) Commit() error
- func (w *DryRunAtomicWriter) GetWorkspace() *DryRunWorkspace
- func (w *DryRunAtomicWriter) MkdirAll(relativePath string, mode os.FileMode) error
- func (w *DryRunAtomicWriter) Remove(relativePath string) error
- func (w *DryRunAtomicWriter) RemoveAll(relativePath string) error
- func (w *DryRunAtomicWriter) Rollback() error
- func (w *DryRunAtomicWriter) SetStage(stageName string)
- func (w *DryRunAtomicWriter) WriteFile(relativePath string, content []byte, mode os.FileMode) error
- func (w *DryRunAtomicWriter) WriteFileString(relativePath string, content string, mode os.FileMode) error
- type DryRunAtomicWriterAdapter
- func (a *DryRunAtomicWriterAdapter) Commit() error
- func (a *DryRunAtomicWriterAdapter) GetDryRunWorkspace() *DryRunWorkspace
- func (a *DryRunAtomicWriterAdapter) IsDryRun() bool
- func (a *DryRunAtomicWriterAdapter) MkdirAll(relativePath string, mode os.FileMode) error
- func (a *DryRunAtomicWriterAdapter) Remove(relativePath string) error
- func (a *DryRunAtomicWriterAdapter) RemoveAll(relativePath string) error
- func (a *DryRunAtomicWriterAdapter) Rollback() error
- func (a *DryRunAtomicWriterAdapter) String() string
- func (a *DryRunAtomicWriterAdapter) WriteFile(relativePath string, content []byte, mode os.FileMode) error
- func (a *DryRunAtomicWriterAdapter) WriteFileString(relativePath string, content string, mode os.FileMode) error
- type DryRunFile
- type DryRunOperation
- type DryRunSummary
- type DryRunWorkspace
- func (w *DryRunWorkspace) CreateCheckpoint(checkpointID string) (WorkspaceCheckpoint, error)
- func (w *DryRunWorkspace) CreatedAt() time.Time
- func (w *DryRunWorkspace) DeleteCheckpoint(checkpointID string) error
- func (w *DryRunWorkspace) Exists(relativePath string) bool
- func (w *DryRunWorkspace) GenerateSummary() DryRunSummary
- func (w *DryRunWorkspace) GetDirectories() []string
- func (w *DryRunWorkspace) GetDirectoryCount() int
- func (w *DryRunWorkspace) GetFileCount() int
- func (w *DryRunWorkspace) GetFiles() map[string]DryRunFile
- func (w *DryRunWorkspace) GetMetadata(key string) (interface{}, bool)
- func (w *DryRunWorkspace) GetOperationCount() int
- func (w *DryRunWorkspace) GetOperations() []DryRunOperation
- func (w *DryRunWorkspace) GetPath(relativePath string) string
- func (w *DryRunWorkspace) GetTempPath(relativePath string) string
- func (w *DryRunWorkspace) GetTotalSize() int64
- func (w *DryRunWorkspace) LastModified() time.Time
- func (w *DryRunWorkspace) RecordOperation(op DryRunOperation)
- func (w *DryRunWorkspace) RestoreCheckpoint(checkpointID string) error
- func (w *DryRunWorkspace) SetMetadata(key string, value interface{})
- func (w *DryRunWorkspace) UpdateModifiedTime()
- type DryRunWorkspaceManager
- func (m *DryRunWorkspaceManager) CleanupWorkspace(ctx context.Context, workspace *GitOpsWorkspace) error
- func (m *DryRunWorkspaceManager) CreateWorkspace(ctx context.Context, cfg v2.Config) (*GitOpsWorkspace, error)
- func (m *DryRunWorkspaceManager) GetDryRunWorkspace(workspaceID string) (*DryRunWorkspace, error)
- func (m *DryRunWorkspaceManager) GetWorkspace(ctx context.Context, workspaceID string) (*GitOpsWorkspace, error)
- type FluxKustomizationPatchesRenderer
- type GeneratedFileInfo
- type GeneratedManifest
- type GenerationOptions
- type GenerationPlan
- type GenerationResult
- type GenerationStage
- type GitOpsGenerator
- type GitOpsWorkspace
- func (w *GitOpsWorkspace) CreateCheckpoint(checkpointID string) (*WorkspaceCheckpoint, error)
- func (w *GitOpsWorkspace) CreatedAt() time.Time
- func (w *GitOpsWorkspace) DeleteCheckpoint(checkpointID string) error
- func (w *GitOpsWorkspace) Exists(relativePath string) bool
- func (w *GitOpsWorkspace) GetCheckpoint(checkpointID string) (*WorkspaceCheckpoint, error)
- func (w *GitOpsWorkspace) GetFileCount() int
- func (w *GitOpsWorkspace) GetMetadata(key string) (interface{}, bool)
- func (w *GitOpsWorkspace) GetPath(relativePath string) string
- func (w *GitOpsWorkspace) GetTempPath(relativePath string) string
- func (w *GitOpsWorkspace) LastModified() time.Time
- func (w *GitOpsWorkspace) ListCheckpoints() []string
- func (w *GitOpsWorkspace) RestoreCheckpoint(checkpointID string) error
- func (w *GitOpsWorkspace) SetMetadata(key string, value interface{})
- func (w *GitOpsWorkspace) UpdateModifiedTime()
- type KustomizationRenderer
- type ManifestValidator
- type OperationType
- type OverlayEncryptor
- type OverlayFilesRenderer
- type OverrideValuesRenderer
- type PipelineGenerator
- func (pg *PipelineGenerator) Generate(ctx context.Context, cfg v2.Config) error
- func (pg *PipelineGenerator) GenerateDryRun(ctx context.Context, cfg v2.Config) (*GenerationPlan, error)
- func (pg *PipelineGenerator) GetCompletedStages() []string
- func (pg *PipelineGenerator) GetCurrentStage() string
- func (pg *PipelineGenerator) GetTotalStages() int
- func (pg *PipelineGenerator) GetWorkspace() *GitOpsWorkspace
- func (pg *PipelineGenerator) Rollback(ctx context.Context, checkpointID string) error
- func (pg *PipelineGenerator) SetProgressCallback(callback ProgressCallback)
- type ProgressCallback
- type ProgressReporter
- type ProgressReporterOptions
- type PromoteOptions
- type PromoteResult
- func GenerateClusterTree(ctx context.Context, cfg v2.Config, opts StagedGenerationOptions) (*PromoteResult, int, error)
- func PlanClusterAppsPromotion(cfg v2.Config) (*PromoteResult, error)
- func PlanClusterAppsPromotionWithOptions(cfg v2.Config, opts PromoteOptions) (*PromoteResult, error)
- func RenderClusterAppsWithEncryptionResult(ctx context.Context, cfg v2.Config, encrypt OverlayEncryptor, ...) (*PromoteResult, error)
- func RenderSingleServiceWithEncryptionResult(ctx context.Context, cfg v2.Config, serviceName string, isManaged bool, ...) (*PromoteResult, error)
- type RenderCatalog
- func (c RenderCatalog) Lookup(serviceName string) (RenderSpec, bool)
- func (c RenderCatalog) Validate() error
- func (c RenderCatalog) ValidateAgainstDescriptors(registry *descriptorcfg.Registry) error
- func (c RenderCatalog) ValidateConfigOwnership(cfg v2.Config, registry *descriptorcfg.Registry) error
- type RenderDiagnostics
- type RenderSpec
- type SecretScanFinding
- type SecretScanOptions
- type SimpleProgressReporter
- type SourceAuthParams
- type StagePlan
- type StagedGenerationOptions
- type Transaction
- type WorkspaceCheckpoint
- type WorkspaceManager
Examples ¶
Constants ¶
const ( AdoptionModeManaged = services.AdoptionModeManaged AdoptionModeExternal = services.AdoptionModeExternal AdoptionModeSync = services.AdoptionModeSync AdoptionModeDeferred = services.AdoptionModeDeferred AdoptionModeTakeover = services.AdoptionModeTakeover )
Re-export adoption mode constants for convenience.
const CustomDirName = "custom"
const GeneratedManifestFile = ".opencenter-generated.json"
GeneratedManifestFile is a legacy sentinel. Legacy manifests are refused; ownership is recorded only in the v2 ledgers below.
Variables ¶
var DeployArtifactIgnorePatterns = []string{
"infrastructure/clusters/*/inventory/",
"infrastructure/clusters/*/venv/",
"infrastructure/clusters/*/kubespray/",
"infrastructure/clusters/*/.bin/",
"infrastructure/clusters/*/kubespray-outputs.json",
"infrastructure/clusters/*/ansible-local-tmp/",
"infrastructure/clusters/*/.kubeconfig.fetch.tmp",
"infrastructure/clusters/*/.terraform/",
"infrastructure/clusters/*/.terraform.lock.hcl",
}
DeployArtifactIgnorePatterns are the root .gitignore exclusions that keep deploy-time Kubespray/OpenTofu outputs (written into the cluster dir, which doubles as the cluster state zone) out of the repository. `cluster init` appends them to an existing .gitignore; a repository created before a pattern existed must not stay dirty forever, so promotion heals the tracked hygiene file the same way (see trackedHygieneHealable).
var Files embed.FS
Files holds the embedded contents of the gitops-base-dir and templates directories.
The go:embed directive includes all files under the gitops-base-dir and templates directories. The embedded filesystem can be accessed using Files.ReadFile or Files.Open. See copy.go for usage examples.
Functions ¶
func CopyBase ¶
CopyBase copies or renders embedded files from gitops-base-dir into the target directory specified by cfg.GitDir().
Files ending with .tpl are always rendered with the cluster configuration bound under the dot context and the .tpl suffix stripped from the destination path. When render is true, .tmpl files are rendered using the same rules. When render is false, .tmpl files are copied verbatim (extension preserved) to allow manual customization workflows.
Non-template files are copied as-is. The directory structure under gitops-base-dir/ is preserved. The target directory is created if it does not exist.
Inputs:
- cfg: The cluster configuration.
- render: If true, both .tpl and .tmpl files render; if false, only .tpl files render while .tmpl files are copied as-is for manual editing.
Outputs:
- error: An error if one occurred during the copy or render operation.
func CopyBaseAtomic ¶
func CopyBaseAtomic(cfg v2.Config, render bool, workspace *GitOpsWorkspace) error
CopyBaseAtomic copies or renders embedded files from gitops-base-dir into the workspace using atomic file operations to prevent partial writes.
This is the workspace-aware version of CopyBase that ensures all file operations are atomic and can be rolled back if needed.
Files ending with .tpl are always rendered with the cluster configuration bound under the dot context and the .tpl suffix stripped from the destination path. When render is true, .tmpl files are rendered using the same rules. When render is false, .tmpl files are copied verbatim (extension preserved) to allow manual customization workflows.
Non-template files are copied as-is. The directory structure under gitops-base-dir/ is preserved.
Inputs:
- cfg: The cluster configuration.
- render: If true, both .tpl and .tmpl files render; if false, only .tpl files render while .tmpl files are copied as-is for manual editing.
- workspace: The GitOps workspace for atomic operations.
Outputs:
- error: An error if one occurred during the copy or render operation.
func GitRepositoryURLVariants ¶
GitRepositoryURLVariants converts a Git repository URL to equivalent HTTPS (token) and ssh:// (SSH key) URLs while preserving its host and path. It accepts https://, ssh://, and scp-style git@host:path input.
func IsGitOpsInitialized ¶
IsGitOpsInitialized checks if a GitOps directory has already been initialized by looking for marker files that indicate a previous setup.
It checks for the presence of:
- README.md: Base GitOps structure file
- .git directory: Git repository initialization
Returns true if the directory appears to be initialized, false otherwise.
func IsServiceDisabled ¶
IsServiceDisabled checks if a service configuration has Enabled set to false. It uses reflection to access the Enabled field since the service config is an interface{}.
func IsServiceExternal ¶
IsServiceExternal returns true if the service has adoption_mode: external. External services are not rendered by Flux at all.
func RenderClusterApps ¶
RenderClusterApps renders cluster-apps-base and promotes it to the final target. It is the raw rendering primitive; production callers that can materialize credentials must use RenderClusterAppsWithEncryption.
func RenderClusterAppsAtomic ¶
func RenderClusterAppsAtomic(cfg v2.Config, workspace *GitOpsWorkspace) error
RenderClusterAppsAtomic renders cluster-apps-base template to applications/overlays/<cluster-name>/ using atomic file operations to prevent partial writes.
This is the workspace-aware version of RenderClusterApps that ensures all file operations are atomic and can be rolled back if needed.
func RenderClusterAppsWithEncryption ¶
func RenderClusterAppsWithEncryption(ctx context.Context, cfg v2.Config, encrypt OverlayEncryptor) error
RenderClusterAppsWithEncryption renders cluster-apps-base into a temporary workspace, encrypts credential-bearing files, and only then promotes it to the final target.
func RenderClusterFluxBridge ¶
RenderClusterFluxBridge renders the bridge Flux Kustomization into clusters/<cluster-name>/services.yaml. Flux's own `flux bootstrap` writes clusters/<cluster-name>/flux-system/, but nothing there references the per-service Flux Kustomizations under applications/overlays/<cluster-name>/ services/fluxcd. Without this bridge, Flux reconciles only its own source-controller and stops.
No top-level kustomization.yaml is emitted here - Flux's kustomize-controller auto-generates a kustomization.yaml at reconcile time when none is present, aggregating every YAML at the path (including files under flux-system/ and this services.yaml).
This function never touches clusters/<cluster-name>/flux-system/ (owned by flux bootstrap).
func RenderClusterFluxBridgeAtomic ¶
func RenderClusterFluxBridgeAtomic(cfg v2.Config, workspace *GitOpsWorkspace) error
RenderClusterFluxBridgeAtomic is the workspace-aware version of RenderClusterFluxBridge. See RenderClusterFluxBridge for behaviour.
func RenderInfrastructureCluster ¶
RenderInfrastructureCluster renders infrastructure-cluster-template to infrastructure/clusters/<cluster-name>/ This function processes all files in the infrastructure-cluster-template directory, renders .tmpl and .tpl files with the cluster configuration, and copies others as-is. It selects the appropriate main.tf template based on the infrastructure provider type.
func RenderInfrastructureClusterAtomic ¶
func RenderInfrastructureClusterAtomic(cfg v2.Config, workspace *GitOpsWorkspace) error
RenderInfrastructureClusterAtomic renders infrastructure-cluster-template to infrastructure/clusters/<cluster-name>/ using atomic file operations to prevent partial writes.
This is the workspace-aware version of RenderInfrastructureCluster that ensures all file operations are atomic and can be rolled back if needed.
func RenderSingleService ¶
func RenderSingleServiceWithEncryption ¶
func RenderSingleServiceWithEncryption(ctx context.Context, cfg v2.Config, serviceName string, isManaged bool, encrypt OverlayEncryptor) error
RenderSingleServiceWithEncryption renders a service into a temporary workspace and promotes its scoped outputs.
func RenderSourceAuthBlock ¶
func RenderSourceAuthBlock(params SourceAuthParams) string
RenderSourceAuthBlock renders the URL, ref, and (unless Anonymous) Secret reference for the selected Git authentication method, followed by a fully commented-out equivalent for the alternative method. The auth method is explicit rather than inferred from a repository URL.
func ShouldRenderService ¶
ShouldRenderService returns true if the service should have manifests rendered. Returns false for disabled services or services with adoption_mode: external.
Types ¶
type ActionDiagnostic ¶
type ActionDiagnostic struct {
Owner string `json:"owner"`
Output string `json:"output"`
Rendered bool `json:"rendered"`
}
ActionDiagnostic records one file action produced by the renderer.
type AdoptionMode ¶
type AdoptionMode = services.AdoptionMode
AdoptionMode mirrors services.AdoptionMode for use in gitops package.
func GetAdoptionMode ¶
func GetAdoptionMode(serviceCfg any) AdoptionMode
GetAdoptionMode extracts the adoption mode from a service configuration. It uses reflection to access the AdoptionMode field since service configs are stored as interface{} in the ServiceMap. Returns AdoptionModeManaged if the field is not found or empty (default behavior).
type AdoptionSettings ¶
type AdoptionSettings struct {
// Force determines if Flux should overwrite existing resource fields.
// false for sync mode, true otherwise.
Force bool
// Suspend determines if the Kustomization should be suspended.
// true for deferred mode, false otherwise.
Suspend bool
}
AdoptionSettings contains the Flux Kustomization settings derived from adoption mode.
func GetAdoptionSettings ¶
func GetAdoptionSettings(mode AdoptionMode) AdoptionSettings
GetAdoptionSettings returns the Flux Kustomization settings for a given adoption mode.
func GetServiceAdoptionSettings ¶
func GetServiceAdoptionSettings(serviceCfg any) AdoptionSettings
GetServiceAdoptionSettings extracts adoption mode from a service config and returns settings.
type AtomicWriter ¶
type AtomicWriter struct {
// contains filtered or unexported fields
}
AtomicWriter provides atomic file write operations to prevent partial writes. Files are written to a temporary location and then atomically moved to the final destination. In dry-run mode, operations are recorded without making filesystem changes.
func NewAtomicWriter ¶
func NewAtomicWriter(workspace *GitOpsWorkspace) *AtomicWriter
NewAtomicWriter creates a new atomic writer for the given workspace. If the workspace is in dry-run mode, it returns a dry-run writer that records operations without making filesystem changes.
func (*AtomicWriter) CopyFile ¶
func (aw *AtomicWriter) CopyFile(srcPath, destRelativePath string, perm os.FileMode) error
CopyFile copies a file atomically within the workspace. The source file is read and then written atomically to the destination.
func (*AtomicWriter) IsDryRun ¶
func (aw *AtomicWriter) IsDryRun() bool
IsDryRun returns true if this writer is in dry-run mode.
func (*AtomicWriter) MkdirAll ¶
func (aw *AtomicWriter) MkdirAll(relativePath string, perm os.FileMode) error
MkdirAll creates a directory and all necessary parent directories. In dry-run mode, the operation is recorded without making filesystem changes.
func (*AtomicWriter) RemoveFile ¶
func (aw *AtomicWriter) RemoveFile(relativePath string) error
RemoveFile removes a file from the workspace. This operation is not atomic but is included for completeness. In dry-run mode, the operation is recorded without making filesystem changes.
func (*AtomicWriter) SetStage ¶
func (aw *AtomicWriter) SetStage(stageName string)
SetStage sets the current stage name for dry-run operation tracking. This is used to associate operations with the stage that performed them.
func (*AtomicWriter) WriteFile ¶
WriteFile writes data to a file atomically within the workspace. The file is first written to a temporary location and then moved to the final path. This ensures that the file is either fully written or not present at all. In dry-run mode, the operation is recorded without making filesystem changes.
func (*AtomicWriter) WriteFileString ¶
func (aw *AtomicWriter) WriteFileString(relativePath string, content string, perm os.FileMode) error
WriteFileString writes a string to a file atomically within the workspace. In dry-run mode, the operation is recorded without making filesystem changes.
type DefaultWorkspaceManager ¶
type DefaultWorkspaceManager struct {
// contains filtered or unexported fields
}
DefaultWorkspaceManager implements WorkspaceManager with standard filesystem operations.
func (*DefaultWorkspaceManager) CleanupOrphanedWorkspaces ¶
func (m *DefaultWorkspaceManager) CleanupOrphanedWorkspaces(ctx context.Context) error
CleanupOrphanedWorkspaces scans the workspace directory and removes any workspace directories that are not tracked in the manager's registry. This helps recover from crashes or improper shutdowns.
func (*DefaultWorkspaceManager) CleanupWorkspace ¶
func (m *DefaultWorkspaceManager) CleanupWorkspace(ctx context.Context, workspace *GitOpsWorkspace) error
CleanupWorkspace removes a workspace and all its resources. This operation is irreversible and should be called when generation is complete or failed.
func (*DefaultWorkspaceManager) CreateWorkspace ¶
func (m *DefaultWorkspaceManager) CreateWorkspace(ctx context.Context, cfg v2.Config) (*GitOpsWorkspace, error)
CreateWorkspace creates a new isolated workspace for GitOps generation. The workspace provides an isolated environment with its own directory structure.
func (*DefaultWorkspaceManager) GetActiveWorkspaceCount ¶
func (m *DefaultWorkspaceManager) GetActiveWorkspaceCount() int
GetActiveWorkspaceCount returns the number of currently active workspaces.
func (*DefaultWorkspaceManager) GetWorkspace ¶
func (m *DefaultWorkspaceManager) GetWorkspace(ctx context.Context, workspaceID string) (*GitOpsWorkspace, error)
GetWorkspace retrieves an existing workspace by ID.
func (*DefaultWorkspaceManager) ListActiveWorkspaces ¶
func (m *DefaultWorkspaceManager) ListActiveWorkspaces() []string
ListActiveWorkspaces returns a list of all active workspace IDs.
type DescriptorDecision ¶
type DescriptorDecision struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Reason string `json:"reason"`
}
DescriptorDecision records the evaluation result for one descriptor.
type DryRunAtomicWriter ¶
type DryRunAtomicWriter struct {
// contains filtered or unexported fields
}
DryRunAtomicWriter is an atomic writer that records operations without making filesystem changes. It provides the same interface as AtomicWriter but operates in dry-run mode.
func NewDryRunAtomicWriter ¶
func NewDryRunAtomicWriter(workspace *DryRunWorkspace, stageName string) *DryRunAtomicWriter
NewDryRunAtomicWriter creates a new dry-run atomic writer.
func (*DryRunAtomicWriter) Commit ¶
func (w *DryRunAtomicWriter) Commit() error
Commit is a no-op in dry-run mode since no actual operations are performed.
func (*DryRunAtomicWriter) GetWorkspace ¶
func (w *DryRunAtomicWriter) GetWorkspace() *DryRunWorkspace
GetWorkspace returns the dry-run workspace.
func (*DryRunAtomicWriter) MkdirAll ¶
func (w *DryRunAtomicWriter) MkdirAll(relativePath string, mode os.FileMode) error
MkdirAll records a directory creation operation without actually creating directories.
func (*DryRunAtomicWriter) Remove ¶
func (w *DryRunAtomicWriter) Remove(relativePath string) error
Remove records a file removal operation without actually removing files.
func (*DryRunAtomicWriter) RemoveAll ¶
func (w *DryRunAtomicWriter) RemoveAll(relativePath string) error
RemoveAll records a directory removal operation without actually removing directories.
func (*DryRunAtomicWriter) Rollback ¶
func (w *DryRunAtomicWriter) Rollback() error
Rollback is a no-op in dry-run mode since no actual operations are performed.
func (*DryRunAtomicWriter) SetStage ¶
func (w *DryRunAtomicWriter) SetStage(stageName string)
SetStage sets the current stage name for operation tracking.
func (*DryRunAtomicWriter) WriteFile ¶
WriteFile records a file write operation without actually writing to disk.
func (*DryRunAtomicWriter) WriteFileString ¶
func (w *DryRunAtomicWriter) WriteFileString(relativePath string, content string, mode os.FileMode) error
WriteFileString records a file write operation without actually writing to disk.
type DryRunAtomicWriterAdapter ¶
type DryRunAtomicWriterAdapter struct {
// contains filtered or unexported fields
}
DryRunAtomicWriterAdapter adapts a DryRunAtomicWriter to work with code expecting AtomicWriter. This allows stages to work in both normal and dry-run modes without modification.
func NewDryRunAtomicWriterAdapter ¶
func NewDryRunAtomicWriterAdapter(workspace *DryRunWorkspace, stageName string) *DryRunAtomicWriterAdapter
NewDryRunAtomicWriterAdapter creates a new adapter.
func (*DryRunAtomicWriterAdapter) Commit ¶
func (a *DryRunAtomicWriterAdapter) Commit() error
Commit is a no-op in dry-run mode.
func (*DryRunAtomicWriterAdapter) GetDryRunWorkspace ¶
func (a *DryRunAtomicWriterAdapter) GetDryRunWorkspace() *DryRunWorkspace
GetDryRunWorkspace returns the underlying dry-run workspace.
func (*DryRunAtomicWriterAdapter) IsDryRun ¶
func (a *DryRunAtomicWriterAdapter) IsDryRun() bool
IsDryRun returns true to indicate this is a dry-run writer.
func (*DryRunAtomicWriterAdapter) MkdirAll ¶
func (a *DryRunAtomicWriterAdapter) MkdirAll(relativePath string, mode os.FileMode) error
MkdirAll delegates to the dry-run writer.
func (*DryRunAtomicWriterAdapter) Remove ¶
func (a *DryRunAtomicWriterAdapter) Remove(relativePath string) error
Remove delegates to the dry-run writer.
func (*DryRunAtomicWriterAdapter) RemoveAll ¶
func (a *DryRunAtomicWriterAdapter) RemoveAll(relativePath string) error
RemoveAll delegates to the dry-run writer.
func (*DryRunAtomicWriterAdapter) Rollback ¶
func (a *DryRunAtomicWriterAdapter) Rollback() error
Rollback is a no-op in dry-run mode.
func (*DryRunAtomicWriterAdapter) String ¶
func (a *DryRunAtomicWriterAdapter) String() string
String returns a string representation of the adapter.
func (*DryRunAtomicWriterAdapter) WriteFile ¶
func (a *DryRunAtomicWriterAdapter) WriteFile(relativePath string, content []byte, mode os.FileMode) error
WriteFile delegates to the dry-run writer.
func (*DryRunAtomicWriterAdapter) WriteFileString ¶
func (a *DryRunAtomicWriterAdapter) WriteFileString(relativePath string, content string, mode os.FileMode) error
WriteFileString delegates to the dry-run writer.
type DryRunFile ¶
type DryRunFile struct {
Path string
Content string
Mode os.FileMode
CreatedBy string // Stage name
Size int64
}
DryRunFile represents a file that would be created.
type DryRunOperation ¶
type DryRunOperation struct {
Type OperationType
Path string
Content string
Mode os.FileMode
Timestamp time.Time
Stage string
}
DryRunOperation represents a single operation that would be performed.
type DryRunSummary ¶
type DryRunSummary struct {
WorkspaceID string
TotalOperations int
FilesCreated int
DirectoriesCreated int
TotalSize int64
Operations []DryRunOperation
Files map[string]DryRunFile
Directories []string
}
DryRunSummary provides a summary of dry-run operations.
type DryRunWorkspace ¶
type DryRunWorkspace struct {
// ID is a unique identifier for this workspace
ID string
// RootDir is the simulated root directory (not actually created)
RootDir string
// TempDir is the simulated temporary directory (not actually created)
TempDir string
// Config is the cluster configuration associated with this workspace
Config v2.Config
// Metadata stores arbitrary key-value pairs for workspace context
Metadata map[string]interface{}
// Checkpoints stores workspace checkpoints (simulated)
Checkpoints map[string]WorkspaceCheckpoint
// contains filtered or unexported fields
}
DryRunWorkspace is a workspace that tracks operations without making filesystem changes. It provides an accurate preview of what would be generated while ensuring no actual files or directories are created.
func NewDryRunWorkspace ¶
func NewDryRunWorkspace(cfg v2.Config) *DryRunWorkspace
NewDryRunWorkspace creates a new dry-run workspace that simulates operations.
func (*DryRunWorkspace) CreateCheckpoint ¶
func (w *DryRunWorkspace) CreateCheckpoint(checkpointID string) (WorkspaceCheckpoint, error)
CreateCheckpoint creates a simulated checkpoint.
func (*DryRunWorkspace) CreatedAt ¶
func (w *DryRunWorkspace) CreatedAt() time.Time
CreatedAt returns the workspace creation time.
func (*DryRunWorkspace) DeleteCheckpoint ¶
func (w *DryRunWorkspace) DeleteCheckpoint(checkpointID string) error
DeleteCheckpoint removes a simulated checkpoint.
func (*DryRunWorkspace) Exists ¶
func (w *DryRunWorkspace) Exists(relativePath string) bool
Exists checks if a file or directory would exist in the simulated workspace.
func (*DryRunWorkspace) GenerateSummary ¶
func (w *DryRunWorkspace) GenerateSummary() DryRunSummary
GenerateSummary creates a summary of what would be generated.
func (*DryRunWorkspace) GetDirectories ¶
func (w *DryRunWorkspace) GetDirectories() []string
GetDirectories returns all directories that would be created.
func (*DryRunWorkspace) GetDirectoryCount ¶
func (w *DryRunWorkspace) GetDirectoryCount() int
GetDirectoryCount returns the number of directories that would be created.
func (*DryRunWorkspace) GetFileCount ¶
func (w *DryRunWorkspace) GetFileCount() int
GetFileCount returns the number of files that would be created.
func (*DryRunWorkspace) GetFiles ¶
func (w *DryRunWorkspace) GetFiles() map[string]DryRunFile
GetFiles returns all files that would be created.
func (*DryRunWorkspace) GetMetadata ¶
func (w *DryRunWorkspace) GetMetadata(key string) (interface{}, bool)
GetMetadata retrieves a metadata value from the workspace.
func (*DryRunWorkspace) GetOperationCount ¶
func (w *DryRunWorkspace) GetOperationCount() int
GetOperationCount returns the total number of operations recorded.
func (*DryRunWorkspace) GetOperations ¶
func (w *DryRunWorkspace) GetOperations() []DryRunOperation
GetOperations returns all recorded operations.
func (*DryRunWorkspace) GetPath ¶
func (w *DryRunWorkspace) GetPath(relativePath string) string
GetPath returns the simulated absolute path for a relative path within the workspace.
func (*DryRunWorkspace) GetTempPath ¶
func (w *DryRunWorkspace) GetTempPath(relativePath string) string
GetTempPath returns the simulated absolute path for a relative path within the temp directory.
func (*DryRunWorkspace) GetTotalSize ¶
func (w *DryRunWorkspace) GetTotalSize() int64
GetTotalSize returns the total size of all files that would be created.
func (*DryRunWorkspace) LastModified ¶
func (w *DryRunWorkspace) LastModified() time.Time
LastModified returns the last modification time.
func (*DryRunWorkspace) RecordOperation ¶
func (w *DryRunWorkspace) RecordOperation(op DryRunOperation)
RecordOperation records an operation that would be performed.
func (*DryRunWorkspace) RestoreCheckpoint ¶
func (w *DryRunWorkspace) RestoreCheckpoint(checkpointID string) error
RestoreCheckpoint simulates restoring to a checkpoint.
func (*DryRunWorkspace) SetMetadata ¶
func (w *DryRunWorkspace) SetMetadata(key string, value interface{})
SetMetadata sets a metadata value in the workspace.
func (*DryRunWorkspace) UpdateModifiedTime ¶
func (w *DryRunWorkspace) UpdateModifiedTime()
UpdateModifiedTime updates the last modified timestamp.
type DryRunWorkspaceManager ¶
type DryRunWorkspaceManager struct {
// contains filtered or unexported fields
}
DryRunWorkspaceManager manages dry-run workspaces.
func NewDryRunWorkspaceManager ¶
func NewDryRunWorkspaceManager() *DryRunWorkspaceManager
NewDryRunWorkspaceManager creates a new dry-run workspace manager.
func (*DryRunWorkspaceManager) CleanupWorkspace ¶
func (m *DryRunWorkspaceManager) CleanupWorkspace(ctx context.Context, workspace *GitOpsWorkspace) error
CleanupWorkspace cleans up a dry-run workspace (no-op since nothing was created).
func (*DryRunWorkspaceManager) CreateWorkspace ¶
func (m *DryRunWorkspaceManager) CreateWorkspace(ctx context.Context, cfg v2.Config) (*GitOpsWorkspace, error)
CreateWorkspace creates a new dry-run workspace.
func (*DryRunWorkspaceManager) GetDryRunWorkspace ¶
func (m *DryRunWorkspaceManager) GetDryRunWorkspace(workspaceID string) (*DryRunWorkspace, error)
GetDryRunWorkspace retrieves the actual dry-run workspace for inspection.
func (*DryRunWorkspaceManager) GetWorkspace ¶
func (m *DryRunWorkspaceManager) GetWorkspace(ctx context.Context, workspaceID string) (*GitOpsWorkspace, error)
GetWorkspace retrieves a dry-run workspace by ID.
type FluxKustomizationPatchesRenderer ¶
FluxKustomizationPatchesRenderer produces an inline patches block for a generated Flux Kustomization. It is used for patches that must be applied to the source tree during that Kustomization's reconciliation, before a later service overlay is reconciled.
type GeneratedFileInfo ¶
type GeneratedManifest ¶
type GeneratedManifest struct {
Version int `json:"version"`
Scope string `json:"scope"`
Identity string `json:"identity"`
Files map[string]string `json:"-"` // legacy migration API
FileRecords map[string]GeneratedFileInfo `json:"-"`
}
GeneratedManifest is the v2 ownership ledger. File names are repository relative, while mode is the permission-bit preimage recorded at promotion.
func (GeneratedManifest) MarshalJSON ¶
func (m GeneratedManifest) MarshalJSON() ([]byte, error)
func (*GeneratedManifest) UnmarshalJSON ¶
func (m *GeneratedManifest) UnmarshalJSON(data []byte) error
type GenerationOptions ¶
type GenerationOptions struct {
// DryRun enables dry-run mode (no filesystem changes)
DryRun bool
// SkipValidation skips validation stages
SkipValidation bool
// OutputDir specifies where to generate the repository (overrides default)
OutputDir string
// CleanupOnError determines whether to clean up workspace on error
CleanupOnError bool
// ProgressCallback is called to report progress
ProgressCallback ProgressCallback
// Verbose enables verbose logging
Verbose bool
}
GenerationOptions configures the generation process.
func DefaultGenerationOptions ¶
func DefaultGenerationOptions() GenerationOptions
DefaultGenerationOptions returns the default generation options.
func (GenerationOptions) Validate ¶
func (opts GenerationOptions) Validate() error
Validate checks if the generation options are valid.
type GenerationPlan ¶
type GenerationPlan struct {
// Stages lists all stages that would be executed
Stages []StagePlan
// TotalFiles is the estimated number of files that would be generated
TotalFiles int
// TotalDirectories is the estimated number of directories that would be created
TotalDirectories int
// EstimatedDuration is an estimate of how long generation would take
EstimatedDuration string
// Warnings contains any warnings about the planned generation
Warnings []string
}
GenerationPlan describes the planned generation operations without executing them. This is used for dry-run mode to preview what would be generated.
func (*GenerationPlan) String ¶
func (plan *GenerationPlan) String() string
String returns a string representation of the generation plan.
type GenerationResult ¶
type GenerationResult struct {
// Success indicates whether generation completed successfully
Success bool
// WorkspaceID is the ID of the workspace used for generation
WorkspaceID string
// StagesCompleted is the number of stages that completed successfully
StagesCompleted int
// TotalStages is the total number of stages
TotalStages int
// FilesGenerated is the number of files created
FilesGenerated int
// Error contains any error that occurred during generation
Error error
// Duration is how long generation took
Duration string
}
GenerationResult contains the results of a generation operation.
func (*GenerationResult) String ¶
func (result *GenerationResult) String() string
String returns a string representation of the generation result.
type GenerationStage ¶
type GenerationStage interface {
// Name returns the unique name of this stage
Name() string
// Description returns a human-readable description of what this stage does
Description() string
// Dependencies returns the names of stages that must complete before this stage
Dependencies() []string
// Execute performs the stage's generation operations
Execute(ctx context.Context, workspace *GitOpsWorkspace) error
// Rollback undoes the changes made by this stage
Rollback(ctx context.Context, workspace *GitOpsWorkspace) error
// Validate checks if the stage completed successfully
Validate(ctx context.Context, workspace *GitOpsWorkspace) error
// DryRun returns a plan of what this stage would do without executing
DryRun(ctx context.Context, cfg v2.Config) (*StagePlan, error)
}
GenerationStage defines the interface for a single generation stage. Each stage is responsible for a specific aspect of GitOps repository generation.
type GitOpsGenerator ¶
type GitOpsGenerator interface {
// Generate creates a complete GitOps repository based on the provided configuration.
// The generation process executes in discrete stages with automatic rollback on failure.
Generate(ctx context.Context, cfg v2.Config) error
// GenerateDryRun previews the generation process without making filesystem changes.
// It returns a plan describing what would be generated.
GenerateDryRun(ctx context.Context, cfg v2.Config) (*GenerationPlan, error)
// Rollback restores the workspace to a previous checkpoint state.
// This is typically called automatically on stage failure but can be invoked manually.
Rollback(ctx context.Context, checkpointID string) error
// GetWorkspace returns the current workspace being used for generation.
GetWorkspace() *GitOpsWorkspace
// SetProgressCallback sets a callback function for progress reporting.
SetProgressCallback(callback ProgressCallback)
}
GitOpsGenerator defines the interface for GitOps repository generation. Implementations should support staged execution with rollback capabilities.
type GitOpsWorkspace ¶
type GitOpsWorkspace struct {
// ID is a unique identifier for this workspace
ID string
// RootDir is the root directory of the workspace where all files are generated
RootDir string
// TempDir is a temporary directory for intermediate operations
TempDir string
// Config is the cluster configuration associated with this workspace
Config v2.Config
// Metadata stores arbitrary key-value pairs for workspace context
Metadata map[string]interface{}
// Checkpoints stores workspace checkpoints for rollback capability
Checkpoints map[string]WorkspaceCheckpoint
// contains filtered or unexported fields
}
GitOpsWorkspace represents an isolated environment for GitOps repository generation. It provides a safe space for file operations with support for checkpointing and rollback.
func (*GitOpsWorkspace) CreateCheckpoint ¶
func (w *GitOpsWorkspace) CreateCheckpoint(checkpointID string) (*WorkspaceCheckpoint, error)
CreateCheckpoint creates a new checkpoint of the current workspace state. The checkpoint captures all files in the workspace and stores them for potential rollback.
func (*GitOpsWorkspace) CreatedAt ¶
func (w *GitOpsWorkspace) CreatedAt() time.Time
CreatedAt returns the workspace creation time.
func (*GitOpsWorkspace) DeleteCheckpoint ¶
func (w *GitOpsWorkspace) DeleteCheckpoint(checkpointID string) error
DeleteCheckpoint removes a checkpoint and frees its storage.
func (*GitOpsWorkspace) Exists ¶
func (w *GitOpsWorkspace) Exists(relativePath string) bool
Exists checks if a file or directory exists in the workspace.
func (*GitOpsWorkspace) GetCheckpoint ¶
func (w *GitOpsWorkspace) GetCheckpoint(checkpointID string) (*WorkspaceCheckpoint, error)
GetCheckpoint retrieves a checkpoint by ID.
func (*GitOpsWorkspace) GetFileCount ¶
func (w *GitOpsWorkspace) GetFileCount() int
GetFileCount returns the number of files in the workspace. It recursively counts all files in the workspace root directory.
func (*GitOpsWorkspace) GetMetadata ¶
func (w *GitOpsWorkspace) GetMetadata(key string) (interface{}, bool)
GetMetadata retrieves a metadata value from the workspace.
func (*GitOpsWorkspace) GetPath ¶
func (w *GitOpsWorkspace) GetPath(relativePath string) string
GetPath returns the absolute path for a relative path within the workspace.
func (*GitOpsWorkspace) GetTempPath ¶
func (w *GitOpsWorkspace) GetTempPath(relativePath string) string
GetTempPath returns the absolute path for a relative path within the temp directory.
func (*GitOpsWorkspace) LastModified ¶
func (w *GitOpsWorkspace) LastModified() time.Time
LastModified returns the last modification time.
func (*GitOpsWorkspace) ListCheckpoints ¶
func (w *GitOpsWorkspace) ListCheckpoints() []string
ListCheckpoints returns a list of all checkpoint IDs in the workspace.
func (*GitOpsWorkspace) RestoreCheckpoint ¶
func (w *GitOpsWorkspace) RestoreCheckpoint(checkpointID string) error
RestoreCheckpoint restores the workspace to a previous checkpoint state. This operation removes all current files and restores files from the checkpoint.
func (*GitOpsWorkspace) SetMetadata ¶
func (w *GitOpsWorkspace) SetMetadata(key string, value interface{})
SetMetadata sets a metadata value in the workspace.
func (*GitOpsWorkspace) UpdateModifiedTime ¶
func (w *GitOpsWorkspace) UpdateModifiedTime()
UpdateModifiedTime updates the last modified timestamp.
type KustomizationRenderer ¶
KustomizationRenderer produces the service overlay kustomization.yaml content from cluster config. When set on a RenderSpec it replaces the static KustomizationContent, letting a service list a config-dependent set of resources (e.g. per-pool EnvoyProxy files for OCTR-762).
type ManifestValidator ¶
type ManifestValidator struct {
// contains filtered or unexported fields
}
ManifestValidator validates generated GitOps manifests for common issues
func NewManifestValidator ¶
func NewManifestValidator(gitDir string) *ManifestValidator
NewManifestValidator creates a new manifest validator
func (*ManifestValidator) Validate ¶
func (v *ManifestValidator) Validate() error
Validate runs all validation checks on generated manifests
type OperationType ¶
type OperationType string
OperationType represents the type of operation.
const ( OpCreateDir OperationType = "create_dir" OpWriteFile OperationType = "write_file" OpRemoveFile OperationType = "remove_file" OpRemoveDir OperationType = "remove_dir" )
type OverlayEncryptor ¶
OverlayEncryptor encrypts the generated cluster-apps overlay before it is promoted. The callback operates on the temporary workspace path, so failures leave the final target unchanged.
type OverlayFilesRenderer ¶
OverlayFilesRenderer produces additional overlay files from cluster config. Returns a map of filename → content.
type OverrideValuesRenderer ¶
OverrideValuesRenderer produces dynamic override-values.yaml content from cluster config.
type PipelineGenerator ¶
type PipelineGenerator struct {
// contains filtered or unexported fields
}
PipelineGenerator implements GitOpsGenerator using a staged pipeline approach. Each stage executes independently and can be rolled back on failure.
Example (WithProgress) ¶
ExamplePipelineGenerator_withProgress demonstrates integrating progress reporting into a complete GitOps generation workflow.
package main
import (
"context"
"fmt"
"os"
v2 "github.com/opencenter-cloud/opencenter-cli/internal/config/v2"
"github.com/opencenter-cloud/opencenter-cli/internal/gitops"
)
func main() {
// Create progress reporter
reporter := gitops.NewProgressReporter(gitops.ProgressReporterOptions{
Writer: os.Stdout,
Verbose: false,
UseColors: true,
})
// Create workspace manager
tempDir := "/tmp/gitops-example"
workspaceManager := gitops.NewWorkspaceManager(tempDir)
// Create generation stages (simplified)
stages := []gitops.GenerationStage{
// Your stages would be defined here
}
// Create generator with options including progress callback
options := gitops.GenerationOptions{
DryRun: false,
SkipValidation: false,
CleanupOnError: true,
ProgressCallback: reporter.Callback(),
Verbose: false,
}
generator := gitops.NewPipelineGeneratorWithOptions(workspaceManager, stages, options)
// Create configuration
cfg := v2.Config{
// Configure your cluster
}
// Generate with progress reporting
ctx := context.Background()
err := generator.Generate(ctx, cfg)
if err != nil {
reporter.Error(err)
fmt.Printf("Generation failed: %v\n", err)
return
}
// Report successful completion
reporter.Complete(0, 0) // Would use actual duration and file count
}
Output:
func NewPipelineGenerator ¶
func NewPipelineGenerator(workspaceManager WorkspaceManager, stages []GenerationStage) *PipelineGenerator
NewPipelineGenerator creates a new pipeline-based GitOps generator.
func NewPipelineGeneratorWithOptions ¶
func NewPipelineGeneratorWithOptions(workspaceManager WorkspaceManager, stages []GenerationStage, options GenerationOptions) *PipelineGenerator
NewPipelineGeneratorWithOptions creates a new pipeline generator with custom options.
func (*PipelineGenerator) Generate ¶
Generate executes the complete GitOps generation pipeline. Stages are executed in order, with automatic rollback on failure.
func (*PipelineGenerator) GenerateDryRun ¶
func (pg *PipelineGenerator) GenerateDryRun(ctx context.Context, cfg v2.Config) (*GenerationPlan, error)
GenerateDryRun performs a dry-run of the generation process. It executes all stages with a dry-run workspace that records operations without making filesystem changes, providing an accurate preview of what would be generated.
func (*PipelineGenerator) GetCompletedStages ¶
func (pg *PipelineGenerator) GetCompletedStages() []string
GetCompletedStages returns the list of stages that have completed successfully.
func (*PipelineGenerator) GetCurrentStage ¶
func (pg *PipelineGenerator) GetCurrentStage() string
GetCurrentStage returns the name of the stage currently being executed.
func (*PipelineGenerator) GetTotalStages ¶
func (pg *PipelineGenerator) GetTotalStages() int
GetTotalStages returns the total number of stages in the pipeline.
func (*PipelineGenerator) GetWorkspace ¶
func (pg *PipelineGenerator) GetWorkspace() *GitOpsWorkspace
GetWorkspace returns the current workspace.
func (*PipelineGenerator) Rollback ¶
func (pg *PipelineGenerator) Rollback(ctx context.Context, checkpointID string) error
Rollback restores the workspace to a previous checkpoint.
func (*PipelineGenerator) SetProgressCallback ¶
func (pg *PipelineGenerator) SetProgressCallback(callback ProgressCallback)
SetProgressCallback sets the progress callback function.
type ProgressCallback ¶
ProgressCallback is called during generation to report progress. It receives the current stage name, progress percentage (0-100), and a status message.
type ProgressReporter ¶
type ProgressReporter struct {
// contains filtered or unexported fields
}
ProgressReporter provides user-facing progress reporting for GitOps generation. It displays real-time progress updates with stage information and completion status.
Example ¶
ExampleProgressReporter demonstrates how to use the progress reporter with the pipeline generator to provide user feedback during GitOps generation.
package main
import (
"context"
"os"
v2 "github.com/opencenter-cloud/opencenter-cli/internal/config/v2"
"github.com/opencenter-cloud/opencenter-cli/internal/gitops"
)
func main() {
// Create a progress reporter that writes to stdout
reporter := gitops.NewDefaultProgressReporter(os.Stdout)
// Create a workspace manager and stages (simplified for example)
workspaceManager := gitops.NewWorkspaceManager("/tmp/gitops-workspace")
stages := []gitops.GenerationStage{
// Add your stages here
}
// Create pipeline generator with progress callback
generator := gitops.NewPipelineGenerator(workspaceManager, stages)
generator.SetProgressCallback(reporter.Callback())
// Create configuration
cfg := v2.Config{
// Configure your cluster here
}
// Generate GitOps repository with progress reporting
ctx := context.Background()
err := generator.Generate(ctx, cfg)
if err != nil {
reporter.Error(err)
return
}
// Report completion
reporter.Complete(0, 42) // duration and file count would be tracked
}
Output:
Example (Quiet) ¶
ExampleProgressReporter_quiet demonstrates quiet mode for non-interactive use.
package main
import (
"os"
"github.com/opencenter-cloud/opencenter-cli/internal/gitops"
)
func main() {
// Create a quiet progress reporter (no output)
reporter := gitops.NewProgressReporter(gitops.ProgressReporterOptions{
Writer: os.Stdout,
Quiet: true, // Suppresses all output
})
// Progress updates will be silently ignored
callback := reporter.Callback()
callback("stage", 50, "This will not be displayed")
}
Output:
Example (Verbose) ¶
ExampleProgressReporter_verbose demonstrates verbose progress reporting with detailed timing information.
package main
import (
"os"
"github.com/opencenter-cloud/opencenter-cli/internal/gitops"
)
func main() {
// Create a verbose progress reporter
reporter := gitops.NewProgressReporter(gitops.ProgressReporterOptions{
Writer: os.Stdout,
Verbose: true,
UseColors: true,
})
// Use the reporter's callback with the generator
callback := reporter.Callback()
// Simulate progress updates
callback("initialization", 0, "Starting GitOps generation")
callback("initialization", 100, "Initialization complete")
callback("base-structure", 0, "Creating directory structure")
callback("base-structure", 50, "Copying base files")
callback("base-structure", 100, "Base structure complete")
callback("completion", 100, "Generation completed")
}
Output:
func NewDefaultProgressReporter ¶
func NewDefaultProgressReporter(writer io.Writer) *ProgressReporter
NewDefaultProgressReporter creates a progress reporter with default settings.
func NewProgressReporter ¶
func NewProgressReporter(opts ProgressReporterOptions) *ProgressReporter
NewProgressReporter creates a new progress reporter with the given options.
func (*ProgressReporter) Callback ¶
func (pr *ProgressReporter) Callback() ProgressCallback
Callback returns a ProgressCallback function that can be used with GitOpsGenerator.
func (*ProgressReporter) Complete ¶
func (pr *ProgressReporter) Complete(duration time.Duration, filesGenerated int)
Complete displays a completion message.
func (*ProgressReporter) Error ¶
func (pr *ProgressReporter) Error(err error)
Error displays an error message.
type ProgressReporterOptions ¶
type ProgressReporterOptions struct {
// Writer is where progress output is written (typically os.Stdout)
Writer io.Writer
// Quiet suppresses all progress output
Quiet bool
// Verbose enables detailed progress messages
Verbose bool
// UseColors enables colored output (ANSI escape codes)
UseColors bool
}
ProgressReporterOptions configures the progress reporter.
type PromoteOptions ¶
type PromoteResult ¶
type PromoteResult struct {
Added, Updated, Unchanged, Pruned, PruneCandidates, Seeded []string
Renamed, Adopted []string
BackupPaths []string
Warnings []string
}
func GenerateClusterTree ¶
func GenerateClusterTree(ctx context.Context, cfg v2.Config, opts StagedGenerationOptions) (*PromoteResult, int, error)
GenerateClusterTree renders the requested GitOps tree once in a private workspace, validates it, runs ownership preflight without mutation, and promotes the already validated stage. It never writes the live target before the ownership preflight succeeds.
func PlanClusterAppsPromotion ¶
func PlanClusterAppsPromotion(cfg v2.Config) (*PromoteResult, error)
PlanClusterAppsPromotion renders the cluster applications into an isolated workspace and reports what promotion to the real overlay would do. It never mutates the configured GitOps repository.
func PlanClusterAppsPromotionWithOptions ¶
func PlanClusterAppsPromotionWithOptions(cfg v2.Config, opts PromoteOptions) (*PromoteResult, error)
PlanClusterAppsPromotionWithOptions renders cluster applications into an isolated workspace and classifies promotion with mutation disabled.
func RenderClusterAppsWithEncryptionResult ¶
func RenderClusterAppsWithEncryptionResult(ctx context.Context, cfg v2.Config, encrypt OverlayEncryptor, opts PromoteOptions) (*PromoteResult, error)
RenderClusterAppsWithEncryption renders and returns the complete promotion classification. The legacy error-only wrapper remains available above.
func RenderSingleServiceWithEncryptionResult ¶
func RenderSingleServiceWithEncryptionResult(ctx context.Context, cfg v2.Config, serviceName string, isManaged bool, encrypt OverlayEncryptor, opts PromoteOptions) (*PromoteResult, error)
RenderSingleServiceWithEncryptionResult returns the scoped promotion result.
type RenderCatalog ¶
type RenderCatalog struct {
// contains filtered or unexported fields
}
RenderCatalog is an immutable lookup of built-in GitOps render specifications. The constructor is the only place where built-in entries are defined; callers receive values and cannot register or mutate catalog ownership globally.
func (RenderCatalog) Lookup ¶
func (c RenderCatalog) Lookup(serviceName string) (RenderSpec, bool)
func (RenderCatalog) Validate ¶
func (c RenderCatalog) Validate() error
func (RenderCatalog) ValidateAgainstDescriptors ¶
func (c RenderCatalog) ValidateAgainstDescriptors(registry *descriptorcfg.Registry) error
func (RenderCatalog) ValidateConfigOwnership ¶
func (c RenderCatalog) ValidateConfigOwnership(cfg v2.Config, registry *descriptorcfg.Registry) error
type RenderDiagnostics ¶
type RenderDiagnostics struct {
Cluster string `json:"cluster"`
Descriptors []DescriptorDecision `json:"descriptors"`
Actions []ActionDiagnostic `json:"actions,omitempty"`
Undeclared []string `json:"undeclared,omitempty"`
}
RenderDiagnostics captures structured diagnostic information about a rendering operation. It records which descriptors were evaluated, why each was included or excluded, and which files were produced.
func (*RenderDiagnostics) JSON ¶
func (d *RenderDiagnostics) JSON() ([]byte, error)
JSON returns the diagnostics as indented JSON bytes.
type RenderSpec ¶
type RenderSpec struct {
ServiceName string
DefaultNamespace string
SourceName string
SourceGroup string
EmitSource bool
BasePath string
PostBaseStages []postBaseStageSpec
SingleStage bool
BaseOnly bool
OmitTargetNamespace bool
PrivilegedNamespace bool
HasOverrideValues bool
NamespaceStage bool
KustomizationName string
// HelmReleaseName is the metadata.name of the HelmRelease the base ships,
// for the services where it differs from ServiceName. The "-base" Flux
// Kustomization's healthChecks reference the HelmRelease by name; a wrong
// name targets a resource that never exists, so the Kustomization never
// reports Ready. Empty means the HelmRelease is named after the service.
HelmReleaseName string
EnterpriseRegistry bool
GeneratedResourceFiles []string
ExtraDependencies []string
ConditionalDependencies []catalogConditionalDependency
OverrideDependsOn []string
// SkipSourcesDependency lets bootstrap-priority services reconcile before the
// aggregate sources gate. Use only for services that must start before external
// git sources are ready (e.g. openstack-ccm, which unblocks CoreDNS and DNS).
SkipSourcesDependency bool
OverrideValues string
KustomizationContent string
OverrideValuesRenderer OverrideValuesRenderer
OverlayFilesRenderer OverlayFilesRenderer
KustomizationRenderer KustomizationRenderer
BaseKustomizationPatchesRenderer FluxKustomizationPatchesRenderer
}
RenderSpec describes all GitOps-owned rendering behavior for one auto-rendered service. It is deliberately independent from services.BaseConfig so internal topology and renderer choices cannot leak into user configuration.
type SecretScanFinding ¶
SecretScanFinding describes a secret policy violation in a GitOps tree.
func ScanGitOpsSecrets ¶
func ScanGitOpsSecrets(root string) ([]SecretScanFinding, error)
ScanGitOpsSecrets scans a GitOps worktree for committed secret material.
func ScanGitOpsSecretsWithOptions ¶
func ScanGitOpsSecretsWithOptions(ctx context.Context, opts SecretScanOptions) ([]SecretScanFinding, error)
ScanGitOpsSecretsWithOptions scans a worktree or its staged blobs.
type SecretScanOptions ¶
SecretScanOptions controls GitOps secret scanning.
type SimpleProgressReporter ¶
type SimpleProgressReporter struct {
// contains filtered or unexported fields
}
SimpleProgressReporter provides a minimal progress reporter for non-interactive use.
Example ¶
ExampleSimpleProgressReporter demonstrates the simple progress reporter for minimal output in CI/CD environments.
package main
import (
"os"
"github.com/opencenter-cloud/opencenter-cli/internal/gitops"
)
func main() {
// Create a simple progress reporter
reporter := gitops.NewSimpleProgressReporter(os.Stdout)
// Use the reporter's callback
callback := reporter.Callback()
// Only stage start and completion are reported
callback("initialization", 0, "Starting")
callback("initialization", 50, "In progress") // Not displayed
callback("initialization", 100, "Done")
}
Output: Starting: initialization Completed: initialization
func NewSimpleProgressReporter ¶
func NewSimpleProgressReporter(writer io.Writer) *SimpleProgressReporter
NewSimpleProgressReporter creates a simple progress reporter that just prints stage names.
func (*SimpleProgressReporter) Callback ¶
func (spr *SimpleProgressReporter) Callback() ProgressCallback
Callback returns a ProgressCallback function.
type SourceAuthParams ¶
type SourceAuthParams struct {
AuthMethod string
TokenURL string
SSHURL string
RefType string
RefValue string
SecretName string
// Anonymous omits the secretRef entirely so Flux accesses the repository
// without credentials. The shared openCenter-gitops-base repository is
// public, so its GitRepository source must not reference a credential
// Secret; attaching one (e.g. the token-derived opencenter-base Secret,
// which in local mode holds the Gitea token) makes Flux authenticate to
// public GitHub with the wrong credential and fail with HTTP 401.
Anonymous bool
}
SourceAuthParams holds the parameters needed to render a GitRepository source auth block with an active and a commented-out alternative variant.
func BuildSourceAuthParams ¶
func BuildSourceAuthParams(authMethod, repositoryURL, refType, refValue, secretName string) (SourceAuthParams, error)
BuildSourceAuthParams derives token and SSH URL variants for repositoryURL and retains the explicit auth method selected for this generation run.
type StagePlan ¶
type StagePlan struct {
// Name is the stage name
Name string
// Description describes what the stage does
Description string
// Files lists files that would be created or modified
Files []string
// Directories lists directories that would be created
Directories []string
// Dependencies lists stages that must complete before this stage
Dependencies []string
}
StagePlan describes a single stage in the generation plan.
type StagedGenerationOptions ¶
type StagedGenerationOptions struct {
Materialize func(string) error
Encrypt OverlayEncryptor
ValidateManifest func(string) error
IncludeInfrastructure bool
IncludeFluxBridge bool
Promote PromoteOptions
BeforePromote func() error
}
StagedGenerationOptions controls complete-tree staging and promotion. The staged tree is the only render pass; validation, ownership planning, and apply all consume the same workspace contents.
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
Transaction represents a set of file operations that can be committed or rolled back atomically.
func NewTransaction ¶
func NewTransaction(workspace *GitOpsWorkspace) *Transaction
NewTransaction creates a new transaction for atomic multi-file operations.
func (*Transaction) Commit ¶
func (t *Transaction) Commit() error
Commit executes all operations in the transaction atomically. If any operation fails, all previous operations are rolled back.
func (*Transaction) MkdirAll ¶
func (t *Transaction) MkdirAll(relativePath string, perm os.FileMode)
MkdirAll adds a directory creation operation to the transaction.
func (*Transaction) RemoveFile ¶
func (t *Transaction) RemoveFile(relativePath string)
RemoveFile adds a file removal operation to the transaction.
func (*Transaction) Rollback ¶
func (t *Transaction) Rollback()
Rollback discards all operations in the transaction without executing them.
type WorkspaceCheckpoint ¶
type WorkspaceCheckpoint struct {
// ID is a unique identifier for this checkpoint
ID string
// Timestamp is when the checkpoint was created
Timestamp time.Time
// Files is a list of files that were present at checkpoint time
Files []string
// Metadata stores arbitrary key-value pairs for checkpoint context
Metadata map[string]interface{}
// contains filtered or unexported fields
}
WorkspaceCheckpoint represents a snapshot of workspace state at a specific point in time. Checkpoints enable rollback capabilities for GitOps generation operations.
type WorkspaceManager ¶
type WorkspaceManager interface {
// CreateWorkspace creates a new isolated workspace for GitOps generation
CreateWorkspace(ctx context.Context, cfg v2.Config) (*GitOpsWorkspace, error)
// CleanupWorkspace removes a workspace and all its resources
CleanupWorkspace(ctx context.Context, workspace *GitOpsWorkspace) error
// GetWorkspace retrieves an existing workspace by ID
GetWorkspace(ctx context.Context, workspaceID string) (*GitOpsWorkspace, error)
}
WorkspaceManager manages GitOps workspace lifecycle including creation, cleanup, and resource management.
func NewWorkspaceManager ¶
func NewWorkspaceManager(baseDir string) WorkspaceManager
NewWorkspaceManager creates a new workspace manager with the specified base directory. If baseDir is empty, it uses the system temporary directory. The manager starts an automatic cleanup goroutine to prevent workspace leaks.
func NewWorkspaceManagerWithOptions ¶
func NewWorkspaceManagerWithOptions(baseDir string, maxAge, cleanupInterval time.Duration) WorkspaceManager
NewWorkspaceManagerWithOptions creates a workspace manager with custom options.
Source Files
¶
- adoption.go
- atomic.go
- auto_descriptor.go
- cert_manager_renderer.go
- checkpoint.go
- config_helpers.go
- copy.go
- descriptor_renderer.go
- doc.go
- dryrun.go
- dryrun_writer.go
- embed.go
- etcd_backup_renderer.go
- gateway_pools.go
- generator.go
- kube_prometheus_stack_contract.go
- metallb_renderer.go
- openstack_ccm_contract.go
- overlay_files_renderers.go
- overlay_units_validation.go
- override_values_registry.go
- override_values_renderers.go
- ownership.go
- pipeline.go
- progress.go
- promote_dryrun.go
- render_catalog.go
- render_diagnostics.go
- security_scanner.go
- source_auth.go
- tree_promotion.go
- validators.go
- workspace.go