Upgrade boilerplate to latest

The latest boilerplate comes with a lot of simplifications and helpers
that let us reduce the amount of code written.
This commit is contained in:
Solly Ross 2018-08-15 15:49:46 -04:00
parent 6b2c04dd61
commit d02384477a
12 changed files with 604 additions and 381 deletions

View file

@ -23,6 +23,7 @@ import (
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/version"
genericapiserver "k8s.io/apiserver/pkg/server"
"k8s.io/client-go/informers"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider"
cminstall "k8s.io/metrics/pkg/apis/custom_metrics/install"
@ -69,12 +70,12 @@ type completedConfig struct {
}
// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.
func (c *Config) Complete() completedConfig {
func (c *Config) Complete(informers informers.SharedInformerFactory) completedConfig {
c.GenericConfig.Version = &version.Info{
Major: "1",
Minor: "0",
}
return completedConfig{c.GenericConfig.Complete(nil)}
return completedConfig{c.GenericConfig.Complete(informers)}
}
// New returns a new instance of CustomMetricsAdapterServer from the given config.

View file

@ -0,0 +1,283 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"fmt"
"sync"
"time"
"github.com/spf13/pflag"
apimeta "k8s.io/apimachinery/pkg/api/meta"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/apiserver"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/cmd/server"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/dynamicmapper"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider"
)
// AdapterBase provides a base set of functionality for any custom metrics adapter.
// Embed it in a struct containing your options, then:
//
// - Use Flags() to add flags, then call Flags().Parse(os.Argv)
// - Use DynamicClient and RESTMapper to fetch handles to common utilities
// - Use WithCustomMetrics(provider) and WithExternalMetrics(provider) to install metrics providers
// - Use Run(stopChannel) to start the server
//
// All methods on this struct are idempotent except for Run -- they'll perform any
// initialization on the first call, then return the existing object on later calls.
// Methods on this struct are not safe to call from multiple goroutines without
// external synchronization.
type AdapterBase struct {
*server.CustomMetricsAdapterServerOptions
// Name is the name of the API server. It defaults to custom-metrics-adapter
Name string
// RemoteKubeConfigFile specifies the kubeconfig to use to construct
// the dynamic client and RESTMapper. It's set from a flag.
RemoteKubeConfigFile string
// DiscoveryInterval specifies the interval at which to recheck discovery
// information for the discovery RESTMapper. It's set from a flag.
DiscoveryInterval time.Duration
// FlagSet is the flagset to add flags to.
// It defaults to the normal CommandLine flags
// if not explicitly set.
FlagSet *pflag.FlagSet
// flagOnce controls initialization of the flags.
flagOnce sync.Once
clientConfig *rest.Config
discoveryClient discovery.DiscoveryInterface
restMapper apimeta.RESTMapper
dynamicClient dynamic.Interface
informers informers.SharedInformerFactory
config *apiserver.Config
server *apiserver.CustomMetricsAdapterServer
cmProvider provider.CustomMetricsProvider
emProvider provider.ExternalMetricsProvider
}
// InstallFlags installs the minimum required set of flags into the flagset.
func (b *AdapterBase) InstallFlags() {
b.initFlagSet()
b.flagOnce.Do(func() {
if b.CustomMetricsAdapterServerOptions == nil {
b.CustomMetricsAdapterServerOptions = server.NewCustomMetricsAdapterServerOptions()
}
b.SecureServing.AddFlags(b.FlagSet)
b.Authentication.AddFlags(b.FlagSet)
b.Authorization.AddFlags(b.FlagSet)
b.Features.AddFlags(b.FlagSet)
b.FlagSet.StringVar(&b.RemoteKubeConfigFile, "lister-kubeconfig", b.RemoteKubeConfigFile,
"kubeconfig file pointing at the 'core' kubernetes server with enough rights to list "+
"any described objects")
b.FlagSet.DurationVar(&b.DiscoveryInterval, "discovery-interval", b.DiscoveryInterval,
"interval at which to refresh API discovery information")
})
}
// initFlagSet populates the flagset to the CommandLine flags if it's not already set.
func (b *AdapterBase) initFlagSet() {
if b.FlagSet == nil {
// default to the normal commandline flags
b.FlagSet = pflag.CommandLine
}
}
// Flags returns the flagset used by this adapter.
// It will initialize the flagset with the minimum required set
// of flags as well.
func (b *AdapterBase) Flags() *pflag.FlagSet {
b.initFlagSet()
b.InstallFlags()
return b.FlagSet
}
// ClientConfig returns the REST client configuration used to construct
// clients for the clients and RESTMapper, and may be used for other
// purposes as well. If you need to mutate it, be sure to copy it with
// rest.CopyConfig first.
func (b *AdapterBase) ClientConfig() (*rest.Config, error) {
if b.clientConfig == nil {
var clientConfig *rest.Config
var err error
if len(b.RemoteKubeConfigFile) > 0 {
loadingRules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: b.RemoteKubeConfigFile}
loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
clientConfig, err = loader.ClientConfig()
} else {
clientConfig, err = rest.InClusterConfig()
}
if err != nil {
return nil, fmt.Errorf("unable to construct lister client config to initialize provider: %v", err)
}
b.clientConfig = clientConfig
}
return b.clientConfig, nil
}
// DiscoveryClient returns a DiscoveryInterface suitable to for discovering resources
// available on the cluster.
func (b *AdapterBase) DiscoveryClient() (discovery.DiscoveryInterface, error) {
if b.discoveryClient == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
discoveryClient, err := discovery.NewDiscoveryClientForConfig(clientConfig)
if err != nil {
return nil, fmt.Errorf("unable to construct discovery client for dynamic client: %v", err)
}
b.discoveryClient = discoveryClient
}
return b.discoveryClient, nil
}
// RESTMapper returns a RESTMapper dynamically populated with discovery information.
// The discovery information will be periodically repopulated according to DiscoveryInterval.
func (b *AdapterBase) RESTMapper() (apimeta.RESTMapper, error) {
if b.restMapper == nil {
discoveryClient, err := b.DiscoveryClient()
if err != nil {
return nil, err
}
// NB: since we never actually look at the contents of
// the objects we fetch (beyond ObjectMeta), unstructured should be fine
dynamicMapper, err := dynamicmapper.NewRESTMapper(discoveryClient, b.DiscoveryInterval)
if err != nil {
return nil, fmt.Errorf("unable to construct dynamic discovery mapper: %v", err)
}
b.restMapper = dynamicMapper
}
return b.restMapper, nil
}
// DynamicClient returns a dynamic Kubernetes client capable of listing and fetching
// any resources on the cluster.
func (b *AdapterBase) DynamicClient() (dynamic.Interface, error) {
if b.dynamicClient == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
dynClient, err := dynamic.NewForConfig(clientConfig)
if err != nil {
return nil, fmt.Errorf("unable to construct lister client to initialize provider: %v", err)
}
b.dynamicClient = dynClient
}
return b.dynamicClient, nil
}
// WithCustomMetrics populates the custom metrics provider for this adapter.
func (b *AdapterBase) WithCustomMetrics(p provider.CustomMetricsProvider) {
b.cmProvider = p
}
// WithExternalMetrics populates the external metrics provider for this adapter.
func (b *AdapterBase) WithExternalMetrics(p provider.ExternalMetricsProvider) {
b.emProvider = p
}
// Config fetches the configuration used to ulitmately create the custom metrics adapter's
// API server. While this method is idempotent, it does "cement" values of some of the other
// fields, so make sure to only call it just before `Server` or `Run`.
// Normal users should not need to call this method -- it's for advanced use cases.
func (b *AdapterBase) Config() (*apiserver.Config, error) {
if b.config == nil {
b.InstallFlags() // just to be sure
config, err := b.CustomMetricsAdapterServerOptions.Config()
if err != nil {
return nil, err
}
b.config = config
}
return b.config, nil
}
// Server fetches API server object used to ulitmately run the custom metrics adapter.
// While this method is idempotent, it does "cement" values of some of the other
// fields, so make sure to only call it just before `Run`.
// Normal users should not need to call this method -- it's for advanced use cases.
func (b *AdapterBase) Server() (*apiserver.CustomMetricsAdapterServer, error) {
if b.server == nil {
config, err := b.Config()
if err != nil {
return nil, err
}
if b.Name == "" {
b.Name = "custom-metrics-adapter"
}
// we add in the informers if they're not nil, but we don't try and
// construct them if the user didn't ask for them
server, err := config.Complete(b.informers).New(b.Name, b.cmProvider, b.emProvider)
if err != nil {
return nil, err
}
b.server = server
}
return b.server, nil
}
// Informers returns a SharedInformerFactory for constructing new informers.
// The informers will be automatically started as part of starting the adapter.
func (b *AdapterBase) Informers() (informers.SharedInformerFactory, error) {
if b.informers == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
kubeClient, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return nil, err
}
b.informers = informers.NewSharedInformerFactory(kubeClient, 0)
}
return b.informers, nil
}
// Run runs this custom metrics adapter until the given stop channel is closed.
func (b *AdapterBase) Run(stopCh <-chan struct{}) error {
server, err := b.Server()
if err != nil {
return err
}
return server.GenericAPIServer.PrepareRun().Run(stopCh)
}

