inject

package
v0.0.0-...-7929486 Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2024 License: Apache-2.0 Imports: 73 Imported by: 12

Documentation

Overview

Package inject implements kube-inject or webhoook autoinject feature to inject sidecar. This file is focused on rewriting Kubernetes app probers to support mutual TLS.

Index

Constants

View Source
const (
	// ProxyContainerName is used by e2e integration tests for fetching logs
	ProxyContainerName = "istio-proxy"

	// ValidationContainerName is the name of the init container that validates
	// if CNI has made the necessary changes to iptables
	ValidationContainerName = "istio-validation"

	// InitContainerName is the name of the init container that deploys iptables
	InitContainerName = "istio-init"

	// EnableCoreDumpName is the name of the init container that allows core dumps
	EnableCoreDumpName = "enable-core-dump"
)
View Source
const (
	// ImageTypeDebug is the suffix of the debug image.
	ImageTypeDebug = "debug"
	// ImageTypeDistroless is the suffix of the distroless image.
	ImageTypeDistroless = "distroless"
	// ImageTypeDefault is the type name of the default image, sufix is elided.
	ImageTypeDefault = "default"
)
View Source
const (
	// InitContainers is the name of the property in k8s pod spec
	InitContainers = "initContainers"

	// Containers is the name of the property in k8s pod spec
	Containers = "containers"
)
View Source
const (
	// AutoImage is the special image name to indicate to the injector that we should use the injected image, and NOT override it
	// This is necessary because image is a required field on container, so if a user defines an istio-proxy container
	// with customizations they must set an image.
	AutoImage = "auto"
)
View Source
const (
	SidecarTemplateName = "sidecar"
)

Variables

View Source
var (
	ErrBlockSlashBadFormat = fmt.Errorf("block not in the format \"<start>/<size>\"")
	ErrBlockDashBadFormat  = fmt.Errorf("block not in the format \"<start>-<end>\"")
)

per-sidecar policy and status

IgnoredNamespaces contains the system namespaces referenced from Kubernetes: Ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/#viewing-namespaces "kube-system": The namespace for objects created by the Kubernetes system. "kube-public": This namespace is mostly reserved for cluster usage. "kube-node-lease": This namespace for the lease objects associated with each node which improves the performance of the node heartbeats as the cluster scales. "local-path-storage": Dynamically provisioning persistent local storage with Kubernetes.

used with Kind cluster: https://github.com/rancher/local-path-provisioner
View Source
var InjectionFuncmap = createInjectionFuncmap()

KnownImageTypes are image types that istio pubishes.

View Source
var (
	URLParameterToEnv = map[string]string{
		"cluster": "ISTIO_META_CLUSTER_ID",
		"net":     "ISTIO_META_NETWORK",
	}
)

Functions

func DumpAppProbers

func DumpAppProbers(pod *corev1.Pod, targetPort int32) string

DumpAppProbers returns a json encoded string as `status.KubeAppProbers`. Also update the probers so that all usages of named port will be resolved to integer.

func FindContainer

func FindContainer(name string, containers []corev1.Container) *corev1.Container

FindContainer returns the pointer to the first container whose name matches.

func FindContainerFromPod

func FindContainerFromPod(name string, pod *corev1.Pod) *corev1.Container

FindContainerFromPod returns the pointer to the first container whose name matches in init containers or regular containers

func FindSidecar

func FindSidecar(pod *corev1.Pod) *corev1.Container

FindSidecar returns the pointer to the first container whose name matches the "istio-proxy".

func FromRawToObject

func FromRawToObject(raw []byte) (runtime.Object, error)

FromRawToObject is used to convert from raw to the runtime object

func GetProxyIDs

func GetProxyIDs(namespace *corev1.Namespace) (uid int64, gid int64)

GetProxyIDs returns the UID and GID to be used in the RunAsUser and RunAsGroup fields in the template Inspects the namespace metadata for hints and fallbacks to the usual value of 1337.

func InboundTrafficPolicyMode

func InboundTrafficPolicyMode(meshConfig *meshconfig.MeshConfig) string

func IntoObject

func IntoObject(injector Injector, sidecarTemplate Templates, valuesConfig ValuesConfig,
	revision string, meshconfig *meshconfig.MeshConfig, in runtime.Object, warningHandler func(string),
) (any, error)

IntoObject convert the incoming resources into Injected resources nolint: lll

func IntoResourceFile

func IntoResourceFile(injector Injector, sidecarTemplate Templates,
	valuesConfig ValuesConfig, revision string, meshconfig *meshconfig.MeshConfig, in io.Reader, out io.Writer, warningHandler func(string),
) error

IntoResourceFile injects the istio proxy into the specified kubernetes YAML file. nolint: lll

func ProxyImage

func ProxyImage(values *opconfig.Values, image *proxyConfig.ProxyImage, annotations map[string]string) string

ProxyImage constructs image url in a backwards compatible way. values based name => {{ .Values.global.hub }}/{{ .Values.global.proxy.image }}:{{ .Values.global.tag }}

func RunTemplate

