/
schemaless.go
259 lines (228 loc) · 8.87 KB
/
schemaless.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
package k8s
import (
"bytes"
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/rest"
"github.com/grafana/grafana-app-sdk/metrics"
"github.com/grafana/grafana-app-sdk/resource"
)
// SchemalessClient implements resource.SchemalessClient and allows for working with Schemas as kubernetes
// Custom Resource Definitions without being tied to a particular Schema (or GroupVerson).
// Since the largest unit a kubernetes rest.Interface can work with is a GroupVersion,
// SchemalessClient is actually an arbitrary number of kubernetes REST clients under-the-hood.
type SchemalessClient struct {
// config REST config used to generate new clients
kubeConfig rest.Config
clientConfig ClientConfig
// codec is used for encoding/decoding JSON bytes into objects
codec resource.Codec
// clients is the actual k8s clients, groupversion -> client
clients map[string]*groupVersionClient
mutex sync.Mutex
// prometheus collectors for the client
requestDurations *prometheus.HistogramVec
totalRequests *prometheus.CounterVec
}
// NewSchemalessClient creates a new SchemalessClient using the provided rest.Config and ClientConfig.
func NewSchemalessClient(kubeConfig rest.Config, clientConfig ClientConfig) *SchemalessClient {
return NewSchemalessClientWithCodec(kubeConfig, clientConfig, resource.NewJSONCodec())
}
func NewSchemalessClientWithCodec(kubeConfig rest.Config, clientConfig ClientConfig, jsonCodec resource.Codec) *SchemalessClient {
kubeConfig.NegotiatedSerializer = &GenericNegotiatedSerializer{}
kubeConfig.UserAgent = rest.DefaultKubernetesUserAgent()
return &SchemalessClient{
kubeConfig: kubeConfig,
clientConfig: clientConfig,
codec: jsonCodec,
clients: make(map[string]*groupVersionClient),
requestDurations: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: clientConfig.MetricsConfig.Namespace,
Subsystem: "kubernetes_client",
Name: "request_duration_seconds",
Help: "Time (in seconds) spent serving HTTP requests.",
Buckets: metrics.LatencyBuckets,
NativeHistogramBucketFactor: clientConfig.MetricsConfig.NativeHistogramBucketFactor,
NativeHistogramMaxBucketNumber: clientConfig.MetricsConfig.NativeHistogramMaxBucketNumber,
NativeHistogramMinResetDuration: time.Hour,
}, []string{"status_code", "verb", "kind", "subresource"}),
totalRequests: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "requests_total",
Subsystem: "kubernetes_client",
Namespace: clientConfig.MetricsConfig.Namespace,
Help: "Total number of kubernetes requests",
}, []string{"status_code", "verb", "kind", "subresource"}),
}
}
// Get gets a resource from kubernetes with the Kind and GroupVersion determined from the FullIdentifier,
// using the namespace and name in FullIdentifier. If identifier.Plural is present, it will use that,
// otherwise, LOWER(identifier.Kind) + s is used for the resource.
// The returned resource is marshaled into `into`.
func (s *SchemalessClient) Get(ctx context.Context, identifier resource.FullIdentifier, into resource.Object) error {
if into == nil {
return fmt.Errorf("into cannot be nil")
}
client, err := s.getClient(identifier)
if err != nil {
return err
}
return client.get(ctx, resource.Identifier{
Namespace: identifier.Namespace,
Name: identifier.Name,
}, s.getPlural(identifier), into, s.codec)
}
// Create creates a new resource, and marshals the storage response (the created object) into the `into` field.
func (s *SchemalessClient) Create(ctx context.Context, identifier resource.FullIdentifier, obj resource.Object,
_ resource.CreateOptions, into resource.Object) error {
if obj == nil {
return fmt.Errorf("obj cannot be nil")
}
if into == nil {
return fmt.Errorf("into cannot be nil")
}
client, err := s.getClient(identifier)
if err != nil {
return err
}
obj.SetStaticMetadata(resource.StaticMetadata{
Namespace: identifier.Namespace,
Name: identifier.Name,
Group: identifier.Group,
Version: identifier.Version,
Kind: identifier.Kind,
})
return client.create(ctx, s.getPlural(identifier), obj, into, s.codec)
}
// Update updates an existing resource, and marshals the updated version into the `into` field
func (s *SchemalessClient) Update(ctx context.Context, identifier resource.FullIdentifier, obj resource.Object,
options resource.UpdateOptions, into resource.Object) error {
if obj == nil {
return fmt.Errorf("obj cannot be nil")
}
if into == nil {
return fmt.Errorf("into cannot be nil")
}
client, err := s.getClient(identifier)
if err != nil {
return err
}
obj.SetStaticMetadata(resource.StaticMetadata{
Namespace: identifier.Namespace,
Name: identifier.Name,
Group: identifier.Group,
Version: identifier.Version,
Kind: identifier.Kind,
})
if options.ResourceVersion == "" {
existingMd, err := client.getMetadata(ctx, resource.Identifier{
Namespace: identifier.Namespace,
Name: identifier.Name,
}, s.getPlural(identifier))
if err != nil {
return err
}
obj.SetResourceVersion(existingMd.GetResourceVersion())
} else {
obj.SetResourceVersion(options.ResourceVersion)
}
if options.Subresource != "" {
return client.updateSubresource(ctx, s.getPlural(identifier), options.Subresource, obj, into, options, s.codec)
}
return client.update(ctx, s.getPlural(identifier), obj, into, options, s.codec)
}
// Patch performs a JSON Patch on the provided resource, and marshals the updated version into the `into` field
func (s *SchemalessClient) Patch(ctx context.Context, identifier resource.FullIdentifier, patch resource.PatchRequest,
options resource.PatchOptions, into resource.Object) error {
client, err := s.getClient(identifier)
if err != nil {
return err
}
return client.patch(ctx, resource.Identifier{
Namespace: identifier.Namespace,
Name: identifier.Name,
}, s.getPlural(identifier), patch, into, options, s.codec)
}
// Delete deletes a resource identified by identifier
func (s *SchemalessClient) Delete(ctx context.Context, identifier resource.FullIdentifier) error {
client, err := s.getClient(identifier)
if err != nil {
return err
}
return client.delete(ctx, resource.Identifier{
Namespace: identifier.Namespace,
Name: identifier.Name,
}, s.getPlural(identifier))
}
// List lists all resources that satisfy identifier, ignoring `Name`. The response is marshaled into `into`
func (s *SchemalessClient) List(ctx context.Context, identifier resource.FullIdentifier,
options resource.ListOptions, into resource.ListObject, exampleListItem resource.Object) error {
if into == nil {
return fmt.Errorf("into cannot be nil")
}
client, err := s.getClient(identifier)
if err != nil {
return err
}
return client.list(ctx, identifier.Namespace, s.getPlural(identifier), into, options,
func(raw []byte) (resource.Object, error) {
into := exampleListItem.Copy()
err := s.codec.Read(bytes.NewReader(raw), into)
return into, err
})
}
// Watch watches all resources that satisfy the identifier, ignoring `Name`.
// The WatchResponse's WatchEvent Objects are created by unmarshaling into an object created by calling
// example.Copy().
func (s *SchemalessClient) Watch(ctx context.Context, identifier resource.FullIdentifier, options resource.WatchOptions,
exampleObject resource.Object) (resource.WatchResponse, error) {
if exampleObject == nil {
return nil, fmt.Errorf("exampleItem cannot be nil")
}
client, err := s.getClient(identifier)
if err != nil {
return nil, err
}
return client.watch(ctx, identifier.Namespace, s.getPlural(identifier), exampleObject, options, s.codec)
}
// PrometheusCollectors returns the prometheus metric collectors used by this client to allow for registration
func (s *SchemalessClient) PrometheusCollectors() []prometheus.Collector {
return []prometheus.Collector{
s.totalRequests, s.requestDurations,
}
}
func (s *SchemalessClient) getClient(identifier resource.FullIdentifier) (*groupVersionClient, error) {
gv := schema.GroupVersion{
Group: identifier.Group,
Version: identifier.Version,
}
s.mutex.Lock()
defer s.mutex.Unlock()
if c, ok := s.clients[gv.Identifier()]; ok {
return c, nil
}
s.kubeConfig.GroupVersion = &gv
client, err := rest.RESTClientFor(&s.kubeConfig)
if err != nil {
return nil, err
}
s.clients[gv.Identifier()] = &groupVersionClient{
client: client,
version: identifier.Version,
config: s.clientConfig,
requestDurations: s.requestDurations,
totalRequests: s.totalRequests,
}
return s.clients[gv.Identifier()], nil
}
//nolint:revive
func (s *SchemalessClient) getPlural(identifier resource.FullIdentifier) string {
if identifier.Plural != "" {
return identifier.Plural
}
return fmt.Sprintf("%ss", strings.ToLower(identifier.Kind))
}