Help us shape the future of Go! Take the 2026 Go Developer Survey

k8s

package
v0.51.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 67 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultWaitingTimeout     = 120 * time.Second
	DefaultErrorWindowTimeout = 2 * time.Second
)
View Source
const (
	KubernetesDeployerName = deployers.Kubernetes

	DefaultLivenessEndpoint  = "/health/liveness"
	DefaultReadinessEndpoint = "/health/readiness"
	DefaultHTTPPort          = 8080

	// KafkaSidecarName is the name of the injected Kafka runtime container.
	// Exported so the keda deployer can target it when wiring the KEDA
	// TriggerAuthentication at the env vars this sidecar carries.
	KafkaSidecarName = "kafka-runtime"

	// RouteHostnameAnnotation records the externally-exposed hostname (if
	// any) on the function's Service, so lister/describer can read it back
	// without re-deriving or re-querying the Route.
	RouteHostnameAnnotation = "function.knative.dev/route-hostname"

	// RouteNamespaceAnnotation records where the exposing Route was created,
	// written by the code that created it; removal reads it. It exists because
	// keda's Route lives with the interceptor, whose namespace depends on how
	// keda was installed.
	//
	// Written and cleared together with RouteHostnameAnnotation.
	RouteNamespaceAnnotation = "function.knative.dev/route-namespace"
)

Variables

View Source
var DefaultKafkaRuntimeImage = "gcr.io/knative-releases/knative.dev/func-adapter-kafka/cmd/fkafka-runtime:v0.1.0"

DefaultKafkaRuntimeImage is the image injected as the Kafka runtime sidecar. It consumes from Kafka and delivers each record to the function over localhost HTTP, so the function needs no Kafka client. Override with the FUNC_KAFKA_RUNTIME_IMAGE environment variable or at build time with ldflags.

This points at the released image published from the func-adapter-kafka release-0.1 branch. The runtime is versioned on its own line like the other func middleware (func-go, func-python), independent of func and the knative release train. Pin a different version or fall back to the nightly build via FUNC_KAFKA_RUNTIME_IMAGE.

View Source
var ErrNoMatchingPods = errors.New("no pods with readable logs matched")

ErrNoMatchingPods is returned when no pod whose logs can be read matches the given options. This is an expected state rather than a failure: a Knative service which has scaled to zero has no pods.

Functions

func AppendKafkaEnvs added in v0.50.0

func AppendKafkaEnvs(envVars []corev1.EnvVar, kafka *fn.KafkaConfig, referencedSecrets, referencedConfigMaps *sets.Set[string]) ([]corev1.EnvVar, error)

AppendKafkaEnvs appends the runtime's Kafka configuration (brokers, topic, consumer group, and any TLS/SASL settings) to envVars. These are consumed by the injected Kafka runtime sidecar, not by the function container. A nil or incomplete Kafka config leaves envVars unchanged.

func CheckResourcesArePresent added in v0.48.0

func CheckResourcesArePresent(ctx context.Context, namespace string, referencedSecrets, referencedConfigMaps, referencedPVCs *sets.Set[string], referencedServiceAccount, imagePullSecret string) error

CheckResourcesArePresent returns error if Secrets or ConfigMaps referenced in input sets are not deployed on the cluster in the specified namespace

func CreatePersistentVolumeClaim

func CreatePersistentVolumeClaim(ctx context.Context, name, namespaceOverride string, labels map[string]string, annotations map[string]string, accessMode corev1.PersistentVolumeAccessMode, resourceRequest resource.Quantity, storageClassName string) (err error)

func DeletePersistentVolumeClaims

func DeletePersistentVolumeClaims(ctx context.Context, namespaceOverride string, listOptions metav1.ListOptions) (err error)

func DeleteSecrets

func DeleteSecrets(ctx context.Context, namespaceOverride string, listOptions metav1.ListOptions) (err error)

func DeployNamespace added in v0.51.0

func DeployNamespace(f fn.Function) (string, error)