func RunTemplate(params InjectionParameters) (mergedPod *corev1.Pod, templatePod *corev1.Pod, err error)

RunTemplate renders the sidecar template Returns the raw string template, as well as the parse pod form

func ShouldRewriteAppHTTPProbers

func ShouldRewriteAppHTTPProbers(annotations map[string]string, specSetting bool) bool

ShouldRewriteAppHTTPProbers returns if we should rewrite apps' probers config.

func StrategicMergePatchYAML

func StrategicMergePatchYAML(originalJSON []byte, patchYAML []byte, dataStruct any) ([]byte, error)

StrategicMergePatchYAML is a small fork of strategicpatch.StrategicMergePatch to allow YAML patches This avoids expensive conversion from YAML to JSON

func ValidateExcludeIPRanges

func ValidateExcludeIPRanges(ipRanges string) error

ValidateExcludeIPRanges validates the excludeIPRanges parameter

func ValidateExcludeInboundPorts

func ValidateExcludeInboundPorts(ports string) error

ValidateExcludeInboundPorts validates the excludeInboundPorts parameter

func ValidateExcludeOutboundPorts

func ValidateExcludeOutboundPorts(ports string) error

ValidateExcludeOutboundPorts validates the excludeOutboundPorts parameter

func ValidateIncludeIPRanges

func ValidateIncludeIPRanges(ipRanges string) error

ValidateIncludeIPRanges validates the includeIPRanges parameter

func ValidateIncludeInboundPorts

func ValidateIncludeInboundPorts(ports string) error

ValidateIncludeInboundPorts validates the includeInboundPorts parameter

Types

type Block

type Block struct {
	Start uint32
	End   uint32
}

func ParseBlock

func ParseBlock(in string) (Block, error)

func (Block) RangeString

func (b Block) RangeString() string

func (Block) Size

func (b Block) Size() uint32

func (Block) String

func (b Block) String() string

type Config

type Config struct {
	Policy InjectionPolicy `json:"policy"`

	// DefaultTemplates defines the default template to use for pods that do not explicitly specify a template
	DefaultTemplates []string `json:"defaultTemplates"`

	// RawTemplates defines a set of templates to be used. The specified template will be run, provided with
	// SidecarTemplateData, and merged with the original pod spec using a strategic merge patch.
	RawTemplates RawTemplates `json:"templates"`

	// Aliases defines a translation of a name to inject template. For example, `sidecar: [proxy,init]` could allow
	// referencing two templates, "proxy" and "init" by a single name, "sidecar".
	// Expansion is not recursive.
	Aliases map[string][]string `json:"aliases"`

	// NeverInjectSelector: Refuses the injection on pods whose labels match this selector.
	// It's an array of label selectors, that will be OR'ed, meaning we will iterate
	// over it and stop at the first match
	// Takes precedence over AlwaysInjectSelector.
	NeverInjectSelector []metav1.LabelSelector `json:"neverInjectSelector"`

	// AlwaysInjectSelector: Forces the injection on pods whose labels match this selector.
	// It's an array of label selectors, that will be OR'ed, meaning we will iterate
	// over it and stop at the first match
	AlwaysInjectSelector []metav1.LabelSelector `json:"alwaysInjectSelector"`

	// InjectedAnnotations are additional annotations that will be added to the pod spec after injection
	// This is primarily to support PSP annotations.
	InjectedAnnotations map[string]string `json:"injectedAnnotations"`

	// Templates is a pre-parsed copy of RawTemplates
	Templates Templates `json:"-"`
}

Config specifies the sidecar injection configuration This includes the sidecar template and cluster-side injection policy. It is used by kube-inject, sidecar injector, and http endpoint.

func UnmarshalConfig

func UnmarshalConfig(yml []byte) (Config, error)

UnmarshalConfig unmarshals the provided YAML configuration, while normalizing the resulting configuration

type ContainerReorder

type ContainerReorder int
const (
	MoveFirst ContainerReorder = iota
	MoveLast
	Remove
)

type InjectionParameters

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

type InjectionPolicy

type InjectionPolicy string

InjectionPolicy determines the policy for injecting the sidecar proxy into the watched namespace(s).

const (
	// InjectionPolicyDisabled specifies that the sidecar injector
	// will not inject the sidecar into resources by default for the
	// namespace(s) being watched. Resources can enable injection
	// using the "sidecar.istio.io/inject" annotation with value of
	// true.
	InjectionPolicyDisabled InjectionPolicy = "disabled"

	// InjectionPolicyEnabled specifies that the sidecar injector will
	// inject the sidecar into resources by default for the
	// namespace(s) being watched. Resources can disable injection
	// using the "sidecar.istio.io/inject" annotation with value of
	// false.
	InjectionPolicyEnabled InjectionPolicy = "enabled"
)

type Injector

type Injector interface {
	Inject(pod *corev1.Pod, namespace string) ([]byte, error)
}

type KubeAppProbers

type KubeAppProbers map[string]*Prober

type ParsedContainers

