util

package
v1.10.6-lite6 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2018 License: Apache-2.0 Imports: 74 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// TODO(sig-cli): Enforce consistent naming for generators here.
	// See discussion in https://github.com/kubernetes/kubernetes/issues/46237
	// before you add any more.
	RunV1GeneratorName                      = "run/v1"
	RunPodV1GeneratorName                   = "run-pod/v1"
	ServiceV1GeneratorName                  = "service/v1"
	ServiceV2GeneratorName                  = "service/v2"
	ServiceNodePortGeneratorV1Name          = "service-nodeport/v1"
	ServiceClusterIPGeneratorV1Name         = "service-clusterip/v1"
	ServiceLoadBalancerGeneratorV1Name      = "service-loadbalancer/v1"
	ServiceExternalNameGeneratorV1Name      = "service-externalname/v1"
	ServiceAccountV1GeneratorName           = "serviceaccount/v1"
	HorizontalPodAutoscalerV1GeneratorName  = "horizontalpodautoscaler/v1"
	DeploymentV1Beta1GeneratorName          = "deployment/v1beta1"
	DeploymentAppsV1Beta1GeneratorName      = "deployment/apps.v1beta1"
	DeploymentBasicV1Beta1GeneratorName     = "deployment-basic/v1beta1"
	DeploymentBasicAppsV1Beta1GeneratorName = "deployment-basic/apps.v1beta1"
	JobV1GeneratorName                      = "job/v1"
	CronJobV2Alpha1GeneratorName            = "cronjob/v2alpha1"
	CronJobV1Beta1GeneratorName             = "cronjob/v1beta1"
	NamespaceV1GeneratorName                = "namespace/v1"
	ResourceQuotaV1GeneratorName            = "resourcequotas/v1"
	SecretV1GeneratorName                   = "secret/v1"
	SecretForDockerRegistryV1GeneratorName  = "secret-for-docker-registry/v1"
	SecretForTLSV1GeneratorName             = "secret-for-tls/v1"
	ConfigMapV1GeneratorName                = "configmap/v1"
	ClusterRoleBindingV1GeneratorName       = "clusterrolebinding.rbac.authorization.k8s.io/v1alpha1"
	RoleBindingV1GeneratorName              = "rolebinding.rbac.authorization.k8s.io/v1alpha1"
	ClusterV1Beta1GeneratorName             = "cluster/v1beta1"
	PodDisruptionBudgetV1GeneratorName      = "poddisruptionbudget/v1beta1"
	PodDisruptionBudgetV2GeneratorName      = "poddisruptionbudget/v1beta1/v2"
	PriorityClassV1Alpha1GeneratorName      = "priorityclass/v1alpha1"
)
View Source
const (
	ApplyAnnotationsFlag     = "save-config"
	DefaultErrorExitCode     = 1
	IncludeUninitializedFlag = "include-uninitialized"
)
View Source
const (
	FlagMatchBinaryVersion = "match-server-version"
)

Variables

View Source
var ErrExit = fmt.Errorf("exit")

ErrExit may be passed to CheckError to instruct it to output nothing but exit with status code 1.

View Source
var (
	FlagHTTPCacheDir = "cache-dir"
)

Functions

func AddApplyAnnotationFlags

func AddApplyAnnotationFlags(cmd *cobra.Command)

func AddApplyAnnotationVarFlags

func AddApplyAnnotationVarFlags(cmd *cobra.Command, applyAnnotation *bool)

func AddDryRunFlag

func AddDryRunFlag(cmd *cobra.Command)

AddDryRunFlag adds dry-run flag to a command. Usually used by mutations.

func AddFilenameOptionFlags

func AddFilenameOptionFlags(cmd *cobra.Command, options *resource.FilenameOptions, usage string)

func AddGeneratorFlags

func AddGeneratorFlags(cmd *cobra.Command, defaultGenerator string)

AddGeneratorFlags adds flags common to resource generation commands TODO: need to take a pass at other generator commands to use this set of flags

