kubernetes

package
v1.15.0 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2021 License: Apache-2.0, BSD-2-Clause, MIT, + 1 more Imports: 61 Imported by: 194

Documentation

Index

Constants

View Source
const KubeConfig = "kubeconfig"

KubeConfig is the key to the kubeconfig

Variables

View Source
var (
	DefaultMergeFuncs = MergeFuncs{
		corev1.SchemeGroupVersion.WithKind("Service").GroupKind(): func(newObj, oldObj *unstructured.Unstructured) {
			newSvcType, found, _ := unstructured.NestedString(newObj.Object, "spec", "type")
			if !found {
				newSvcType = string(corev1.ServiceTypeClusterIP)
				_ = unstructured.SetNestedField(newObj.Object, newSvcType, "spec", "type")
			}

			oldSvcType, found, _ := unstructured.NestedString(oldObj.Object, "spec", "type")
			if !found {
				oldSvcType = string(corev1.ServiceTypeClusterIP)
			}

			switch newSvcType {
			case string(corev1.ServiceTypeLoadBalancer), string(corev1.ServiceTypeNodePort):
				oldPorts, found, _ := unstructured.NestedSlice(oldObj.Object, "spec", "ports")
				if !found {

					break
				}

				newPorts, found, _ := unstructured.NestedSlice(newObj.Object, "spec", "ports")
				if !found {

					break
				}

				ports := make([]interface{}, 0, len(newPorts))
				for _, newPort := range newPorts {
					np := newPort.(map[string]interface{})
					npName, _, _ := unstructured.NestedString(np, "name")
					npPort, _ := nestedFloat64OrInt64(np, "port")
					nodePort, ok := nestedFloat64OrInt64(np, "nodePort")

					for _, oldPortObj := range oldPorts {
						op := oldPortObj.(map[string]interface{})
						opName, _, _ := unstructured.NestedString(op, "name")
						opPort, _ := nestedFloat64OrInt64(op, "port")

						if (opName == npName || opPort == npPort) && (!ok || nodePort == 0) {
							np["nodePort"] = op["nodePort"]
						}
					}

					ports = append(ports, np)
				}

				_ = unstructured.SetNestedSlice(newObj.Object, ports, "spec", "ports")

			case string(corev1.ServiceTypeExternalName):

				return
			}

			if oldSvcType != string(corev1.ServiceTypeExternalName) {
				newClusterIP, _, _ := unstructured.NestedString(newObj.Object, "spec", "clusterIP")
				if newClusterIP != corev1.ClusterIPNone || newSvcType != string(corev1.ServiceTypeClusterIP) {
					oldClusterIP, _, _ := unstructured.NestedString(oldObj.Object, "spec", "clusterIP")
					_ = unstructured.SetNestedField(newObj.Object, oldClusterIP, "spec", "clusterIP")
				}
			}

			newETP, _, _ := unstructured.NestedString(newObj.Object, "spec", "externalTrafficPolicy")
			oldETP, _, _ := unstructured.NestedString(oldObj.Object, "spec", "externalTrafficPolicy")

			if oldSvcType == string(corev1.ServiceTypeLoadBalancer) &&
				newSvcType == string(corev1.ServiceTypeLoadBalancer) &&
				newETP == string(corev1.ServiceExternalTrafficPolicyTypeLocal) &&
				oldETP == string(corev1.ServiceExternalTrafficPolicyTypeLocal) {
				newHealthCheckPort, _ := nestedFloat64OrInt64(newObj.Object, "spec", "healthCheckNodePort")
				if newHealthCheckPort == 0 {
					oldHealthCheckPort, _ := nestedFloat64OrInt64(oldObj.Object, "spec", "healthCheckNodePort")
					_ = unstructured.SetNestedField(newObj.Object, oldHealthCheckPort, "spec", "healthCheckNodePort")
				}
			}

		},
		corev1.SchemeGroupVersion.WithKind("ServiceAccount").GroupKind(): func(newObj, oldObj *unstructured.Unstructured) {

			newObj.Object["secrets"] = oldObj.Object["secrets"]
			newObj.Object["imagePullSecrets"] = oldObj.Object["imagePullSecrets"]
		},
		{Group: "autoscaling.k8s.io", Kind: "VerticalPodAutoscaler"}: func(newObj, oldObj *unstructured.Unstructured) {

			newObj.Object["status"] = oldObj.Object["status"]
		},
	}

	DeploymentKeepReplicasMergeFunc = MergeFunc(func(newObj, oldObj *unstructured.Unstructured) {
		oldReplicas, ok := nestedFloat64OrInt64(oldObj.Object, "spec", "replicas")
		if !ok {
			return
		}
		_ = unstructured.SetNestedField(newObj.Object, oldReplicas, "spec", "replicas")
	})
)

