这是本节的多页打印视图。 点击此处打印.

返回本页常规视图.

仓库视角

以代码仓库视角来学习 k8s 源码

staging 仓库

根目录下的 staging 目录是外部版本库暂存区,这些软件包已被拆分到各自的版本库中。这里的内容将定期发布到各自的顶级 k8s.io 仓库。

  • k8s.io/api
  • k8s.io/apiextensions-apiserver
  • k8s.io/apimachinery
  • k8s.io/apiserver
  • k8s.io/cli-runtime
  • k8s.io/client-go
  • k8s.io/cloud-provider
  • k8s.io/cluster-bootstrap
  • k8s.io/code-generator
  • k8s.io/component-base
  • k8s.io/component-helpers
  • k8s.io/controller-manager
  • k8s.io/cri-api
  • k8s.io/cri-client
  • k8s.io/csi-translation-lib
  • k8s.io/dynamic-resource-allocation
  • k8s.io/endpointslice
  • k8s.io/externaljwt
  • k8s.io/kms
  • k8s.io/kube-aggregator
  • k8s.io/kube-controller-manager
  • k8s.io/kube-proxy
  • k8s.io/kube-scheduler
  • k8s.io/kubectl
  • k8s.io/kubelet
  • k8s.io/metrics
  • k8s.io/mount-utils
  • k8s.io/pod-security-admission

1 - api 仓库

api 仓库

1.1 - 概述

api 仓库概述

api 信息

api 列表

  • admission
  • admissionregistration
  • apidiscovery
  • apiserverinternal
  • apps
  • authentication
  • authorization
  • autoscaling
  • batch
  • certificates
  • coordination
  • core
  • discovery
  • doc.go
  • events
  • extensions
  • flowcontrol
  • imagepolicy
  • networking
  • node
  • policy
  • rbac
  • resource
  • scheduling
  • storage
  • storagemigration

API 版本

大部分 api 都有多个版本,如:

  • v1
  • v1alpha1
  • v1beta1

代码学习中,我们以 v1 版本为主。

api 代码结构

基本上每个 api 文件夹都有如下的文件列表:

  • doc.go
  • generated.pb.go
  • register.go
  • types.go
  • types_swagger_doc_generated.go
  • zz_generated.deepcopy.go
  • zz_generated.prerelease-lifecycle.go

doc.go

这是包的文档文件,包含包的用途说明和基本的文档注释

通常会包含 +k8s:openapi-gen=true 这样的代码生成标记

定义了包的帮助文档和代码生成器的元数据。

打开看源码,发现除了 license 之外,只定义了 package 名字和该 package 相关的注解,如:

// +k8s:deepcopy-gen=package
// +k8s:protobuf-gen=package
// +k8s:openapi-gen=false
// +k8s:prerelease-lifecycle-gen=true
// +groupName=admission.k8s.io

package v1

generated.pb.go

generated.pb.go 是 Protocol Buffers 的生成文件(由 generated.proto 生成),包含了 AdmissionReview 等类型的 Protocol Buffers 序列化相关代码,用于 Kubernetes API 的 gRPC 通信和存储序列化。

代码都是从 generated.proto 文件生成的,没啥好看的,直接看 generated.proto 文件好了。

generated.proto

generated.proto 是Protocol Buffers 的定义文件,定义了当前 API 类型的 protobuf 消息格式。

generated.proto 文件会被 protoc 编译器用来生成 generated.pb.go

register.go

register.go 包含 API 类型的注册逻辑,将 API 中的类型注册到 Kubernetes API 的 Scheme 中。

register.go 定义了如何将 Go 类型与 API 版本/组进行映射,包含 AddToScheme 函数,其他组件可以调用它来注册这些类型。

types.go

最重要的文件,包含核心 API 类型的 Go 定义,定义了 API 相关的各种结构体,包含字段定义、标签注释和验证逻辑,有详细的字段注释说明每个字段的用途

types_swagger_doc_generated.go

自动生成的 Swagger 文档,包含 API 类型的详细文档,用于生成 Kubernetes API 参考文档。

这些注释会被 Kubernetes API 文档工具使用。

zz_generated.deepcopy.go

自动生成的 DeepCopy 方法实现,包含 api 类型的深拷贝方法,由 deepcopy-gen 工具根据 types.go 中的标记生成。

Kubernetes 运行时需要这些方法来安全地复制对象。

zz_generated.prerelease-lifecycle.go

自动生成的 API 生命周期相关代码,包含 API 版本的弃用和移除策略,由 prerelease-lifecycle-gen 工具生成。

用于管理 API 版本的生命周期(alpha/beta/stable 状态转换)。

1.2 - admission

Admission API 主要用于 动态准入控制(Dynamic Admission Control),即在 Kubernetes API 请求被处理之前或之后,对其进行 拦截、验证或修改。

1.2.1 - 概述

Admission API

介绍

Admission API 主要用于 动态准入控制(Dynamic Admission Control),即在 Kubernetes API 请求被处理之前或之后,对其进行 拦截、验证或修改。它的主要功能包括:

  • 验证(Validation):检查资源的合法性(如 Pod 的镜像是否符合安全策略)。
  • 变更(Mutation):修改请求的内容(如自动注入 Sidecar 容器)。
  • 审计(Auditing):记录 API 请求的详细信息,用于安全审计。

