Kubernetes Scheme 与 API 多版本

本文基于 Kubernetes v1.24.0

带着几个问题

  1. kube-apiserver 怎么返回用户指定的版本资源
  2. 不同 api group 怎么做到兼容, 如 apps/v1beta1 下的 StatefulSet 和 apps/v1 下的 StatefulSet
  3. kube-apiserver 如何读取解析 etcd 中的数据

概念

Group and Version and Kinds

当我们谈论到 Kubernetes 的 API 时, 一般都会谈论到 4 个术语: groups, versions, kinds和resources

Groups 和 Versions

Kubernetes 中的API Group只是相关功能的集合, 每个组都有一个或多个版本, (例如 apps/v1 和 apps/vbeta1) 顾名思义, 这些版本允许我们随着时间的推移更改 API 的工作方式.

Kinds 和 Resources

Kinds

每个API group-version包含一个或者多个 API 类型, 我们称之为Kinds. 虽然同类型Kind在不同的version之间的表现形式可能不同,但是同类型Kind必须能够存储其他Kind的全部数据, 也就是说同类型Kind之间必须是互相兼容的(我们可以把数据存到 fields 或者 annotations), 这样当你使用老版本的API group-version时不会造成丢失或损坏.

Resources

Resource是Kind在 API 中的标识, 通常情况下Kind和Resource是一一对应的, 但是有时候相同的Kind可能对应多个Resources, 比如 Scale Kind 可能对应很多 Resources: deployments/scale 或者 replicasets/scale, 但是在 CRD 中, 每个Kind只会对应一种Resource.

Resource始终是小写形式, 并且通常情况下是Kind的小写形式.

kube-apiserver 对 API 多版本兼容的要求

参见 Kubernetes API 弃用策略 #规则2

在给定的发布版本中, API 对象必须能够在不同的 API 版本之间来回转换且不造成信息丢失, 除非整个 REST 资源在某些版本中完全不存在.

例如, 一个对象可被用 v1 来写入之后用 v2 来读出并转换为 v1, 所得到的 v1 必须与原来的 v1 对象完全相同. v2 中的表现形式可能与 v1 不同, 但系统知道如何在两个版本之间执行双向转换. 此外, v2 中添加的所有新字段都必须能够转换为 v1 再转换回来. 这意味着 v1 必须添加一个新的等效字段或者将其表现为一个注解.

举个栗子

