util

package
v1.4.0-beta.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2016 License: Apache-2.0 Imports: 58 Imported by: 0

Documentation

Index

Constants

View Source
const (
	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"
	ServiceAccountV1GeneratorName               = "serviceaccount/v1"
	HorizontalPodAutoscalerV1Beta1GeneratorName = "horizontalpodautoscaler/v1beta1"
	HorizontalPodAutoscalerV1GeneratorName      = "horizontalpodautoscaler/v1"
	DeploymentV1Beta1GeneratorName              = "deployment/v1beta1"
	DeploymentBasicV1Beta1GeneratorName         = "deployment-basic/v1beta1"
	JobV1Beta1GeneratorName                     = "job/v1beta1"
	JobV1GeneratorName                          = "job/v1"
	ScheduledJobV2Alpha1GeneratorName           = "scheduledjob/v2alpha1"
	NamespaceV1GeneratorName                    = "namespace/v1"
	ResourceQuotaV1GeneratorName                = "resourcequotas/v1"
	SecretV1GeneratorName                       = "secret/v1"
	SecretForDockerRegistryV1GeneratorName      = "secret-for-docker-registry/v1"
	SecretForTLSV1GeneratorName                 = "secret-for-tls/v1"
	ConfigMapV1GeneratorName                    = "configmap/v1"
)
View Source
const (
	ApplyAnnotationsFlag = "save-config"
	DefaultErrorExitCode = 1
)
View Source
const (
	FlagMatchBinaryVersion = "match-server-version"
)

Variables

This section is empty.

Functions

func AddApplyAnnotationFlags added in v1.2.0

func AddApplyAnnotationFlags(cmd *cobra.Command)

func AddDryRunFlag added in v1.3.0

func AddDryRunFlag(cmd *cobra.Command)

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

func AddGeneratorFlags added in v1.2.0

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 added in v1.3.0

func AddInclude3rdPartyFlags(cmd *cobra.Command)

func AddNoHeadersFlags added in v1.4.2

func AddNoHeadersFlags(cmd *cobra.Command)

AddNoHeadersFlags adds no-headers flags to a command.

func AddOutputFlags added in v1.4.2

func AddOutputFlags(cmd *cobra.Command)

AddOutputFlags adds output related flags to a command.

func AddOutputFlagsForMutation added in v1.1.1

func AddOutputFlagsForMutation(cmd *cobra.Command)

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

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 added in v1.2.0

func AddRecordFlag(cmd *cobra.Command)

AddCmdRecordFlag adds --record flag to command

func AddRecursiveFlag added in v1.3.0

func AddRecursiveFlag(cmd *cobra.Command, value *bool)

func AddSourceToErr added in v0.20.0

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. souce is the filename or URL to the template file(*.json or *.yaml), or stdin to use to handle the resource.

func AddValidateFlags added in v1.1.1

func AddValidateFlags(cmd *cobra.Command)

func BehaviorOnFatal added in v1.1.1

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 added in v1.2.0

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

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

func CheckErr added in v0.13.0

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 ContainsChangeCause added in v1.2.0

func ContainsChangeCause(info *resource.Info) bool

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

func DefaultBehaviorOnFatal added in v1.2.0

func DefaultBehaviorOnFatal()

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

func DefaultClientConfig added in v0.15.0

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 added in v1.2.0

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

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

func DumpReaderToFile added in v1.1.1

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 GetDryRunFlag added in v1.3.0

func GetDryRunFlag(cmd *cobra.Command) bool

func GetFirstPod added in v1.2.0

