kube

package
v1.0.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2023 License: Apache-2.0 Imports: 98 Imported by: 0

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)

Variables

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 IstioScheme = istioScheme()

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

Functions

func AdmissionReviewAdapterToKube

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

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 *kubeApiCore.Pod) error

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

func CheckPodReadyOrComplete

func CheckPodReadyOrComplete(pod *kubeApiCore.Pod) error

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

func CreateClientset

func CreateClientset(kubeconfig, context string, fns ...func(*rest.Config)) (*kubernetes.Clientset, error)

CreateClientset is a helper function that builds a kubernetes Clienset from a kubeconfig filepath. See `BuildClientConfig` for kubeconfig loading rules.

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 GetDeployMetaFromPod

func GetDeployMetaFromPod(pod *kubeApiCore.Pod) (metav1.ObjectMeta, metav1.TypeMeta)

GetDeployMetaFromPod heuristically derives deployment metadata from the pod spec.

func HTTPConfigReader

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

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

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

func WaitForCacheSyncInterval(stopCh <-chan struct{}, interval time.Duration, cacheSyncs ...cache.InformerSynced) bool

WaitForCacheSyncInterval waits for caches to populate, with explicitly configured interval

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 Client

type Client interface {
	// TODO: stop embedding this, it will conflict with future additions. Use Kube() instead is preferred
	kubernetes.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

	// KubeInformer returns an informer for core kube client
	KubeInformer() informers.SharedInformerFactory

	// DynamicInformer returns an informer for dynamic client
	DynamicInformer() dynamicinformer.DynamicSharedInformerFactory

	// MetadataInformer returns an informer for metadata client
	MetadataInformer() metadatainformer.SharedInformerFactory

	// IstioInformer returns an informer for the istio client
	IstioInformer() istioinformer.SharedInformerFactory

	// GatewayAPIInformer returns an informer for the gateway-api client
	GatewayAPIInformer() gatewayapiinformer.SharedInformerFactory

	// ExtInformer returns an informer for the extension client
	ExtInformer() kubeExtInformers.SharedInformerFactory

	// 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.
	RunAndWait(stop <-chan struct{})

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

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 NewClient

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

NewClient creates a Kubernetes client from the given rest config.

type ExtendedClient

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

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

	// EnvoyDoWithPort makes an 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 an 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, params map[string]string) ([]v1.Pod, 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

	// 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() util.Factory
}

ExtendedClient is an extended client with additional helpers/functionality for Istioctl and testing.

func NewDefaultClient

func NewDefaultClient() (ExtendedClient, error)

NewDefaultClient returns a default client, using standard Kubernetes config resolution to determine the cluster to access.

func NewExtendedClient

func NewExtendedClient(clientConfig clientcmd.ClientConfig, revision string) (ExtendedClient, error)

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

func NewFakeClient

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

NewFakeClient creates a new, fake, client

func NewFakeClientWithVersion

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

type MockClient

type MockClient struct {
	kubernetes.Interface
	RestClient *rest.RESTClient
	// Results is a map of podName to the results of the expected test on the pod
	Results           map[string][]byte
	DiscoverablePods  map[string]map[string]*v1.PodList
	RevisionValue     string
	ConfigValue       *rest.Config
	IstioVersions     *version.MeshInfo
	KubernetesVersion uint
	IstiodVersion     string
}

MockClient for tests that rely on kube.Client.

func (MockClient) AllDiscoveryDo

func (c MockClient) AllDiscoveryDo(_ context.Context, _, _ string) (map[string][]byte, error)

func (MockClient) ApplyYAMLFiles

func (c MockClient) ApplyYAMLFiles(string, ...string) error

func (MockClient) ApplyYAMLFilesDryRun

func (c MockClient) ApplyYAMLFilesDryRun(string, ...string) error

func (MockClient) CreatePerRPCCredentials

func (c MockClient) CreatePerRPCCredentials(ctx context.Context, tokenNamespace, tokenServiceAccount string, audiences []string,
	expirationSeconds int64) (credentials.PerRPCCredentials, error)

CreatePerRPCCredentials -- when implemented -- mocks per-RPC credentials (bearer token)

func (MockClient) DeleteYAMLFiles

func (c MockClient) DeleteYAMLFiles(string, ...string) error

func (MockClient) DeleteYAMLFilesDryRun

