fn

package module
v0.0.0-...-3255acc Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2023 License: Apache-2.0 Imports: 17 Imported by: 140

Documentation

Overview

Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

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:

  1. Reads the "ResourceList" object from STDIN.
  2. Gets the function configs from the "ResourceList.FunctionConfig".
  3. Mutate or validate the Kubernetes YAML resources from the "ResourceList.Items" field with the function configs.
  4. Writes the modified "ResourceList" to STDOUT.
  5. 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/GoogleContainerTools/kpt-functions-sdk/go/fn/examples for detailed usage.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
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"
)
View Source
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

View Source
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

This section is empty.

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 Execute

func Execute(p ResourceListProcessor, r io.Reader, w io.Writer) error

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 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 Log

func Log(in ...interface{})

func Logf

func Logf(format string, in ...interface{})

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

func ParseGroupVersion(apiVersion string) (group, version string)

ParseGroupVersion parses a "apiVersion" to get the "group" and "version" values.

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.

Types

type Context

type Context struct {
	context.Context
}

TODO: Have Context implement `context.Context`.

type ErrAttemptToTouchUpstreamIdentifier

type ErrAttemptToTouchUpstreamIdentifier struct{}

func (ErrAttemptToTouchUpstreamIdentifier) Error

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

type ErrUnmatchedField struct {
	SubObject *SubObject
	DataType  string
}

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 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 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) 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) 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

Label returns one label with key k.

func (*KubeObject) GetLabels

func (o *KubeObject) GetLabels() map[string]string

Labels 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) 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) 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 return -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) PathAnnotation

func (o *KubeObject) PathAnnotation() string

func (*KubeObject) RemoveAnnotationsIfEmpty

func (o *KubeObject) RemoveAnnotationsIfEmpty() error

RemoveAnnotationsIfEmpty removes the annotations field when it has zero annotations.

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) 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) 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 (KubeObjects) GetRootKptfile

func (o KubeObjects) GetRootKptfile() *KubeObject

GetRootKptfile returns the root Kptfile. Nested kpt packages can have multiple Kptfile files of the same GVKNN.

func (KubeObjects) Len

func (o KubeObjects) Len() int

func (KubeObjects) Less

func (o KubeObjects) Less(i, j int) bool

func (KubeObjects) String

func (o KubeObjects) String() string

func (KubeObjects) Swap

func (o KubeObjects) Swap(i, j int)

func (KubeObjects) Where

