kubernetes

package module
v4.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2025 License: Apache-2.0 Imports: 30 Imported by: 0

README

go-kubernetes

This library provides a simplified interface on top of the official kubernetes client libraries.

The design focus of this module is usability, not performance or type-safety. We wanted to create a module that is closer to the use of kubectl based scripts.

We use this library for tools that interact with the Kubernetes API, especially when the inspected objects are of varying types.
There's also support for building simple admission webhooks using the Gin framework. This provides an alternative solutions to writing admission controllers that is more lightweight than the official SDK.

Maintenance and PRs

This repository is in active development but is not our main focus.
PRs are welcome, but will take some time to be reviewed.

License

All files in the repository are subject to the Apache 2.0 License

Builds and Releases

All commits to the main branch need to use conventional commits.
Releases will be generated automatically from these commits using Release Please.

Required tools

All required tools can be installed locally via nix and are loaded on demand via direnv.
On MacOS you can install nix via the installer from determinate systems.

curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install

We provided a justfile to generate the required .envrc file. Run just init-nix to get started, or run the script directly.

Running unit-tests

After you have set up your environment, run unittests via just test or

go test ./...
Running commit checks

We use pre-commit hooks to ensure code quality. These hooks are run on PR creation.
If you encounter issues reported during PR creation, please run the tests locally until the issues are resolved.

You can use just lint to run the pre-commit hooks.
Please note that this command requires [RequiredTools] to be installed

Examples

We provide example code in the cmd directory. This code is not part of the official library.

List all namespaces
func ListAllNamespaces() {
  // Get the kubeconfig file path
  kubeConfigPath := os.Getenv("KUBECONFIG")
  if kubeConfigPath == "" {
      kubeConfigPath = os.ExpandEnv("$HOME/.kube/config")
  }

  // Create a new client
  client, err := kubernetes.NewClient(kubeConfigPath)
  if err != nil {
    log.Fatal(err)
  }

  // List all objects of type "namespace"
  namespaces, err := client.ListAllObjects(kubernetes.ResourceNamespace, "", "")
  if err != nil {
    log.Fatal(err)
  }

  // Print the names
  for _, namespace := range namespaces {
    fmt.Println(namespace.GetName())
  }
}

Documentation

Index

Constants

View Source
const (
	// ArrayNotationInvalid is used when parsing did neither yield index nor
	// traversal notation
	ArrayNotationInvalid = ArrayNotation(-1)
	// ArrayNotationIndex is used when direct element access is requested
	ArrayNotationIndex = ArrayNotation(0)
	// ArrayNotationTraversal is used when any element access is requested
	ArrayNotationTraversal = ArrayNotation(1)
)

Variables

View Source
var (
	// ResourceConfigMap is the most commonly used GVR for ConfigMaps
	ResourceConfigMap = schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "configmaps",
	}

	// ResourceNamespace is the most commonly used GVR for Namespaces
	ResourceNamespace = schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "namespaces",
	}

	// ResourceNode is the most commonly used GVR for Nodes
	ResourceNode = schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "nodes",
	}

	// ResourcePod is the most commonly used GVR for Pods
	ResourcePod = schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "pods",
	}

	// ResourceSecret is the most commonly used GVR for Secrets
	ResourceSecret = schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "secrets",
	}

	// ResourceService is the most commonly used GVR for Services
	ResourceService = schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "services",
	}

	// ResourceServiceAccount is the most commonly used GVR for ServiceAccounts
	ResourceServiceAccount = schema.GroupVersionResource{
		Group:    "",
		Version:  "v1",
		Resource: "serviceaccounts",
	}

	// ResourceDaemonSet is the most commonly used GVR for DaemonSets
	ResourceDaemonSet = schema.GroupVersionResource{
		Group:    "apps",
		Version:  "v1",
		Resource: "daemonsets",
	}

	// ResourceDeployment is the most commonly used GVR for Deployments
	ResourceDeployment = schema.GroupVersionResource{
		Group:    "apps",
		Version:  "v1",
		Resource: "deployments",
	}

	// ResourceStatefulSet is the most commonly used GVR for StatefulSets
	ResourceStatefulSet = schema.GroupVersionResource{
		Group:    "apps",
		Version:  "v1",
		Resource: "statefulsets",
	}
)
View Source
var (
	// PathMetadata holds the common path to an object's metadata section
	PathMetadata = Path{"metadata"}

	// PathMetadataName holds the common path to an object's name
	PathMetadataName = Path{"metadata", "name"}

	// PathMetadataGenerateName holds the common path to an object's name prefix
	PathMetadataGenerateName = Path{"metadata", "generateName"}

	// PathMetadataNamespace holds the common path to an object's namespace
	PathMetadataNamespace = Path{"metadata", "namespace"}

	// PathLabels holds the common path to an object's label section
	PathLabels = Path{"metadata", "labels"}

	// PathAnnotations holds the common path to an object's annotation section
	PathAnnotations = Path{"metadata", "annotations"}

	// PathOwnerReference holds the common path to an object's owner section
	PathOwnerReference = Path{"metadata", "ownerReferences"}

	// PathOwnerReference holds the common path to an object-owner's kind
	PathOwnerReferenceKind = Path{"metadata", "ownerReferences", "kind"}

	// PathSpec holds the common path to an object's spec section
	PathSpec = Path{"spec"}
)
View Source
var (
	ValidationOk     = ValidationResult{Ok: true}
	ValidationFailed = ValidationResult{Ok: false}
)
View Source
var ManagedFields = FieldCleaner{
	// contains filtered or unexported fields
}

