Check in the vendor directory

Travis seems to be having issues pulling deps, so we'll have to check in
the vendor directory and prevent the makefile from trying to regenerate
it normally.
This commit is contained in:
Solly Ross 2018-07-13 17:31:57 -04:00
parent 98e16bc315
commit a293b2bf94
2526 changed files with 930931 additions and 4 deletions

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.

View file

@ -0,0 +1,108 @@
/*
Copyright 2017 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 apiserver
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/version"
genericapiserver "k8s.io/apiserver/pkg/server"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider"
cminstall "k8s.io/metrics/pkg/apis/custom_metrics/install"
eminstall "k8s.io/metrics/pkg/apis/external_metrics/install"
)
var (
Scheme = runtime.NewScheme()
Codecs = serializer.NewCodecFactory(Scheme)
)
func init() {
cminstall.Install(Scheme)
eminstall.Install(Scheme)
// we need to add the options to empty v1
// TODO fix the server code to avoid this
metav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
// TODO: keep the generic API server from wanting this
unversioned := schema.GroupVersion{Group: "", Version: "v1"}
Scheme.AddUnversionedTypes(unversioned,
&metav1.Status{},
&metav1.APIVersions{},
&metav1.APIGroupList{},
&metav1.APIGroup{},
&metav1.APIResourceList{},
)
}
type Config struct {
GenericConfig *genericapiserver.Config
}
// CustomMetricsAdapterServer contains state for a Kubernetes cluster master/api server.
type CustomMetricsAdapterServer struct {
GenericAPIServer *genericapiserver.GenericAPIServer
customMetricsProvider provider.CustomMetricsProvider
externalMetricsProvider provider.ExternalMetricsProvider
}
type completedConfig struct {
genericapiserver.CompletedConfig
}
// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.
func (c *Config) Complete() completedConfig {
c.GenericConfig.Version = &version.Info{
Major: "1",
Minor: "0",
}
return completedConfig{c.GenericConfig.Complete(nil)}
}
// New returns a new instance of CustomMetricsAdapterServer from the given config.
// name is used to differentiate for logging.
// Each of the arguments: customMetricsProvider, externalMetricsProvider can be set either to
// a provider implementation, or to nil to disable one of the APIs.
func (c completedConfig) New(name string, customMetricsProvider provider.CustomMetricsProvider, externalMetricsProvider provider.ExternalMetricsProvider) (*CustomMetricsAdapterServer, error) {
genericServer, err := c.CompletedConfig.New(name, genericapiserver.NewEmptyDelegate()) // completion is done in Complete, no need for a second time
if err != nil {
return nil, err
}
s := &CustomMetricsAdapterServer{
GenericAPIServer: genericServer,
customMetricsProvider: customMetricsProvider,
externalMetricsProvider: externalMetricsProvider,
}
if customMetricsProvider != nil {
if err := s.InstallCustomMetricsAPI(); err != nil {
return nil, err
}
}
if externalMetricsProvider != nil {
if err := s.InstallExternalMetricsAPI(); err != nil {
return nil, err
}
}
return s, nil
}

View file

@ -0,0 +1,85 @@
/*
Copyright 2017 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 apiserver
import (
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
genericapi "k8s.io/apiserver/pkg/endpoints"
"k8s.io/apiserver/pkg/endpoints/discovery"
genericapiserver "k8s.io/apiserver/pkg/server"
specificapi "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/apiserver/installer"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider"
metricstorage "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/registry/custom_metrics"
"k8s.io/metrics/pkg/apis/custom_metrics"
)
func (s *CustomMetricsAdapterServer) InstallCustomMetricsAPI() error {
groupInfo := genericapiserver.NewDefaultAPIGroupInfo(custom_metrics.GroupName, Scheme, metav1.ParameterCodec, Codecs)
mainGroupVer := groupInfo.PrioritizedVersions[0]
preferredVersionForDiscovery := metav1.GroupVersionForDiscovery{
GroupVersion: mainGroupVer.String(),
Version: mainGroupVer.Version,
}
groupVersion := metav1.GroupVersionForDiscovery{
GroupVersion: mainGroupVer.String(),
Version: mainGroupVer.Version,
}
apiGroup := metav1.APIGroup{
Name: mainGroupVer.Group,
Versions: []metav1.GroupVersionForDiscovery{groupVersion},
PreferredVersion: preferredVersionForDiscovery,
}
cmAPI := s.cmAPI(&groupInfo, mainGroupVer)
if err := cmAPI.InstallREST(s.GenericAPIServer.Handler.GoRestfulContainer); err != nil {
return err
}
s.GenericAPIServer.DiscoveryGroupManager.AddGroup(apiGroup)
s.GenericAPIServer.Handler.GoRestfulContainer.Add(discovery.NewAPIGroupHandler(s.GenericAPIServer.Serializer, apiGroup).WebService())
return nil
}
func (s *CustomMetricsAdapterServer) cmAPI(groupInfo *genericapiserver.APIGroupInfo, groupVersion schema.GroupVersion) *specificapi.MetricsAPIGroupVersion {
resourceStorage := metricstorage.NewREST(s.customMetricsProvider)
return &specificapi.MetricsAPIGroupVersion{
DynamicStorage: resourceStorage,
APIGroupVersion: &genericapi.APIGroupVersion{
Root: genericapiserver.APIGroupPrefix,
GroupVersion: groupVersion,
MetaGroupVersion: groupInfo.MetaGroupVersion,
ParameterCodec: groupInfo.ParameterCodec,
Serializer: groupInfo.NegotiatedSerializer,
Creater: groupInfo.Scheme,
Convertor: groupInfo.Scheme,
UnsafeConvertor: runtime.UnsafeObjectConvertor(groupInfo.Scheme),
Typer: groupInfo.Scheme,
Linker: runtime.SelfLinker(meta.NewAccessor()),
},
ResourceLister: provider.NewCustomMetricResourceLister(s.customMetricsProvider),
Handlers: &specificapi.CMHandlers{},
}
}

View file

@ -0,0 +1,85 @@
/*
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 apiserver
import (
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
genericapi "k8s.io/apiserver/pkg/endpoints"
"k8s.io/apiserver/pkg/endpoints/discovery"
genericapiserver "k8s.io/apiserver/pkg/server"
specificapi "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/apiserver/installer"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider"
metricstorage "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/registry/external_metrics"
"k8s.io/metrics/pkg/apis/external_metrics"
)
// InstallExternalMetricsAPI registers the api server in Kube Aggregator
func (s *CustomMetricsAdapterServer) InstallExternalMetricsAPI() error {
groupInfo := genericapiserver.NewDefaultAPIGroupInfo(external_metrics.GroupName, Scheme, metav1.ParameterCodec, Codecs)
mainGroupVer := groupInfo.PrioritizedVersions[0]
preferredVersionForDiscovery := metav1.GroupVersionForDiscovery{
GroupVersion: mainGroupVer.String(),
Version: mainGroupVer.Version,
}
groupVersion := metav1.GroupVersionForDiscovery{
GroupVersion: mainGroupVer.String(),
Version: mainGroupVer.Version,
}
apiGroup := metav1.APIGroup{
Name: mainGroupVer.Group,
Versions: []metav1.GroupVersionForDiscovery{groupVersion},
PreferredVersion: preferredVersionForDiscovery,
}
emAPI := s.emAPI(&groupInfo, mainGroupVer)
if err := emAPI.InstallREST(s.GenericAPIServer.Handler.GoRestfulContainer); err != nil {
return err
}
s.GenericAPIServer.DiscoveryGroupManager.AddGroup(apiGroup)
s.GenericAPIServer.Handler.GoRestfulContainer.Add(discovery.NewAPIGroupHandler(s.GenericAPIServer.Serializer, apiGroup).WebService())
return nil
}
func (s *CustomMetricsAdapterServer) emAPI(groupInfo *genericapiserver.APIGroupInfo, groupVersion schema.GroupVersion) *specificapi.MetricsAPIGroupVersion {
resourceStorage := metricstorage.NewREST(s.externalMetricsProvider)
return &specificapi.MetricsAPIGroupVersion{
DynamicStorage: resourceStorage,
APIGroupVersion: &genericapi.APIGroupVersion{
Root: genericapiserver.APIGroupPrefix,
GroupVersion: groupVersion,
MetaGroupVersion: groupInfo.MetaGroupVersion,
ParameterCodec: groupInfo.ParameterCodec,
Serializer: groupInfo.NegotiatedSerializer,
Creater: groupInfo.Scheme,
Convertor: groupInfo.Scheme,
UnsafeConvertor: runtime.UnsafeObjectConvertor(groupInfo.Scheme),
Typer: groupInfo.Scheme,
Linker: runtime.SelfLinker(meta.NewAccessor()),
},
ResourceLister: provider.NewExternalMetricResourceLister(s.externalMetricsProvider),
Handlers: &specificapi.EMHandlers{},
}
}

View file

@ -0,0 +1,191 @@
/*
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 installer
import (
"net/http"
gpath "path"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apiserver/pkg/endpoints/handlers"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/metrics"
"k8s.io/apiserver/pkg/registry/rest"
"github.com/emicklei/go-restful"
)
type CMHandlers struct{}
// registerResourceHandlers registers the resource handlers for custom metrics.
// Compared to the normal installer, this plays fast and loose a bit, but should still
// follow the API conventions.
func (ch *CMHandlers) registerResourceHandlers(a *MetricsAPIInstaller, ws *restful.WebService) error {
optionsExternalVersion := a.group.GroupVersion
if a.group.OptionsExternalVersion != nil {
optionsExternalVersion = *a.group.OptionsExternalVersion
}
fqKindToRegister, err := a.getResourceKind(a.group.DynamicStorage)
if err != nil {
return err
}
kind := fqKindToRegister.Kind
lister := a.group.DynamicStorage.(rest.Lister)
list := lister.NewList()
listGVKs, _, err := a.group.Typer.ObjectKinds(list)
if err != nil {
return err
}
versionedListPtr, err := a.group.Creater.New(a.group.GroupVersion.WithKind(listGVKs[0].Kind))
if err != nil {
return err
}
versionedList := indirectArbitraryPointer(versionedListPtr)
versionedListOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind("ListOptions"))
if err != nil {
return err
}
nameParam := ws.PathParameter("name", "name of the described resource").DataType("string")
resourceParam := ws.PathParameter("resource", "the name of the resource").DataType("string")
subresourceParam := ws.PathParameter("subresource", "the name of the subresource").DataType("string")
// metrics describing non-namespaced objects (e.g. nodes)
rootScopedParams := []*restful.Parameter{
resourceParam,
nameParam,
subresourceParam,
}
rootScopedPath := "{resource}/{name}/{subresource}"
// metrics describing namespaced objects (e.g. pods)
namespaceParam := ws.PathParameter("namespace", "object name and auth scope, such as for teams and projects").DataType("string")
namespacedParams := []*restful.Parameter{
namespaceParam,
resourceParam,
nameParam,
subresourceParam,
}
namespacedPath := "namespaces/{namespace}/{resource}/{name}/{subresource}"
namespaceSpecificPath := "namespaces/{namespace}/metrics/{name}"
namespaceSpecificParams := []*restful.Parameter{
namespaceParam,
nameParam,
}
mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
allMediaTypes := append(mediaTypes, streamMediaTypes...)
ws.Produces(allMediaTypes...)
reqScope := handlers.RequestScope{
Serializer: a.group.Serializer,
ParameterCodec: a.group.ParameterCodec,
Creater: a.group.Creater,
Convertor: a.group.Convertor,
Typer: a.group.Typer,
UnsafeConvertor: a.group.UnsafeConvertor,
// TODO: support TableConvertor?
// TODO: This seems wrong for cross-group subresources. It makes an assumption that a subresource and its parent are in the same group version. Revisit this.
Resource: a.group.GroupVersion.WithResource("*"),
Subresource: "*",
Kind: fqKindToRegister,
MetaGroupVersion: metav1.SchemeGroupVersion,
}
if a.group.MetaGroupVersion != nil {
reqScope.MetaGroupVersion = *a.group.MetaGroupVersion
}
// we need one path for namespaced resources, one for non-namespaced resources
doc := "list custom metrics describing an object or objects"
reqScope.Namer = MetricsNaming{
handlers.ContextBasedNaming{
SelfLinker: a.group.Linker,
ClusterScoped: true,
SelfLinkPathPrefix: a.prefix + "/",
},
}
rootScopedHandler := metrics.InstrumentRouteFunc("LIST", "custom-metrics", "", "cluster", restfulListResource(lister, nil, reqScope, false, a.minRequestTimeout))
// install the root-scoped route
rootScopedRoute := ws.GET(rootScopedPath).To(rootScopedHandler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("list"+kind).
Produces(allMediaTypes...).
Returns(http.StatusOK, "OK", versionedList).
Writes(versionedList)
if err := addObjectParams(ws, rootScopedRoute, versionedListOptions); err != nil {
return err
}
addParams(rootScopedRoute, rootScopedParams)
ws.Route(rootScopedRoute)
// install the namespace-scoped route
reqScope.Namer = MetricsNaming{
handlers.ContextBasedNaming{
SelfLinker: a.group.Linker,
ClusterScoped: false,
SelfLinkPathPrefix: gpath.Join(a.prefix, "namespaces") + "/",
},
}
namespacedHandler := metrics.InstrumentRouteFunc("LIST", "custom-metrics-namespaced", "", "namespace", restfulListResource(lister, nil, reqScope, false, a.minRequestTimeout))
namespacedRoute := ws.GET(namespacedPath).To(namespacedHandler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("listNamespaced"+kind).
Produces(allMediaTypes...).
Returns(http.StatusOK, "OK", versionedList).
Writes(versionedList)
if err := addObjectParams(ws, namespacedRoute, versionedListOptions); err != nil {
return err
}
addParams(namespacedRoute, namespacedParams)
ws.Route(namespacedRoute)
// install the special route for metrics describing namespaces (last b/c we modify the context func)
reqScope.Namer = MetricsNaming{
handlers.ContextBasedNaming{
SelfLinker: a.group.Linker,
ClusterScoped: false,
SelfLinkPathPrefix: gpath.Join(a.prefix, "namespaces") + "/",
},
}
namespaceSpecificHandler := metrics.InstrumentRouteFunc("LIST", "custom-metrics-for-namespace", "", "cluster", restfulListResource(lister, nil, reqScope, false, a.minRequestTimeout))
namespaceSpecificRoute := ws.GET(namespaceSpecificPath).To(namespaceSpecificHandler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("read"+kind+"ForNamespace").
Produces(allMediaTypes...).
Returns(http.StatusOK, "OK", versionedList).
Writes(versionedList)
if err := addObjectParams(ws, namespaceSpecificRoute, versionedListOptions); err != nil {
return err
}
addParams(namespaceSpecificRoute, namespaceSpecificParams)
ws.Route(namespaceSpecificRoute)
return nil
}

View file

@ -0,0 +1,125 @@
/*
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 installer
import (
"net/http"
gpath "path"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apiserver/pkg/endpoints/handlers"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/metrics"
"k8s.io/apiserver/pkg/registry/rest"
"github.com/emicklei/go-restful"
)
type EMHandlers struct{}
// registerResourceHandlers registers the resource handlers for external metrics.
// The implementation is based on corresponding registerResourceHandlers for Custom Metrics API
func (ch *EMHandlers) registerResourceHandlers(a *MetricsAPIInstaller, ws *restful.WebService) error {
optionsExternalVersion := a.group.GroupVersion
if a.group.OptionsExternalVersion != nil {
optionsExternalVersion = *a.group.OptionsExternalVersion
}
fqKindToRegister, err := a.getResourceKind(a.group.DynamicStorage)
if err != nil {
return err
}
kind := fqKindToRegister.Kind
lister := a.group.DynamicStorage.(rest.Lister)
list := lister.NewList()
listGVKs, _, err := a.group.Typer.ObjectKinds(list)
if err != nil {
return err
}
versionedListPtr, err := a.group.Creater.New(a.group.GroupVersion.WithKind(listGVKs[0].Kind))
if err != nil {
return err
}
versionedList := indirectArbitraryPointer(versionedListPtr)
versionedListOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind("ListOptions"))
if err != nil {
return err
}
namespaceParam := ws.PathParameter("namespace", "object name and auth scope, such as for teams and projects").DataType("string")
nameParam := ws.PathParameter("name", "name of the described resource").DataType("string")
externalMetricParams := []*restful.Parameter{
namespaceParam,
nameParam,
}
externalMetricPath := "namespaces" + "/{namespace}/{resource}"
mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
allMediaTypes := append(mediaTypes, streamMediaTypes...)
ws.Produces(allMediaTypes...)
reqScope := handlers.RequestScope{
Serializer: a.group.Serializer,
ParameterCodec: a.group.ParameterCodec,
Creater: a.group.Creater,
Convertor: a.group.Convertor,
Typer: a.group.Typer,
UnsafeConvertor: a.group.UnsafeConvertor,
// TODO: support TableConvertor?
// TODO: This seems wrong for cross-group subresources. It makes an assumption that a subresource and its parent are in the same group version. Revisit this.
Resource: a.group.GroupVersion.WithResource("*"),
Subresource: "*",
Kind: fqKindToRegister,
MetaGroupVersion: metav1.SchemeGroupVersion,
}
if a.group.MetaGroupVersion != nil {
reqScope.MetaGroupVersion = *a.group.MetaGroupVersion
}
doc := "list external metrics"
reqScope.Namer = MetricsNaming{
handlers.ContextBasedNaming{
SelfLinker: a.group.Linker,
ClusterScoped: false,
SelfLinkPathPrefix: gpath.Join(a.prefix, "namespaces") + "/",
},
}
externalMetricHandler := metrics.InstrumentRouteFunc("LIST", "external-metrics", "", "", restfulListResource(lister, nil, reqScope, false, a.minRequestTimeout))
externalMetricRoute := ws.GET(externalMetricPath).To(externalMetricHandler).
Doc(doc).
Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
Operation("list"+kind).
Produces(allMediaTypes...).
Returns(http.StatusOK, "OK", versionedList).
Writes(versionedList)
if err := addObjectParams(ws, externalMetricRoute, versionedListOptions); err != nil {
return err
}
addParams(externalMetricRoute, externalMetricParams)
ws.Route(externalMetricRoute)
return nil
}

View file

@ -0,0 +1,288 @@
/*
Copyright 2017 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 installer
import (
"fmt"
gpath "path"
"reflect"
"strings"
"time"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apiserver/pkg/endpoints"
"k8s.io/apiserver/pkg/endpoints/discovery"
"k8s.io/apiserver/pkg/endpoints/handlers"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"github.com/emicklei/go-restful"
)
// NB: the contents of this file should mostly be a subset of the functionality
// in "k8s.io/apiserver/pkg/endpoints". It would be nice to eventual figure out
// a way to not have to recreate/copy a bunch of the structure from the normal API
// installer, so that this trivially tracks changes to the main installer.
// MetricsAPIGroupVersion is similar to "k8s.io/apiserver/pkg/endpoints".APIGroupVersion,
// except that it installs the metrics REST handlers, which use wildcard resources
// and subresources.
//
// This basically only serves the limitted use case required by the metrics API server --
// the only verb accepted is GET (and perhaps WATCH in the future).
type MetricsAPIGroupVersion struct {
DynamicStorage rest.Storage
*endpoints.APIGroupVersion
ResourceLister discovery.APIResourceLister
Handlers apiHandlers
}
type apiHandlers interface {
registerResourceHandlers(a *MetricsAPIInstaller, ws *restful.WebService) error
}
// InstallDynamicREST registers the dynamic REST handlers into a restful Container.
// It is expected that the provided path root prefix will serve all operations. Root MUST
// NOT end in a slash. It should mirror InstallREST in the plain APIGroupVersion.
func (g *MetricsAPIGroupVersion) InstallREST(container *restful.Container) error {
installer := g.newDynamicInstaller()
ws := installer.NewWebService()
registrationErrors := installer.Install(ws)
lister := g.ResourceLister
if lister == nil {
return fmt.Errorf("must provide a dynamic lister for dynamic API groups")
}
versionDiscoveryHandler := discovery.NewAPIVersionHandler(g.Serializer, g.GroupVersion, lister)
versionDiscoveryHandler.AddToWebService(ws)
container.Add(ws)
return utilerrors.NewAggregate(registrationErrors)
}
// newDynamicInstaller is a helper to create the installer. It mirrors
// newInstaller in APIGroupVersion.
func (g *MetricsAPIGroupVersion) newDynamicInstaller() *MetricsAPIInstaller {
prefix := gpath.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version)
installer := &MetricsAPIInstaller{
group: g,
prefix: prefix,
minRequestTimeout: g.MinRequestTimeout,
handlers: g.Handlers,
}
return installer
}
// MetricsAPIInstaller is a specialized API installer for the metrics API.
// It is intended to be fully compliant with the Kubernetes API server conventions,
// but serves wildcard resource/subresource routes instead of hard-coded resources
// and subresources.
type MetricsAPIInstaller struct {
group *MetricsAPIGroupVersion
prefix string // Path prefix where API resources are to be registered.
minRequestTimeout time.Duration
handlers apiHandlers
// TODO: do we want to embed a normal API installer here so we can serve normal
// endpoints side by side with dynamic ones (from the same API group)?
}
// Install installs handlers for External Metrics API resources.
func (a *MetricsAPIInstaller) Install(ws *restful.WebService) (errors []error) {
errors = make([]error, 0)
err := a.handlers.registerResourceHandlers(a, ws)
if err != nil {
errors = append(errors, fmt.Errorf("error in registering custom metrics resource: %v", err))
}
return errors
}
// NewWebService creates a new restful webservice with the api installer's prefix and version.
func (a *MetricsAPIInstaller) NewWebService() *restful.WebService {
ws := new(restful.WebService)
ws.Path(a.prefix)
// a.prefix contains "prefix/group/version"
ws.Doc("API at " + a.prefix)
// Backwards compatibility, we accepted objects with empty content-type at V1.
// If we stop using go-restful, we can default empty content-type to application/json on an
// endpoint by endpoint basis
ws.Consumes("*/*")
mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
ws.Produces(append(mediaTypes, streamMediaTypes...)...)
ws.ApiVersion(a.group.GroupVersion.String())
return ws
}
// This magic incantation returns *ptrToObject for an arbitrary pointer
func indirectArbitraryPointer(ptrToObject interface{}) interface{} {
return reflect.Indirect(reflect.ValueOf(ptrToObject)).Interface()
}
// getResourceKind returns the external group version kind registered for the given storage object.
func (a *MetricsAPIInstaller) getResourceKind(storage rest.Storage) (schema.GroupVersionKind, error) {
object := storage.New()
fqKinds, _, err := a.group.Typer.ObjectKinds(object)
if err != nil {
return schema.GroupVersionKind{}, err
}
// a given go type can have multiple potential fully qualified kinds. Find the one that corresponds with the group
// we're trying to register here
fqKindToRegister := schema.GroupVersionKind{}
for _, fqKind := range fqKinds {
if fqKind.Group == a.group.GroupVersion.Group {
fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind)
break
}
// TODO: keep rid of extensions api group dependency here
// This keeps it doing what it was doing before, but it doesn't feel right.
if fqKind.Group == "extensions" && fqKind.Kind == "ThirdPartyResourceData" {
fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind)
}
}
if fqKindToRegister.Empty() {
return schema.GroupVersionKind{}, fmt.Errorf("unable to locate fully qualified kind for %v: found %v when registering for %v", reflect.TypeOf(object), fqKinds, a.group.GroupVersion)
}
return fqKindToRegister, nil
}
func addParams(route *restful.RouteBuilder, params []*restful.Parameter) {
for _, param := range params {
route.Param(param)
}
}
// addObjectParams converts a runtime.Object into a set of go-restful Param() definitions on the route.
// The object must be a pointer to a struct; only fields at the top level of the struct that are not
// themselves interfaces or structs are used; only fields with a json tag that is non empty (the standard
// Go JSON behavior for omitting a field) become query parameters. The name of the query parameter is
// the JSON field name. If a description struct tag is set on the field, that description is used on the
// query parameter. In essence, it converts a standard JSON top level object into a query param schema.
func addObjectParams(ws *restful.WebService, route *restful.RouteBuilder, obj interface{}) error {
sv, err := conversion.EnforcePtr(obj)
if err != nil {
return err
}
st := sv.Type()
switch st.Kind() {
case reflect.Struct:
for i := 0; i < st.NumField(); i++ {
name := st.Field(i).Name
sf, ok := st.FieldByName(name)
if !ok {
continue
}
switch sf.Type.Kind() {
case reflect.Interface, reflect.Struct:
case reflect.Ptr:
// TODO: This is a hack to let metav1.Time through. This needs to be fixed in a more generic way eventually. bug #36191
if (sf.Type.Elem().Kind() == reflect.Interface || sf.Type.Elem().Kind() == reflect.Struct) && strings.TrimPrefix(sf.Type.String(), "*") != "metav1.Time" {
continue
}
fallthrough
default:
jsonTag := sf.Tag.Get("json")
if len(jsonTag) == 0 {
continue
}
jsonName := strings.SplitN(jsonTag, ",", 2)[0]
if len(jsonName) == 0 {
continue
}
var desc string
if docable, ok := obj.(documentable); ok {
desc = docable.SwaggerDoc()[jsonName]
}
route.Param(ws.QueryParameter(jsonName, desc).DataType(typeToJSON(sf.Type.String())))
}
}
}
return nil
}
// TODO: this is incomplete, expand as needed.
// Convert the name of a golang type to the name of a JSON type
func typeToJSON(typeName string) string {
switch typeName {
case "bool", "*bool":
return "boolean"
case "uint8", "*uint8", "int", "*int", "int32", "*int32", "int64", "*int64", "uint32", "*uint32", "uint64", "*uint64":
return "integer"
case "float64", "*float64", "float32", "*float32":
return "number"
case "metav1.Time", "*metav1.Time":
return "string"
case "byte", "*byte":
return "string"
case "v1.DeletionPropagation", "*v1.DeletionPropagation":
return "string"
// TODO: Fix these when go-restful supports a way to specify an array query param:
// https://github.com/emicklei/go-restful/issues/225
case "[]string", "[]*string":
return "string"
case "[]int32", "[]*int32":
return "integer"
default:
return typeName
}
}
// An interface to see if an object supports swagger documentation as a method
type documentable interface {
SwaggerDoc() map[string]string
}
// MetricsNaming is similar to handlers.ContextBasedNaming, except that it handles
// polymorphism over subresources.
type MetricsNaming struct {
handlers.ContextBasedNaming
}
func (n MetricsNaming) GenerateLink(requestInfo *request.RequestInfo, obj runtime.Object) (uri string, err error) {
if requestInfo.Resource != "metrics" {
n.SelfLinkPathSuffix += "/" + requestInfo.Subresource
}
// since this is not a pointer receiver, it's ok to modify it here
// (since we copy around every method call)
if n.ClusterScoped {
n.SelfLinkPathPrefix += requestInfo.Resource + "/"
return n.ContextBasedNaming.GenerateLink(requestInfo, obj)
}
return n.ContextBasedNaming.GenerateLink(requestInfo, obj)
}
func restfulListResource(r rest.Lister, rw rest.Watcher, scope handlers.RequestScope, forceWatch bool, minRequestTimeout time.Duration) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
handlers.ListResource(r, rw, scope, forceWatch, minRequestTimeout)(res.ResponseWriter, req.Request)
}
}