func (o 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 (o 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 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

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 ConfigFileResult(msg, path string, severity Severity) *Result

func ConfigObjectResult

func ConfigObjectResult(msg string, obj *KubeObject, severity Severity) *Result

func ErrorConfigFileResult

func ErrorConfigFileResult(err error, path string) *Result

func ErrorConfigObjectResult

func ErrorConfigObjectResult(err error, obj *KubeObject) *Result

func ErrorResult

func ErrorResult(err error) *Result

func GeneralResult

func GeneralResult(msg string, severity Severity) *Result

func (Result) Error

func (i Result) Error() string

func (Result) String

func (i Result) String() string

String provides a human-readable message for the result item

type Results

type Results []*Result

func (Results) Error

func (r Results) Error() string

Error enables Results to be returned as an error

func (*Results) ErrorE

func (r *Results) ErrorE(err error)

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

func (r *Results) Errorf(format string, a ...any)

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) ExitCode

func (r Results) ExitCode() int

ExitCode provides the exit code based on the result's severity

func (*Results) Infof

func (r *Results) Infof(format string, a ...any)

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")

func (Results) Sort

func (r Results) Sort()

Sort performs an in place stable sort of Results

func (*Results) String

func (r *Results) String() string

func (*Results) WarningE

func (r *Results) WarningE(err error)

WarningE writes an error as a Warning level `result` to the results slice. Normally this function can be used for cases that need error tolerance.

func (*Results) Warningf

func (r *Results) Warningf(format string, a ...any)

Warningf writes a Warning level `result` to the results slice. It accepts arguments according to a format specifier. e.g.

results.Warningf("bad kind %q", "invalid")

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 Severity

type Severity string

Severity indicates the severity of the Result

const (
	// Error indicates the result is an error.  Will cause the function to exit non-0.
	Error Severity = "error"
	// Warning indicates the result is a warning
	Warning Severity = "warning"
	// Info indicates the result is an informative message
	Info Severity = "info"
)

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

func (o *SubObject) As(ptr interface{}) error

As converts a KubeObject to the desired typed object. ptr must be a pointer to a typed object.

func (*SubObject) Get

func (o *SubObject) Get(_ interface{}, _ ...string) (bool, error)

DEPRECATED: Please use type-aware functions instead. To parse struct object, please use `NestedResource`.

func (*SubObject) GetBool

func (o *SubObject) GetBool(k string) bool

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

func (o *SubObject) GetInt(k string) int64

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

func (o *SubObject) GetMap(k string) *SubObject

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

func (o *SubObject) GetString(k string) string

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

func (o *SubObject) NestedBool(fields ...string) (bool, bool, error)

NestedBool returns the bool value, if the field exist and a potential error.

func (*SubObject) NestedFloat64

func (o *SubObject) NestedFloat64(fields ...string) (float64, bool, error)

NestedFloat64 returns the float64 value, if the field exist and a potential error.

func (*SubObject) NestedInt

func (o *SubObject) NestedInt(fields ...string) (int, bool, error)

NestedInt returns the int64 value, if the field exist and a potential error.

func (*SubObject) NestedInt64

func (o *SubObject) NestedInt64(fields ...string) (int64, bool, error)

NestedInt64 returns the int64 value, if the field exist and a potential error.

func (*SubObject) NestedResource

func (o *SubObject) NestedResource(ptr interface{}, fields ...string) (bool, error)

NestedMap 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

func (o *SubObject) NestedString(fields ...string) (string, bool, error)

NestedString returns the string value, if the field exist and a potential error.

func (*SubObject) NestedStringMap

func (o *SubObject) NestedStringMap(fields ...string) (map[string]string, bool, error)

NestedMap 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

func (o *SubObject) NestedStringSlice(fields ...string) ([]string, bool, error)

NestedStringSlice 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) NestedSubObject

func (o *SubObject) NestedSubObject(fields ...string) (SubObject, bool, error)

NestedSubObject returns with a SubObject representing the YAML subtree under the path specified by `fields“

func (*SubObject) RemoveNestedField

func (o *SubObject) RemoveNestedField(fields ...string) (bool, error)

RemoveNestedField removes the field located by fields if found. It returns if the field is found and a potential error.

func (*SubObject) SetNestedBool

func (o *SubObject) SetNestedBool(value bool, fields ...string) error

SetNestedBool sets the `fields` value to bool `value`. It returns error if the fields type is not bool.

func (*SubObject) SetNestedField

func (o *SubObject) SetNestedField(val interface{}, fields ...string) error

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

func (o *SubObject) SetNestedInt(value int, fields ...string) error

SetNestedInt sets the `fields` value to int `value`. It returns error if the fields type is not int.

func (*SubObject) SetNestedString

func (o *SubObject) SetNestedString(value string, fields ...string) error

SetNestedString sets the `fields` value to string `value`. It returns error if the fields type is not string.

func (*SubObject) SetNestedStringMap

func (o *SubObject) SetNestedStringMap(value map[string]string, fields ...string) error

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

func (o *SubObject) SetNestedStringSlice(value []string, fields ...string) error

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) String

func (o *SubObject) String() string

String serializes the object in yaml format.

func (*SubObject) UpsertMap

func (o *SubObject) UpsertMap(k string) *SubObject

Directories

Path Synopsis
examples module

Jump to

Keyboard shortcuts

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