Functions

func GetContextsFromConfig

func GetContextsFromConfig(path string) ([]string, error)

GetContextsFromConfig reads a kubeconfig file and returns a list of contexts names.

func NewErrorResponse

func NewErrorResponse(req *admission.AdmissionRequest, message string) *admission.AdmissionResponse

func ParseLabelSelector

func ParseLabelSelector(obj map[string]interface{}) (metav1.LabelSelector, error)

ParseLabelSelector parses a label selector from a map[string]interface{}. If any of the required keys is of the wrong type, an error is returned as well as all keys that were parsed successfully up to that point. A valid label selector looks like this in YAML:

matchLabels:
  app.kubernetes.io/instance: test
  app.kubernetes.io/name: test
matchExpressions:
  - key: app.kubernetes.io/instance
    operator: In
    values:
      - test

If neither matchLabels nor matchExpressions are present, the selector is expected to be a map[string]string, containing the matchLabels section directly.

Types

type AdmissionRequestHook

type AdmissionRequestHook struct {
	Create ValidationFunc
	Delete ValidationFunc
	Update ValidationFunc
}

AdmissionRequestHook is a helper struct to automaticall map admission operations to functions.

func (AdmissionRequestHook) Call

Call runs the correct callback per requested operation. If an operation does not have a callback registered, an error is reported, but the request is reported as validated.

func (AdmissionRequestHook) Handle

func (h AdmissionRequestHook) Handle(ctx *gin.Context)

Handle reads an admission request, calls the corresponding hook and builds the correct response object.

type ArrayNotation

type ArrayNotation int

ArrayNotation defines the type of an array index notation. Either Index, for explicit indexing or Traversal for "any" access.

func GetArrayNotation

func GetArrayNotation(key string) ArrayNotation

GetArrayNotation returns the notation type of an array index notation value

type Client

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

Client allows communication with the kubernetes API.

func NewClient

func NewClient(path string) (*Client, error)

NewClient creates a new kubernetes client for a given path to a kubeconfig. The client will use the default context from the kubeconfig file.

func NewClientUsingContext

func NewClientUsingContext(path, context string) (*Client, error)

NewClientUsingContext creates a new kubernetes client for a given path to a kubeconfig file. If no file is given, an in-cluster client will be created. The context parameter can be used to specify a specific context from the kubeconfig file. When left empty, the default context will be used.

func NewClusterClient

func NewClusterClient() (*Client, error)

NewClusterClient creates a new kubernetes client for the current cluster.

func (*Client) Apply

func (k8s *Client) Apply(resource schema.GroupVersionResource, object NamedObject, options metav1.ApplyOptions, ctx context.Context) error

Apply creates or updates a given kubernetes object. If a namespace is set, the object will be created in that namespace.

func (*Client) DeleteNamespaced

