/
util.go
342 lines (293 loc) · 11.1 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
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
package util
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
v1 "k8s.io/api/networking/v1"
lsv1alpha1 "github.com/gardener/landscaper/apis/core/v1alpha1"
"github.com/gardener/landscaper/apis/core/v1alpha1/targettypes"
"github.com/gardener/landscaper/apis/mediatype"
modeltypes "github.com/gardener/landscaper/pkg/components/model/types"
corev1 "k8s.io/api/core/v1"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// CheckConditionPeriodically checks the success of a function peridically. Returns timeout(bool) to indicate the success of the function
// and propagates possible errors of the function.
func CheckConditionPeriodically(conditionFunc func() (bool, error), sleepTime time.Duration, maxRetries int) (bool, error) {
retries := 0
for {
fmt.Printf("Checking condition... retries: %d\n", retries)
ok, err := conditionFunc()
if err != nil {
return false, err
}
if ok {
break
}
if retries >= maxRetries {
return true, nil
}
retries++
time.Sleep(sleepTime)
}
return false, nil
}
// CheckAndWaitUntilAllPodsAreReady checks and wait until all pods have the ready condition set to true. Returns an error on failure
// or if timeout (sleepTime and maxRetries is reached). Returns a boolean indicating if all pods have the ready condition true on return.
func CheckAndWaitUntilAllPodsAreReady(k8sClient client.Client, namespace string, sleepTime time.Duration, maxRetries int) (bool, error) {
conditionFunc := func() (bool, error) {
podList := corev1.PodList{}
err := k8sClient.List(context.TODO(), &podList, client.InNamespace(namespace))
if err != nil {
return false, fmt.Errorf("cannot list pods: %w", err)
}
numberOfRunningPods := 0
for _, pod := range podList.Items {
if pod.Status.Phase == corev1.PodSucceeded {
numberOfRunningPods++
} else {
for _, condition := range pod.Status.Conditions {
if condition.Type == corev1.PodReady {
if condition.Status == corev1.ConditionTrue {
numberOfRunningPods++
break
}
}
}
}
}
return numberOfRunningPods == len(podList.Items), nil
}
return CheckConditionPeriodically(conditionFunc, sleepTime, maxRetries)
}
func CheckIngressReady(k8sClient client.Client, namespace string, sleepTime time.Duration, maxRetries int) (string, error) {
conditionFunc := func() (bool, error) {
ingress := v1.Ingress{}
ingress.Name = "oci-registry"
ingress.Namespace = namespace
err := k8sClient.Get(context.TODO(), client.ObjectKeyFromObject(&ingress), &ingress)
if err != nil {
return false, fmt.Errorf("cannot get ingress: %w", err)
}
if len(ingress.Status.LoadBalancer.Ingress) > 1 {
return true, nil
}
return false, nil
}
_, err := CheckConditionPeriodically(conditionFunc, sleepTime, maxRetries)
if err != nil {
return "", err
}
ingress := v1.Ingress{}
ingress.Name = "oci-registry"
ingress.Namespace = namespace
err = k8sClient.Get(context.TODO(), client.ObjectKeyFromObject(&ingress), &ingress)
if err != nil {
return "", fmt.Errorf("cannot get ingress: %w", err)
}
return ingress.Spec.TLS[0].Hosts[0], nil
}
// CheckAndWaitUntilLandscaperInstallationSucceeded checks and wait until the installation is on status succeeded. Returns an error on failure
// or if timeout (sleepTime and maxRetries is reached). Returns a boolean indicating if the installation succeeded.
func CheckAndWaitUntilLandscaperInstallationSucceeded(k8sClient client.Client, key types.NamespacedName, sleepTime time.Duration, maxRetries int) (bool, error) {
conditionFunc := func() (bool, error) {
inst := &lsv1alpha1.Installation{}
err := k8sClient.Get(context.TODO(), key, inst)
if err != nil {
return false, fmt.Errorf("cannot get installation: %w", err)
}
return inst.Status.InstallationPhase == lsv1alpha1.InstallationPhases.Succeeded, nil
}
return CheckConditionPeriodically(conditionFunc, sleepTime, maxRetries)
}
// CheckAndWaitUntilObjectNotExistAnymore periodically checks and wait until the object does not exist anymore. Returns an error on failure
// or if timeout (sleepTime and maxRetries is reached). Returns a boolean indicating if the object remains on return.
func CheckAndWaitUntilObjectNotExistAnymore(k8sClient client.Client, objKey types.NamespacedName, obj client.Object, sleepTime time.Duration, maxRetries int) (bool, error) {
conditionFunc := func() (bool, error) {
err := k8sClient.Get(context.TODO(), objKey, obj)
if err != nil {
if k8sErrors.IsNotFound(err) {
return true, nil
}
return false, err
}
return false, nil
}
return CheckConditionPeriodically(conditionFunc, sleepTime, maxRetries)
}
// CheckAndWaitUntilNoInstallationsInNamespaceExists periodically checks and wait until no installation in the namespace remains. Returns an error on failure
// or if timeout (sleepTime and maxRetries is reached). Returns a boolean indicating if no installations remains on return.
func CheckAndWaitUntilNoInstallationsInNamespaceExists(k8sClient client.Client, namespace string, sleepTime time.Duration, maxRetries int) (bool, error) {
conditionFunc := func() (bool, error) {
ctx := context.TODO()
installationList := &lsv1alpha1.InstallationList{}
err := k8sClient.List(ctx, installationList, &client.ListOptions{Namespace: namespace})
if err != nil {
return false, err
}
return len(installationList.Items) == 0, nil
}
return CheckConditionPeriodically(conditionFunc, sleepTime, maxRetries)
}
// DeleteNamespace deletes a namespace (if it exists). First, a graceful delete will be tried with a timeout.
// On timeout, the namespace will be deleted forcefully by removing the finalizers on the Landscaper CRs.
func DeleteNamespace(k8sClient client.Client, namespace string, sleepTime time.Duration, maxRetries int) error {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
err := k8sClient.Get(context.TODO(), client.ObjectKey{Name: namespace}, ns)
if err != nil {
if k8sErrors.IsNotFound(err) {
return nil
}
return fmt.Errorf("error getting namespace %s: %w", namespace, err)
}
timeout, err := gracefullyDeleteNamespace(k8sClient, namespace, sleepTime, maxRetries)
if err != nil {
return fmt.Errorf("deleting namespace gracefully failed: %w", err)
}
if timeout {
return fmt.Errorf("Deleting namespace gracefully timed out")
}
return nil
}
// gracefully try to delete all Landscaper installations in a namespace, then delete the namespace itself
func gracefullyDeleteNamespace(k8sClient client.Client, namespace string, sleepTime time.Duration, maxRetries int) (bool, error) {
ctx := context.TODO()
installationList := lsv1alpha1.InstallationList{}
if err := k8sClient.List(ctx, &installationList, &client.ListOptions{Namespace: namespace}); err != nil {
return false, err
}
for _, installation := range installationList.Items {
fmt.Println("Deleting installation:", installation.Name)
if err := k8sClient.Delete(ctx, &installation, &client.DeleteOptions{}); err != nil {
return false, fmt.Errorf("cannot delete installation: %w", err)
}
}
timeout, err := CheckAndWaitUntilNoInstallationsInNamespaceExists(k8sClient, namespace, sleepTime, maxRetries)
if err != nil {
return false, err
}
if timeout {
return timeout, nil
}
podList := corev1.PodList{}
if err := k8sClient.List(ctx, &podList, &client.ListOptions{Namespace: namespace}); err != nil {
return false, err
}
if len(podList.Items) > 0 {
for i := range podList.Items {
next := &podList.Items[i]
if len(next.GetFinalizers()) > 0 {
return false, fmt.Errorf("there still exists pods with finalizer in namespace %s though all installations were deleted: %w", namespace, err)
}
}
}
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
fmt.Println("Deleting namespace:", namespace)
err = k8sClient.Delete(ctx, ns, &client.DeleteOptions{})
if err != nil {
return false, fmt.Errorf("cannot delete namespace: %w", err)
}
timeout, err = CheckAndWaitUntilObjectNotExistAnymore(k8sClient, client.ObjectKey{Name: namespace}, ns, sleepTime, maxRetries)
if err != nil {
return false, fmt.Errorf("error while waiting for namespace to be deleted: %w", err)
}
if timeout {
return true, nil
}
return false, nil
}
func BuildTargetWithContent(name, namespace string, targetType lsv1alpha1.TargetType, content []byte, secretName string) (*lsv1alpha1.Target, *corev1.Secret) {
target := &lsv1alpha1.Target{
TypeMeta: metav1.TypeMeta{
APIVersion: lsv1alpha1.SchemeGroupVersion.String(),
Kind: "Target",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Spec: lsv1alpha1.TargetSpec{
Type: targetType,
},
}
var secret *corev1.Secret
secretKeyName := "config"
if secretName != "" {
secret = &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: corev1.SchemeGroupVersion.String(),
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: namespace,
},
Data: map[string][]byte{
secretKeyName: content,
},
}
target.Spec.SecretRef = &lsv1alpha1.LocalSecretReference{
Name: secretName,
Key: secretKeyName,
}
} else {
target.Spec.Configuration = lsv1alpha1.NewAnyJSONPointer(content)
}
return target, secret
}
func BuildKubernetesClusterTarget(name, namespace, kubeconfigPath, secretName string) (*lsv1alpha1.Target, *corev1.Secret, error) {
marshalledConfig, err := GetKubernetesClusterTargetContent(kubeconfigPath)
if err != nil {
return nil, nil, err
}
target, secret := BuildTargetWithContent(name, namespace, targettypes.KubernetesClusterTargetType, marshalledConfig, secretName)
return target, secret, nil
}
func GetKubernetesClusterTargetContent(kubeconfigPath string) ([]byte, error) {
kubeconfigContent, err := os.ReadFile(kubeconfigPath)
if err != nil {
return nil, fmt.Errorf("cannot read kubeconfig: %w", err)
}
config := targettypes.KubernetesClusterTargetConfig{
Kubeconfig: targettypes.ValueRef{
StrVal: ptr.To[string](string(kubeconfigContent)),
},
}
marshalledConfig, err := json.Marshal(config)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return marshalledConfig, nil
}
// GetBlueprintResourceName returns the name of the blueprint resource in the provided component descriptor,
// provided the component descriptor contains exactly one blueprint resource.
func GetBlueprintResourceName(cd *modeltypes.ComponentDescriptor) (string, error) {
var blueprintResourceNames []string
for _, resource := range cd.ComponentSpec.Resources {
if resource.IdentityObjectMeta.Type == mediatype.BlueprintType || resource.IdentityObjectMeta.Type == mediatype.OldBlueprintType {
blueprintResourceNames = append(blueprintResourceNames, resource.Name)
}
}
switch len(blueprintResourceNames) {
case 0:
return "", fmt.Errorf("no blueprint resources defined in the component descriptor")
case 1:
return blueprintResourceNames[0], nil
default:
return "", fmt.Errorf("the blueprint resource name must be defined since multiple blueprint resources exist in the component descriptor")
}
}