forked from projectcalico/calicoctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resourcemgr.go
551 lines (474 loc) · 20 KB
/
resourcemgr.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
// Copyright (c) 2017 Tigera, Inc. All rights reserved.
// 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 resourcemgr
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"reflect"
"strings"
"time"
"github.com/projectcalico/calicoctl/calicoctl/commands/argutils"
yamlsep "github.com/projectcalico/calicoctl/calicoctl/util/yaml"
yaml "github.com/projectcalico/go-yaml-wrapper"
client "github.com/projectcalico/libcalico-go/lib/clientv3"
cerrors "github.com/projectcalico/libcalico-go/lib/errors"
validator "github.com/projectcalico/libcalico-go/lib/validator/v3"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// The ResourceManager interface provides useful function for each resource type. This includes:
// - Commands to assist with generation of table output format of resources
// - Commands to manage resource instances through an un-typed interface.
type ResourceManager interface {
GetTableDefaultHeadings(wide bool) []string
GetTableTemplate(columns []string, printNamespace bool) (string, error)
GetObjectType() reflect.Type
IsNamespaced() bool
Apply(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error)
Create(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error)
Update(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error)
Delete(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error)
GetOrList(ctx context.Context, client client.Interface, resource ResourceObject) (runtime.Object, error)
}
// All Calico resources implement the resource interface.
type ResourceObject interface {
runtime.Object
v1.ObjectMetaAccessor
}
// All Calico resources list implement the resource interface.
type ResourceListObject interface {
runtime.Object
v1.ListMetaAccessor
}
type ResourceActionCommand func(context.Context, client.Interface, ResourceObject) (ResourceObject, error)
type ResourceListActionCommand func(context.Context, client.Interface, ResourceObject) (ResourceListObject, error)
// ResourceHelper encapsulates details about a specific version of a specific resource:
//
// - The type of resource (Kind and Version). This includes the list types (even
// though they are not strictly resources themselves).
// - The concrete resource struct for this version
// - Template strings used to format output for each resource type.
// - Functions to handle resource management actions (apply, create, update, delete, list).
// These functions are an untyped interface (generic Resource interfaces) that map through
// to the Calico clients typed interface.
type resourceHelper struct {
resource runtime.Object
listResource ResourceListObject
resourceType reflect.Type
tableHeadings []string
tableHeadingsWide []string
headingsMap map[string]string
isList bool
isNamespaced bool
create ResourceActionCommand
update ResourceActionCommand
delete ResourceActionCommand
get ResourceActionCommand
list ResourceListActionCommand
}
func (r resourceHelper) String() string {
if !r.isList {
return fmt.Sprintf("Resource(%s %s)", r.resource.GetObjectKind(), r.resource.GetObjectKind().GroupVersionKind())
}
return fmt.Sprintf("Resource(%s %s)", r.listResource.GetObjectKind(), r.listResource.GetListMeta().GetResourceVersion())
}
// Store a resourceHelper for each resource.
var helpers map[schema.GroupVersionKind]resourceHelper
var kindToRes = make(map[string]ResourceObject)
func registerResource(res ResourceObject, resList ResourceListObject, isNamespaced bool, names []string,
tableHeadings []string, tableHeadingsWide []string, headingsMap map[string]string,
create, update, delete, get ResourceActionCommand, list ResourceListActionCommand) {
if helpers == nil {
helpers = make(map[schema.GroupVersionKind]resourceHelper)
}
rh := resourceHelper{
resource: res,
resourceType: reflect.ValueOf(res).Elem().Type(),
tableHeadings: tableHeadings,
tableHeadingsWide: tableHeadingsWide,
headingsMap: headingsMap,
isList: false,
isNamespaced: isNamespaced,
create: create,
update: update,
delete: delete,
get: get,
list: list,
}
helpers[res.GetObjectKind().GroupVersionKind()] = rh
rh = resourceHelper{
listResource: resList.(ResourceListObject),
resourceType: reflect.ValueOf(resList).Elem().Type(),
tableHeadings: tableHeadings,
tableHeadingsWide: tableHeadingsWide,
headingsMap: headingsMap,
isList: true,
}
helpers[resList.GetObjectKind().GroupVersionKind()] = rh
for _, v := range names {
kindToRes[v] = res
}
}
func (rh resourceHelper) GetObjectType() reflect.Type {
return rh.resourceType
}
// Apply is an un-typed method to apply (create or update) a resource. This calls Create
// and if the resource already exists then we call the Update method.
func (rh resourceHelper) Apply(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {
// Store the original ResourceVersion for the Update operation later.
originalRV := resource.(ResourceObject).GetObjectMeta().GetResourceVersion()
// Remove the resourceVersion, because Create call can't have
// resourceVersion set and Update automatically gets and sets
// the resourceVersion to the latest one from the datastore.
resource.GetObjectMeta().SetResourceVersion("")
// Try to create the resource first.
ro, err := rh.Create(ctx, client, resource)
// Fall back to an Update if the resource already exists, or the datastore does not support
// create operations for that resource.
switch err.(type) {
case cerrors.ErrorResourceAlreadyExists, cerrors.ErrorOperationNotSupported:
// Insert the original ResourceVersion back into the object before trying the Update.
resource.(ResourceObject).GetObjectMeta().SetResourceVersion(originalRV)
// Try updating if the resource already exists.
return rh.Update(ctx, client, resource)
}
// For any other errors, return the error
return ro, err
}
// Create is an un-typed method to create a new resource. This calls directly
// through to the resource helper specific Create method which will map the untyped call to
// the typed interface on the client.
func (rh resourceHelper) Create(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {
resourceCopy := prepareMetadataForCreate(resource)
return rh.create(ctx, client, resourceCopy)
}
// Update is an un-typed method to update an existing resource. This calls the resource
// specific Get method to get the resourceVersion, and then calls resource specific
// Update method with the resource with the updated resourceVersion, but if the resourceVersion is provided
// then we use that. We retry 5 times if there is an update conflict during the Update operation.
func (rh resourceHelper) Update(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {
var err error
// Check to see if the resourceVersion is specified in the resource object.
rv := resource.(ResourceObject).GetObjectMeta().GetResourceVersion()
// If the resourceVersion is specified then we use it to try and update the resource.
// Do not attempt to retry if the resource version is specified.
if rv != "" {
// Validate the metadata is not changed for the the resource.
ro, err := rh.get(ctx, client, resource)
if err != nil {
return ro, err
}
// Set the specific resource version we are attempting to update.
ro.GetObjectMeta().SetResourceVersion(rv)
resource = mergeMetadataForUpdate(ro, resource)
return rh.update(ctx, client, resource)
}
// If the resourceVersion is not specified then we do a Get to get
// the latest resourceVersion and then do an Update with it.
// We retry only if we get an update conflict.
for i := 0; i < 5; i++ {
// Get the resource to get the resourceVersion.
ro, err := rh.get(ctx, client, resource)
if err != nil {
return ro, err
}
resource = mergeMetadataForUpdate(ro, resource)
// Try to update with the resource with the updated resourceVersion.
ru, err := rh.update(ctx, client, resource)
if _, ok := err.(cerrors.ErrorResourceUpdateConflict); ok {
// Wait for a second and try again if there was a conflict during the resource update.
log.Infof("Error updating the resource %s: %s. Retrying.", resource.GetObjectMeta().GetName(), err)
time.Sleep(1 * time.Second)
continue
}
// For any other errors or nil error, return the result and error.
return ru, err
}
return nil, fmt.Errorf("failed to update the resource: %s", err)
}
// Delete is an un-typed method to delete an existing resource. This calls directly
// through to the resource helper specific Delete method which will map the untyped call to
// the typed interface on the client.
func (rh resourceHelper) Delete(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {
return rh.delete(ctx, client, resource)
}
// GetOrList is an un-typed method to get an existing resource. This calls directly
// through to the resource helper specific Get (if the resource name is set)
// or List (if the resource name is empty) method which will map the untyped call to
// the typed interface on the client.
func (rh resourceHelper) GetOrList(ctx context.Context, client client.Interface, resource ResourceObject) (runtime.Object, error) {
if resource.GetObjectMeta().GetName() != "" {
if resource.GetObjectMeta().GetNamespace() == "" && rh.isNamespaced {
return nil, fmt.Errorf("cannot use --all-namespace flag for getting a single resource")
}
return rh.get(ctx, client, resource)
}
return rh.list(ctx, client, resource)
}
// Return the Resource Manager for a particular resource type.
func GetResourceManager(resource runtime.Object) ResourceManager {
return helpers[resource.GetObjectKind().GroupVersionKind()]
}
// Gets resource from arguments.
// This function also inserts resource name, namespace if specified.
// Example "calicoctl get bgppeer peer123" will return
// a BGPPeer resource with name field populated to "peer123".
func GetResourceFromArgs(args map[string]interface{}) (ResourceObject, error) {
kind := args["<KIND>"].(string)
name := argutils.ArgStringOrBlank(args, "<NAME>")
namespace := argutils.ArgStringOrBlank(args, "--namespace")
res, ok := kindToRes[strings.ToLower(kind)]
if !ok {
return nil, fmt.Errorf("resource type '%s' is not supported", kind)
}
res.(ResourceObject).GetObjectMeta().SetName(name)
// Set the namespace if the object kind is namespaced.
if helpers[res.GetObjectKind().GroupVersionKind()].isNamespaced {
res.(ResourceObject).GetObjectMeta().SetNamespace(namespace)
}
return res, nil
}
// Check if the resource kind is namespaced.
func (rh resourceHelper) IsNamespaced() bool {
return rh.isNamespaced
}
// Create a new concrete resource structure based on the type. If the type is
// a list, this creates a concrete Resource-List of the required type.
func newResource(tm schema.GroupVersionKind) (runtime.Object, error) {
rh, ok := helpers[tm]
if !ok {
return nil, errors.New(fmt.Sprintf("Unknown resource type (%s) and/or version (%s)", tm.Kind, tm.GroupVersion().String()))
}
log.Infof("Found resource helper: %s", rh)
// Create new resource and fill in the type metadata.
new := reflect.New(rh.resourceType)
elem := new.Elem()
elem.FieldByName("Kind").SetString(tm.Kind)
elem.FieldByName("APIVersion").SetString(tm.GroupVersion().String())
_, ok = new.Interface().(ResourceObject)
if ok {
return new.Interface().(ResourceObject), nil
} else {
return new.Interface().(ResourceListObject), nil
}
}
// Create the resource from the specified byte array encapsulating the resource.
// - The byte array may be JSON or YAML encoding of either a single resource or list of
// resources as defined by the API objects in /api.
//
// The returned Resource will either be a single resource document or a List of documents.
// If the file does not contain any valid Resources this function returns an error.
func createResourcesFromBytes(b []byte) ([]runtime.Object, error) {
// Start by unmarshalling the bytes into a TypeMetadata structure - this will ignore
// other fields.
var err error
tm := unstructured.Unstructured{}
tms := []unstructured.Unstructured{}
if err = yaml.Unmarshal(b, &tm); err == nil {
// We processed a metadata, so create a concrete resource struct to unpack
// into.
return unmarshalResource(tm, b)
} else if err = yaml.Unmarshal(b, &tms); err == nil {
// We processed a slice of metadata's, create a list of concrete resource
// structs to unpack into.
return unmarshalSliceOfResources(tms, b)
} else {
// Failed to parse a single resource or list of resources.
return nil, err
}
}
// Unmarshal a bytearray containing a single resource of the specified type into
// a concrete structure for that resource type.
//
// Return as a slice of Resource interfaces, containing a single element that is
// the unmarshalled resource.
func unmarshalResource(tm unstructured.Unstructured, b []byte) ([]runtime.Object, error) {
log.Infof("Processing type %s", tm.GetObjectKind())
unpacked, err := newResource(tm.GroupVersionKind())
if err != nil {
return nil, err
}
if err = yaml.UnmarshalStrict(b, unpacked); err != nil {
return nil, err
}
log.Infof("Type of unpacked data: %v", reflect.TypeOf(unpacked))
if err = validator.Validate(unpacked); err != nil {
return nil, err
}
log.Infof("Unpacked: %+v", unpacked)
return []runtime.Object{unpacked}, nil
}
// Unmarshal a bytearray containing a list of resources of the specified types into
// a slice of concrete structures for those resource types.
//
// Return as a slice of Resource interfaces, containing an element that is each of
// the unmarshalled resources.
func unmarshalSliceOfResources(tml []unstructured.Unstructured, b []byte) ([]runtime.Object, error) {
log.Infof("Processing list of resources")
unpacked := make([]runtime.Object, len(tml))
for i, tm := range tml {
log.Infof(" - processing type %s", tm.GetObjectKind())
r, err := newResource(tm.GroupVersionKind())
if err != nil {
return nil, err
}
unpacked[i] = r
}
if err := yaml.UnmarshalStrict(b, &unpacked); err != nil {
return nil, err
}
// Validate the data in the structures. The validator does not handle slices, so
// validate each resource separately.
for _, r := range unpacked {
if err := validator.Validate(r); err != nil {
return nil, err
}
}
log.Infof("Unpacked: %+v", unpacked)
return unpacked, nil
}
// Create the Resource from the specified file f.
// - The file format may be JSON or YAML encoding of either a single resource or list of
// resources as defined by the API objects in /api.
// - A filename of "-" means "Read from stdin".
//
// The returned Resource will either be a single Resource or a List containing zero or more
// Resources. If the file does not contain any valid Resources this function returns an error.
func CreateResourcesFromFile(f string) ([]runtime.Object, error) {
// Load the bytes from file or from stdin.
logCxt := log.WithField("source", f)
var reader io.Reader
var err error
if f == "-" {
reader = os.Stdin
} else {
reader, err = os.Open(f)
if err != nil {
logCxt.WithError(err).Error("Failed to open file")
return nil, err
}
}
logCxt.Debug("Creating document separator")
var resources []runtime.Object
separator := yamlsep.NewYAMLDocumentSeparator(reader)
for {
b, err := separator.Next()
if err != nil {
if err == io.EOF {
break
}
logCxt.WithError(err).Error("Document separator failed")
return nil, err
}
logCxt.WithField("byteLength", len(b)).Debug("Found a resource")
r, err := createResourcesFromBytes(b)
if err != nil {
logCxt.WithError(err).Error("Failed to parse resource from bytes")
return nil, err
}
resources = append(resources, r...)
}
logCxt.WithField("numResources", len(resources)).Info("Finished parsing")
return resources, nil
}
// Implement the ResourceManager interface on the resourceHelper struct.
// GetTableDefaultHeadings returns the default headings to use in the ps-style get output
// for the resource. Wide indicates whether the wide (true) or concise (false) column set is
// required.
func (rh resourceHelper) GetTableDefaultHeadings(wide bool) []string {
if wide {
return rh.tableHeadingsWide
}
return rh.tableHeadings
}
// GetTableTemplate constructs the go-lang template string from the supplied set of headings.
// The template separates columns using tabs so that a tabwriter can be used to pretty-print
// the table.
func (rh resourceHelper) GetTableTemplate(headings []string, printNamespace bool) (string, error) {
if _, ok := rh.headingsMap["NAMESPACE"]; printNamespace && ok {
headings = append([]string{"NAMESPACE"}, headings...)
}
// Write the headings line.
buf := new(bytes.Buffer)
for _, heading := range headings {
buf.WriteString(heading)
buf.WriteByte('\t')
}
buf.WriteByte('\n')
// If this is a list type, we need to iterate over the list items.
if rh.isList {
buf.WriteString("{{range .Items}}")
}
// For each column, add the go-template snippet for the corresponding field value.
for _, heading := range headings {
value, ok := rh.headingsMap[heading]
if !ok {
headings := make([]string, 0, len(rh.headingsMap))
for heading := range rh.headingsMap {
headings = append(headings, heading)
}
return "", fmt.Errorf("Unknown heading %s, valid values are: %s",
heading,
strings.Join(headings, ", "))
}
buf.WriteString(value)
buf.WriteByte('\t')
}
buf.WriteByte('\n')
// If this is a list, close off the range.
if rh.isList {
buf.WriteString("{{end}}")
}
return buf.String(), nil
}
// mergeMetadataForUpdate merges the Metadata for a stored ResourceObject and a potentail
// update. All metadata in the potential update will be overwritten by the stored object
// except for Labels and Annotations. This prevents accidental modifications to the metadata
// fields by forcing updates to those fields to be handled by internal or more involved
// processes.
func mergeMetadataForUpdate(old, new ResourceObject) ResourceObject {
sm := old.GetObjectMeta()
cm := new.GetObjectMeta()
// Set the fields that are allowed to be overwritten (Labels and Annotations)
// so that they will not be overwritten.
sm.SetAnnotations(cm.GetAnnotations())
sm.SetLabels(cm.GetLabels())
sm.(*v1.ObjectMeta).DeepCopyInto(cm.(*v1.ObjectMeta))
return new
}
// prepareMetadataForCreate removes the metadata fields that should not be set from
// calicoctl. Only the metadata fields Name, Namespace, ResourceVersion, Labels,
// and Annotations will be kept. All other fields will be set elsewhere if required.
// This prevents accidental modifications to the metadata fields by forcing updates
// to those fields to be handled by internal or more involved processes.
func prepareMetadataForCreate(r ResourceObject) ResourceObject {
rom := r.GetObjectMeta()
meta := &v1.ObjectMeta{}
// Save the important fields in the meta before everything gets wiped out.
meta.Name = rom.GetName()
meta.Namespace = rom.GetNamespace()
meta.ResourceVersion = rom.GetResourceVersion()
meta.Labels = rom.GetLabels()
meta.Annotations = rom.GetAnnotations()
// Make a copy of the resource so the input does not get modified
resOut := r.DeepCopyObject().(ResourceObject)
meta.DeepCopyInto(resOut.GetObjectMeta().(*v1.ObjectMeta))
return resOut
}