resource

package
v0.31.1 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2024 License: Apache-2.0 Imports: 48 Imported by: 1,499

Documentation

Overview

Package resource assists clients in dealing with RESTful objects that match the Kubernetes API conventions. The Helper object provides simple CRUD operations on resources. The Visitor interface makes it easy to deal with multiple resources in bulk for retrieval and operation. The Builder object simplifies converting standard command line arguments and parameters into a Visitor that can iterate over all of the identified resources, whether on the server or on the local filesystem.

Index

Examples

Constants

This section is empty.

Variables

View Source
var FakeCategoryExpander restmapper.CategoryExpander = restmapper.SimpleCategoryExpander{
	Expansions: map[string][]schema.GroupResource{
		"all": {
			{Group: "", Resource: "pods"},
			{Group: "", Resource: "replicationcontrollers"},
			{Group: "", Resource: "services"},
			{Group: "apps", Resource: "statefulsets"},
			{Group: "autoscaling", Resource: "horizontalpodautoscalers"},
			{Group: "batch", Resource: "jobs"},
			{Group: "batch", Resource: "cronjobs"},
			{Group: "extensions", Resource: "daemonsets"},
			{Group: "extensions", Resource: "deployments"},
			{Group: "extensions", Resource: "replicasets"},
		},
	},
}

FakeCategoryExpander is for testing only

View Source
var FileExtensions = []string{".json", ".yaml", ".yml"}
View Source
var InputExtensions = append(FileExtensions, "stdin")
View Source
var LocalResourceError = errors.New(`error: you must specify resources by --filename when --local is set.
Example resource specifications include:
   '-f rsrc.yaml'
   '--filename=rsrc.json'`)
View Source
var StdinMultiUseError = errors.New("standard input cannot be used for multiple arguments")

Functions

func EnhanceListError added in v0.22.0

func EnhanceListError(err error, opts metav1.ListOptions, subj string) error

EnhanceListError augments errors typically returned by List operations with additional context, making sure to retain the StatusError type when applicable.

func FilterNamespace

func FilterNamespace(info *Info, err error) error

FilterNamespace omits the namespace if the object is not namespace scoped

func FollowContinue added in v0.22.0

func FollowContinue(initialOpts *metav1.ListOptions,
	listFunc func(metav1.ListOptions) (runtime.Object, error)) error

FollowContinue handles the continue parameter returned by the API server when using list chunking. To take advantage of this, the initial ListOptions provided by the consumer should include a non-zero Limit parameter.

func HasNames

func HasNames(args []string) (bool, error)

HasNames returns true if the provided args contain resource names

func IsParamUnsupportedError added in v0.24.0

func IsParamUnsupportedError(err error) bool

func IsUsageError

func IsUsageError(err error) bool

TODO: expand this to include other errors.

func NewParamUnsupportedError added in v0.24.0

func NewParamUnsupportedError(gvk schema.GroupVersionKind, param VerifiableQueryParam) error

func RetrieveLatest

func RetrieveLatest(info *Info, err error) error

RetrieveLatest updates the Object on each Info by invoking a standard client Get.

func RetrieveLazy

func RetrieveLazy(info *Info, err error) error

RetrieveLazy updates the object if it has not been loaded yet.

func SplitResourceArgument

func SplitResourceArgument(arg string) []string

SplitResourceArgument splits the argument with commas and returns unique strings in the original order.

func UnstructuredPlusDefaultContentConfig

func UnstructuredPlusDefaultContentConfig() rest.ContentConfig

UnstructuredPlusDefaultContentConfig returns a rest.ContentConfig for dynamic types. It includes enough codecs to act as a "normal" serializer for the rest.client with options, status and the like.

func UpdateObjectNamespace

func UpdateObjectNamespace(info *Info, err error) error

func ValidateSchema

func ValidateSchema(data []byte, schema ContentValidator) error

Types

type Builder

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

Builder provides convenience functions for taking arguments and parameters from the command line and converting them to a list of resources to iterate over using the Visitor interface.

func NewBuilder

func NewBuilder(restClientGetter RESTClientGetter) *Builder

func NewFakeBuilder

func NewFakeBuilder(fakeClientFn FakeClientFunc, restMapper RESTMapperFunc, categoryExpander CategoryExpanderFunc) *Builder

func NewLocalBuilder added in v0.20.0

func NewLocalBuilder() *Builder

NewLocalBuilder returns a builder that is configured not to create REST clients and avoids asking the server for results.

Example

ExampleNewLocalBuilderLoad demonstrates using a local resource builder to read typed resources from a manifest

package main