func AddInclude3rdPartyFlags

func AddInclude3rdPartyFlags(cmd *cobra.Command)

func AddInclude3rdPartyVarFlags

func AddInclude3rdPartyVarFlags(cmd *cobra.Command, include3rdParty *bool)

func AddIncludeUninitializedFlag

func AddIncludeUninitializedFlag(cmd *cobra.Command)

func AddNoHeadersFlags

func AddNoHeadersFlags(cmd *cobra.Command)

AddNoHeadersFlags adds no-headers flags to a command.

func AddNonDeprecatedPrinterFlags

func AddNonDeprecatedPrinterFlags(cmd *cobra.Command)

AddNonDeprecatedPrinterFlags supports the conversion case which must logically have output-version. Once output-version is completely removed, this function can go away.

func AddOutputFlags

func AddOutputFlags(cmd *cobra.Command)

AddOutputFlags adds output related flags to a command.

func AddOutputFlagsForMutation

func AddOutputFlagsForMutation(cmd *cobra.Command)

AddOutputFlagsForMutation adds output related flags to a command. Used by mutations only.

func AddOutputVarFlagsForMutation

func AddOutputVarFlagsForMutation(cmd *cobra.Command, output *string)

AddOutputVarFlagsForMutation adds output related flags to a command. Used by mutations only.

func AddPodRunningTimeoutFlag

func AddPodRunningTimeoutFlag(cmd *cobra.Command, defaultTimeout time.Duration)

func AddPrinterFlags

func AddPrinterFlags(cmd *cobra.Command)

AddPrinterFlags adds printing related flags to a command (e.g. output format, no headers, template path)

func AddRecordFlag

func AddRecordFlag(cmd *cobra.Command)

func AddRecordVarFlag

func AddRecordVarFlag(cmd *cobra.Command, record *bool)

func AddSourceToErr

func AddSourceToErr(verb string, source string, err error) error

AddSourceToErr adds handleResourcePrefix and source string to error message. verb is the string like "creating", "deleting" etc. source is the filename or URL to the template file(*.json or *.yaml), or stdin to use to handle the resource.

func AddValidateFlags

func AddValidateFlags(cmd *cobra.Command)

func AddValidateOptionFlags

func AddValidateOptionFlags(cmd *cobra.Command, options *ValidateOptions)

func BehaviorOnFatal

func BehaviorOnFatal(f func(string, int))

BehaviorOnFatal allows you to override the default behavior when a fatal error occurs, which is to call os.Exit(code). You can pass 'panic' as a function here if you prefer the panic() over os.Exit(1).

func ChangeResourcePatch

func ChangeResourcePatch(info *resource.Info, changeCause string) ([]byte, types.PatchType, error)

ChangeResourcePatch creates a patch between the origin input resource info and the annotated with change-cause input resource info.

func CheckErr

func CheckErr(err error)

CheckErr prints a user friendly error to STDERR and exits with a non-zero exit code. Unrecognized errors will be printed with an "error: " prefix.

This method is generic to the command in use and may be used by non-Kubectl commands.

func Contains

func Contains(resourcesList []*metav1.APIResourceList, resource schema.GroupVersionResource) bool

func ContainsChangeCause

func ContainsChangeCause(info *resource.Info) bool

ContainsChangeCause checks if input resource info contains change-cause annotation.

func DefaultBehaviorOnFatal

func DefaultBehaviorOnFatal()

DefaultBehaviorOnFatal allows you to undo any previous override. Useful in tests.

func DefaultClientConfig

func DefaultClientConfig(flags *pflag.FlagSet) clientcmd.ClientConfig