DefaultMergeFuncs contains options for common k8s objects, e.g. Service, ServiceAccount.

View Source
var (
	// GardenScheme is the scheme used in the Garden cluster.
	GardenScheme = runtime.NewScheme()
	// SeedScheme is the scheme used in the Seed cluster.
	SeedScheme = runtime.NewScheme()
	// ShootScheme is the scheme used in the Shoot cluster.
	ShootScheme = runtime.NewScheme()
	// PlantScheme is the scheme used in the Plant cluster
	PlantScheme = runtime.NewScheme()

	// DefaultDeleteOptions use foreground propagation policy and grace period of 60 seconds.
	DefaultDeleteOptions = []client.DeleteOption{
		client.PropagationPolicy(metav1.DeletePropagationForeground),
		client.GracePeriodSeconds(60),
	}
	// ForceDeleteOptions use background propagation policy and grace period of 0 seconds.
	ForceDeleteOptions = []client.DeleteOption{
		client.PropagationPolicy(metav1.DeletePropagationBackground),
		client.GracePeriodSeconds(0),
	}

	// SeedSerializer is a YAML serializer using the Seed scheme.
	SeedSerializer = json.NewSerializerWithOptions(json.DefaultMetaFactory, SeedScheme, SeedScheme, json.SerializerOptions{Yaml: true, Pretty: false, Strict: false})
	// SeedCodec is a codec factory using the Seed scheme.
	SeedCodec = serializer.NewCodecFactory(SeedScheme)

	// ShootSerializer is a YAML serializer using the Shoot scheme.
	ShootSerializer = json.NewSerializerWithOptions(json.DefaultMetaFactory, ShootScheme, ShootScheme, json.SerializerOptions{Yaml: true, Pretty: false, Strict: false})
	// ShootCodec is a codec factory using the Shoot scheme.
	ShootCodec = serializer.NewCodecFactory(ShootScheme)
)
View Source
var ForceNamespace = forceNamespace{}

ForceNamespace can be used for native chart objects do not come with a Release.Namespace option and leave the namespace field empty.

View Source
var (
	// UseCachedRuntimeClients is a flag for enabling cached controller-runtime clients (defaults to false).
	// If enabled, the client returned by Interface.Client() will be backed by a cache, otherwise it will be the same
	// client that will be returned by Interface.DirectClient().
	UseCachedRuntimeClients = false
)
View Source
var Values = func(values interface{}) ValueOption { return &withValue{values} }

Values applies values to ApplyOptions or DeleteOptions.

Functions

func DefaultCreateOptions added in v1.11.0

func DefaultCreateOptions() metav1.CreateOptions

DefaultCreateOptions are the default options for CREATE requests.

func DefaultGetOptions added in v1.11.0

func DefaultGetOptions() metav1.GetOptions

DefaultGetOptions are the default options for GET requests.

func DefaultUpdateOptions added in v1.11.0

func DefaultUpdateOptions() metav1.UpdateOptions

DefaultUpdateOptions are the default options for UPDATE requests.

func GetAdmissionPluginsForVersion

func GetAdmissionPluginsForVersion(v string) []gardencorev1beta1.AdmissionPlugin