func (k8s *Client) DeleteNamespaced(resource schema.GroupVersionResource, name, namespace string, ctx context.Context) error

DeleteNamespaced removes a specific kubernetes object from a specific namespace. If an empty namespace is given, the object will be treated as a cluster-wide resource.

func (*Client) GetNamedObject

func (k8s *Client) GetNamedObject(resource schema.GroupVersionResource, name string, ctx context.Context) (NamedObject, error)

GetNamedObject returns a specific kubernetes object

func (*Client) GetNamespacedObject

func (k8s *Client) GetNamespacedObject(resource schema.GroupVersionResource, name, namespace string, ctx context.Context) (NamedObject, error)

GetNamespacedObject returns a specific kubernetes object from a specific namespace

func (*Client) GetServiceAccountToken

func (k8s *Client) GetServiceAccountToken(serviceAccountName, namespace string, expiration time.Duration, audiences []string, pod NamedObject, ctx context.Context) (string, error)

GetServiceAccountToken returns a token for a given service account. This requires the calling service to have the necessary permissions for `authentication.k8s.io/tokenrequests`.

func (*Client) ListAllObjects

func (k8s *Client) ListAllObjects(resource schema.GroupVersionResource, labelSelector, fieldSelector string, ctx context.Context) ([]NamedObject, error)

ListAllObjects returns a list of all objects for a given type that is assumed to be global.

func (*Client) ListAllObjectsInNamespace

func (k8s *Client) ListAllObjectsInNamespace(resource schema.GroupVersionResource, namespace, labelSelector, fieldSelector string, ctx context.Context) ([]NamedObject, error)

ListAllObjectsInNamespace returns a list of all objects for a given type in a given namespace.

func (*Client) ListAllObjectsInNamespaceMatching

func (k8s *Client) ListAllObjectsInNamespaceMatching(resource schema.GroupVersionResource, namespace string, labelMatchExpression metav1.LabelSelector, fieldSelector string, ctx context.Context) ([]NamedObject, error)

ListAllObjectsInNamespaceMatching returns a list of all objects matching a given selector struct. This struct is used in varios API objects like namespaceSelector or objectSelector. Use ParseLabelSelector to create this struct from an existing object.

func (*Client) ListAllObjectsMatching

func (k8s *Client) ListAllObjectsMatching(resource schema.GroupVersionResource, labelMatchExpression metav1.LabelSelector, fieldSelector string, ctx context.Context) ([]NamedObject, error)

ListAllObjectsMatching returns a list of all objects matching a given selector struct. This struct is used in varios API objects like namespaceSelector or objectSelector. Use ParseLabelSelector to create this struct from an existing object.

func (*Client) Patch

func (k8s *Client) Patch(resource schema.GroupVersionResource, object NamedObject, patches []PatchOperation, options metav1.PatchOptions, ctx context.Context) error

Patch applies a set of patches on a given kubernetes object. The patches are applied as json patches.

type ErrIncorrectType

type ErrIncorrectType string

ErrIncorrectType is returned when a value retrieved from a path does not match the expected type for the operation. This occurs when:

  • GetString is called but the value is not a string
  • GetSection is called but the value is not a map[string]interface{}
  • GetList is called but the value is not a []interface{}

The error string contains the actual type that was encountered (e.g., "int", "bool").

func (ErrIncorrectType) Error

func (e ErrIncorrectType) Error() string

type ErrIndexNotation

type ErrIndexNotation struct{}

ErrIndexNotation is returned when attempting to use explicit array index notation during path extension operations that require dynamic array growth. This occurs when:

  • Trying to create or add elements to an array using index notation (e.g., "0", "1") instead of the append notation ("-")
  • The operation would require inserting at a specific index during array creation

Array modification operations must use "-" for appending; explicit indices are not supported during path extension.

func (ErrIndexNotation) Error

func (e ErrIndexNotation) Error() string

type ErrInvalidBoundObjectRef added in v4.1.0

type ErrInvalidBoundObjectRef struct{}

ErrInvalidBoundObjectRef is returned when attempting to create a service account token with an invalid bound object reference. This occurs when:

  • A bound object reference is provided but is not a Pod
  • The Kind field is set to something other than "pod" (case-insensitive)

Service account tokens can only be bound to Pod objects or have no binding.

