说明
apiserver对外提供API服务,主要功能是验证处理REST请求,并更新保存在etcd中的相关对象。这篇文章以kubernetes1.5.3进行说明。
代码学习
apiserver的入口是cmd/kube-apiserver/apiserver.go
app.Run()的操作:
- 参数校验
- 加载插件
- m, err := config.Complete().New()为httpserver设置路由
- sharedInformers.Start(wait.NeverStop)启动informer,用于监听pods, nodes, namespaces等组件的事件
- m.GenericAPIServer.PrepareRun().Run(wait.NeverStop)启动http server
k8s设置对象的默认值:pkg/api/<version>/defaults.go
例:
1 | func SetDefaults_Container(obj *Container) { |
验证对象格式:pkg/api/validation/validation.go
1 | // ValidateHasLabel requires that api.ObjectMeta has a Label with key and expectedValue |
api url结构
prefix/group/version/…
例:
/apis/extensions/v1beta1/deployments,prefix=apis group=extensions version=v1beta1
/api/v1,prefix=api group="" version=v1
操作etcd
代码位置:pkg/storage,使用etcd客户端github.com/coreos/etcd/clientv3(v3)/github.com/coreos/etcd/client(v2)
pkg/api/rest/rest.go
声明各个interface,在registerResourceHandlers中做断言
registerResourceHandlers()为path注册handler
action path:namespaces/{namespace}/bindings, verb:POST
action path:componentstatuses, verb:LIST
action path:componentstatuses/{name}, verb:GET
type APIGroupVersion
1 | type APIGroupVersion struct { |
Storage的key(string)是各资源的path,value(rest.Storage)是操作此path的对象
下面的函数从apiGroupInfo.VersionedResourcesStorageMap
中取得storage
1 | func (s *GenericAPIServer) getAPIGroupVersion(apiGroupInfo *APIGroupInfo, groupVersion unversioned.GroupVersion, apiPrefix string) (*apiserver.APIGroupVersion, error) { |
type APIGroupInfo
APIGroupInfo.VersionedResourcesStorageMap
保存group中各version的资源storage
1 | // Info about an API group. |
pkg/registry
代码中对这个包的说明是Package registry implements the storage and system logic for the core of the api server.
以pkg/registry/core/rest/storage_core.go
为例说明
func (c LegacyRESTStorageProvider) NewLegacyRESTStorage(restOptionsGetter genericapiserver.RESTOptionsGetter) (LegacyRESTStorage, genericapiserver.APIGroupInfo, error)
此函数中初始化资源与storage映射的map,部分代码:
1 | restStorageMap := map[string]rest.Storage{ |
pkg/registry/core/pod/etcd/etcd.go
的NewStorage()
中变量storageInterface
1 | func (c completedConfig) New() (*Master, error) { |
1 | // NewRawStorage creates the low level kv storage. This is a work-around for current |
storage.Interface
pkg/storage/etcd/etcd_helper.go
使用etcd v2 api,实现了storage.Interface
pkg/storage/etcd3/store.go
使用etcd v3 api,实现了storage.Interface
编解码etcd存储的数据
pkg/genericapiserver/storage_factory.go
NewStorageCodec()
生成Codec
参考
- https://github.com/kubernetes/kubernetes/blob/release-1.5/docs/design/architecture.md
- https://kubernetes.io/docs/admin/kube-apiserver/
- https://github.com/kubernetes/community/tree/master/contributors/design-proposals
- https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md
- https://github.com/kubernetes/community/blob/master/contributors/devel/api_changes.md
- https://github.com/kubernetes/community/blob/master/contributors/design-proposals/api-group.md