k8s

package
v0.0.0-...-ae32cb6 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	GVRPod = &schema.GroupVersionResource{
		Group:    "",
		Resource: "pods",
		Version:  "v1",
	}
	GVRNode = &schema.GroupVersionResource{
		Group:    "",
		Resource: "nodes",
		Version:  "v1",
	}
	GVRDeployment, _ = schema.ParseResourceArg("deployments.v1.apps")
	GVRNamespace     = &schema.GroupVersionResource{
		Group:    "",
		Resource: "namespaces",
		Version:  "v1",
	}
	GVRPersistentVolumeClaim = &schema.GroupVersionResource{
		Group:    "",
		Resource: "persistentvolumeclaims",
		Version:  "v1",
	}
	GVRConfigMap = &schema.GroupVersionResource{
		Group:    "",
		Resource: "configmaps",
		Version:  "v1",
	}
	GVREvents = &schema.GroupVersionResource{
		Group:    "",
		Resource: "events",
		Version:  "v1",
	}
	GVRCiliumNetworkPolicy = &schema.GroupVersionResource{
		Group:    "cilium.io",
		Resource: "ciliumnetworkpolicies",
		Version:  "v2",
	}
	ResourceToKind = map[string]string{
		GVRPod.Resource:                   "Pod",
		GVRNode.Resource:                  "Node",
		GVRDeployment.Resource:            "Deployment",
		GVRNamespace.Resource:             "Namespace",
		GVRPersistentVolumeClaim.Resource: "PersistentVolumeClaim",
		GVRConfigMap.Resource:             "ConfigMap",
		GVREvents.Resource:                "Event",
		GVRCiliumNetworkPolicy.Resource:   "CiliumNetworkPolicy",
	}
	ScaffoldingLabel         = "cilium.scaffolding"
	ScaffoldingLabelSelector = fmt.Sprintf("app.kubernetes.io=%s", ScaffoldingLabel)
)

Functions

func CheckUnstructuredForReadyState

func CheckUnstructuredForReadyState(logger *log.Logger, resource *unstructured.Unstructured) (bool, error)

CheckUnstructuredForReadyState takes in an *unstructured.Unstructured and returns a boolean describe if or if not the resource should be considered ready, depending on its (if applicable): conditions, phase, containers. It also logs the result as a pretty string.

func DoesConditionShowReady

func DoesConditionShowReady(condition map[string]interface{}) (bool, error)

DoesConditionShowReady returns if the given map reflects a condition that is in a ready state. For instance, if the condition has "ContainersReady" as true but "PIDPressure" as true as well, the condition is showing not ready. Essentially just a big switch statement.

func DoesContainerStatusShowCompleted

func DoesContainerStatusShowCompleted(containerStatus map[string]interface{}) (bool, error)

DoesContainerStatusShowCompleted takes the given containerStatus map and returns whether or not the status shows the container as having terminated with the reason "Completed".

func DoesPhaseShowReady

func DoesPhaseShowReady(phase string, kind string) (bool, error)

DoesPhaseShowReady is similar to DoesConditionShowReady but works for phases. Requires the kind of resource the phase is attached too, as different resource have different phase strings. Currently supports Pods, Namespaces and PVCs.

func FindKubeconfig

func FindKubeconfig(logger *log.Logger) string

FindKubeconfig attempts to resolve the location of the kubeconfig, returning its path. The following places will be uses, in order from first to last: 1. KUBECONFIG - environment variable 2. ./kubeconfig - kubeconfig in current working directory 3. ~/.kube/config - user's default kubeconfig

func GetNestedSliceStringInterfaceMap

func GetNestedSliceStringInterfaceMap(
	u *unstructured.Unstructured, path ...string,
) ([]map[string]interface{}, bool, error)

GetNestedSliceStringInterfaceMap returns a slice of string to interface maps within the given unstructured at the path described by the given variadic arguments. This is analogous to the suite of "NestedThing" functions in apimachinery.

func NewDynamicK8sClientSetOrDie

func NewDynamicK8sClientSetOrDie(logger *log.Logger, config *rest.Config) k8sDynamic.Interface

func NewFieldSelectorFromName

func NewFieldSelectorFromName(name string) string

NewFieldSelectorFromName constructs a new field selector to target resources whose metadata.name attribute matches the given name.

func NewK8sClientSetOrDie

func NewK8sClientSetOrDie(logger *log.Logger, config *rest.Config) k8s.Interface

NewK8sClientSetOrDie attempts to use the given kubeconfig path to create a new k8s clientset object. Upon failure, `ExitWithError` is called, which terminates execution.

func NewK8sConfigOrDie

func NewK8sConfigOrDie(logger *log.Logger, kubeconfigPath string) *rest.Config

func NewUnstructuredConfigMap

func NewUnstructuredConfigMap(name string, namespace string, data map[string]string) *unstructured.Unstructured

NewUnstructuredConfigMap creates a new *unstructured.Unstructured that represents a configmap data is a map that will be added under the configmaps "data" field.

func NewUnstructuredNS

func NewUnstructuredNS(name string) *unstructured.Unstructured

NewUnstructuredNS creates a new *unstructured.Unstructured representing a namespace. name is the name of the namespace to create.

func NewUnstructuredPVC

func NewUnstructuredPVC(name string, namespace string, accessMode string, size string) *unstructured.Unstructured

NewUnstructuredPVC creates a new *unstructured.Unstructured representing a PVC. It is a simple, classless PVC that depends on defaults setup in the cluster.

