基于版本 1.6.7

k8s使用了go-restful github, 在前面, 已经介绍了container如何初始化的.

这里, 需要关注, api是如何注册进来的. 即, route -> webservice -> container

begin

  • pkg/master/master.go
func (c completedConfig) New() (*Master, error) {

   //  register /api
   m.InstallLegacyAPI(c.Config, c.Config.GenericConfig.RESTOptionsGetter, legacyRESTStorageProvider)
   //  register /apis
   m.InstallAPIs(c.Config.APIResourceConfigSource, c.Config.GenericConfig.RESTOptionsGetter, restStorageProviders...)
}

1. /api

  • pkg/master/master.go
func (m *Master) InstallLegacyAPI(c *Config, restOptionsGetter generic.RESTOptionsGetter, legacyRESTStorageProvider corerest.LegacyRESTStorageProvider) {
    legacyRESTStorage, apiGroupInfo, err := legacyRESTStorageProvider.NewLegacyRESTStorage(restOptionsGetter)
    m.GenericAPIServer.InstallLegacyAPIGroup(genericapiserver.DefaultLegacyAPIPrefix, &apiGroupInfo)
  • vendor/k8s.io/apiserver/pkg/server/genericapiserver.go
func (s *GenericAPIServer) InstallLegacyAPIGroup(apiPrefix string, apiGroupInfo *APIGroupInfo) error {
    s.installAPIResources(apiPrefix, apiGroupInfo)
}

2. /apis

  • pkg/master/master.go
func (m *Master) InstallAPIs(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, restStorageProviders ...RESTStorageProvider) {
    for i := range apiGroupsInfo {
        m.GenericAPIServer.InstallAPIGroup(&apiGroupsInfo[i])   }
}
  • vendor/k8s.io/apiserver/pkg/server/genericapiserver.go
func (s *GenericAPIServer) InstallAPIGroup(apiGroupInfo *APIGroupInfo) error {
    s.installAPIResources(APIGroupPrefix, apiGroupInfo)
}

3. all to installAPIResources

  • vendor/k8s.io/apiserver/pkg/server/genericapiserver.go
func (s *GenericAPIServer) installAPIResources(apiPrefix string, apiGroupInfo *APIGroupInfo) error {
    for _, groupVersion := range apiGroupInfo.GroupMeta.GroupVersions {
        apiGroupVersion.InstallREST(s.HandlerContainer.Container)
    }
}
  • vendor/k8s.io/apiserver/pkg/endpoints/groupversion.go
func (g *APIGroupVersion) InstallREST(container *restful.Container) error {
    installer := g.newInstaller()
    // 新建一个WebService
    ws := installer.NewWebService()

    // 关键, URL注册, add router into ws
    apiResources, registrationErrors := installer.Install(ws)
    lister := g.ResourceLister
    if lister == nil {
        lister = staticLister{apiResources}
    }
    AddSupportedResourcesWebService(g.Serializer, ws, g.GroupVersion, lister)

    // container.add(webservice)
    container.Add(ws)
    return utilerrors.NewAggregate(registrationErrors)
}

在这里

  1. 新建一个WebService
  2. installer.Install(ws)将API 对应的route新建初始化后, 加入到 WebService
  3. WebService加入到Container

完成了router -> webservice -> container的流程

后面, 分析 installer.Install(ws) 具体做了哪些事情(vendor/k8s.io/apiserver/pkg/endpoints/installer.go)