GetAdmissionPluginsForVersion returns the set of default admission plugins for the given Kubernetes version. If the given Kubernetes version does not explicitly define admission plugins the set of names for the next available version will be returned (e.g., for version X not defined the set of version X-1 will be returned).

func GetPodLogs

func GetPodLogs(ctx context.Context, podInterface corev1client.PodInterface, name string, options *corev1.PodLogOptions) ([]byte, error)

GetPodLogs retrieves the pod logs of the pod of the given name with the given options.

func HasDeploymentRolloutCompleted added in v1.8.0

func HasDeploymentRolloutCompleted(ctx context.Context, c client.Client, namespace, name string) (bool, error)

HasDeploymentRolloutCompleted checks for the number of updated & available replicas to be equal to the deployment's desired replicas count. Thus confirming a successful rollout of the deployment.

func NewDirectClient added in v1.6.0

func NewDirectClient(config *rest.Config, options client.Options) (client.Client, error)

NewDirectClient creates a new client.Client which can be used to talk to the API directly (without a cache).

func NewDirectClientFromBytes added in v1.7.0

func NewDirectClientFromBytes(kubeconfig []byte, fns ...ConfigFunc) (client.Client, error)

NewDirectClientFromBytes creates a new controller runtime Client struct for a given kubeconfig byte slice.

func NewDirectClientFromSecret added in v1.7.0

func NewDirectClientFromSecret(secret *corev1.Secret, fns ...ConfigFunc) (client.Client, error)

NewDirectClientFromSecret creates a new controller runtime Client struct for a given secret.

func NewDirectClientWithConfig added in v1.7.0

func NewDirectClientWithConfig(fns ...ConfigFunc) (client.Client, error)

NewDirectClientWithConfig returns a new controller runtime client from a config.

func NewRuntimeCache added in v1.7.0

func NewRuntimeCache(config *rest.Config, options cache.Options) (cache.Cache, error)

NewRuntimeCache creates a new cache.Cache with the given config and options. It can be used for creating new controller-runtime clients with caches.

func NewRuntimeClientWithCache added in v1.7.0

func NewRuntimeClientWithCache(config *rest.Config, options client.Options, stopCh <-chan struct{}) (client.Client, error)

NewRuntimeClientWithCache creates a new client.client with the given config and options. The client uses a new cache, which will be started immediately using the given stop channel.

func RESTConfigFromClientConnectionConfiguration added in v0.33.0

func RESTConfigFromClientConnectionConfiguration(cfg *componentbaseconfig.ClientConnectionConfiguration, kubeconfig []byte) (*rest.Config, error)

RESTConfigFromClientConnectionConfiguration creates a *rest.Config from a componentbaseconfig.ClientConnectionConfiguration & the configured kubeconfig

func RESTConfigFromKubeconfig added in v1.10.0

func RESTConfigFromKubeconfig(kubeconfig []byte) (*rest.Config, error)

RESTConfigFromKubeconfig returns a rest.Config from the bytes of a kubeconfig

func ScaleDeployment

func ScaleDeployment(ctx context.Context, c client.Client, key client.ObjectKey, replicas int32) error

ScaleDeployment scales a Deployment.

func ScaleEtcd added in v1.2.0

func ScaleEtcd(ctx context.Context, c client.Client, key client.ObjectKey, replicas int) error

ScaleEtcd scales a Etcd resource.

func ScaleStatefulSet

func ScaleStatefulSet(ctx context.Context, c client.Client, key client.ObjectKey, replicas int32) error

ScaleStatefulSet scales a StatefulSet.

func ValidateConfig added in v0.33.0

func ValidateConfig(config clientcmdapi.Config) error

ValidateConfig validates that the auth info of a given kubeconfig doesn't have unsupported fields.

func WaitUntilDeploymentRolloutIsComplete added in v1.8.0

func WaitUntilDeploymentRolloutIsComplete(ctx context.Context, client client.Client, namespace string, name string, interval, timeout time.Duration) error

WaitUntilDeploymentRolloutIsComplete waits for the number of updated & available replicas to be equal to the deployment's desired replicas count. It keeps retrying until timeout