func (ErrInvalidBoundObjectRef) Error added in v4.1.0

func (e ErrInvalidBoundObjectRef) Error() string

type ErrMissingArrayTraversal

type ErrMissingArrayTraversal string

ErrMissingArrayTraversal is returned when a path reaches an array but the next path segment does not include proper array notation. This occurs when:

  • An array is encountered but the next path element is neither an index (e.g., "0", "1") nor a traversal indicator ("-")
  • The path syntax is invalid for array access

Valid array notations are numeric indices or "-" for traversal. The error string contains the problematic path key.

func (ErrMissingArrayTraversal) Error

func (e ErrMissingArrayTraversal) Error() string

type ErrMissingName added in v4.1.0

type ErrMissingName struct{}

ErrMissingName is returned when a Kubernetes object does not have a name or generateName field set in its metadata. This occurs during object validation in NamedObjectFromUnstructured when neither metadata.name nor metadata.generateName is present. All Kubernetes objects must have at least one of these fields defined.

func (ErrMissingName) Error added in v4.1.0

func (e ErrMissingName) Error() string

type ErrNoCallback added in v4.1.0

type ErrNoCallback string

ErrNoCallback is returned when an admission webhook receives a request for an operation that does not have a validation callback registered. This occurs in AdmissionRequestHook.Call when the operation (Create, Update, or Delete) handler is nil. The request is still marked as validated to avoid blocking operations.

The error string contains the operation name that lacks a callback.

func (ErrNoCallback) Error added in v4.1.0

func (e ErrNoCallback) Error() string

type ErrNoData added in v4.1.0

type ErrNoData struct{}

ErrNoData is returned when a RawExtension object does not contain any data. This occurs when both the Raw and Object fields are nil during conversion from a runtime.RawExtension to a NamedObject.

func (ErrNoData) Error added in v4.1.0

func (e ErrNoData) Error() string

type ErrNoToken added in v4.1.0

type ErrNoToken struct{}

ErrNoToken is returned when a service account token request succeeds but the response does not contain a token. This occurs in GetServiceAccountToken when the Kubernetes API returns a successful response with an empty token field, indicating an unexpected API behavior.

func (ErrNoToken) Error added in v4.1.0

func (e ErrNoToken) Error() string

type ErrNotAnArray

type ErrNotAnArray string

ErrNotAnArray is returned when array notation (index or traversal) is used on a path element that is not an array. This occurs when:

  • A map/object is encountered but the path uses array syntax (e.g., "key/-" or "key/0")
  • Array notation is applied to a non-slice type

The error string contains the path key where the invalid array notation was used.

func (ErrNotAnArray) Error

func (e ErrNotAnArray) Error() string

type ErrNotFound

type ErrNotFound string

ErrNotFound is returned when a requested path key or array index does not exist in a NamedObject. This error is used during path traversal operations when:

  • A map key is not present in the object
  • An array index is out of bounds
  • A traversal operation ("-") finds no matching elements
  • A MatchFunc returns false, indicating no match was found

The error string contains the key or index that was not found.

func (ErrNotFound) Error

func (e ErrNotFound) Error() string

type ErrNotKeyValue

type ErrNotKeyValue string

ErrNotKeyValue is returned when a path operation expects a key-value structure (map[string]interface{}) but encounters a different type. This error type is defined but currently not used in the codebase. It may be reserved for future validation of path items that must be key-value objects.

The error string would contain the problematic path item identifier.

func (ErrNotKeyValue) Error

func (e ErrNotKeyValue) Error() string

type ErrNotTraversable

type ErrNotTraversable string

ErrNotTraversable is returned when attempting to traverse through a path element that cannot be navigated. This occurs when:

  • A nil value is encountered in the traversal path
  • A node is expected to be a map but is not of type map[string]interface{}
  • A node is expected to be a slice but is not of type []interface{}
  • A parent node during mutation is not the expected map or slice type
  • A node is of an unsupported type for traversal (e.g., primitives, structs)

The error string describes what was encountered and why it cannot be traversed.

func (ErrNotTraversable) Error

func (e ErrNotTraversable) Error() string

type ErrParseError added in v4.1.0

type ErrParseError string

