-
Notifications
You must be signed in to change notification settings - Fork 361
/
crds.go
75 lines (64 loc) · 2.11 KB
/
crds.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
package util
import (
"context"
"fmt"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
"math"
"time"
"github.com/loft-sh/vcluster/pkg/util/applier"
"github.com/loft-sh/vcluster/pkg/util/loghelper"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/discovery"
"k8s.io/client-go/rest"
)
func EnsureCRDFromFile(ctx context.Context, config *rest.Config, crdFilePath string, groupVersionKind schema.GroupVersionKind) error {
exists, err := KindExists(config, groupVersionKind)
if err != nil {
return err
} else if exists {
return nil
}
err = wait.ExponentialBackoffWithContext(ctx, wait.Backoff{Duration: time.Second, Factor: 1.5, Cap: 5 * time.Minute, Steps: math.MaxInt32}, func() (bool, error) {
err := applier.ApplyManifestFile(config, crdFilePath)
if err != nil {
loghelper.Infof("Failed to apply CRD %s from the manifest file %s: %v", groupVersionKind.String(), crdFilePath, err)
return false, nil
}
return true, nil
})
if err != nil {
return fmt.Errorf("failed to apply CRD %s: %v", groupVersionKind.String(), err)
}
var lastErr error
err = wait.ExponentialBackoffWithContext(ctx, wait.Backoff{Duration: time.Second, Factor: 1.5, Cap: time.Minute, Steps: math.MaxInt32}, func() (bool, error) {
var found bool
found, lastErr = KindExists(config, groupVersionKind)
return found, nil
})
if err != nil {
return fmt.Errorf("failed to find CRD %s: %v: %v", groupVersionKind.String(), err, lastErr)
}
return nil
}
// KindExists checks if given CRDs exist in the given group.
// Returns foundKinds, notFoundKinds, error
func KindExists(config *rest.Config, groupVersionKind schema.GroupVersionKind) (bool, error) {
discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)
if err != nil {
return false, err
}
resources, err := discoveryClient.ServerResourcesForGroupVersion(groupVersionKind.GroupVersion().String())
if err != nil {
if kerrors.IsNotFound(err) {
return false, nil
}
return false, err
}
for _, r := range resources.APIResources {
if r.Kind == groupVersionKind.Kind {
return true, nil
}
}
return false, nil
}