Types

type Applier

type Applier interface {
	ApplyManifest(ctx context.Context, unstructured UnstructuredReader, options MergeFuncs) error
	DeleteManifest(ctx context.Context, unstructured UnstructuredReader, opts ...DeleteManifestOption) error
}

Applier is an interface which describes declarative operations to apply multiple Kubernetes objects.

func NewApplier added in v1.6.0

func NewApplier(c client.Client, restMapper meta.RESTMapper) Applier

NewApplier constructs a new Applier from the given client.

func NewApplierForConfig

func NewApplierForConfig(config *rest.Config) (Applier, error)

NewApplierForConfig creates a new Applier for the given rest.Config. Use NewApplier if you already have a client and RESTMapper at hand, as this will create a new direct client.

type ApplyOption added in v1.2.0

type ApplyOption interface {
	// MutateApplyOptions applies this configuration to the given apply options.
	MutateApplyOptions(opts *ApplyOptions)
}

ApplyOption is some configuration that modifies options for a apply request.

type ApplyOptions added in v1.2.0

type ApplyOptions struct {
	// Values to pass to chart.
	Values interface{}

	// Additional MergeFunctions.
	MergeFuncs MergeFuncs

	// Forces the namespace for chart objects when applying the chart, this is because sometimes native chart
	// objects do not come with a Release.Namespace option and leave the namespace field empty
	ForceNamespace bool
}

ApplyOptions contains options for apply requests

type ChartApplier

type ChartApplier interface {
	chartrenderer.Interface
	Apply(ctx context.Context, chartPath, namespace, name string, opts ...ApplyOption) error
	Delete(ctx context.Context, chartPath, namespace, name string, opts ...DeleteOption) error
}

ChartApplier is an interface that describes needed methods that render and apply Helm charts in Kubernetes clusters.

func NewChartApplier

func NewChartApplier(renderer chartrenderer.Interface, applier Applier) ChartApplier

NewChartApplier returns a new chart applier.

func NewChartApplierForConfig

func NewChartApplierForConfig(config *rest.Config) (ChartApplier, error)

NewChartApplierForConfig returns a new chart applier based on the given REST config.

type Config added in v1.11.0

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

Config carries options for new ClientSets.

func NewConfig added in v1.11.0

func NewConfig() *Config

NewConfig returns a new Config with an empty REST config to allow testing ConfigFuncs without exporting the fields of the Config type.

type ConfigFunc

type ConfigFunc func(config *Config) error

ConfigFunc is a function that mutates a Config struct. It implements the functional options pattern. See https://github.com/tmrts/go-patterns/blob/master/idiom/functional-options.md.

func WithCacheResyncPeriod added in v1.7.0

func WithCacheResyncPeriod(resync time.Duration) ConfigFunc

WithCacheResyncPeriod returns a ConfigFunc that set the client's cache's resync period to the given duration.

func WithClientConnectionOptions

func WithClientConnectionOptions(cfg baseconfig.ClientConnectionConfiguration) ConfigFunc

WithClientConnectionOptions returns a ConfigFunc that transfers settings from the passed ClientConnectionConfiguration. The kubeconfig location in ClientConnectionConfiguration is disregarded, though!

func WithClientOptions

func WithClientOptions(opt client.Options) ConfigFunc

WithClientOptions returns a ConfigFunc that sets the passed Options on the Config object.

func WithDisabledCacheFor added in v1.12.0

func WithDisabledCacheFor(objects ...runtime.Object) ConfigFunc

WithDisabledCacheFor disables the cached client for the specified objects' GroupKinds.

func WithDisabledCachedClient added in v1.8.0

func WithDisabledCachedClient() ConfigFunc

WithDisabledCachedClient disables the cache in the controller-runtime client, so Client() will be equivalent to DirectClient().

func WithEnabledCacheFor added in v1.12.0

func WithEnabledCacheFor(objects ...runtime.Object) ConfigFunc