假设当前一个Kubernetes集群中存在一个StatefulSet, 其名称为 Kayn . 我们分别对 kube-apiserver 发送这样两条请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
curl http://kube-apiserver/apis/apps/**v1beta1**/namespaces/default/statefulsets/kayn
{
"kind": "StatefulSet",
"apiVersion": "apps/v1beta1",
"metadata": {
"name": "kayn",
"namespace": "default",
"labels": {
"app": "kayn",
}
},
"spec": {
"replicas": 1,
"selector": {
"matchLabels": {
"app": "kayn",
}
...
},
}

curl http://kube-apiserver/apis/apps/**v1**/namespaces/default/statefulsets/kayn
{
"kind": "StatefulSet",
"apiVersion": "apps/v1",
"metadata": {
"name": "kayn",
"namespace": "default",
"labels": {
"app": "kayn",
}
},
"spec": {
"replicas": 1,
"selector": {
"matchLabels": {
"app": "kayn",
}
...
},
}

我们分别请求了 apps group 下 v1beta1 和 v1 两个不同 version 的 StatefulSet 资源, 相应的, kube-apiserver 也返回了对应的 StatefulSet 资源信息.

Runtime内部结构和实现

Scheme

为了同时解决数据对象的序列化、反序列化与多版本数据对象的兼容和转换问题, Kubernetes设计了一套复杂的机制. 为了管理 GVK 和 Golang Type 的关系, K8s 设计了runtime.Scheme这个结构体.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
type Scheme struct {
// gvkToType allows one to figure out the go type of an object with
// the given version and name.
gvkToType map[schema.GroupVersionKind]reflect.Type
// typeToGVK allows one to find metadata for a given go object.
// The reflect.Type we index by should *not* be a pointer.
typeToGVK map[reflect.Type][]schema.GroupVersionKind
// unversionedTypes are transformed without conversion in ConvertToVersion.
unversionedTypes map[reflect.Type]schema.GroupVersionKind
// unversionedKinds are the names of kinds that can be created in the context of any group
// or version
unversionedKinds map[string]reflect.Type
// Map from version and resource to the corresponding func to convert
// resource field labels in that version to internal version.
fieldLabelConversionFuncs map[schema.GroupVersionKind]FieldLabelConversionFunc
// defaulterFuncs is a map to funcs to be called with an object to provide defaulting
// the provided object must be a pointer.
defaulterFuncs map[reflect.Type]func(interface{})
// converter stores all registered conversion functions. It also has
// default converting behavior.
converter *conversion.Converter
// versionPriority is a map of groups to ordered lists of versions for those groups indicating the
// default priorities of these versions as registered in the scheme
versionPriority map[string][]string
// observedVersions keeps track of the order we've seen versions during type registration
observedVersions []schema.GroupVersion
schemeName string
}

我们可以向 Scheme 中注册多种资源类型. Scheme 支持两种资源类型的注册, UnversionedType和KnownType, UnversionedType 无版本资源类型, 例如: metav1.Status、metav1.APIVersions、metav1.APIGroupList、metav1.APIGroup、metav1.APIResourceList; KnownType 是 Kubernetes 中最常见的一种资源注册方法, 通过 scheme.AddKnownTypes 方法注册.

Scheme 还提供了类型转换, 类型默认值等方法.

Scheme 资源类型的注册

以 apps/v1 下的资源注册为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// GroupName is the group name use in this package
const GroupName = "apps"

// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1beta1"}

var (
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)

// Adds the list of known types to the given scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Deployment{},
&DeploymentList{},
&DeploymentRollback{},
&Scale{},
&StatefulSet{},
&StatefulSetList{},
&ControllerRevision{},
&ControllerRevisionList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

Scheme 的AddKnownTypes方法是对gvkToType和typeToGVK这两个 map 的更改. 由这两个 map 的定义我们可知: 一个 GVK 只能对应一个 Type , 一个 Type 可能对应多个 GVK .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func (s *Scheme) AddKnownTypeWithName(gvk schema.GroupVersionKind, obj Object) {
...
if oldT, found := s.gvkToType[gvk]; found && oldT != t {
panic(fmt.Sprintf("Double registration of different types for %v: old=%v.%v, new=%v.%v in scheme %q", gvk, oldT.PkgPath(), oldT.Name(), t.PkgPath(), t.Name(), s.schemeName))
}

s.gvkToType[gvk] = t

for _, existingGvk := range s.typeToGVK[t] {
if existingGvk == gvk {
return
}
}
s.typeToGVK[t] = append(s.typeToGVK[t], gvk)

// if the type implements DeepCopyInto(<obj>), register a self-conversion
if m := reflect.ValueOf(obj).MethodByName("DeepCopyInto"); m.IsValid() && m.Type().NumIn() == 1 && m.Type().NumOut() == 0 && m.Type().In(0) == reflect.TypeOf(obj) {
if err := s.AddGeneratedConversionFunc(obj, obj, func(a, b interface{}, scope conversion.Scope) error {
// copy a to b
reflect.ValueOf(a).MethodByName("DeepCopyInto").Call([]reflect.Value{reflect.ValueOf(b)})
// clear TypeMeta to match legacy reflective conversion
b.(Object).GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{})
return nil
}); err != nil {
panic(err)
}
}
}

Scheme Defaulter

defaulterFuncs存储 Type 及其对应的默认值设置函数. 在初始化阶段通过 scheme.AddTypeDefaultingFunc函数注册. 举个栗子, 当我们创建一个 apps/v1beta1 StatefulSet 时, 如果我们未为 StatefulSet 添加 Label , 那么 defaultFunc 就会从Spec.Selector中取值作为 StatefulSet 的默认 Label .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func SetDefaults_StatefulSet(obj *appsv1beta1.StatefulSet) {
...
labels := obj.Spec.Template.Labels
if labels != nil {
if obj.Spec.Selector == nil {
obj.Spec.Selector = &metav1.LabelSelector{
MatchLabels: labels,
}
}
if len(obj.Labels) == 0 {
obj.Labels = labels
}
}
...
}

Scheme Converter

Scheme Converter 主要用于解决多资源版本转换问题. K8s 系统中的一个资源支持多个资源版本, 如果要在每个资源版本之间转换, 最直接的方式是, 每个资源版本都支持其他资源版本的转换, 但这样处理起来非常麻烦. 例如, 某个资源对象支持3个资源版本, 那么就需要提前定义一个资源版本转换到其他两个资源版本(v1→v1alpha1, v1→v1beta1)(v1alpha1→v1, v1alpha1→v1beta1) 及(v1beta1→v1, v1beta1→v1alpha1), 随着资源版本的增加, 资源版本转换的定义会越来越多. 为了解决这个问题, K8s通过内部版本(Internal Version)机制实现资源版本转换.

资源内部版本的 Version 固定为__internal

1
2
3
4
5
6
const (
// APIVersionInternal may be used if you are registering a type that should not
// be considered stable or serialized - it is a convention only and has no
// special behavior in this package.
APIVersionInternal = "__internal"
)

Convert 函数的注册

Convert Func 主要通过两种方法向 Scheme 中注册:

1
2
3
4
5
6
7
8
9
10
11
12
13
// AddConversionFunc registers a function that converts between a and b by passing objects of those
// types to the provided function. The function *must* accept objects of a and b - this machinery will not enforce
// any other guarantee.
func (s *Scheme) AddConversionFunc(a, b interface{}, fn conversion.ConversionFunc) error {
return s.converter.RegisterUntypedConversionFunc(a, b, fn)
}

// AddGeneratedConversionFunc registers a function that converts between a and b by passing objects of those
// types to the provided function. The function *must* accept objects of a and b - this machinery will not enforce
// any other guarantee.
func (s *Scheme) AddGeneratedConversionFunc(a, b interface{}, fn conversion.ConversionFunc) error {
return s.converter.RegisterGeneratedUntypedConversionFunc(a, b, fn)
}

每一个资源只需要注册两种 Convert Func 即可完成注册: 自身到内部版本的 Convert Func , 内部版本到自身的 Convert Func . 以 apps/v1 StatefulSet 的 Convert Func 注册为例:

1
2
3
4
5
6
7
8
9
10
if err := s.AddGeneratedConversionFunc((*v1.StatefulSet)(nil), (*apps.StatefulSet)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_StatefulSet_To_apps_StatefulSet(a.(*v1.StatefulSet), b.(*apps.StatefulSet), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*apps.StatefulSet)(nil), (*v1.StatefulSet)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_apps_StatefulSet_To_v1_StatefulSet(a.(*apps.StatefulSet), b.(*v1.StatefulSet), scope)
}); err != nil {
return err
}

