kube

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2024 License: Apache-2.0 Imports: 29 Imported by: 2

Documentation

Overview

Package kube provides primitives for working with Kubernetes objects.

Index

Constants

View Source
const (
	DeployerPodForDeploymentAnnotation string = "openshift.io/deployment-config.name"
)
View Source
const KubeSystemNamespace = "kube-system"

Variables

View Source
var ErrNoRunningPods = errors.New("no active pods for controller")
View Source
var ErrReplicaSetNotFound = errors.New("replicaset not found")
View Source
var ErrUnSupportedKind = errors.New("unsupported workload kind")

Functions

func AggregateImagePullSecretsData

func AggregateImagePullSecretsData(images ContainerImages, credentials map[string]docker.Auth) map[string][]byte

func AppendCustomLabels added in v0.13.0

func AppendCustomLabels(configCustomLabels map[string]string, reportLabels map[string]string)

AppendCustomLabels append custom labels to report

func AppendResourceLabels added in v0.13.0

func AppendResourceLabels(configLabelsNames []string, resourceLabels map[string]string, reportLabels map[string]string)

AppendResourceLabels match resource labels by config and append it to report labels

func ComputeHash

func ComputeHash(obj interface{}) string

ComputeHash returns a hash value calculated from a given object. The hash will be safe encoded to avoid bad words.

func ComputeSpecHash

func ComputeSpecHash(obj client.Object) (string, error)

ComputeSpecHash computes hash of the specified K8s client.Object. The hash is used to indicate whether the client.Object should be rescanned or not by adding it as the trivy-operator.LabelResourceSpecHash label to an instance of a security report.

func DeepHashObject

func DeepHashObject(hasher hash.Hash, objectToWrite interface{})

DeepHashObject writes specified object to hash using the spew library which follows pointers and prints actual values of the nested objects ensuring the hash does not change when a pointer changes.

func GetPodSpec

func GetPodSpec(obj client.Object) (corev1.PodSpec, error)

GetPodSpec returns v1.PodSpec from the specified Kubernetes client.Object. Returns error if the given client.Object is not a Kubernetes workload.

func GetTerminatedContainersStatusesByPod

func GetTerminatedContainersStatusesByPod(pod *corev1.Pod) map[string]*corev1.ContainerStateTerminated

func GetWildcardServers added in v0.13.0

func GetWildcardServers(auths map[string]docker.Auth) []string

func IsBuiltInWorkload

func IsBuiltInWorkload(controller *metav1.OwnerReference) bool

IsBuiltInWorkload returns true if the specified v1.OwnerReference is a built-in Kubernetes workload, false otherwise.

func IsClusterScopedKind

func IsClusterScopedKind(kind string) bool

IsClusterScopedKind returns true if the specified kind is ClusterRole, ClusterRoleBinding, and CustomResourceDefinition. TODO Use discovery client to have a generic implementation.

func IsPodControlledByJobNotFound

func IsPodControlledByJobNotFound(err error) bool

func IsRoleRelatedNamespaceScope added in v0.1.3

func IsRoleRelatedNamespaceScope(kind Kind) bool

func IsRoleTypes added in v0.1.3

func IsRoleTypes(kind Kind) bool

func IsValidK8sKind added in v0.1.0

func IsValidK8sKind(kind string) bool

func IsWorkload

func IsWorkload(kind string) bool

IsWorkload returns true if the specified resource kinds represents Kubernetes workload, false otherwise.

func MapContainerNamesToDockerAuths

func MapContainerNamesToDockerAuths(images ContainerImages, auths map[string]docker.Auth) (map[string]docker.Auth, error)

MapContainerNamesToDockerAuths creates the mapping from a container name to the Docker authentication credentials for the specified kube.ContainerImages and image pull Secrets.

func MapDockerRegistryServersToAuths

func MapDockerRegistryServersToAuths(imagePullSecrets []corev1.Secret, multiSecretSupport bool) (map[string]docker.Auth, error)

MapDockerRegistryServersToAuths creates the mapping from a Docker registry server to the Docker authentication credentials for the specified slice of image pull Secrets.

func ObjectRefToLabels

func ObjectRefToLabels(obj ObjectRef) map[string]string

ObjectRefToLabels encodes the specified ObjectRef as a set of labels.

If Object's name cannot be used as the value of the trivy-operator.LabelResourceName label, as a fallback, this method will calculate a hash of the Object's name and use it as the value of the trivy-operator.LabelResourceNameHash label.

func ObjectToObjectMeta

func ObjectToObjectMeta(obj client.Object, objectMeta *metav1.ObjectMeta) error

ObjectToObjectMeta encodes the specified client.Object as a set of labels and annotations added to the given ObjectMeta.

Types

type CompatibleMgr added in v0.1.4