DeployNamespace is where a function will be deployed: the requested namespace, or the one it is already deployed in. The wider arbitration between kube context, flags, environment and global defaults is settled earlier, before a Function reaches a deployer.

Exported so pkg/keda can apply this exact rule ahead of its embedded raw deploy; a copy could drift.

func DetectOpenShift added in v0.51.0

func DetectOpenShift() (bool, error)

DetectOpenShift reports whether the cluster serves the OpenShift Route API. A non-nil error means the cluster could not be asked and the bool is meaningless. Probes once per process, answers from cache after.

func EnsureSecretExist

func EnsureSecretExist(ctx context.Context, secret corev1.Secret, namespaceOverride string) (err error)

func FindSecretForPath added in v0.51.0

func FindSecretForPath(certPath string, volumes []fn.Volume) (secretName, key string)

FindSecretForPath resolves the Secret that backs a given file path among the function's volumes. It returns the Secret name and the data key (the filename) for the path, or empty strings when no Secret backs it.

A match requires a Secret volume whose mount path is the immediate parent directory of certPath: func mounts a Secret at a single directory level, so the cert must sit directly in that directory for its filename to be a valid Secret data key. Non-Secret volumes (PVC/ConfigMap/emptyDir) never match, and an ancestor directory that is not the immediate parent (e.g. a PVC at /data for a cert at /data/certs/ca.crt) is rejected because the relative path still contains a separator.

Both the raw/k8s Kafka sidecar mount selection (kafkaSidecarVolumeMounts) and the keda TriggerAuthentication wiring resolve cert paths through this one function so the two paths stay genuinely in parity.

func GetACRCredentialLoader added in v0.47.0

func GetACRCredentialLoader() []creds.ContextCredentialsCallback

func GetClientConfig

func GetClientConfig() clientcmd.ClientConfig

func GetConfigMap

func GetConfigMap(ctx context.Context, name, namespaceOverride string) (*corev1.ConfigMap, error)

func GetDefaultNamespace added in v0.41.0

func GetDefaultNamespace() (namespace string, err error)

GetDefaultNamespace returns default namespace

func GetDefaultOpenShiftRegistry added in v0.38.1

func GetDefaultOpenShiftRegistry() string

func GetECRCredentialLoader added in v0.47.0

func GetECRCredentialLoader() []creds.CredentialsCallback

func GetGoogleCredentialLoader added in v0.47.0

func GetGoogleCredentialLoader() []creds.CredentialsCallback

func GetManifestivalClient added in v0.38.0

func GetManifestivalClient() (manifestival.Client, error)

func GetOpenShiftDockerCredentialLoaders added in v0.38.1

func GetOpenShiftDockerCredentialLoaders() []creds.CredentialsCallback

func GetOpenShiftServiceCA added in v0.38.1

func GetOpenShiftServiceCA(ctx context.Context) (*x509.Certificate, error)

func GetPersistentVolumeClaim

func GetPersistentVolumeClaim(ctx context.Context, name, namespaceOverride string) (*corev1.PersistentVolumeClaim, error)

func GetPodLogs

func GetPodLogs(ctx context.Context, namespace, podName, containerName string) (string, error)

GetPodLogs returns logs from a specified Container in a Pod, if container is empty string, then the first container in the pod is selected.

func GetPodLogsBySelector added in v0.48.0

func GetPodLogsBySelector(ctx context.Context, opts PodLogsOptions, out io.Writer) error

GetPodLogsBySelector will get logs of a pod.

It will do so by gathering logs of the given container of all affiliated pods. In addition, filtering on image can be done so only logs for given image are logged.

When Follow is set, this function runs as long as the passed context is active (i.e. it is required to cancel the context to stop log gathering). Otherwise a snapshot of the currently available logs is written and the function returns.

func GetSecret

func GetSecret(ctx context.Context, name, namespaceOverride string) (*corev1.Secret, error)

func GetServiceAccount added in v0.38.0