Admission API 通常与 Admission Webhooks 配合使用,允许用户自定义准入逻辑(如通过 Webhook 调用外部服务)。

核心类型

Admission API 主要定义在 types.go 中,核心结构体包括:

  1. AdmissionReview

    • 用于封装 准入请求(Request)准入响应(Response)

    • 是 Webhook 和 API Server 之间的通信格式。

  2. AdmissionRequest

    表示一个 准入请求,包含所有需要验证或修改的资源信息。

  3. AdmissionResponse

    表示 准入控制的结果,决定是否允许该请求,并可以返回修改内容。

HTTP 方法

Admission API 本身不直接提供 REST API,而是 由 API Server 调用 Webhook 时使用。其交互流程如下:

  1. API Server 收到请求(如 kubectl create -f pod.yaml)。
  2. API Server 构造 AdmissionReview,发送给配置的 Webhook。
  3. Webhook 处理请求,返回 AdmissionReview{ Response: ... }
  4. API Server 根据响应决定是否继续处理

使用场景

Admission API 通常用于:

  1. 强制安全策略(如禁止特权容器)。
  2. 资源默认值注入(如自动设置 requests/limits)。
  3. Sidecar 注入(如 Istio 自动注入 istio-proxy)。
  4. 自定义验证逻辑(如检查 Ingress 域名是否合法)。

1.2.2 - types.go

Admission API 类型

AdmissionReview

AdmissionReview 描述了准入审查请求/应答。

// AdmissionReview describes an admission review request/response.
type AdmissionReview struct {
	metav1.TypeMeta `json:",inline"`
	// Request describes the attributes for the admission request.
	// +optional
	Request *AdmissionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"`
	// Response describes the attributes for the admission response.
	// +optional
	Response *AdmissionResponse `json:"response,omitempty" protobuf:"bytes,2,opt,name=response"`
}

AdmissionRequest

dmissionRequest 描述了准入请求的准入属性

type AdmissionRequest struct {
	// UID 是单个请求/响应的唯一标识符。它允许我们区分其他方面相同的请求实例
	//(并行请求、先前请求未修改时的请求等)
	// UID 用于跟踪 KAS 和 WebHook 之间的往返(请求/响应),而不是用户请求
	// 它适合在 webhook 和 apiserver 之间关联日志条目,用于审计或调试
	UID types.UID `json:"uid" protobuf:"bytes,1,opt,name=uid"`
	// Kind 是被提交对象的完全限定类型(例如 v1.Pod 或 autoscaling.v1.Scale)
	Kind metav1.GroupVersionKind `json:"kind" protobuf:"bytes,2,opt,name=kind"`
	// Resource 是被请求的完全限定资源(例如 v1.pods)
	Resource metav1.GroupVersionResource `json:"resource" protobuf:"bytes,3,opt,name=resource"`
	// SubResource 是被请求的子资源(如果有)(例如 "status" 或 "scale")
	// +optional
	SubResource string `json:"subResource,omitempty" protobuf:"bytes,4,opt,name=subResource"`

	// RequestKind 是原始 API 请求的完全限定类型(例如 v1.Pod 或 autoscaling.v1.Scale)
	// 如果指定且与 "kind" 中的值不同,则表示执行了等效匹配和转换
	//
	// 例如,如果 deployments 可以通过 apps/v1 和 apps/v1beta1 修改,并且 webhook 注册了规则
	// `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` 和 `matchPolicy: Equivalent`,
	// 那么发送到 apps/v1beta1 deployments 的 API 请求会被转换并发送到 webhook,
	// 其中 `kind: {group:"apps", version:"v1", kind:"Deployment"}`(匹配 webhook 注册的规则),
	// 而 `requestKind: {group:"apps", version:"v1beta1", kind:"Deployment"}`(表示原始 API 请求的类型)
	//
	// 更多详情请参阅 webhook 配置类型中 "matchPolicy" 字段的文档
	// +optional
	RequestKind *metav1.GroupVersionKind `json:"requestKind,omitempty" protobuf:"bytes,13,opt,name=requestKind"`
	// RequestResource 是原始 API 请求的完全限定资源(例如 v1.pods)
	// 如果指定且与 "resource" 中的值不同,则表示执行了等效匹配和转换
	//
	// 例如,如果 deployments 可以通过 apps/v1 和 apps/v1beta1 修改,并且 webhook 注册了规则
	// `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` 和 `matchPolicy: Equivalent`,
	// 那么发送到 apps/v1beta1 deployments 的 API 请求会被转换并发送到 webhook,
	// 其中 `resource: {group:"apps", version:"v1", resource:"deployments"}`(匹配 webhook 注册的资源),
	// 而 `requestResource: {group:"apps", version:"v1beta1", resource:"deployments"}`(表示原始 API 请求的资源)
	//
	// 更多详情请参阅 webhook 配置类型中 "matchPolicy" 字段的文档
	// +optional
	RequestResource *metav1.GroupVersionResource `json:"requestResource,omitempty" protobuf:"bytes,14,opt,name=requestResource"`
	// RequestSubResource 是原始 API 请求的子资源名称(如果有)(例如 "status" 或 "scale")
	// 如果指定且与 "subResource" 中的值不同,则表示执行了等效匹配和转换
	// 更多详情请参阅 webhook 配置类型中 "matchPolicy" 字段的文档
	// +optional
	RequestSubResource string `json:"requestSubResource,omitempty" protobuf:"bytes,15,opt,name=requestSubResource"`

	// Name 是请求中呈现的对象名称。在 CREATE 操作中,客户端可以省略名称,
	// 依赖服务器生成名称。如果是这种情况,此字段将包含空字符串
	// +optional
	Name string `json:"name,omitempty" protobuf:"bytes,5,opt,name=name"`
	// Namespace 是与请求关联的命名空间(如果有)
	// +optional
	Namespace string `json:"namespace,omitempty" protobuf:"bytes,6,opt,name=namespace"`
	// Operation 是正在执行的操作。这可能与请求的操作不同
	// 例如,一个 patch 可能导致 CREATE 或 UPDATE 操作
	Operation Operation `json:"operation" protobuf:"bytes,7,opt,name=operation"`
	// UserInfo 是关于请求用户的信息
	UserInfo authenticationv1.UserInfo `json:"userInfo" protobuf:"bytes,8,opt,name=userInfo"`
	// Object 是来自传入请求的对象
	// +optional
	Object runtime.RawExtension `json:"object,omitempty" protobuf:"bytes,9,opt,name=object"`
	// OldObject 是现有对象。仅对 DELETE 和 UPDATE 请求填充
	// +optional
	OldObject runtime.RawExtension `json:"oldObject,omitempty" protobuf:"bytes,10,opt,name=oldObject"`
	// DryRun 表示此请求的修改肯定不会持久化
	// 默认为 false
	// +optional
	DryRun *bool `json:"dryRun,omitempty" protobuf:"varint,11,opt,name=dryRun"`
	// Options 是正在执行的操作的操作选项结构
	// 例如 `meta.k8s.io/v1.DeleteOptions` 或 `meta.k8s.io/v1.CreateOptions`。这可能与
	// 调用者提供的选项不同。例如,对于 patch 请求,执行的操作可能是 CREATE,
	// 在这种情况下,Options 将是 `meta.k8s.io/v1.CreateOptions`,即使调用者提供了 `meta.k8s.io/v1.PatchOptions`
	// +optional
	Options runtime.RawExtension `json:"options,omitempty" protobuf:"bytes,12,opt,name=options"`
}

