k8sclient

package
v1.6.5 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2021 License: Apache-2.0 Imports: 59 Imported by: 0

Documentation

Overview

Package k8sclient implements various k8s and EKS client utils.

Index

Constants

View Source
const (

	// DefaultNamespacePollInterval is the default namespace poll interval.
	DefaultNamespacePollInterval = 15 * time.Second
	// DefaultNamespaceDeletionInterval is the default namespace deletion interval.
	DefaultNamespaceDeletionInterval = 15 * time.Second
	// DefaultNamespaceDeletionTimeout is the default namespace deletion timeout.
	DefaultNamespaceDeletionTimeout = 30 * time.Minute
)

Variables

This section is empty.

Functions

func CreateNamespace

func CreateNamespace(lg *zap.Logger, c clientset.Interface, namespace string) error

CreateNamespace creates a single namespace with given name.

func CreateObject

func CreateObject(dynamicClient dynamic.Interface, namespace string, name string, obj *unstructured.Unstructured, options ...*ApiCallOptions) error

CreateObject creates object based on given object description.

func DeleteNamespaceAndWait

func DeleteNamespaceAndWait(
	lg *zap.Logger,
	c clientset.Interface,
	namespace string,
	pollInterval time.Duration,
	timeout time.Duration,
	opts ...OpOption) error

DeleteNamespaceAndWait deletes namespace with given name and waits for its deletion. Default interval is 5-second and default timeout is 10-min.

func IsRetryableAPIError

func IsRetryableAPIError(err error) bool

IsRetryableAPIError verifies whether the error is retryable.

func IsRetryableNetError

func IsRetryableNetError(err error) bool

IsRetryableNetError determines whether the error is a retryable net error.

func ListEvents

func ListEvents(c clientset.Interface, namespace string, name string, options ...*ApiCallOptions) (obj *v1.EventList, err error)

ListEvents retrieves events for the object with the given name.

func ListNamespaces

func ListNamespaces(c clientset.Interface) ([]v1.Namespace, error)

ListNamespaces returns list of existing namespace names.

func ListNodes

func ListNodes(c clientset.Interface) ([]v1.Node, error)

ListNodes returns list of cluster nodes.

func ListNodesWithOptions

func ListNodesWithOptions(c clientset.Interface, listOpts metav1.ListOptions) ([]v1.Node, error)

ListNodesWithOptions lists the cluster nodes using the provided options.

func ListPodsWithOptions

func ListPodsWithOptions(c clientset.Interface, namespace string, listOpts metav1.ListOptions) ([]v1.Pod, error)

ListPodsWithOptions lists the pods using the provided options.

func RetryFunction

func RetryFunction(f func() error, options ...*ApiCallOptions) wait.ConditionFunc

RetryFunction opaques given function into retryable function.

func RetryWithExponentialBackOff

func RetryWithExponentialBackOff(fn wait.ConditionFunc) error

RetryWithExponentialBackOff a utility for retrying the given function with exponential backoff.

func WaitForCronJobCompletes added in v1.4.6

func WaitForCronJobCompletes(
	ctx context.Context,
	lg *zap.Logger,
	logWriter io.Writer,
	stopc chan struct{},
	k8sClient EKS,
	initialWait time.Duration,
	pollInterval time.Duration,
	namespace string,
	jobName string,
	targetCompletes int,
	opts ...OpOption) (cronJob *batchv1beta1.CronJob, pods []v1.Pod, err error)

WaitForCronJobCompletes waits for all CronJob completion, by counting the number of pods in the namespace.

func WaitForDeploymentCompletes added in v1.4.6

func WaitForDeploymentCompletes(
	ctx context.Context,
	lg *zap.Logger,
	logWriter io.Writer,
	stopc chan struct{},
	k8sClient EKS,
	initialWait time.Duration,
	pollInterval time.Duration,
	namespace string,
	deploymentName string,
	targetAvailableReplicas int32,
	opts ...OpOption) (dp *appsv1.Deployment, err error)

WaitForDeploymentCompletes waits till target replicas are ready in the Deployment.

func WaitForJobCompletes added in v1.4.6

func WaitForJobCompletes(
	ctx context.Context,
	lg *zap.Logger,
	logWriter io.Writer,
	stopc chan struct{},
	k8sClient EKS,
	initialWait time.Duration,
	pollInterval time.Duration,
	namespace string,
	jobName string,
	targetCompletes int,
	opts ...OpOption) (job *batchv1.Job, pods []v1.Pod, err error)