RestMapper

当我们要定义一个 GVR 的时候, 怎么知道这个 GVR 是属于哪个 GVK 的呢? 举个例子, kubectl 是如何从 YAML 描述文件中知道该请求的是哪个 GVR URL? 这就是 REST Mapping 的功能, REST Mapping 可以指定一个 GVR, 然后它返回对应的 GVK 以及支持的操作等.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// RESTMapper allows clients to map resources to kind, and map kind and version
// to interfaces for manipulating those objects. It is primarily intended for
// consumers of Kubernetes compatible REST APIs as defined in docs/devel/api-conventions.md.
//
// The Kubernetes API provides versioned resources and object kinds which are scoped
// to API groups. In other words, kinds and resources should not be assumed to be
// unique across groups.
//
// TODO: split into sub-interfaces
type RESTMapper interface {
// KindFor takes a partial resource and returns the single match. Returns an error if there are multiple matches
KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)

// KindsFor takes a partial resource and returns the list of potential kinds in priority order
KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error)

// ResourceFor takes a partial resource and returns the single match. Returns an error if there are multiple matches
ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error)

// ResourcesFor takes a partial resource and returns the list of potential resource in priority order
ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error)

// RESTMapping identifies a preferred resource mapping for the provided group kind.
RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error)
// RESTMappings returns all resource mappings for the provided group kind if no
// version search is provided. Otherwise identifies a preferred resource mapping for
// the provided version(s).
RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error)

ResourceSingularizer(resource string) (singular string, err error)
}

Codec 和 Serializer