import (
	"bytes"
	"fmt"

	"k8s.io/cli-runtime/pkg/resource"
	"k8s.io/client-go/kubernetes/scheme"
)

var exampleManifest = `
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: mutating1
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfigurationList
items:
- apiVersion: admissionregistration.k8s.io/v1
  kind: MutatingWebhookConfiguration
  metadata:
    name: mutating2
- apiVersion: admissionregistration.k8s.io/v1
  kind: MutatingWebhookConfiguration
  metadata:
    name: mutating3
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: validating1
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfigurationList
items:
- apiVersion: admissionregistration.k8s.io/v1
  kind: ValidatingWebhookConfiguration
  metadata:
    name: validating2
- apiVersion: admissionregistration.k8s.io/v1
  kind: ValidatingWebhookConfiguration
  metadata:
    name: validating3
---
apiVersion: v1
kind: List
items:
- apiVersion: admissionregistration.k8s.io/v1
  kind: MutatingWebhookConfiguration
  metadata:
    name: mutating4
- apiVersion: admissionregistration.k8s.io/v1
  kind: ValidatingWebhookConfiguration
  metadata:
    name: validating4
---
`

// ExampleNewLocalBuilderLoad demonstrates using a local resource builder to read typed resources from a manifest
func main() {
	// Create a local builder...
	builder := resource.NewLocalBuilder().
		// Configure with a scheme to get typed objects in the versions registered with the scheme.
		// As an alternative, could call Unstructured() to get unstructured objects.
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		// Provide input via a Reader.
		// As an alternative, could call Path(false, "/path/to/file") to read from a file.
		Stream(bytes.NewBufferString(exampleManifest), "input").
		// Flatten items contained in List objects
		Flatten().
		// Accumulate as many items as possible
		ContinueOnError()

	// Run the builder
	result := builder.Do()

	if err := result.Err(); err != nil {
		fmt.Println("builder error:", err)
		return
	}

	items, err := result.Infos()
	if err != nil {
		fmt.Println("infos error:", err)
		return
	}

	for _, item := range items {
		fmt.Printf("%s (%T)\n", item.String(), item.Object)
	}

}
Output:

Name: "mutating1", Namespace: "" (*v1.MutatingWebhookConfiguration)
Name: "mutating2", Namespace: "" (*v1.MutatingWebhookConfiguration)
Name: "mutating3", Namespace: "" (*v1.MutatingWebhookConfiguration)
Name: "validating1", Namespace: "" (*v1.ValidatingWebhookConfiguration)
Name: "validating2", Namespace: "" (*v1.ValidatingWebhookConfiguration)
Name: "validating3", Namespace: "" (*v1.ValidatingWebhookConfiguration)
Name: "mutating4", Namespace: "" (*v1.MutatingWebhookConfiguration)
Name: "validating4", Namespace: "" (*v1.ValidatingWebhookConfiguration)

func (*Builder) AddError

func (b *Builder) AddError(err error) *Builder

func (*Builder) AllNamespaces

func (b *Builder) AllNamespaces(allNamespace bool) *Builder

AllNamespaces instructs the builder to metav1.NamespaceAll as a namespace to request resources across all of the namespace. This overrides the namespace set by NamespaceParam().

func (*Builder) ContinueOnError

func (b *Builder) ContinueOnError() *Builder

ContinueOnError will attempt to load and visit as many objects as possible, even if some visits return errors or some objects cannot be loaded. The default behavior is to terminate after the first error is returned from a VisitorFunc.

func (*Builder) DefaultNamespace

func (b *Builder) DefaultNamespace() *Builder

DefaultNamespace instructs the builder to set the namespace value for any object found to NamespaceParam() if empty.

func (*Builder) Do

func (b *Builder) Do() *Result

Do returns a Result object with a Visitor for the resources identified by the Builder. The visitor will respect the error behavior specified by ContinueOnError. Note that stream inputs are consumed by the first execution - use Infos() or Object() on the Result to capture a list for further iteration.

func (*Builder) FieldSelectorParam

func (b *Builder) FieldSelectorParam(s string) *Builder

FieldSelectorParam defines a selector that should be applied to the object types to load. This will not affect files loaded from disk or URL. If the parameter is empty it is a no-op - to select all resources.

func (*Builder) FilenameParam

func (b *Builder) FilenameParam(enforceNamespace bool, filenameOptions *FilenameOptions) *Builder

FilenameParam groups input in two categories: URLs and files (files, directories, STDIN) If enforceNamespace is false, namespaces in the specs will be allowed to override the default namespace. If it is true, namespaces that don't match will cause an error. If ContinueOnError() is set prior to this method, objects on the path that are not recognized will be ignored (but logged at V(2)).

