Documentation
¶
Overview ¶
Package layout provides utilities for generating cluster directory layouts and for writing Kubernetes and Flux manifests to disk.
Flux Kustomizations and ArgoCD Applications reference directories in a Git repository using different fields. Flux uses `spec.path`, which must start with `./` and is always interpreted relative to the repository root. ArgoCD uses `spec.source.path` without the `./` prefix but with the same relative semantics.
When nodes or bundles live in nested subfolders, the path must point directly to the folder containing the manifests unless the directory tree only contains files for a single node or bundle. Flux will recursively auto-generate a `kustomization.yaml` when one is missing and include every manifest under the specified path. ArgoCD does not auto-generate a `kustomization.yaml` and therefore ignores nested directories unless they are referenced from a `kustomization.yaml` at the target path.
For example, consider the layout:
repo/
clusters/
prod/
nodes/
cp/
kustomization.yaml
bundles/
monitoring/
kustomization.yaml
The Flux Kustomization for the control-plane node uses:
spec.path: ./clusters/prod/nodes/cp
The equivalent ArgoCD Application uses:
spec.source.path: clusters/prod/nodes/cp
With this layout, each node or bundle is targeted individually. Pointing a Flux Kustomization at `./clusters/prod` would combine the `cp` and `monitoring` manifests into a single deployment because it would auto-generate a `kustomization.yaml` for the entire tree. ArgoCD will only process the manifests under `clusters/prod` itself unless a `kustomization.yaml` aggregates the subdirectories, so each subfolder must be referenced separately.
Package api defines configuration structures used to generate Kubernetes manifests and Flux resources.
Example (AgentsLayout) ¶
cluster := exampleCluster()
rules := layout.LayoutRules{
BundleGrouping: layout.GroupFlat,
ApplicationGrouping: layout.GroupFlat,
}
ml, err := layout.WalkCluster(cluster, rules)
if err != nil {
panic(err)
}
// The root node's layout renders no bundle: bundle "web" has the directory
// inside it.
unit := ml.OriginUnit()
fmt.Println(ml.FullRepoPath(), len(ml.Resources))
fmt.Println(unit.FullRepoPath(), len(unit.Resources))
Output: apps 0 apps/web 2
Index ¶
- func DefaultKustomizationFileName(name string) string
- func DefaultManifestFileName(namespace, kind, name string, mode FileExportMode) string
- func KindNameManifestFileName(_, kind, name string, mode FileExportMode) string
- func TopDirectory(root *stack.Node, rules LayoutRules) (string, error)
- func WalkClusterByPackage(c *stack.Cluster, rules LayoutRules) (map[string]*ManifestLayout, error)
- func WriteManifest(basePath string, cfg Config, ml *ManifestLayout) error
- func WritePackagesToDisk(packages map[string]*ManifestLayout, basePath string) error
- type ApplicationFileMode
- type ApplicationObjects
- type Config
- type ConfigMapGeneratorSpec
- type ExtraFile
- type FileExportMode
- type FileNamingMode
- type FluxKustomizationRecord
- type FluxPlacement
- type GroupingMode
- type KustomizationFileNameFunc
- type KustomizationMode
- type LayoutAugmenter
- type LayoutIntentAugmenter
- type LayoutPreset
- type LayoutRules
- type ManifestFileNameFunc
- type ManifestLayout
- func (ml *ManifestLayout) FluxBuild() bool
- func (ml *ManifestLayout) FluxKustomizations() []FluxKustomizationRecord
- func (ml *ManifestLayout) FullRepoPath() string
- func (ml *ManifestLayout) FullRepoPathWithPackage() string
- func (ml *ManifestLayout) OriginApplication() *stack.Application
- func (ml *ManifestLayout) OriginApplicationObjects() []ApplicationObjects
- func (ml *ManifestLayout) OriginBundleObjects(b *stack.Bundle) []client.Object
- func (ml *ManifestLayout) OriginBundles() []*stack.Bundle
- func (ml *ManifestLayout) OriginNodes() []*stack.Node
- func (ml *ManifestLayout) OriginUnit() *ManifestLayout
- func (ml *ManifestLayout) SameDirectory(other *ManifestLayout) bool
- func (ml *ManifestLayout) SetFluxBuild(b bool)
- func (ml *ManifestLayout) SetFluxKustomizations(recs []FluxKustomizationRecord)
- func (ml *ManifestLayout) WriteToDisk(basePath string) error
- func (ml *ManifestLayout) WriteToTar(w io.Writer) error
- type OriginIndex
- func (ix *OriginIndex) BundleLayout(b *stack.Bundle) *ManifestLayout
- func (ix *OriginIndex) Bundles() []*stack.Bundle
- func (ix *OriginIndex) KustomizationPath(b *stack.Bundle) (string, error)
- func (ix *OriginIndex) NodeLayout(n *stack.Node) *ManifestLayout
- func (ix *OriginIndex) Parent(ml *ManifestLayout) *ManifestLayout
- func (ix *OriginIndex) UnitDependencies(l *ManifestLayout) []string
- func (ix *OriginIndex) UnitName(b *stack.Bundle) string
- func (ix *OriginIndex) UnitNamedDependencies(l *ManifestLayout) []string
- func (ix *OriginIndex) UnitOfName(name string) string
- func (ix *OriginIndex) Units() []*ManifestLayout
- type Profile
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultKustomizationFileName ¶
DefaultKustomizationFileName returns the standard Flux Kustomization file name.
func DefaultManifestFileName ¶
func DefaultManifestFileName(namespace, kind, name string, mode FileExportMode) string
DefaultManifestFileName implements the standard file naming convention used by Kure. It writes either one file per resource or groups by kind depending on the FileExportMode.
func KindNameManifestFileName ¶
func KindNameManifestFileName(_, kind, name string, mode FileExportMode) string
KindNameManifestFileName returns file names using {kind}-{name}.yaml format, without the namespace prefix. This is the default for Pattern A (CentralizedControlPlane) where per-app artifact directories make the namespace prefix redundant.
func TopDirectory ¶
func TopDirectory(root *stack.Node, rules LayoutRules) (string, error)
TopDirectory returns the directory at the top of the tree WalkCluster builds with rules for a cluster whose root node is root: the directory that holds the tree's first kustomization.yaml, and so the one to point Flux at. It is relative to the directory the tree is written into and has no leading slash; "." is that directory itself. The walk takes its top from the same place (topLayout), so the two name the same directory. The rules are validated first, as WalkCluster validates them.
With a ClusterName it is the cluster directory. Without one it is the root node's name, "cluster" for an unnamed root node, and "." when root is nil: no tree is walked then, and the caller applies the directory it writes to.
Where the root node's name is the directory, a name that is no directory name ("../prod", "a/b", ".") is an error, as it is to WalkCluster (stack.ValidateCluster): no tree is walked for such a root. Under a ClusterName the name is no part of the directory and is not checked here.
Only the spelling differs, and only for a rooted ClusterName ("/prod"): the walk's own ManifestLayout.FullRepoPath keeps the slash, and the writers resolve it under the directory they write to. That is the directory returned here, "prod"; a ClusterName of "/" alone gives ".".
It does not describe a WalkClusterByPackage tree, which is placed without the ClusterName, one tree per package. Nor does it know the directory a writer is given: a tree written below a sub-path of the repository is at that sub-path joined with this directory.
func WalkClusterByPackage ¶
func WalkClusterByPackage(c *stack.Cluster, rules LayoutRules) (map[string]*ManifestLayout, error)
WalkClusterByPackage traverses a stack.Cluster and builds separate ManifestLayout trees for each unique PackageRef (OCI artifact). Returns a map where keys are PackageRef GVKs and values are the corresponding ManifestLayout trees. Nodes without PackageRef inherit from their parent, with nil representing the default package. The grouping axes apply as in WalkCluster; the package trees carry no Flux placement. The rules are validated first, as in WalkCluster, including the options this walk does not use.
func WriteManifest ¶
func WriteManifest(basePath string, cfg Config, ml *ManifestLayout) error
WriteManifest writes a ManifestLayout to disk using the provided configuration, every directory under basePath/<cfg.ManifestsDir>: a Flux source for a walked layout must be rooted there, because every Flux Kustomization spec.path is a layout directory relative to that root. It refuses, before writing anything, a tree in which two layouts resolve to the same directory (see checkLayoutTree) and a layout that renders a node or bundle but sets AppFileSingle as its own mode: that layout's files go into its Namespace, so no directory exists at the path its Flux Kustomization or ArgoCD Application names. cfg's AppFileSingle never applies to such a layout (see manifestAppMode).
func WritePackagesToDisk ¶
func WritePackagesToDisk(packages map[string]*ManifestLayout, basePath string) error
WritePackagesToDisk writes multiple package layouts to separate directory structures
Types ¶
type ApplicationFileMode ¶
type ApplicationFileMode string
ApplicationFileMode specifies how resources within an application are written.
The default is AppFilePerResource which mirrors the behaviour of FilePerResource and writes each generated resource to its own file. AppFileSingle groups all resources belonging to an application into a single manifest file.
const ( // AppFilePerResource writes each application resource to its own file. AppFilePerResource ApplicationFileMode = "resource" // AppFileSingle writes all resources for an application into one file. AppFileSingle ApplicationFileMode = "single" // AppFileUnset indicates that no application file mode was specified. AppFileUnset ApplicationFileMode = "" )
type ApplicationObjects ¶
type ApplicationObjects struct {
// Application is the application.
Application *stack.Application
// Objects are the objects the application's directory builds for it, the
// same values the layouts hold: those it emitted and, when it has a layout
// of its own, those a LayoutAugmenter added to that layout or below it. A
// ConfigMap that a configMapGenerator builds is not among them: it exists
// only once kustomize has built the directory (see Layout).
Objects []client.Object
// Layout is the application's own layout, whose ConfigMapGenerators (and
// those of the layouts below it) are the application's. Nil when the
// application's objects were written into its bundle's directory.
Layout *ManifestLayout
// contains filtered or unexported fields
}
ApplicationObjects is what one application rendered in a walked layout.
type Config ¶
type Config struct {
// ManifestsDir is the directory under which Kubernetes manifests are written.
ManifestsDir string
// FluxDir is the directory under which Flux manifests are written.
FluxDir string
// FilePer determines how resources are grouped into files when writing manifests.
FilePer FileExportMode
// ApplicationFileMode controls whether application resources are written
// to a single file or split per resource. Defaults to AppFilePerResource.
ApplicationFileMode ApplicationFileMode
// KustomizationMode controls how kustomization.yaml files are generated.
// Defaults to KustomizationExplicit.
KustomizationMode KustomizationMode
// FluxKustomizationMode overrides KustomizationMode based on FluxPlacement.
// When a ManifestLayout's FluxPlacement matches a key in this map, the
// corresponding KustomizationMode is used instead of the global
// KustomizationMode. This allows different kustomization.yaml reference
// styles per flux placement strategy.
FluxKustomizationMode map[FluxPlacement]KustomizationMode
// FileNaming controls the file naming pattern. When set, it determines
// the ManifestFileNameFunc to use. If ManifestFileName is also set, it
// takes precedence over FileNaming.
FileNaming FileNamingMode
// ManifestFileName formats the file name for a resource manifest.
// Takes precedence over FileNaming when set.
ManifestFileName ManifestFileNameFunc
// KustomizationFileName formats the file name for a Flux Kustomization.
KustomizationFileName KustomizationFileNameFunc
}
Config LayoutConfig defines rules for generating a cluster layout.
func ConfigForPreset ¶
func ConfigForPreset(p LayoutPreset) (Config, error)
ConfigForPreset returns a Config configured for the given preset. Unknown presets return an error.
func DefaultConfigForProfile ¶
DefaultConfigForProfile returns a Config initialised with defaults for the given profile. Unknown profiles fall back to FluxProfile.
func DefaultLayoutConfig ¶
func DefaultLayoutConfig() Config
DefaultLayoutConfig returns a configuration that matches the directory layout expected by FluxCD when writing manifests and Kustomizations.
func (Config) ResolveKustomizationMode ¶
func (c Config) ResolveKustomizationMode(fp FluxPlacement) KustomizationMode
ResolveKustomizationMode returns the effective KustomizationMode for the given FluxPlacement. If FluxKustomizationMode contains an override for the placement, that value is used. Otherwise, the global KustomizationMode (or KustomizationExplicit when unset) is returned.
func (Config) ResolveManifestFileName ¶
func (c Config) ResolveManifestFileName() ManifestFileNameFunc
ResolveManifestFileName returns the effective ManifestFileNameFunc for this Config. If ManifestFileName is set it is returned directly. Otherwise, FileNaming is used to select the function. If neither is set, DefaultManifestFileName is returned.
type ConfigMapGeneratorSpec ¶
ConfigMapGeneratorSpec describes a single kustomize configMapGenerator entry. Files are paths (relative to the layout directory) of files included in the generated ConfigMap. Annotations are written as the entry's options.annotations, which kustomize puts on the ConfigMap it generates: the only way to annotate an object that exists only after the build.
type ExtraFile ¶
ExtraFile is an arbitrary file written into a ManifestLayout's directory alongside the resource YAMLs.
type FileExportMode ¶
type FileExportMode string
FileExportMode determines how resources are written to disk.
const ( // FilePerResource writes each resource to its own file. FilePerResource FileExportMode = "resource" // FilePerKind groups resources by kind into a single file. FilePerKind FileExportMode = "kind" // FilePerUnset indicates that no export mode is specified. FilePerUnset FileExportMode = "" )
type FileNamingMode ¶
type FileNamingMode string
FileNamingMode controls the file naming pattern for manifest files.
const ( // FileNamingDefault uses the standard {namespace}-{kind}-{name}.yaml format. FileNamingDefault FileNamingMode = "default" // FileNamingKindName uses the {kind}-{name}.yaml format, omitting the namespace prefix. FileNamingKindName FileNamingMode = "kind-name" // FileNamingUnset indicates no file naming preference. FileNamingUnset FileNamingMode = "" )
type FluxKustomizationRecord ¶
type FluxKustomizationRecord struct {
Namespace, Name string
Path string
SourceKind string
SourceNamespace string
SourceName string
KubeConfig bool
}
FluxKustomizationRecord is what a Flux Kustomization kure placed or kept in a layout read when the integration ended: its identity, its spec.path as path.Clean leaves it, the Source its spec.sourceRef names (an omitted namespace the Kustomization's own) and whether it sets spec.kubeConfig. fluxcd.UmbrellaTerminals compares records as kure reads identities: Path cleaned, an omitted Namespace "default", an omitted SourceNamespace the record's Namespace.
type FluxPlacement ¶
type FluxPlacement string
FluxPlacement determines how Flux Kustomizations are placed in the layout.
const ( // FluxSeparate places all Flux Kustomizations in a separate directory. FluxSeparate FluxPlacement = "separate" // FluxIntegratedPerLayout places a Flux Kustomization CR inline for every // layout node, including augmenter-added child layouts. Each child's CR is // hosted in its parent layout and listed there as a resource file; the // parent does not reference the child directory. Finest granularity; use // when each child should be reconciled by // its own Flux Kustomization (e.g. hook-group dependsOn). FluxIntegratedPerLayout FluxPlacement = "integrated" // FluxIntegratedPerBundle places Flux Kustomization CRs inline at bundle // boundaries only, each hosted in the parent of the directory it applies; // a bundle's interior (application and augmenter-added child layouts) is a // single kustomize build, with those children referenced as directories. // A child that renders bundles is never referenced: its own CR applies // it. Coarser than PerLayout: Flux reconciles per bundle, kustomize // handles the interior. Use when the unit of Flux reconciliation is the // bundle, not each layout node. FluxIntegratedPerBundle FluxPlacement = "integrated-per-bundle" // FluxUnset indicates no flux placement preference. FluxUnset FluxPlacement = "" )
type GroupingMode ¶
type GroupingMode string
GroupingMode controls how nodes, bundles and applications are laid out on disk.
The default for all grouping modes is GroupByName which creates a directory per entity. GroupFlat places all entities in the same directory.
const ( // GroupByName creates a directory for each item in the hierarchy. GroupByName GroupingMode = "name" // GroupFlat flattens the hierarchy placing all items in the same directory. GroupFlat GroupingMode = "flat" // GroupUnset indicates that no grouping preference was specified. GroupUnset GroupingMode = "" )
type KustomizationFileNameFunc ¶
KustomizationFileNameFunc returns the file name for a Flux Kustomization manifest.
type KustomizationMode ¶
type KustomizationMode string
KustomizationMode determines how kustomization.yaml files reference manifests.
const ( // KustomizationExplicit lists each manifest file in kustomization.yaml. KustomizationExplicit KustomizationMode = "explicit" // KustomizationRecursive writes no kustomization.yaml into the layout's // directory, and every other file as KustomizationExplicit does: a Flux // Kustomization builds the directory from every .yaml and .yml file below // it (go-kure/kure#868). KustomizationRecursive KustomizationMode = "recursive" // KustomizationUnset indicates no kustomization mode preference. KustomizationUnset KustomizationMode = "" )
type LayoutAugmenter ¶
type LayoutAugmenter interface {
AugmentLayout(layout *ManifestLayout) error
}
LayoutAugmenter is an optional interface that ApplicationConfig implementations can implement to attach extra files or configMapGenerator entries to their per-app ManifestLayout after resource generation. The walker invokes AugmentLayout when app.Config satisfies this interface.
A walk calls AugmentLayout once, right after the Generate call it belongs to, on the application's own layout; that layout's Resources are the very objects the call returned. The augmenter reads them there, never from state Generate saved. It runs only where the walk gives the application a layout of its own (see LayoutIntentAugmenter for flat grouping), and never from Application.Generate or Bundle.Generate. Each walk augments a new layout, so for an unchanged config an augmenter adds the same things every time and keeps no state the next call depends on.
The interface lives in the layout package (rather than pkg/stack alongside Validator) because ApplicationConfig — defined in pkg/stack — cannot reference *ManifestLayout without creating an import cycle: the layout package already imports pkg/stack.
type LayoutIntentAugmenter ¶
type LayoutIntentAugmenter interface {
LayoutAugmenter
WantsOwnLayout() bool
}
LayoutIntentAugmenter is an optional companion to LayoutAugmenter for a config whose desire for its own per-app layout varies per instance rather than being fixed for the whole type. Implementing LayoutAugmenter alone is a per-type, presence-only signal: the method either exists or it doesn't, so a config that only wants its own layout for some instance configurations has no way to express that without a separate wrapper type per case. LayoutIntentAugmenter lets such a config implement AugmentLayout unconditionally and answer "do I want the walker to carve me a directory" per instance instead.
WantsOwnLayout() gates placement only, and only where ApplicationGrouping is GroupFlat (in every walker, WalkClusterByPackage included): false is treated as-if-absent for that decision — the app's resources merge into the bundle's layout instead of getting a per-app child, and AugmentLayout is not invoked because no per-app layout exists to pass it. With ApplicationGrouping GroupByName every app already gets its own layout and AugmentLayout runs unconditionally, regardless of augmenter status.
A config that does not implement this interface keeps LayoutAugmenter's existing presence-only behaviour unchanged.
WantsOwnLayout answers from the config alone: the same config gives the same answer on every call.
The interface lives in the layout package for the same import-cycle reason as LayoutAugmenter above.
type LayoutPreset ¶
type LayoutPreset string
LayoutPreset identifies a named layout pattern that configures all layout dimensions into a known-valid combination. Presets are based on the layout patterns defined in the multi-tier FluxCD layout research.
const ( // PresetCentralizedControlPlane implements Pattern A: all Flux KS CRs in // dedicated aggregator directories, completely separate from payload. Best // suited for fleet management with many applications. Uses flat directory // grouping and {kind}-{name}.yaml file naming. PresetCentralizedControlPlane LayoutPreset = "CentralizedControlPlane" // PresetSiblingControlPlane implements Pattern B: Flux KS CRs in a // flux-system/ sibling directory within each artifact. Designed for // single-artifact or per-app artifact scenarios. PresetSiblingControlPlane LayoutPreset = "SiblingControlPlane" // PresetParentDeployedControl implements Pattern C: KS CRs live in the // payload of their parent Kustomization. Best suited for simple, // single-app deployments. PresetParentDeployedControl LayoutPreset = "ParentDeployedControl" )
type LayoutRules ¶
type LayoutRules struct {
// NodeGrouping says whether each child node gets its own directory
// (GroupByName) or is merged into its parent's (GroupFlat): its bundle,
// child nodes and origins then render in the parent's directory. The root
// node always keeps its directory. Defaults to GroupByName.
NodeGrouping GroupingMode
// BundleGrouping says whether each bundle gets its own directory inside
// its node's (GroupByName) or is rendered in the node's directory
// (GroupFlat). The root node's directory renders no bundle: with GroupFlat
// the bundles that would render there share one directory inside it, named
// after the first of them, and a child node of the root with that name is
// refused. Defaults to GroupFlat.
BundleGrouping GroupingMode
// ApplicationGrouping says whether each application gets its own
// directory inside its bundle's (GroupByName) or writes its resources into
// the bundle's directory (GroupFlat). An augmenter application that wants
// its own layout gets a directory either way, and so does every umbrella
// child bundle. The three axes are independent. Defaults to GroupFlat.
ApplicationGrouping GroupingMode
// FilePer sets the default file export mode for resources. Defaults to
// FilePerResource.
FilePer FileExportMode
// ClusterName specifies a cluster name to prepend to all paths.
// When set, creates clusters/{ClusterName}/... structure.
ClusterName string
// FluxPlacement determines how Flux Kustomizations are placed.
// Defaults to FluxSeparate.
FluxPlacement FluxPlacement
// FileNaming is the naming pattern of the manifest files WriteToDisk and
// WriteToTar write, for every layout of the tree: those the walkers
// create, the layouts an augmenter adds and leaves unset (each takes its
// parent's) and the flux-system directory of FluxSeparate. A layout that
// sets its own FileNaming keeps it. WriteManifest names files from its
// Config instead. Defaults to FileNamingDefault
// ({namespace}-{kind}-{name}.yaml).
FileNaming FileNamingMode
// FlattenSingleTier collapses a vestigial intermediate directory layer
// produced by the walker when it adds no semantic value: a parent layout
// with exactly one named child whose own children are empty, which is
// not an UmbrellaChild and which renders no bundle, where the parent
// itself is a top-level layout (Namespace has no path separator) with no
// own Resources.
//
// A directory that renders a bundle is never collapsed: its Flux
// Kustomization is hosted by its parent, and the top of the tree has
// none. In a walked tree that leaves one case: a single child directory
// that renders no bundle and has no directory below it. That is a node
// with neither a bundle nor child nodes, or, under NodeGrouping flat, a
// node with the bundle-less nodes below it merged into it.
//
// Only effective for WalkCluster (not WalkClusterByPackage, which uses
// synthetic unnamed wrappers to express package boundaries).
//
// The absorbing layout takes over the collapsed layout's origin nodes.
// Nothing is rewritten afterwards: a Flux CR a caller adds to the walked
// tree keeps the spec.path it was given.
FlattenSingleTier bool
}
LayoutRules control how layouts are generated.
Zero values are interpreted as the defaults described in the field documentation.
func DefaultLayoutRules ¶
func DefaultLayoutRules() LayoutRules
DefaultLayoutRules returns a LayoutRules instance populated with the documented default values.
func LayoutRulesForPreset ¶
func LayoutRulesForPreset(p LayoutPreset) (LayoutRules, error)
LayoutRulesForPreset returns LayoutRules configured for the given preset. Unknown presets return an error.
Example ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/stack/layout"
)
func main() {
rules, err := layout.LayoutRulesForPreset(layout.PresetCentralizedControlPlane)
if err != nil {
panic(err)
}
cfg, err := layout.ConfigForPreset(layout.PresetCentralizedControlPlane)
if err != nil {
panic(err)
}
fmt.Println(rules.FluxPlacement, rules.NodeGrouping, rules.FileNaming, cfg.KustomizationFileName("web"))
}
Output: separate flat kind-name kustomization-web.yaml
func (LayoutRules) Validate ¶
func (lr LayoutRules) Validate() error
Validate ensures the LayoutRules contain known option values and a ClusterName the writers can write: one without a ".." path segment. An unset value is valid; it takes its documented default. WalkCluster and WalkClusterByPackage validate the rules they are given before they build anything, so no caller has to (go-kure/kure#979).
type ManifestFileNameFunc ¶
type ManifestFileNameFunc func(namespace, kind, name string, mode FileExportMode) string
ManifestFileNameFunc returns a file name for the given namespace, kind and resource name.
type ManifestLayout ¶
type ManifestLayout struct {
Name string
Namespace string
PackageRef *schema.GroupVersionKind
FilePer FileExportMode
ApplicationFileMode ApplicationFileMode
Mode KustomizationMode
FluxPlacement FluxPlacement // Track flux placement mode for kustomization generation
// FileNaming is the naming pattern of this layout's resource files under
// WriteToDisk and WriteToTar. The writers read it from the layout itself,
// never from its parent: the walkers set it from LayoutRules.FileNaming,
// and give a layout an augmenter added and left unset its parent's.
FileNaming FileNamingMode
Resources []client.Object
Children []*ManifestLayout
// ExtraFiles are arbitrary files written alongside resource YAMLs in this
// layout's directory. Typical use: a values.yaml referenced by a
// configMapGenerator entry. Augmenters (LayoutAugmenter) attach these.
ExtraFiles []ExtraFile
// ConfigMapGenerators emit a kustomize configMapGenerator: section in
// kustomization.yaml. kustomize appends a content-hash suffix to each
// generated ConfigMap name; resources referencing it (e.g.
// HelmRelease.spec.valuesFrom) are rewritten to the suffixed name on
// build, so any change to the source file forces re-reconciliation.
ConfigMapGenerators []ConfigMapGeneratorSpec
// UmbrellaChild marks this layout as rendered from a Bundle.Children
// entry. When true, the parent's kustomization.yaml does not list it: the
// child is applied by its own Flux Kustomization, which the layout
// integrator places at the parent layout node (integrated placement) or
// in flux-system (separate placement), with spec.path = this layout's
// directory.
UmbrellaChild bool
// DependsOn lists what this layout's Flux Kustomization CR waits for.
// Augmenters (LayoutAugmenter) set this field; on a node's own layout the
// walker fills it from Node.NamedDependsOn.
//
// On an application or augmenter layout an entry is read as a layout name
// first: that of a sibling, or of another layout below the same bundle's
// directory. The Flux layout integrator then writes the name of that
// layout's CR, which is not the layout's ("<unit>-<layout name>", or its
// KustomizationName). An entry that names no such layout is written as
// given, as a Kustomization name: the CR of a node layout that renders no
// bundle is named "<path with / replaced by ->-node" unless the node names
// it, and that is the name to list. On a node's own layout every entry is
// a Kustomization name and is written as given; an entry the node lists
// in NamedDependsOn and this field lacks (the node got it after the walk)
// is refused by the integrator.
//
// The integrator writes spec.dependsOn only on the Kustomization CR it
// generates for this layout itself, which it does only under
// FluxIntegratedPerLayout and only for a child layout that is not an
// umbrella child, is not AppFileSingle and renders no bundle. In every
// other case the integrator, and ResourceGenerator.GenerateFromLayout,
// refuse the field (go-kure/kure#1032): under FluxIntegratedPerBundle and
// FluxSeparate an augmenter that orders its layouts is refused, and only
// FluxIntegratedPerLayout carries the ordering: integrate an augmenter
// that orders its layouts with FluxIntegratedPerLayout. What a node sets is refused on the node's own fields, by the
// node's path, and not again on the layout that carries it.
DependsOn []string
// KustomizationName names the Flux Kustomization the layout integrator
// generates for this layout in FluxIntegratedPerLayout mode, instead of
// the default: "<unit>-<layout name>" for an application or augmenter
// layout, the "-node" name for a node's own layout. An augmenter sets it
// on a layout it creates; the walker fills it from Node.KustomizationName
// on a node's own layout. A name a caller sets on a walked node layout
// wins over the node's; a node that has a name while its layout carries
// none (the node got it after the walk) is refused by the integrator.
// Like DependsOn it is read only where the
// layout gets a Kustomization of its own, and refused anywhere else.
// The name in effect, set or
// default, must be one Flux can reconcile
// (stack.ValidateKustomizationName): the integrator refuses any other
// where it creates the Kustomization. It shortens a "<unit>-<Name>"
// default over the limit, keeping the "-<Name>" tail where Name has at
// most 54 characters, and keeping the first 54 bytes of a longer Name,
// without the hyphens and dots that end them, before the hash (the hash
// alone where nothing is left of them). A name set here is not
// shortened, so one that is too long is refused.
KustomizationName string
// Wait, Timeout, RetryInterval, Labels and Annotations are settings of the
// Flux Kustomization the layout integrator generates for this layout in
// FluxIntegratedPerLayout mode: its spec.wait, spec.timeout and
// spec.retryInterval, and the labels and annotations of the Kustomization
// object itself. No object in the layout's directory gets them. Like
// KustomizationName they are read only where the layout gets a
// Kustomization of its own, and are refused anywhere else.
//
// An application's own layout, and every layout below it (the ones its
// LayoutAugmenter added), inherits the five from the bundle that holds the
// application. Wait, Timeout and RetryInterval left unset here are the
// bundle's, and set here they replace it: a Wait that points at false
// turns an inherited wait off, while an inherited Timeout or RetryInterval
// can be replaced but not removed. Labels and Annotations are merged with
// the bundle's per key and the value set here wins, so a key the bundle
// sets can be given another value but not dropped. Any other layout (a
// node's own, one a caller added to the tree) inherits nothing: its
// Kustomization carries what is set here.
//
// Timeout and RetryInterval must parse as a Go duration ("5m"). Where the
// integrator creates the Kustomization it refuses any other value, and a
// label or annotation the Kubernetes API does not accept.
Wait *bool
Timeout string
RetryInterval string
Labels map[string]string
Annotations map[string]string
// Interval, Prune, Force and Suspend are four more settings of that
// Kustomization (go-kure/kure#1021): its spec.interval, spec.prune,
// spec.force and spec.suspend. They are read where the five above are and
// refused anywhere else, and they follow the same rule:
// set here, a value replaces the one of the bundle that holds the
// application; left unset, it is that bundle's. A Prune, Force or Suspend
// that points at false turns an inherited true off.
//
// Where neither the layout nor a holding bundle sets one, Interval and
// Prune are the generator's (ResourceGenerator.DefaultInterval and
// ResourceGenerator.Prune), and Force and Suspend are left out. Interval
// must parse as a Go duration and be one Flux takes; the integrator
// refuses any other value where it creates the Kustomization.
//
// The patches and the postBuild substitution of that Kustomization have
// no field here: they are the holding bundle's (Bundle.Patches,
// Bundle.PostBuild), and a layout without a holding bundle has none.
Interval string
Prune *bool
Force *bool
Suspend *bool
// contains filtered or unexported fields
}
func WalkCluster ¶
func WalkCluster(c *stack.Cluster, rules LayoutRules) (*ManifestLayout, error)
WalkCluster traverses a stack.Cluster and builds a ManifestLayout tree that mirrors the node, bundle and application hierarchy. Each grouping axis of rules decides whether its level gets a directory (see grouping). The rules are validated first, as given (LayoutRules.Validate); unset values then take their defaults.
Example ¶
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/go-kure/kure/pkg/kubernetes"
"github.com/go-kure/kure/pkg/stack"
"github.com/go-kure/kure/pkg/stack/layout"
)
// exampleApp is a minimal stack.ApplicationConfig: one ConfigMap named after
// the application.
type exampleApp struct{}
func (exampleApp) Generate(app *stack.Application) ([]*client.Object, error) {
var obj client.Object = kubernetes.CreateConfigMap(app.Name, app.Namespace)
return []*client.Object{&obj}, nil
}
// exampleCluster is the cluster the examples walk: a root node "apps" whose
// bundle "web" holds the applications "api" and "ui".
func exampleCluster() *stack.Cluster {
cluster, err := stack.NewClusterBuilder("prod").
WithNode("apps").
WithBundle("web").
WithApplication("api", exampleApp{}).
WithApplication("ui", exampleApp{}).
End().
End().
Build()
if err != nil {
panic(err)
}
return cluster
}
// printFiles prints every file below dir, relative to it.
func printFiles(dir string) {
err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err == nil && !d.IsDir() {
rel, _ := filepath.Rel(dir, path)
fmt.Println(rel)
}
return err
})
if err != nil {
panic(err)
}
}
func main() {
cluster := exampleCluster()
out, err := os.MkdirTemp("", "kure-layout-example")
if err != nil {
panic(err)
}
defer func() { _ = os.RemoveAll(out) }()
// Create layout rules
rules := layout.DefaultLayoutRules()
rules.BundleGrouping = layout.GroupFlat
rules.ApplicationGrouping = layout.GroupFlat
// Walk cluster to create layout
ml, err := layout.WalkCluster(cluster, rules)
if err != nil {
panic(err)
}
// Write to disk
cfg := layout.DefaultLayoutConfig()
err = layout.WriteManifest(filepath.Join(out, "out/manifests"), cfg, ml)
if err != nil {
panic(err)
}
printFiles(out)
}
Output: out/manifests/clusters/apps/kustomization.yaml out/manifests/clusters/apps/web/cluster-configmap-api.yaml out/manifests/clusters/apps/web/cluster-configmap-ui.yaml out/manifests/clusters/apps/web/kustomization.yaml
func (*ManifestLayout) FluxBuild ¶
func (ml *ManifestLayout) FluxBuild() bool
FluxBuild reports what SetFluxBuild last recorded.
func (*ManifestLayout) FluxKustomizations ¶
func (ml *ManifestLayout) FluxKustomizations() []FluxKustomizationRecord
FluxKustomizations returns a copy of what SetFluxKustomizations last recorded: nil when nothing was.
func (*ManifestLayout) FullRepoPath ¶
func (ml *ManifestLayout) FullRepoPath() string
FullRepoPath returns the layout's directory: Namespace joined with Name. Namespace is always the parent's path ("." for the tree root); an empty Namespace means "cluster". A child whose Namespace is already its own path nests one level deeper (go-kure/kure#771), and the writers refuse it where its parent lists it (go-kure/kure#979); set Namespace to the parent path.
func (*ManifestLayout) FullRepoPathWithPackage ¶
func (ml *ManifestLayout) FullRepoPathWithPackage() string
FullRepoPathWithPackage returns the repository path including package-specific prefix
func (*ManifestLayout) OriginApplication ¶
func (ml *ManifestLayout) OriginApplication() *stack.Application
OriginApplication returns the application a per-app layout renders, or nil.
func (*ManifestLayout) OriginApplicationObjects ¶
func (ml *ManifestLayout) OriginApplicationObjects() []ApplicationObjects
OriginApplicationObjects returns, for a layout that renders bundles, what each application of those bundles rendered, in emission order: the record a workflow uses to act on one application's objects (a delivery intent, say). The layout package applies nothing to them. Nil for a hand-built layout and for a layout that renders no bundle.
func (*ManifestLayout) OriginBundleObjects ¶
func (ml *ManifestLayout) OriginBundleObjects(b *stack.Bundle) []client.Object
OriginBundleObjects returns the objects bundle b's applications render in this layout's directory or its per-app directories. Nil when b is not one of OriginBundles. A ConfigMap a configMapGenerator builds is among them as a stand-in: its kind and name, and the annotations its entry sets at the time of the call. Only the stand-ins of the applications b emitted when the layout was walked are brought up to date, even if b.Applications has changed since: a call for another bundle of this layout does not refresh them, an application two bundles list included. The slice is the layout's own record, not a copy, so a write to an element changes it.
func (*ManifestLayout) OriginBundles ¶
func (ml *ManifestLayout) OriginBundles() []*stack.Bundle
OriginBundles returns the bundles whose resources this layout's directory holds. Nil for a hand-built layout.
func (*ManifestLayout) OriginNodes ¶
func (ml *ManifestLayout) OriginNodes() []*stack.Node
OriginNodes returns the stack nodes whose directory this layout is. Nil for a hand-built layout and for bundle, application and augmenter layouts.
func (*ManifestLayout) OriginUnit ¶
func (ml *ManifestLayout) OriginUnit() *ManifestLayout
OriginUnit returns the child layout that renders the bundles a flat BundleGrouping merges into this layout's node: the root node's layout renders no bundle, so they have one directory inside it (go-kure/kure#979). Nil for every other layout, and under BundleGrouping by name, where each bundle has a directory of its own.
func (*ManifestLayout) SameDirectory ¶
func (ml *ManifestLayout) SameDirectory(other *ManifestLayout) bool
SameDirectory reports whether the directories of ml and other, each written as a directory, are one directory to the writers: the FullRepoPath resolved under the output directory (a leading slash dropped) and cleaned, compared without regard to case. A Name such as "/web" or "./web" resolves to the directory of "web", and the writers refuse a tree in which two layouts share a directory. It says nothing about a layout a writer writes as a single file (AppFileSingle), which has no directory of its own. WriteToDisk with an empty base path is the one writer call it does not describe: that call has no output directory to resolve a rooted path under, and writes it as an absolute path.
func (*ManifestLayout) SetFluxBuild ¶
func (ml *ManifestLayout) SetFluxBuild(b bool)
SetFluxBuild records whether a Flux Kustomization kure generated builds this layout's directory: its spec.path names the directory, or it is the root of a tree whose integration generated one (the Flux bootstrap applies the root). Only fluxcd's LayoutIntegrator sets it; a caller that places Flux Kustomizations itself, from fluxcd's GenerateFromLayout or its own code, marks their spec.path layouts here. For a KustomizationRecursive layout so marked the writers refuse a directory that holds no file and a build that differs from what the Explicit mode would build (see checkRecursiveLayouts).
func (*ManifestLayout) SetFluxKustomizations ¶
func (ml *ManifestLayout) SetFluxKustomizations(recs []FluxKustomizationRecord)
SetFluxKustomizations records the Flux Kustomizations kure placed or kept in this layout, replacing any earlier record; in memory only, never serialised. Only fluxcd's LayoutIntegrator sets it, on every layout of a tree it integrates, as the last step of an integration that succeeds (a refused one leaves every record as it was); a caller that places Flux Kustomizations itself records them here to have fluxcd.UmbrellaTerminals read them as the integration's. The slice is copied.
func (*ManifestLayout) WriteToDisk ¶
func (ml *ManifestLayout) WriteToDisk(basePath string) error
WriteToDisk writes the layout tree under basePath. It refuses a tree in which two layouts resolve to the same directory (see checkLayoutTree) before writing anything.
func (*ManifestLayout) WriteToTar ¶
func (ml *ManifestLayout) WriteToTar(w io.Writer) error
WriteToTar writes the ManifestLayout to a tar archive, mirroring the directory structure that WriteToDisk would produce. File paths use forward slashes and output is deterministic (sorted file names). It refuses a tree in which two layouts resolve to the same directory (see checkLayoutTree) before writing any entry.
type OriginIndex ¶
type OriginIndex struct {
// contains filtered or unexported fields
}
OriginIndex resolves the stack objects of one cluster to the layouts that render them. Build it with IndexOrigins.
func IndexOrigins ¶
func IndexOrigins(root *ManifestLayout, c *stack.Cluster) (*OriginIndex, error)
IndexOrigins indexes a layout tree walked from cluster c (WalkCluster) by the origins its layouts record. It refuses:
- a bundle or node rendered by two layouts;
- a tree whose rendered set differs from the bundles and nodes reachable from c (node bundles plus their umbrella descendants), naming what is missing or foreign — so a hand-built, partial or other-cluster tree is refused;
- two bundles with one Name: the name is the bundle's identity, by which a copy of it is resolved;
- two bundles whose Flux Kustomization or ArgoCD Application would get one name (Bundle.UnitName: KustomizationName, or Name without it), naming both bundles by their paths;
- a layout rendering a node or bundle in AppFileSingle mode: it is written into its Namespace, not into its own directory;
- a DependsOn bundle that is a copy of a rendered bundle (another bundle with its Name, which UnitName resolves to it) and sets a KustomizationName other than the rendered bundle's name in effect, naming both. A copy that leaves the field empty is the rendered bundle;
- such a copy of a bundle whose Kustomization name is also in the dependant's NamedDependsOn: one dependency in both lists, which Bundle.Validate cannot see through the copy. stack.ValidateCluster refuses both in the same words (see checkDependencyCopies);
- a layout that is a bundle's own directory (an umbrella child, or a node's bundle under BundleGrouping GroupByName) whose Name is not the bundle's directory name, its DirName or else its Name: the directory is named on the bundle, not by renaming the layout after the walk. A node layout that renders a differently named bundle is not affected;
- two bundles whose own directories are one, compared as the writers compare them (SameDirectory), so two DirNames that differ in case only are one: each would get a Kustomization or Application for that one directory. Both are named by their paths (the writers refuse the same tree in the same words, see checkLayoutTree);
- a dependency cycle between reconciliation units (see Units).
func (*OriginIndex) BundleLayout ¶
func (ix *OriginIndex) BundleLayout(b *stack.Bundle) *ManifestLayout
BundleLayout returns the layout whose directory holds b's resources, or nil.
func (*OriginIndex) Bundles ¶
func (ix *OriginIndex) Bundles() []*stack.Bundle
Bundles returns every rendered bundle in layout pre-order (a layout's own bundles before its children's).
func (*OriginIndex) KustomizationPath ¶
func (ix *OriginIndex) KustomizationPath(b *stack.Bundle) (string, error)
KustomizationPath returns the directory of the layout that renders b: the one path rule for a bundle's Flux Kustomization spec.path and ArgoCD Application source.path, relative to the writer's output root.
func (*OriginIndex) NodeLayout ¶
func (ix *OriginIndex) NodeLayout(n *stack.Node) *ManifestLayout
NodeLayout returns the layout whose directory is n's, or nil.
func (*OriginIndex) Parent ¶
func (ix *OriginIndex) Parent(ml *ManifestLayout) *ManifestLayout
Parent returns ml's parent layout in the indexed tree, or nil for the root.
func (*OriginIndex) UnitDependencies ¶
func (ix *OriginIndex) UnitDependencies(l *ManifestLayout) []string
UnitDependencies returns the units the unit of layout l depends on through the DependsOn of the bundles it renders: each dependency mapped to the unit that applies it, in order and without repeats. A dependency applied by l's own unit is dropped: the bundles are applied together.
func (*OriginIndex) UnitName ¶
func (ix *OriginIndex) UnitName(b *stack.Bundle) string
UnitName returns the name of the reconciliation unit that applies bundle b: the name in effect (Bundle.UnitName) of the first bundle the layout rendering b renders. b is resolved by its Name, which IndexOrigins proves unique, so a copy of a rendered bundle (the fluent builder copies bundles) resolves like the original, whatever KustomizationName the copy carries (IndexOrigins refuses a DependsOn copy that sets another one than the rendered bundle's name in effect). A bundle outside the index keeps its own name in effect.
func (*OriginIndex) UnitNamedDependencies ¶
func (ix *OriginIndex) UnitNamedDependencies(l *ManifestLayout) []string
UnitNamedDependencies is UnitDependencies for the bundles' NamedDependsOn: a name that is a rendered bundle's Kustomization name is mapped to its unit (and dropped when that is l's own), any other name is kept as the external dependency it is.
func (*OriginIndex) UnitOfName ¶
func (ix *OriginIndex) UnitOfName(name string) string
UnitOfName maps the name of a rendered bundle's Kustomization or Application (Bundle.UnitName) to the name of the unit that applies the bundle; a name no rendered bundle has in effect (an external Kustomization, say) is returned unchanged. A bundle's Name is not looked up: it resolves only where it is some bundle's name in effect. References to a bundle's Kustomization by name — health checks, dependencies — resolve through it.
func (*OriginIndex) Units ¶
func (ix *OriginIndex) Units() []*ManifestLayout
Units returns the layouts that render bundles, in layout pre-order. Each is one reconciliation unit: the directory is what a Flux Kustomization or an ArgoCD Application applies, so the bundles a grouping axis merged into one directory share one, named after the first of them (UnitName).