WithEnabledCacheFor enables the cached client only for the specified objects' GroupKinds.

func WithRESTConfig

func WithRESTConfig(restConfig *rest.Config) ConfigFunc

WithRESTConfig returns a ConfigFunc that sets the passed rest.Config on the Config object.

type DeleteManifestOption added in v1.7.0

type DeleteManifestOption interface {
	// MutateDeleteOptions applies this configuration to the given delete options.
	MutateDeleteManifestOptions(opts *DeleteManifestOptions)
}

DeleteManifestOption is some configuration that modifies options for a delete request.

type DeleteManifestOptions added in v1.7.0

type DeleteManifestOptions struct {
	// TolerateErrorFuncs are functions for which errors are tolerated.
	TolerateErrorFuncs []TolerateErrorFunc
}

DeleteOptions contains options for delete requests

type DeleteOption added in v1.2.0

type DeleteOption interface {
	// MutateDeleteOptions applies this configuration to the given delete options.
	MutateDeleteOptions(opts *DeleteOptions)
}

DeleteOption is some configuration that modifies options for a delete request.

type DeleteOptions added in v1.2.0

type DeleteOptions struct {
	// Values to pass to chart.
	Values interface{}

	// Forces the namespace for chart objects when applying the chart, this is because sometimes native chart
	// objects do not come with a Release.Namespace option and leave the namespace field empty
	ForceNamespace bool

	// TolerateErrorFuncs are functions for which errors are tolerated.
	TolerateErrorFuncs []TolerateErrorFunc
}

DeleteOptions contains options for delete requests

type Interface

type Interface interface {
	RESTConfig() *rest.Config
	RESTMapper() meta.RESTMapper
	RESTClient() rest.Interface

	// Client returns the ClientSet's controller-runtime client. This client should be used by default, as it carries
	// a cache, which uses SharedIndexInformers to keep up-to-date.
	Client() client.Client
	// DirectClient returns a controller-runtime client, which can be used to talk to the API server directly
	// (without using a cache).
	DirectClient() client.Client
	// Cache returns the ClientSet's controller-runtime cache. It can be used to get Informers for arbitrary objects.
	Cache() cache.Cache

	// Applier returns an Applier which uses the ClientSet's client.
	Applier() Applier
	// ChartRenderer returns a ChartRenderer populated with the cluster's Capabilities.
	ChartRenderer() chartrenderer.Interface
	// ChartApplier returns a ChartApplier using the ClientSet's ChartRenderer and Applier.
	ChartApplier() ChartApplier

	Kubernetes() kubernetesclientset.Interface
	GardenCore() gardencoreclientset.Interface
	APIExtension() apiextensionsclientset.Interface
	APIRegistration() apiregistrationclientset.Interface

	// Deprecated: Use `Client()` and utils instead.
	ForwardPodPort(string, string, int, int) (chan struct{}, error)
	CheckForwardPodPort(string, string, int, int) error

	// Version returns the server version of the targeted Kubernetes cluster.
	Version() string
	// DiscoverVersion tries to retrieve the server version of the targeted Kubernetes cluster and updates the
	// ClientSet's saved version accordingly. Use Version if you only want to retrieve the kubernetes version instead
	// of refreshing the ClientSet's saved version.
	DiscoverVersion() (*version.Info, error)

	// Start starts the cache of the ClientSet's controller-runtime client and returns immediately.
	// It must be called first before using the client to retrieve objects from the API server.
	Start(stopCh <-chan struct{})
	// WaitForCacheSync waits for the cache of the ClientSet's controller-runtime client to be synced.
	WaitForCacheSync(stopCh <-chan struct{}) bool
}

Interface is used to wrap the interactions with a Kubernetes cluster (which are performed with the help of kubernetes/client-go) in order to allow the implementation of several Kubernetes versions.

func NewClientFromBytes

func NewClientFromBytes(kubeconfig []byte, fns ...ConfigFunc) (Interface, error)

NewClientFromBytes creates a new Client struct for a given kubeconfig byte slice.