func (*Builder) Flatten

func (b *Builder) Flatten() *Builder

Flatten will convert any objects with a field named "Items" that is an array of runtime.Object compatible types into individual entries and give them their own items. The original object is not passed to any visitors.

func (*Builder) LabelSelector

func (b *Builder) LabelSelector(selector string) *Builder

LabelSelector accepts a selector directly and will filter the resulting list by that object. Use LabelSelectorParam instead for user input.

func (*Builder) LabelSelectorParam

func (b *Builder) LabelSelectorParam(s string) *Builder

LabelSelectorParam defines a selector that should be applied to the object types to load. This will not affect files loaded from disk or URL. If the parameter is empty it is a no-op - to select all resources invoke `b.LabelSelector(labels.Everything.String)`.

func (*Builder) Latest

func (b *Builder) Latest() *Builder

Latest will fetch the latest copy of any objects loaded from URLs or files from the server.

func (*Builder) Local

func (b *Builder) Local() *Builder

Local will avoid asking the server for results.

func (*Builder) LocalParam

func (b *Builder) LocalParam(local bool) *Builder

LocalParam calls Local() if local is true.

func (*Builder) Mapper

func (b *Builder) Mapper() *mapper

Mapper returns a copy of the current mapper.

func (*Builder) NamespaceParam

func (b *Builder) NamespaceParam(namespace string) *Builder

NamespaceParam accepts the namespace that these resources should be considered under from - used by DefaultNamespace() and RequireNamespace()

func (*Builder) Path

func (b *Builder) Path(recursive bool, paths ...string) *Builder

Path accepts a set of paths that may be files, directories (all can containing one or more resources). Creates a FileVisitor for each file and then each FileVisitor is streaming the content to a StreamVisitor. If ContinueOnError() is set prior to this method being called, objects on the path that are unrecognized will be ignored (but logged at V(2)).

func (*Builder) ReplaceAliases

func (b *Builder) ReplaceAliases(input string) string

ReplaceAliases accepts an argument and tries to expand any existing aliases found in it

func (*Builder) RequestChunksOf

func (b *Builder) RequestChunksOf(chunkSize int64) *Builder

RequestChunksOf attempts to load responses from the server in batches of size limit to avoid long delays loading and transferring very large lists. If unset defaults to no chunking.

func (*Builder) RequireNamespace

func (b *Builder) RequireNamespace() *Builder

RequireNamespace instructs the builder to set the namespace value for any object found to NamespaceParam() if empty, and if the value on the resource does not match NamespaceParam() an error will be returned.

func (*Builder) RequireObject

func (b *Builder) RequireObject(require bool) *Builder

RequireObject ensures that resulting infos have an object set. If false, resulting info may not have an object set.

func (*Builder) ResourceNames

func (b *Builder) ResourceNames(resource string, names ...string) *Builder

ResourceNames accepts a default type and one or more names, and creates tuples of resources

func (*Builder) ResourceTypeOrNameArgs

func (b *Builder) ResourceTypeOrNameArgs(allowEmptySelector bool, args ...string) *Builder

ResourceTypeOrNameArgs indicates that the builder should accept arguments of the form `(<type1>[,<type2>,...]|<type> <name1>[,<name2>,...])`. When one argument is received, the types provided will be retrieved from the server (and be comma delimited). When two or more arguments are received, they must be a single type and resource name(s). The allowEmptySelector permits to select all the resources (via Everything func).

func (*Builder) ResourceTypes

func (b *Builder) ResourceTypes(types ...string) *Builder

ResourceTypes is a list of types of resources to operate on, when listing objects on the server or retrieving objects that match a selector.

func (*Builder) Schema

func (b *Builder) Schema(schema ContentValidator) *Builder

func (*Builder) SelectAllParam

func (b *Builder) SelectAllParam(selectAll bool) *Builder

SelectEverythingParam

func (*Builder) SingleResourceType

func (b *Builder) SingleResourceType() *Builder

SingleResourceType will cause the builder to error if the user specifies more than a single type of resource.

func (*Builder) Stdin

func (b *Builder) Stdin() *Builder

Stdin will read objects from the standard input. If ContinueOnError() is set prior to this method being called, objects in the stream that are unrecognized will be ignored (but logged at V(2)). If StdinInUse() is set prior to this method being called, an error will be recorded as there are multiple entities trying to use the single standard input stream.

func (*Builder) StdinInUse added in v0.22.0

func (b *Builder) StdinInUse() *Builder