AdmissionResponse

// AdmissionResponse 描述了一个准入响应
type AdmissionResponse struct {
	// UID 是单个请求/响应的标识符
	// 必须从对应的 AdmissionRequest 中复制过来
	UID types.UID `json:"uid" protobuf:"bytes,1,opt,name=uid"`

	// Allowed 表示是否允许该准入请求
	Allowed bool `json:"allowed" protobuf:"varint,2,opt,name=allowed"`

	// Result 包含关于为什么拒绝准入请求的额外细节
	// 如果 "Allowed" 为 "true",则不会参考此字段
	// +optional
	Result *metav1.Status `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`

	// patch 内容体。目前我们只支持实现了 RFC 6902 的 "JSONPatch"
	// +optional
	Patch []byte `json:"patch,omitempty" protobuf:"bytes,4,opt,name=patch"`

	// patch 类型。目前我们只允许 "JSONPatch"
	// +optional
	PatchType *PatchType `json:"patchType,omitempty" protobuf:"bytes,5,opt,name=patchType"`

	// AuditAnnotations 是由远程准入控制器设置的非结构化键值映射(例如 error=image-blacklisted)
	// MutatingAdmissionWebhook 和 ValidatingAdmissionWebhook 准入控制器会在键前加上
	// 准入 webhook 名称(例如 imagepolicy.example.com/error=image-blacklisted)
	// 准入 webhook 提供 AuditAnnotations 来为此请求的审计日志添加上下文
	// +optional
	AuditAnnotations map[string]string `json:"auditAnnotations,omitempty" protobuf:"bytes,6,opt,name=auditAnnotations"`

	// warnings 是要返回给请求 API 客户端的警告消息列表
	// 警告消息描述了 API 请求客户端应该纠正或注意的问题
	// 尽可能将警告限制在 120 个字符以内
	// 超过 256 个字符的警告和大量警告可能会被截断
	// +optional
	Warnings []string `json:"warnings,omitempty" protobuf:"bytes,7,rep,name=warnings"`
}

// PatchType is the type of patch being used to represent the mutated object
type PatchType string

// PatchType constants.
const (
	PatchTypeJSONPatch PatchType = "JSONPatch"
)

1.2.3 - register.go

Admission API 类型注册

就注册了一个类型 AdmissionReview:

// Adds the list of known types to the given scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&AdmissionReview{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

1.3 - admissionregistration