View file

@ -18,7 +18,6 @@ package server
import (
"fmt"
"io"
"net"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/apiserver"
@ -32,20 +31,14 @@ type CustomMetricsAdapterServerOptions struct {
Authentication *genericoptions.DelegatingAuthenticationOptions
Authorization *genericoptions.DelegatingAuthorizationOptions
Features *genericoptions.FeatureOptions
StdOut io.Writer
StdErr io.Writer
}
func NewCustomMetricsAdapterServerOptions(out, errOut io.Writer) *CustomMetricsAdapterServerOptions {
func NewCustomMetricsAdapterServerOptions() *CustomMetricsAdapterServerOptions {
o := &CustomMetricsAdapterServerOptions{
SecureServing: genericoptions.WithLoopback(genericoptions.NewSecureServingOptions()),
Authentication: genericoptions.NewDelegatingAuthenticationOptions(),
Authorization: genericoptions.NewDelegatingAuthorizationOptions(),
Features: genericoptions.NewFeatureOptions(),
StdOut: out,
StdErr: errOut,
}
return o

View file

@ -0,0 +1,106 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package helpers
import (
"fmt"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"k8s.io/metrics/pkg/apis/custom_metrics"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider"
)
// ResourceFor attempts to resolve a single qualified resource for the given metric.
// You can use this to resolve a particular piece of CustomMetricInfo to the underlying
// resource that it describes, so that you can list matching objects in the cluster.
func ResourceFor(mapper apimeta.RESTMapper, info provider.CustomMetricInfo) (schema.GroupVersionResource, error) {
fullResources, err := mapper.ResourcesFor(info.GroupResource.WithVersion(""))
if err == nil && len(fullResources) == 0 {
err = fmt.Errorf("no fully versioned resources known for group-resource %v", info.GroupResource)
}
if err != nil {
return schema.GroupVersionResource{}, fmt.Errorf("unable to find preferred version to list matching resource names: %v", err)
}
return fullResources[0], nil
}
// ReferenceFor returns a new ObjectReference for the given group-resource and name.
// The group-resource is converted into a group-version-kind using the given RESTMapper.
// You can use this to easily construct an object reference for use in the DescribedObject
// field of CustomMetricInfo.
func ReferenceFor(mapper apimeta.RESTMapper, name types.NamespacedName, info provider.CustomMetricInfo) (custom_metrics.ObjectReference, error) {
kind, err := mapper.KindFor(info.GroupResource.WithVersion(""))
if err != nil {
return custom_metrics.ObjectReference{}, err
}
// NB: return straight value, not a reference, so that the object can easily
// be copied for use multiple times with a different name.
return custom_metrics.ObjectReference{
APIVersion: kind.Group + "/" + kind.Version,
Kind: kind.Kind,
Name: name.Name,
Namespace: name.Namespace,
}, nil
}
// ListObjectNames uses the given dynamic client to list the names of all objects
// of the given resource matching the given selector. Namespace may be empty
// if the metric is for a root-scoped resource.
func ListObjectNames(mapper apimeta.RESTMapper, client dynamic.Interface, namespace string, selector labels.Selector, info provider.CustomMetricInfo) ([]string, error) {
res, err := ResourceFor(mapper, info)
if err != nil {
return nil, err
}
var resClient dynamic.ResourceInterface
if info.Namespaced {
resClient = client.Resource(res).Namespace(namespace)
} else {
resClient = client.Resource(res)
}
matchingObjectsRaw, err := resClient.List(metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return nil, err
}
if !apimeta.IsListType(matchingObjectsRaw) {
return nil, fmt.Errorf("result of label selector list operation was not a list")
}
var names []string
err = apimeta.EachListItem(matchingObjectsRaw, func(item runtime.Object) error {
objName := item.(*unstructured.Unstructured).GetName()
names = append(names, objName)
return nil
})
if err != nil {
return nil, err
}
return names, nil
}

View file

@ -22,6 +22,7 @@ import (
apimeta "k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/metrics/pkg/apis/custom_metrics"
"k8s.io/metrics/pkg/apis/external_metrics"
)
@ -37,7 +38,6 @@ type CustomMetricInfo struct {
// ExternalMetricInfo describes a metric.
type ExternalMetricInfo struct {
Metric string
Labels map[string]string
}
func (i CustomMetricInfo) String() string {
@ -82,19 +82,13 @@ func (i CustomMetricInfo) Normalized(mapper apimeta.RESTMapper) (normalizedInfo
// they may wish to query the main Kubernetes API server, or may
// wish to simply make use of stored information in their TSDB.
type CustomMetricsProvider interface {
// GetRootScopedMetricByName fetches a particular metric for a particular root-scoped object.
GetRootScopedMetricByName(groupResource schema.GroupResource, name string, metricName string) (*custom_metrics.MetricValue, error)
// GetMetricByName fetches a particular metric for a particular object.
// The namespace will be empty if the metric is root-scoped.
GetMetricByName(name types.NamespacedName, info CustomMetricInfo) (*custom_metrics.MetricValue, error)
// GetRootScopedMetricByName fetches a particular metric for a set of root-scoped objects
// matching the given label selector.
GetRootScopedMetricBySelector(groupResource schema.GroupResource, selector labels.Selector, metricName string) (*custom_metrics.MetricValueList, error)
// GetNamespacedMetricByName fetches a particular metric for a particular namespaced object.
GetNamespacedMetricByName(groupResource schema.GroupResource, namespace string, name string, metricName string) (*custom_metrics.MetricValue, error)
// GetNamespacedMetricByName fetches a particular metric for a set of namespaced objects
// matching the given label selector.
GetNamespacedMetricBySelector(groupResource schema.GroupResource, namespace string, selector labels.Selector, metricName string) (*custom_metrics.MetricValueList, error)
// GetMetricBySelector fetches a particular metric for a set of objects matching
// the given label selector. The namespace will be empty if the metric is root-scoped.
GetMetricBySelector(namespace string, selector labels.Selector, info CustomMetricInfo) (*custom_metrics.MetricValueList, error)
// ListAllMetrics provides a list of all available metrics at
// the current time. Note that this is not allowed to return
@ -108,7 +102,7 @@ type CustomMetricsProvider interface {
// implementation how to translate metricSelector to a filter for metric values.
// Namespace can be used by the implemetation for metric identification, access control or ignored.
type ExternalMetricsProvider interface {
GetExternalMetric(namespace string, metricName string, metricSelector labels.Selector) (*external_metrics.ExternalMetricValueList, error)
GetExternalMetric(namespace string, metricSelector labels.Selector, info ExternalMetricInfo) (*external_metrics.ExternalMetricValueList, error)
ListAllExternalMetrics() []ExternalMetricInfo
}

View file

@ -25,6 +25,7 @@ import (
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/endpoints/request"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
@ -103,14 +104,11 @@ func (r *REST) List(ctx context.Context, options *metainternalversion.ListOption
}
func (r *REST) handleIndividualOp(namespace string, groupResource schema.GroupResource, name string, metricName string) (*custom_metrics.MetricValueList, error) {
var err error
var singleRes *custom_metrics.MetricValue
if namespace == "" {
singleRes, err = r.cmProvider.GetRootScopedMetricByName(groupResource, name, metricName)
} else {
singleRes, err = r.cmProvider.GetNamespacedMetricByName(groupResource, namespace, name, metricName)
}
singleRes, err := r.cmProvider.GetMetricByName(types.NamespacedName{Namespace: namespace, Name: name}, provider.CustomMetricInfo{
GroupResource: groupResource,
Metric: metricName,
Namespaced: namespace != "",
})
if err != nil {
return nil, err
}
@ -121,9 +119,9 @@ func (r *REST) handleIndividualOp(namespace string, groupResource schema.GroupRe
}
func (r *REST) handleWildcardOp(namespace string, groupResource schema.GroupResource, selector labels.Selector, metricName string) (*custom_metrics.MetricValueList, error) {
if namespace == "" {
return r.cmProvider.GetRootScopedMetricBySelector(groupResource, selector, metricName)
} else {
return r.cmProvider.GetNamespacedMetricBySelector(groupResource, namespace, selector, metricName)
}
return r.cmProvider.GetMetricBySelector(namespace, selector, provider.CustomMetricInfo{
GroupResource: groupResource,
Metric: metricName,
Namespaced: namespace != "",
})
}

View file

@ -76,5 +76,5 @@ func (r *REST) List(ctx context.Context, options *metainternalversion.ListOption
}
metricName := requestInfo.Resource
return r.emProvider.GetExternalMetric(namespace, metricName, metricSelector)
return r.emProvider.GetExternalMetric(namespace, metricSelector, provider.ExternalMetricInfo{Metric: metricName})
}