StdinInUse will mark standard input as in use by this Builder, and therefore standard input should not be used by another entity. If Stdin() is set prior to this method being called, an error will be recorded as there are multiple entities trying to use the single standard input stream.

func (*Builder) Stream

func (b *Builder) Stream(r io.Reader, name string) *Builder

Stream will read objects from the provided reader, and if an error occurs will include the name string in the error message. If ContinueOnError() is set prior to this method being called, objects in the stream that are unrecognized will be ignored (but logged at V(2)).

func (*Builder) Subresource added in v0.24.0

func (b *Builder) Subresource(subresource string) *Builder

Subresource instructs the builder to retrieve the object at the subresource path instead of the main resource path.

func (*Builder) TransformRequests

func (b *Builder) TransformRequests(opts ...RequestTransform) *Builder

TransformRequests alters API calls made by clients requested from this builder. Pass an empty list to clear modifiers.

func (*Builder) URL

func (b *Builder) URL(httpAttemptCount int, urls ...*url.URL) *Builder

URL accepts a number of URLs directly.

func (*Builder) Unstructured

func (b *Builder) Unstructured() *Builder

Unstructured updates the builder so that it will request and send unstructured objects. Unstructured objects preserve all fields sent by the server in a map format based on the object's JSON structure which means no data is lost when the client reads and then writes an object. Use this mode in preference to Internal unless you are working with Go types directly.

func (*Builder) VisitorConcurrency added in v0.28.0

func (b *Builder) VisitorConcurrency(concurrency int) *Builder

VisitorConcurrency sets the number of concurrent visitors to use when visiting lists.

func (*Builder) WithScheme

func (b *Builder) WithScheme(scheme *runtime.Scheme, decodingVersions ...schema.GroupVersion) *Builder

WithScheme uses the scheme to manage typing, conversion (optional), and decoding. If decodingVersions is empty, then you can end up with internal types. You have been warned.

type CRDFinder added in v0.18.0

type CRDFinder interface {
	HasCRD(gvk schema.GroupKind) (bool, error)
}

CRDFinder keeps a cache of known CRDs and finds a given GVK in the list.

func NewCRDFinder added in v0.18.0

func NewCRDFinder(getter CRDGetter) CRDFinder

type CRDGetter added in v0.18.0

type CRDGetter func() ([]schema.GroupKind, error)

CRDGetter is a function that can download the list of GVK for all CRDs.

func CRDFromDynamic added in v0.18.0

func CRDFromDynamic(client dynamic.Interface) CRDGetter

type CategoryExpanderFunc

type CategoryExpanderFunc func() (restmapper.CategoryExpander, error)

type ClientConfigFunc

type ClientConfigFunc func() (*rest.Config, error)

type ConcurrentVisitorList added in v0.28.0

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

func (ConcurrentVisitorList) Visit added in v0.28.0

type ContentValidator

type ContentValidator interface {
	ValidateBytes(data []byte) error
}

ContentValidator is an interface that knows how to validate an API object serialized to a byte array.

type ContinueOnErrorVisitor

type ContinueOnErrorVisitor struct {
	Visitor
}

ContinueOnErrorVisitor visits each item and, if an error occurs on any individual item, returns an aggregate error after all items are visited.

func (ContinueOnErrorVisitor) Visit

Visit returns nil if no error occurs during traversal, a regular error if one occurs, or if multiple errors occur, an aggregate error. If the provided visitor fails on any individual item it will not prevent the remaining items from being visited. An error returned by the visitor directly may still result in some items not being visited.

type DecoratedVisitor

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

DecoratedVisitor will invoke the decorators in order prior to invoking the visitor function passed to Visit. An error will terminate the visit.

func (DecoratedVisitor) Visit

func (v DecoratedVisitor) Visit(fn VisitorFunc) error

Visit implements Visitor

type EagerVisitorList

type EagerVisitorList []Visitor

EagerVisitorList implements Visit for the sub visitors it contains. All errors will be captured and returned at the end of iteration.

func (EagerVisitorList) Visit

func (l EagerVisitorList) Visit(fn VisitorFunc) error

Visit implements Visitor, and gathers errors that occur during processing until all sub visitors have been visited.

type ErrMatchFunc

type ErrMatchFunc func(error) bool

ErrMatchFunc can be used to filter errors that may not be true failures.

type FakeClientFunc

type FakeClientFunc func(version schema.GroupVersion) (RESTClient, error)

type FileVisitor

type FileVisitor struct {
	Path string
	*StreamVisitor
}

FileVisitor is wrapping around a StreamVisitor, to handle open/close files

func (*FileVisitor) Visit

func (v *FileVisitor) Visit(fn VisitorFunc) error

