/
gvclient.go
556 lines (523 loc) · 18.1 KB
/
gvclient.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package k8s
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/rest"
"github.com/grafana/grafana-app-sdk/resource"
)
const (
versionLabel = "grafana-app-sdk-resource-version"
// AnnotationPrefix is the prefix used in annotations which contain grafana kind metadata
AnnotationPrefix = "grafana.com/"
)
// groupVersionClient is the underlying client both Client and SchemalessClient use.
// GroupVersion is the unit with which kubernetes rest.Interface clients exist, so at minimum,
// we require one rest.Interface for each unique GroupVersion.
type groupVersionClient struct {
client rest.Interface
version string
config ClientConfig
requestDurations *prometheus.HistogramVec
totalRequests *prometheus.CounterVec
}
func (g *groupVersionClient) get(ctx context.Context, identifier resource.Identifier, plural string,
into resource.Object, codec resource.Codec) error {
ctx, span := GetTracer().Start(ctx, "kubernetes-get")
defer span.End()
sc := 0
request := g.client.Get().Resource(plural).Name(identifier.Name)
if strings.TrimSpace(identifier.Namespace) != "" {
request = request.Namespace(identifier.Namespace)
}
start := time.Now()
raw, err := request.Do(ctx).StatusCode(&sc).Raw()
g.logRequestDuration(time.Since(start), sc, "GET", plural, "spec")
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodGet),
attribute.String("server.address", request.URL().Hostname()),
attribute.String("server.port", request.URL().Port()),
attribute.String("url.full", request.URL().String()),
)
g.incRequestCounter(sc, "GET", plural, "spec")
if err != nil {
err = parseKubernetesError(raw, sc, err)
span.SetStatus(codes.Error, err.Error())
return err
}
err = codec.Read(bytes.NewReader(raw), into)
if err != nil {
span.SetStatus(codes.Error, err.Error())
}
return err
}
type metadataObject struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
}
func (g *groupVersionClient) getMetadata(ctx context.Context, identifier resource.Identifier, plural string) (
*metadataObject, error) {
ctx, span := GetTracer().Start(ctx, "kubernetes-getmetadata")
defer span.End()
sc := 0
request := g.client.Get().Resource(plural).Name(identifier.Name)
if strings.TrimSpace(identifier.Namespace) != "" {
request = request.Namespace(identifier.Namespace)
}
start := time.Now()
raw, err := request.Do(ctx).StatusCode(&sc).Raw()
g.logRequestDuration(time.Since(start), sc, "GET", plural, "spec")
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodGet),
attribute.String("server.address", request.URL().Hostname()),
attribute.String("server.port", request.URL().Port()),
attribute.String("url.full", request.URL().String()),
)
g.incRequestCounter(sc, "GET", plural, "spec")
if err != nil {
err = parseKubernetesError(raw, sc, err)
span.SetStatus(codes.Error, err.Error())
return nil, err
}
md := metadataObject{}
err = json.Unmarshal(raw, &md)
if err != nil {
span.SetStatus(codes.Error, fmt.Sprintf("unable to unmarshal request body: %s", err.Error()))
return nil, err
}
return &md, nil
}
//nolint:unused
func (g *groupVersionClient) exists(ctx context.Context, identifier resource.Identifier, plural string) (
bool, error) {
ctx, span := GetTracer().Start(ctx, "kubernetes-exists")
defer span.End()
sc := 0
request := g.client.Get().Resource(plural).Name(identifier.Name)
if strings.TrimSpace(identifier.Namespace) != "" {
request = request.Namespace(identifier.Namespace)
}
start := time.Now()
err := request.Do(ctx).StatusCode(&sc).Error()
g.logRequestDuration(time.Since(start), sc, "GET", plural, "spec")
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodGet),
attribute.String("server.address", request.URL().Hostname()),
attribute.String("server.port", request.URL().Port()),
attribute.String("url.full", request.URL().String()),
)
g.incRequestCounter(sc, "GET", plural, "spec")
if err != nil {
// HTTP error?
if sc == http.StatusNotFound {
return false, nil
}
if sc > 0 {
span.SetStatus(codes.Error, err.Error())
return false, NewServerResponseError(err, sc)
}
span.SetStatus(codes.Error, err.Error())
return false, err
}
return true, nil
}
func (g *groupVersionClient) create(ctx context.Context, plural string, obj resource.Object,
into resource.Object, codec resource.Codec) error {
ctx, span := GetTracer().Start(ctx, "kubernetes-create")
defer span.End()
addLabels(obj, map[string]string{
versionLabel: g.version,
})
buf := &bytes.Buffer{}
err := codec.Write(buf, obj)
if err != nil {
span.SetStatus(codes.Error, fmt.Sprintf("error marshaling kubernetes JSON: %s", err.Error()))
return err
}
sc := 0
request := g.client.Post().Resource(plural).Body(buf.Bytes())
if strings.TrimSpace(obj.GetNamespace()) != "" {
request = request.Namespace(obj.GetNamespace())
}
start := time.Now()
raw, err := request.Do(ctx).StatusCode(&sc).Raw()
g.logRequestDuration(time.Since(start), sc, "CREATE", plural, "spec")
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodPost),
attribute.String("server.address", request.URL().Hostname()),
attribute.String("server.port", request.URL().Port()),
attribute.String("url.full", request.URL().String()),
)
g.incRequestCounter(sc, "CREATE", plural, "spec")
if err != nil {
err = parseKubernetesError(raw, sc, err)
span.SetStatus(codes.Error, err.Error())
return err
}
err = codec.Read(bytes.NewReader(raw), into)
if err != nil {
span.SetStatus(codes.Error, fmt.Sprintf("unable to convert kubernetes response to resource: %s", err.Error()))
return err
}
return nil
}
func (g *groupVersionClient) update(ctx context.Context, plural string, obj resource.Object,
into resource.Object, _ resource.UpdateOptions, codec resource.Codec) error {
ctx, span := GetTracer().Start(ctx, "kubernetes-update")
defer span.End()
addLabels(obj, map[string]string{
versionLabel: g.version,
})
buf := &bytes.Buffer{}
err := codec.Write(buf, obj)
if err != nil {
span.SetStatus(codes.Error, fmt.Sprintf("error marshaling kubernetes JSON: %s", err.Error()))
return err
}
req := g.client.Put().Resource(plural).
Name(obj.GetName()).Body(buf.Bytes())
if strings.TrimSpace(obj.GetNamespace()) != "" {
req = req.Namespace(obj.GetNamespace())
}
sc := 0
start := time.Now()
raw, err := req.Do(ctx).StatusCode(&sc).Raw()
g.logRequestDuration(time.Since(start), sc, "UPDATE", plural, "spec")
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodPut),
attribute.String("server.address", req.URL().Hostname()),
attribute.String("server.port", req.URL().Port()),
attribute.String("url.full", req.URL().String()),
)
g.incRequestCounter(sc, "UPDATE", plural, "spec")
if err != nil {
err = parseKubernetesError(raw, sc, err)
span.SetStatus(codes.Error, err.Error())
return err
}
err = codec.Read(bytes.NewReader(raw), into)
if err != nil {
span.SetStatus(codes.Error, fmt.Sprintf("unable to convert kubernetes response to resource: %s", err.Error()))
return err
}
return nil
}
func (g *groupVersionClient) updateSubresource(ctx context.Context, plural, subresource string, obj resource.Object,
into resource.Object, _ resource.UpdateOptions, codec resource.Codec) error {
ctx, span := GetTracer().Start(ctx, "kubernetes-update-subresource")
defer span.End()
addLabels(obj, map[string]string{
versionLabel: g.version,
})
buf := &bytes.Buffer{}
err := codec.Write(buf, obj)
if err != nil {
span.SetStatus(codes.Error, fmt.Sprintf("error marshaling kubernetes JSON: %s", err.Error()))
return err
}
req := g.client.Put().Resource(plural).SubResource(subresource).
Name(obj.GetName()).Body(buf.Bytes())
if strings.TrimSpace(obj.GetNamespace()) != "" {
req = req.Namespace(obj.GetNamespace())
}
sc := 0
start := time.Now()
raw, err := req.Do(ctx).StatusCode(&sc).Raw()
g.logRequestDuration(time.Since(start), sc, "UPDATE", plural, subresource)
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodPut),
attribute.String("server.address", req.URL().Hostname()),
attribute.String("server.port", req.URL().Port()),
attribute.String("url.full", req.URL().String()),
)
g.incRequestCounter(sc, "UPDATE", plural, subresource)
if err != nil {
err = parseKubernetesError(raw, sc, err)
span.SetStatus(codes.Error, err.Error())
return err
}
err = codec.Read(bytes.NewReader(raw), into)
if err != nil {
span.SetStatus(codes.Error, fmt.Sprintf("unable to convert kubernetes response to resource: %s", err.Error()))
return err
}
return nil
}
//nolint:revive,unused
func (g *groupVersionClient) patch(ctx context.Context, identifier resource.Identifier, plural string,
patch resource.PatchRequest, into resource.Object, _ resource.PatchOptions, codec resource.Codec) error {
ctx, span := GetTracer().Start(ctx, "kubernetes-patch")
defer span.End()
patchBytes, err := marshalJSONPatch(patch)
if err != nil {
return err
}
req := g.client.Patch(types.JSONPatchType).Resource(plural).
Name(identifier.Name).Body(patchBytes)
if strings.TrimSpace(identifier.Namespace) != "" {
req = req.Namespace(identifier.Namespace)
}
sc := 0
start := time.Now()
raw, err := req.Do(ctx).StatusCode(&sc).Raw()
g.logRequestDuration(time.Since(start), sc, "PATCH", plural, "spec")
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodPatch),
attribute.String("server.address", req.URL().Hostname()),
attribute.String("server.port", req.URL().Port()),
attribute.String("url.full", req.URL().String()),
)
g.incRequestCounter(sc, "PATCH", plural, "spec")
if err != nil {
err = parseKubernetesError(raw, sc, err)
span.SetStatus(codes.Error, err.Error())
return err
}
err = codec.Read(bytes.NewReader(raw), into)
if err != nil {
span.SetStatus(codes.Error, fmt.Sprintf("unable to convert kubernetes response to resource: %s", err.Error()))
return err
}
return nil
}
func (g *groupVersionClient) delete(ctx context.Context, identifier resource.Identifier, plural string) error {
ctx, span := GetTracer().Start(ctx, "kubernetes-delete")
defer span.End()
sc := 0
request := g.client.Delete().Resource(plural).Name(identifier.Name)
if strings.TrimSpace(identifier.Namespace) != "" {
request = request.Namespace(identifier.Namespace)
}
start := time.Now()
err := request.Do(ctx).StatusCode(&sc).Error()
g.logRequestDuration(time.Since(start), sc, "DELETE", plural, "spec")
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodDelete),
attribute.String("server.address", request.URL().Hostname()),
attribute.String("server.port", request.URL().Port()),
attribute.String("url.full", request.URL().String()),
)
g.incRequestCounter(sc, "DELETE", plural, "spec")
if err != nil && sc >= 300 {
return NewServerResponseError(err, sc)
}
return err
}
func (g *groupVersionClient) list(ctx context.Context, namespace, plural string, into resource.ListObject,
options resource.ListOptions, itemParser func([]byte) (resource.Object, error)) error {
ctx, span := GetTracer().Start(ctx, "kubernetes-list")
defer span.End()
req := g.client.Get().Resource(plural)
if strings.TrimSpace(namespace) != "" {
req = req.Namespace(namespace)
}
if len(options.LabelFilters) > 0 {
req = req.Param("labelSelector", strings.Join(options.LabelFilters, ","))
}
if options.Limit > 0 {
req = req.Param("limit", strconv.Itoa(options.Limit))
}
if options.Continue != "" {
req = req.Param("continue", options.Continue)
}
if options.ResourceVersion != "" {
req = req.Param("resourceVersion", options.ResourceVersion)
}
sc := 0
start := time.Now()
raw, err := req.Do(ctx).StatusCode(&sc).Raw()
g.logRequestDuration(time.Since(start), sc, "LIST", plural, "spec")
span.SetAttributes(
attribute.Int("http.response.status_code", sc),
attribute.String("http.request.method", http.MethodGet),
attribute.String("server.address", req.URL().Hostname()),
attribute.String("server.port", req.URL().Port()),
attribute.String("url.full", req.URL().String()),
)
g.incRequestCounter(sc, "LIST", plural, "spec")
if err != nil {
err = parseKubernetesError(raw, sc, err)
span.SetStatus(codes.Error, err.Error())
return err
}
return rawToListWithParser(raw, into, itemParser)
}
//nolint:revive
func (g *groupVersionClient) watch(ctx context.Context, namespace, plural string,
exampleObject resource.Object, options resource.WatchOptions, codec resource.Codec) (*WatchResponse, error) {
ctx, span := GetTracer().Start(ctx, "kubernetes-watch")
defer span.End()
g.client.Get()
req := g.client.Get().Resource(plural).
Param("watch", "1")
if strings.TrimSpace(namespace) != "" {
req = req.Namespace(namespace)
}
if len(options.LabelFilters) > 0 {
req = req.Param("labelSelector", strings.Join(options.LabelFilters, ","))
}
if options.ResourceVersion != "" {
req = req.Param("resourceVersion", options.ResourceVersion)
}
resp, err := req.Watch(ctx)
if err != nil {
span.SetStatus(codes.Error, err.Error())
return nil, err
}
span.SetAttributes(
attribute.Int("http.response.status_code", http.StatusOK),
attribute.String("http.request.method", http.MethodGet),
attribute.String("server.address", req.URL().Hostname()),
attribute.String("server.port", req.URL().Port()),
attribute.String("url.full", req.URL().String()),
)
g.incRequestCounter(http.StatusOK, "WATCH", plural, "spec")
channelBufferSize := options.EventBufferSize
if channelBufferSize <= 0 {
channelBufferSize = 1
}
w := &WatchResponse{
ex: exampleObject,
codec: codec,
watch: resp,
ch: make(chan resource.WatchEvent, channelBufferSize),
stopCh: make(chan struct{}),
}
return w, nil
}
func (g *groupVersionClient) incRequestCounter(statusCode int, verb, kind, subresource string) {
if g.totalRequests == nil {
return
}
g.totalRequests.WithLabelValues(strconv.Itoa(statusCode), verb, kind, subresource).Inc()
}
func (g *groupVersionClient) logRequestDuration(dur time.Duration, statusCode int, verb, kind, subresource string) {
if g.requestDurations == nil {
return
}
g.requestDurations.WithLabelValues(strconv.Itoa(statusCode), verb, kind, subresource).Observe(dur.Seconds())
}
func (g *groupVersionClient) metrics() []prometheus.Collector {
return []prometheus.Collector{
g.totalRequests, g.requestDurations,
}
}
// WatchResponse wraps a kubernetes watch.Interface in order to implement resource.WatchResponse.
// The underlying watch.Interface can be accessed with KubernetesWatch().
type WatchResponse struct {
watch watch.Interface
ch chan resource.WatchEvent
stopCh chan struct{}
ex resource.Object
codec resource.Codec
started bool
}
//nolint:revive,staticcheck
func (w *WatchResponse) start() {
for {
select {
case evt := <-w.watch.ResultChan():
var obj resource.Object
if cast, ok := evt.Object.(intoObject); ok {
obj = w.ex.Copy()
err := cast.Into(obj, w.codec)
if err != nil {
// TODO: hmm
break
}
} else if cast, ok := evt.Object.(wrappedObject); ok {
obj = cast.ResourceObject()
} else {
// TODO: hmm
}
w.ch <- resource.WatchEvent{
EventType: string(evt.Type),
Object: obj,
}
case <-w.stopCh:
close(w.stopCh)
return
}
}
}
// Stop stops the translation channel between the kubernetes watch.Interface,
// and stops the continued watch request encapsulated by the watch.Interface.
func (w *WatchResponse) Stop() {
w.stopCh <- struct{}{}
close(w.ch)
w.watch.Stop()
}
// WatchEvents returns a channel that receives watch events.
// All calls to this method will return the same channel.
// This channel will stop receiving events if KubernetesWatch() is called, as that halts the event translation process.
// If Stop() is called, ths channel is closed.
func (w *WatchResponse) WatchEvents() <-chan resource.WatchEvent {
if !w.started {
// Start the translation buffer
go w.start()
}
return w.ch
}
// KubernetesWatch returns the underlying watch.Interface.
// Calling this method will shut down the translation channel between the watch.Interface and ResultChan().
// Using both KubernetesWatch() and ResultChan() simultaneously is not supported, and may result in undefined behavior.
func (w *WatchResponse) KubernetesWatch() watch.Interface {
// Stop the internal channel with the translation layer
if w.started {
w.stopCh <- struct{}{}
}
return w.watch
}
type k8sErrBody struct {
Message string `json:"message"`
Code int `json:"code"`
}
// parseKubernetesError attempts to create a better error response from a k8s error
// by using the body and status code from the request. The normal k8s error string is very generic
// (typically: "the server rejected our request for an unknown reason (<METHOD> <GV> <NAME>)"),
// but the response body often has more details about the nature of the failure (for example, missing a required field).
// Ths method will parse the response body for a better error message if available, and return a *ServerResponseError
// if the status code is a non-success (>= 300).
func parseKubernetesError(responseBytes []byte, statusCode int, err error) error {
if len(responseBytes) > 0 {
parsed := k8sErrBody{}
// If we can parse the response body, use the error contained there instead, because it's clearer
if e := json.Unmarshal(responseBytes, &parsed); e == nil {
err = fmt.Errorf(parsed.Message)
}
}
// HTTP error?
if statusCode >= 300 {
return NewServerResponseError(err, statusCode)
}
return err
}
func addLabels(obj resource.Object, labels map[string]string) {
l := obj.GetLabels()
if l == nil {
l = make(map[string]string)
}
for k, v := range labels {
l[k] = v
}
obj.SetLabels(l)
}