-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathkubernetes.go
More file actions
189 lines (153 loc) · 4.77 KB
/
kubernetes.go
File metadata and controls
189 lines (153 loc) · 4.77 KB
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
// Copyright 2021 - 2024 Crunchy Data Solutions, Inc.
//
// SPDX-License-Identifier: Apache-2.0
package require
import (
"context"
"os"
"path/filepath"
goruntime "runtime"
"strings"
"sync"
"golang.org/x/tools/go/packages"
"gotest.tools/v3/assert"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"github.com/percona/percona-postgresql-operator/v2/internal/controller/runtime"
)
type TestingT interface {
assert.TestingT
Cleanup(func())
Helper()
Name() string
SkipNow()
}
// https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/envtest#pkg-constants
var envtestVarsSet = os.Getenv("KUBEBUILDER_ASSETS") != "" ||
strings.EqualFold(os.Getenv("USE_EXISTING_CLUSTER"), "true")
// EnvTest returns an unstarted Environment with crds. It calls t.Skip when
// the "KUBEBUILDER_ASSETS" and "USE_EXISTING_CLUSTER" environment variables
// are unset.
func EnvTest(t TestingT, crds envtest.CRDInstallOptions) *envtest.Environment {
t.Helper()
if !envtestVarsSet {
t.SkipNow()
}
return &envtest.Environment{
CRDInstallOptions: crds,
Scheme: crds.Scheme,
}
}
var kubernetes struct {
sync.Mutex
// Count references to the started Environment.
count int
env *envtest.Environment
}
// Kubernetes starts or connects to a Kubernetes API and returns a client that uses it.
// When starting a local API, the client is a member of the "system:masters" group.
//
// It calls t.Fatal when something fails. It stops the local API using t.Cleanup.
// It calls t.Skip when the "KUBEBUILDER_ASSETS" and "USE_EXISTING_CLUSTER" environment
// variables are unset.
//
// Tests that call t.Parallel might share the same local API. Call t.Parallel after this
// function to ensure they share.
func Kubernetes(t TestingT) client.Client {
t.Helper()
_, cc := kubernetes3(t)
return cc
}
// Kubernetes2 is the same as [Kubernetes] but also returns a copy of the client
// configuration.
func Kubernetes2(t TestingT) (*rest.Config, client.Client) {
t.Helper()
env, cc := kubernetes3(t)
return rest.CopyConfig(env.Config), cc
}
func kubernetes3(t TestingT) (*envtest.Environment, client.Client) {
t.Helper()
if !envtestVarsSet {
t.SkipNow()
}
frames := func() *goruntime.Frames {
var pcs [5]uintptr
n := goruntime.Callers(2, pcs[:])
return goruntime.CallersFrames(pcs[0:n])
}()
// Calculate the project directory as reported by [goruntime.CallersFrames].
frame, ok := frames.Next()
self := frame.File
root := strings.TrimSuffix(self,
filepath.Join("internal", "testing", "require", "kubernetes.go"))
// Find the first caller that is not in this file.
for ok && frame.File == self {
frame, ok = frames.Next()
}
caller := frame.File
// Calculate the project directory path relative to the caller.
base, err := filepath.Rel(filepath.Dir(caller), root)
assert.NilError(t, err)
// Calculate the snapshotter module directory path relative to the project directory.
var snapshotter string
if pkgs, err := packages.Load(
&packages.Config{Mode: packages.NeedModule},
"github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1",
); assert.Check(t,
err == nil && len(pkgs) > 0 && pkgs[0].Module != nil, "got %v\n%#v", err, pkgs,
) {
if pkgs[0].Module.Dir != "" {
snapshotter, err = filepath.Rel(root, pkgs[0].Module.Dir)
assert.NilError(t, err)
}
}
kubernetes.Lock()
defer kubernetes.Unlock()
if kubernetes.env == nil {
env := EnvTest(t, envtest.CRDInstallOptions{
ErrorIfPathMissing: true,
Paths: []string{
filepath.Join(base, "config", "crd", "bases"),
filepath.Join(base, snapshotter, "config", "crd"),
},
Scheme: runtime.Scheme,
})
_, err := env.Start()
assert.NilError(t, err)
kubernetes.env = env
}
kubernetes.count++
t.Cleanup(func() {
kubernetes.Lock()
defer kubernetes.Unlock()
kubernetes.count--
if kubernetes.count == 0 {
assert.Check(t, kubernetes.env.Stop())
kubernetes.env = nil
}
})
cc, err := client.New(kubernetes.env.Config, client.Options{
Scheme: kubernetes.env.Scheme,
})
assert.NilError(t, err)
return kubernetes.env, cc
}
// Namespace creates a random namespace that is deleted by t.Cleanup. It calls
// t.Fatal when creation fails. The caller may delete the namespace at any time.
func Namespace(t TestingT, cc client.Client) *corev1.Namespace {
t.Helper()
// Remove / that shows up when running a sub-test
// TestSomeThing/test_some_specific_thing
name, _, _ := strings.Cut(t.Name(), "/")
ns := &corev1.Namespace{}
ns.GenerateName = "postgres-operator-test-"
ns.Labels = map[string]string{"postgres-operator-test": name}
ctx := context.Background()
assert.NilError(t, cc.Create(ctx, ns))
t.Cleanup(func() {
assert.Check(t, client.IgnoreNotFound(cc.Delete(ctx, ns)))
})
return ns
}