Documentation
¶
Overview ¶
Package fn provides the SDK to write KRM functions.
Before you start ¶
This fn SDK requires some basic KRM function Specification knowledge. To make the best usage of your time, we recommend you to be familiar with "ResourceList" before moving forward.
The KRM Function Specification, or "ResourceList", defines the standards of the inter-process communication between the orchestrator (i.e. kpt CLI) and functions.
See KRM Function Specification reference in https://github.com/kubernetes-sigs/kustomize/blob/master/cmd/config/docs/api-conventions/functions-spec.md
KRM Function ¶
A KRM function can mutate and/or validate Kubernetes resources in a ResourceList.
The ResourceList type and the KubeObject type are the core parts of this package. The ResourceList type maps to the ResourceList in the function spec.
Read more about how to use KRM functions in https://kpt.dev/book/04-using-functions/
Read more about how to develop a KRM function in https://kpt.dev/book/05-developing-functions/
A general workflow is:
- Reads the "ResourceList" object from STDIN.
- Gets the function configs from the "ResourceList.FunctionConfig".
- Mutate or validate the Kubernetes YAML resources from the "ResourceList.Items" field with the function configs.
- Writes the modified "ResourceList" to STDOUT.
- Write function message to "ResourceList.Results" with severity "Info", "Warning" or "Error"
KubeObject ¶
The KubeObject is the basic unit to perform operations on KRM resources.
In the "AsMain", both "Items" and "FunctionConfig" are converted to the KubeObject(s).
If you are familiar with unstructured.Unstructured, using KubeObject is as simple as using unstructured.Unstructured. You can call function like `NestedStringOrDie` `SetNestedStringMap`, etc.
Except that KubeObject will not have pass-in interface arguments, nor will return an interface. Instead, you shall treat each KubeObject field (slice, or non-string map)as SubObject.
SubObject also have most of the KubeObject methods, except the MetaType or NameType specific methods like "GetNamespace", "SetLabel". This is because SubObject is designed as a sub object of KubeObject. SubObject to KubeObject is like `spec` section to `Deployment`. You can get the Deployment name from `metadata.name`, KubeObject.GetName() or KubeObject.NestedString("metadata", "name"). But you cannot get "metadata.name" from a Deployment "spec". For "spec" SubObject, you can get the ".replicas" field by SubObject.NestedInt64("replicas")
Besides unstructured style, another way to use KubeObject is to purely work on the KubeObject/SubObject by calling "GetMap", "GetSlice", "UpsertMap" which expects the return to be SubObject(s) pointer.
AsMain ¶
"AsMain" is the main entrypoint. In most cases, you only need to provide the mutator or validation logic and have AsMain handles the ResourceList parsing, KRM resource field type detection, read from STDIN and write to STDOUT.
"AsMain" accepts a struct that either implement the ResourceListProcessor interface or Runner interface.
See github.com/kptdev/krm-functions-sdk/go/fn/examples for detailed usage.
Package fn is the SDK for go krm functions.
Index ¶
- Constants
- Variables
- func ApplyFnBySelector(rl *ResourceList, selector func(obj *KubeObject) bool, ...) error
- func AsMain(input interface{}) error
- func CheckResourceDuplication(rl *ResourceList) error
- func EmptyFunctionConfig(o *KubeObject) bool
- func Execute(p ResourceListProcessor, r io.Reader, w io.Writer) error
- func HasAnnotations(annotations map[string]string) func(*KubeObject) bool
- func HasLabels(labels map[string]string) func(*KubeObject) bool
- func IsGVK(group, version, kind string) func(*KubeObject) bool
- func IsGroupKind(gk schema.GroupKind) func(*KubeObject) bool
- func IsGroupVersionKind(gvk schema.GroupVersionKind) func(*KubeObject) bool
- func IsKrmResourceFile(path string) bool
- func IsLocalConfig(o *KubeObject) bool
- func IsMetaResource() func(*KubeObject) bool
- func IsName(name string) func(*KubeObject) bool
- func IsNamespace(namespace string) func(*KubeObject) bool
- func Log(in ...interface{})
- func Logf(format string, in ...interface{})
- func Not(f func(*KubeObject) bool) func(o *KubeObject) bool
- func ParseGroupVersion(apiVersion string) (group, version string)
- func PathOfKubeObject(node *KubeObject) string
- func Run(p ResourceListProcessor, input []byte) ([]byte, error)
- func WriteKubeObjectsToPackage(objs KubeObjects) (map[string]string, error)
- func WriteKubeObjectsToString(objs KubeObjects) (string, error)
- type Context
- type ErrAttemptToTouchUpstreamIdentifier
- type ErrInternalAnnotation
- type ErrMissingFnConfig
- type ErrUnmatchedField
- type Field
- type File
- type KubeObject
- func CopyToKubeObject(rn *yaml.RNode) *KubeObject
- func MoveToKubeObject(rn *yaml.RNode) *KubeObject
- func NewEmptyKubeObject() *KubeObject
- func NewFromTypedObject(v interface{}) (*KubeObject, error)
- func NewKubeObjectFromMap(m map[string]interface{}) (*KubeObject, error)
- func NewKubeObjectFromResourceNode(rn *yaml.RNode) *KubeObject
- func ParseKubeObject(in []byte) (*KubeObject, error)
- func ParseKubeObjects(in []byte) ([]*KubeObject, error)
- func (o *KubeObject) Copy() *KubeObject
- func (o *KubeObject) CopyToResourceNode() *yaml.RNode
- func (o *KubeObject) GetAPIVersion() string
- func (o *KubeObject) GetAnnotation(k string) string
- func (o *KubeObject) GetAnnotations() map[string]string
- func (o *KubeObject) GetGKNNString() string
- func (o *KubeObject) GetID() *ResourceIdentifier
- func (o *KubeObject) GetKind() string
- func (o *KubeObject) GetLabel(k string) string
- func (o *KubeObject) GetLabels() map[string]string
- func (o *KubeObject) GetName() string
- func (o *KubeObject) GetNamespace() string
- func (o *KubeObject) GetOriginID() (*ResourceIdentifier, error)
- func (o *KubeObject) GetPackageScopeUniqueID() PackageScopeUniqueID
- func (o *KubeObject) GroupKind() schema.GroupKind
- func (o *KubeObject) GroupVersionKind() schema.GroupVersionKind
- func (o *KubeObject) HasAnnotations(annotations map[string]string) bool
- func (o *KubeObject) HasLabels(labels map[string]string) bool
- func (o *KubeObject) HasNamespace() bool
- func (o *KubeObject) HasSameID(b *KubeObject) bool
- func (o *KubeObject) HasUpstreamOrigin() bool
- func (o *KubeObject) HeadComment(fields ...string) (string, bool, error)
- func (o *KubeObject) IDAnnotation() int
- func (o *KubeObject) IndexAnnotation() int
- func (o *KubeObject) IsClusterScoped() bool
- func (o *KubeObject) IsEmpty() bool
- func (o *KubeObject) IsGVK(group, version, kind string) bool
- func (o *KubeObject) IsGroupKind(gk schema.GroupKind) bool
- func (o *KubeObject) IsGroupVersionKind(gvk schema.GroupVersionKind) bool
- func (o *KubeObject) IsLocalConfig() bool
- func (o *KubeObject) IsNamespaceScoped() bool
- func (o *KubeObject) LineComment(fields ...string) (string, bool, error)
- func (o *KubeObject) MoveToResourceNode() *yaml.RNode
- func (o *KubeObject) PathAnnotation() string
- func (o *KubeObject) RemoveAnnotation(k string) error
- func (o *KubeObject) RemoveAnnotationsIfEmpty() error
- func (o *KubeObject) RemoveLabel(k string) error
- func (o *KubeObject) SetAPIVersion(apiVersion string) error
- func (o *KubeObject) SetAnnotation(k, v string) error
- func (o *KubeObject) SetHeadComment(comment string, fields ...string) error
- func (o *KubeObject) SetIndexAnnotation(index int) error
- func (o *KubeObject) SetKind(kind string) error
- func (o *KubeObject) SetLabel(k, v string) error
- func (o *KubeObject) SetLineComment(comment string, fields ...string) error
- func (o *KubeObject) SetName(name string) error
- func (o *KubeObject) SetNamespace(name string) error
- func (o *KubeObject) SetPathAnnotation(path string) error
- func (o *KubeObject) ShortString() string
- type KubeObjects
- func MoveToKubeObjects(rns []*yaml.RNode) KubeObjects
- func ReadKubeObjectsFromDirectory(path string) (KubeObjects, error)
- func ReadKubeObjectsFromFile(filepath string, content string) (KubeObjects, error)
- func ReadKubeObjectsFromPackage(inputFiles map[string]string) (objs KubeObjects, extraFiles map[string]string, err error)
- func (kos KubeObjects) CopyToResourceNodes() kio.ResourceNodeSlice
- func (kos KubeObjects) EnsureSingleItem() (*KubeObject, error)
- func (kos KubeObjects) EnsureSingleItemAs(out any) error
- func (kos KubeObjects) GetRootKptfile() *KubeObject
- func (kos KubeObjects) Len() int
- func (kos KubeObjects) Less(i, j int) bool
- func (kos KubeObjects) SetAnnotation(key, value string) error
- func (kos KubeObjects) Split(predicate func(o *KubeObject) bool) (KubeObjects, KubeObjects)
- func (kos KubeObjects) String() string
- func (kos KubeObjects) Swap(i, j int)
- func (kos *KubeObjects) Upsert(newObj *KubeObject)
- func (kos *KubeObjects) UpsertTypedObject(newObj any) error
- func (kos KubeObjects) Where(f func(*KubeObject) bool) KubeObjects
- func (kos KubeObjects) WhereNot(f func(o *KubeObject) bool) KubeObjects
- type PackageScopeUniqueID
- type ResourceIdentifier
- type ResourceList
- type ResourceListProcessor
- type ResourceListProcessorFunc
- type ResourceRef
- type Result
- func ConfigFileResult(msg, path string, severity Severity) *Result
- func ConfigObjectResult(msg string, obj *KubeObject, severity Severity) *Result
- func ErrorConfigFileResult(err error, path string) *Result
- func ErrorConfigObjectResult(err error, obj *KubeObject) *Result
- func ErrorResult(err error) *Result
- func GeneralResult(msg string, severity Severity) *Result
- type Results
- func (r Results) Error() string
- func (r *Results) ErrorE(err error)
- func (r *Results) Errorf(format string, a ...any)
- func (r Results) ExitCode() int
- func (r *Results) Infof(format string, a ...any)
- func (r Results) Sort()
- func (r *Results) String() string
- func (r *Results) WarningE(err error)
- func (r *Results) Warningf(format string, a ...any)
- type Runner
- type Severity
- type SliceSubObjects
- type SubObject
- func (o *SubObject) As(ptr interface{}) error
- func (o *SubObject) Bytes() []byte
- func (o *SubObject) GetBool(k string) bool
- func (o *SubObject) GetInt(k string) int64
- func (o *SubObject) GetMap(k string) *SubObject
- func (o *SubObject) GetSlice(k string) SliceSubObjects
- func (o *SubObject) GetString(k string) string
- func (o *SubObject) HasField(key string) bool
- func (o *SubObject) IsEmpty() bool
- func (o *SubObject) NestedBool(fields ...string) (bool, bool, error)
- func (o *SubObject) NestedFloat64(fields ...string) (float64, bool, error)
- func (o *SubObject) NestedInt(fields ...string) (int, bool, error)
- func (o *SubObject) NestedInt64(fields ...string) (int64, bool, error)
- func (o *SubObject) NestedResource(ptr interface{}, fields ...string) (bool, error)
- func (o *SubObject) NestedSlice(fields ...string) (SliceSubObjects, bool, error)
- func (o *SubObject) NestedString(fields ...string) (string, bool, error)
- func (o *SubObject) NestedStringMap(fields ...string) (map[string]string, bool, error)
- func (o *SubObject) NestedStringSlice(fields ...string) ([]string, bool, error)
- func (o *SubObject) NestedSubObject(fields ...string) (SubObject, bool, error)
- func (o *SubObject) RemoveNestedField(fields ...string) (bool, error)
- func (o *SubObject) Set(newValue *SubObject) error
- func (o *SubObject) SetFromTypedObject(newValue any) error
- func (o *SubObject) SetMap(mapObj *SubObject, k string) error
- func (o *SubObject) SetNestedBool(value bool, fields ...string) error
- func (o *SubObject) SetNestedField(val interface{}, fields ...string) error
- func (o *SubObject) SetNestedInt(value int, fields ...string) error
- func (o *SubObject) SetNestedString(value string, fields ...string) error
- func (o *SubObject) SetNestedStringMap(value map[string]string, fields ...string) error
- func (o *SubObject) SetNestedStringSlice(value []string, fields ...string) error
- func (o *SubObject) SetSlice(objects SliceSubObjects, field string) error
- func (o *SubObject) String() string
- func (o *SubObject) UpdateNestedStringMap(values map[string]string, fields ...string) error
- func (o *SubObject) UpsertMap(k string) *SubObject
Constants ¶
const ( // IndexAnnotation records the index of a specific resource in a file or input stream. IndexAnnotation string = internalPrefix + "index" // PathAnnotation records the path to the file the Resource was read from PathAnnotation string = internalPrefix + "path" // SeqIndentAnnotation records the sequence nodes indentation of the input resource SeqIndentAnnotation string = internalPrefix + "seqindent" // IDAnnotation records the id of the resource to map inputs to outputs IDAnnotation string = internalPrefix + "id" // InternalAnnotationsMigrationResourceIDAnnotation is used to uniquely identify // resources during round trip to and from a function execution. We will use it // to track the internal annotations and reconcile them if needed. InternalAnnotationsMigrationResourceIDAnnotation = internalPrefix + "annotations-migration-resource-id" // ConfigPrefix is the prefix given to the custom kubernetes annotations. ConfigPrefix string = "config.kubernetes.io/" // KptLocalConfig marks a KRM resource to be skipped from deploying to the cluster via `kpt live apply`. KptLocalConfig = ConfigPrefix + "local-config" )
const ( // KptUseOnlyPrefix is the prefix of kpt-only annotations. Users are not expected to touch these annotations. KptUseOnlyPrefix = "internal.kpt.dev/" // UpstreamIdentifier is the annotation to record a resource's upstream origin. // It is in the form of <GROUP>|<KIND>|<NAMESPACE>|<NAME> UpstreamIdentifier = KptUseOnlyPrefix + "upstream-identifier" // UnknownNamespace is the special char for cluster-scoped or unknown-scoped resources. This is only used in upstream-identifier UnknownNamespace = "~C" // DefaultNamespace is the actual namespace value if a namespace-scoped resource has its namespace field unspecified. DefaultNamespace = "default" )
For Kpt use only constants
const ( // KptFunctionGroup is the group name for the KRM resource which defines the configuration of a function execution. // See KRM function specification `ResourceList.FunctionConfig` KptFunctionGroup = "fn.kpt.dev" // KptFunctionGroup is the version for the KRM resource which defines the configuration of a function execution. // See KRM function specification `ResourceList.FunctionConfig` KptFunctionVersion = "v1alpha1" // KptFunctionGroup is the ApiVersion for the KRM resource which defines the configuration of a function execution. // See KRM function specification `ResourceList.FunctionConfig` KptFunctionAPIVersion = KptFunctionGroup + "/" + KptFunctionVersion )
For KPT Function Configuration
Variables ¶
var MatchAllKRM = append([]string{kptfilev1.KptFileName}, kio.MatchAll...)
Functions ¶
func ApplyFnBySelector ¶
func ApplyFnBySelector(rl *ResourceList, selector func(obj *KubeObject) bool, fn func(obj *KubeObject) error) error
ApplyFnBySelector iterates through every object in ResourceList.items, and if it satisfies the selector, fn will be applied on it.
func AsMain ¶
func AsMain(input interface{}) error
AsMain evaluates the ResourceList from STDIN to STDOUT. `input` can be - a `ResourceListProcessor` which implements `Process` method - a function `Runner` which implements `Run` method
func CheckResourceDuplication ¶
func CheckResourceDuplication(rl *ResourceList) error
CheckResourceDuplication checks the GVKNN of resourceList.items to make sure they are unique. It returns errors if found more than one resource having the same GVKNN.
func EmptyFunctionConfig ¶
func EmptyFunctionConfig(o *KubeObject) bool
EmptyFunctionConfig is a workaround solution to handle the case where kpt passes in a functionConfig placeholder (Configmap with empty `data`) if user does not provide the actual FunctionConfig. Ideally, kpt should pass in an empty FunctionConfig object.
func HasAnnotations ¶
func HasAnnotations(annotations map[string]string) func(*KubeObject) bool
HasAnnotations returns a function that checks if a KubeObject has all the given annotations.
func HasLabels ¶
func HasLabels(labels map[string]string) func(*KubeObject) bool
HasLabels returns a function that checks if a KubeObject has all the given labels.
func IsGVK ¶
func IsGVK(group, version, kind string) func(*KubeObject) bool
IsGVK returns a function that checks if a KubeObject has a certain GVK. Deprecated: Prefer exact matching with IsGroupVersionKind or IsGroupKind
func IsGroupKind ¶
func IsGroupKind(gk schema.GroupKind) func(*KubeObject) bool
IsGroupKind returns a function that checks if a KubeObject has a certain GroupKind.
func IsGroupVersionKind ¶
func IsGroupVersionKind(gvk schema.GroupVersionKind) func(*KubeObject) bool
IsGroupVersionKind returns a function that checks if a KubeObject has a certain GroupVersionKind.
func IsKrmResourceFile ¶
IsKrmResourceFile checks if a file in a kpt package should be parsed for KRM resources
func IsLocalConfig ¶
func IsLocalConfig(o *KubeObject) bool
IsLocalConfig determines whether a KubeObject (or KRM resource) has the config.kubernetes.io/local-config: true annotation
func IsMetaResource ¶
func IsMetaResource() func(*KubeObject) bool
IsMetaResource returns a function that checks if a KubeObject is a meta resource. For now this just includes the Kptfile
func IsName ¶
func IsName(name string) func(*KubeObject) bool
IsName returns a function that checks if a KubeObject has a certain name.
func IsNamespace ¶
func IsNamespace(namespace string) func(*KubeObject) bool
IsNamespace returns a function that checks if a KubeObject has a certain namespace.
func Not ¶
func Not(f func(*KubeObject) bool) func(o *KubeObject) bool
Not returns will return a function that returns the opposite of f(object), i.e. !f(object)
func ParseGroupVersion ¶
ParseGroupVersion parses a "apiVersion" to get the "group" and "version" values.
func PathOfKubeObject ¶
func PathOfKubeObject(node *KubeObject) string
PathOfKubeObject returns the path of a KubeObject within a package By default is uses the PathAnnotation, otherwise it returns with a default path based on the namespace and name of the object
func Run ¶
func Run(p ResourceListProcessor, input []byte) ([]byte, error)
Run evaluates the function. input must be a resourceList in yaml format. An updated resourceList will be returned.
func WriteKubeObjectsToPackage ¶
func WriteKubeObjectsToPackage(objs KubeObjects) (map[string]string, error)
func WriteKubeObjectsToString ¶
func WriteKubeObjectsToString(objs KubeObjects) (string, error)
Types ¶
type ErrAttemptToTouchUpstreamIdentifier ¶
type ErrAttemptToTouchUpstreamIdentifier struct{}
func (ErrAttemptToTouchUpstreamIdentifier) Error ¶
func (ErrAttemptToTouchUpstreamIdentifier) Error() string
type ErrInternalAnnotation ¶
type ErrInternalAnnotation struct {
Message string
}
func (*ErrInternalAnnotation) Error ¶
func (e *ErrInternalAnnotation) Error() string
type ErrMissingFnConfig ¶
type ErrMissingFnConfig struct{}
ErrMissingFnConfig raises error if a required functionConfig is missing.
func (ErrMissingFnConfig) Error ¶
func (ErrMissingFnConfig) Error() string
type ErrUnmatchedField ¶
ErrUnmatchedField defines the error when a KubeObject's field paths has a different data type as expected e.g. ConfigMap `.data` is string map. If the a ConfigMap KubeObject calls `NestedInt("data")`, this error should raise.
func NewErrUnmatchedField ¶
func NewErrUnmatchedField(obj SubObject, fields []string, expectedFieldType any) *ErrUnmatchedField
NewErrUnmatchedField returns a ErrUnmatchedField error with the specific field path of a KubeObject that has the mismatched data type.
func (*ErrUnmatchedField) Error ¶
func (e *ErrUnmatchedField) Error() string
Error returns the message to guide users
type Field ¶
type Field struct {
// Path is the field path. This field is required.
Path string `yaml:"path,omitempty" json:"path,omitempty"`
// CurrentValue is the current field value
CurrentValue interface{} `yaml:"currentValue,omitempty" json:"currentValue,omitempty"`
// ProposedValue is the proposed value of the field to fix an issue.
ProposedValue interface{} `yaml:"proposedValue,omitempty" json:"proposedValue,omitempty"`
}
Field references a field in a resource
type File ¶
type File struct {
// Path is relative path to the file containing the resource.
// This field is required.
Path string `yaml:"path,omitempty" json:"path,omitempty"`
// Index is the index into the file containing the resource
// (i.e. if there are multiple resources in a single file)
Index int `yaml:"index,omitempty" json:"index,omitempty"`
}
File references a file containing a resource
type KubeObject ¶
type KubeObject struct {
SubObject
}
KubeObject presents a k8s object.
func CopyToKubeObject ¶
func CopyToKubeObject(rn *yaml.RNode) *KubeObject
CopyToKubeObject makes a copy of the internal yaml nodes of the RNode into a new KubeObject.
func MoveToKubeObject ¶
func MoveToKubeObject(rn *yaml.RNode) *KubeObject
MoveToKubeObject transfers the ownership of the internal yaml nodes of the RNode into a new KubeObject, and leaves the original RNode empty.
func NewEmptyKubeObject ¶
func NewEmptyKubeObject() *KubeObject
func NewFromTypedObject ¶
func NewFromTypedObject(v interface{}) (*KubeObject, error)
NewFromTypedObject construct a KubeObject from a typed object (e.g. corev1.Pod)
func NewKubeObjectFromMap ¶ added in v1.0.2
func NewKubeObjectFromMap(m map[string]interface{}) (*KubeObject, error)
func NewKubeObjectFromResourceNode ¶
func NewKubeObjectFromResourceNode(rn *yaml.RNode) *KubeObject
NewKubeObjectFromResourceNode creates a KubeObject from the deep copy of a yaml.RNode
func ParseKubeObject ¶
func ParseKubeObject(in []byte) (*KubeObject, error)
ParseKubeObject parses input byte slice to a single KubeObject.
func ParseKubeObjects ¶
func ParseKubeObjects(in []byte) ([]*KubeObject, error)
ParseKubeObjects parses input byte slice to multiple KubeObjects.
func (*KubeObject) Copy ¶
func (o *KubeObject) Copy() *KubeObject
Copy returns a deep copy of the KubeObject
func (*KubeObject) CopyToResourceNode ¶
func (o *KubeObject) CopyToResourceNode() *yaml.RNode
CopyToResourceNode returns a deep copy of the KubeObject's internal yaml.RNode
func (*KubeObject) GetAPIVersion ¶
func (o *KubeObject) GetAPIVersion() string
func (*KubeObject) GetAnnotation ¶
func (o *KubeObject) GetAnnotation(k string) string
GetAnnotation returns one annotation with key k.
func (*KubeObject) GetAnnotations ¶
func (o *KubeObject) GetAnnotations() map[string]string
GetAnnotations returns all annotations.
func (*KubeObject) GetGKNNString ¶ added in v1.0.2
func (o *KubeObject) GetGKNNString() string
GetGKNNString returns with Group, Kind, Namespace, Name in a human readable string
func (*KubeObject) GetID ¶
func (o *KubeObject) GetID() *ResourceIdentifier
GetID gets the Group, Kind, Namespace and Name as the ResourceIdentifier.
func (*KubeObject) GetKind ¶
func (o *KubeObject) GetKind() string
func (*KubeObject) GetLabel ¶
func (o *KubeObject) GetLabel(k string) string
GetLabel returns one label with key k.
func (*KubeObject) GetLabels ¶
func (o *KubeObject) GetLabels() map[string]string
GetLabels returns all labels.
func (*KubeObject) GetName ¶
func (o *KubeObject) GetName() string
func (*KubeObject) GetNamespace ¶
func (o *KubeObject) GetNamespace() string
func (*KubeObject) GetOriginID ¶
func (o *KubeObject) GetOriginID() (*ResourceIdentifier, error)
GetOriginID provides the `ResourceIdentifier` to identify the upstream origin of a KRM resource. This origin is generated and maintained by kpt pkg management and is stored in the `internal.kpt.dev/upstream-identiifer` annotation. If a resource does not have an upstream origin, we use its current meta resource ID instead.
func (*KubeObject) GetPackageScopeUniqueID ¶ added in v1.0.2
func (o *KubeObject) GetPackageScopeUniqueID() PackageScopeUniqueID
GetPackageScopeUniqueID returns with a key that uniquely identifies a resource in a package, even if there are multiple resources with the same GVKNN.
func (*KubeObject) GroupKind ¶
func (o *KubeObject) GroupKind() schema.GroupKind
GroupKind returns the schema.GroupKind for the specified object.
func (*KubeObject) GroupVersionKind ¶
func (o *KubeObject) GroupVersionKind() schema.GroupVersionKind
GroupVersionKind returns the schema.GroupVersionKind for the specified object.
func (*KubeObject) HasAnnotations ¶
func (o *KubeObject) HasAnnotations(annotations map[string]string) bool
HasAnnotations returns whether the KubeObject has all the given annotations.
func (*KubeObject) HasLabels ¶
func (o *KubeObject) HasLabels(labels map[string]string) bool
HasLabels returns whether the KubeObject has all the given labels
func (*KubeObject) HasNamespace ¶
func (o *KubeObject) HasNamespace() bool
func (*KubeObject) HasSameID ¶
func (o *KubeObject) HasSameID(b *KubeObject) bool
HasSameID returns true if the two KubeObjects has the same (Group, Version, Kind, Namespace, Name)
func (*KubeObject) HasUpstreamOrigin ¶
func (o *KubeObject) HasUpstreamOrigin() bool
HasUpstreamOrigin tells whether a resource is sourced from an upstream package resource.
func (*KubeObject) HeadComment ¶
func (o *KubeObject) HeadComment(fields ...string) (string, bool, error)
HeadComment returns the head comment, if the target field exist and a potential error.
func (*KubeObject) IDAnnotation ¶
func (o *KubeObject) IDAnnotation() int
IDAnnotation return -1 if not found.
func (*KubeObject) IndexAnnotation ¶
func (o *KubeObject) IndexAnnotation() int
IndexAnnotation returns -1 if not found.
func (*KubeObject) IsClusterScoped ¶
func (o *KubeObject) IsClusterScoped() bool
IsClusterScoped tells whether a resource is cluster scoped.
func (*KubeObject) IsEmpty ¶
func (o *KubeObject) IsEmpty() bool
func (*KubeObject) IsGVK ¶
func (o *KubeObject) IsGVK(group, version, kind string) bool
IsGVK compares the given group, version, and kind with KubeObject's apiVersion and Kind. It only matches on specified arguments, for example if the group is empty this will match any group. Deprecated: Prefer exact matching with IsGroupVersionKind or IsGroupKind
func (*KubeObject) IsGroupKind ¶
func (o *KubeObject) IsGroupKind(gk schema.GroupKind) bool
IsGroupKind compares the given group and kind with KubeObject's apiVersion and Kind.
func (*KubeObject) IsGroupVersionKind ¶
func (o *KubeObject) IsGroupVersionKind(gvk schema.GroupVersionKind) bool
IsGroupVersionKind compares the given group, version, and kind with KubeObject's apiVersion and Kind.
func (*KubeObject) IsLocalConfig ¶
func (o *KubeObject) IsLocalConfig() bool
IsLocalConfig checks the "config.kubernetes.io/local-config" field to tell whether a KRM resource will be skipped by `kpt live apply` or not.
func (*KubeObject) IsNamespaceScoped ¶
func (o *KubeObject) IsNamespaceScoped() bool
IsNamespaceScoped tells whether a k8s resource is namespace scoped. If the KubeObject resource is a customized, it determines the namespace scope by checking whether `metadata.namespace` is set.
func (*KubeObject) LineComment ¶
func (o *KubeObject) LineComment(fields ...string) (string, bool, error)
LineComment returns the line comment, if the target field exist and a potential error.
func (*KubeObject) MoveToResourceNode ¶
func (o *KubeObject) MoveToResourceNode() *yaml.RNode
MoveToResourceNode transfers the ownership of the internal yaml nodes of the KubeObject into a new yaml.RNode, and leaves the original KubeObject empty.
func (*KubeObject) PathAnnotation ¶
func (o *KubeObject) PathAnnotation() string
func (*KubeObject) RemoveAnnotation ¶
func (o *KubeObject) RemoveAnnotation(k string) error
func (*KubeObject) RemoveAnnotationsIfEmpty ¶
func (o *KubeObject) RemoveAnnotationsIfEmpty() error
RemoveAnnotationsIfEmpty removes the annotations field when it has zero annotations.
func (*KubeObject) RemoveLabel ¶
func (o *KubeObject) RemoveLabel(k string) error
func (*KubeObject) SetAPIVersion ¶
func (o *KubeObject) SetAPIVersion(apiVersion string) error
func (*KubeObject) SetAnnotation ¶
func (o *KubeObject) SetAnnotation(k, v string) error
func (*KubeObject) SetHeadComment ¶
func (o *KubeObject) SetHeadComment(comment string, fields ...string) error
func (*KubeObject) SetIndexAnnotation ¶ added in v1.0.2
func (o *KubeObject) SetIndexAnnotation(index int) error
func (*KubeObject) SetKind ¶
func (o *KubeObject) SetKind(kind string) error
func (*KubeObject) SetLabel ¶
func (o *KubeObject) SetLabel(k, v string) error
func (*KubeObject) SetLineComment ¶
func (o *KubeObject) SetLineComment(comment string, fields ...string) error
func (*KubeObject) SetName ¶
func (o *KubeObject) SetName(name string) error
func (*KubeObject) SetNamespace ¶
func (o *KubeObject) SetNamespace(name string) error
func (*KubeObject) SetPathAnnotation ¶ added in v1.0.2
func (o *KubeObject) SetPathAnnotation(path string) error
func (*KubeObject) ShortString ¶
func (o *KubeObject) ShortString() string
ShortString provides a human readable information for the KubeObject Identifier in the form of GVKNN.
type KubeObjects ¶
type KubeObjects []*KubeObject
func MoveToKubeObjects ¶
func MoveToKubeObjects(rns []*yaml.RNode) KubeObjects
MoveToKubeObjects moves all yaml.RNodes into KubeObjects, leaving the original slice with empty nodes
func ReadKubeObjectsFromDirectory ¶ added in v1.0.2
func ReadKubeObjectsFromDirectory(path string) (KubeObjects, error)
func ReadKubeObjectsFromFile ¶
func ReadKubeObjectsFromFile(filepath string, content string) (KubeObjects, error)
func (KubeObjects) CopyToResourceNodes ¶
func (kos KubeObjects) CopyToResourceNodes() kio.ResourceNodeSlice
CopyToResourceNodes copies the entire KubeObjects slice to yaml.RNodes
func (KubeObjects) EnsureSingleItem ¶
func (kos KubeObjects) EnsureSingleItem() (*KubeObject, error)
EnsureSingleItem checks if KubeObjects contains exactly one item and returns it, or an error if it doesn't.
func (KubeObjects) EnsureSingleItemAs ¶
func (kos KubeObjects) EnsureSingleItemAs(out any) error
func (KubeObjects) GetRootKptfile ¶
func (kos KubeObjects) GetRootKptfile() *KubeObject
GetRootKptfile returns the root Kptfile. Nested kpt packages can have multiple Kptfile files of the same GVKNN.
func (KubeObjects) Len ¶
func (kos KubeObjects) Len() int
func (KubeObjects) Less ¶
func (kos KubeObjects) Less(i, j int) bool
func (KubeObjects) SetAnnotation ¶
func (kos KubeObjects) SetAnnotation(key, value string) error
SetAnnotation sets the specified annotation for all KubeObjects in the slice
func (KubeObjects) Split ¶
func (kos KubeObjects) Split(predicate func(o *KubeObject) bool) (KubeObjects, KubeObjects)
Split separates the KubeObjects based on whether the predicate is true or false for them.
func (KubeObjects) String ¶
func (kos KubeObjects) String() string
func (KubeObjects) Swap ¶
func (kos KubeObjects) Swap(i, j int)
func (*KubeObjects) Upsert ¶
func (kos *KubeObjects) Upsert(newObj *KubeObject)
Upsert updates or insert the given KubeObject into the list If the list contains an object with the same (Group, Version, Kind, Namespace, Name), then Upsert replaces it with `newObj`, otherwise it appends `newObj` to the list
func (*KubeObjects) UpsertTypedObject ¶
func (kos *KubeObjects) UpsertTypedObject(newObj any) error
UpsertTypedObject attempts to convert `newObj` to a KubeObject and then calls Upsert().
func (KubeObjects) Where ¶
func (kos KubeObjects) Where(f func(*KubeObject) bool) KubeObjects
Where will return the subset of objects in KubeObjects such that f(object) returns 'true'.
func (KubeObjects) WhereNot ¶
func (kos KubeObjects) WhereNot(f func(o *KubeObject) bool) KubeObjects
WhereNot will return the subset of objects in KubeObjects such that f(object) returns 'false'. This is a shortcut for Where(Not(f)).
type PackageScopeUniqueID ¶ added in v1.0.2
type PackageScopeUniqueID struct {
yaml.ResourceIdentifier
Path string
Index int
}
PackageScopeUniqueID is a key that uniquely identifies a resource in a package, even if there are multiple resources with the same GVKNN.
func (PackageScopeUniqueID) String ¶ added in v1.0.2
func (id PackageScopeUniqueID) String() string
type ResourceIdentifier ¶
type ResourceIdentifier struct {
Group string
Version string
Kind string
Name string
Namespace string
}
func (*ResourceIdentifier) String ¶
func (r *ResourceIdentifier) String() string
type ResourceList ¶
type ResourceList struct {
// Items is the ResourceList.items input and output value.
//
// e.g. given the function input:
//
// kind: ResourceList
// items:
// - kind: Deployment
// ...
// - kind: Service
// ...
//
// Items will be a slice containing the Deployment and Service resources
// Mutating functions will alter this field during processing.
// This field is required.
Items KubeObjects `yaml:"items" json:"items"`
// FunctionConfig is the ResourceList.functionConfig input value.
//
// e.g. given the input:
//
// kind: ResourceList
// functionConfig:
// kind: Example
// spec:
// foo: var
//
// FunctionConfig will contain the RNodes for the Example:
// kind: Example
// spec:
// foo: var
FunctionConfig *KubeObject `yaml:"functionConfig,omitempty" json:"functionConfig,omitempty"`
// Results is ResourceList.results output value.
// Validating functions can optionally use this field to communicate structured
// validation error data to downstream functions.
Results Results `yaml:"results,omitempty" json:"results,omitempty"`
}
ResourceList is a Kubernetes list type used as the primary data interchange format in the Configuration Functions Specification: https://github.com/kubernetes-sigs/kustomize/blob/master/cmd/config/docs/api-conventions/functions-spec.md This framework facilitates building functions that receive and emit ResourceLists, as required by the specification.
func ParseResourceList ¶
func ParseResourceList(in []byte) (*ResourceList, error)
ParseResourceList parses a ResourceList from the input byte array. This function can be used to parse either KRM fn input or KRM fn output
func (*ResourceList) LogResult ¶
func (rl *ResourceList) LogResult(err error)
func (*ResourceList) Sort ¶
func (rl *ResourceList) Sort()
Sort sorts the ResourceList.items by apiVersion, kind, namespace and name.
func (*ResourceList) ToYAML ¶
func (rl *ResourceList) ToYAML() ([]byte, error)
ToYAML converts the ResourceList to yaml.
func (*ResourceList) UpsertObjectToItems ¶
func (rl *ResourceList) UpsertObjectToItems(obj interface{}, checkExistence func(obj, another *KubeObject) bool, replaceIfAlreadyExist bool) error
UpsertObjectToItems adds an object to ResourceList.items. The input object can be a KubeObject or any typed object (e.g. corev1.Pod).
type ResourceListProcessor ¶
type ResourceListProcessor interface {
Process(rl *ResourceList) (bool, error)
}
ResourceListProcessor is implemented by configuration functions built with this framework to conform to the Configuration Functions Specification: https://github.com/kubernetes-sigs/kustomize/blob/master/cmd/config/docs/api-conventions/functions-spec.md
func Chain ¶
func Chain(processors ...ResourceListProcessor) ResourceListProcessor
Chain chains a list of ResourceListProcessor as a single ResourceListProcessor.
func WithContext ¶
func WithContext(ctx context.Context, runner Runner) ResourceListProcessor
type ResourceListProcessorFunc ¶
type ResourceListProcessorFunc func(rl *ResourceList) (bool, error)
ResourceListProcessorFunc converts a compatible function to a ResourceListProcessor.
func ChainFunctions ¶
func ChainFunctions(functions ...ResourceListProcessorFunc) ResourceListProcessorFunc
ChainFunctions chains a list of ResourceListProcessorFunc as a single ResourceListProcessorFunc.
func (ResourceListProcessorFunc) Process ¶
func (p ResourceListProcessorFunc) Process(rl *ResourceList) (bool, error)
type ResourceRef ¶
type ResourceRef struct {
APIVersion string `yaml:"apiVersion,omitempty" json:"apiVersion,omitempty"`
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"`
Name string `yaml:"name,omitempty" json:"name,omitempty"`
Namespace string `yaml:"namespace,omitempty" json:"namespace,omitempty"`
}
ResourceRef fills the ResourceRef field in Results
type Result ¶
type Result struct {
// Message is a human readable message. This field is required.
Message string `yaml:"message,omitempty" json:"message,omitempty"`
// Severity is the severity of this result
Severity Severity `yaml:"severity,omitempty" json:"severity,omitempty"`
// ResourceRef is a reference to a resource.
// Required fields: apiVersion, kind, name.
ResourceRef *ResourceRef `yaml:"resourceRef,omitempty" json:"resourceRef,omitempty"`
// Field is a reference to the field in a resource this result refers to
Field *Field `yaml:"field,omitempty" json:"field,omitempty"`
// File references a file containing the resource this result refers to
File *File `yaml:"file,omitempty" json:"file,omitempty"`
// Tags is an unstructured key value map stored with a result that may be set
// by external tools to store and retrieve arbitrary metadata
Tags map[string]string `yaml:"tags,omitempty" json:"tags,omitempty"`
}
Result defines a validation result
func ConfigFileResult ¶
func ConfigObjectResult ¶
func ConfigObjectResult(msg string, obj *KubeObject, severity Severity) *Result
func ErrorConfigFileResult ¶
func ErrorConfigObjectResult ¶
func ErrorConfigObjectResult(err error, obj *KubeObject) *Result
func ErrorResult ¶
func GeneralResult ¶
type Results ¶
type Results []*Result
func (*Results) ErrorE ¶
ErrorE writes the `error` as an Error level `result` to the results slice. e.g.
err := error.New("test)
results.ErrorE(err)
func (*Results) Errorf ¶
Errorf writes an Error level `result` to the results slice. It accepts arguments according to a format specifier. e.g. results.Errorf("bad kind %v", "invalid")
func (*Results) Infof ¶
Infof writes an Info level `result` to the results slice. It accepts arguments according to a format specifier. e.g.
results.Infof("update %v %q ", "ConfigMap", "kptfile.kpt.dev")
type Runner ¶
type Runner interface {
// Run provides the entrypoint to allow you make changes to input `resourcelist.Items`
// Args:
// items: The KRM resources in the form of a slice of KubeObject.
// Note: You can only modify the existing items but not add or delete items.
// We intentionally design the method this way to make the Runner be used as a Transformer or Validator, but not a Generator.
// results: You can use `ErrorE` `Errorf` `Infof` `Warningf` `WarningE` to add user message to `Results`.
// Returns:
// return a boolean to tell whether the execution should be considered as PASS or FAIL. CLI like kpt will
// display the corresponding message.
Run(context *Context, functionConfig *KubeObject, items KubeObjects, results *Results) bool
}
type SliceSubObjects ¶
type SliceSubObjects []*SubObject
func (*SliceSubObjects) MarshalJSON ¶
func (s *SliceSubObjects) MarshalJSON() ([]byte, error)
MarshalJSON provides the custom encoding format for encode.json. This is used when KubeObject `Set` a slice of SubObjects.
type SubObject ¶
type SubObject struct {
// contains filtered or unexported fields
}
SubObject represents a map within a KubeObject
func (*SubObject) As ¶
As converts a KubeObject to the desired typed object. ptr must be a pointer to a typed object.
func (*SubObject) GetBool ¶
GetBool accepts a single key `k` whose value is expected to be a boolean. It returns the int value of the `k`. It panic with errSubObjectFields error if the field is not an integer type.
func (*SubObject) GetInt ¶
GetInt accepts a single key `k` whose value is expected to be an integer. It returns the int value of the `k`. It panic with errSubObjectFields error if the field is not an integer type.
func (*SubObject) GetMap ¶
GetMap accepts a single key `k` whose value is expected to be a map. It returns the map in the form of a SubObject pointer. It panic with ErrSubObjectFields error if the field cannot be represented as a SubObject.
func (*SubObject) GetSlice ¶
func (o *SubObject) GetSlice(k string) SliceSubObjects
GetSlice accepts a single key `k` whose value is expected to be a slice. It returns the value as a slice of SubObject. It panic with errSubObjectFields error if the field is not a slice type.
func (*SubObject) GetString ¶
GetString accepts a single key `k` whose value is expected to be a string. It returns the value of the `k`. It panic with errSubObjectFields error if the field is not a string type.
func (*SubObject) NestedBool ¶
NestedBool returns the bool value, if the field exist and a potential error.
func (*SubObject) NestedFloat64 ¶
NestedFloat64 returns the float64 value, if the field exist and a potential error.
func (*SubObject) NestedInt ¶
NestedInt returns the int64 value, if the field exist and a potential error.
func (*SubObject) NestedInt64 ¶
NestedInt64 returns the int64 value, if the field exist and a potential error.
func (*SubObject) NestedResource ¶
NestedResource returns a map[string]string value of a nested field, false if not found and an error if not a map[string]string type.
func (*SubObject) NestedSlice ¶
func (o *SubObject) NestedSlice(fields ...string) (SliceSubObjects, bool, error)
NestedSlice accepts a slice of `fields` which represents the path to the slice component and return a slice of SubObjects as the first return value; whether the component exists or not as the second return value, and errors as the third return value.
func (*SubObject) NestedString ¶
NestedString returns the string value, if the field exist and a potential error.
func (*SubObject) NestedStringMap ¶
NestedStringMap returns a map[string]string value of a nested field, false if not found and an error if not a map[string]string type.
func (*SubObject) NestedStringSlice ¶
NestedStringSlice returns a []string value of a nested field, false if not found and an error if not a []string type.
func (*SubObject) NestedSubObject ¶
NestedSubObject returns with a SubObject representing the YAML subtree under the path specified by `fields“
func (*SubObject) RemoveNestedField ¶
RemoveNestedField removes the field located by fields if found. It returns if the field is found and a potential error.
func (*SubObject) Set ¶ added in v1.0.2
Set ensures that the value of `o` (this object) is the same as `newValue“, while keeps the formatting of the original object.
func (*SubObject) SetFromTypedObject ¶ added in v1.0.2
SetFromTypedObject ensures that the value of `o` (this object) is the same as `newValue“, while keeps the formatting of the original object. `newValue` must be of type struct or map[string]...
func (*SubObject) SetMap ¶
SetMap accepts a single key `k`, and ensures that the value of `k` is the same as the map it received via `mapObject` in the form of a SubObject pointer.
func (*SubObject) SetNestedBool ¶
SetNestedBool sets the `fields` value to bool `value`. It returns error if the fields type is not bool.
func (*SubObject) SetNestedField ¶
SetNestedField sets a nested field located by fields to the value provided as val. val should not be a yaml.RNode. If you want to deal with yaml.RNode, you should use Get method and modify the underlying yaml.Node.
func (*SubObject) SetNestedInt ¶
SetNestedInt sets the `fields` value to int `value`. It returns error if the fields type is not int.
func (*SubObject) SetNestedString ¶
SetNestedString sets the `fields` value to string `value`. It returns error if the fields type is not string.
func (*SubObject) SetNestedStringMap ¶
SetNestedStringMap sets the `fields` value to map[string]string `value`. It returns error if the fields type is not map[string]string.
func (*SubObject) SetNestedStringSlice ¶
SetNestedStringSlice sets the `fields` value to []string `value`. It returns error if the fields type is not []string.
func (*SubObject) SetSlice ¶
func (o *SubObject) SetSlice(objects SliceSubObjects, field string) error
SetSlice sets the SliceSubObjects to the given field. It creates the field if not exists. If returns error if the field exists but not a slice type.
func (*SubObject) UpdateNestedStringMap ¶
UpdateNestedStringMap updates the map[string]string `fields` value with the (key, value) pairs in `values`. It returns error if the fields type is not map[string]string.