DefaultClientConfig creates a clientcmd.ClientConfig with the following hierarchy:

  1. Use the kubeconfig builder. The number of merges and overrides here gets a little crazy. Stay with me.

  2. Merge the kubeconfig itself. This is done with the following hierarchy rules:

  3. CommandLineLocation - this parsed from the command line, so it must be late bound. If you specify this, then no other kubeconfig files are merged. This file must exist.

  4. If $KUBECONFIG is set, then it is treated as a list of files that should be merged.

  5. HomeDirectoryLocation Empty filenames are ignored. Files with non-deserializable content produced errors. The first file to set a particular value or map key wins and the value or map key is never changed. This means that the first file to set CurrentContext will have its context preserved. It also means that if two files specify a "red-user", only values from the first file's red-user are used. Even non-conflicting entries from the second file's "red-user" are discarded.

  6. Determine the context to use based on the first hit in this chain

  7. command line argument - again, parsed from the command line, so it must be late bound

  8. CurrentContext from the merged kubeconfig file

  9. Empty is allowed at this stage

  10. Determine the cluster info and auth info to use. At this point, we may or may not have a context. They are built based on the first hit in this chain. (run it twice, once for auth, once for cluster)

  11. command line argument

  12. If context is present, then use the context value

  13. Empty is allowed

  14. Determine the actual cluster info to use. At this point, we may or may not have a cluster info. Build each piece of the cluster info based on the chain:

  15. command line argument

  16. If cluster info is present and a value for the attribute is present, use it.

  17. If you don't have a server location, bail.

  18. Auth info is build using the same rules as cluster info, EXCEPT that you can only have one authentication technique per auth info. The following conditions result in an error:

  19. If there are two conflicting techniques specified from the command line, fail.

  20. If the command line does not specify one, and the auth info has conflicting techniques, fail.

  21. If the command line specifies one and the auth info specifies another, honor the command line technique.

  22. Use default values and potentially prompt for auth information

    However, if it appears that we're running in a kubernetes cluster container environment, then run with the auth info kubernetes mounted for us. Specifically: The env vars KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are set, and the file /var/run/secrets/kubernetes.io/serviceaccount/token exists and is not a directory.

func DefaultGenerators

func DefaultGenerators(cmdName string) map[string]kubectl.Generator

DefaultGenerators returns the set of default generators for use in Factory instances

func DefaultSubCommandRun

func DefaultSubCommandRun(out io.Writer) func(c *cobra.Command, args []string)

DefaultSubCommandRun prints a command's help string to the specified output if no arguments (sub-commands) are provided, or a usage error otherwise.

func DumpReaderToFile

func DumpReaderToFile(reader io.Reader, filename string) error

DumpReaderToFile writes all data from the given io.Reader to the specified file (usually for temporary use).

func ExtractCmdPrintOptions

func ExtractCmdPrintOptions(cmd *cobra.Command, withNamespace bool) *printers.PrintOptions

ExtractCmdPrintOptions parses printer specific commandline args and returns a PrintOptions object. Requires that printer flags have been added to cmd (see AddPrinterFlags)

func FallbackGeneratorNameIfNecessary

func FallbackGeneratorNameIfNecessary(
	generatorName string,
	discoveryClient discovery.DiscoveryInterface,
	cmdErr io.Writer,
) (string, error)

fallbackGeneratorNameIfNecessary returns the name of the old generator if server does not support new generator. Otherwise, the generator string is returned unchanged.

If the generator name is changed, print a warning message to let the user know.

func FilterResourceList

func FilterResourceList(obj runtime.Object, filterFuncs kubectl.Filters, filterOpts *printers.PrintOptions) (int, []runtime.Object, error)

FilterResourceList receives a list of runtime objects. If any objects are filtered, that number is returned along with a modified list.

func GetDryRunFlag

func GetDryRunFlag(cmd *cobra.Command) bool

func GetFirstPod

func GetFirstPod(client coreclient.PodsGetter, namespace string, selector string, timeout time.Duration, sortBy func([]*v1.Pod) sort.Interface) (*api.Pod, int, error)

GetFirstPod returns a pod matching the namespace and label selector and the number of all pods that match the label selector.

func GetFlagBool

func GetFlagBool(cmd *cobra.Command, flag string) bool

