This repository has been archived by the owner on Jun 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdelete.go
73 lines (57 loc) · 1.74 KB
/
delete.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
package manifest
import (
"context"
"fmt"
"strings"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/wait"
)
func (l *list) Delete(ctx context.Context, opts ...DeleteOptionFunc) error {
options := newDeleteOptions(opts...)
for _, v := range l.Resources() {
if err := l.delete(ctx, v, options); err != nil {
return err
}
}
return nil
}
func (l *list) delete(ctx context.Context, obj *unstructured.Unstructured, options *deleteOptions) error {
log := logr.FromContextOrDiscard(ctx)
gvk := obj.GroupVersionKind()
kind := fmt.Sprintf("%s.%s", strings.ToLower(gvk.Kind), gvk.Group)
if len(gvk.Group) == 0 {
kind = strings.ToLower(gvk.Kind)
}
mapper, err := l.mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return fmt.Errorf("failed to retrieve REST mapping for %s: %w", kind, err)
}
resource := l.client.Resource(mapper.Resource).Namespace(obj.GetNamespace())
if mapper.Scope.Name() == meta.RESTScopeNameRoot {
resource = l.client.Resource(mapper.Resource)
}
err = resource.Delete(ctx, obj.GetName(), metav1.DeleteOptions{})
if errors.IsNotFound(err) {
return nil
}
if err != nil {
return fmt.Errorf("failed to delete %s %q: %w", kind, obj.GetName(), err)
}
log.Info(fmt.Sprintf("%s %q deleted", kind, obj.GetName()))
if !options.Wait {
return nil
}
return wait.ExponentialBackoff(defaultBackoff, func() (done bool, err error) {
_, err = resource.Get(ctx, obj.GetName(), metav1.GetOptions{})
if errors.IsNotFound(err) {
return true, nil
} else if err != nil {
return false, err
}
return false, nil
})
}