discovery_client.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. goerrors "errors"
  18. "fmt"
  19. "mime"
  20. "net/http"
  21. "net/url"
  22. "sort"
  23. "strings"
  24. "sync"
  25. "time"
  26. openapi_v2 "github.com/google/gnostic-models/openapiv2"
  27. "google.golang.org/protobuf/proto"
  28. apidiscoveryv2 "k8s.io/api/apidiscovery/v2"
  29. apidiscoveryv2beta1 "k8s.io/api/apidiscovery/v2beta1"
  30. "k8s.io/apimachinery/pkg/api/errors"
  31. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  32. "k8s.io/apimachinery/pkg/runtime"
  33. "k8s.io/apimachinery/pkg/runtime/schema"
  34. "k8s.io/apimachinery/pkg/runtime/serializer"
  35. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  36. "k8s.io/apimachinery/pkg/version"
  37. "k8s.io/client-go/kubernetes/scheme"
  38. "k8s.io/client-go/openapi"
  39. restclient "k8s.io/client-go/rest"
  40. )
  41. const (
  42. // defaultRetries is the number of times a resource discovery is repeated if an api group disappears on the fly (e.g. CustomResourceDefinitions).
  43. defaultRetries = 2
  44. // protobuf mime type
  45. openAPIV2mimePb = "application/com.github.proto-openapi.spec.v2@v1.0+protobuf"
  46. // defaultTimeout is the maximum amount of time per request when no timeout has been set on a RESTClient.
  47. // Defaults to 32s in order to have a distinguishable length of time, relative to other timeouts that exist.
  48. defaultTimeout = 32 * time.Second
  49. // defaultBurst is the default burst to be used with the discovery client's token bucket rate limiter
  50. defaultBurst = 300
  51. AcceptV1 = runtime.ContentTypeJSON
  52. // Aggregated discovery content-type (v2beta1). NOTE: content-type parameters
  53. // MUST be ordered (g, v, as) for server in "Accept" header (BUT we are resilient
  54. // to ordering when comparing returned values in "Content-Type" header).
  55. AcceptV2Beta1 = runtime.ContentTypeJSON + ";" + "g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList"
  56. AcceptV2 = runtime.ContentTypeJSON + ";" + "g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList"
  57. AcceptV2NoPeer = runtime.ContentTypeJSON + ";" + "g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList;profile=nopeer"
  58. // Prioritize aggregated discovery by placing first in the order of discovery accept types.
  59. acceptDiscoveryFormats = AcceptV2 + "," + AcceptV2Beta1 + "," + AcceptV1
  60. )
  61. // Aggregated discovery content-type GVK.
  62. var v2Beta1GVK = schema.GroupVersionKind{Group: "apidiscovery.k8s.io", Version: "v2beta1", Kind: "APIGroupDiscoveryList"}
  63. var v2GVK = schema.GroupVersionKind{Group: "apidiscovery.k8s.io", Version: "v2", Kind: "APIGroupDiscoveryList"}
  64. // DiscoveryInterface holds the methods that discover server-supported API groups,
  65. // versions and resources.
  66. type DiscoveryInterface interface {
  67. RESTClient() restclient.Interface
  68. ServerGroupsInterface
  69. ServerResourcesInterface
  70. ServerVersionInterface
  71. OpenAPISchemaInterface
  72. OpenAPIV3SchemaInterface
  73. // Returns copy of current discovery client that will only
  74. // receive the legacy discovery format, or pointer to current
  75. // discovery client if it does not support legacy-only discovery.
  76. WithLegacy() DiscoveryInterface
  77. }
  78. // AggregatedDiscoveryInterface extends DiscoveryInterface to include a method to possibly
  79. // return discovery resources along with the discovery groups, which is what the newer
  80. // aggregated discovery format does (APIGroupDiscoveryList).
  81. type AggregatedDiscoveryInterface interface {
  82. DiscoveryInterface
  83. GroupsAndMaybeResources() (*metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, error)
  84. }
  85. // CachedDiscoveryInterface is a DiscoveryInterface with cache invalidation and freshness.
  86. // Note that If the ServerResourcesForGroupVersion method returns a cache miss
  87. // error, the user needs to explicitly call Invalidate to clear the cache,
  88. // otherwise the same cache miss error will be returned next time.
  89. type CachedDiscoveryInterface interface {
  90. DiscoveryInterface
  91. // Fresh is supposed to tell the caller whether or not to retry if the cache
  92. // fails to find something (false = retry, true = no need to retry).
  93. //
  94. // TODO: this needs to be revisited, this interface can't be locked properly
  95. // and doesn't make a lot of sense.
  96. Fresh() bool
  97. // Invalidate enforces that no cached data that is older than the current time
  98. // is used.
  99. Invalidate()
  100. }
  101. // ServerGroupsInterface has methods for obtaining supported groups on the API server
  102. type ServerGroupsInterface interface {
  103. // ServerGroups returns the supported groups, with information like supported versions and the
  104. // preferred version.
  105. ServerGroups() (*metav1.APIGroupList, error)
  106. }
  107. // ServerResourcesInterface has methods for obtaining supported resources on the API server
  108. type ServerResourcesInterface interface {
  109. // ServerResourcesForGroupVersion returns the supported resources for a group and version.
  110. ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error)
  111. // ServerGroupsAndResources returns the supported groups and resources for all groups and versions.
  112. //
  113. // The returned group and resource lists might be non-nil with partial results even in the
  114. // case of non-nil error.
  115. ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)
  116. // ServerPreferredResources returns the supported resources with the version preferred by the
  117. // server.
  118. //
  119. // The returned group and resource lists might be non-nil with partial results even in the
  120. // case of non-nil error.
  121. ServerPreferredResources() ([]*metav1.APIResourceList, error)
  122. // ServerPreferredNamespacedResources returns the supported namespaced resources with the
  123. // version preferred by the server.
  124. //
  125. // The returned resource list might be non-nil with partial results even in the case of
  126. // non-nil error.
  127. ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error)
  128. }
  129. // ServerVersionInterface has a method for retrieving the server's version.
  130. type ServerVersionInterface interface {
  131. // ServerVersion retrieves and parses the server's version (git version).
  132. ServerVersion() (*version.Info, error)
  133. }
  134. // OpenAPISchemaInterface has a method to retrieve the open API schema.
  135. type OpenAPISchemaInterface interface {
  136. // OpenAPISchema retrieves and parses the swagger API schema the server supports.
  137. OpenAPISchema() (*openapi_v2.Document, error)
  138. }
  139. type OpenAPIV3SchemaInterface interface {
  140. OpenAPIV3() openapi.Client
  141. }
  142. // DiscoveryClient implements the functions that discover server-supported API groups,
  143. // versions and resources.
  144. type DiscoveryClient struct {
  145. restClient restclient.Interface
  146. LegacyPrefix string
  147. // Forces the client to request only "unaggregated" (legacy) discovery.
  148. UseLegacyDiscovery bool
  149. // NoPeerDiscovery will request the "nopeer" profile of aggregated discovery.
  150. // This allows a client to get just the discovery documents served by the single apiserver
  151. // that it is talking to. This is useful for clients that need to understand the state
  152. // of a single apiserver, for example, to validate that the apiserver is ready to serve traffic.
  153. NoPeerDiscovery bool
  154. }
  155. var _ AggregatedDiscoveryInterface = &DiscoveryClient{}
  156. // Convert metav1.APIVersions to metav1.APIGroup. APIVersions is used by legacy v1, so
  157. // group would be "".
  158. func apiVersionsToAPIGroup(apiVersions *metav1.APIVersions) (apiGroup metav1.APIGroup) {
  159. groupVersions := []metav1.GroupVersionForDiscovery{}
  160. for _, version := range apiVersions.Versions {
  161. groupVersion := metav1.GroupVersionForDiscovery{
  162. GroupVersion: version,
  163. Version: version,
  164. }
  165. groupVersions = append(groupVersions, groupVersion)
  166. }
  167. apiGroup.Versions = groupVersions
  168. // There should be only one groupVersion returned at /api
  169. apiGroup.PreferredVersion = groupVersions[0]
  170. return
  171. }
  172. // GroupsAndMaybeResources returns the discovery groups, and (if new aggregated
  173. // discovery format) the resources keyed by group/version. Merges discovery groups
  174. // and resources from /api and /apis (either aggregated or not). Legacy groups
  175. // must be ordered first. The server will either return both endpoints (/api, /apis)
  176. // as aggregated discovery format or legacy format. For safety, resources will only
  177. // be returned if both endpoints returned resources. Returned "failedGVs" can be
  178. // empty, but will only be nil in the case an error is returned.
  179. func (d *DiscoveryClient) GroupsAndMaybeResources() (
  180. *metav1.APIGroupList,
  181. map[schema.GroupVersion]*metav1.APIResourceList,
  182. map[schema.GroupVersion]error,
  183. error) {
  184. // Legacy group ordered first (there is only one -- core/v1 group). Returned groups must
  185. // be non-nil, but it could be empty. Returned resources, apiResources map could be nil.
  186. groups, resources, failedGVs, err := d.downloadLegacy()
  187. if err != nil {
  188. return nil, nil, nil, err
  189. }
  190. // Discovery groups and (possibly) resources downloaded from /apis.
  191. apiGroups, apiResources, failedApisGVs, aerr := d.downloadAPIs()
  192. if aerr != nil {
  193. return nil, nil, nil, aerr
  194. }
  195. // Merge apis groups into the legacy groups.
  196. for _, group := range apiGroups.Groups {
  197. groups.Groups = append(groups.Groups, group)
  198. }
  199. // For safety, only return resources if both endpoints returned resources.
  200. if resources != nil && apiResources != nil {
  201. for gv, resourceList := range apiResources {
  202. resources[gv] = resourceList
  203. }
  204. } else if resources != nil {
  205. resources = nil
  206. }
  207. // Merge failed GroupVersions from /api and /apis
  208. for gv, err := range failedApisGVs {
  209. failedGVs[gv] = err
  210. }
  211. return groups, resources, failedGVs, err
  212. }
  213. // downloadLegacy returns the discovery groups and possibly resources
  214. // for the legacy v1 GVR at /api, or an error if one occurred. It is
  215. // possible for the resource map to be nil if the server returned
  216. // the unaggregated discovery. Returned "failedGVs" can be empty, but
  217. // will only be nil in the case of a returned error.
  218. func (d *DiscoveryClient) downloadLegacy() (
  219. *metav1.APIGroupList,
  220. map[schema.GroupVersion]*metav1.APIResourceList,
  221. map[schema.GroupVersion]error,
  222. error) {
  223. accept := selectDiscoveryAcceptHeader(d.UseLegacyDiscovery, d.NoPeerDiscovery)
  224. var responseContentType string
  225. body, err := d.restClient.Get().
  226. AbsPath("/api").
  227. SetHeader("Accept", accept).
  228. Do(context.TODO()).
  229. ContentType(&responseContentType).
  230. Raw()
  231. apiGroupList := &metav1.APIGroupList{}
  232. failedGVs := map[schema.GroupVersion]error{}
  233. if err != nil {
  234. // Tolerate 404, since aggregated api servers can return it.
  235. if errors.IsNotFound(err) {
  236. // Return empty structures and no error.
  237. emptyGVMap := map[schema.GroupVersion]*metav1.APIResourceList{}
  238. return apiGroupList, emptyGVMap, failedGVs, nil
  239. } else {
  240. return nil, nil, nil, err
  241. }
  242. }
  243. var resourcesByGV map[schema.GroupVersion]*metav1.APIResourceList
  244. // Based on the content-type server responded with: aggregated or unaggregated.
  245. if isGVK, _ := ContentTypeIsGVK(responseContentType, v2GVK); isGVK {
  246. var aggregatedDiscovery apidiscoveryv2.APIGroupDiscoveryList
  247. err = json.Unmarshal(body, &aggregatedDiscovery)
  248. if err != nil {
  249. return nil, nil, nil, err
  250. }
  251. apiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResources(aggregatedDiscovery)
  252. } else if isGVK, _ := ContentTypeIsGVK(responseContentType, v2Beta1GVK); isGVK {
  253. var aggregatedDiscovery apidiscoveryv2beta1.APIGroupDiscoveryList
  254. err = json.Unmarshal(body, &aggregatedDiscovery)
  255. if err != nil {
  256. return nil, nil, nil, err
  257. }
  258. apiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResourcesV2Beta1(aggregatedDiscovery)
  259. } else {
  260. // Default is unaggregated discovery v1.
  261. var v metav1.APIVersions
  262. err = json.Unmarshal(body, &v)
  263. if err != nil {
  264. return nil, nil, nil, err
  265. }
  266. apiGroup := metav1.APIGroup{}
  267. if len(v.Versions) != 0 {
  268. apiGroup = apiVersionsToAPIGroup(&v)
  269. }
  270. apiGroupList.Groups = []metav1.APIGroup{apiGroup}
  271. }
  272. return apiGroupList, resourcesByGV, failedGVs, nil
  273. }
  274. // downloadAPIs returns the discovery groups and (if aggregated format) the
  275. // discovery resources. The returned groups will always exist, but the
  276. // resources map may be nil. Returned "failedGVs" can be empty, but will
  277. // only be nil in the case of a returned error.
  278. func (d *DiscoveryClient) downloadAPIs() (
  279. *metav1.APIGroupList,
  280. map[schema.GroupVersion]*metav1.APIResourceList,
  281. map[schema.GroupVersion]error,
  282. error) {
  283. accept := selectDiscoveryAcceptHeader(d.UseLegacyDiscovery, d.NoPeerDiscovery)
  284. var responseContentType string
  285. body, err := d.restClient.Get().
  286. AbsPath("/apis").
  287. SetHeader("Accept", accept).
  288. Do(context.TODO()).
  289. ContentType(&responseContentType).
  290. Raw()
  291. if err != nil {
  292. return nil, nil, nil, err
  293. }
  294. apiGroupList := &metav1.APIGroupList{}
  295. failedGVs := map[schema.GroupVersion]error{}
  296. var resourcesByGV map[schema.GroupVersion]*metav1.APIResourceList
  297. // Based on the content-type server responded with: aggregated or unaggregated.
  298. if isGVK, _ := ContentTypeIsGVK(responseContentType, v2GVK); isGVK {
  299. var aggregatedDiscovery apidiscoveryv2.APIGroupDiscoveryList
  300. err = json.Unmarshal(body, &aggregatedDiscovery)
  301. if err != nil {
  302. return nil, nil, nil, err
  303. }
  304. apiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResources(aggregatedDiscovery)
  305. } else if isGVK, _ := ContentTypeIsGVK(responseContentType, v2Beta1GVK); isGVK {
  306. var aggregatedDiscovery apidiscoveryv2beta1.APIGroupDiscoveryList
  307. err = json.Unmarshal(body, &aggregatedDiscovery)
  308. if err != nil {
  309. return nil, nil, nil, err
  310. }
  311. apiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResourcesV2Beta1(aggregatedDiscovery)
  312. } else {
  313. // Default is unaggregated discovery v1.
  314. err = json.Unmarshal(body, apiGroupList)
  315. if err != nil {
  316. return nil, nil, nil, err
  317. }
  318. }
  319. return apiGroupList, resourcesByGV, failedGVs, nil
  320. }
  321. func selectDiscoveryAcceptHeader(useLegacy, nopeer bool) string {
  322. if useLegacy {
  323. return AcceptV1
  324. }
  325. if nopeer {
  326. return AcceptV2NoPeer + "," + acceptDiscoveryFormats
  327. }
  328. return acceptDiscoveryFormats
  329. }
  330. // ContentTypeIsGVK checks of the content-type string is both
  331. // "application/json" and matches the provided GVK. An error
  332. // is returned if the content type string is malformed.
  333. // NOTE: This function is resilient to the ordering of the
  334. // content-type parameters, as well as parameters added by
  335. // intermediaries such as proxies or gateways. Examples:
  336. //
  337. // ("application/json; g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList", {apidiscovery.k8s.io, v2beta1, APIGroupDiscoveryList}) = (true, nil)
  338. // ("application/json; as=APIGroupDiscoveryList;v=v2beta1;g=apidiscovery.k8s.io", {apidiscovery.k8s.io, v2beta1, APIGroupDiscoveryList}) = (true, nil)
  339. // ("application/json; as=APIGroupDiscoveryList;v=v2beta1;g=apidiscovery.k8s.io;charset=utf-8", {apidiscovery.k8s.io, v2beta1, APIGroupDiscoveryList}) = (true, nil)
  340. // ("application/json", any GVK) = (false, nil)
  341. // ("application/json; charset=UTF-8", any GVK) = (false, nil)
  342. // ("malformed content type string", any GVK) = (false, error)
  343. func ContentTypeIsGVK(contentType string, gvk schema.GroupVersionKind) (bool, error) {
  344. base, params, err := mime.ParseMediaType(contentType)
  345. if err != nil {
  346. return false, err
  347. }
  348. gvkMatch := runtime.ContentTypeJSON == base &&
  349. params["g"] == gvk.Group &&
  350. params["v"] == gvk.Version &&
  351. params["as"] == gvk.Kind
  352. return gvkMatch, nil
  353. }
  354. // ServerGroups returns the supported groups, with information like supported versions and the
  355. // preferred version.
  356. func (d *DiscoveryClient) ServerGroups() (*metav1.APIGroupList, error) {
  357. groups, _, _, err := d.GroupsAndMaybeResources()
  358. if err != nil {
  359. return nil, err
  360. }
  361. return groups, nil
  362. }
  363. // ServerResourcesForGroupVersion returns the supported resources for a group and version.
  364. func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (resources *metav1.APIResourceList, err error) {
  365. url := url.URL{}
  366. if len(groupVersion) == 0 {
  367. return nil, fmt.Errorf("groupVersion shouldn't be empty")
  368. }
  369. if len(d.LegacyPrefix) > 0 && groupVersion == "v1" {
  370. url.Path = d.LegacyPrefix + "/" + groupVersion
  371. } else {
  372. url.Path = "/apis/" + groupVersion
  373. }
  374. resources = &metav1.APIResourceList{
  375. GroupVersion: groupVersion,
  376. }
  377. err = d.restClient.Get().AbsPath(url.String()).Do(context.TODO()).Into(resources)
  378. if err != nil {
  379. // Tolerate core/v1 not found response by returning empty resource list;
  380. // this probably should not happen. But we should verify all callers are
  381. // not depending on this toleration before removal.
  382. if groupVersion == "v1" && errors.IsNotFound(err) {
  383. return resources, nil
  384. }
  385. return nil, err
  386. }
  387. return resources, nil
  388. }
  389. // ServerGroupsAndResources returns the supported resources for all groups and versions.
  390. func (d *DiscoveryClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  391. return withRetries(defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  392. return ServerGroupsAndResources(d)
  393. })
  394. }
  395. // ErrGroupDiscoveryFailed is returned if one or more API groups fail to load.
  396. type ErrGroupDiscoveryFailed struct {
  397. // Groups is a list of the groups that failed to load and the error cause
  398. Groups map[schema.GroupVersion]error
  399. }
  400. // Error implements the error interface
  401. func (e *ErrGroupDiscoveryFailed) Error() string {
  402. var groups []string
  403. for k, v := range e.Groups {
  404. groups = append(groups, fmt.Sprintf("%s: %v", k, v))
  405. }
  406. sort.Strings(groups)
  407. return fmt.Sprintf("unable to retrieve the complete list of server APIs: %s", strings.Join(groups, ", "))
  408. }
  409. // Is makes it possible for the callers to use `errors.Is(` helper on errors wrapped with ErrGroupDiscoveryFailed error.
  410. func (e *ErrGroupDiscoveryFailed) Is(target error) bool {
  411. _, ok := target.(*ErrGroupDiscoveryFailed)
  412. return ok
  413. }
  414. // IsGroupDiscoveryFailedError returns true if the provided error indicates the server was unable to discover
  415. // a complete list of APIs for the client to use.
  416. func IsGroupDiscoveryFailedError(err error) bool {
  417. _, ok := err.(*ErrGroupDiscoveryFailed)
  418. return err != nil && ok
  419. }
  420. // GroupDiscoveryFailedErrorGroups returns true if the error is an ErrGroupDiscoveryFailed error,
  421. // along with the map of group versions that failed discovery.
  422. func GroupDiscoveryFailedErrorGroups(err error) (map[schema.GroupVersion]error, bool) {
  423. var groupDiscoveryError *ErrGroupDiscoveryFailed
  424. if err != nil && goerrors.As(err, &groupDiscoveryError) {
  425. return groupDiscoveryError.Groups, true
  426. }
  427. return nil, false
  428. }
  429. func ServerGroupsAndResources(d DiscoveryInterface) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  430. var sgs *metav1.APIGroupList
  431. var resources []*metav1.APIResourceList
  432. var failedGVs map[schema.GroupVersion]error
  433. var err error
  434. // If the passed discovery object implements the wider AggregatedDiscoveryInterface,
  435. // then attempt to retrieve aggregated discovery with both groups and the resources.
  436. if ad, ok := d.(AggregatedDiscoveryInterface); ok {
  437. var resourcesByGV map[schema.GroupVersion]*metav1.APIResourceList
  438. sgs, resourcesByGV, failedGVs, err = ad.GroupsAndMaybeResources()
  439. for _, resourceList := range resourcesByGV {
  440. resources = append(resources, resourceList)
  441. }
  442. } else {
  443. sgs, err = d.ServerGroups()
  444. }
  445. if sgs == nil {
  446. return nil, nil, err
  447. }
  448. resultGroups := []*metav1.APIGroup{}
  449. for i := range sgs.Groups {
  450. resultGroups = append(resultGroups, &sgs.Groups[i])
  451. }
  452. // resources is non-nil if aggregated discovery succeeded.
  453. if resources != nil {
  454. // Any stale Group/Versions returned by aggregated discovery
  455. // must be surfaced to the caller as failed Group/Versions.
  456. var ferr error
  457. if len(failedGVs) > 0 {
  458. ferr = &ErrGroupDiscoveryFailed{Groups: failedGVs}
  459. }
  460. return resultGroups, resources, ferr
  461. }
  462. groupVersionResources, failedGroups := fetchGroupVersionResources(d, sgs)
  463. // order results by group/version discovery order
  464. result := []*metav1.APIResourceList{}
  465. for _, apiGroup := range sgs.Groups {
  466. for _, version := range apiGroup.Versions {
  467. gv := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}
  468. if resources, ok := groupVersionResources[gv]; ok {
  469. result = append(result, resources)
  470. }
  471. }
  472. }
  473. if len(failedGroups) == 0 {
  474. return resultGroups, result, nil
  475. }
  476. return resultGroups, result, &ErrGroupDiscoveryFailed{Groups: failedGroups}
  477. }
  478. // ServerPreferredResources uses the provided discovery interface to look up preferred resources
  479. func ServerPreferredResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) {
  480. var serverGroupList *metav1.APIGroupList
  481. var failedGroups map[schema.GroupVersion]error
  482. var groupVersionResources map[schema.GroupVersion]*metav1.APIResourceList
  483. var err error
  484. // If the passed discovery object implements the wider AggregatedDiscoveryInterface,
  485. // then it is attempt to retrieve both the groups and the resources. "failedGroups"
  486. // are Group/Versions returned as stale in AggregatedDiscovery format.
  487. ad, ok := d.(AggregatedDiscoveryInterface)
  488. if ok {
  489. serverGroupList, groupVersionResources, failedGroups, err = ad.GroupsAndMaybeResources()
  490. } else {
  491. serverGroupList, err = d.ServerGroups()
  492. }
  493. if err != nil {
  494. return nil, err
  495. }
  496. // Non-aggregated discovery must fetch resources from Groups.
  497. if groupVersionResources == nil {
  498. groupVersionResources, failedGroups = fetchGroupVersionResources(d, serverGroupList)
  499. }
  500. result := []*metav1.APIResourceList{}
  501. grVersions := map[schema.GroupResource]string{} // selected version of a GroupResource
  502. grAPIResources := map[schema.GroupResource]*metav1.APIResource{} // selected APIResource for a GroupResource
  503. gvAPIResourceLists := map[schema.GroupVersion]*metav1.APIResourceList{} // blueprint for a APIResourceList for later grouping
  504. for _, apiGroup := range serverGroupList.Groups {
  505. for _, version := range apiGroup.Versions {
  506. groupVersion := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}
  507. apiResourceList, ok := groupVersionResources[groupVersion]
  508. if !ok {
  509. continue
  510. }
  511. // create empty list which is filled later in another loop
  512. emptyAPIResourceList := metav1.APIResourceList{
  513. GroupVersion: version.GroupVersion,
  514. }
  515. gvAPIResourceLists[groupVersion] = &emptyAPIResourceList
  516. result = append(result, &emptyAPIResourceList)
  517. for i := range apiResourceList.APIResources {
  518. apiResource := &apiResourceList.APIResources[i]
  519. if strings.Contains(apiResource.Name, "/") {
  520. continue
  521. }
  522. gv := schema.GroupResource{Group: apiGroup.Name, Resource: apiResource.Name}
  523. if _, ok := grAPIResources[gv]; ok && version.Version != apiGroup.PreferredVersion.Version {
  524. // only override with preferred version
  525. continue
  526. }
  527. grVersions[gv] = version.Version
  528. grAPIResources[gv] = apiResource
  529. }
  530. }
  531. }
  532. // group selected APIResources according to GroupVersion into APIResourceLists
  533. for groupResource, apiResource := range grAPIResources {
  534. version := grVersions[groupResource]
  535. groupVersion := schema.GroupVersion{Group: groupResource.Group, Version: version}
  536. apiResourceList := gvAPIResourceLists[groupVersion]
  537. apiResourceList.APIResources = append(apiResourceList.APIResources, *apiResource)
  538. }
  539. if len(failedGroups) == 0 {
  540. return result, nil
  541. }
  542. return result, &ErrGroupDiscoveryFailed{Groups: failedGroups}
  543. }
  544. // fetchServerResourcesForGroupVersions uses the discovery client to fetch the resources for the specified groups in parallel.
  545. func fetchGroupVersionResources(d DiscoveryInterface, apiGroups *metav1.APIGroupList) (map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error) {
  546. groupVersionResources := make(map[schema.GroupVersion]*metav1.APIResourceList)
  547. failedGroups := make(map[schema.GroupVersion]error)
  548. wg := &sync.WaitGroup{}
  549. resultLock := &sync.Mutex{}
  550. for _, apiGroup := range apiGroups.Groups {
  551. for _, version := range apiGroup.Versions {
  552. groupVersion := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}
  553. wg.Add(1)
  554. go func() {
  555. defer wg.Done()
  556. defer utilruntime.HandleCrash()
  557. apiResourceList, err := d.ServerResourcesForGroupVersion(groupVersion.String())
  558. // lock to record results
  559. resultLock.Lock()
  560. defer resultLock.Unlock()
  561. if err != nil {
  562. // TODO: maybe restrict this to NotFound errors
  563. failedGroups[groupVersion] = err
  564. }
  565. if apiResourceList != nil {
  566. // even in case of error, some fallback might have been returned
  567. groupVersionResources[groupVersion] = apiResourceList
  568. }
  569. }()
  570. }
  571. }
  572. wg.Wait()
  573. return groupVersionResources, failedGroups
  574. }
  575. // ServerPreferredResources returns the supported resources with the version preferred by the
  576. // server.
  577. func (d *DiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error) {
  578. _, rs, err := withRetries(defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  579. rs, err := ServerPreferredResources(d)
  580. return nil, rs, err
  581. })
  582. return rs, err
  583. }
  584. // ServerPreferredNamespacedResources returns the supported namespaced resources with the
  585. // version preferred by the server.
  586. func (d *DiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) {
  587. return ServerPreferredNamespacedResources(d)
  588. }
  589. // ServerPreferredNamespacedResources uses the provided discovery interface to look up preferred namespaced resources
  590. func ServerPreferredNamespacedResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) {
  591. all, err := ServerPreferredResources(d)
  592. return FilteredBy(ResourcePredicateFunc(func(groupVersion string, r *metav1.APIResource) bool {
  593. return r.Namespaced
  594. }), all), err
  595. }
  596. // ServerVersion retrieves and parses the server's version (git version).
  597. func (d *DiscoveryClient) ServerVersion() (*version.Info, error) {
  598. body, err := d.restClient.Get().AbsPath("/version").Do(context.TODO()).Raw()
  599. if err != nil {
  600. return nil, err
  601. }
  602. var info version.Info
  603. err = json.Unmarshal(body, &info)
  604. if err != nil {
  605. return nil, fmt.Errorf("unable to parse the server version: %v", err)
  606. }
  607. return &info, nil
  608. }
  609. // OpenAPISchema fetches the open api v2 schema using a rest client and parses the proto.
  610. func (d *DiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error) {
  611. data, err := d.restClient.Get().AbsPath("/openapi/v2").SetHeader("Accept", openAPIV2mimePb).Do(context.TODO()).Raw()
  612. if err != nil {
  613. return nil, err
  614. }
  615. document := &openapi_v2.Document{}
  616. err = proto.Unmarshal(data, document)
  617. if err != nil {
  618. return nil, err
  619. }
  620. return document, nil
  621. }
  622. func (d *DiscoveryClient) OpenAPIV3() openapi.Client {
  623. return openapi.NewClient(d.restClient)
  624. }
  625. // WithLegacy returns copy of current discovery client that will only
  626. // receive the legacy discovery format.
  627. func (d *DiscoveryClient) WithLegacy() DiscoveryInterface {
  628. client := *d
  629. client.UseLegacyDiscovery = true
  630. return &client
  631. }
  632. // withRetries retries the given recovery function in case the groups supported by the server change after ServerGroup() returns.
  633. func withRetries(maxRetries int, f func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {
  634. var result []*metav1.APIResourceList
  635. var resultGroups []*metav1.APIGroup
  636. var err error
  637. for i := 0; i < maxRetries; i++ {
  638. resultGroups, result, err = f()
  639. if err == nil {
  640. return resultGroups, result, nil
  641. }
  642. if _, ok := err.(*ErrGroupDiscoveryFailed); !ok {
  643. return nil, nil, err
  644. }
  645. }
  646. return resultGroups, result, err
  647. }
  648. func setDiscoveryDefaults(config *restclient.Config) error {
  649. config.APIPath = ""
  650. config.GroupVersion = nil
  651. if config.Timeout == 0 {
  652. config.Timeout = defaultTimeout
  653. }
  654. // if a burst limit is not already configured
  655. if config.Burst == 0 {
  656. // discovery is expected to be bursty, increase the default burst
  657. // to accommodate looking up resource info for many API groups.
  658. // matches burst set by ConfigFlags#ToDiscoveryClient().
  659. // see https://issue.k8s.io/86149
  660. config.Burst = defaultBurst
  661. }
  662. codec := runtime.NoopEncoder{Decoder: scheme.Codecs.UniversalDecoder()}
  663. config.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: codec})
  664. if len(config.UserAgent) == 0 {
  665. config.UserAgent = restclient.DefaultKubernetesUserAgent()
  666. }
  667. return nil
  668. }
  669. // NewDiscoveryClientForConfig creates a new DiscoveryClient for the given config. This client
  670. // can be used to discover supported resources in the API server.
  671. // NewDiscoveryClientForConfig is equivalent to NewDiscoveryClientForConfigAndClient(c, httpClient),
  672. // where httpClient was generated with rest.HTTPClientFor(c).
  673. func NewDiscoveryClientForConfig(c *restclient.Config) (*DiscoveryClient, error) {
  674. config := *c
  675. if err := setDiscoveryDefaults(&config); err != nil {
  676. return nil, err
  677. }
  678. httpClient, err := restclient.HTTPClientFor(&config)
  679. if err != nil {
  680. return nil, err
  681. }
  682. return NewDiscoveryClientForConfigAndClient(&config, httpClient)
  683. }
  684. // NewDiscoveryClientForConfigAndClient creates a new DiscoveryClient for the given config. This client
  685. // can be used to discover supported resources in the API server.
  686. // Note the http client provided takes precedence over the configured transport values.
  687. func NewDiscoveryClientForConfigAndClient(c *restclient.Config, httpClient *http.Client) (*DiscoveryClient, error) {
  688. config := *c
  689. if err := setDiscoveryDefaults(&config); err != nil {
  690. return nil, err
  691. }
  692. client, err := restclient.UnversionedRESTClientForConfigAndClient(&config, httpClient)
  693. return &DiscoveryClient{restClient: client, LegacyPrefix: "/api", UseLegacyDiscovery: false}, err
  694. }
  695. // NewDiscoveryClientForConfigOrDie creates a new DiscoveryClient for the given config. If
  696. // there is an error, it panics.
  697. func NewDiscoveryClientForConfigOrDie(c *restclient.Config) *DiscoveryClient {
  698. client, err := NewDiscoveryClientForConfig(c)
  699. if err != nil {
  700. panic(err)
  701. }
  702. return client
  703. }
  704. // NewDiscoveryClient returns a new DiscoveryClient for the given RESTClient.
  705. func NewDiscoveryClient(c restclient.Interface) *DiscoveryClient {
  706. return &DiscoveryClient{restClient: c, LegacyPrefix: "/api", UseLegacyDiscovery: false}
  707. }
  708. // RESTClient returns a RESTClient that is used to communicate
  709. // with API server by this client implementation.
  710. func (d *DiscoveryClient) RESTClient() restclient.Interface {
  711. if d == nil {
  712. return nil
  713. }
  714. return d.restClient
  715. }