func GetFlagDuration

func GetFlagDuration(cmd *cobra.Command, flag string) time.Duration

func GetFlagInt

func GetFlagInt(cmd *cobra.Command, flag string) int

Assumes the flag has a default value.

func GetFlagInt32

func GetFlagInt32(cmd *cobra.Command, flag string) int32

Assumes the flag has a default value.

func GetFlagInt64

func GetFlagInt64(cmd *cobra.Command, flag string) int64

Assumes the flag has a default value.

func GetFlagString

func GetFlagString(cmd *cobra.Command, flag string) string

func GetFlagStringArray

func GetFlagStringArray(cmd *cobra.Command, flag string) []string

GetFlagStringArray can be used to accept multiple argument with flag repetition (e.g. -f arg1 -f arg2 ...)

func GetFlagStringSlice

func GetFlagStringSlice(cmd *cobra.Command, flag string) []string

GetFlagStringSlice can be used to accept multiple argument with flag repetition (e.g. -f arg1,arg2 -f arg3 ...)

func GetPodRunningTimeoutFlag

func GetPodRunningTimeoutFlag(cmd *cobra.Command) (time.Duration, error)

func GetRecordFlag

func GetRecordFlag(cmd *cobra.Command) bool

func GetResourcesAndPairs

func GetResourcesAndPairs(args []string, pairType string) (resources []string, pairArgs []string, err error)

GetResourcesAndPairs retrieves resources and "KEY=VALUE or KEY-" pair args from given args

func GetWideFlag

func GetWideFlag(cmd *cobra.Command) bool

GetWideFlag is used to determine if "-o wide" is used

func HasResource

func HasResource(client discovery.DiscoveryInterface, resource schema.GroupVersionResource) (bool, error)

func InternalVersionDecoder

func InternalVersionDecoder() runtime.Decoder

this method exists to help us find the points still relying on internal types.

func InternalVersionJSONEncoder

func InternalVersionJSONEncoder() runtime.Encoder

func IsFilenameSliceEmpty

func IsFilenameSliceEmpty(filenames []string) bool

func IsSiblingCommandExists

func IsSiblingCommandExists(cmd *cobra.Command, targetCmdName string) bool

IsSiblingCommandExists receives a pointer to a cobra command and a target string. Returns true if the target string is found in the list of sibling commands.

func ManualStrip

func ManualStrip(file []byte) []byte

ManualStrip is used for dropping comments from a YAML file

func Merge

func Merge(codec runtime.Codec, dst runtime.Object, fragment string) (runtime.Object, error)

Merge requires JSON serialization TODO: merge assumes JSON serialization, and does not properly abstract API retrieval

func MultilineError

func MultilineError(prefix string, err error) string

MultilineError returns a string representing an error that splits sub errors into their own lines. The returned string will end with a newline.

func MultipleErrors

func MultipleErrors(prefix string, errs []error) string

MultipleErrors returns a newline delimited string containing the prefix and referenced errors in standard form.

func MustPrintWithKinds

func MustPrintWithKinds(objs []runtime.Object, infos []*resource.Info, sorter *kubectl.RuntimeSort) bool

MustPrintWithKinds determines if printer is dealing with multiple resource kinds, in which case it will return true, indicating resource kind will be included as part of printer output

func NewShortcutExpander

func NewShortcutExpander(delegate meta.RESTMapper, client discovery.DiscoveryInterface) shortcutExpander

func OutputsRawFormat

func OutputsRawFormat(cmd *cobra.Command) bool

OutputsRawFormat determines if a command's output format is machine parsable or returns false if it is human readable (name, wide, etc.)

func ParsePairs

func ParsePairs(pairArgs []string, pairType string, supportRemove bool) (newPairs map[string]string, removePairs []string, err error)

ParsePairs retrieves new and remove pairs (if supportRemove is true) from "KEY=VALUE or KEY-" pair args

func PrintErrorWithCauses

func PrintErrorWithCauses(err error, errOut io.Writer) bool