Visit in a FileVisitor is just taking care of opening/closing files

type FilenameOptions

type FilenameOptions struct {
	Filenames []string
	Kustomize string
	Recursive bool
}

func (*FilenameOptions) RequireFilenameOrKustomize

func (o *FilenameOptions) RequireFilenameOrKustomize() error

type FilterFunc

type FilterFunc func(info *Info, err error) (bool, error)

func FilterByLabelSelector

func FilterByLabelSelector(s labels.Selector) FilterFunc

type FilteredVisitor

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

func (FilteredVisitor) Visit

func (v FilteredVisitor) Visit(fn VisitorFunc) error

type FlattenListVisitor

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

FlattenListVisitor flattens any objects that runtime.ExtractList recognizes as a list - has an "Items" public field that is a slice of runtime.Objects or objects satisfying that interface - into multiple Infos. Returns nil in the case of no errors. When an error is hit on sub items (for instance, if a List contains an object that does not have a registered client or resource), returns an aggregate error.

func (FlattenListVisitor) Visit

func (v FlattenListVisitor) Visit(fn VisitorFunc) error

type Helper

type Helper struct {
	// The name of this resource as the server would recognize it
	Resource string
	// The name of the subresource as the server would recognize it
	Subresource string
	// A RESTClient capable of mutating this resource.
	RESTClient RESTClient
	// True if the resource type is scoped to namespaces
	NamespaceScoped bool
	// If true, then use server-side dry-run to not persist changes to storage
	// for verbs and resources that support server-side dry-run.
	//
	// Note this should only be used against an apiserver with dry-run enabled,
	// and on resources that support dry-run. If the apiserver or the resource
	// does not support dry-run, then the change will be persisted to storage.
	ServerDryRun bool

	// FieldManager is the name associated with the actor or entity that is making
	// changes.
	FieldManager string

	// FieldValidation is the directive used to indicate how the server should perform
	// field validation (Ignore, Warn, or Strict)
	FieldValidation string
}

Helper provides methods for retrieving or mutating a RESTful resource.

func NewHelper

func NewHelper(client RESTClient, mapping *meta.RESTMapping) *Helper

NewHelper creates a Helper from a ResourceMapping

func (*Helper) Create

func (m *Helper) Create(namespace string, modify bool, obj runtime.Object) (runtime.Object, error)

func (*Helper) CreateWithOptions added in v0.18.0

func (m *Helper) CreateWithOptions(namespace string, modify bool, obj runtime.Object, options *metav1.CreateOptions) (runtime.Object, error)

func (*Helper) Delete

func (m *Helper) Delete(namespace, name string) (runtime.Object, error)

func (*Helper) DeleteWithOptions

func (m *Helper) DeleteWithOptions(namespace, name string, options *metav1.DeleteOptions) (runtime.Object, error)

func (*Helper) DryRun added in v0.18.0

func (m *Helper) DryRun(dryRun bool) *Helper

DryRun, if true, will use server-side dry-run to not persist changes to storage. Otherwise, changes will be persisted to storage.

func (*Helper) Get

func (m *Helper) Get(namespace, name string) (runtime.Object, error)

func (*Helper) List

func (m *Helper) List(namespace, apiVersion string, options *metav1.ListOptions) (runtime.Object, error)

func (*Helper) Patch

func (m *Helper) Patch(namespace, name string, pt types.PatchType, data []byte, options *metav1.PatchOptions) (runtime.Object, error)

func (*Helper) Replace

func (m *Helper) Replace(namespace, name string, overwrite bool, obj runtime.Object) (runtime.Object, error)

func (*Helper) Watch

func (m *Helper) Watch(namespace, apiVersion string, options *metav1.ListOptions) (watch.Interface, error)

func (*Helper) WatchSingle

func (m *Helper) WatchSingle(namespace, name, resourceVersion string) (watch.Interface, error)

func (*Helper) WithFieldManager added in v0.19.0

func (m *Helper) WithFieldManager(fieldManager string) *Helper

WithFieldManager sets the field manager option to indicate the actor or entity that is making changes in a create or update operation.

func (*Helper) WithFieldValidation added in v0.24.0

func (m *Helper) WithFieldValidation(validationDirective string) *Helper

WithFieldValidation sets the field validation option to indicate how the server should perform field validation (Ignore, Warn, or Strict).

func (*Helper) WithSubresource added in v0.24.0

func (m *Helper) WithSubresource(subresource string) *Helper

Subresource sets the helper to access (<resource>/[ns/<namespace>/]<name>/<subresource>)

type Info