func GetServiceAccount(ctx context.Context, referencedServiceAccount, namespace string) error

func HandleDockerCfgJSONContent

func HandleDockerCfgJSONContent(username, password, email, server string) ([]byte, error)

func ImagePullSecrets added in v0.50.0

func ImagePullSecrets(secret string) []corev1.LocalObjectReference

ImagePullSecrets converts a secret name to a slice of LocalObjectReference suitable for use in a PodSpec. Returns nil if the name is empty.

func IsOpenShift added in v0.38.1

func IsOpenShift() bool

IsOpenShift is a convenient wrapper for getting simple yes/no for openshift cluster. The inner function should run in the cmd layer once to resolve the detectOnce.Do(), any call after is cached so we dont have to call API all the time.

note: gauron99: this might change after restructuring to kubeconfig resolution at the start of program instead of adhoc API calls of kube client throughout the codebase

func IsOpenShiftInternalRegistry added in v0.49.0

func IsOpenShiftInternalRegistry(registry string) bool

IsOpenShiftInternalRegistry returns true if the given registry string refers to the OpenShift internal image registry.

func ListConfigMapsNamesIfConnected

func ListConfigMapsNamesIfConnected(ctx context.Context, namespaceOverride string) (names []string, err error)

ListConfigMapsNamesIfConnected lists names of ConfigMaps present and the current k8s context returns empty list, if not connected to any cluster

func ListPersistentVolumeClaimsNamesIfConnected added in v0.38.0

func ListPersistentVolumeClaimsNamesIfConnected(ctx context.Context, namespaceOverride string) (names []string, err error)

ListPersistentVolumeClaimsNamesIfConnected lists names of PersistentVolumeClaims present and the current k8s context returns empty list, if not connected to any cluster

func ListSecretsNamesIfConnected

func ListSecretsNamesIfConnected(ctx context.Context, namespaceOverride string) (names []string, err error)

ListSecretsNamesIfConnected lists names of Secrets present and the current k8s context returns empty list, if not connected to any cluster

func NewClientAndResolvedNamespace

func NewClientAndResolvedNamespace(ns string) (*kubernetes.Clientset, string, error)

func NewDynamicClient

func NewDynamicClient() (dynamic.Interface, error)

func NewInClusterDialer

func NewInClusterDialer(ctx context.Context, clientConfig clientcmd.ClientConfig) (*contextDialer, error)

NewInClusterDialer creates context dialer that will dial TCP connections via POD running in k8s cluster. This is useful when accessing k8s services that are not exposed outside cluster (e.g. openshift image registry).

Usage:

dialer, err := k8s.NewInClusterDialer(ctx)
if err != nil {
    return err
}
defer dialer.Close()

transport := &http.Transport{
    DialContext: dialer.DialContext,
}

var client = http.Client{
    Transport: transport,
}

func NewKubernetesClientset

func NewKubernetesClientset() (*kubernetes.Clientset, error)

func NewLazyInitInClusterDialer

func NewLazyInitInClusterDialer(clientConfig clientcmd.ClientConfig) *lazyInitInClusterDialer

func NewLister added in v0.48.0

func NewLister(kc *Client, verbose bool) fn.Lister

func NewRegistrySecret added in v0.51.0

func NewRegistrySecret(f fn.Function, username, password, server string) (corev1.Secret, error)

NewRegistrySecret returns the Secret holding the registry credentials of function f, of type kubernetes.io/dockerconfigjson, the standard type for them, which image pull secrets require. Remote builds mount its .dockerconfigjson key as the config.json the build reads. All its writers build it here, so none undoes another's write. The function's labels let func delete remove it.

func ProcessEnvs added in v0.48.0

func ProcessEnvs(envs []fn.Env, referencedSecrets, referencedConfigMaps *sets.Set[string]) ([]corev1.EnvVar, []corev1.EnvFromSource, error)