func GetFirstPod(client client.PodsNamespacer, namespace string, selector labels.Selector, timeout time.Duration, sortBy func([]*api.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 GetFlagInt64 added in v1.1.1

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 GetFlagStringSlice added in v1.1.1

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

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

func GetIncludeThirdPartyAPIs added in v1.3.0

func GetIncludeThirdPartyAPIs(cmd *cobra.Command) bool

func GetRecordFlag added in v1.2.0

func GetRecordFlag(cmd *cobra.Command) bool

func GetResourcesAndPairs added in v1.3.0

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 GetThirdPartyGroupVersions added in v1.3.0

func GetThirdPartyGroupVersions(discovery discovery.DiscoveryInterface) ([]unversioned.GroupVersion, []unversioned.GroupVersionKind, error)

GetThirdPartyGroupVersions returns the thirdparty "group/versions"s and resources supported by the server. A user may delete a thirdparty resource when this function is running, so this function may return a "NotFound" error due to the race.

func GetWideFlag added in v0.21.0

func GetWideFlag(cmd *cobra.Command) bool

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

func MaybeConvertObject added in v1.3.0

func MaybeConvertObject(obj runtime.Object, gv unversioned.GroupVersion, converter runtime.ObjectConvertor) (runtime.Object, error)

MaybeConvertObject attempts to convert an object to a specific group/version. If the object is a third party resource it is simply passed through.

func Merge

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

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

func MultilineError added in v0.15.0

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 added in v0.18.2

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

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

func OutputVersion

func OutputVersion(cmd *cobra.Command, defaultVersion *unversioned.GroupVersion) (unversioned.GroupVersion, error)

OutputVersion returns the preferred output version for generic content (JSON, YAML, or templates) defaultVersion is never mutated. Nil simply allows clean passing in common usage from client.Config

func ParsePairs added in v1.3.0

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 PrintSuccess added in v1.1.1

func PrintSuccess(mapper meta.RESTMapper, shortOutput bool, out io.Writer, resource string, name string, operation string)

PrintSuccess prints message after finishing mutating operations

func PrinterForCommand

func PrinterForCommand(cmd *cobra.Command) (kubectl.ResourcePrinter, bool, error)

PrinterForCommand returns the default printer for this command. Requires that printer flags have been added to cmd (see AddPrinterFlags).

func ReadConfigDataFromReader added in v0.13.0

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

func RecordChangeCause added in v1.2.0

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

RecordChangeCause annotate change-cause to input runtime object.

func ShouldRecord added in v1.2.0

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

ShouldRecord checks if we should record current change cause

func StandardErrorMessage added in v0.18.2

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 UpdateObject added in v1.1.1

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

UpdateObject updates resource object with updateFn

func UsageError added in v0.13.0

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

func ValidateOutputArgs added in v1.1.1

func ValidateOutputArgs(cmd *cobra.Command) error

ValidateOutputArgs validates -o flag args for mutations

Types

type ClientCache added in v1.1.1

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

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

func NewClientCache added in v0.19.1

func NewClientCache(loader clientcmd.ClientConfig) *ClientCache

func (*ClientCache) ClientConfigForVersion added in v1.1.1

func (c *ClientCache) ClientConfigForVersion(version *unversioned.GroupVersion) (*restclient.Config, error)

ClientConfigForVersion returns the correct config for a server

func (*ClientCache) ClientForVersion added in v1.1.1

func (c *ClientCache) ClientForVersion(version *unversioned.GroupVersion) (*client.Client, error)

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

func (*ClientCache) FederationClientForVersion added in v1.3.0

func (c *ClientCache) FederationClientForVersion(version *unversioned.GroupVersion) (*restclient.RESTClient, error)

func (*ClientCache) FederationClientSetForVersion added in v1.3.0

func (c *ClientCache) FederationClientSetForVersion(version *unversioned.GroupVersion) (fed_clientset.Interface, error)

type Factory added in v0.15.0

type Factory struct {

	// Returns interfaces for dealing with arbitrary runtime.Objects. If thirdPartyDiscovery is true, performs API calls
	// to discovery dynamic API objects registered by third parties.
	Object func(thirdPartyDiscovery bool) (meta.RESTMapper, runtime.ObjectTyper)
	// Returns interfaces for dealing with arbitrary
	// runtime.Unstructured. This performs API calls to discover types.
	UnstructuredObject func() (meta.RESTMapper, runtime.ObjectTyper, error)
	// Returns interfaces for decoding objects - if toInternal is set, decoded objects will be converted
	// into their internal form (if possible). Eventually the internal form will be removed as an option,
	// and only versioned objects will be returned.
	Decoder func(toInternal bool) runtime.Decoder
	// Returns an encoder capable of encoding a provided object into JSON in the default desired version.
	JSONEncoder func() runtime.Encoder
	// Returns a client for accessing Kubernetes resources or an error.
	Client func() (*client.Client, error)
	// Returns a client.Config for accessing the Kubernetes server.
	ClientConfig func() (*restclient.Config, error)
	// 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 func(mapping *meta.RESTMapping) (resource.RESTClient, error)
	// Returns a RESTClient for working with Unstructured objects.
	UnstructuredClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error)
	// Returns a Describer for displaying the specified RESTMapping type or an error.
	Describer func(mapping *meta.RESTMapping) (kubectl.Describer, error)
	// Returns a Printer for formatting objects of the given type or an error.
	Printer func(mapping *meta.RESTMapping, options kubectl.PrintOptions) (kubectl.ResourcePrinter, error)
	// Returns a Scaler for changing the size of the specified RESTMapping type or an error
	Scaler func(mapping *meta.RESTMapping) (kubectl.Scaler, error)
	// Returns a Reaper for gracefully shutting down resources.
	Reaper func(mapping *meta.RESTMapping) (kubectl.Reaper, error)
	// Returns a HistoryViewer for viewing change history
	HistoryViewer func(mapping *meta.RESTMapping) (kubectl.HistoryViewer, error)
	// Returns a Rollbacker for changing the rollback version of the specified RESTMapping type or an error
	Rollbacker func(mapping *meta.RESTMapping) (kubectl.Rollbacker, error)
	// Returns a StatusViewer for printing rollout status.
	StatusViewer func(mapping *meta.RESTMapping) (kubectl.StatusViewer, 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 func(object runtime.Object) (string, error)
	// PortsForObject returns the ports associated with the provided object
	PortsForObject func(object runtime.Object) ([]string, error)
	// ProtocolsForObject returns the <port, protocol> mapping associated with the provided object
	ProtocolsForObject func(object runtime.Object) (map[string]string, error)
	// LabelsForObject returns the labels associated with the provided object
	LabelsForObject func(object runtime.Object) (map[string]string, error)
	// LogsForObject returns a request for the logs associated with the provided object
	LogsForObject func(object, options runtime.Object) (*restclient.Request, error)
	// PauseObject marks the provided object as paused ie. it will not be reconciled by its controller.
	PauseObject func(object runtime.Object) (bool, error)
	// ResumeObject resumes a paused object ie. it will be reconciled by its controller.
	ResumeObject func(object runtime.Object) (bool, error)
	// Returns a schema that can validate objects stored on disk.
	Validator func(validate bool, cacheDir string) (validation.Schema, error)
	// SwaggerSchema returns the schema declaration for the provided group version kind.
	SwaggerSchema func(unversioned.GroupVersionKind) (*swagger.ApiDeclaration, error)
	// Returns the default namespace to use in cases where no
	// other namespace is specified and whether the namespace was
	// overridden.
	DefaultNamespace func() (string, bool, error)
	// Generators returns the generators for the provided command
	Generators func(cmdName string) map[string]kubectl.Generator
	// Check whether the kind of resources could be exposed
	CanBeExposed func(kind unversioned.GroupKind) error
	// Check whether the kind of resources could be autoscaled
	CanBeAutoscaled func(kind unversioned.GroupKind) error
	// AttachablePodForObject returns the pod to which to attach given an object.
	AttachablePodForObject func(object runtime.Object) (*api.Pod, 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 func(obj runtime.Object, fn func(*api.PodSpec) error) (bool, 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 func() []string
	// PrintObjectSpecificMessage prints object-specific messages on the provided writer
	PrintObjectSpecificMessage func(obj runtime.Object, out io.Writer)
	// contains filtered or unexported fields
}

Factory provides abstractions that allow the Kubectl command to be extended across multiple types of resources and different API sets. 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 added in v0.15.0

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.

func (*Factory) BindExternalFlags added in v1.2.0

func (f *Factory) BindExternalFlags(flags *pflag.FlagSet)

BindCommonFlags adds any flags defined by external projects (not part of pflags)

func (*Factory) BindFlags added in v0.15.0

func (f *Factory) BindFlags(flags *pflag.FlagSet)

BindFlags adds any flags that are common to all kubectl sub commands.

func (*Factory) Command added in v1.2.0

func (f *Factory) Command() string

Command will stringify and return all environment arguments ie. a command run by a client using the factory. TODO: We need to filter out stuff like secrets.

func (*Factory) NewBuilder added in v1.2.0

func (f *Factory) NewBuilder(thirdPartyDiscovery bool) *resource.Builder

One stop shopping for a Builder

func (*Factory) PrintObject added in v0.15.0

func (f *Factory) PrintObject(cmd *cobra.Command, mapper meta.RESTMapper, obj runtime.Object, out io.Writer) error

PrintObject prints an api object given command line flags to modify the output format

func (*Factory) PrinterForMapping added in v0.15.0

func (f *Factory) PrinterForMapping(cmd *cobra.Command, mapping *meta.RESTMapping, withNamespace bool) (kubectl.ResourcePrinter, error)

PrinterForMapping returns a printer suitable for displaying the provided resource type. Requires that printer flags have been added to cmd (see AddPrinterFlags).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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