type Info struct {
	// Client will only be present if this builder was not local
	Client RESTClient
	// Mapping will only be present if this builder was not local
	Mapping *meta.RESTMapping

	// Namespace will be set if the object is namespaced and has a specified value.
	Namespace string
	Name      string

	// Optional, Source is the filename or URL to template file (.json or .yaml),
	// or stdin to use to handle the resource
	Source string
	// Optional, this is the most recent value returned by the server if available. It will
	// typically be in unstructured or internal forms, depending on how the Builder was
	// defined. If retrieved from the server, the Builder expects the mapping client to
	// decide the final form. Use the AsVersioned, AsUnstructured, and AsInternal helpers
	// to alter the object versions.
	// If Subresource is specified, this will be the object for the subresource.
	Object runtime.Object
	// Optional, this is the most recent resource version the server knows about for
	// this type of resource. It may not match the resource version of the object,
	// but if set it should be equal to or newer than the resource version of the
	// object (however the server defines resource version).
	ResourceVersion string
	// Optional, if specified, the object is the most recent value of the subresource
	// returned by the server if available.
	Subresource string
}

Info contains temporary info to execute a REST call, or show the results of an already completed REST call.

func (*Info) Get

func (i *Info) Get() (err error)

Get retrieves the object from the Namespace and Name fields

func (*Info) Namespaced

func (i *Info) Namespaced() bool

Namespaced returns true if the object belongs to a namespace

func (*Info) ObjectName

func (i *Info) ObjectName() string

ObjectName returns an approximate form of the resource's kind/name.

func (*Info) Refresh

func (i *Info) Refresh(obj runtime.Object, ignoreError bool) error

Refresh updates the object with another object. If ignoreError is set the Object will be updated even if name, namespace, or resourceVersion attributes cannot be loaded from the object.

func (*Info) ResourceMapping

func (i *Info) ResourceMapping() *meta.RESTMapping

ResourceMapping returns the mapping for this resource and implements ResourceMapping

func (*Info) String

func (i *Info) String() string

String returns the general purpose string representation

func (*Info) Visit

func (i *Info) Visit(fn VisitorFunc) error

Visit implements Visitor

func (*Info) Watch

func (i *Info) Watch(resourceVersion string) (watch.Interface, error)

Watch returns server changes to this object after it was retrieved.

type InfoListVisitor

type InfoListVisitor []*Info

func (InfoListVisitor) Visit

func (infos InfoListVisitor) Visit(fn VisitorFunc) error

type KustomizeVisitor

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

KustomizeVisitor handles kustomization.yaml files.

func (*KustomizeVisitor) Visit

func (v *KustomizeVisitor) Visit(fn VisitorFunc) error

Visit passes the result of a kustomize build to a StreamVisitor.

type QueryParamVerifier added in v0.24.0

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

QueryParamVerifier verifies if a given group-version-kind supports a given VerifiableQueryParam against the current server.

Currently supported query params are: fieldValidation

Support for each of these query params needs to be verified because we determine whether or not to perform server-side or client-side schema validation based on whether the fieldValidation query param is supported or not.

It reads the OpenAPI to see if the given GVK supports the given query param. If the GVK can not be found, we assume that CRDs will have the same level of support as "namespaces", and non-CRDs will not be supported. We delay the check for CRDs as much as possible though, since it requires an extra round-trip to the server.

func NewQueryParamVerifier added in v0.24.0

func NewQueryParamVerifier(dynamicClient dynamic.Interface, openAPIGetter discovery.OpenAPISchemaInterface, queryParam VerifiableQueryParam) *QueryParamVerifier

func (*QueryParamVerifier) HasSupport added in v0.24.0

func (v *QueryParamVerifier) HasSupport(gvk schema.GroupVersionKind) error

HasSupport checks if the given gvk supports the query param configured on v

type RESTClient

type RESTClient interface {
	Get() *rest.Request
	Post() *rest.Request
	Patch(types.PatchType) *rest.Request
	Delete() *rest.Request
	Put() *rest.Request
}

RESTClient is a client helper for dealing with RESTful resources in a generic way.

func NewClientWithOptions

func NewClientWithOptions(c RESTClient, transforms ...RequestTransform) RESTClient

NewClientWithOptions wraps the provided RESTClient and invokes each transform on each newly created request.

type RESTClientGetter

type RESTClientGetter interface {
	ToRESTConfig() (*rest.Config, error)
	ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error)
	ToRESTMapper() (meta.RESTMapper, error)
}

type RESTMapperFunc

type RESTMapperFunc func() (meta.RESTMapper, error)

type RequestTransform

type RequestTransform func(*rest.Request)

RequestTransform is a function that is given a chance to modify the outgoing request.

