kube

package
v0.0.0-...-00bc251 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2024 License: Apache-2.0 Imports: 97 Imported by: 125

Documentation

Index

Constants

View Source
const (

	// Operation constants
	Create  string = "CREATE"
	Update  string = "UPDATE"
	Delete  string = "DELETE"
	Connect string = "CONNECT"
)
View Source
const MaxRequestBodyBytes = int64(6 * 1024 * 1024)

MaxRequestBodyBytes represents the max size of Kubernetes objects we read. Kubernetes allows a 2x buffer on the max etcd size (https://github.com/kubernetes/kubernetes/blob/0afa569499d480df4977568454a50790891860f5/staging/src/k8s.io/apiserver/pkg/server/config.go#L362). We allow an additional 2x buffer, as it is still fairly cheap (6mb)

View Source
const (
	RunningStatus = "status.phase=Running"
)

Variables

View Source
var (
	IstioScheme = istioScheme()
	IstioCodec  = serializer.NewCodecFactory(IstioScheme)
)

IstioScheme returns a scheme will all known Istio-related types added

View Source
var FakeIstioScheme = func() *runtime.Scheme {
	s := istioScheme()

	s.AddKnownTypeWithName(schema.GroupVersionKind{Group: "fake-metadata-client-group", Version: "v1", Kind: "List"}, &metav1.List{})
	return s
}()

FakeIstioScheme is an IstioScheme that has List type registered.

View Source
var NewCrdWatcher func(Client) kubetypes.CrdWatcher

Functions

func AdmissionReviewAdapterToKube

func AdmissionReviewAdapterToKube(ar *AdmissionReview, apiVersion string) runtime.Object

func AllSynced

func AllSynced[T Syncer](syncers []T) bool

func BuildClientCmd

func BuildClientCmd(kubeconfig, context string, overrides ...func(*clientcmd.ConfigOverrides)) clientcmd.ClientConfig

BuildClientCmd builds a client cmd config from a kubeconfig filepath and context. It overrides the current context with the one provided (empty to use default).

This is a modified version of k8s.io/client-go/tools/clientcmd/BuildConfigFromFlags with the difference that it loads default configs if not running in-cluster.

func BuildClientConfig

func BuildClientConfig(kubeconfig, context string) (*rest.Config, error)

BuildClientConfig builds a client rest config from a kubeconfig filepath and context. It overrides the current context with the one provided (empty to use default).

This is a modified version of k8s.io/client-go/tools/clientcmd/BuildConfigFromFlags with the difference that it loads default configs if not running in-cluster.

func CheckPodReady

func CheckPodReady(pod *corev1.Pod) error

CheckPodReady returns nil if the given pod and all of its containers are ready.

func CheckPodReadyOrComplete

func CheckPodReadyOrComplete(pod *corev1.Pod) error

CheckPodReadyOrComplete returns nil if the given pod and all of its containers are ready or terminated successfully.

func CheckPodTerminal

func CheckPodTerminal(pod *corev1.Pod) bool

CheckPodTermina returns true if the pod's phase is terminal (succeeded || failed) usually used to filter cron jobs.

func ConfigLoadingRules

func ConfigLoadingRules(kubeconfig string) *clientcmd.ClientConfigLoadingRules

func DefaultRestConfig

func DefaultRestConfig(kubeconfig, configContext string, fns ...func(*rest.Config)) (*rest.Config, error)

DefaultRestConfig returns the rest.Config for the given kube config file and context.

func FindIstiodMonitoringPort

func FindIstiodMonitoringPort(pod *v1.Pod) int

func GetDeployMetaFromPod

func GetDeployMetaFromPod(pod *corev1.Pod) (types.NamespacedName, metav1.TypeMeta)

GetDeployMetaFromPod heuristically derives deployment metadata from the pod spec.

func GetVersionAsInt

func GetVersionAsInt(client Client) int

GetVersionAsInt returns the the kubernetes version as an integer. For example, on Kubernetes v1.15.2, GetVersionAsInt returns 115

func HTTPConfigReader

func HTTPConfigReader(req *http.Request) ([]byte, error)

HTTPConfigReader is reads an HTTP request, imposing size restrictions aligned with Kubernetes limits

func InClusterConfig

func InClusterConfig(fns ...func(*rest.Config)) (*rest.Config, error)

InClusterConfig returns the rest.Config for in cluster usage. Typically, DefaultRestConfig is used and this is auto detected; usage directly allows explicitly overriding to use in-cluster.

func IsAtLeastVersion

func IsAtLeastVersion(client Client, minorVersion uint) bool

IsAtLeastVersion returns true if the client is at least the specified version. For example, on Kubernetes v1.15.2, IsAtLeastVersion(13) == true, IsAtLeastVersion(17) == false

func IsKubeAtLeastOrLessThanVersion

func IsKubeAtLeastOrLessThanVersion(clusterVersion *kubeVersion.Info, minorVersion uint, atLeast bool) bool

IsKubeAtLeastOrLessThanVersion returns if the kubernetes version is at least or less than the specified version.

func IsLessThanVersion

func IsLessThanVersion(client Client, minorVersion uint) bool

IsLessThanVersion returns true if the client version is less than the specified version. For example, on Kubernetes v1.15.2, IsLessThanVersion(13) == false, IsLessThanVersion(17) == true

func IstioUserAgent

func IstioUserAgent() string

IstioUserAgent returns the user agent string based on the command being used. example: pilot-discovery/1.9.5 or istioctl/1.10.0 This is a specialized version of rest.DefaultKubernetesUserAgent()

func NewClientConfigForRestConfig

func NewClientConfigForRestConfig(restConfig *rest.Config) clientcmd.ClientConfig

NewClientConfigForRestConfig creates a new k8s clientcmd.ClientConfig from the given rest.Config.

func NewRPCCredentials

func NewRPCCredentials(kubeClient Client, tokenNamespace, tokenSA string,
	tokenAudiences []string, expirationSeconds, sunsetPeriodSeconds int64,
) (credentials.PerRPCCredentials, error)

NewRPCCredentials creates a PerRPCCredentials capable of getting tokens from Istio and tracking their expiration

func NewUntrustedRestConfig

func NewUntrustedRestConfig(kubeConfig []byte, configOverrides ...func(*rest.Config)) (*rest.Config, error)

NewUntrustedRestConfig returns the rest.Config for the given kube config context. This is suitable for access to remote clusters from untrusted kubeConfig inputs. The kubeconfig is sanitized and unsafe auth methods are denied.

func SetRestDefaults

func SetRestDefaults(config *rest.Config) *rest.Config

SetRestDefaults is a helper function that sets default values for the given rest.Config. This function is idempotent.

func SlowConvertKindsToRuntimeObjects

func SlowConvertKindsToRuntimeObjects(in []crd.IstioKind) ([]runtime.Object, error)

func SlowConvertToRuntimeObject

func SlowConvertToRuntimeObject(in *crd.IstioKind) (runtime.Object, error)

SlowConvertToRuntimeObject converts an IstioKind to a runtime.Object. As the name implies, it is not efficient.

func StripNodeUnusedFields

func StripNodeUnusedFields(obj any) (any, error)

StripNodeUnusedFields is the transform function for shared node informers, it removes unused fields from objects before they are stored in the cache to save memory.

func StripPodUnusedFields

func StripPodUnusedFields(obj any) (any, error)

StripPodUnusedFields is the transform function for shared pod informers, it removes unused fields from objects before they are stored in the cache to save memory.

func WaitForCacheSync

func WaitForCacheSync(name string, stop <-chan struct{}, cacheSyncs ...cache.InformerSynced) (r bool)

WaitForCacheSync waits until all caches are synced. This will return true only if things synced successfully before the stop channel is closed. This function also lives in the Kubernetes cache library. However, that library will poll with 100ms fixed interval. Often the cache syncs in a few ms, but we are delayed a full 100ms. This is especially apparent in tests, which previously spent most of their time just in the 100ms wait interval.

To optimize this, this function performs exponential backoff. This is generally safe because cache.InformerSynced functions are ~always quick to run. However, if the sync functions do perform expensive checks this function may not be suitable.

Types

type AdmissionRequest

type AdmissionRequest struct {
	// UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are
	// otherwise identical (parallel requests, requests when earlier requests did not modify etc)
	// The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request.
	// It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging.
	UID types.UID `json:"uid"`

	// Kind is the fully-qualified type of object being submitted (for example, v1.Pod or autoscaling.v1.Scale)
	Kind metav1.GroupVersionKind `json:"kind"`

	// Resource is the fully-qualified resource being requested (for example, v1.pods)
	Resource metav1.GroupVersionResource `json:"resource"`

	// SubResource is the subresource being requested, if any (for example, "status" or "scale")
	SubResource string `json:"subResource,omitempty"`
	// RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale).
	// If this is specified and differs from the value in "kind", an equivalent match and conversion was performed.
	//
	// For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of
	// `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`,
	// an API request to apps/v1beta1 deployments would be converted and sent to the webhook
	// with `kind: {group:"apps", version:"v1", kind:"Deployment"}` (matching the rule the webhook registered for),
	// and `requestKind: {group:"apps", version:"v1beta1", kind:"Deployment"}` (indicating the kind of the original API request).
	//
	RequestKind *metav1.GroupVersionKind `json:"requestKind,omitempty"`

	// RequestResource is the fully-qualified resource of the original API request (for example, v1.pods).
	// If this is specified and differs from the value in "resource", an equivalent match and conversion was performed.
	//
	// For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of
	// `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`,
	// an API request to apps/v1beta1 deployments would be converted and sent to the webhook
	// with `resource: {group:"apps", version:"v1", resource:"deployments"}` (matching the resource the webhook registered for),
	// and `requestResource: {group:"apps", version:"v1beta1", resource:"deployments"}` (indicating the resource of the original API request).
	//
	RequestResource *metav1.GroupVersionResource `json:"requestResource,omitempty"`

	// RequestSubResource is the name of the subresource of the original API request, if any (for example, "status" or "scale")
	// If this is specified and differs from the value in "subResource", an equivalent match and conversion was performed.
	RequestSubResource string `json:"requestSubResource,omitempty"`

	// UserInfo is information about the requesting user
	UserInfo authenticationv1.UserInfo `json:"userInfo"`

	// Name is the name of the object as presented in the request.  On a CREATE operation, the client may omit name and
	// rely on the server to generate the name.  If that is the case, this field will contain an empty string.
	Name string `json:"name,omitempty"`

	// Namespace is the namespace associated with the request (if any).
	Namespace string `json:"namespace,omitempty"`

	// Operation is the operation being performed. This may be different than the operation
	// requested. e.g. a patch can result in either a CREATE or UPDATE Operation.
	Operation string `json:"operation"`

	// Object is the object from the incoming request.
	Object runtime.RawExtension `json:"object,omitempty"`

	// OldObject is the existing object. Only populated for DELETE and UPDATE requests.
	OldObject runtime.RawExtension `json:"oldObject,omitempty"`

	// DryRun indicates that modifications will definitely not be persisted for this request.
	// Defaults to false.
	DryRun *bool `json:"dryRun,omitempty"`

	// Options is the operation option structure of the operation being performed.
	// e.g. `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This may be
	// different than the options the caller provided. e.g. for a patch request the performed
	// Operation might be a CREATE, in which case the Options will a
	// `meta.k8s.io/v1.CreateOptions` even though the caller provided `meta.k8s.io/v1.PatchOptions`.
	Options runtime.RawExtension `json:"options,omitempty"`
}

AdmissionRequest describes the admission.Attributes for the admission request.

type AdmissionResponse

type AdmissionResponse struct {
	// UID is an identifier for the individual request/response.
	// This should be copied over from the corresponding AdmissionRequest.
	UID types.UID `json:"uid"`

	// Allowed indicates whether or not the admission request was permitted.
	Allowed bool `json:"allowed"`

	// Result contains extra details into why an admission request was denied.
	// This field IS NOT consulted in any way if "Allowed" is "true".
	Result *metav1.Status `json:"status,omitempty"`

	// The patch body. Currently we only support "JSONPatch" which implements RFC 6902.
	Patch []byte `json:"patch,omitempty"`

	// The type of Patch. Currently we only allow "JSONPatch".
	PatchType *string `json:"patchType,omitempty"`

	// AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted).
	// MutatingAdmissionWebhook and ValidatingAdmissionWebhook admission controller will prefix the keys with
	// admission webhook name (e.g. imagepolicy.example.com/error=image-blacklisted). AuditAnnotations will be provided by
	// the admission webhook to add additional context to the audit log for this request.
	AuditAnnotations map[string]string `json:"auditAnnotations,omitempty"`

	// warnings is a list of warning messages to return to the requesting API client.
	// Warning messages describe a problem the client making the API request should correct or be aware of.
	// Limit warnings to 120 characters if possible.
	// Warnings over 256 characters and large numbers of warnings may be truncated.
	Warnings []string `json:"warnings,omitempty"`
}

AdmissionResponse describes an admission response.

type AdmissionReview

type AdmissionReview struct {
	// TypeMeta describes an individual object in an API response or request
	// with strings representing the type of the object and its API schema version.
	// Structures that are versioned or persisted should inline TypeMeta.
	metav1.TypeMeta

	// Request describes the attributes for the admission request.
	Request *AdmissionRequest `json:"request,omitempty"`

	// Response describes the attributes for the admission response.
	Response *AdmissionResponse `json:"response,omitempty"`
}

AdmissionReview describes an admission review request/response.

func AdmissionReviewKubeToAdapter

func AdmissionReviewKubeToAdapter(object runtime.Object) (*AdmissionReview, error)

type CLIClient

type CLIClient interface {
	Client
	// Revision of the Istio control plane.
	Revision() string

	// EnvoyDo makes a http request to the Envoy in the specified pod.
	EnvoyDo(ctx context.Context, podName, podNamespace, method, path string) ([]byte, error)

	// EnvoyDoWithPort makes a http request to the Envoy in the specified pod and port.
	EnvoyDoWithPort(ctx context.Context, podName, podNamespace, method, path string, port int) ([]byte, error)

	// AllDiscoveryDo makes a http request to each Istio discovery instance.
	AllDiscoveryDo(ctx context.Context, namespace, path string) (map[string][]byte, error)

	// GetIstioVersions gets the version for each Istio control plane component.
	GetIstioVersions(ctx context.Context, namespace string) (*version.MeshInfo, error)

	// PodsForSelector finds pods matching selector.
	PodsForSelector(ctx context.Context, namespace string, labelSelectors ...string) (*v1.PodList, error)

	// GetIstioPods retrieves the pod objects for Istio deployments
	GetIstioPods(ctx context.Context, namespace string, opts metav1.ListOptions) ([]v1.Pod, error)

	// GetProxyPods retrieves all the proxy pod objects: sidecar injected pods and gateway pods.
	GetProxyPods(ctx context.Context, limit int64, token string) (*v1.PodList, error)

	// PodExecCommands takes a list of commands and the pod data to run the commands in the specified pod.
	PodExecCommands(podName, podNamespace, container string, commands []string) (stdout string, stderr string, err error)

	// PodExec takes a command and the pod data to run the command in the specified pod.
	PodExec(podName, podNamespace, container string, command string) (stdout string, stderr string, err error)

	// PodLogs retrieves the logs for the given pod.
	PodLogs(ctx context.Context, podName string, podNamespace string, container string, previousLog bool) (string, error)

	// NewPortForwarder creates a new PortForwarder configured for the given pod. If localPort=0, a port will be
	// dynamically selected. If localAddress is empty, "localhost" is used.
	NewPortForwarder(podName string, ns string, localAddress string, localPort int, podPort int) (PortForwarder, error)

	// ApplyYAMLFiles applies the resources in the given YAML files.
	ApplyYAMLFiles(namespace string, yamlFiles ...string) error

	// ApplyYAMLContents applies the resources in the given YAML strings.
	ApplyYAMLContents(namespace string, yamls ...string) error

	// ApplyYAMLFilesDryRun performs a dry run for applying the resource in the given YAML files
	ApplyYAMLFilesDryRun(namespace string, yamlFiles ...string) error

	// DeleteYAMLFiles deletes the resources in the given YAML files.
	DeleteYAMLFiles(namespace string, yamlFiles ...string) error

	// DeleteYAMLFilesDryRun performs a dry run for deleting the resources in the given YAML files.
	DeleteYAMLFilesDryRun(namespace string, yamlFiles ...string) error

	// CreatePerRPCCredentials creates a gRPC bearer token provider that can create (and renew!) Istio tokens
	CreatePerRPCCredentials(ctx context.Context, tokenNamespace, tokenServiceAccount string, audiences []string,
		expirationSeconds int64) (credentials.PerRPCCredentials, error)

	// UtilFactory returns a kubectl factory
	UtilFactory() PartialFactory

	// InvalidateDiscovery invalidates the discovery client, useful after manually changing CRD's
	InvalidateDiscovery()

	// DynamicClientFor builds a dynamic client to a resource
	DynamicClientFor(gvk schema.GroupVersionKind, obj *unstructured.Unstructured, namespace string) (dynamic.ResourceInterface, error)
}

CLIClient is an extended client with additional helpers/functionality for Istioctl and testing. CLIClient is not appropriate for controllers, as it does a number of highly privileged or highly risky operations such as `exec`, `port-forward`, etc.

func NewCLIClient

func NewCLIClient(clientConfig clientcmd.ClientConfig, opts ...ClientOption) (CLIClient, error)

NewCLIClient creates a Kubernetes client from the given ClientConfig. The "revision" parameter controls the behavior of GetIstioPods, by selecting a specific revision of the control plane. This is appropriate for use in CLI libraries because it exposes functionality unsafe for in-cluster controllers, and uses standard CLI (kubectl) caching.

func NewFakeClient

func NewFakeClient(objects ...runtime.Object) CLIClient

NewFakeClient creates a new, fake, client

func NewFakeClientWithVersion

func NewFakeClientWithVersion(minor string, objects ...runtime.Object) CLIClient

func SetRevisionForTest

func SetRevisionForTest(c CLIClient, rev string) CLIClient

type Client

type Client interface {
	// RESTConfig returns the Kubernetes rest.Config used to configure the clients.
	RESTConfig() *rest.Config

	// Ext returns the API extensions client.
	Ext() kubeExtClient.Interface

	// Kube returns the core kube client
	Kube() kubernetes.Interface

	// Dynamic client.
	Dynamic() dynamic.Interface

	// Metadata returns the Metadata kube client.
	Metadata() metadata.Interface

	// Istio returns the Istio kube client.
	Istio() istioclient.Interface

	// GatewayAPI returns the gateway-api kube client.
	GatewayAPI() gatewayapiclient.Interface

	// Informers returns an informer factory
	Informers() informerfactory.InformerFactory

	// CrdWatcher returns the CRD watcher for this client
	CrdWatcher() kubetypes.CrdWatcher

	// ObjectFilter returns an object filter that can be used to filter out unwanted objects based on configuration.
	// This must be set on a client with SetObjectFilter.
	ObjectFilter() kubetypes.DynamicObjectFilter

	// RunAndWait starts all informers and waits for their caches to sync.
	// Warning: this must be called AFTER .Informer() is called, which will register the informer.
	// "false" is returned if this prematurely exited without syncing.
	RunAndWait(stop <-chan struct{}) bool

	// WaitForCacheSync waits for all cache functions to sync, as well as all informers started by the *fake* client.
	WaitForCacheSync(name string, stop <-chan struct{}, cacheSyncs ...cache.InformerSynced) bool

	// GetKubernetesVersion returns the Kubernetes server version
	GetKubernetesVersion() (*kubeVersion.Info, error)

	// Shutdown closes all informers and waits for them to terminate
	Shutdown()

	// ClusterID returns the cluster this client is connected to
	ClusterID() cluster.ID
}

Client is a helper for common Kubernetes client operations. This contains various different kubernetes clients using a shared config. It is expected that all of Istiod can share the same set of clients and informers. Sharing informers is especially important for load on the API server/Istiod itself.

func EnableCrdWatcher

func EnableCrdWatcher(c Client) Client

EnableCrdWatcher enables the CRD watcher on the client.

func NewClient

func NewClient(clientConfig clientcmd.ClientConfig, cluster cluster.ID) (Client, error)

NewClient creates a Kubernetes client from the given rest config.

func SetObjectFilter

func SetObjectFilter(c Client, filter kubetypes.DynamicObjectFilter) Client

SetObjectFilter adds an object filter to the client, which can later be returned with client.ObjectFilter()

type ClientOption

type ClientOption func(CLIClient) CLIClient

ClientOption defines an option for configuring the CLIClient.

func WithCluster

func WithCluster(id cluster.ID) ClientOption

WithCluster creates a ClientOption to set the cluster ID on the CLIClient.

func WithRevision

func WithRevision(revision string) ClientOption

WithRevision creates a ClientOption to set the revision on the CLIClient.

type PartialFactory

type PartialFactory interface {

	// DynamicClient returns a dynamic client ready for use
	DynamicClient() (dynamic.Interface, error)

	// KubernetesClientSet gives you back an external clientset
	KubernetesClientSet() (*kubernetes.Clientset, error)

	// Returns a RESTClient for accessing Kubernetes resources or an error.
	RESTClient() (*rest.RESTClient, error)
	// contains filtered or unexported methods
}

type PortForwarder

type PortForwarder interface {
	// Start runs this forwarder.
	Start() error

	// Address returns the local forwarded address. Only valid while the forwarder is running.
	Address() string

	// Close this forwarder and release an resources.
	Close()

	// ErrChan returns a channel that returns an error when one is encountered. While Start() may return an initial error,
	// the port-forward connection may be lost at anytime. The ErrChan can be read to determine if/when the port-forwarding terminates.
	// This can return nil if the port forwarding stops gracefully.
	ErrChan() <-chan error

	// WaitForStop blocks until connection closed (e.g. control-C interrupt)
	WaitForStop()
}

PortForwarder manages the forwarding of a single port.

type PortManager

type PortManager func() (uint16, error)

type Syncer

type Syncer interface {
	HasSynced() bool
}

Directories

Path Synopsis
Package apimirror contains copies of Kubernetes APIs.
Package apimirror contains copies of Kubernetes APIs.
Package informerfactory provides a "factory" to generate informers.
Package informerfactory provides a "factory" to generate informers.
Package inject implements kube-inject or webhoook autoinject feature to inject sidecar.
Package inject implements kube-inject or webhoook autoinject feature to inject sidecar.
krt
Package labels provides utility methods for retrieving Istio-specific labels from Kubernetes resources.
Package labels provides utility methods for retrieving Istio-specific labels from Kubernetes resources.
watcher

Jump to

Keyboard shortcuts

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