kubernetes

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2020 License: Apache-2.0, BSD-2-Clause, MIT, + 1 more Imports: 50 Imported by: 189

Documentation

Index

Constants

View Source
const KubeConfig = "kubeconfig"

KubeConfig is the key to the kubeconfig

Variables

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),
	}
)
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 := []interface{}{}
			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 != string(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"]
	},
}

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

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 NewControllerClient = newControllerClient

NewControllerClient instantiates a new client.Client.

View Source
var Values = func(values interface{}) ValueOption { return &withValue{values} }

Values applies values to ApplyOptions or DeleteOptions.

Functions

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(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 NewRuntimeClientForConfig

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

NewRuntimeClientForConfig returns a new controller runtime client from a config.

func NewRuntimeClientFromBytes

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

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

func NewRuntimeClientFromSecret

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

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

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 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.

Types

type Applier

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

Applier is a default implementation of the ApplyInterface. It applies objects with by first checking whether they exist and then either creating / updating them (update happens with a predefined merge logic).

func NewApplierForConfig

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

NewApplierForConfig creates and returns a new Applier for the given rest.Config.

func NewApplierInternal

func NewApplierInternal(config *rest.Config, discoveryClient discovery.CachedDiscoveryInterface) (*Applier, error)

NewApplierInternal constructs a new Applier from the given config and DiscoveryInterface. This method should only be used for testing.

func (*Applier) ApplyManifest

func (c *Applier) ApplyManifest(ctx context.Context, r UnstructuredReader, options MergeFuncs) error

ApplyManifest is a function which does the same like `kubectl apply -f <file>`. It takes a bunch of manifests <m>, all concatenated in a byte slice, and sends them one after the other to the API server. If a resource already exists at the API server, it will update it. It returns an error as soon as the first error occurs.

func (*Applier) DeleteManifest

func (c *Applier) DeleteManifest(ctx context.Context, r UnstructuredReader) error

DeleteManifest is a function which does the same like `kubectl delete -f <file>`. It takes a bunch of manifests <m>, all concatenated in a byte slice, and sends them one after the other to the API server for deletion. It returns an error as soon as the first error occurs.

type ApplierInterface

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

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

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 ApplierInterface) 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 Clientset

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

Clientset is a struct containing the configuration for the respective Kubernetes cluster, the collection of Kubernetes clients <Clientset> containing all REST clients for the built-in Kubernetes API groups, and the Garden which is a REST clientset for the Garden API group. The RESTClient itself is a normal HTTP client for the respective Kubernetes cluster, allowing requests to arbitrary URLs. The version string contains only the major/minor part in the form <major>.<minor>.

func (*Clientset) APIExtension

func (c *Clientset) APIExtension() apiextensionclientset.Interface

APIExtension will return the apiextensionsClientset attribute of the Client object.

func (*Clientset) APIRegistration

func (c *Clientset) APIRegistration() apiregistrationclientset.Interface

APIRegistration will return the apiregistration attribute of the Client object.

func (*Clientset) Applier

func (c *Clientset) Applier() ApplierInterface

Applier returns the applier of this Clientset.

func (*Clientset) CheckForwardPodPort

func (c *Clientset) CheckForwardPodPort(namespace, name string, local, remote int) error

CheckForwardPodPort tries to forward the <remote> port of the pod with name <name> in namespace <namespace> to the <local> port. If <local> equals zero, a free port will be chosen randomly. It returns true if the port forward connection has been established successfully or false otherwise.

func (*Clientset) Client

func (c *Clientset) Client() client.Client

Client returns the client of this Clientset.

func (*Clientset) ForwardPodPort

func (c *Clientset) ForwardPodPort(namespace, name string, local, remote int) (chan struct{}, error)

ForwardPodPort tries to forward the <remote> port of the pod with name <name> in namespace <namespace> to the <local> port. If <local> equals zero, a free port will be chosen randomly. It returns the stop channel which must be closed when the port forward connection should be terminated.

func (*Clientset) GardenCore

func (c *Clientset) GardenCore() gardencoreclientset.Interface

GardenCore will return the gardenCore attribute of the Client object.

func (*Clientset) Kubernetes

func (c *Clientset) Kubernetes() kubernetes.Interface

Kubernetes will return the kubernetes attribute of the Client object.

func (*Clientset) RESTClient

func (c *Clientset) RESTClient() rest.Interface

RESTClient will return the restClient attribute of the Client object.

func (*Clientset) RESTConfig

func (c *Clientset) RESTConfig() *rest.Config

RESTConfig will return the config attribute of the Client object.

func (*Clientset) RESTMapper

func (c *Clientset) RESTMapper() meta.RESTMapper

RESTMapper returns the restMapper of this Clientset.

func (*Clientset) Version

func (c *Clientset) Version() string

Version returns the GitVersion of the Kubernetes client stored on the object.

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 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 WithRESTConfig

func WithRESTConfig(restConfig *rest.Config) ConfigFunc

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

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
}

DeleteOptions contains options for delete requests

type Interface

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

	Client() client.Client
	Applier() ApplierInterface

	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() string
}

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(k8sClient Interface, 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 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.

Jump to

Keyboard shortcuts

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