/
cmhandlers.go
212 lines (181 loc) · 7.26 KB
/
cmhandlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/*
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/endpoints/request"
"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 {
context := a.group.Context
optionsExternalVersion := a.group.GroupVersion
if a.group.OptionsExternalVersion != nil {
optionsExternalVersion = *a.group.OptionsExternalVersion
}
mapping, err := a.restMapping()
if err != nil {
return err
}
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
}
ctxFn := func(req *http.Request) request.Context {
if ctx, ok := context.Get(req); ok {
return request.WithUserAgent(ctx, req.Header.Get("User-Agent"))
}
return request.WithUserAgent(request.NewContext(), req.Header.Get("User-Agent"))
}
scope := mapping.Scope
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(scope.ArgumentName(), scope.ParamDescription()).DataType("string")
namespacedParams := []*restful.Parameter{
namespaceParam,
resourceParam,
nameParam,
subresourceParam,
}
namespacedPath := scope.ParamName() + "/{" + scope.ArgumentName() + "}/{resource}/{name}/{subresource}"
namespaceSpecificPath := scope.ParamName() + "/{" + scope.ArgumentName() + "}/metrics/{name}"
namespaceSpecificParams := []*restful.Parameter{
namespaceParam,
nameParam,
}
mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
allMediaTypes := append(mediaTypes, streamMediaTypes...)
ws.Produces(allMediaTypes...)
reqScope := handlers.RequestScope{
ContextFunc: ctxFn,
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{
GetContext: ctxFn,
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{
GetContext: ctxFn,
SelfLinker: a.group.Linker,
ClusterScoped: false,
SelfLinkPathPrefix: gpath.Join(a.prefix, scope.ParamName()) + "/",
},
}
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.ContextFunc = ctxFn
reqScope.Namer = MetricsNaming{
handlers.ContextBasedNaming{
GetContext: ctxFn,
SelfLinker: a.group.Linker,
ClusterScoped: false,
SelfLinkPathPrefix: gpath.Join(a.prefix, scope.ParamName()) + "/",
},
}
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
}