ErrParseError is returned when parsing label selector components fails due to type mismatches. This occurs in ParseLabelSelector when:

  • A selector value is not a string
  • matchLabels is not a map[string]string or map[string]interface{}
  • matchExpressions is not the expected slice type
  • A matchExpressions element is not a map[string]interface{}
  • Required fields (key, operator, values) are not of the expected type

The error string contains details about what failed to parse and the actual value.

func (ErrParseError) Error added in v4.1.0

func (e ErrParseError) Error() string

type ErrUnknownOperation added in v4.1.0

type ErrUnknownOperation string

ErrUnknownOperation is returned when an admission webhook receives a request with an operation type that is not recognized. Valid operations are Create, Update, and Delete. This error occurs in AdmissionRequestHook.Call when the admission request contains an unsupported operation.

The error string contains the unknown operation name.

func (ErrUnknownOperation) Error added in v4.1.0

func (e ErrUnknownOperation) Error() string

type ErrUnsupportedHashType added in v4.1.0

type ErrUnsupportedHashType string

ErrUnsupportedHashType is returned when attempting to hash a field with a type that is not supported by the hashing algorithm. This occurs when:

  • A field type cannot be converted to a hashable representation
  • An unknown or complex type is encountered during object hashing

The error string contains the field name and its type information.

func (ErrUnsupportedHashType) Error added in v4.1.0

func (e ErrUnsupportedHashType) Error() string

type FieldCleaner

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

func (FieldCleaner) Clean

func (f FieldCleaner) Clean(obj map[string]interface{}) map[string]interface{}

Remove fields from an existing object

type NamedObject

type NamedObject map[string]interface{}

NamedObject represents a kubernetes object and provides common functionality such as patch generators or accessing common fields.

func NamedObjectFromRaw

func NamedObjectFromRaw(data *runtime.RawExtension) (NamedObject, error)

NamedObjectFromUnstructured converts a raw runtime object intor a namespaced object. If the object does not have name or namespace set an error will be returned.

func NamedObjectFromUnstructured

func NamedObjectFromUnstructured(unstructuredObj unstructured.Unstructured) (NamedObject, error)

NamedObjectFromUnstructured converts an unstructured Kubernetes object into a namespaced object. If the object does not have name or namespace set an error will be returned.

func NewNamedObject

func NewNamedObject(name string) NamedObject

NewNamedObject create a new object with metdata.name set

func (NamedObject) CreateAddPatch

func (obj NamedObject) CreateAddPatch(path Path, value interface{}) PatchOperation

CreateAddPatch generates an add patch based.

func (NamedObject) CreateRemovePatch

func (obj NamedObject) CreateRemovePatch(path Path) PatchOperation

RemoveField generates a remove patch.

func (NamedObject) CreateReplacePatch

func (obj NamedObject) CreateReplacePatch(path Path, value interface{}) PatchOperation

PatchField generates a replace patch.

func (NamedObject) DeepCopyObject

func (obj NamedObject) DeepCopyObject() runtime.Object

DeepCopyObject implements the runtime.Object interface.

func (NamedObject) Delete

func (obj NamedObject) Delete(path Path) error

Delete will remove a given key on a given path. If an unindexed array notation is used ("[]") the first matching path will be used, which might lead to the key not being deleted. If the path is not valid because a key in the path does not exist, is no map or array, false will be returned. If the key is deleted or does not exist, true will be returned.

func (NamedObject) EachListItem

func (obj NamedObject) EachListItem(func(runtime.Object) error) error

EachListItem implements the runtime.Unstructured interface. This function does nothing.

func (NamedObject) EachListItemWithAlloc

func (obj NamedObject) EachListItemWithAlloc(func(runtime.Object) error) error

EachListItemWithAlloc implements the runtime.Unstructured interface. This function does nothing.

func (NamedObject) FindAll

func (obj NamedObject) FindAll(path Path, value interface{}) ([]Path, error)

Find looks for a path with the given value and returns all matching paths. If nil is passed as a value, all full matching paths will be returned.

func (NamedObject) FindFirst

func (obj NamedObject) FindFirst(path Path, value interface{}) (Path, error)

FindFirst looks for a path with the given value and returns the first, resolved, matching path. If nil is passed as a value just the path will be matched.

func (NamedObject) GeneratePatch