type ParsedContainers struct {
	Containers     []corev1.Container `json:"containers,omitempty"`
	InitContainers []corev1.Container `json:"initContainers,omitempty"`
}

ParsedContainers holds the unmarshalled containers and initContainers

func (ParsedContainers) AllContainers

func (p ParsedContainers) AllContainers() []corev1.Container

type Prober

type Prober struct {
	HTTPGet        *corev1.HTTPGetAction   `json:"httpGet,omitempty"`
	TCPSocket      *corev1.TCPSocketAction `json:"tcpSocket,omitempty"`
	GRPC           *corev1.GRPCAction      `json:"grpc,omitempty"`
	TimeoutSeconds int32                   `json:"timeoutSeconds,omitempty"`
}

Prober represents a single container prober

type RawTemplates

type RawTemplates map[string]string

type SidecarInjectionStatus

type SidecarInjectionStatus struct {
	InitContainers   []string `json:"initContainers"`
	Containers       []string `json:"containers"`
	Volumes          []string `json:"volumes"`
	ImagePullSecrets []string `json:"imagePullSecrets"`
	Revision         string   `json:"revision"`
}

SidecarInjectionStatus contains basic information about the injected sidecar. This includes the names of added containers and volumes.

type SidecarTemplateData

type SidecarTemplateData struct {
	TypeMeta                 metav1.TypeMeta
	DeploymentMeta           types.NamespacedName
	ObjectMeta               metav1.ObjectMeta
	Spec                     corev1.PodSpec
	ProxyConfig              *meshconfig.ProxyConfig
	MeshConfig               *meshconfig.MeshConfig
	Values                   map[string]any
	Revision                 string
	ProxyImage               string
	ProxyUID                 int64
	ProxyGID                 int64
	InboundTrafficPolicyMode string
	CompliancePolicy         string
}

SidecarTemplateData is the data object to which the templated version of `SidecarInjectionSpec` is applied.

type Template

type Template *corev1.Pod

type Templates

type Templates map[string]*template.Template

func ParseTemplates

func ParseTemplates(tmpls RawTemplates) (Templates, error)

type ValuesConfig

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

func NewValuesConfig

func NewValuesConfig(v string) (ValuesConfig, error)

func (ValuesConfig) Map

func (v ValuesConfig) Map() map[string]any

func (ValuesConfig) Struct

func (v ValuesConfig) Struct() *opconfig.Values

type Watcher

type Watcher interface {
	// SetHandler sets the handler that is run when the config changes.
	// Must call this before Run.
	SetHandler(func(*Config, string) error)

	// Run starts the Watcher. Must call this after SetHandler.
	Run(<-chan struct{})

	// Get returns the sidecar and values configuration.
	Get() (*Config, string, error)
}

Watcher watches for and reacts to injection config updates.

func NewConfigMapWatcher

func NewConfigMapWatcher(client kube.Client, namespace, name, configKey, valuesKey string) Watcher

NewConfigMapWatcher creates a new Watcher for changes to the given ConfigMap.

func NewFileWatcher

func NewFileWatcher(configFile, valuesFile string) (Watcher, error)

NewFileWatcher creates a Watcher for local config and values files.

type WatcherMulticast

type WatcherMulticast struct {
	Get func() WebhookConfig
	// contains filtered or unexported fields
}

WatcherMulticast allows multiple event handlers to register for the same watcher, simplifying injector based controllers.

func NewMulticast

func NewMulticast(impl Watcher, getter func() WebhookConfig) *WatcherMulticast

func (*WatcherMulticast) AddHandler

func (wm *WatcherMulticast) AddHandler(handler func(*Config, string) error)

SetHandler sets the handler that is run when the config changes. Must call this before Run.

type Webhook

type Webhook struct {
	Config *Config

	MultiCast *WatcherMulticast
	// contains filtered or unexported fields
}

Webhook implements a mutating webhook for automatic proxy injection.

func NewWebhook

func NewWebhook(p WebhookParameters) (*Webhook, error)

NewWebhook creates a new instance of a mutating webhook for automatic sidecar injection.

func (*Webhook) GetConfig

func (wh *Webhook) GetConfig() WebhookConfig

func (*Webhook) Run

func (wh *Webhook) Run(stop <-chan struct{})

Run implements the webhook server

type WebhookConfig

type WebhookConfig struct {
	Templates  Templates
	Values     ValuesConfig
	MeshConfig *meshconfig.MeshConfig
}

type WebhookParameters

type WebhookParameters struct {
	// Watcher watches the sidecar injection configuration.
	Watcher Watcher

	// Port is the webhook port, e.g. typically 443 for https.
	// This is mainly used for tests. Webhook runs on the port started by Istiod.
	Port int

	Env *model.Environment

	// Use an existing mux instead of creating our own.
	Mux *http.ServeMux

	// The istio.io/rev this injector is responsible for
	Revision string

	// MultiCluster is used to access namespaces across clusters
	MultiCluster multicluster.ComponentBuilder
}

WebhookParameters configures parameters for the sidecar injection webhook.

Jump to

Keyboard shortcuts

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