注册和管理 Kubernetes 的 动态准入控制 Webhook,允许用户在不修改 API Server 代码的情况下扩展准入控制逻辑。

1.3.1 - 概述

AdmissionRegistration API

介绍

AdmissionRegistration API 核心功能:用于注册和管理 Kubernetes 的 动态准入控制 Webhook,允许用户在不修改 API Server 代码的情况下扩展准入控制逻辑。

主要分为两类:

  1. MutatingAdmissionWebhook
    • 用于 修改 API 请求对象(如自动注入 Sidecar 容器)
  2. ValidatingAdmissionWebhook
    • 用于 验证 API 请求对象(如检查资源是否符合安全策略)

核心类型

admissionregistration.k8s.io/v1 中定义了以下关键资源:

  1. MutatingWebhookConfiguration
    • 用于注册多个 修改型 Webhook
    • 每个 Webhook 指定:
      • 触发规则(匹配哪些 API 请求)
      • 调用的 Webhook 服务地址
      • 失败策略(如拒绝请求或忽略错误)
  2. ValidatingWebhookConfiguration
    • 用于注册多个 验证型 Webhook
    • 结构与 MutatingWebhookConfiguration 类似,但 Webhook 不能修改对象。

核心 API 方法

AdmissionRegistration API 通过标准的 Kubernetes REST 接口提供以下操作:

HTTP 方法 路径 功能
GET /apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations 列出所有 MutatingWebhookConfiguration
POST 同上 创建新的 MutatingWebhookConfiguration
PUT /apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name} 更新指定配置
DELETE 同上 删除配置
GET /apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations 列出所有 ValidatingWebhookConfiguration
POST 同上 创建新的 ValidatingWebhookConfiguration

关键字段解析

(1) WebhookClientConfig