func (obj NamedObject) GeneratePatch(path Path, value interface{}) (Path, interface{}, error)

GeneratePatch will reduce the given path so that only exisiting elements are included. The given value will be extended so that missing elements from the path will be created. Please note that path creation will fail if non- existing arrays are addressed using index notation.

func (NamedObject) Get

func (obj NamedObject) Get(path Path) (interface{}, error)

Get will return an object for a given path. If the object or any part of the path does not exist, nil is returned. If an unindexed array notation is used ("[]") the first matching path is returned.

func (NamedObject) GetAnnotation

func (obj NamedObject) GetAnnotation(key string) (string, error)

GetAnnotation will return the value of a given label. If the annotation is not set, an empty string and false is returned.

func (NamedObject) GetKind

func (obj NamedObject) GetKind() string

GetKind returns the kind of the object.

func (NamedObject) GetLabel

func (obj NamedObject) GetLabel(key string) (string, error)

GetLabel will return the value of a given label. If the label is not set, an empty string and false is returned.

func (NamedObject) GetList

func (obj NamedObject) GetList(path Path) ([]interface{}, error)

GetList will return a []interface{} assigned to a given key on a given path. If the object is not a list or the path or key does not exist, nil and an error are returned.

func (NamedObject) GetName

func (obj NamedObject) GetName() string

GetName will return the name of the object. The name can be a prefix if a pod is processed before it has been processed by the corresponding, e.g., ReplicaSet controller. If the name is not set, an empty string is returned.

func (NamedObject) GetNamespace

func (obj NamedObject) GetNamespace() string

GetName will return the namespace of the object. If the namespace is not set, an empty string is returned.

func (NamedObject) GetObjectKind

func (obj NamedObject) GetObjectKind() schema.ObjectKind

GetObjectKind implements the runtime.Object interface. Returns schema.EmptyObjectKind

func (NamedObject) GetOwnerKind

func (obj NamedObject) GetOwnerKind() string

GetOwnerKind returns the resource kind of an owning resource, e.g., ReplicaSet if the pod is managed by a ReplicaSet

func (NamedObject) GetSection

func (obj NamedObject) GetSection(path Path) (map[string]interface{}, error)

GetSection will return a map[string]interface{} (a sub-section) assigned to a given key on a given path. If the object is not a map or the path or key does not exist, nil and an error are returned.

func (NamedObject) GetString

func (obj NamedObject) GetString(path Path) (string, error)

GetString will return a string value assigned to a given key on a given path. If the object is not a string or the path or key does not exist, an empty string and an error are returned.

func (NamedObject) GetUID

func (obj NamedObject) GetUID() string

GetUID returns the UID of the object from the metadata.

func (NamedObject) GetVersion

func (obj NamedObject) GetVersion() string

GetVersion returns the apiVersion of the object.

func (NamedObject) Has

func (obj NamedObject) Has(path Path) bool

Has will return true if a key on a given path is set.

func (NamedObject) HasAnnotations

func (obj NamedObject) HasAnnotations() bool

HasAnnotations returns true if an annotation section exists

func (NamedObject) HasLabels

func (obj NamedObject) HasLabels() bool

HasLabels returns true if a labels section exists

func (NamedObject) Hash

func (obj NamedObject) Hash() (uint64, error)

Hash calculates an ordered hash of the object.

func (NamedObject) HashStr

func (obj NamedObject) HashStr() (string, error)

Hash calculates an ordered hash of the object an returns a base64 encoded string.

func (NamedObject) IsAnnotationNotSetTo

func (obj NamedObject) IsAnnotationNotSetTo(key, value string) bool

IsAnnotationNotSetTo checks if a specific annotation is not set to a given value. The comparison is done in a case insensitive way.

func (NamedObject) IsAnnotationSetTo

func (obj NamedObject) IsAnnotationSetTo(key, value string) bool

IsAnnotationSetTo checks if a specific annotation is set to a given value. The comparison is done in a case insensitive way.

func (NamedObject) IsLabelNotSetTo

func (obj NamedObject) IsLabelNotSetTo(key, value string) bool

IsLabelNotSetTo checks if a specific label is not set to a given value. The comparison is done in a case insensitive way.

func (NamedObject) IsLabelSetTo