Codec编解码器是一个通用的术语, 包含编码器和解码器, 表示将数据转换为特定格式的过程, 在 K8s 中主要负责将 etcd 中的数据进行编码和解码操作.

Serializer是序列化器, 包含序列化和反序列化操作, 序列化操作是将数据转为字符串的操作, 反序列化是将字符串转为数据的过程.

Serializer 算是 Codec 编码器的一种, 因为每种 Serializer 序列化器都实现了 Encoder 和 Decoder 接口, 只要实现 Encoder 和 Decoder 接口方法的数据结构的都是序列化器.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Serializer is the core interface for transforming objects into a serialized format and back.
// Implementations may choose to perform conversion of the object, but no assumptions should be made.
type Serializer interface {
Encoder
Decoder
}

// Codec is a Serializer that deals with the details of versioning objects. It offers the same
// interface as Serializer, so this is a marker to consumers that care about the version of the objects
// they receive.
type Codec Serializer

// ParameterCodec defines methods for serializing and deserializing API objects to url.Values and
// performing any necessary conversion. Unlike the normal Codec, query parameters are not self describing
// and the desired version must be specified.
type ParameterCodec interface {
// DecodeParameters takes the given url.Values in the specified group version and decodes them
// into the provided object, or returns an error.
DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error
// EncodeParameters encodes the provided object as query parameters or returns an error.
EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error)
}

使用Scheme进行编解码和资源转换

因为 Kubernetes 中对 Scheme 的使用分散在各个角落, 我们这里直接选用 Scheme 的测试文件k8s.io/apimachinery/pkg/runtime/scheme_test.go为例来说明如何使用 Scheme

资源注册

1
2
3
4
5
6
7
8
9
internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal}
internalGVK := internalGV.WithKind("Simple")
externalGV := schema.GroupVersion{Group: "test.group", Version: "testExternal"}
externalGVK := externalGV.WithKind("Simple")

scheme := runtime.NewScheme()
scheme.AddKnownTypeWithName(internalGVK, &runtimetesting.InternalSimple{})
scheme.AddKnownTypeWithName(externalGVK, &runtimetesting.ExternalSimple{})
utilruntime.Must(runtimetesting.RegisterConversions(scheme))
  1. 测试用例中定义了两种测试资源类型, 其 Kind 都为 Simple , runtime.APIVersionInternal 是 Kubernetes 用来标识内部版本的一个约定字段, 其值为__internal; 所以现在我们拥有了两个不同的GVK:test.group/__internal和test.group/testExternal
  2. runtime.NewScheme()创建一个默认的 scheme 结构
  3. 调用scheme.AddKnownTypeWithName方法将 GVK 和其对应的结构体注册到 scheme 中
  4. RegisterConversions中注册了InternalSimple与ExternalSimple之间的 ConversionFunc
1
2
3
4
5
6
7
8
9
10
if err := s.AddConversionFunc((*InternalExtensionType)(nil), (*ExternalExtensionType)(nil), func(a, b interface{}, scope conversion.Scope) error {
return convertInternalExtensionTypeToExternalExtensionType(a.(*InternalExtensionType), b.(*ExternalExtensionType), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*ExternalExtensionType)(nil), (*InternalExtensionType)(nil), func(a, b interface{}, scope conversion.Scope) error {
return convertExternalExtensionTypeToInternalExtensionType(a.(*ExternalExtensionType), b.(*InternalExtensionType), scope)
}); err != nil {
return err
}

编解码

获取Codec与Serializer

1
2
3
4
codecs := serializer.NewCodecFactory(scheme)
codec := codecs.LegacyCodec(externalGV)
info, _ := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), runtime.ContentTypeJSON)
jsonserializer := info.Serializer
  1. serializer.NewCodecFactory方法接收一个 scheme , 生成一个 CodecFactory , 其中默认包含了jsonSerializer, yamlSerializer, protoSerializer等格式的 Serializer
  2. codecs.LegacyCodec(externalGV)生成一个 codec , 其
    1. encoder通常为一个jsonSerializer, 将 obj 编码为 json 格式
    2. decoder为一个能解析上述NewCodecFactory中注册的多种格式的 decoder 集合.
    3. convertor, creater, typer, defaulter等接口都由 scheme 实现
    4. encodeVersion置为externalGV
    5. decodeVersion置为__internal, 即调用该 codec 默认使用 obj 的__internal版本进行 decode
  3. 调用runtime.SerializerInfoForMediaType方法从codecs中获取一个jsonserializer以便后续测试