func NewClientFromFile

func NewClientFromFile(masterURL, kubeconfigPath string, fns ...ConfigFunc) (Interface, error)

NewClientFromFile creates a new Client struct for a given kubeconfig. The kubeconfig will be read from the filesystem at location <kubeconfigPath>. If given, <masterURL> overrides the master URL in the kubeconfig. If no filepath is given, the in-cluster configuration will be taken into account.

func NewClientFromSecret

func NewClientFromSecret(ctx context.Context, c client.Client, namespace, secretName string, fns ...ConfigFunc) (Interface, error)

NewClientFromSecret creates a new Client struct for a given kubeconfig stored as a Secret in an existing Kubernetes cluster. This cluster will be accessed by the <k8sClient>. It will read the Secret <secretName> in <namespace>. The Secret must contain a field "kubeconfig" which will be used.

func NewClientFromSecretObject

func NewClientFromSecretObject(secret *corev1.Secret, fns ...ConfigFunc) (Interface, error)

NewClientFromSecretObject creates a new Client struct for a given Kubernetes Secret object. The Secret must contain a field "kubeconfig" which will be used.

func NewWithConfig

func NewWithConfig(fns ...ConfigFunc) (Interface, error)

NewWithConfig returns a new Kubernetes base client.

type MergeFunc

type MergeFunc func(newObj, oldObj *unstructured.Unstructured)

MergeFunc determines how oldOj is merged into new oldObj.

type MergeFuncs added in v1.2.0

type MergeFuncs map[schema.GroupKind]MergeFunc

MergeFuncs can be used modify the default merge functions for ApplyOptions:

Apply(ctx, "chart", "my-ns", "my-release", MergeFuncs{
		corev1.SchemeGroupVersion.WithKind("Service").GroupKind(): func(newObj, oldObj *unstructured.Unstructured) {
			newObj.SetAnnotations(map[string]string{"foo":"bar"})
		}
})

func CopyApplierOptions

func CopyApplierOptions(in MergeFuncs) MergeFuncs

CopyApplierOptions returns a copies of the provided applier options.

func (MergeFuncs) MutateApplyOptions added in v1.2.0

func (m MergeFuncs) MutateApplyOptions(opts *ApplyOptions)

MutateApplyOptions applies this configuration to the given apply options.

type PodExecutor

type PodExecutor interface {
	Execute(namespace, name, containerName, command, commandArg string) (io.Reader, error)
}

PodExecutor is the pod executor interface

func NewPodExecutor

func NewPodExecutor(config *rest.Config) PodExecutor

NewPodExecutor returns a podExecutor

type TolerateErrorFunc added in v1.7.0

type TolerateErrorFunc func(err error) bool

TolerateErrorFunc is a function for which err is tolerated.

func (TolerateErrorFunc) MutateDeleteManifestOptions added in v1.7.0

func (t TolerateErrorFunc) MutateDeleteManifestOptions(opts *DeleteManifestOptions)

func (TolerateErrorFunc) MutateDeleteOptions added in v1.7.0

func (t TolerateErrorFunc) MutateDeleteOptions(opts *DeleteOptions)

type UnstructuredReader

type UnstructuredReader interface {
	Read() (*unstructured.Unstructured, error)
}

UnstructuredReader an interface that all manifest readers should implement

func NewManifestReader

func NewManifestReader(manifest []byte) UnstructuredReader

NewManifestReader initializes a reader for yaml manifests

func NewNamespaceSettingReader

func NewNamespaceSettingReader(mReader UnstructuredReader, namespace string) UnstructuredReader

NewNamespaceSettingReader initializes a reader for yaml manifests with support for setting the namespace

func NewObjectReferenceReader

func NewObjectReferenceReader(objectReference *corev1.ObjectReference) UnstructuredReader

NewObjectReferenceReader initializes a reader from ObjectReference

type ValueOption added in v1.2.0

type ValueOption interface {
	ApplyOption
	DeleteOption
}

ValueOption contains value options for Apply and Delete.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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