func (obj NamedObject) IsLabelSetTo(key, value string) bool

IsLabelSetTo checks if a specific label is set to a given value. The comparison is done in a case insensitive way.

func (NamedObject) IsList

func (obj NamedObject) IsList() bool

IsList implements the runtime.Unstructured interface. This function returns false

func (NamedObject) IsOfKind

func (obj NamedObject) IsOfKind(kind, apiVersion string) bool

IsOfKind returns true if the object is of the given kind and/or apiVersion. Both kind and apiVersion can be an empty string, which translates to "any"

func (NamedObject) NewEmptyInstance

func (obj NamedObject) NewEmptyInstance() runtime.Unstructured

NewEmptyInstance implements the runtime.Unstructured interface. Returns an empty NamedObject.

func (NamedObject) RemoveManagedFields

func (obj NamedObject) RemoveManagedFields()

RemoveManagedFields removes managed fields from an object. See KubernetesManagedFields and FieldCleaner.

func (NamedObject) Set

func (obj NamedObject) Set(path Path, value interface{}) error

Set will set a value for a given key on a given path. The path will be created if not existing through a call to GeneratePatch.

func (NamedObject) SetAnnotation

func (obj NamedObject) SetAnnotation(key, value string) error

SetAnnotation will set an annotation on the object. It will create the annotations section if it does not exist.

func (NamedObject) SetLabel

func (obj NamedObject) SetLabel(key, value string) error

SetAnnotation will set a label on the object. It will create the labels section if it does not exist.

func (NamedObject) SetName

func (obj NamedObject) SetName(value string) error

SetName will set the name of the object.

func (NamedObject) SetNamespace

func (obj NamedObject) SetNamespace(value string) error

SetName will set the namespace of the object.

func (NamedObject) SetUnstructuredContent

func (obj NamedObject) SetUnstructuredContent(new map[string]interface{})

SetUnstructuredContent implements the runtime.Unstructured interface.

func (NamedObject) ToJSON

func (obj NamedObject) ToJSON() (string, error)

ToJSON generates a JSON string out of this object

func (NamedObject) UnstructuredContent

func (obj NamedObject) UnstructuredContent() map[string]interface{}

UnstructuredContent implements the runtime.Unstructured interface. Returns the object itself

func (*NamedObject) Walk

func (obj *NamedObject) Walk(path Path, args WalkArgs) (interface{}, error)

Walk will iterate the path up until key is found or path cannot be matched. If key is found, the value of key and true is returned. Otherwise nil and false will be returned.

type ParsedAdmissionRequest

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

func NewParsedAdmissionRequest

func NewParsedAdmissionRequest(gvr schema.GroupVersionResource, name, namespace string, new, old NamedObject) ParsedAdmissionRequest

NewParsedAdmissionRequest creates a new ParsedAdmissionRequest from a given resources. This can be used to simulate AdmissionRequests.

func ParseRequest

ParseRequest converts an kubernetes AdmissionRequest into a parsed request.

func (*ParsedAdmissionRequest) GetExistingObject

func (p *ParsedAdmissionRequest) GetExistingObject() (NamedObject, error)

GetExistingObject returns the object existing on the cluster. This object is only available on Delete and Update requests.

func (*ParsedAdmissionRequest) GetGroupVersionResource

func (p *ParsedAdmissionRequest) GetGroupVersionResource() schema.GroupVersionResource

GetGroupVersionResource returns the GroupVersionResource assigned to this request.

func (*ParsedAdmissionRequest) GetIncomingJSON

func (p *ParsedAdmissionRequest) GetIncomingJSON() []byte

Returns the incoming object raw json string

func (*ParsedAdmissionRequest) GetIncomingObject

func (p *ParsedAdmissionRequest) GetIncomingObject() (NamedObject, error)

GetIncomingObject returns the object to be placed on the cluster. This object is only available on Create and Update requests.

func (*ParsedAdmissionRequest) GetName

func (p *ParsedAdmissionRequest) GetName() string

GetName returns the name assigned to the admission request. This should be equal to GetNewObject().GetName()

func (*ParsedAdmissionRequest) GetNamespace

func (p *ParsedAdmissionRequest) GetNamespace() string

GetNamespace returns the namespace assigned to the admission request.