type CompatibleMgr interface {
	// GetSupportedObjectByKind get specific k8s compatible object (group/api/kind) by kind
	GetSupportedObjectByKind(kind Kind, defaultObject client.Object) client.Object
}

CompatibleMgr provide k8s compatible objects (group/api/kind) capabilities

func InitCompatibleMgr added in v0.1.4

func InitCompatibleMgr() (CompatibleMgr, error)

InitCompatibleMgr initializes a CompatibleObjectMapper who store a map the of supported kinds with it compatible Objects (group/api/kind) it dynamically fetches the compatible k8s objects (group/api/kind) by resource from the cluster and store it in kind vs k8s object mapping It will enable the operator to support old and new API resources based on cluster version support

type CompatibleObjectMapper added in v0.1.4

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

func (*CompatibleObjectMapper) GetSupportedObjectByKind added in v0.1.4

func (o *CompatibleObjectMapper) GetSupportedObjectByKind(kind Kind, defaultObject client.Object) client.Object

GetSupportedObjectByKind accept kind and return the supported object (group/api/kind) of the cluster

type ContainerImages

type ContainerImages map[string]string

ContainerImages is a simple structure to hold the mapping between container names and container image references.

func GetContainerImagesFromContainersList added in v0.14.0

func GetContainerImagesFromContainersList(containers []corev1.Container) ContainerImages

GetContainerImagesFromContainersList returns a map of container names to container images from the specified corev1.Container array.

func GetContainerImagesFromJob

func GetContainerImagesFromJob(job *batchv1.Job) (ContainerImages, error)

GetContainerImagesFromJob returns a map of container names to container images from the specified v1.Job. The mapping is encoded as JSON value of the AnnotationContainerImages annotation.

func GetContainerImagesFromPodSpec

func GetContainerImagesFromPodSpec(spec corev1.PodSpec, skipInitContainers bool) ContainerImages

GetContainerImagesFromPodSpec returns a map of container names to container images from the specified v1.PodSpec.

func (ContainerImages) AsJSON

func (ci ContainerImages) AsJSON() (string, error)

func (ContainerImages) FromJSON

func (ci ContainerImages) FromJSON(value string) error

type Kind

type Kind string

Kind represents the type of Kubernetes client.Object.

const (
	KindPod                   Kind = "Pod"
	KindReplicaSet            Kind = "ReplicaSet"
	KindReplicationController Kind = "ReplicationController"
	KindDeployment            Kind = "Deployment"
	KindDeploymentConfig      Kind = "DeploymentConfig"
	KindStatefulSet           Kind = "StatefulSet"
	KindDaemonSet             Kind = "DaemonSet"
	KindCronJob               Kind = "CronJob"
	KindJob                   Kind = "Job"
	KindService               Kind = "Service"
	KindConfigMap             Kind = "ConfigMap"
	KindRole                  Kind = "Role"
	KindRoleBinding           Kind = "RoleBinding"
	KindNetworkPolicy         Kind = "NetworkPolicy"
	KindIngress               Kind = "Ingress"
	KindResourceQuota         Kind = "ResourceQuota"
	KindLimitRange            Kind = "LimitRange"

	KindClusterRole              Kind = "ClusterRole"
	KindClusterRoleBindings      Kind = "ClusterRoleBinding"
	KindCustomResourceDefinition Kind = "CustomResourceDefinition"
	KindNode                     Kind = "Node"
	KindClusterSbomReport        Kind = "ClusterSbomReport"
)

type LogsReader

type LogsReader interface {
	GetLogsByJobAndContainerName(ctx context.Context, job *batchv1.Job, containerName string) (io.ReadCloser, error)
	GetTerminatedContainersStatusesByJob(ctx context.Context, job *batchv1.Job) (map[string]*corev1.ContainerStateTerminated, error)
}

func NewLogsReader

func NewLogsReader(clientset kubernetes.Interface) LogsReader

type ObjectRef

type ObjectRef struct {
	Kind      Kind
	Name      string
	Namespace string
}

ObjectRef is a simplified representation of a Kubernetes client.Object. Each object has Kind, which designates the type of the entity it represents. Objects have names and many of them live in namespaces.

func ObjectRefFromKindAndObjectKey

func ObjectRefFromKindAndObjectKey(kind Kind, name client.ObjectKey) ObjectRef

func ObjectRefFromObjectMeta

func ObjectRefFromObjectMeta(objectMeta metav1.ObjectMeta) (ObjectRef, error)

type ObjectResolver

type ObjectResolver struct {
	client.Client
	CompatibleMgr
}

func NewObjectResolver added in v0.1.4

func NewObjectResolver(c client.Client, cm CompatibleMgr) ObjectResolver

func (*ObjectResolver) CronJobByJob