Encode和Decode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
simple := &runtimetesting.InternalSimple{
TestString: "foo",
}

obj := runtime.Object(simple)
data, err := runtime.Encode(codec, obj)
if err != nil {
t.Fatal(err)
}

obj2, err := runtime.Decode(codec, data)
if err != nil {
t.Fatal(err)
}
if _, ok := obj2.(*runtimetesting.InternalSimple); !ok {
t.Fatalf("Got wrong type")
}
if e, a := simple, obj2; !reflect.DeepEqual(e, a) {
t.Errorf("Expected:\n %#v,\n Got:\n %#v", e, a)
}

...

初始化一个 InternalSimple 结构进行测试

Encode

  1. runtime.Encode(codec, obj)会调用codec.doEncode方法
    1. c.convertor.ConvertToVersion最终会调用scheme.converter.Convert方法, scheme 会在自身的conversionFuncs和generatedConversionFuncs这两个 map 中寻找对应的 ConversionFuncs(也就是上面我们向 scheme 中注册的转换函数) 对 obj 进行转换
    2. c.encoder.Encode对应各个 serializer 的 Encode 方法, 如jsonSerializer的 Encode 方法为json.Marshal🥱
  2. 经过上述的操作(记住上述codec的encodeVersion被置为了externalGV), encode 的 data 为: {"apiVersion":"test.group/testExternal","kind":"Simple","testString":"foo"}
1
2
3
4
5
6
7
8
9
10
11
12
13
// 只显示了部分逻辑
func (c *codec) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {
encodeFn := c.encoder.Encode

// Perform a conversion if necessary
out, err := c.convertor.ConvertToVersion(obj, c.encodeVersion)
if err != nil {
return err
}

// Conversion is responsible for setting the proper group, version, and kind onto the outgoing object
return encodeFn(out, w)
}

Decode

  1. runtime.Decode(codec, data)会调用codec.Decode方法, 该方法尝试解码入参为一个对象, 然后将其转化为内部版本对象
    1. codec 的decoder是一个 serializer slice, 一般包含 json, yaml, protobuf 这三者的 serializer

    2. 调用codec.decoder.Decode会根据入参的数据格式调用对应 serializer 的Decode方法, 此处使用的是 json serializer

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
      data := originalData
      if s.options.Yaml {
      altered, err := yaml.YAMLToJSON(data)
      if err != nil {
      return nil, nil, err
      }
      data = altered
      }

      actual, err := s.meta.Interpret(data)
      if err != nil {
      return nil, nil, err
      }

      if gvk != nil {
      *actual = gvkWithDefaults(*actual, *gvk)
      }

      // use the target if necessary
      obj, err := runtime.UseOrCreateObject(s.typer, s.creater, *actual, into)
      if err != nil {
      return nil, actual, err
      }

      strictErrs, err := s.unmarshal(obj, data, originalData)
      if err != nil {
      return nil, actual, err
      } else if len(strictErrs) > 0 {
      return obj, actual, runtime.NewStrictDecodingError(strictErrs)
      }
      return obj, actual, nil
      }
      1. serializer.Decode 首先调用SimpleMetaFactory.Interpret获取 data 的真实类型, 该方法其实进行了一次对 APIVersion 和 Kind 的尝试性的json.Unmarshal
      2. 如果没有指定into对象, 就通过actual的 GVK 生成一个对象, s.typer 和 s.creater 都是一个 Scheme .
      3. 执行真正的unmarshal方法反序列化数据
    3. 此时已经解码完成, 调用codec.defaulter的Default方法进行默认值设置

    4. 最终调用codec.convertor的ConvertToVersion方法, 通过注册到 Scheme 中对应的 Convert Func 将对象转换为 decodeVersion 版本的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
func (c *codec) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
decodeInto := into

obj, gvk, err := c.decoder.Decode(data, defaultGVK, decodeInto)
if err != nil {
if strictErr, ok := runtime.AsStrictDecodingError(err); obj != nil && ok {
// save the strictDecodingError and let the caller decide what to do with it
strictDecodingErrs = append(strictDecodingErrs, strictErr.Errors()...)
} else {
return nil, gvk, err
}
}