func NewUnstructuredPod

func NewUnstructuredPod(
	name string, namespace string, image string, cmd []string, args []string, opts *UnstructuredPodOpts,
) *unstructured.Unstructured

NewUnstructuredPod creates a new *unstructured.Unstructured that represents a pod.

func WithScaffoldingLabel

func WithScaffoldingLabel(res *unstructured.Unstructured) *unstructured.Unstructured

WithScaffoldingLabel adds a scaffolding specific variable to the given unstructured resource. This is useful to be able to watch resources created by the scaffolding toolkit.

Types

type Helper

type Helper struct {
	DynamicClientset k8sDynamic.Interface
	Clientset        k8s.Interface
	Kubeconfig       string
	Config           *rest.Config
	Logger           *log.Logger
}

Helper has useful methods for doing things in kubernetes. The goal with Helper is to reduce boilerplate code of tasks required by commands in toolkit

func NewHelperOrDie

func NewHelperOrDie(logger *log.Logger, kubeconfig string) *Helper

NewHelperOrDie creates a new Helper instance from the given kubeconfig and logger. If something goes wrong while creating it, then the entire program will exit.

func (*Helper) ApplyResource

func (k *Helper) ApplyResource(
	ctx context.Context, gvr schema.GroupVersionResource, res *unstructured.Unstructured, waitReady bool, ro *RetryOpts,
) (*unstructured.Unstructured, error)

ApplyResource is a wrapper around a dynamic apply, logging tasks and errors along the way. waitReady can be given to wait for the given structure to be ready. This uses WaitOnWatchedResource and CheckUnstructuredForReadyState.

func (*Helper) DeleteResourceAndWaitGone

func (k *Helper) DeleteResourceAndWaitGone(
	ctx context.Context, gvr schema.GroupVersionResource, name string, ns string, ro *RetryOpts,
) error

DeleteResourceAndWaitGone is a wrapper around a dynamic Delete, only returning when it is confirmed that the given resource is gone.

func (*Helper) LogPodLogs

func (k *Helper) LogPodLogs(
	ctx context.Context, ns string, podName string, wg *sync.WaitGroup, ro *RetryOpts,
	ignoredContainers ...string,
) (context.CancelFunc, error)

LogPodLogs attempts to stream logs from the containers in the given pod. There are two possible exit options: (1) Wait for all streams to hit an EOF with wg.Done, or (2) call the returned cancel function. Containers can be ignored from the log streams by passing them as variadic arguments. This is useful for pause or containers which have no logs, as they may not ever hit an EOF. This could cause the wait group to hang forever. This method needs a lot of love in the future. A great nice-to-have is being able to watch the given pod and create log streams for containers as they become available. This would require some work to differentiate between initContainers and normal containers

func (*Helper) PodExec

func (k *Helper) PodExec(
	podName string, containerName string, namespace string, cmd []string, dst *bytes.Buffer,
) error

PodExec runs a command within a pod within the given container. dst is a buffer where output from the command will be placed.

func (*Helper) VerifyResourceIsReady

func (k *Helper) VerifyResourceIsReady(
	ctx context.Context, gvr schema.GroupVersionResource, name string, ns string,
) (bool, error)

VerifyResourceIsReady runs a dynamic get on the given resource with name and ns, then passes it to CheckUnstructuredForReadyState.

func (*Helper) VerifyResourcesAreReady

func (k *Helper) VerifyResourcesAreReady(ctx context.Context, gvr schema.GroupVersionResource) (bool, error)

VerifyResourcesAreReady will list all resources describe by the given GVR and pass them to CheckUnstructuredForReadyState.

func (*Helper) WaitOnWatchedResource

func (k *Helper) WaitOnWatchedResource(
	ctx context.Context, gvr schema.GroupVersionResource, ns string, fieldSelector string, labelSelector string,
	cacheSyncCallback func(), conditions ...watchTools.ConditionFunc,
) (*watch.Event, error)

WaitOnWatchedResource is a wrapper around client-go/tools/watch.UntilWithSync function, providing the plumbing needed to watch resources, without having to handle creating a lister watcher.

func (*Helper) WatchAndLogEvents

func (k *Helper) WatchAndLogEvents(
	ctx context.Context, watchOpts metav1.ListOptions, eventFields ...string,
) (func(), error)

WatchAndLogEvents is a wrapper around a dynamic watch call, logging events as they come. Fields to pull from each event can be specified as variadic arguments.

type RetryOpts

type RetryOpts struct {
	MaxAttempts int
	Delay       time.Duration
}

RetryOpts defines variables controlling how tasks should be retried. Currently only supports a simple "retry x times with y delay in-between each attempt"

type UnstructuredPodOpts

type UnstructuredPodOpts struct {
	// Pin the pod onto the given node by name
	PinnedNode string
	// Mount the PVC with name "PVCName" into the pod (at /store)
	MountPVC bool
	// Name of PVC to mount into the pod
	PVCName string
	// Mount the config map with the name "ConfigMapName" into the pod (at /configs)
	MountConfigMap bool
	// ConfigMapName is the name of the configmap to mount into the pod
	ConfigMapName string
	// HostNS determines if the pod should enter the node PID and Network NSs and if the pod should be privileged
	HostNS bool
	// WithSleepContainer adds an alpine container to the pod that runs "sleep infinity"
	WithSleepContainer bool
}

UnstructuredPodOpts defines options for NewUnstructuredPod

Jump to

Keyboard shortcuts

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