WaitForJobCompletes waits for all Job completion, by counting the number of pods in the namespace.

func WaitForReplicationControllerCompletes added in v1.4.6

func WaitForReplicationControllerCompletes(
	ctx context.Context,
	lg *zap.Logger,
	logWriter io.Writer,
	stopc chan struct{},
	k8sClient EKS,
	initialWait time.Duration,
	pollInterval time.Duration,
	namespace string,
	replicationControllerName string,
	targetAvailableReplicas int32,
	opts ...OpOption) (dp *v1.ReplicationController, err error)

WaitForReplicationControllerCompletes waits till target replicas are ready in the ReplicationController.

Types

type ApiCallOptions

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

ApiCallOptions describes how api call errors should be treated, i.e. which errors should be allowed (ignored) and which should be retried.

func Allow

func Allow(allowErrorPredicate func(error) bool) *ApiCallOptions

Allow creates an ApiCallOptions that allows (ignores) errors matching the given predicate.

func Retry

func Retry(retryErrorPredicate func(error) bool) *ApiCallOptions

Retry creates an ApiCallOptions that retries errors matching the given predicate.

type EKS added in v1.0.2

type EKS interface {
	// KubernetesClientSet returns a new kubernetes client set.
	KubernetesClientSet() *kubernetes.Clientset
	// APIExtensionsClientSet returns a new apiextensions client set.
	APIExtensionsClientSet() *apiextensions_client.Clientset

	// Apply raw YAML using kubectl.
	// Writes to a temporary file and execute kubectl. Returns the complete output or an error.
	Apply(data string) error
	// Delete raw YAML using kubectl.
	// Writes to a temporary file and execute kubectl. Returns the complete output or an error.
	Delete(data string) error

	// CheckEKSHealth checks the EKS health.
	CheckHealth() error

	// FetchServerVersion fetches the version from kube-apiserver.
	//
	// e.g.
	//
	//	{
	//		"major": "1",
	//		"minor": "16+",
	//		"gitVersion": "v1.16.8-eks-e16311",
	//		"gitCommit": "e163110a04dcb2f39c3325af96d019b4925419eb",
	//		"gitTreeState": "clean",
	//		"buildDate": "2020-03-27T22:37:12Z",
	//		"goVersion": "go1.13.8",
	//		"compiler": "gc",
	//		"platform": "linux/amd64"
	//	}
	//
	FetchServerVersion() (ServerVersionInfo, error)

	// FetchSupportedAPIGroupVersions fetches all supported API group resources.
	// ref. https://github.com/kubernetes/kubernetes/tree/master/staging/src/k8s.io/kubectl/pkg/cmd/apiresources
	FetchSupportedAPIGroupVersions() (float64, map[string]struct{}, error)

	// ListNamespaces returns the list of existing namespace names.
	ListNamespaces(batchLimit int64, batchInterval time.Duration) ([]v1.Namespace, error)
	// ListNodes returns the list of existing nodes.
	ListNodes(batchLimit int64, batchInterval time.Duration, opts ...OpOption) ([]v1.Node, error)
	// ListCSRs returns the list of existing CSRs.
	ListCSRs(batchLimit int64, batchInterval time.Duration) ([]certificatesv1beta1.CertificateSigningRequest, error)
	// ListPods returns the list of existing namespace names.
	ListPods(namespace string, batchLimit int64, batchInterval time.Duration, opts ...OpOption) ([]v1.Pod, error)
	// ListConfigMaps returns the list of existing config maps.
	ListConfigMaps(namespace string, batchLimit int64, batchInterval time.Duration) ([]v1.ConfigMap, error)
	// ListSecrets returns the list of existing Secret objects.
	ListSecrets(namespace string, batchLimit int64, batchInterval time.Duration) ([]v1.Secret, error)

	ListAppsV1Deployments(namespace string, batchLimit int64, batchInterval time.Duration) (ss []apps_v1.Deployment, err error)
	ListAppsV1StatefulSets(namespace string, batchLimit int64, batchInterval time.Duration) (ss []apps_v1.StatefulSet, err error)
	ListAppsV1DaemonSets(namespace string, batchLimit int64, batchInterval time.Duration) (ss []apps_v1.DaemonSet, err error)
	ListAppsV1ReplicaSets(namespace string, batchLimit int64, batchInterval time.Duration) (ss []apps_v1.ReplicaSet, err error)
	ListNetworkingV1NetworkPolicies(namespace string, batchLimit int64, batchInterval time.Duration) (ss []networking_v1.NetworkPolicy, err error)
	ListPolicyV1beta1PodSecurityPolicies(batchLimit int64, batchInterval time.Duration) (ss []policy_v1beta1.PodSecurityPolicy, err error)

	ListAppsV1beta1Deployments(namespace string, batchLimit int64, batchInterval time.Duration) (ss []apps_v1beta1.Deployment, err error)
	ListAppsV1beta1StatefulSets(namespace string, batchLimit int64, batchInterval time.Duration) (ss []apps_v1beta1.StatefulSet, err error)
	ListAppsV1beta2Deployments(namespace string, batchLimit int64, batchInterval time.Duration) (ss []apps_v1beta2.Deployment, err error)
	ListAppsV1beta2StatefulSets(namespace string, batchLimit int64, batchInterval time.Duration) (ss []apps_v1beta2.StatefulSet, err error)
	ListExtensionsV1beta1DaemonSets(namespace string, batchLimit int64, batchInterval time.Duration) (ss []extensions_v1beta1.DaemonSet, err error)
	ListExtensionsV1beta1Deployments(namespace string, batchLimit int64, batchInterval time.Duration) (ss []extensions_v1beta1.Deployment, err error)
	ListExtensionsV1beta1ReplicaSets(namespace string, batchLimit int64, batchInterval time.Duration) (ss []extensions_v1beta1.ReplicaSet, err error)
	ListExtensionsV1beta1NetworkPolicies(namespace string, batchLimit int64, batchInterval time.Duration) (ss []extensions_v1beta1.NetworkPolicy, err error)
	ListExtensionsV1beta1PodSecurityPolicies(batchLimit int64, batchInterval time.Duration) (ss []extensions_v1beta1.PodSecurityPolicy, err error)

	// GetObject get object type and object metadata using kubectl.
	// The internal API group version is not exposed,
	// thus kubectl converts API version internally.
	// ref. https://github.com/kubernetes/kubernetes/issues/58131#issuecomment-403829566
	GetObject(namespace string, kind string, name string) (obj Object, d []byte, err error)

	// Deprecate checks deprecated API groups based on the current kube-apiserver version.
	Deprecate(batchLimit int64, batchInterval time.Duration) error
}

