-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathutil.go
245 lines (209 loc) · 8.12 KB
/
util.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
/*
Copyright 2019 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 external
import (
"context"
"strings"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apiserver/pkg/storage/names"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// Get uses the client and reference to get an external, unstructured object.
func Get(ctx context.Context, c client.Client, ref *corev1.ObjectReference, namespace string) (*unstructured.Unstructured, error) {
if ref == nil {
return nil, errors.Errorf("cannot get object - object reference not set")
}
obj := new(unstructured.Unstructured)
obj.SetAPIVersion(ref.APIVersion)
obj.SetKind(ref.Kind)
obj.SetName(ref.Name)
key := client.ObjectKey{Name: obj.GetName(), Namespace: namespace}
if err := c.Get(ctx, key, obj); err != nil {
return nil, errors.Wrapf(err, "failed to retrieve %s external object %q/%q", obj.GetKind(), key.Namespace, key.Name)
}
return obj, nil
}
// Delete uses the client and reference to delete an external, unstructured object.
func Delete(ctx context.Context, c client.Client, ref *corev1.ObjectReference) error {
obj := new(unstructured.Unstructured)
obj.SetAPIVersion(ref.APIVersion)
obj.SetKind(ref.Kind)
obj.SetName(ref.Name)
obj.SetNamespace(ref.Namespace)
if err := c.Delete(ctx, obj); err != nil {
return errors.Wrapf(err, "failed to delete %s external object %q/%q", obj.GetKind(), obj.GetNamespace(), obj.GetName())
}
return nil
}
// CloneTemplateInput is the input to CloneTemplate.
type CloneTemplateInput struct {
// Client is the controller runtime client.
Client client.Client
// TemplateRef is a reference to the template that needs to be cloned.
TemplateRef *corev1.ObjectReference
// Namespace is the Kubernetes namespace the cloned object should be created into.
Namespace string
// ClusterName is the cluster this object is linked to.
ClusterName string
// OwnerRef is an optional OwnerReference to attach to the cloned object.
// +optional
OwnerRef *metav1.OwnerReference
// Labels is an optional map of labels to be added to the object.
// +optional
Labels map[string]string
// Annotations is an optional map of annotations to be added to the object.
// +optional
Annotations map[string]string
}
// CloneTemplate uses the client and the reference to create a new object from the template.
func CloneTemplate(ctx context.Context, in *CloneTemplateInput) (*corev1.ObjectReference, error) {
from, err := Get(ctx, in.Client, in.TemplateRef, in.Namespace)
if err != nil {
return nil, err
}
generateTemplateInput := &GenerateTemplateInput{
Template: from,
TemplateRef: in.TemplateRef,
Namespace: in.Namespace,
ClusterName: in.ClusterName,
OwnerRef: in.OwnerRef,
Labels: in.Labels,
Annotations: in.Annotations,
}
to, err := GenerateTemplate(generateTemplateInput)
if err != nil {
return nil, err
}
// Create the external clone.
if err := in.Client.Create(ctx, to); err != nil {
return nil, err
}
return GetObjectReference(to), nil
}
// GenerateTemplateInput is the input needed to generate a new template.
type GenerateTemplateInput struct {
// Template is the TemplateRef turned into an unstructured.
Template *unstructured.Unstructured
// TemplateRef is a reference to the template that needs to be cloned.
TemplateRef *corev1.ObjectReference
// Namespace is the Kubernetes namespace the cloned object should be created into.
Namespace string
// ClusterName is the cluster this object is linked to.
ClusterName string
// OwnerRef is an optional OwnerReference to attach to the cloned object.
// +optional
OwnerRef *metav1.OwnerReference
// Labels is an optional map of labels to be added to the object.
// +optional
Labels map[string]string
// Annotations is an optional map of annotations to be added to the object.
// +optional
Annotations map[string]string
}
// GenerateTemplate generates an object with the given template input.
func GenerateTemplate(in *GenerateTemplateInput) (*unstructured.Unstructured, error) {
template, found, err := unstructured.NestedMap(in.Template.Object, "spec", "template")
if !found {
return nil, errors.Errorf("missing Spec.Template on %v %q", in.Template.GroupVersionKind(), in.Template.GetName())
} else if err != nil {
return nil, errors.Wrapf(err, "failed to retrieve Spec.Template map on %v %q", in.Template.GroupVersionKind(), in.Template.GetName())
}
// Create the unstructured object from the template.
to := &unstructured.Unstructured{Object: template}
to.SetResourceVersion("")
to.SetFinalizers(nil)
to.SetUID("")
to.SetSelfLink("")
to.SetName(names.SimpleNameGenerator.GenerateName(in.Template.GetName() + "-"))
to.SetNamespace(in.Namespace)
// Set annotations.
annotations := to.GetAnnotations()
if annotations == nil {
annotations = map[string]string{}
}
for key, value := range in.Annotations {
annotations[key] = value
}
annotations[clusterv1.TemplateClonedFromNameAnnotation] = in.TemplateRef.Name
annotations[clusterv1.TemplateClonedFromGroupKindAnnotation] = in.TemplateRef.GroupVersionKind().GroupKind().String()
to.SetAnnotations(annotations)
// Set labels.
labels := to.GetLabels()
if labels == nil {
labels = map[string]string{}
}
for key, value := range in.Labels {
labels[key] = value
}
labels[clusterv1.ClusterLabelName] = in.ClusterName
to.SetLabels(labels)
// Set the owner reference.
if in.OwnerRef != nil {
to.SetOwnerReferences([]metav1.OwnerReference{*in.OwnerRef})
}
// Set the object APIVersion.
if to.GetAPIVersion() == "" {
to.SetAPIVersion(in.Template.GetAPIVersion())
}
// Set the object Kind and strip the word "Template" if it's a suffix.
if to.GetKind() == "" {
to.SetKind(strings.TrimSuffix(in.Template.GetKind(), clusterv1.TemplateSuffix))
}
return to, nil
}
// GetObjectReference converts an unstructured into object reference.
func GetObjectReference(obj *unstructured.Unstructured) *corev1.ObjectReference {
return &corev1.ObjectReference{
APIVersion: obj.GetAPIVersion(),
Kind: obj.GetKind(),
Name: obj.GetName(),
Namespace: obj.GetNamespace(),
UID: obj.GetUID(),
}
}
// FailuresFrom returns the FailureReason and FailureMessage fields from the external object status.
func FailuresFrom(obj *unstructured.Unstructured) (string, string, error) {
failureReason, _, err := unstructured.NestedString(obj.Object, "status", "failureReason")
if err != nil {
return "", "", errors.Wrapf(err, "failed to determine failureReason on %v %q",
obj.GroupVersionKind(), obj.GetName())
}
failureMessage, _, err := unstructured.NestedString(obj.Object, "status", "failureMessage")
if err != nil {
return "", "", errors.Wrapf(err, "failed to determine failureMessage on %v %q",
obj.GroupVersionKind(), obj.GetName())
}
return failureReason, failureMessage, nil
}
// IsReady returns true if the Status.Ready field on an external object is true.
func IsReady(obj *unstructured.Unstructured) (bool, error) {
ready, found, err := unstructured.NestedBool(obj.Object, "status", "ready")
if err != nil {
return false, errors.Wrapf(err, "failed to determine %v %q readiness",
obj.GroupVersionKind(), obj.GetName())
}
return ready && found, nil
}
// IsInitialized returns true if the Status.Initialized field on an external object is true.
func IsInitialized(obj *unstructured.Unstructured) (bool, error) {
initialized, found, err := unstructured.NestedBool(obj.Object, "status", "initialized")
if err != nil {
return false, errors.Wrapf(err, "failed to determine %v %q initialized",
obj.GroupVersionKind(), obj.GetName())
}
return initialized && found, nil
}