View file

@ -0,0 +1,87 @@
/*
Copyright 2017 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 server
import (
"fmt"
"io"
"net"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/apiserver"
genericapiserver "k8s.io/apiserver/pkg/server"
genericoptions "k8s.io/apiserver/pkg/server/options"
)
type CustomMetricsAdapterServerOptions struct {
// genericoptions.ReccomendedOptions - EtcdOptions
SecureServing *genericoptions.SecureServingOptionsWithLoopback
Authentication *genericoptions.DelegatingAuthenticationOptions
Authorization *genericoptions.DelegatingAuthorizationOptions
Features *genericoptions.FeatureOptions
StdOut io.Writer
StdErr io.Writer
}
func NewCustomMetricsAdapterServerOptions(out, errOut io.Writer) *CustomMetricsAdapterServerOptions {
o := &CustomMetricsAdapterServerOptions{
SecureServing: genericoptions.WithLoopback(genericoptions.NewSecureServingOptions()),
Authentication: genericoptions.NewDelegatingAuthenticationOptions(),
Authorization: genericoptions.NewDelegatingAuthorizationOptions(),
Features: genericoptions.NewFeatureOptions(),
StdOut: out,
StdErr: errOut,
}
return o
}
func (o CustomMetricsAdapterServerOptions) Validate(args []string) error {
return nil
}
func (o *CustomMetricsAdapterServerOptions) Complete() error {
return nil
}
func (o CustomMetricsAdapterServerOptions) Config() (*apiserver.Config, error) {
// TODO have a "real" external address (have an AdvertiseAddress?)
if err := o.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil {
return nil, fmt.Errorf("error creating self-signed certificates: %v", err)
}
serverConfig := genericapiserver.NewConfig(apiserver.Codecs)
if err := o.SecureServing.ApplyTo(serverConfig); err != nil {
return nil, err
}
if err := o.Authentication.ApplyTo(&serverConfig.Authentication, serverConfig.SecureServing, nil); err != nil {
return nil, err
}
if err := o.Authorization.ApplyTo(&serverConfig.Authorization); err != nil {
return nil, err
}
// TODO: we can't currently serve swagger because we don't have a good way to dynamically update it
// serverConfig.SwaggerConfig = genericapiserver.DefaultSwaggerConfig()
config := &apiserver.Config{
GenericConfig: serverConfig,
}
return config, nil
}

View file

@ -0,0 +1,152 @@
/*
Copyright 2016 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 dynamicmapper
import (
"fmt"
"github.com/emicklei/go-restful-swagger12"
"github.com/googleapis/gnostic/OpenAPIv2"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/version"
kubeversion "k8s.io/client-go/pkg/version"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/testing"
)
// NB: this is a copy of k8s.io/client-go/discovery/fake. The original returns `nil, nil`
// for some methods, which is generally confuses lots of code.
type FakeDiscovery struct {
*testing.Fake
}
func (c *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {
action := testing.ActionImpl{
Verb: "get",
Resource: schema.GroupVersionResource{Resource: "resource"},
}
c.Invokes(action, nil)
for _, resourceList := range c.Resources {
if resourceList.GroupVersion == groupVersion {
return resourceList, nil
}
}
return nil, fmt.Errorf("GroupVersion %q not found", groupVersion)
}
func (c *FakeDiscovery) ServerResources() ([]*metav1.APIResourceList, error) {
action := testing.ActionImpl{
Verb: "get",
Resource: schema.GroupVersionResource{Resource: "resource"},
}
c.Invokes(action, nil)
return c.Resources, nil
}
func (c *FakeDiscovery) ServerPreferredResources() ([]*metav1.APIResourceList, error) {
return nil, nil
}
func (c *FakeDiscovery) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) {
return nil, nil
}
func (c *FakeDiscovery) ServerGroups() (*metav1.APIGroupList, error) {
groups := map[string]*metav1.APIGroup{}
groupVersions := map[metav1.GroupVersionForDiscovery]struct{}{}
for _, resourceList := range c.Resources {
groupVer, err := schema.ParseGroupVersion(resourceList.GroupVersion)
if err != nil {
return nil, err
}
groupVerForDisc := metav1.GroupVersionForDiscovery{
GroupVersion: resourceList.GroupVersion,
Version: groupVer.Version,
}
group, groupPresent := groups[groupVer.Group]
if !groupPresent {
group = &metav1.APIGroup{
Name: groupVer.Group,
// use the fist seen version as the preferred version
PreferredVersion: groupVerForDisc,
}
groups[groupVer.Group] = group
}
// we'll dedup in the end by deleting the group-versions
// from the global map one at a time
group.Versions = append(group.Versions, groupVerForDisc)
groupVersions[groupVerForDisc] = struct{}{}
}
groupList := make([]metav1.APIGroup, 0, len(groups))
for _, group := range groups {
newGroup := metav1.APIGroup{
Name: group.Name,
PreferredVersion: group.PreferredVersion,
}
for _, groupVer := range group.Versions {
if _, ok := groupVersions[groupVer]; ok {
delete(groupVersions, groupVer)
newGroup.Versions = append(newGroup.Versions, groupVer)
}
}
groupList = append(groupList, newGroup)
}
return &metav1.APIGroupList{
Groups: groupList,
}, nil
}
func (c *FakeDiscovery) ServerVersion() (*version.Info, error) {
action := testing.ActionImpl{}
action.Verb = "get"
action.Resource = schema.GroupVersionResource{Resource: "version"}
c.Invokes(action, nil)
versionInfo := kubeversion.Get()
return &versionInfo, nil
}
func (c *FakeDiscovery) SwaggerSchema(version schema.GroupVersion) (*swagger.ApiDeclaration, error) {
action := testing.ActionImpl{}
action.Verb = "get"
if version == v1.SchemeGroupVersion {
action.Resource = schema.GroupVersionResource{Resource: "/swaggerapi/api/" + version.Version}
} else {
action.Resource = schema.GroupVersionResource{Resource: "/swaggerapi/apis/" + version.Group + "/" + version.Version}
}
c.Invokes(action, nil)
return &swagger.ApiDeclaration{}, nil
}
func (c *FakeDiscovery) OpenAPISchema() (*openapi_v2.Document, error) {
return &openapi_v2.Document{}, nil
}
func (c *FakeDiscovery) RESTClient() restclient.Interface {
return nil
}

View file

@ -0,0 +1,113 @@
package dynamicmapper
import (
"fmt"
"sync"
"time"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/discovery"
"k8s.io/client-go/restmapper"
)
// RengeneratingDiscoveryRESTMapper is a RESTMapper which Regenerates its cache of mappings periodically.
// It functions by recreating a normal discovery RESTMapper at the specified interval.
// We don't refresh automatically on cache misses, since we get called on every label, plenty of which will
// be unrelated to Kubernetes resources.
type RegeneratingDiscoveryRESTMapper struct {
discoveryClient discovery.DiscoveryInterface
refreshInterval time.Duration
mu sync.RWMutex
delegate meta.RESTMapper
}
func NewRESTMapper(discoveryClient discovery.DiscoveryInterface, refreshInterval time.Duration) (*RegeneratingDiscoveryRESTMapper, error) {
mapper := &RegeneratingDiscoveryRESTMapper{
discoveryClient: discoveryClient,
refreshInterval: refreshInterval,
}
if err := mapper.RegenerateMappings(); err != nil {
return nil, fmt.Errorf("unable to populate initial set of REST mappings: %v", err)
}
return mapper, nil
}
// RunUtil runs the mapping refresher until the given stop channel is closed.
func (m *RegeneratingDiscoveryRESTMapper) RunUntil(stop <-chan struct{}) {
go wait.Until(func() {
if err := m.RegenerateMappings(); err != nil {
glog.Errorf("error regenerating REST mappings from discovery: %v", err)
}
}, m.refreshInterval, stop)
}
func (m *RegeneratingDiscoveryRESTMapper) RegenerateMappings() error {
resources, err := restmapper.GetAPIGroupResources(m.discoveryClient)
if err != nil {
return err
}
newDelegate := restmapper.NewDiscoveryRESTMapper(resources)
// don't lock until we're ready to replace
m.mu.Lock()
defer m.mu.Unlock()
m.delegate = newDelegate
return nil
}
func (m *RegeneratingDiscoveryRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
m.mu.RLock()
defer m.mu.RUnlock()
return m.delegate.KindFor(resource)
}
func (m *RegeneratingDiscoveryRESTMapper) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {
m.mu.RLock()
defer m.mu.RUnlock()
return m.delegate.KindsFor(resource)
}
func (m *RegeneratingDiscoveryRESTMapper) ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error) {
m.mu.RLock()
defer m.mu.RUnlock()
return m.delegate.ResourceFor(input)
}
func (m *RegeneratingDiscoveryRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
m.mu.RLock()
defer m.mu.RUnlock()
return m.delegate.ResourcesFor(input)
}
func (m *RegeneratingDiscoveryRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) {
m.mu.RLock()
defer m.mu.RUnlock()
return m.delegate.RESTMapping(gk, versions...)
}
func (m *RegeneratingDiscoveryRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error) {
m.mu.RLock()
defer m.mu.RUnlock()
return m.delegate.RESTMappings(gk, versions...)
}
func (m *RegeneratingDiscoveryRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {
m.mu.RLock()
defer m.mu.RUnlock()
return m.delegate.ResourceSingularizer(resource)
}

View file

@ -0,0 +1,49 @@
/*
Copyright 2017 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 provider
import (
"fmt"
"net/http"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// NewMetricNotFoundError returns a StatusError indicating the given metric could not be found.
// It is similar to NewNotFound, but more specialized
func NewMetricNotFoundError(resource schema.GroupResource, metricName string) *apierr.StatusError {
return &apierr.StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: int32(http.StatusNotFound),
Reason: metav1.StatusReasonNotFound,
Message: fmt.Sprintf("the server could not find the metric %s for %s", metricName, resource.String()),
}}
}
// NewMetricNotFoundForError returns a StatusError indicating the given metric could not be found for
// the given named object. It is similar to NewNotFound, but more specialized
func NewMetricNotFoundForError(resource schema.GroupResource, metricName string, resourceName string) *apierr.StatusError {
return &apierr.StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: int32(http.StatusNotFound),
Reason: metav1.StatusReasonNotFound,
Message: fmt.Sprintf("the server could not find the metric %s for %s %s", metricName, resource.String(), resourceName),
}}
}

View file

@ -0,0 +1,119 @@
/*
Copyright 2017 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 provider
import (
"fmt"
apimeta "k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/metrics/pkg/apis/custom_metrics"
"k8s.io/metrics/pkg/apis/external_metrics"
)
// CustomMetricInfo describes a metric for a particular
// fully-qualified group resource.
type CustomMetricInfo struct {
GroupResource schema.GroupResource
Namespaced bool
Metric string
}
// ExternalMetricInfo describes a metric.
type ExternalMetricInfo struct {
Metric string
Labels map[string]string
}
func (i CustomMetricInfo) String() string {
if i.Namespaced {
return fmt.Sprintf("%s/%s(namespaced)", i.GroupResource.String(), i.Metric)
} else {
return fmt.Sprintf("%s/%s", i.GroupResource.String(), i.Metric)
}
}
// Normalized returns a copy of the current MetricInfo with the GroupResource resolved using the
// provided REST mapper, to ensure consistent pluralization, etc, for use when looking up or comparing
// the MetricInfo. It also returns the singular form of the GroupResource associated with the given
// MetricInfo.
func (i CustomMetricInfo) Normalized(mapper apimeta.RESTMapper) (normalizedInfo CustomMetricInfo, singluarResource string, err error) {
normalizedGroupRes, err := mapper.ResourceFor(i.GroupResource.WithVersion(""))
if err != nil {
return i, "", err
}
i.GroupResource = normalizedGroupRes.GroupResource()
singularResource, err := mapper.ResourceSingularizer(i.GroupResource.Resource)
if err != nil {
return i, "", err
}
return i, singularResource, nil
}
// CustomMetricsProvider is a source of custom metrics
// which is able to supply a list of available metrics,
// as well as metric values themselves on demand.
//
// Note that group-resources are provided as GroupResources,
// not GroupKinds. This is to allow flexibility on the part
// of the implementor: implementors do not necessarily need
// to be aware of all existing kinds and their corresponding
// REST mappings in order to perform queries.
//
// For queries that use label selectors, it is up to the
// implementor to decide how to make use of the label selector --
// 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)
// 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)
// ListAllMetrics provides a list of all available metrics at
// the current time. Note that this is not allowed to return
// an error, so it is reccomended that implementors cache and
// periodically update this list, instead of querying every time.
ListAllMetrics() []CustomMetricInfo
}
// ExternalMetricsProvider is a source of external metrics.
// Metric is normally idendified by a name and a set of labels/tags. It is up to a specific
// 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)
ListAllExternalMetrics() []ExternalMetricInfo
}
type MetricsProvider interface {
CustomMetricsProvider
ExternalMetricsProvider
}

View file

@ -0,0 +1,77 @@
/*
Copyright 2017 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 provider
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apiserver/pkg/endpoints/discovery"
)
type customMetricsResourceLister struct {
provider CustomMetricsProvider
}
type externalMetricsResourceLister struct {
provider ExternalMetricsProvider
}
// NewCustomMetricResourceLister creates APIResourceLister for provided CustomMetricsProvider.
func NewCustomMetricResourceLister(provider CustomMetricsProvider) discovery.APIResourceLister {
return &customMetricsResourceLister{
provider: provider,
}
}
func (l *customMetricsResourceLister) ListAPIResources() []metav1.APIResource {
metrics := l.provider.ListAllMetrics()
resources := make([]metav1.APIResource, len(metrics))
for i, metric := range metrics {
resources[i] = metav1.APIResource{
Name: metric.GroupResource.String() + "/" + metric.Metric,
Namespaced: metric.Namespaced,
Kind: "MetricValueList",
Verbs: metav1.Verbs{"get"}, // TODO: support "watch"
}
}
return resources
}
// NewExternalMetricResourceLister creates APIResourceLister for provided CustomMetricsProvider.
func NewExternalMetricResourceLister(provider ExternalMetricsProvider) discovery.APIResourceLister {
return &externalMetricsResourceLister{
provider: provider,
}
}
// ListAPIResources lists all supported custom metrics.
func (l *externalMetricsResourceLister) ListAPIResources() []metav1.APIResource {
metrics := l.provider.ListAllExternalMetrics()
resources := make([]metav1.APIResource, len(metrics))
for i, metric := range metrics {
resources[i] = metav1.APIResource{
Name: metric.Metric,
Namespaced: true,
Kind: "ExternalMetricValueList",
Verbs: metav1.Verbs{"get"},
}
}
return resources
}

View file

@ -0,0 +1,129 @@
/*
Copyright 2017 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 apiserver
import (
"context"
"fmt"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/endpoints/request"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/metrics/pkg/apis/custom_metrics"
)
type REST struct {
cmProvider provider.CustomMetricsProvider
}
var _ rest.Storage = &REST{}
var _ rest.Lister = &REST{}
func NewREST(cmProvider provider.CustomMetricsProvider) *REST {
return &REST{
cmProvider: cmProvider,
}
}
// Implement Storage
func (r *REST) New() runtime.Object {
return &custom_metrics.MetricValue{}
}
// Implement Lister
func (r *REST) NewList() runtime.Object {
return &custom_metrics.MetricValueList{}
}
func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
// populate the label selector, defaulting to all
selector := labels.Everything()
if options != nil && options.LabelSelector != nil {
selector = options.LabelSelector
}
// grab the name, if present, from the field selector list options
// (this is how the list handler logic injects it)
// (otherwise we'd have to write a custom list handler)
name := "*"
if options != nil && options.FieldSelector != nil {
if nameMatch, required := options.FieldSelector.RequiresExactMatch("metadata.name"); required {
name = nameMatch
}
}
namespace := genericapirequest.NamespaceValue(ctx)
requestInfo, ok := request.RequestInfoFrom(ctx)
if !ok {
return nil, fmt.Errorf("unable to get resource and metric name from request")
}
resourceRaw := requestInfo.Resource
metricName := requestInfo.Subresource
groupResource := schema.ParseGroupResource(resourceRaw)
// handle metrics describing namespaces
if namespace != "" && resourceRaw == "metrics" {
// namespace-describing metrics have a path of /namespaces/$NS/metrics/$metric,
groupResource = schema.GroupResource{Resource: "namespaces"}
metricName = name
name = namespace
namespace = ""
}
// handle namespaced and root metrics
if name == "*" {
return r.handleWildcardOp(namespace, groupResource, selector, metricName)
} else {
return r.handleIndividualOp(namespace, groupResource, name, metricName)
}
}
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)
}
if err != nil {
return nil, err
}
return &custom_metrics.MetricValueList{
Items: []custom_metrics.MetricValue{*singleRes},
}, nil
}
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)
}
}

View file

@ -0,0 +1,80 @@
/*
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 apiserver
import (
"context"
"fmt"
"github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/endpoints/request"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/metrics/pkg/apis/external_metrics"
)
// REST is a wrapper for CustomMetricsProvider that provides implementation for Storage and Lister
// interfaces.
type REST struct {
emProvider provider.ExternalMetricsProvider
}
var _ rest.Storage = &REST{}
var _ rest.Lister = &REST{}
// NewREST returns new REST object for provided CustomMetricsProvider.
func NewREST(emProvider provider.ExternalMetricsProvider) *REST {
return &REST{
emProvider: emProvider,
}
}
// Implement Storage
// New returns empty MetricValue.
func (r *REST) New() runtime.Object {
return &external_metrics.ExternalMetricValue{}
}
// Implement Lister
// NewList returns empty MetricValueList.
func (r *REST) NewList() runtime.Object {
return &external_metrics.ExternalMetricValueList{}
}
// List selects resources in the storage which match to the selector.
func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
// populate the label selector, defaulting to all
metricSelector := labels.Everything()
if options != nil && options.LabelSelector != nil {
metricSelector = options.LabelSelector
}
namespace := genericapirequest.NamespaceValue(ctx)
requestInfo, ok := request.RequestInfoFrom(ctx)
if !ok {
return nil, fmt.Errorf("unable to get resource and metric name from request")
}
metricName := requestInfo.Resource
return r.emProvider.GetExternalMetric(namespace, metricName, metricSelector)
}