EKS defines EKS client operations.

func NewEKS added in v1.0.2

func NewEKS(cfg *EKSConfig) (e EKS, err error)

NewEKS returns a new EKS client.

type EKSConfig added in v1.0.2

type EKSConfig struct {
	// Logger is the logger to log client operations.
	Logger *zap.Logger
	// Region is used for EKS auth provider configuration.
	Region string
	// ClusterName is the EKS cluster name.
	// Used for EKS auth provider configuration.
	ClusterName string
	// ClusterAPIServerEndpoint is the EKS kube-apiserver endpoint.
	// Use for kubeconfig.
	ClusterAPIServerEndpoint string
	// ClusterCADecoded is the cluster CA base64-decoded.
	// Use for kubeconfig.
	ClusterCADecoded string
	// KubectlPath is the kubectl path, used for health checks.
	KubectlPath string
	// KubeConfigPath is the kubeconfig path to load.
	KubeConfigPath string
	// KubeConfigContext is the kubeconfig context.
	KubeConfigContext string
	// ServerVersion is the kube-apiserver version.
	// If not empty, this is used for health checks.
	ServerVersion string
	// UpgradeServerVersion is the target cluster upgrade version
	// used for sever version checks.
	UpgradeServerVersion string
	// EncryptionEnabled is true if EKS cluster is created with KMS encryption enabled.
	// If true, the health check checks if data encryption key has been generated
	// to encrypt initial service account tokens, via kube-apiserver metrics endpoint.
	EncryptionEnabled bool
	// EnablePrompt is true to enable interactive mode.
	EnablePrompt bool
	// Dir is the directory to store all upgrade/rollback files.
	Dir string

	S3API                              s3iface.S3API
	S3BucketName                       string
	S3MetricsRawOutputDirKubeAPIServer string
	MetricsRawOutputDirKubeAPIServer   string

	// Clients is the number of kubernetes clients to create.
	// Default is 1.
	Clients int
	// ClientQPS is the QPS for kubernetes client.
	// To use while talking with kubernetes apiserver.
	//
	// Kubernetes client DefaultQPS is 5.
	// Kubernetes client DefaultBurst is 10.
	// ref. https://github.com/kubernetes/kubernetes/blob/4d0e86f0b8d1eae00a202009858c8739e4c9402e/staging/src/k8s.io/client-go/rest/config.go#L43-L46
	//
	// kube-apiserver default inflight requests limits are:
	// FLAG: --max-mutating-requests-inflight="200"
	// FLAG: --max-requests-inflight="400"
	// ref. https://github.com/kubernetes/kubernetes/blob/4d0e86f0b8d1eae00a202009858c8739e4c9402e/staging/src/k8s.io/apiserver/pkg/server/config.go#L300-L301
	//
	ClientQPS float32
	// ClientBurst is the burst for kubernetes client.
	// To use while talking with kubernetes apiserver
	//
	// Kubernetes client DefaultQPS is 5.
	// Kubernetes client DefaultBurst is 10.
	// ref. https://github.com/kubernetes/kubernetes/blob/4d0e86f0b8d1eae00a202009858c8739e4c9402e/staging/src/k8s.io/client-go/rest/config.go#L43-L46
	//
	// kube-apiserver default inflight requests limits are:
	// FLAG: --max-mutating-requests-inflight="200"
	// FLAG: --max-requests-inflight="400"
	// ref. https://github.com/kubernetes/kubernetes/blob/4d0e86f0b8d1eae00a202009858c8739e4c9402e/staging/src/k8s.io/apiserver/pkg/server/config.go#L300-L301
	//
	ClientBurst int
	// ClientTimeout is the client timeout.
	ClientTimeout time.Duration
}

