...

Source file src/k8s.io/kubectl/pkg/util/openapi/openapi_getter.go

Documentation: k8s.io/kubectl/pkg/util/openapi

     1  /*
     2  Copyright 2017 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package openapi
    18  
    19  import (
    20  	"sync"
    21  
    22  	openapi_v2 "github.com/google/gnostic-models/openapiv2"
    23  	"k8s.io/client-go/discovery"
    24  )
    25  
    26  // CachedOpenAPIGetter fetches the openapi schema once and then caches it in memory
    27  type CachedOpenAPIGetter struct {
    28  	openAPIClient discovery.OpenAPISchemaInterface
    29  
    30  	// Cached results
    31  	sync.Once
    32  	openAPISchema *openapi_v2.Document
    33  	err           error
    34  }
    35  
    36  var _ discovery.OpenAPISchemaInterface = &CachedOpenAPIGetter{}
    37  
    38  // NewOpenAPIGetter returns an object to return OpenAPIDatas which reads
    39  // from a server, and then stores in memory for subsequent invocations
    40  func NewOpenAPIGetter(openAPIClient discovery.OpenAPISchemaInterface) *CachedOpenAPIGetter {
    41  	return &CachedOpenAPIGetter{
    42  		openAPIClient: openAPIClient,
    43  	}
    44  }
    45  
    46  // OpenAPISchema implements OpenAPISchemaInterface.
    47  func (g *CachedOpenAPIGetter) OpenAPISchema() (*openapi_v2.Document, error) {
    48  	g.Do(func() {
    49  		g.openAPISchema, g.err = g.openAPIClient.OpenAPISchema()
    50  	})
    51  
    52  	// Return the saved result.
    53  	return g.openAPISchema, g.err
    54  }
    55  
    56  type CachedOpenAPIParser struct {
    57  	openAPIClient discovery.OpenAPISchemaInterface
    58  
    59  	// Cached results
    60  	sync.Once
    61  	openAPIResources Resources
    62  	err              error
    63  }
    64  
    65  func NewOpenAPIParser(openAPIClient discovery.OpenAPISchemaInterface) *CachedOpenAPIParser {
    66  	return &CachedOpenAPIParser{
    67  		openAPIClient: openAPIClient,
    68  	}
    69  }
    70  
    71  func (p *CachedOpenAPIParser) Parse() (Resources, error) {
    72  	p.Do(func() {
    73  		oapi, err := p.openAPIClient.OpenAPISchema()
    74  		if err != nil {
    75  			p.err = err
    76  			return
    77  		}
    78  		p.openAPIResources, p.err = NewOpenAPIData(oapi)
    79  	})
    80  
    81  	return p.openAPIResources, p.err
    82  }
    83  

View as plain text