type ResourceMapping

type ResourceMapping interface {
	ResourceMapping() *meta.RESTMapping
}

ResourceMapping allows an object to return the resource mapping associated with the resource or resources it represents.

type Result

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

Result contains helper methods for dealing with the outcome of a Builder.

func (*Result) Err

func (r *Result) Err() error

Err returns one or more errors (via a util.ErrorList) that occurred prior to visiting the elements in the visitor. To see all errors including those that occur during visitation, invoke Infos().

func (*Result) IgnoreErrors

func (r *Result) IgnoreErrors(fns ...ErrMatchFunc) *Result

IgnoreErrors will filter errors that occur when by visiting the result (but not errors that occur by creating the result in the first place), eliminating any that match fns. This is best used in combination with Builder.ContinueOnError(), where the visitors accumulate errors and return them after visiting as a slice of errors. If no errors remain after filtering, the various visitor methods on Result will return nil for err.

func (*Result) Infos

func (r *Result) Infos() ([]*Info, error)

Infos returns an array of all of the resource infos retrieved via traversal. Will attempt to traverse the entire set of visitors only once, and will return a cached list on subsequent calls.

func (*Result) IntoSingleItemImplied

func (r *Result) IntoSingleItemImplied(b *bool) *Result

IntoSingleItemImplied sets the provided boolean pointer to true if the Builder input implies a single item, or multiple.

func (*Result) Mapper

func (r *Result) Mapper() *mapper

Mapper returns a copy of the builder's mapper.

func (*Result) Object

func (r *Result) Object() (runtime.Object, error)

Object returns a single object representing the output of a single visit to all found resources. If the Builder was a singular context (expected to return a single resource by user input) and only a single resource was found, the resource will be returned as is. Otherwise, the returned resources will be part of an v1.List. The ResourceVersion of the v1.List will be set only if it is identical across all infos returned.

func (*Result) ResourceMapping

func (r *Result) ResourceMapping() (*meta.RESTMapping, error)

ResourceMapping returns a single meta.RESTMapping representing the resources located by the builder, or an error if more than one mapping was found.

func (*Result) TargetsSingleItems

func (r *Result) TargetsSingleItems() bool

TargetsSingleItems returns true if any of the builder arguments pointed to non-list calls (if the user explicitly asked for any object by name). This includes directories, streams, URLs, and resource name tuples.

func (*Result) Visit

func (r *Result) Visit(fn VisitorFunc) error

Visit implements the Visitor interface on the items described in the Builder. Note that some visitor sources are not traversable more than once, or may return different results. If you wish to operate on the same set of resources multiple times, use the Infos() method.

func (*Result) Watch

func (r *Result) Watch(resourceVersion string) (watch.Interface, error)

Watch retrieves changes that occur on the server to the specified resource. It currently supports watching a single source - if the resource source (selectors or pure types) can be watched, they will be, otherwise the list will be visited (equivalent to the Infos() call) and if there is a single resource present, it will be watched, otherwise an error will be returned.

type Selector

type Selector struct {
	Client        RESTClient
	Mapping       *meta.RESTMapping
	Namespace     string
	LabelSelector string
	FieldSelector string
	LimitChunks   int64
}

Selector is a Visitor for resources that match a label selector.

func NewSelector

func NewSelector(client RESTClient, mapping *meta.RESTMapping, namespace, labelSelector, fieldSelector string, limitChunks int64) *Selector

NewSelector creates a resource selector which hides details of getting items by their label selector.

func (*Selector) ResourceMapping

func (r *Selector) ResourceMapping() *meta.RESTMapping

ResourceMapping returns the mapping for this resource and implements ResourceMapping

func (*Selector) Visit

func (r *Selector) Visit(fn VisitorFunc) error

Visit implements Visitor and uses request chunking by default.

func (*Selector) Watch

func (r *Selector) Watch(resourceVersion string) (watch.Interface, error)

type StreamVisitor

type StreamVisitor struct {
	io.Reader

	Source string
	Schema ContentValidator
	// contains filtered or unexported fields
}

StreamVisitor reads objects from an io.Reader and walks them. A stream visitor can only be visited once. TODO: depends on objects being in JSON format before being passed to decode - need to implement a stream decoder method on runtime.Codec to properly handle this.

func NewStreamVisitor

func NewStreamVisitor(r io.Reader, mapper *mapper, source string, schema ContentValidator) *StreamVisitor

NewStreamVisitor is a helper function that is useful when we want to change the fields of the struct but keep calls the same.

func (*StreamVisitor) Visit

func (v *StreamVisitor) Visit(fn VisitorFunc) error