ProcessEnvs generates array of EnvVars and EnvFromSources from a function config envs:

  • name: EXAMPLE1 # ENV directly from a value value: value1
  • name: EXAMPLE2 # ENV from the local ENV var value: {{ env:MY_ENV }}
  • name: EXAMPLE3 value: {{ secret:example-secret:key }} # ENV from a key in Secret
  • value: {{ secret:example-secret }} # all ENVs from Secret
  • name: EXAMPLE4 value: {{ configMap:configMapName:key }} # ENV from a key in ConfigMap
  • value: {{ configMap:configMapName }} # all key-pair values from ConfigMap are set as ENV

func ProcessVolumes added in v0.48.0

func ProcessVolumes(volumes []fn.Volume, referencedSecrets, referencedConfigMaps, referencedPVCs *sets.Set[string]) ([]corev1.Volume, []corev1.VolumeMount, error)

ProcessVolumes generates Volumes and VolumeMounts from a function config volumes:

  • secret: example-secret # mount Secret as Volume path: /etc/secret-volume
  • configMap: example-configMap # mount ConfigMap as Volume path: /etc/configMap-volume
  • persistentVolumeClaim: { claimName: example-pvc } # mount PersistentVolumeClaim as Volume path: /etc/secret-volume
  • emptyDir: {} # mount EmptyDir as Volume path: /etc/configMap-volume

func RecordExposure added in v0.51.0

func RecordExposure(ctx context.Context, clientset kubernetes.Interface, ref deployer.ExposureRef, hostname string) error

RecordExposure writes or clears the Route record on the function's Service. ref identifies the Service (FunctionName + FunctionNamespace) and where the Route lives (Namespace). A non-empty hostname writes both annotations; an empty hostname removes them. A missing Service is fine when clearing.

func SetHealthEndpoints added in v0.48.0

func SetHealthEndpoints(f fn.Function, container *corev1.Container)

SetHealthEndpoints configures health probes for a container

func SetOpenShiftForTest added in v0.49.0

func SetOpenShiftForTest(val bool, err error) func()

SetOpenShiftForTest seeds the detection cache; err simulates a cluster that could not be asked. Returns a cleanup restoring the previous state.

func SetSecurityContext added in v0.48.0

func SetSecurityContext(container *corev1.Container)

SetSecurityContext configures security settings for a container

func UploadToVolume

func UploadToVolume(ctx context.Context, content io.Reader, claimName, namespace string) error

UploadToVolume uploads files (passed in form of tar stream) into volume.

func UsesRawDeployer added in v0.48.0

func UsesRawDeployer(annotations map[string]string) bool

func WaitForDeploymentAvailable added in v0.48.0

func WaitForDeploymentAvailable(ctx context.Context, clientset *kubernetes.Clientset, namespace, deploymentName string, timeout time.Duration) error

WaitForDeploymentAvailable waits for a specific deployment to be fully available. A deployment is considered available when: - The number of available replicas matches the desired replicas - All replicas are updated to the latest version - There are no unavailable replicas - All pods associated with the deployment are running

func WaitForDeploymentAvailableBySelector added in v0.48.0

func WaitForDeploymentAvailableBySelector(ctx context.Context, clientset *kubernetes.Clientset, namespace, selector string, timeout time.Duration) error

func WaitForServiceRemoved added in v0.48.0

func WaitForServiceRemoved(ctx context.Context, clientset *kubernetes.Clientset, namespace, name string, timeout time.Duration) error

Types

type Client added in v0.51.0

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

func NewClient added in v0.51.0

func NewClient(cc clientcmd.ClientConfig) *Client

func NewClientFromConfig added in v0.51.0

func NewClientFromConfig(cfg *rest.Config) *Client

func (*Client) ClientConfig added in v0.51.0

func (c *Client) ClientConfig() (*rest.Config, error)

func (*Client) Clientset added in v0.51.0

func (c *Client) Clientset() (*kubernetes.Clientset, error)

type Deployer added in v0.48.0

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

func NewDeployer added in v0.48.0