func (c MockClient) DeleteYAMLFilesDryRun(string, ...string) error

func (MockClient) Dynamic

func (c MockClient) Dynamic() dynamic.Interface

func (MockClient) DynamicClient

func (c MockClient) DynamicClient() dynamic.Interface

func (MockClient) DynamicInformer

func (MockClient) EnvoyDo

func (c MockClient) EnvoyDo(ctx context.Context, podName, podNamespace, method, path string) ([]byte, error)

func (MockClient) EnvoyDoWithPort

func (c MockClient) EnvoyDoWithPort(ctx context.Context, podName, podNamespace, method, path string, port int) ([]byte, error)

func (MockClient) Ext

func (c MockClient) Ext() clientset.Interface

func (MockClient) ExtInformer

func (MockClient) GatewayAPI

func (c MockClient) GatewayAPI() serviceapisclient.Interface

func (MockClient) GatewayAPIInformer

func (c MockClient) GatewayAPIInformer() serviceapisinformer.SharedInformerFactory

func (MockClient) GetIstioPods

func (c MockClient) GetIstioPods(_ context.Context, _ string, _ map[string]string) ([]v1.Pod, error)

func (MockClient) GetIstioVersions

func (c MockClient) GetIstioVersions(_ context.Context, _ string) (*version.MeshInfo, error)

func (MockClient) GetKubernetesVersion

func (c MockClient) GetKubernetesVersion() (*kubeVersion.Info, error)

func (MockClient) Istio

func (c MockClient) Istio() istioclient.Interface

func (MockClient) IstioInformer

func (MockClient) Kube

func (c MockClient) Kube() kubernetes.Interface

func (MockClient) KubeInformer

func (c MockClient) KubeInformer() informers.SharedInformerFactory

func (MockClient) MCSApis

func (c MockClient) MCSApis() mcsapisclient.Interface

func (MockClient) MCSApisInformer

func (c MockClient) MCSApisInformer() mcsapisinformer.SharedInformerFactory

func (MockClient) Metadata

func (c MockClient) Metadata() metadata.Interface

func (MockClient) MetadataClient

func (c MockClient) MetadataClient() metadata.Interface

func (MockClient) MetadataInformer

func (c MockClient) MetadataInformer() metadatainformer.SharedInformerFactory

func (MockClient) NewPortForwarder

func (c MockClient) NewPortForwarder(_, _, _ string, _, _ int) (PortForwarder, error)

func (MockClient) PodExec

func (c MockClient) PodExec(_, _, _ string, _ string) (string, string, error)

func (MockClient) PodExecCommands

func (c MockClient) PodExecCommands(podName, podNamespace, container string, commands []string) (stdout string, stderr string, err error)

func (MockClient) PodLogs

func (c MockClient) PodLogs(_ context.Context, _ string, _ string, _ string, _ bool) (string, error)

func (MockClient) PodsForSelector

func (c MockClient) PodsForSelector(_ context.Context, namespace string, labelSelectors ...string) (*v1.PodList, error)

func (MockClient) REST

func (c MockClient) REST() rest.Interface

func (MockClient) RESTConfig

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

func (MockClient) Revision

func (c MockClient) Revision() string

func (MockClient) RunAndWait

func (c MockClient) RunAndWait(stop <-chan struct{})

func (MockClient) UtilFactory

func (c MockClient) UtilFactory() util.Factory

UtilFactory mock's kubectl's utility factory. This code sets up a fake factory, similar to the one in https://github.com/kubernetes/kubectl/blob/master/pkg/cmd/describe/describe_test.go

type MockPortForwarder

type MockPortForwarder struct{}

func (MockPortForwarder) Address

func (m MockPortForwarder) Address() string

func (MockPortForwarder) Close

func (m MockPortForwarder) Close()

func (MockPortForwarder) Start

func (m MockPortForwarder) Start() error

func (MockPortForwarder) WaitForStop

func (m MockPortForwarder) WaitForStop()

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

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

PortForwarder manages the forwarding of a single port.

Directories

Path Synopsis
Package apimirror contains copies of Kubernetes APIs.
Package apimirror contains copies of Kubernetes APIs.
Package inject implements kube-inject or webhoook autoinject feature to inject sidecar.
Package inject implements kube-inject or webhoook autoinject feature to inject sidecar.
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.

Jump to

Keyboard shortcuts

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