Visit implements Visitor over a stream. StreamVisitor is able to distinct multiple resources in one stream.

type URLVisitor

type URLVisitor struct {
	URL *url.URL
	*StreamVisitor
	HttpAttemptCount int
}

URLVisitor downloads the contents of a URL, and if successful, returns an info object representing the downloaded object.

func (*URLVisitor) Visit

func (v *URLVisitor) Visit(fn VisitorFunc) error

type VerifiableQueryParam added in v0.24.0

type VerifiableQueryParam string

VerifiableQueryParam is a query parameter who's enablement on the apiserver can be determined by evaluating the OpenAPI for a specific GVK.

const (
	QueryParamFieldValidation VerifiableQueryParam = "fieldValidation"
)

type Verifier added in v0.24.0

type Verifier interface {
	HasSupport(gvk schema.GroupVersionKind) error
}

Verifier is the generic verifier interface used for testing QueryParamVerifier

func NewFallbackQueryParamVerifier added in v0.27.0

func NewFallbackQueryParamVerifier(primary Verifier, secondary Verifier) Verifier

NewFallbackQueryParamVerifier returns a new Verifier which will invoke the initial/primary Verifier. If the primary Verifier is "NotFound", then the secondary Verifier is invoked as a fallback.

func NewQueryParamVerifierV3 added in v0.27.0

func NewQueryParamVerifierV3(dynamicClient dynamic.Interface, oapiClient openapi.Client, queryParam VerifiableQueryParam) Verifier

NewQueryParamVerifierV3 returns a pointer to the created queryParamVerifier3 struct, which implements the Verifier interface. The caching characteristics of the OpenAPI V3 specs are determined by the passed oapiClient. For memory caching, the client should be wrapped beforehand as: cached.NewClient(oapiClient). The disk caching is determined by the discovery client the oapiClient is created from.

type Visitor

type Visitor interface {
	Visit(VisitorFunc) error
}

Visitor lets clients walk a list of resources.

func ExpandPathsToFileVisitors

func ExpandPathsToFileVisitors(mapper *mapper, paths string, recursive bool, extensions []string, schema ContentValidator) ([]Visitor, error)

ExpandPathsToFileVisitors will return a slice of FileVisitors that will handle files from the provided path. After FileVisitors open the files, they will pass an io.Reader to a StreamVisitor to do the reading. (stdin is also taken care of). Paths argument also accepts a single file, and will return a single visitor

func FileVisitorForSTDIN

func FileVisitorForSTDIN(mapper *mapper, schema ContentValidator) Visitor

FileVisitorForSTDIN return a special FileVisitor just for STDIN

func NewDecoratedVisitor

func NewDecoratedVisitor(v Visitor, fn ...VisitorFunc) Visitor

NewDecoratedVisitor will create a visitor that invokes the provided visitor functions before the user supplied visitor function is invoked, giving them the opportunity to mutate the Info object or terminate early with an error.

func NewFilteredVisitor

func NewFilteredVisitor(v Visitor, fn ...FilterFunc) Visitor

func NewFlattenListVisitor

func NewFlattenListVisitor(v Visitor, typer runtime.ObjectTyper, mapper *mapper) Visitor

NewFlattenListVisitor creates a visitor that will expand list style runtime.Objects into individual items and then visit them individually.

type VisitorFunc

type VisitorFunc func(*Info, error) error

VisitorFunc implements the Visitor interface for a matching function. If there was a problem walking a list of resources, the incoming error will describe the problem and the function can decide how to handle that error. A nil returned indicates to accept an error to continue loops even when errors happen. This is useful for ignoring certain kinds of errors or aggregating errors in some way.

func RequireNamespace

func RequireNamespace(namespace string) VisitorFunc

RequireNamespace will either set a namespace if none is provided on the Info object, or if the namespace is set and does not match the provided value, returns an error. This is intended to guard against administrators accidentally operating on resources outside their namespace.

func SetNamespace

func SetNamespace(namespace string) VisitorFunc

SetNamespace ensures that every Info object visited will have a namespace set. If info.Object is set, it will be mutated as well.

type VisitorList

type VisitorList []Visitor

VisitorList implements Visit for the sub visitors it contains. The first error returned from a child Visitor will terminate iteration.

func (VisitorList) Visit

func (l VisitorList) Visit(fn VisitorFunc) error

Visit implements Visitor

type Watchable

type Watchable interface {
	Watch(resourceVersion string) (watch.Interface, error)
}

Watchable describes a resource that can be watched for changes that occur on the server, beginning after the provided resource version.

Jump to

Keyboard shortcuts

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