PrintErrorWithCauses prints an error's kind, name, and each of the error's causes in a new line. The returned string will end with a newline. Returns true if a case exists to handle the error type, or false otherwise.

func PrintFilterCount

func PrintFilterCount(out io.Writer, found, hidden, errors int, options *printers.PrintOptions, ignoreNotFound bool)

PrintFilterCount displays informational messages based on the number of resources found, hidden, or config flags shown.

func PrintObject

func PrintObject(cmd *cobra.Command, obj runtime.Object, out io.Writer) error

PrintObject prints a single object based on the default command options TODO this should go away once commands can embed the PrintOptions instead

func PrintSuccess

func PrintSuccess(shortOutput bool, out io.Writer, obj runtime.Object, dryRun bool, operation string)

PrintSuccess prints a success message and can do a "-o name" as "shortOutput" TODO this should really just be a printer. It's got just about the exact same signature.

func PrinterForOptions

func PrinterForOptions(options *printers.PrintOptions) (printers.ResourcePrinter, error)

PrinterForOptions returns the printer for the outputOptions (if given) or returns the default printer for the command. TODO this should become a function on the PrintOptions struct

func ReadConfigDataFromReader

func ReadConfigDataFromReader(reader io.Reader, source string) ([]byte, error)

func RecordChangeCause

func RecordChangeCause(obj runtime.Object, changeCause string) error

RecordChangeCause annotate change-cause to input runtime object.

func RequireNoArguments

func RequireNoArguments(c *cobra.Command, args []string)

RequireNoArguments exits with a usage error if extra arguments are provided.

func ShouldIncludeUninitialized

func ShouldIncludeUninitialized(cmd *cobra.Command, includeUninitialized bool) bool

ShouldIncludeUninitialized identifies whether to include uninitialized objects. includeUninitialized is the default value. Assume we can parse `all` and `selector` from cmd.

func ShouldRecord

func ShouldRecord(cmd *cobra.Command, info *resource.Info) bool

ShouldRecord checks if we should record current change cause

func StandardErrorMessage

func StandardErrorMessage(err error) (string, bool)

StandardErrorMessage translates common errors into a human readable message, or returns false if the error is not one of the recognized types. It may also log extended information to glog.

This method is generic to the command in use and may be used by non-Kubectl commands.

func StripComments

func StripComments(file []byte) []byte

StripComments will transform a YAML file into JSON, thus dropping any comments in it. Note that if the given file has a syntax error, the transformation will fail and we will manually drop all comments from the file.

func UpdateObject

func UpdateObject(info *resource.Info, codec runtime.Codec, updateFn func(runtime.Object) error) (runtime.Object, error)

UpdateObject updates resource object with updateFn

func UsageErrorf

func UsageErrorf(cmd *cobra.Command, format string, args ...interface{}) error

func ValidArgList

func ValidArgList(f ClientAccessFactory) []string

Retrieve a list of handled resources from printer as valid args TODO: This function implementation should be replaced with a real implementation from the discovery service.

func ValidResourceTypeList

func ValidResourceTypeList(f ClientAccessFactory) string

ValidResourceTypeList returns a multi-line string containing the valid resources. May be called before the factory is initialized. TODO: This function implementation should be replaced with a real implementation from the

discovery service.

func ValidateOutputArgs

func ValidateOutputArgs(cmd *cobra.Command) error

ValidateOutputArgs validates -o flag args for mutations

Types

type BuilderFactory

type BuilderFactory interface {
	// NewBuilder returns an object that assists in loading objects from both disk and the server
	// and which implements the common patterns for CLI interactions with generic resources.
	NewBuilder() *resource.Builder
	// PluginLoader provides the implementation to be used to load cli plugins.
	PluginLoader() plugins.PluginLoader
	// PluginRunner provides the implementation to be used to run cli plugins.
	PluginRunner() plugins.PluginRunner
}