type WebhookClientConfig struct {
    URL      *string           `json:"url,omitempty"`      // Webhook 服务 URL(直接调用)
    Service  *ServiceReference `json:"service,omitempty"`  // 通过 Service 调用
    CABundle []byte            `json:"caBundle,omitempty"`  // CA 证书(用于 TLS 验证)
}
  • 支持两种调用方式:
    • 直接指定 URL(如 https://webhook.example.com:443/admit
    • 通过 Kubernetes Service 调用(推荐)

(2) RuleWithOperations

type RuleWithOperations struct {
    Operations []OperationType `json:"operations"`  // 操作类型:CREATE, UPDATE, DELETE, *
    Rule       Rule            `json:"rule"`        // 资源匹配规则
}
  • 示例:匹配所有 Pod 的 CREATE/UPDATE 操作:

    rules:
    - operations: ["CREATE", "UPDATE"]
      apiGroups: [""]
      apiVersions: ["v1"]
      resources: ["pods"]
    

(3) FailurePolicy

type FailurePolicyType string
const (
    Ignore FailurePolicyType = "Ignore"  // 失败时忽略(继续请求)
    Fail   FailurePolicyType = "Fail"    // 失败时拒绝请求
)

工作原理

  1. API Server 接收请求(如创建 Pod)
  2. 检查匹配的 Webhook 规则
    • 通过 rules 字段过滤
  3. 调用 Webhook 服务
    • 发送 AdmissionReview 请求
  4. 处理响应
    • 根据 allowedpatch 字段决定是否允许请求

1.3.2 - types.go

AdmissionRegistration API 类型

WebhookClientConfig

AdmissionReview 描述了准入审查请求/应答。


// WebhookClientConfig contains the information to make a TLS
// connection with the webhook
type WebhookClientConfig struct {
	// `url` gives the location of the webhook, in standard URL form
	// (`scheme://host:port/path`). Exactly one of `url` or `service`
	// must be specified.
	//
	// The `host` should not refer to a service running in the cluster; use
	// the `service` field instead. The host might be resolved via external
	// DNS in some apiservers (e.g., `kube-apiserver` cannot resolve
	// in-cluster DNS as that would be a layering violation). `host` may
	// also be an IP address.
	//
	// Please note that using `localhost` or `127.0.0.1` as a `host` is
	// risky unless you take great care to run this webhook on all hosts
	// which run an apiserver which might need to make calls to this
	// webhook. Such installs are likely to be non-portable, i.e., not easy
	// to turn up in a new cluster.
	//
	// The scheme must be "https"; the URL must begin with "https://".
	//
	// A path is optional, and if present may be any string permissible in
	// a URL. You may use the path to pass an arbitrary string to the
	// webhook, for example, a cluster identifier.
	//
	// Attempting to use a user or basic auth e.g. "user:password@" is not
	// allowed. Fragments ("#...") and query parameters ("?...") are not
	// allowed, either.
	//
	// +optional
	URL *string `json:"url,omitempty" protobuf:"bytes,3,opt,name=url"`

	// `service` is a reference to the service for this webhook. Either
	// `service` or `url` must be specified.
	//
	// If the webhook is running within the cluster, then you should use `service`.
	//
	// +optional
	Service *ServiceReference `json:"service,omitempty" protobuf:"bytes,1,opt,name=service"`

	// `caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate.
	// If unspecified, system trust roots on the apiserver are used.
	// +optional
	CABundle []byte `json:"caBundle,omitempty" protobuf:"bytes,2,opt,name=caBundle"`
}

RuleWithOperations

// RuleWithOperations is a tuple of Operations and Resources. It is recommended to make
// sure that all the tuple expansions are valid.
type RuleWithOperations struct {
	// Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or *
	// for all of those operations and any future admission operations that are added.
	// If '*' is present, the length of the slice must be one.
	// Required.
	// +listType=atomic
	Operations []OperationType `json:"operations,omitempty" protobuf:"bytes,1,rep,name=operations,casttype=OperationType"`
	// Rule is embedded, it describes other criteria of the rule, like
	// APIGroups, APIVersions, Resources, etc.
	Rule `json:",inline" protobuf:"bytes,2,opt,name=rule"`
}

OperationType

// OperationType specifies an operation for a request.
// +enum
type OperationType string

// The constants should be kept in sync with those defined in k8s.io/kubernetes/pkg/admission/interface.go.
const (
	OperationAll OperationType = "*"
	Create       OperationType = "CREATE"
	Update       OperationType = "UPDATE"
	Delete       OperationType = "DELETE"
	Connect      OperationType = "CONNECT"
)

FailurePolicyType

// FailurePolicyType specifies a failure policy that defines how unrecognized errors from the admission endpoint are handled.
// +enum
type FailurePolicyType string

const (
	// Ignore means that an error calling the webhook is ignored.
	Ignore FailurePolicyType = "Ignore"
	// Fail means that an error calling the webhook causes the admission to fail.
	Fail FailurePolicyType = "Fail"
)

1.3.3 - register.go

AdmissionRegistration API 类型注册

注册类型

// Adds the list of known types to the given scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&ValidatingWebhookConfiguration{},
		&ValidatingWebhookConfigurationList{},
		&MutatingWebhookConfiguration{},
		&MutatingWebhookConfigurationList{},
		&ValidatingAdmissionPolicy{},
		&ValidatingAdmissionPolicyList{},
		&ValidatingAdmissionPolicyBinding{},
		&ValidatingAdmissionPolicyBindingList{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

1.4 - apidiscovery

提供 Kubernetes API 的 动态发现机制,使客户端能够自动发现集群支持的 API 资源及其详细信息。

1.4.1 - 概述

APIDiscovery API

介绍

APIDiscovery API 的核心功能是提供 Kubernetes API 的 动态发现机制,使客户端能够自动发现集群支持的 API 资源及其详细信息。

主要解决以下问题:

  1. API 资源发现:客户端无需硬编码即可知道集群支持哪些 API(如 pods、deployments 等)
  2. 版本兼容性:发现不同 API 版本(如 v1、v1beta1)及其差异
  3. API 聚合支持:支持自定义 API Server(Aggregated API Server)的自动注册和发现
  4. 高效缓存:客户端可以缓存发现信息,减少不必要的 API 调用

核心 API 资源类型

apidiscovery.k8s.io/v2(最新版本)中定义了以下关键结构:

(1) APIGroupDiscovery

// 描述一个 API 组的所有可用版本和资源
type APIGroupDiscovery struct {
    metav1.TypeMeta `json:",inline"`
    metav1.GroupVersion `json:",inline"`  // 例如 "apps/v1"
    Versions []APIVersionDiscovery `json:"versions"`  // 该组下的所有版本
}

(2) APIVersionDiscovery

// 描述一个 API 版本下的所有资源
type APIVersionDiscovery struct {
    Version string `json:"version"`  // 例如 "v1"
    Resources []APIResourceDiscovery `json:"resources"`  // 该版本下的资源列表
    Freshness metav1.ConditionStatus `json:"freshness"`  // 表示数据是否最新
}

(3) APIResourceDiscovery

// 描述单个 API 资源的详细信息
type APIResourceDiscovery struct {
    Resource string `json:"resource"`  // 例如 "pods"
    ResponseKind *metav1.GroupVersionKind `json:"responseKind"`  // 返回的 Kind
    Scope ScopeType `json:"scope"`  // 作用域(Namespaced/Cluster)
    SingularResource string `json:"singularResource"`  // 单数形式(如 "pod")
    Verbs []string `json:"verbs"`  // 支持的动词(get/list/watch 等)
    ShortNames []string `json:"shortNames"`  // 缩写(如 "po")
    Categories []string `json:"categories"`  // 所属分类(如 "all")
    Subresources []APISubresourceDiscovery `json:"subresources"`  // 子资源
}

核心 API 方法

APIDiscovery API 通过以下标准 HTTP 端点提供服务:

HTTP 方法 路径 功能
GET /apis/apidiscovery.k8s.io/v2 获取 APIDiscovery API 自身的描述
GET /apis/apidiscovery.k8s.io/v2/apigroups 获取所有 API 组的发现信息
GET /apis/apidiscovery.k8s.io/v2/apigroups/{group} 获取特定 API 组的发现信息

工作原理

  1. 客户端首次查询

    kubectl get --raw /apis/apidiscovery.k8s.io/v2beta1/apigroups
    
  2. 解析响应

    • 获取所有 API 组、版本、资源及其能力
  3. 建立本地缓存

    • 客户端缓存发现结果,后续只检查 Freshness
  4. 处理 API 变更

    • 当 API 扩展(如 CRD 注册)时,APIServer 自动更新发现信息

实际应用场景

(1) kubectl 自动补全

# kubectl 依赖发现 API 实现自动补全
kubectl get <TAB>  # 显示所有可用资源类型

(2) 客户端库初始化

// client-go 使用发现 API 初始化动态客户端
discoveryClient := clientset.Discovery()
resources, err := discoveryClient.ServerResources()

(3) 自定义控制器开发

// 动态发现新的 CRD
discoveryClient.Discovery().ServerPreferredResources()

源码学习路径

  1. 类型定义staging/src/k8s.io/api/apidiscovery/v2/types.go
  2. 服务端实现pkg/controlplane/apiserver/discovery/
  3. 客户端缓存逻辑staging/src/k8s.io/client-go/discovery/

1.4.2 - types.go

apidiscovery API 类型

APIGroupDiscoveryList


// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +k8s:prerelease-lifecycle-gen:introduced=1.30

// APIGroupDiscoveryList is a resource containing a list of APIGroupDiscovery.
// This is one of the types able to be returned from the /api and /apis endpoint and contains an aggregated
// list of API resources (built-ins, Custom Resource Definitions, resources from aggregated servers)
// that a cluster supports.
type APIGroupDiscoveryList struct {
	v1.TypeMeta `json:",inline"`
	// ResourceVersion will not be set, because this does not have a replayable ordering among multiple apiservers.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	v1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
	// items is the list of groups for discovery. The groups are listed in priority order.
	Items []APIGroupDiscovery `json:"items" protobuf:"bytes,2,rep,name=items"`
}

APIGroupDiscovery

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +k8s:prerelease-lifecycle-gen:introduced=1.30

// APIGroupDiscovery holds information about which resources are being served for all version of the API Group.
// It contains a list of APIVersionDiscovery that holds a list of APIResourceDiscovery types served for a version.
// Versions are in descending order of preference, with the first version being the preferred entry.
type APIGroupDiscovery struct {
	v1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// The only field completed will be name. For instance, resourceVersion will be empty.
	// name is the name of the API group whose discovery information is presented here.
	// name is allowed to be "" to represent the legacy, ungroupified resources.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
	// versions are the versions supported in this group. They are sorted in descending order of preference,
	// with the preferred version being the first entry.
	// +listType=map
	// +listMapKey=version
	Versions []APIVersionDiscovery `json:"versions,omitempty" protobuf:"bytes,2,rep,name=versions"`
}

1.4.3 - register.go

apidiscovery API 类型注册

注册类型 APIGroupDiscoveryList 和 APIGroupDiscovery:

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&APIGroupDiscoveryList{},
		&APIGroupDiscovery{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

1.5 - apiserverinternal

提供 API Server 的 内部状态管理和协调机制

1.5.1 - 概述

apiserverinternal API

介绍

apiserverinternal API 的核心功能是提供 API Server 的 内部状态管理和协调机制,主要服务于以下场景:

  1. 存储版本管理
    • 跟踪资源对象在 etcd 中的存储版本(Storage Version)
    • 确保多版本 API 的兼容性转换
  2. API Server 实例协调
    • 在多个 API Server 实例间同步状态信息
    • 支持高可用部署模式下的协调
  3. 内部状态监控
    • 暴露 API Server 的内部健康状态和性能指标

核心 API 资源类型

apiserverinternal.k8s.io/v1alpha1 中定义了以下关键资源:

  1. StorageVersion
  2. StorageVersionStatus
  3. ServerStorageVersion

关键工作流程

(1) 存储版本协商

  1. 当资源存在多版本(如 v1v1beta1)时:
    • 所有 API Server 实例通过 StorageVersion 资源协商出一个统一的存储版本
    • 写入 etcd 时统一转换为该版本
  2. 客户端请求时按需转换回目标版本

(2) 状态同步示例

# 示例:Deployment 资源的存储版本状态
apiVersion: apiserverinternal.k8s.io/v1alpha1
kind: StorageVersion
metadata:
  name: deployments.apps
status:
  storageVersions:
  - apiServerID: "kube-apiserver-xyz"
    encodingVersion: "apps/v1"
    decodableVersions: ["apps/v1", "apps/v1beta1"]
  commonEncodingVersion: "apps/v1"

实际应用场景

(1) 版本升级监控

# 查看当前存储版本协商状态
kubectl get storageversions.apiserverinternal.k8s.io

(2) 多版本兼容性保障

  • 确保旧版本客户端(如使用 apps/v1beta1)仍能读写数据
  • API Server 自动处理版本转换

(3) API Server 运维

  • 检测集群中不同 API Server 实例的版本一致性
  • 灰度升级时监控版本迁移状态

源码学习路径

  1. 类型定义staging/src/k8s.io/api/apiserverinternal/v1alpha1/types.go
  2. 控制器逻辑pkg/controlplane/storageversiongc/ (存储版本垃圾回收) pkg/apiserver/storageversion/ (版本协调主逻辑)
  3. 客户端交互staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/

调试技巧

# 查看所有资源的存储版本
kubectl get storageversions.apiserverinternal.k8s.io -o yaml

# 检查特定资源(如 Deployment)
kubectl get storageversions deployments.apps -o yaml

设计意义

  1. 解耦存储与 API 版本:允许 etcd 存储格式独立于对外暴露的 API 版本
  2. 平滑升级:支持多版本共存期间的无缝转换
  3. 分布式协调:解决多 API Server 实例的状态一致性问题

1.5.2 - types.go

apiserverinternal API 类型

StorageVersion

// Storage version of a specific resource.
type StorageVersion struct {
	metav1.TypeMeta `json:",inline"`
	// The name is <group>.<resource>.
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Spec is an empty spec. It is here to comply with Kubernetes API style.
	Spec StorageVersionSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"`

	// API server instances report the version they can decode and the version they
	// encode objects to when persisting objects in the backend.
	Status StorageVersionStatus `json:"status" protobuf:"bytes,3,opt,name=status"`
}

StorageVersionList

// A list of StorageVersions.
type StorageVersionList struct {
	metav1.TypeMeta `json:",inline"`
	// Standard list metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
	// Items holds a list of StorageVersion
	Items []StorageVersion `json:"items" protobuf:"bytes,2,rep,name=items"`
}

1.5.3 - register.go

apiserverinternal API 类型注册

注册类型 APIGroupDiscoveryList 和 APIGroupDiscovery:

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&StorageVersion{},
		&StorageVersionList{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

1.6 - apps

提供对 应用层工作负载 的声明式管理

1.6.1 - 概述

apps API

介绍

apps API 的核心功能是提供对 应用层工作负载 的声明式管理,主要包括:

  • 部署管理:滚动更新、回滚、扩缩容
  • 状态维护:确保应用实例数与声明的一致
  • 版本控制:管理应用更新时的版本切换
  • 与底层资源(Pod)的协调

主要管理的资源类型:

  1. 无状态应用(Deployment)
  2. 有状态应用(StatefulSet)
  3. 守护进程(DaemonSet)
  4. 一次性任务(ReplicaSet,通常由 Deployment 自动管理)

核心 API 资源类型

在 apps/v1 中定义了以下关键资源(所有资源均为 namespace-scoped):

  1. Deployment
  2. DaemonSet
  3. StatefulSet
  4. ReplicaSet

源码学习路径

类型定义:

  • staging/src/k8s.io/api/apps/v1/types.go

控制器实现:

  • Deployment: pkg/controller/deployment/
  • StatefulSet: pkg/controller/statefulset/
  • DaemonSet: pkg/controller/daemon/

客户端操作:

  • staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/

设计意义

  1. 抽象与自动化:将 Pod 管理从手动操作转为声明式管理
  2. 版本化运维:支持灰度发布、金丝雀发布等高级部署模式
  3. 状态分离:区分应用定义(Spec)和运行时状态(Status)

1.6.2 - types.go

apps API 类型

StatefulSet

// StatefulSet represents a set of pods with consistent identities.
// Identities are defined as:
//   - Network: A single stable DNS and hostname.
//   - Storage: As many VolumeClaims as requested.
//
// The StatefulSet guarantees that a given network identity will always
// map to the same storage identity.
type StatefulSet struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Spec defines the desired identities of pods in this set.
	// +optional
	Spec StatefulSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`

	// Status is the current status of Pods in this StatefulSet. This data
	// may be out of date by some window of time.
	// +optional
	Status StatefulSetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

Deployment

// Deployment enables declarative updates for Pods and ReplicaSets.
type Deployment struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Specification of the desired behavior of the Deployment.
	// +optional
	Spec DeploymentSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`

	// Most recently observed status of the Deployment.
	// +optional
	Status DeploymentStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

DaemonSet

// DaemonSet represents the configuration of a daemon set.
type DaemonSet struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// The desired behavior of this daemon set.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
	// +optional
	Spec DaemonSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`

	// The current status of this daemon set. This data may be
	// out of date by some window of time.
	// Populated by the system.
	// Read-only.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
	// +optional
	Status DaemonSetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

ReplicaSet

// ReplicaSet ensures that a specified number of pod replicas are running at any given time.
type ReplicaSet struct {
	metav1.TypeMeta `json:",inline"`

	// If the Labels of a ReplicaSet are empty, they are defaulted to
	// be the same as the Pod(s) that the ReplicaSet manages.
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Spec defines the specification of the desired behavior of the ReplicaSet.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
	// +optional
	Spec ReplicaSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`

	// Status is the most recently observed status of the ReplicaSet.
	// This data may be out of date by some window of time.
	// Populated by the system.
	// Read-only.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
	// +optional
	Status ReplicaSetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

ControllerRevision


// ControllerRevision implements an immutable snapshot of state data. Clients
// are responsible for serializing and deserializing the objects that contain
// their internal state.
// Once a ControllerRevision has been successfully created, it can not be updated.
// The API Server will fail validation of all requests that attempt to mutate
// the Data field. ControllerRevisions may, however, be deleted. Note that, due to its use by both
// the DaemonSet and StatefulSet controllers for update and rollback, this object is beta. However,
// it may be subject to name and representation changes in future releases, and clients should not
// depend on its stability. It is primarily for internal use by controllers.
type ControllerRevision struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Data is the serialized representation of the state.
	Data runtime.RawExtension `json:"data,omitempty" protobuf:"bytes,2,opt,name=data"`

	// Revision indicates the revision of the state represented by Data.
	Revision int64 `json:"revision" protobuf:"varint,3,opt,name=revision"`
}

1.6.3 - register.go

apps API 类型注册

注册类型:

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&Deployment{},
		&DeploymentList{},
		&StatefulSet{},
		&StatefulSetList{},
		&DaemonSet{},
		&DaemonSetList{},
		&ReplicaSet{},
		&ReplicaSetList{},
		&ControllerRevision{},
		&ControllerRevisionList{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

1.7 - authentication

处理 Kubernetes 集群的 身份认证,确保请求来源的合法性

1.7.1 - 概述

authentication API

介绍

authentication API 的核心功能是处理 Kubernetes 集群的 身份认证,确保请求来源的合法性。

主要职责包括:

  1. 验证请求者身份
    • 确认用户、ServiceAccount 或外部系统的身份凭证
  2. 支持多种认证机制
    • X.509 客户端证书
    • Bearer Token(如 ServiceAccount Token)
    • 身份代理(OIDC、LDAP 等)
  3. 提供认证配置管理
    • 管理 TLS 证书配置
    • 管理 ServiceAccount 的 Token 签发

核心 API 资源类型

authentication.k8s.io/v1 和核心 API 组中定义了以下关键资源:

(1) TokenReview

// 用于验证 Bearer Token 的有效性
type TokenReview struct {
    metav1.TypeMeta `json:",inline"`
    Spec   TokenReviewSpec   `json:"spec"`
    Status TokenReviewStatus `json:"status,omitempty"`
}

关键字段

  • spec.token:待验证的 Token 字符串
  • status.authenticated:验证结果(true/false)
  • status.user:认证通过后的用户信息(用户名、组等)

(2) CertificateSigningRequest (CSR)

// 在 certificates.k8s.io/v1 中定义,但用于认证流程
type CertificateSigningRequest struct {
    metav1.TypeMeta `json:",inline"`
    Spec   CertificateSigningRequestSpec `json:"spec"`
}

关键字段

  • spec.request:PEM 编码的证书签名请求
  • spec.signerName:指定签名用途(如 kubernetes.io/kube-apiserver-client

(3) ServiceAccount

// 在核心 v1 API 中定义,用于 Pod 身份认证
type ServiceAccount struct {
    metav1.TypeMeta `json:",inline"`
    Secrets []ObjectReference `json:"secrets,omitempty"` // 关联的 Token Secret
}

1.7.2 - types.go

authentication API 类型

TokenReview

type TokenReview struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Spec holds information about the request being evaluated
	Spec TokenReviewSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"`

	// Status is filled in by the server and indicates whether the request can be authenticated.
	// +optional
	Status TokenReviewStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

TokenRequest

// TokenRequest requests a token for a given service account.
type TokenRequest struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Spec holds information about the request being evaluated
	Spec TokenRequestSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"`

	// Status is filled in by the server and indicates whether the token can be authenticated.
	// +optional
	Status TokenRequestStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

SelfSubjectReview

// SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request.
// When using impersonation, users will receive the user info of the user being impersonated.  If impersonation or
// request header authentication is used, any extra keys will have their case ignored and returned as lowercase.
type SelfSubjectReview struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
	// Status is filled in by the server with the user attributes.
	Status SelfSubjectReviewStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"`
}

1.7.3 - register.go

authentication API 类型注册

注册类型:

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&TokenReview{},
		&TokenRequest{},
		&SelfSubjectReview{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

1.8 - authorization

决定是否允许某个主体(用户/ServiceAccount/组)执行特定操作

1.8.1 - 概述

authorization API

介绍

authorization API 的核心功能:决定是否允许某个主体(用户/ServiceAccount/组)执行特定操作。

1.8.2 - types.go

authorization API 类型

TokenReview

TokenRequest

// TokenRequest requests a token for a given service account.
type TokenRequest struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Spec holds information about the request being evaluated
	Spec TokenRequestSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"`

	// Status is filled in by the server and indicates whether the token can be authenticated.
	// +optional
	Status TokenRequestStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

SelfSubjectReview

// SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request.
// When using impersonation, users will receive the user info of the user being impersonated.  If impersonation or
// request header authentication is used, any extra keys will have their case ignored and returned as lowercase.
type SelfSubjectReview struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
	// Status is filled in by the server with the user attributes.
	Status SelfSubjectReviewStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"`
}

1.8.3 - register.go

authorization API 类型注册

注册类型:

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&TokenReview{},
		&TokenRequest{},
		&SelfSubjectReview{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}