func (o *ObjectResolver) CronJobByJob(ctx context.Context, job *batchv1.Job) (client.Object, error)

func (*ObjectResolver) GetActivePodsMatchingLabels added in v0.2.0

func (o *ObjectResolver) GetActivePodsMatchingLabels(ctx context.Context, namespace string,
	labels map[string]string) ([]corev1.Pod, error)

func (*ObjectResolver) GetNodeName

func (o *ObjectResolver) GetNodeName(ctx context.Context, obj client.Object) (string, error)

GetNodeName returns the name of the node on which the given workload is scheduled. If there are no running pods then the ErrNoRunningPods error is returned. If there are no active ReplicaSets for the Deployment the ErrReplicaSetNotFound error is returned. If the specified workload is a CronJob the ErrUnSupportedKind error is returned.

func (*ObjectResolver) IsActiveReplicaSet

func (o *ObjectResolver) IsActiveReplicaSet(ctx context.Context, workloadObj client.Object, controller *metav1.OwnerReference) (bool, error)

func (*ObjectResolver) IsActiveReplicationController added in v0.15.0

func (o *ObjectResolver) IsActiveReplicationController(ctx context.Context, workloadObj client.Object, controller *metav1.OwnerReference) (bool, error)

func (*ObjectResolver) JobByPod

func (o *ObjectResolver) JobByPod(ctx context.Context, pod *corev1.Pod) (*batchv1.Job, error)

func (*ObjectResolver) ObjectFromObjectRef

func (o *ObjectResolver) ObjectFromObjectRef(ctx context.Context, ref ObjectRef) (client.Object, error)

func (*ObjectResolver) RelatedReplicaSetName

func (o *ObjectResolver) RelatedReplicaSetName(ctx context.Context, object ObjectRef) (string, error)

RelatedReplicaSetName attempts to find the replicaset that is associated with the given owner. If the owner is a Deployment, it will look for a ReplicaSet that is controlled by the Deployment. If the owner is a Pod, it will look for the ReplicaSet that owns the Pod.

func (*ObjectResolver) ReplicaSetByDeployment

func (o *ObjectResolver) ReplicaSetByDeployment(ctx context.Context, deployment *appsv1.Deployment) (*appsv1.ReplicaSet, error)

ReplicaSetByDeployment returns the current revision of the specified Deployment. If the current revision cannot be found the ErrReplicaSetNotFound error is returned.

func (*ObjectResolver) ReplicaSetByDeploymentRef

func (o *ObjectResolver) ReplicaSetByDeploymentRef(ctx context.Context, deploymentRef ObjectRef) (*appsv1.ReplicaSet, error)

ReplicaSetByDeploymentRef returns the current revision of the specified Deployment reference. If the current revision cannot be found the ErrReplicaSetNotFound error is returned.

func (*ObjectResolver) ReplicaSetByPod

func (o *ObjectResolver) ReplicaSetByPod(ctx context.Context, pod *corev1.Pod) (*appsv1.ReplicaSet, error)

ReplicaSetByPod returns the controller ReplicaSet of the specified Pod.

func (*ObjectResolver) ReplicaSetByPodRef

func (o *ObjectResolver) ReplicaSetByPodRef(ctx context.Context, object ObjectRef) (*appsv1.ReplicaSet, error)

ReplicaSetByPodRef returns the controller ReplicaSet of the specified Pod reference.

func (*ObjectResolver) ReportOwner

func (o *ObjectResolver) ReportOwner(ctx context.Context, obj client.Object) (client.Object, error)

ReportOwner resolves the owner of a security report for the specified object.

type Resource added in v0.3.0

type Resource struct {
	Kind       Kind
	ForObject  client.Object
	OwnsObject client.Object
}

Resource represents a Kubernetes resource Object

func (*Resource) GetWorkloadResource added in v0.3.0

func (r *Resource) GetWorkloadResource(kind string, object client.Object, resolver ObjectResolver) error

GetWorkloadResource returns a Resource object which can be used by controllers for reconciliation

type SecretsReader

type SecretsReader interface {
	ListByLocalObjectReferences(ctx context.Context, refs []corev1.LocalObjectReference, ns string) ([]corev1.Secret, error)
	ListImagePullSecretsByPodSpec(ctx context.Context, spec corev1.PodSpec, ns string) ([]corev1.Secret, error)
	CredentialsByServer(ctx context.Context, workload client.Object, secretsInfo map[string]string, multiSecretSupport bool) (map[string]docker.Auth, error)
}

SecretsReader defines methods for reading Secrets.

func NewSecretsReader

func NewSecretsReader(c client.Client) SecretsReader

NewSecretsReader constructs a new SecretsReader which is using the client package provided by the controller-runtime libraries for interacting with the Kubernetes API server.

Jump to

Keyboard shortcuts

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