// if we specify a target, use generic conversion.
if into != nil {
// perform defaulting if requested
if c.defaulter != nil {
c.defaulter.Default(obj)
}

// Short-circuit conversion if the into object is same object
if into == obj {
return into, gvk, strictDecodingErr
}

if err := c.convertor.Convert(obj, into, c.decodeVersion); err != nil {
return nil, gvk, err
}

return into, gvk, strictDecodingErr
}

// perform defaulting if requested
if c.defaulter != nil {
c.defaulter.Default(obj)
}

out, err := c.convertor.ConvertToVersion(obj, c.decodeVersion)
if err != nil {
return nil, gvk, err
}
return out, gvk, strictDecodingErr
}

一个完整的GET请求

设想我们执行了如下命令:

1
curl --request GET --url http://{APISERVER_ADDR}/apis/apps/v1/namespaces/default/statefulsets/xxx

该命令向 apiserver 发送了一个 GET 请求, 用以获取某一 StatefulSet 对象.

该次 HTTP 请求会由getResourceHandler进行处理.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// getResourceHandler is an HTTP handler function for get requests. It delegates to the
// passed-in getterFunc to perform the actual get.
func getResourceHandler(scope *RequestScope, getter getterFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
...
namespace, name, err := scope.Namer.Name(req)
if err != nil {
scope.err(err, w, req)
return
}
ctx := req.Context()
ctx = request.WithNamespace(ctx, namespace)

outputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)
if err != nil {
scope.err(err, w, req)
return
}

result, err := getter(ctx, name, req, trace)
if err != nil {
scope.err(err, w, req)
return
}

trace.Step("About to write a response")
defer trace.Step("Writing http response done")
transformResponseObject(ctx, scope, trace, req, w, http.StatusOK, outputMediaType, result)
}
}

getResourceHandler的流程主要分为三部分:

  1. 根据请求信息获取输出类型outputMediaType
  2. 通过执行getter函数从 ETCD 中获取具体存储的对象, 这里会将读取到的对象转为内部版本对象
  3. 执行transformResponseObject对内部版本对象转换并返回结果

存储版本和“内存”版本

首先来看下 Kubernetes 定义的DefaultResourceEncodingConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func (o *DefaultResourceEncodingConfig) StorageEncodingFor(resource schema.GroupResource) (schema.GroupVersion, error) {
if !o.scheme.IsGroupRegistered(resource.Group) {
return schema.GroupVersion{}, fmt.Errorf("group %q is not registered in scheme", resource.Group)
}

resourceOverride, resourceExists := o.resources[resource]
if resourceExists {
return resourceOverride.ExternalResourceEncoding, nil
}

// return the most preferred external version for the group
return o.scheme.PrioritizedVersionsForGroup(resource.Group)[0], nil
}

func (o *DefaultResourceEncodingConfig) InMemoryEncodingFor(resource schema.GroupResource) (schema.GroupVersion, error) {
if !o.scheme.IsGroupRegistered(resource.Group) {
return schema.GroupVersion{}, fmt.Errorf("group %q is not registered in scheme", resource.Group)
}

resourceOverride, resourceExists := o.resources[resource]
if resourceExists {
return resourceOverride.InternalResourceEncoding, nil
}
return schema.GroupVersion{Group: resource.Group, Version: runtime.APIVersionInternal}, nil
}

可以看到

  • 存储版本指定为scheme.PrioritizedVersionsForGroup(resource.Group)[0], 该优先级在注册 Scheme 时通过scheme.SetVersionPriority设置, 如appsgroup 的设置为 scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta2.SchemeGroupVersion, v1beta1.SchemeGroupVersion), 即指明v1version 为默认的存储版本
  • 无论 ETCD 中存储的是何种版本的对象, 在解码器解码之后在内存中都会变为内部版本, 即 version 为runtime.APIVersionInternal