EKSConfig defines EKS client configuration.

type Object added in v1.0.2

type Object struct {
	// Kind is a string value representing the REST resource this object represents.
	// Servers may infer this from the endpoint the client submits requests to.
	// Cannot be updated.
	// In CamelCase.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
	// ref. metav1.TypeMeta
	Kind string `json:"kind"`
	// APIVersion defines the versioned schema of this representation of an object.
	// Servers should convert recognized schemas to the latest internal value, and
	// may reject unrecognized values.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
	// ref. metav1.TypeMeta
	APIVersion string `json:"apiVersion"`

	ObjectMeta metav1.ObjectMeta `json:"metadata"`
}

Object contains all object metadata.

type Op added in v1.3.8

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

Op represents a Kubernetes client operation.

type OpOption added in v1.3.8

type OpOption func(*Op)

OpOption configures Kubernetes client operations.

func WithFieldSelector added in v1.5.6

func WithFieldSelector(s string) OpOption

WithFieldSelector configures field selector for list operations.

func WithForceDelete added in v1.4.6

func WithForceDelete(forceDelete bool) OpOption

WithForceDelete configures force delete. Useful for namespace deletion. ref. https://github.com/kubernetes/kubernetes/issues/60807

func WithForceDeleteFunc added in v1.4.6

func WithForceDeleteFunc(forceDeleteFunc func()) OpOption

WithForceDeleteFunc configures force delete. Useful for namespace deletion. ref. https://github.com/kubernetes/kubernetes/issues/60807

func WithLabelSelector added in v1.5.6

func WithLabelSelector(s string) OpOption

WithLabelSelector configures label selector for list operations.

func WithPodFunc added in v1.4.6

func WithPodFunc(f func(v1.Pod)) OpOption

WithPodFunc configures function to be called for pod.

func WithQueryFunc added in v1.3.8

func WithQueryFunc(f func()) OpOption

WithQueryFunc configures query function to be called in retry func.

type ServerVersionInfo added in v1.0.2

type ServerVersionInfo struct {
	version.Info
	VersionValue float64 `json:"version-value"`
}

ServerVersionInfo is the server version info from kube-apiserver

func (ServerVersionInfo) String added in v1.0.2

func (sv ServerVersionInfo) String() string

Directories

Path Synopsis
Package eksdeprecate defines deprecated APIs for EKS.
Package eksdeprecate defines deprecated APIs for EKS.

Jump to

Keyboard shortcuts

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