BuilderFactory holds the third level of factory methods. These functions depend upon ObjectMappingFactory and ClientAccessFactory methods. Generally they depend upon client mapper functions

func NewBuilderFactory

func NewBuilderFactory(clientAccessFactory ClientAccessFactory, objectMappingFactory ObjectMappingFactory) BuilderFactory

type CachedDiscoveryClient

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

CachedDiscoveryClient implements the functions that discovery server-supported API groups, versions and resources.

func NewCachedDiscoveryClient

func NewCachedDiscoveryClient(delegate discovery.DiscoveryInterface, cacheDirectory string, ttl time.Duration) *CachedDiscoveryClient

NewCachedDiscoveryClient creates a new DiscoveryClient. cacheDirectory is the directory where discovery docs are held. It must be unique per host:port combination to work well.

func (*CachedDiscoveryClient) Fresh

func (d *CachedDiscoveryClient) Fresh() bool

func (*CachedDiscoveryClient) Invalidate

func (d *CachedDiscoveryClient) Invalidate()

func (*CachedDiscoveryClient) OpenAPISchema

func (d *CachedDiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error)

func (*CachedDiscoveryClient) RESTClient

func (d *CachedDiscoveryClient) RESTClient() restclient.Interface

func (*CachedDiscoveryClient) ServerGroups

func (d *CachedDiscoveryClient) ServerGroups() (*metav1.APIGroupList, error)

func (*CachedDiscoveryClient) ServerPreferredNamespacedResources

func (d *CachedDiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error)

func (*CachedDiscoveryClient) ServerPreferredResources

func (d *CachedDiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error)

func (*CachedDiscoveryClient) ServerResources

func (d *CachedDiscoveryClient) ServerResources() ([]*metav1.APIResourceList, error)

ServerResources returns the supported resources for all groups and versions.

func (*CachedDiscoveryClient) ServerResourcesForGroupVersion

func (d *CachedDiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error)

ServerResourcesForGroupVersion returns the supported resources for a group and version.

func (*CachedDiscoveryClient) ServerVersion

func (d *CachedDiscoveryClient) ServerVersion() (*version.Info, error)

type ClientAccessFactory

type ClientAccessFactory interface {
	// Returns a discovery client
	DiscoveryClient() (discovery.CachedDiscoveryInterface, error)

	// ClientSet gives you back an internal, generated clientset
	ClientSet() (internalclientset.Interface, error)

	// KubernetesClientSet gives you back an external clientset
	KubernetesClientSet() (*kubernetes.Clientset, error)

	// Returns a RESTClient for accessing Kubernetes resources or an error.
	RESTClient() (*restclient.RESTClient, error)
	// Returns a client.Config for accessing the Kubernetes server.
	ClientConfig() (*restclient.Config, error)
	// BareClientConfig returns a client.Config that has NOT been negotiated. It's
	// just directions to the server. People use this to build RESTMappers on top of
	BareClientConfig() (*restclient.Config, error)

	// UpdatePodSpecForObject will call the provided function on the pod spec this object supports,
	// return false if no pod spec is supported, or return an error.
	UpdatePodSpecForObject(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error)

	// MapBasedSelectorForObject returns the map-based selector associated with the provided object. If a
	// new set-based selector is provided, an error is returned if the selector cannot be converted to a
	// map-based selector
	MapBasedSelectorForObject(object runtime.Object) (string, error)
	// PortsForObject returns the ports associated with the provided object
	PortsForObject(object runtime.Object) ([]string, error)
	// ProtocolsForObject returns the <port, protocol> mapping associated with the provided object
	ProtocolsForObject(object runtime.Object) (map[string]string, error)
	// LabelsForObject returns the labels associated with the provided object
	LabelsForObject(object runtime.Object) (map[string]string, error)

	// Returns internal flagset
	FlagSet() *pflag.FlagSet
	// Command will stringify and return all environment arguments ie. a command run by a client
	// using the factory.
	Command(cmd *cobra.Command, showSecrets bool) string
	// BindFlags adds any flags that are common to all kubectl sub commands.
	BindFlags(flags *pflag.FlagSet)
	// BindExternalFlags adds any flags defined by external projects (not part of pflags)
	BindExternalFlags(flags *pflag.FlagSet)

	// DefaultResourceFilterFunc returns a collection of FilterFuncs suitable for filtering specific resource types.
	DefaultResourceFilterFunc() kubectl.Filters

	// SuggestedPodTemplateResources returns a list of resource types that declare a pod template
	SuggestedPodTemplateResources() []schema.GroupResource

	// Pauser marks the object in the info as paused. Currently supported only for Deployments.
	// Returns the patched object in bytes and any error that occurred during the encoding or
	// in case the object is already paused.
	Pauser(info *resource.Info) ([]byte, error)
	// Resumer resumes a paused object inside the info. Currently supported only for Deployments.
	// Returns the patched object in bytes and any error that occurred during the encoding or
	// in case the object is already resumed.
	Resumer(info *resource.Info) ([]byte, error)

	// ResolveImage resolves the image names. For kubernetes this function is just
	// passthrough but it allows to perform more sophisticated image name resolving for
	// third-party vendors.
	ResolveImage(imageName string) (string, error)

	// Returns the default namespace to use in cases where no
	// other namespace is specified and whether the namespace was
	// overridden.
	DefaultNamespace() (string, bool, error)
	// Generators returns the generators for the provided command
	Generators(cmdName string) map[string]kubectl.Generator
	// Check whether the kind of resources could be exposed
	CanBeExposed(kind schema.GroupKind) error
	// Check whether the kind of resources could be autoscaled
	CanBeAutoscaled(kind schema.GroupKind) error

	// EditorEnvs returns a group of environment variables that the edit command
	// can range over in order to determine if the user has specified an editor
	// of their choice.
	EditorEnvs() []string
}

