discovery_client.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package discovery
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "net/url"
  19. "sort"
  20. "strings"
  21. "sync"
  22. "time"
  23. "github.com/golang/protobuf/proto"
  24. openapi_v2 "github.com/googleapis/gnostic/openapiv2"
  25. "k8s.io/apimachinery/pkg/api/errors"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/runtime"
  28. "k8s.io/apimachinery/pkg/runtime/schema"
  29. "k8s.io/apimachinery/pkg/runtime/serializer"
  30. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  31. "k8s.io/apimachinery/pkg/version"
  32. "k8s.io/client-go/kubernetes/scheme"
  33. restclient "k8s.io/client-go/rest"
  34. )
  35. const (
  36. // defaultRetries is the number of times a resource discovery is repeated if an api group disappears on the fly (e.g. ThirdPartyResources).
  37. defaultRetries = 2
  38. // protobuf mime type
  39. mimePb = "application/com.github.proto-openapi.spec.v2@v1.0+protobuf"
  40. // defaultTimeout is the maximum amount of time per request when no timeout has been set on a RESTClient.
  41. // Defaults to 32s in order to have a distinguishable length of time, relative to other timeouts that exist.
  42. defaultTimeout = 32 * time.Second
  43. )
  44. // DiscoveryInterface holds the methods that discover server-supported API groups,
  45. // versions and resources.
  46. type DiscoveryInterface interface {
  47. RESTClient() restclient.Interface
  48. ServerGroupsInterface
  49. ServerResourcesInterface
  50. ServerVersionInterface
  51. OpenAPISchemaInterface
  52. }
  53. // CachedDiscoveryInterface is a DiscoveryInterface with cache invalidation and freshness.
  54. // Note that If the ServerResourcesForGroupVersion method returns a cache miss
  55. // error, the user needs to explicitly call Invalidate to clear the cache,
  56. // otherwise the same cache miss error will be returned next time.
  57. type CachedDiscoveryInterface interface {
  58. DiscoveryInterface
  59. // Fresh is supposed to tell the caller whether or not to retry if the cache
  60. // fails to find something (false = retry, true = no need to retry).
  61. //
  62. // TODO: this needs to be revisited, this interface can't be locked properly
  63. // and doesn't make a lot of sense.
  64. Fresh() bool
  65. // Invalidate enforces that no cached data that is older than the current time
  66. // is used.
  67. Invalidate()
  68. }
  69. // ServerGroupsInterface has methods for obtaining supported groups on the API server
  70. type ServerGroupsInterface interface {
  71. // ServerGroups returns the supported groups, with information like supported versions and the
  72. // preferred version.
  73. ServerGroups() (*metav1.APIGroupList, error)
  74. }
  75. // ServerResourcesInterface has methods for obtaining supported resources on the API server
  76. type ServerResourcesInterface interface {
  77. // ServerResourcesForGroupVersion returns the supported resources for a group and version.
  78. ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error)
  79. // ServerResources returns the supported resources for all groups and versions.
  80. //
  81. // The returned resource list might be non-nil with partial results even in the case of
  82. // non-nil error.
  83. //
  84. // Deprecated: use ServerGroupsAndResources instead.
  85. ServerResources() ([]*metav1.APIResourceList, error)
  86. // ServerResources returns the supported groups and resources for all groups and versions.
  87. //
  88. // The returned group and resource lists might be non-nil with partial results even in the
  89. // case of non-nil error.
  90. ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)
  91. // ServerPreferredResources returns the supported resources with the version preferred by the
  92. // server.
  93. //
  94. // The returned group and resource lists might be non-nil with partial results even in the
  95. // case of non-nil error.
  96. ServerPreferredResources() ([]*metav1.APIResourceList, error)
  97. // ServerPreferredNamespacedResources returns the supported namespaced resources with the
  98. // version preferred by the server.
  99. //
  100. // The returned resource list might be non-nil with partial results even in the case of
  101. // non-nil error.
  102. ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error)
  103. }
  104. // ServerVersionInterface has a method for retrieving the server's version.
  105. type ServerVersionInterface interface {
  106. // ServerVersion retrieves and parses the server's version (git version).
  107. ServerVersion() (*version.Info, error)
  108. }
  109. // OpenAPISchemaInterface has a method to retrieve the open API schema.
  110. type OpenAPISchemaInterface interface {
  111. // OpenAPISchema retrieves and parses the swagger API schema the server supports.
  112. OpenAPISchema() (*openapi_v2.Document, error)
  113. }
  114. // DiscoveryClient implements the functions that discover server-supported API groups,
  115. // versions and resources.
  116. type DiscoveryClient struct {
  117. restClient restclient.Interface
  118. LegacyPrefix string
  119. }
  120. // Convert metav1.APIVersions to metav1.APIGroup. APIVersions is used by legacy v1, so
  121. // group would be "".
  122. func apiVersionsToAPIGroup(apiVersions *metav1.APIVersions) (apiGroup metav1.APIGroup) {
  123. groupVersions := []metav1.GroupVersionForDiscovery{}
  124. for _, version := range apiVersions.Versions {
  125. groupVersion := metav1.GroupVersionForDiscovery{
  126. GroupVersion: version,
  127. Version: version,
  128. }
  129. groupVersions = append(groupVersions, groupVersion)
  130. }
  131. apiGroup.Versions = groupVersions
  132. // There should be only one groupVersion returned at /api
  133. apiGroup.PreferredVersion = groupVersions[0]
  134. return
  135. }
  136. // ServerGroups returns the supported groups, with information like supported versions and the
  137. // preferred version.
  138. func (d *DiscoveryClient) ServerGroups() (apiGroupList *metav1.APIGroupList, err error) {
  139. // Get the groupVersions exposed at /api
  140. v := &metav1.APIVersions{}
  141. err = d.restClient.Get().AbsPath(d.LegacyPrefix).Do(context.TODO()).Into(v)
  142. apiGroup := metav1.APIGroup{}
  143. if err == nil && len(v.Versions) != 0 {
  144. apiGroup = apiVersionsToAPIGroup(v)
  145. }
  146. if err != nil && !errors.IsNotFound(err) && !errors.IsForbidden(err) {
  147. return nil, err
  148. }
  149. // Get the groupVersions exposed at /apis
  150. apiGroupList = &metav1.APIGroupList{}
  151. err = d.restClient.Get().AbsPath("/apis").Do(context.TODO()).Into(apiGroupList)
  152. if err != nil && !errors.IsNotFound(err) && !errors.IsForbidden(err) {
  153. return nil, err
  154. }
  155. // to be compatible with a v1.0 server, if it's a 403 or 404, ignore and return whatever we got from /api
  156. if err != nil && (errors.IsNotFound(err) || errors.IsForbidden(err)) {
  157. apiGroupList = &metav1.APIGroupList{}
  158. }
  159. // prepend the group retrieved from /api to the list if not empty
  160. if len(v.Versions) != 0 {
  161. apiGroupList.Groups = append([]metav1.APIGroup{apiGroup}, apiGroupList.Groups...)
  162. }
  163. return apiGroupList, nil
  164. }
  165. // ServerResourcesForGroupVersion returns the supported resources for a group and version.
  166. func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (resources *metav1.APIResourceList, err error) {
  167. url := url.URL{}
  168. if len(groupVersion) == 0 {
  169. return nil, fmt.Errorf("groupVersion shouldn't be empty")
  170. }
  171. if len(d.LegacyPrefix) > 0 && groupVersion == "v1" {
  172. url.Path = d.LegacyPrefix + "/" + groupVersion
  173. } else {
  174. url.Path = "/apis/" + groupVersion
  175. }
  176. resources = &metav1.APIResourceList{
  177. GroupVersion: groupVersion,
  178. }
  179. err = d.restClient.Get().AbsPath(url.String()).Do(context.TODO()).Into(resources)
  180. if err != nil {
  181. // ignore 403 or 404 error to be compatible with an v1.0 server.
  182. if groupVersion == "v1" && (errors.IsNotFound(err) || errors.IsForbidden(err)) {
  183. return resources, nil
  184. }
  185. return nil, err
  186. }
  187. return resources, nil
  188. }
  189. // ServerResources returns the supported resources for all groups and versions.
  190. // Deprecated: use ServerGroupsAndResources instead.
  191. func (d *DiscoveryClient) ServerResources() ([]*metav1.APIResourceList, error) {
  192. _, rs, err := d.ServerGroupsAndResources()
  193. return rs, err
  194. }
  195. // ServerGroupsAndResources returns the supported resources for all groups and versions.
  196. func (d *DiscoveryClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  197. return withRetries(defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  198. return ServerGroupsAndResources(d)
  199. })
  200. }
  201. // ErrGroupDiscoveryFailed is returned if one or more API groups fail to load.
  202. type ErrGroupDiscoveryFailed struct {
  203. // Groups is a list of the groups that failed to load and the error cause
  204. Groups map[schema.GroupVersion]error
  205. }
  206. // Error implements the error interface
  207. func (e *ErrGroupDiscoveryFailed) Error() string {
  208. var groups []string
  209. for k, v := range e.Groups {
  210. groups = append(groups, fmt.Sprintf("%s: %v", k, v))
  211. }
  212. sort.Strings(groups)
  213. return fmt.Sprintf("unable to retrieve the complete list of server APIs: %s", strings.Join(groups, ", "))
  214. }
  215. // IsGroupDiscoveryFailedError returns true if the provided error indicates the server was unable to discover
  216. // a complete list of APIs for the client to use.
  217. func IsGroupDiscoveryFailedError(err error) bool {
  218. _, ok := err.(*ErrGroupDiscoveryFailed)
  219. return err != nil && ok
  220. }
  221. // ServerResources uses the provided discovery interface to look up supported resources for all groups and versions.
  222. // Deprecated: use ServerGroupsAndResources instead.
  223. func ServerResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) {
  224. _, rs, err := ServerGroupsAndResources(d)
  225. return rs, err
  226. }
  227. func ServerGroupsAndResources(d DiscoveryInterface) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  228. sgs, err := d.ServerGroups()
  229. if sgs == nil {
  230. return nil, nil, err
  231. }
  232. resultGroups := []*metav1.APIGroup{}
  233. for i := range sgs.Groups {
  234. resultGroups = append(resultGroups, &sgs.Groups[i])
  235. }
  236. groupVersionResources, failedGroups := fetchGroupVersionResources(d, sgs)
  237. // order results by group/version discovery order
  238. result := []*metav1.APIResourceList{}
  239. for _, apiGroup := range sgs.Groups {
  240. for _, version := range apiGroup.Versions {
  241. gv := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}
  242. if resources, ok := groupVersionResources[gv]; ok {
  243. result = append(result, resources)
  244. }
  245. }
  246. }
  247. if len(failedGroups) == 0 {
  248. return resultGroups, result, nil
  249. }
  250. return resultGroups, result, &ErrGroupDiscoveryFailed{Groups: failedGroups}
  251. }
  252. // ServerPreferredResources uses the provided discovery interface to look up preferred resources
  253. func ServerPreferredResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) {
  254. serverGroupList, err := d.ServerGroups()
  255. if err != nil {
  256. return nil, err
  257. }
  258. groupVersionResources, failedGroups := fetchGroupVersionResources(d, serverGroupList)
  259. result := []*metav1.APIResourceList{}
  260. grVersions := map[schema.GroupResource]string{} // selected version of a GroupResource
  261. grAPIResources := map[schema.GroupResource]*metav1.APIResource{} // selected APIResource for a GroupResource
  262. gvAPIResourceLists := map[schema.GroupVersion]*metav1.APIResourceList{} // blueprint for a APIResourceList for later grouping
  263. for _, apiGroup := range serverGroupList.Groups {
  264. for _, version := range apiGroup.Versions {
  265. groupVersion := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}
  266. apiResourceList, ok := groupVersionResources[groupVersion]
  267. if !ok {
  268. continue
  269. }
  270. // create empty list which is filled later in another loop
  271. emptyAPIResourceList := metav1.APIResourceList{
  272. GroupVersion: version.GroupVersion,
  273. }
  274. gvAPIResourceLists[groupVersion] = &emptyAPIResourceList
  275. result = append(result, &emptyAPIResourceList)
  276. for i := range apiResourceList.APIResources {
  277. apiResource := &apiResourceList.APIResources[i]
  278. if strings.Contains(apiResource.Name, "/") {
  279. continue
  280. }
  281. gv := schema.GroupResource{Group: apiGroup.Name, Resource: apiResource.Name}
  282. if _, ok := grAPIResources[gv]; ok && version.Version != apiGroup.PreferredVersion.Version {
  283. // only override with preferred version
  284. continue
  285. }
  286. grVersions[gv] = version.Version
  287. grAPIResources[gv] = apiResource
  288. }
  289. }
  290. }
  291. // group selected APIResources according to GroupVersion into APIResourceLists
  292. for groupResource, apiResource := range grAPIResources {
  293. version := grVersions[groupResource]
  294. groupVersion := schema.GroupVersion{Group: groupResource.Group, Version: version}
  295. apiResourceList := gvAPIResourceLists[groupVersion]
  296. apiResourceList.APIResources = append(apiResourceList.APIResources, *apiResource)
  297. }
  298. if len(failedGroups) == 0 {
  299. return result, nil
  300. }
  301. return result, &ErrGroupDiscoveryFailed{Groups: failedGroups}
  302. }
  303. // fetchServerResourcesForGroupVersions uses the discovery client to fetch the resources for the specified groups in parallel.
  304. func fetchGroupVersionResources(d DiscoveryInterface, apiGroups *metav1.APIGroupList) (map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error) {
  305. groupVersionResources := make(map[schema.GroupVersion]*metav1.APIResourceList)
  306. failedGroups := make(map[schema.GroupVersion]error)
  307. wg := &sync.WaitGroup{}
  308. resultLock := &sync.Mutex{}
  309. for _, apiGroup := range apiGroups.Groups {
  310. for _, version := range apiGroup.Versions {
  311. groupVersion := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}
  312. wg.Add(1)
  313. go func() {
  314. defer wg.Done()
  315. defer utilruntime.HandleCrash()
  316. apiResourceList, err := d.ServerResourcesForGroupVersion(groupVersion.String())
  317. // lock to record results
  318. resultLock.Lock()
  319. defer resultLock.Unlock()
  320. if err != nil {
  321. // TODO: maybe restrict this to NotFound errors
  322. failedGroups[groupVersion] = err
  323. }
  324. if apiResourceList != nil {
  325. // even in case of error, some fallback might have been returned
  326. groupVersionResources[groupVersion] = apiResourceList
  327. }
  328. }()
  329. }
  330. }
  331. wg.Wait()
  332. return groupVersionResources, failedGroups
  333. }
  334. // ServerPreferredResources returns the supported resources with the version preferred by the
  335. // server.
  336. func (d *DiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error) {
  337. _, rs, err := withRetries(defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  338. rs, err := ServerPreferredResources(d)
  339. return nil, rs, err
  340. })
  341. return rs, err
  342. }
  343. // ServerPreferredNamespacedResources returns the supported namespaced resources with the
  344. // version preferred by the server.
  345. func (d *DiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) {
  346. return ServerPreferredNamespacedResources(d)
  347. }
  348. // ServerPreferredNamespacedResources uses the provided discovery interface to look up preferred namespaced resources
  349. func ServerPreferredNamespacedResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) {
  350. all, err := ServerPreferredResources(d)
  351. return FilteredBy(ResourcePredicateFunc(func(groupVersion string, r *metav1.APIResource) bool {
  352. return r.Namespaced
  353. }), all), err
  354. }
  355. // ServerVersion retrieves and parses the server's version (git version).
  356. func (d *DiscoveryClient) ServerVersion() (*version.Info, error) {
  357. body, err := d.restClient.Get().AbsPath("/version").Do(context.TODO()).Raw()
  358. if err != nil {
  359. return nil, err
  360. }
  361. var info version.Info
  362. err = json.Unmarshal(body, &info)
  363. if err != nil {
  364. return nil, fmt.Errorf("unable to parse the server version: %v", err)
  365. }
  366. return &info, nil
  367. }
  368. // OpenAPISchema fetches the open api schema using a rest client and parses the proto.
  369. func (d *DiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error) {
  370. data, err := d.restClient.Get().AbsPath("/openapi/v2").SetHeader("Accept", mimePb).Do(context.TODO()).Raw()
  371. if err != nil {
  372. if errors.IsForbidden(err) || errors.IsNotFound(err) || errors.IsNotAcceptable(err) {
  373. // single endpoint not found/registered in old server, try to fetch old endpoint
  374. // TODO: remove this when kubectl/client-go don't work with 1.9 server
  375. data, err = d.restClient.Get().AbsPath("/swagger-2.0.0.pb-v1").Do(context.TODO()).Raw()
  376. if err != nil {
  377. return nil, err
  378. }
  379. } else {
  380. return nil, err
  381. }
  382. }
  383. document := &openapi_v2.Document{}
  384. err = proto.Unmarshal(data, document)
  385. if err != nil {
  386. return nil, err
  387. }
  388. return document, nil
  389. }
  390. // withRetries retries the given recovery function in case the groups supported by the server change after ServerGroup() returns.
  391. func withRetries(maxRetries int, f func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  392. var result []*metav1.APIResourceList
  393. var resultGroups []*metav1.APIGroup
  394. var err error
  395. for i := 0; i < maxRetries; i++ {
  396. resultGroups, result, err = f()
  397. if err == nil {
  398. return resultGroups, result, nil
  399. }
  400. if _, ok := err.(*ErrGroupDiscoveryFailed); !ok {
  401. return nil, nil, err
  402. }
  403. }
  404. return resultGroups, result, err
  405. }
  406. func setDiscoveryDefaults(config *restclient.Config) error {
  407. config.APIPath = ""
  408. config.GroupVersion = nil
  409. if config.Timeout == 0 {
  410. config.Timeout = defaultTimeout
  411. }
  412. if config.Burst == 0 && config.QPS < 100 {
  413. // discovery is expected to be bursty, increase the default burst
  414. // to accommodate looking up resource info for many API groups.
  415. // matches burst set by ConfigFlags#ToDiscoveryClient().
  416. // see https://issue.k8s.io/86149
  417. config.Burst = 100
  418. }
  419. codec := runtime.NoopEncoder{Decoder: scheme.Codecs.UniversalDecoder()}
  420. config.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: codec})
  421. if len(config.UserAgent) == 0 {
  422. config.UserAgent = restclient.DefaultKubernetesUserAgent()
  423. }
  424. return nil
  425. }
  426. // NewDiscoveryClientForConfig creates a new DiscoveryClient for the given config. This client
  427. // can be used to discover supported resources in the API server.
  428. func NewDiscoveryClientForConfig(c *restclient.Config) (*DiscoveryClient, error) {
  429. config := *c
  430. if err := setDiscoveryDefaults(&config); err != nil {
  431. return nil, err
  432. }
  433. client, err := restclient.UnversionedRESTClientFor(&config)
  434. return &DiscoveryClient{restClient: client, LegacyPrefix: "/api"}, err
  435. }
  436. // NewDiscoveryClientForConfigOrDie creates a new DiscoveryClient for the given config. If
  437. // there is an error, it panics.
  438. func NewDiscoveryClientForConfigOrDie(c *restclient.Config) *DiscoveryClient {
  439. client, err := NewDiscoveryClientForConfig(c)
  440. if err != nil {
  441. panic(err)
  442. }
  443. return client
  444. }
  445. // NewDiscoveryClient returns a new DiscoveryClient for the given RESTClient.
  446. func NewDiscoveryClient(c restclient.Interface) *DiscoveryClient {
  447. return &DiscoveryClient{restClient: c, LegacyPrefix: "/api"}
  448. }
  449. // RESTClient returns a RESTClient that is used to communicate
  450. // with API server by this client implementation.
  451. func (d *DiscoveryClient) RESTClient() restclient.Interface {
  452. if d == nil {
  453. return nil
  454. }
  455. return d.restClient
  456. }