/
object.go
180 lines (158 loc) · 6.87 KB
/
object.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
// Copyright 2020 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 unstructured
import (
"context"
autoscalingv1 "k8s.io/api/autoscaling/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/gardener/gardener/pkg/controllerutils"
"github.com/gardener/gardener/pkg/utils"
)
var systemMetadataFields = []string{"ownerReferences", "uid", "resourceVersion", "generation", "creationTimestamp", "deletionTimestamp", "deletionGracePeriodSeconds", "managedFields"}
// GetObjectByRef returns the object with the given reference and namespace using the given client.
// The full content of the object is returned as map[string]interface{}, except for system metadata fields.
// This function can be combined with runtime.DefaultUnstructuredConverter.FromUnstructured to get the object content
// as runtime.RawExtension.
func GetObjectByRef(ctx context.Context, c client.Client, ref *autoscalingv1.CrossVersionObjectReference, namespace string) (map[string]interface{}, error) {
gvk, err := gvkFromCrossVersionObjectReference(ref)
if err != nil {
return nil, err
}
return GetObject(ctx, c, gvk, ref.Name, namespace)
}
// GetObject returns the object with the given GVK, name, and namespace as a map using the given client.
// The full content of the object is returned as map[string]interface{}, except for system metadata fields.
// This function can be combined with runtime.DefaultUnstructuredConverter.FromUnstructured to get the object content
// as runtime.RawExtension.
func GetObject(ctx context.Context, c client.Client, gvk schema.GroupVersionKind, name, namespace string) (map[string]interface{}, error) {
// Initialize the object
key := client.ObjectKey{Namespace: namespace, Name: name}
obj := &unstructured.Unstructured{}
obj.SetGroupVersionKind(gvk)
// Get the object
if err := c.Get(ctx, key, obj); err != nil {
if !apierrors.IsNotFound(err) {
return nil, err
}
return nil, nil
}
// Return object content
return FilterMetadata(obj.UnstructuredContent(), systemMetadataFields...), nil
}
// CreateOrPatchObjectByRef creates or patches the object with the given reference and namespace using the given client.
// The object is created or patched with the given content, except for system metadata fields.
// This function can be combined with runtime.DefaultUnstructuredConverter.ToUnstructured to create or update an object
// from runtime.RawExtension.
func CreateOrPatchObjectByRef(ctx context.Context, c client.Client, ref *autoscalingv1.CrossVersionObjectReference, namespace string, content map[string]interface{}) error {
gvk, err := gvkFromCrossVersionObjectReference(ref)
if err != nil {
return err
}
return CreateOrPatchObject(ctx, c, gvk, ref.Name, namespace, content)
}
// CreateOrPatchObject creates or patches the object with the given GVK, name, and namespace using the given client.
// The object is created or patched with the given content, except for system metadata fields, namespace, and name.
// This function can be combined with runtime.DefaultUnstructuredConverter.ToUnstructured to create or update an object
// from runtime.RawExtension.
func CreateOrPatchObject(ctx context.Context, c client.Client, gvk schema.GroupVersionKind, name, namespace string, content map[string]interface{}) error {
// Initialize the object
obj := &unstructured.Unstructured{}
obj.SetGroupVersionKind(gvk)
obj.SetName(name)
obj.SetNamespace(namespace)
// Create or patch the object
_, err := controllerutils.GetAndCreateOrMergePatch(ctx, c, obj, func() error {
// Set object content
if content != nil {
obj.SetUnstructuredContent(mergeObjectContents(obj.UnstructuredContent(),
FilterMetadata(content, add(systemMetadataFields, "namespace", "name")...)))
}
return nil
})
return err
}
// DeleteObjectByRef deletes the object with the given reference and namespace using the given client.
func DeleteObjectByRef(ctx context.Context, c client.Client, ref *autoscalingv1.CrossVersionObjectReference, namespace string) error {
gvk, err := gvkFromCrossVersionObjectReference(ref)
if err != nil {
return err
}
return DeleteObject(ctx, c, gvk, ref.Name, namespace)
}
// DeleteObject deletes the object with the given GVK, name, and namespace using the given client.
func DeleteObject(ctx context.Context, c client.Client, gvk schema.GroupVersionKind, name, namespace string) error {
// Initialize the object
obj := &unstructured.Unstructured{}
obj.SetGroupVersionKind(gvk)
obj.SetName(name)
obj.SetNamespace(namespace)
// Delete the object
return client.IgnoreNotFound(c.Delete(ctx, obj))
}
func gvkFromCrossVersionObjectReference(ref *autoscalingv1.CrossVersionObjectReference) (schema.GroupVersionKind, error) {
gv, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
return schema.GroupVersionKind{}, err
}
return schema.GroupVersionKind{
Group: gv.Group,
Version: gv.Version,
Kind: ref.Kind,
}, nil
}
func mergeObjectContents(dest, src map[string]interface{}) map[string]interface{} {
// Merge metadata
srcMetadata, srcMetadataOK := src["metadata"].(map[string]interface{})
if srcMetadataOK {
destMetadata, destMetadataOK := dest["metadata"].(map[string]interface{})
if destMetadataOK {
dest["metadata"] = utils.MergeMaps(destMetadata, srcMetadata)
} else {
dest["metadata"] = srcMetadata
}
}
// Take spec and data from the source
for _, key := range []string{"spec", "data", "stringData"} {
srcSpec, srcSpecOK := src[key]
if srcSpecOK {
dest[key] = srcSpec
} else {
delete(dest, key)
}
}
return dest
}
// FilterMetadata filters metadata from the provided unstructured object content.
func FilterMetadata(content map[string]interface{}, fields ...string) map[string]interface{} {
// Copy content to result
result := make(map[string]interface{})
for key, value := range content {
result[key] = value
}
// Delete specified fields from result
if metadata, ok := result["metadata"].(map[string]interface{}); ok {
for _, field := range fields {
delete(metadata, field)
}
}
return result
}
func add(s []string, elems ...string) []string {
result := make([]string, len(s))
copy(result, s)
return append(result, elems...)
}