ClientAccessFactory holds the first level of factory methods. Generally provides discovery, negotiation, and no-dep calls. TODO The polymorphic calls probably deserve their own interface.

func NewClientAccessFactory

func NewClientAccessFactory(optionalClientConfig clientcmd.ClientConfig) ClientAccessFactory

func NewClientAccessFactoryFromDiscovery

func NewClientAccessFactoryFromDiscovery(flags *pflag.FlagSet, clientConfig clientcmd.ClientConfig, discoveryFactory DiscoveryClientFactory) ClientAccessFactory

NewClientAccessFactoryFromDiscovery allows an external caller to substitute a different discoveryFactory Which allows for the client cache to be built in ring0, but still rely on a custom discovery client

type ClientCache

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

ClientCache caches previously loaded clients for reuse, and ensures MatchServerVersion is invoked only once

func NewClientCache

func NewClientCache(loader clientcmd.ClientConfig, discoveryClientFactory DiscoveryClientFactory) *ClientCache

func (*ClientCache) ClientConfigForVersion

func (c *ClientCache) ClientConfigForVersion(requiredVersion *schema.GroupVersion) (*restclient.Config, error)

ClientConfigForVersion returns the correct config for a server

func (*ClientCache) ClientSetForVersion

func (c *ClientCache) ClientSetForVersion(requiredVersion *schema.GroupVersion) (internalclientset.Interface, error)

ClientSetForVersion initializes or reuses a clientset for the specified version, or returns an error if that is not possible

func (*ClientCache) KubernetesClientSetForVersion

func (c *ClientCache) KubernetesClientSetForVersion(requiredVersion *schema.GroupVersion) (*kubernetes.Clientset, error)

KubernetesClientSetForVersion returns a new kubernetes.Clientset. It will cache the value the first time it is called and return the cached value on subsequent calls. If an error is encountered the first time KubernetesClientSetForVersion is called, the error will be cached.

type DiscoveryClientFactory

type DiscoveryClientFactory interface {
	// Returns a discovery client
	DiscoveryClient() (discovery.CachedDiscoveryInterface, error)

	// BindFlags adds any discovery flags that are common to all kubectl sub commands.
	BindFlags(flags *pflag.FlagSet)
}

