openapi_getter.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2017 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 openapi
  14. import (
  15. "sync"
  16. "k8s.io/client-go/discovery"
  17. )
  18. // synchronizedOpenAPIGetter fetches the openapi schema once and then caches it in memory
  19. type synchronizedOpenAPIGetter struct {
  20. // Cached results
  21. sync.Once
  22. openAPISchema Resources
  23. err error
  24. openAPIClient discovery.OpenAPISchemaInterface
  25. }
  26. var _ Getter = &synchronizedOpenAPIGetter{}
  27. // Getter is an interface for fetching openapi specs and parsing them into an Resources struct
  28. type Getter interface {
  29. // OpenAPIData returns the parsed OpenAPIData
  30. Get() (Resources, error)
  31. }
  32. // NewOpenAPIGetter returns an object to return OpenAPIDatas which reads
  33. // from a server, and then stores in memory for subsequent invocations
  34. func NewOpenAPIGetter(openAPIClient discovery.OpenAPISchemaInterface) Getter {
  35. return &synchronizedOpenAPIGetter{
  36. openAPIClient: openAPIClient,
  37. }
  38. }
  39. // Resources implements Getter
  40. func (g *synchronizedOpenAPIGetter) Get() (Resources, error) {
  41. g.Do(func() {
  42. s, err := g.openAPIClient.OpenAPISchema()
  43. if err != nil {
  44. g.err = err
  45. return
  46. }
  47. g.openAPISchema, g.err = NewOpenAPIData(s)
  48. })
  49. // Return the save result
  50. return g.openAPISchema, g.err
  51. }