type PatchOperation

type PatchOperation struct {
	Op    string      `json:"op"`
	Path  string      `json:"path"`
	From  string      `json:"from,omitempty"`
	Value interface{} `json:"value,omitempty"`
}

PatchOperation is an operation of a JSON patch https://tools.ietf.org/html/rfc6902. This is required to report changes back through an admissionreview response.

func NewPatchOperationAdd

func NewPatchOperationAdd(path string, value interface{}) PatchOperation

NewPatchOperationAdd returns an "add" JSON patch operation.

func NewPatchOperationCopy

func NewPatchOperationCopy(from, path string) PatchOperation

NewPatchOperationCopy returns a "copy" JSON patch operation.

func NewPatchOperationMove

func NewPatchOperationMove(from, path string) PatchOperation

NewPatchOperationMove returns a "move" JSON patch operation.

func NewPatchOperationRemove

func NewPatchOperationRemove(path string) PatchOperation

NewPatchOperationRemove returns a "remove" JSON patch operation.

func NewPatchOperationReplace

func NewPatchOperationReplace(path string, value interface{}) PatchOperation

NewPatchOperationReplace returns a "replace" JSON patch operation.

type Path

type Path []string

Path holds a list of path elements that can be used to traverse a namedObject. Arrays access is denoted with 2 elements in the list: the name of the array and the traversalNotation. The later is either "-" for "any" or a number denoting the index.

func ConcatPaths

func ConcatPaths(p1, p2 Path) Path

ConcatPaths will create a new path object by concatenating both pathes. Note that this function will always allocate new memory.

func NewPath

func NewPath(p Path, key ...string) Path

NewPath creates a new path object by appending a key to the given path. Note that this function will always allocate new memory.

func NewPathFromJQFormat

func NewPathFromJQFormat(jqPath string) Path

NewPathFromJQFormat accepts a JQ-style path and transforms it into a Path object. Field names can be quoted using single tick. Arrays need to use square-braces postfixes (Array[]). Empty braces translated to "all" (read) or "append" (write). Example of a jq path string: "a.b[].c[1].'d'.e"

func NewPathFromJSONPathFormat

func NewPathFromJSONPathFormat(jsonPath string) Path

NewPathFromJSONPathFormat accepts a JSON path and transforms it into a Path object. See https://jsonpatch.com/#json-pointer Example of a JSON-Path string: "a/b/-/c/1/d/e"

func (Path) IsArray

func (p Path) IsArray(idx int) (bool, ArrayNotation)

IsArray returns true if an element at a specific location is either a fully referenced array (name + index notation) or if it is just an index notation.

func (Path) SplitKey

func (p Path) SplitKey() (Path, string)

SplitKey extracts the last element from the path and returns it as a separate key. If the last element denotes an array access, the access pattern (all or explicit index) is dropped and only the name is returned.

func (Path) ToJSONPath

func (p Path) ToJSONPath() string

ToJSONPath converts the path to a valid JSONPatch path, escaping special characters if needed. See https://jsonpatch.com/#json-pointer

type ValidationFunc

type ValidationFunc func(req ParsedAdmissionRequest) ValidationResult

ValidationFunc callback function prototype for hooks

type ValidationResult

type ValidationResult struct {
	// Ok holds the result of the validation
	Ok bool
	// Message can give additional context on the result
	Message string
	// Patches may hold modifications to be done on the validated object
	Patches []PatchOperation
}

Result of a ValidationFunc.

func (ValidationResult) ToResponse

type WalkArgs

type WalkArgs struct {
	// MatchAll will iterate over all matches when set to true.
	MatchAll bool

	// MatchFunc is called whenever a path is found to be matching.
	// The path is the resolved path, i.e. array search notation is transformed
	// into array index notation.
	MatchFunc func(value interface{}, p Path) bool

	// MutateFunc allows a value to be modified or deleted after match.
	MutateFunc func(value interface{}) interface{}

	// NotFoundFunc is alled whenever walk needs to abort path walking.
	// The path contains the traversed path up to (including) the key that was
	// not found,
	NotFoundFunc func(p Path)
	// contains filtered or unexported fields
}

WalkArgs is the parameter set passed to the walk function.

Jump to

Keyboard shortcuts

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