type Factory

Factory provides abstractions that allow the Kubectl command to be extended across multiple types of resources and different API sets. The rings are here for a reason. In order for composers to be able to provide alternative factory implementations they need to provide low level pieces of *certain* functions so that when the factory calls back into itself it uses the custom version of the function. Rather than try to enumerate everything that someone would want to override we split the factory into rings, where each ring can depend on methods in an earlier ring, but cannot depend upon peer methods in its own ring. TODO: make the functions interfaces TODO: pass the various interfaces on the factory directly into the command constructors (so the commands are decoupled from the factory).

func NewFactory

func NewFactory(optionalClientConfig clientcmd.ClientConfig) Factory

NewFactory creates a factory with the default Kubernetes resources defined if optionalClientConfig is nil, then flags will be bound to a new clientcmd.ClientConfig. if optionalClientConfig is not nil, then this factory will make use of it.

type ObjectMappingFactory

type ObjectMappingFactory interface {
	// Returns interfaces for dealing with arbitrary runtime.Objects.
	Object() (meta.RESTMapper, runtime.ObjectTyper)
	// Returns interface for expanding categories like `all`.
	CategoryExpander() categories.CategoryExpander
	// Returns a RESTClient for working with the specified RESTMapping or an error. This is intended
	// for working with arbitrary resources and is not guaranteed to point to a Kubernetes APIServer.
	ClientForMapping(mapping *meta.RESTMapping) (resource.RESTClient, error)
	// Returns a RESTClient for working with Unstructured objects.
	UnstructuredClientForMapping(mapping *meta.RESTMapping) (resource.RESTClient, error)
	// Returns a Describer for displaying the specified RESTMapping type or an error.
	Describer(mapping *meta.RESTMapping) (printers.Describer, error)

	// LogsForObject returns a request for the logs associated with the provided object
	LogsForObject(object, options runtime.Object, timeout time.Duration) (*restclient.Request, error)
	// Returns a Scaler for changing the size of the specified RESTMapping type or an error
	Scaler(mapping *meta.RESTMapping) (kubectl.Scaler, error)
	// Returns a Reaper for gracefully shutting down resources.
	Reaper(mapping *meta.RESTMapping) (kubectl.Reaper, error)
	// Returns a HistoryViewer for viewing change history
	HistoryViewer(mapping *meta.RESTMapping) (kubectl.HistoryViewer, error)
	// Returns a Rollbacker for changing the rollback version of the specified RESTMapping type or an error
	Rollbacker(mapping *meta.RESTMapping) (kubectl.Rollbacker, error)
	// Returns a StatusViewer for printing rollout status.
	StatusViewer(mapping *meta.RESTMapping) (kubectl.StatusViewer, error)

	// AttachablePodForObject returns the pod to which to attach given an object.
	AttachablePodForObject(object runtime.Object, timeout time.Duration) (*api.Pod, error)

	// ApproximatePodTemplateForObject returns a pod template object for the provided source.
	// It may return both an error and a object. It attempt to return the best possible template
	// available at the current time.
	ApproximatePodTemplateForObject(runtime.Object) (*api.PodTemplateSpec, error)

	// Returns a schema that can validate objects stored on disk.
	Validator(validate bool) (validation.Schema, error)
}

ObjectMappingFactory holds the second level of factory methods. These functions depend upon ClientAccessFactory methods. Generally they provide object typing and functions that build requests based on the negotiated clients.

func NewObjectMappingFactory

func NewObjectMappingFactory(clientAccessFactory ClientAccessFactory) ObjectMappingFactory

type ValidateOptions

type ValidateOptions struct {
	EnableValidation bool
}

Directories

Path Synopsis
Package env provides functions to incorporate environment variables into kubectl commands.
Package env provides functions to incorporate environment variables into kubectl commands.

Jump to

Keyboard shortcuts

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