k8s源码设计模式之Adapter

什么是Adapter

Adapter也就是适配器模式

适配器模式是一种结构型设计模式,它将一个接口转换成另一个客户端所期望的接口,从而使得原本不兼容的接口能够协同工作。适配器模式常常用于将一个旧接口适配成新接口,或将一个外部库的接口适配成当前应用程序所需的接口

适配器模式由三个主要角色组成:客户端、适配器和被适配者。其中,客户端使用目标接口来与适配器交互,适配器将客户端的请求转换为被适配者的请求并进行处理,被适配者则是适配器所需要的接口。

k8s中适配器模式

k8s中有很多不同的资源,对于创建资源,k8s实现了createHandler方法来处理

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
// staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go
// 这里返回http.HandlerFunc
func createHandler(r rest.NamedCreater, scope *RequestScope, admit admission.Interface, includeName bool) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
// For performance tracking purposes.
ctx, span := tracing.Start(ctx, "Create", traceFields(req)...)
defer span.End(500 * time.Millisecond)
...
namespace, name, err := scope.Namer.Name(req)
requestFunc := func() (runtime.Object, error) {
// 调用r实现的Create方法,上层可以实现这个接口实现适配
return r.Create(
ctx,
name,
obj,
rest.AdmissionToValidateObjectFunc(admit, admissionAttributes, scope),
options,
)
}
...
}
}


// CreateNamedResource returns a function that will handle a resource creation with name.
func CreateNamedResource(r rest.NamedCreater, scope *RequestScope, admission admission.Interface) http.HandlerFunc {
return createHandler(r, scope, admission, true)
}

// CreateResource returns a function that will handle a resource creation.
func CreateResource(r rest.Creater, scope *RequestScope, admission admission.Interface) http.HandlerFunc {
return createHandler(&namedCreaterAdapter{r}, scope, admission, false)
}

// 通过namedCreaterAdapter实现Create方法,适配createHandler. createHandler将调用对应的Create方法
type namedCreaterAdapter struct {
rest.Creater
}

func (c *namedCreaterAdapter) Create(ctx context.Context, name string, obj runtime.Object, createValidatingAdmission rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
return c.Creater.Create(ctx, obj, createValidatingAdmission, options)
}

REF:
1.staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go