-
Notifications
You must be signed in to change notification settings - Fork 148
/
integration_test.go
443 lines (390 loc) · 12.5 KB
/
integration_test.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// +build integration
// Copyright 2019 The Kanister 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 testing
import (
"context"
"os"
test "testing"
"time"
"github.com/pkg/errors"
. "gopkg.in/check.v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/rand"
"k8s.io/client-go/kubernetes"
crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1"
"github.com/kanisterio/kanister/pkg/app"
crclient "github.com/kanisterio/kanister/pkg/client/clientset/versioned/typed/cr/v1alpha1"
"github.com/kanisterio/kanister/pkg/controller"
"github.com/kanisterio/kanister/pkg/field"
_ "github.com/kanisterio/kanister/pkg/function"
"github.com/kanisterio/kanister/pkg/kanctl"
"github.com/kanisterio/kanister/pkg/kube"
"github.com/kanisterio/kanister/pkg/log"
"github.com/kanisterio/kanister/pkg/poll"
"github.com/kanisterio/kanister/pkg/resource"
"github.com/kanisterio/kanister/pkg/testutil"
)
// Hook up gocheck into the "go test" runner for integration builds
func Test(t *test.T) {
integrationSetup(t)
TestingT(t)
integrationCleanup(t)
}
// Global variables shared across Suite instances
type kanisterKontroller struct {
namespace string
context context.Context
cancel context.CancelFunc
kubeCli *kubernetes.Clientset
}
var kontroller kanisterKontroller
func integrationSetup(t *test.T) {
ns := "integration-test-controller-" + rand.String(5)
ctx, cancel := context.WithCancel(context.Background())
cfg, err := kube.LoadConfig()
if err != nil {
t.Fatalf("Integration test setup failure: Error loading kube.Config; err=%v", err)
}
cli, err := kubernetes.NewForConfig(cfg)
if err != nil {
t.Fatalf("Integration test setup failure: Error createing kubeCli; err=%v", err)
}
if err = createNamespace(cli, ns); err != nil {
t.Fatalf("Integration test setup failure: Error createing namespace; err=%v", err)
}
// Set Controller namespace and service account
os.Setenv(kube.PodNSEnvVar, ns)
os.Setenv(kube.PodSAEnvVar, controllerSA)
if err = resource.CreateCustomResources(ctx, cfg); err != nil {
t.Fatalf("Integration test setup failure: Error createing custom resources; err=%v", err)
}
ctlr := controller.New(cfg)
if err = ctlr.StartWatch(ctx, ns); err != nil {
t.Fatalf("Integration test setup failure: Error starting controller; err=%v", err)
}
kontroller.namespace = ns
kontroller.context = ctx
kontroller.cancel = cancel
kontroller.kubeCli = cli
}
func integrationCleanup(t *test.T) {
if kontroller.cancel != nil {
kontroller.cancel()
}
if kontroller.namespace != "" {
kontroller.kubeCli.CoreV1().Namespaces().Delete(context.TODO(), kontroller.namespace, metav1.DeleteOptions{})
}
}
const (
// appWaitTimeout decides the time we are going to wait for app to be ready
appWaitTimeout = 3 * time.Minute
controllerSA = "default"
)
type secretProfile struct {
secret *v1.Secret
profile *crv1alpha1.Profile
}
type IntegrationSuite struct {
name string
cli kubernetes.Interface
crCli crclient.CrV1alpha1Interface
app app.App
bp app.Blueprinter
profile *secretProfile
namespace string
skip bool
cancel context.CancelFunc
}
func newSecretProfile() *secretProfile {
_, location := testutil.GetObjectstoreLocation()
secret, profile, err := testutil.NewSecretProfileFromLocation(location)
if err != nil {
return nil
}
return &secretProfile{
secret: secret,
profile: profile,
}
}
func (s *IntegrationSuite) SetUpSuite(c *C) {
ctx := context.Background()
ctx, s.cancel = context.WithCancel(ctx)
// Instantiate Client SDKs
cfg, err := kube.LoadConfig()
c.Assert(err, IsNil)
s.cli, err = kubernetes.NewForConfig(cfg)
c.Assert(err, IsNil)
s.crCli, err = crclient.NewForConfig(cfg)
c.Assert(err, IsNil)
}
// TestRun executes e2e workflow on the app
// 1. Install DB app
// 2. Add data
// 3. Create Kanister Profile and Blueprint
// 4. Take Backup
// 5. Delete DB data
// 6. Restore data from backup
// 7. Uninstall DB app
func (s *IntegrationSuite) TestRun(c *C) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Execute e2e workflow
log.Info().Print("Running e2e integration test.", field.M{"app": s.name, "testName": c.TestName()})
// Check config
err := s.app.Init(ctx)
if err != nil {
log.Info().Print("Skipping integration test.", field.M{"app": s.name, "reason": err.Error()})
s.skip = true
c.Skip(err.Error())
}
// Create namespace
err = createNamespace(s.cli, s.namespace)
c.Assert(err, IsNil)
// Create profile
if s.profile == nil {
log.Info().Print("Skipping integration test. Could not create profile. Please check if required credentials are set.", field.M{"app": s.name})
s.skip = true
c.Skip("Could not create a Profile")
}
profileName := s.createProfile(c)
// Install db
err = s.app.Install(ctx, s.namespace)
c.Assert(err, IsNil)
// Check if ready
ok, err := s.app.IsReady(ctx)
c.Assert(err, IsNil)
c.Assert(ok, Equals, true)
// Create blueprint
bp := s.bp.Blueprint()
c.Assert(bp, NotNil)
_, err = s.crCli.Blueprints(kontroller.namespace).Create(ctx, bp, metav1.CreateOptions{})
c.Assert(err, IsNil)
var configMaps, secrets map[string]crv1alpha1.ObjectReference
testEntries := 3
// Add test entries to DB
if a, ok := s.app.(app.DatabaseApp); ok {
// wait for application to be actually ready
err = pingAppAndWait(ctx, a)
c.Assert(err, IsNil)
err = a.Reset(ctx)
c.Assert(err, IsNil)
// Add few entries
for i := 0; i < testEntries; i++ {
c.Assert(a.Insert(ctx), IsNil)
}
count, err := a.Count(ctx)
c.Assert(err, IsNil)
c.Assert(count, Equals, testEntries)
}
// Get Secret and ConfigMap object references
if a, ok := s.app.(app.ConfigApp); ok {
configMaps = a.ConfigMaps()
secrets = a.Secrets()
}
// Validate Blueprint
validateBlueprint(c, *bp, configMaps, secrets)
// Create ActionSet specs
as := newActionSet(bp.GetName(), profileName, kontroller.namespace, s.app.Object(), configMaps, secrets)
// Take backup
backup := s.createActionset(ctx, c, as, "backup", nil)
c.Assert(len(backup), Not(Equals), 0)
// Save timestamp for PITR
var restoreOptions map[string]string
if b, ok := s.bp.(app.PITRBlueprinter); ok {
pitr := b.FormatPITR(time.Now())
log.Info().Print("Saving timestamp for PITR", field.M{"pitr": pitr})
restoreOptions = map[string]string{
"pitr": pitr,
}
// Add few more entries with timestamp > pitr
time.Sleep(time.Second)
if a, ok := s.app.(app.DatabaseApp); ok {
c.Assert(a.Insert(ctx), IsNil)
c.Assert(a.Insert(ctx), IsNil)
count, err := a.Count(ctx)
c.Assert(err, IsNil)
c.Assert(count, Equals, testEntries+2)
}
}
// Reset DB
if a, ok := s.app.(app.DatabaseApp); ok {
err = a.Reset(ctx)
c.Assert(err, IsNil)
count, err := a.Count(ctx)
c.Assert(err, IsNil)
c.Assert(count, Equals, 0)
}
// Restore backup
pas, err := s.crCli.ActionSets(kontroller.namespace).Get(ctx, backup, metav1.GetOptions{})
c.Assert(err, IsNil)
s.createActionset(ctx, c, pas, "restore", restoreOptions)
// Verify data
if a, ok := s.app.(app.DatabaseApp); ok {
// wait for application to be actually ready
err = pingAppAndWait(ctx, a)
c.Assert(err, IsNil)
count, err := a.Count(ctx)
c.Assert(err, IsNil)
c.Assert(count, Equals, testEntries)
}
// Delete snapshots
s.createActionset(ctx, c, pas, "delete", nil)
}
func newActionSet(bpName, profile, profileNs string, object crv1alpha1.ObjectReference, configMaps, secrets map[string]crv1alpha1.ObjectReference) *crv1alpha1.ActionSet {
return &crv1alpha1.ActionSet{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "test-actionset-",
},
Spec: &crv1alpha1.ActionSetSpec{
Actions: []crv1alpha1.ActionSpec{
crv1alpha1.ActionSpec{
Name: "backup",
Object: object,
Blueprint: bpName,
Profile: &crv1alpha1.ObjectReference{
Name: profile,
Namespace: profileNs,
},
ConfigMaps: configMaps,
Secrets: secrets,
},
},
},
}
}
func (s *IntegrationSuite) createProfile(c *C) string {
secret, err := s.cli.CoreV1().Secrets(kontroller.namespace).Create(context.TODO(), s.profile.secret, metav1.CreateOptions{})
c.Assert(err, IsNil)
// set secret ref in profile
s.profile.profile.Credential.KeyPair.Secret = crv1alpha1.ObjectReference{
Name: secret.GetName(),
Namespace: secret.GetNamespace(),
}
profile, err := s.crCli.Profiles(kontroller.namespace).Create(context.TODO(), s.profile.profile, metav1.CreateOptions{})
c.Assert(err, IsNil)
return profile.GetName()
}
func validateBlueprint(c *C, bp crv1alpha1.Blueprint, configMaps, secrets map[string]crv1alpha1.ObjectReference) {
for _, action := range bp.Actions {
// Validate BP action ConfigMapNames with the app.ConfigMaps references
for _, bpc := range action.ConfigMapNames {
validConfig := false
for appc, _ := range configMaps {
if appc == bpc {
validConfig = true
}
}
c.Assert(validConfig, Equals, true)
}
// Validate BP action SecretNames with the app.Secrets reference
for _, bps := range action.SecretNames {
validSecret := false
for apps, _ := range secrets {
if apps == bps {
validSecret = true
}
}
c.Assert(validSecret, Equals, true)
}
}
}
// createActionset creates and wait for actionset to complete
func (s *IntegrationSuite) createActionset(ctx context.Context, c *C, as *crv1alpha1.ActionSet, action string, options map[string]string) string {
var err error
switch action {
case "backup":
as.Spec.Actions[0].Options = options
as, err = s.crCli.ActionSets(kontroller.namespace).Create(ctx, as, metav1.CreateOptions{})
c.Assert(err, IsNil)
case "restore", "delete":
as, err = restoreActionSetSpecs(as, action)
c.Assert(err, IsNil)
as.Spec.Actions[0].Options = options
if action == "delete" {
// object of delete is always namespace of actionset
as.Spec.Actions[0].Object = crv1alpha1.ObjectReference{
APIVersion: "v1",
Group: "",
Resource: "namespaces",
Kind: "namespace",
Name: kontroller.namespace,
Namespace: "",
}
}
as, err = s.crCli.ActionSets(kontroller.namespace).Create(ctx, as, metav1.CreateOptions{})
c.Assert(err, IsNil)
default:
c.Errorf("Invalid action %s while creating ActionSet", action)
}
// Wait for the ActionSet to complete.
err = poll.Wait(ctx, func(ctx context.Context) (bool, error) {
as, err = s.crCli.ActionSets(kontroller.namespace).Get(ctx, as.GetName(), metav1.GetOptions{})
switch {
case err != nil, as.Status == nil:
return false, err
case as.Status.State == crv1alpha1.StateFailed:
return true, errors.Errorf("Actionset failed: %#v", as.Status)
case as.Status.State == crv1alpha1.StateComplete:
return true, nil
}
return false, nil
})
c.Assert(err, IsNil)
return as.GetName()
}
// restoreActionSetSpecs generates restore actionset specs from backup name
func restoreActionSetSpecs(from *crv1alpha1.ActionSet, action string) (*crv1alpha1.ActionSet, error) {
params := kanctl.PerformParams{
ActionName: action,
ParentName: from.GetName(),
}
return kanctl.ChildActionSet(from, ¶ms)
}
func createNamespace(cli kubernetes.Interface, name string) error {
// Create Namespace
ns := &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
_, err := cli.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})
if err != nil {
return err
}
return nil
}
func (s *IntegrationSuite) TearDownSuite(c *C) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Uninstall app
if !s.skip {
err := s.app.Uninstall(ctx)
c.Assert(err, IsNil)
}
// Uninstall implementation of the apps doesn't delete namespace
// Delete the namespace separately
err := s.cli.CoreV1().Namespaces().Delete(ctx, s.namespace, metav1.DeleteOptions{})
c.Assert(err, IsNil)
}
func pingAppAndWait(ctx context.Context, a app.DatabaseApp) error {
timeoutCtx, waitCancel := context.WithTimeout(ctx, appWaitTimeout)
defer waitCancel()
err := poll.Wait(timeoutCtx, func(ctx context.Context) (bool, error) {
err := a.Ping(ctx)
return err == nil, nil
})
return err
}