从 ETCD 中读取并转化对象

  1. Store.Get方法负责从 ETCD 中读取对象
  2. Store.NewFunc方法在此次请求中对应func() runtime.Object { return &apps.StatefulSet{} }, 注意这个是内部版本的 StatefulSet 对象
  3. 通过Store.KeyFunc方法获取存储 Key , 此次请求对应的 Key 为/statefulsets/default/xxx
  4. Store.Storage.Get方法真正执行从 ETCD 进行读取的操作, 读取后进行一次decode(k8s.io/apiserver/pkg/storage/etcd3/store.go)转换. 该次 decode 使用的codec由DefaultStorageFactory.NewConfig(k8s.io/apiserver/pkg/server/storage/storage_factory.go)初始化, 其 encodeVersion 和 decodeVersion 分别被设置为 apps/v1 和 apps/__internal (默认的存储版本和内存版本)
  5. 返回一个内部版本的 StatefulSet 对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Get retrieves the item from storage.
func (e *Store) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
obj := e.NewFunc()
key, err := e.KeyFunc(ctx, name)
if err != nil {
return nil, err
}
if err := e.Storage.Get(ctx, key, storage.GetOptions{ResourceVersion: options.ResourceVersion}, obj); err != nil {
return nil, storeerr.InterpretGetError(err, e.qualifiedResourceFromContext(ctx), name)
}
if e.Decorator != nil {
e.Decorator(obj)
}
return obj, nil
}

转化为对应的版本并返回

  1. transformResponseObject最终会调用WriteObjectNegotiated方法转化并返回数据
  2. 通过negotiation.NegotiateOutputMediaType方法从该次 HTTP 请求中获取对应合适的 serializer
  3. 通过EncoderForVersion方法根据 serializer 获取对应的 codec 以便于后续的 encode
  4. 最终SerializeObject会执行encoder.Encode(object, w), 其中入参w为一个特殊的 http.ResponseWriter, 执行完成后即完成了转换及返回 Client 数据的操作
1
2
3
4
5
6
7
8
9
10
11
func WriteObjectNegotiated(s runtime.NegotiatedSerializer, restrictions negotiation.EndpointRestrictions, gv schema.GroupVersion, w http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object) {
_, serializer, err := negotiation.NegotiateOutputMediaType(req, s, restrictions)
if err != nil {
...
}

encoder := s.EncoderForVersion(serializer.Serializer, gv)
endpointsrequest.TrackSerializeResponseObjectLatency(req.Context(), func() {
SerializeObject(serializer.MediaType, encoder, w, req, statusCode, object)
})
}

一个 POST 请求中版本转换的图示


ref: https://pt.slideshare.net/sttts/kubernetes-api-deep-dive-into-the-kubeapiserver/8

Client 使用 Scheme 的两种风格

上文主要说明的是 Scheme 在 kube-apiserver 端的应用, 在我们平日与 Kubernetes 交互的 Client 中, Scheme 也是无处不在的.

当我们定义了一个 CRD , 将其安装到 Kubernetes 集群中后, 我们想编程以对其进行 CURD 等等操作, 一般有两种姿势:

生成静态 Client

通过 https://github.com/kubernetes/code-generator 生成 Client 代码, 项目引用 Client 后进行相关操作, 其 API 风格类似于

1
obj, err := pkg.{GROUP}.{VERSION}.{KIND}.Get(ctx, name, options)

其 Scheme 注册流程通常为:

1
2
3
4
5
6
7
8
9
10
11
12
13
var Scheme = runtime.NewScheme()
var Codecs = serializer.NewCodecFactory(Scheme)
var ParameterCodec = runtime.NewParameterCodec(Scheme)
var localSchemeBuilder = runtime.SchemeBuilder{
// 此处注册资源的Scheme
xxx.AddToScheme,
}
var AddToScheme = localSchemeBuilder.AddToScheme

func init() {
v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
utilruntime.Must(AddToScheme(Scheme))
}

使用动态 Client

通过类似 https://github.com/kubernetes-sigs/controller-runtime 的风格对 Kubernetes 对象进行操作, 其 API 风格类似于

1
err := client.Get(ctx, req.NamespacedName, &obj)

其无需生成相关 Client 代码, 唯一需要的一般是在程序初始化时将相关资源的 Scheme 注册到 controller-runtime Client 的 Scheme 中. 且其默认注册了kubernetes/scheme/register.go中的所有资源, 即 Kubernetes 原生资源都可直接操作