func NewDeployer(opts ...DeployerOpt) *Deployer

func (*Deployer) Deploy added in v0.48.0

func (d *Deployer) Deploy(ctx context.Context, f fn.Function) (fn.DeploymentResult, error)

type DeployerOpt added in v0.48.0

type DeployerOpt func(*Deployer)

func WithDeployerDecorator added in v0.48.0

func WithDeployerDecorator(decorator deployer.DeployDecorator) DeployerOpt

func WithDeployerVerbose added in v0.48.0

func WithDeployerVerbose(verbose bool) DeployerOpt

func WithExposer added in v0.51.0

func WithExposer(exposer deployer.Exposer) DeployerOpt

type Describer added in v0.48.0

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

func NewDescriber added in v0.48.0

func NewDescriber(verbose bool, opts ...DescriberOpt) *Describer

func (*Describer) Describe added in v0.48.0

func (d *Describer) Describe(ctx context.Context, name, namespace string) (fn.Instance, error)

Describe a function by name.

type DescriberOpt added in v0.49.0

type DescriberOpt func(*Describer)

func WithDescriberTransport added in v0.49.0

func WithDescriberTransport(transport http.RoundTripper) DescriberOpt

type Lister added in v0.48.0

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

func (*Lister) List added in v0.48.0

func (l *Lister) List(ctx context.Context, namespace string) ([]fn.ListItem, error)

type OpenshiftMetadataDecorator added in v0.38.1

type OpenshiftMetadataDecorator struct{}

func (OpenshiftMetadataDecorator) UpdateAnnotations added in v0.38.1

func (o OpenshiftMetadataDecorator) UpdateAnnotations(f fn.Function, annotations map[string]string) map[string]string

func (OpenshiftMetadataDecorator) UpdateLabels added in v0.38.1

func (o OpenshiftMetadataDecorator) UpdateLabels(f fn.Function, labels map[string]string) map[string]string

type PartialLogsError added in v0.51.0

type PartialLogsError struct {
	Err error
}

PartialLogsError is returned when the logs of some, but not all, matching pods could be gathered. The logs which were gathered have been written.

func (*PartialLogsError) Error added in v0.51.0

func (e *PartialLogsError) Error() string

func (*PartialLogsError) Unwrap added in v0.51.0

func (e *PartialLogsError) Unwrap() error

type PodLogsOptions added in v0.51.0

type PodLogsOptions struct {
	// Namespace in which the pods reside.  An empty value resolves to the
	// currently active namespace.
	Namespace string

	// LabelSelector which matches the pods whose logs are gathered.
	LabelSelector string

	// Container whose logs are gathered.
	Container string

	// Image, when non-empty, restricts gathering to pods whose container runs
	// this exact image.
	Image string

	// Since, when non-nil, is the time from which logs are returned.
	Since *time.Time

	// TailLines, when non-nil, limits the output to the last N lines per pod.
	TailLines *int64

	// Follow streams logs of matching pods, including pods which appear later,
	// until the context is cancelled.  When false, the logs currently available
	// from the currently matching pods are written and the call returns.
	Follow bool
}

PodLogsOptions are the parameters of GetPodLogsBySelector.

type Remover added in v0.48.0

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

func NewRemover added in v0.48.0

func NewRemover(verbose bool) *Remover

func (*Remover) Remove added in v0.48.0

func (remover *Remover) Remove(ctx context.Context, name, ns string) error

type SynchronizedBuffer added in v0.48.0

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

func (*SynchronizedBuffer) Read added in v0.48.0

func (b *SynchronizedBuffer) Read(p []byte) (n int, err error)

func (*SynchronizedBuffer) Reset added in v0.48.0

func (b *SynchronizedBuffer) Reset()

func (*SynchronizedBuffer) String added in v0.48.0

func (b *SynchronizedBuffer) String() string

func (*SynchronizedBuffer) Write added in v0.48.0

func (b *SynchronizedBuffer) Write(p []byte) (n int, err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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