-
Notifications
You must be signed in to change notification settings - Fork 55
/
envtest.go
1535 lines (1391 loc) · 52 KB
/
envtest.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 Google LLC
//
// 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 testhelpers
import (
"bytes"
"context"
"crypto/tls"
"encoding/base32"
"errors"
"fmt"
"io"
"io/ioutil"
logg "log"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"cloud.google.com/go/storage"
"github.com/bazelbuild/rules_go/go/tools/bazel"
snapv1 "github.com/kubernetes-csi/external-snapshotter/v2/pkg/apis/volumesnapshot/v1beta1"
. "github.com/onsi/ginkgo"
ginkgoconfig "github.com/onsi/ginkgo/config"
. "github.com/onsi/gomega"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
"k8s.io/client-go/rest"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
"k8s.io/klog/v2/klogr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"sigs.k8s.io/controller-runtime/pkg/envtest/printer"
logf "sigs.k8s.io/controller-runtime/pkg/log"
commonv1alpha1 "github.com/GoogleCloudPlatform/elcarro-oracle-operator/common/api/v1alpha1"
"github.com/GoogleCloudPlatform/elcarro-oracle-operator/oracle/api/v1alpha1"
"github.com/GoogleCloudPlatform/elcarro-oracle-operator/oracle/controllers"
"github.com/GoogleCloudPlatform/elcarro-oracle-operator/oracle/pkg/k8s"
)
// Reconciler is the interface to setup a reconciler for testing.
type Reconciler interface {
SetupWithManager(manager ctrl.Manager) error
}
// Webhook is the interface to setup a webhook for testing.
type Webhook interface {
SetupWebhookWithManager(mgr ctrl.Manager) error
}
type AdmissionWebhook interface {
ServeHTTP(http.ResponseWriter, *http.Request)
}
// cdToRoot change to the repo root directory.
func CdToRoot(t *testing.T) {
for {
if _, err := os.Stat("config/crd/bases/oracle.db.anthosapis.com_instances.yaml"); err == nil {
break
}
if err := os.Chdir(".."); err != nil {
t.Fatalf("Failed to cd: %v", err)
}
if cwd, err := os.Getwd(); err != nil || cwd == "/" {
t.Fatalf("Failed to find config dir")
}
}
}
// RandName generates a name suitable for use as a namespace with a given prefix.
func RandName(base string) string {
seed := rand.NewSource(time.Now().UnixNano() + int64(1000000*ginkgoconfig.GinkgoConfig.ParallelNode))
testrand := rand.New(seed)
buf := make([]byte, 4)
testrand.Read(buf)
str := strings.ToLower(base32.StdEncoding.EncodeToString(buf))
return base + "-" + str[:4]
}
// RunFunctionalTestSuite runs all specs in the current package against a
// specialized testing environment. Before running the suite, this function
// configures the test environment by taking the following actions:
//
// * Starting a control plane consisting of an etcd process and a Kubernetes API
//
// server process.
//
// * Installing CRDs into the control plane (using provided 'schemeBuilders')
// * Starting an in-process manager in a dedicated goroutine with the given
//
// reconcilers installed in it.
//
// These components will be torn down after the suite runs.
func RunFunctionalTestSuite(
t *testing.T,
k8sClient *client.Client,
k8sManager *ctrl.Manager,
schemeBuilders []*runtime.SchemeBuilder,
description string,
controllers func() []Reconciler,
crdPaths []string,
) {
RunFunctionalTestSuiteWithWebhooks(
t,
k8sClient,
k8sManager,
schemeBuilders,
description,
controllers,
crdPaths,
func() []Webhook { return []Webhook{} }, // No webhooks
func() map[string]AdmissionWebhook { return nil }, // No admission webhook handlers
[]string{}, // Use default Webhook locations
)
}
// RunFunctionalTestSuiteWithWebhooks extends RunFunctionalTestSuite
// allowing to set up test webhooks
func RunFunctionalTestSuiteWithWebhooks(
t *testing.T,
k8sClient *client.Client,
k8sManager *ctrl.Manager,
schemeBuilders []*runtime.SchemeBuilder,
description string,
controllers func() []Reconciler,
crdPaths []string,
webhooks func() []Webhook,
admissionWebhookHandlers func() map[string]AdmissionWebhook,
webhookPaths []string,
) {
// Define the test environment.
crdPaths = append(crdPaths, filepath.Join("config", "crd", "bases"), filepath.Join("config", "crd", "testing"))
var testEnvLock sync.Mutex
testEnv := envtest.Environment{
CRDDirectoryPaths: crdPaths,
ControlPlaneStartTimeout: 60 * time.Second, // Default 20s may not be enough for test pods.
}
// Set up webhooks
if len(webhookPaths) != 0 {
testEnv.WebhookInstallOptions = envtest.WebhookInstallOptions{
Paths: webhookPaths,
IgnoreErrorIfPathMissing: true,
}
}
if runfiles, err := bazel.RunfilesPath(); err == nil {
// Running with bazel test, find binary assets in runfiles.
testEnv.BinaryAssetsDirectory = filepath.Join(runfiles, "external/kubebuilder_tools/bin")
}
// k8s 1.21 introduced graceful shutdown so testEnv wont shutdown if we
// keep a connection open. By using a context with cancel we can
// shutdown our managers before we try to shutdown the testEnv and
// ensure no hanging connections keep the apiserver from stopping.
mgrCtx, mgrCancel := context.WithCancel(ctrl.SetupSignalHandler())
BeforeSuite(func(done Done) {
testEnvLock.Lock()
defer testEnvLock.Unlock()
klog.SetOutput(GinkgoWriter)
logf.SetLogger(klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog)))
log := logf.FromContext(nil)
var err error
var cfg *rest.Config
var backoff = wait.Backoff{
Steps: 6,
Duration: 100 * time.Millisecond,
Factor: 5.0,
Jitter: 0.1,
}
Expect(retry.OnError(backoff, func(error) bool { return true }, func() error {
cfg, err = testEnv.Start()
if err != nil {
log.Error(err, "Envtest startup failed, retrying")
}
return err
})).Should(Succeed())
for _, sb := range schemeBuilders {
utilruntime.Must(sb.AddToScheme(scheme.Scheme))
}
if len(webhookPaths) != 0 {
// start webhook server using Manager
webhookInstallOptions := &testEnv.WebhookInstallOptions
*k8sManager, err = ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme.Scheme,
Host: webhookInstallOptions.LocalServingHost,
Port: webhookInstallOptions.LocalServingPort,
CertDir: webhookInstallOptions.LocalServingCertDir,
LeaderElection: false,
MetricsBindAddress: "0",
})
Expect(err).NotTo(HaveOccurred())
} else {
*k8sManager, err = ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme.Scheme,
MetricsBindAddress: "0",
})
Expect(err).ToNot(HaveOccurred())
}
*k8sClient = (*k8sManager).GetClient()
// Install controllers into the manager.
for _, c := range controllers() {
Expect(c.SetupWithManager(*k8sManager)).To(Succeed())
}
// Install webhooks into the manager.
for _, c := range webhooks() {
Expect(c.SetupWebhookWithManager(*k8sManager)).To(Succeed())
}
// Register admission webhook handlers into the webhook in the manager
for path, handler := range admissionWebhookHandlers() {
(*k8sManager).GetWebhookServer().Register(path, handler)
}
go func() {
defer GinkgoRecover()
err = (*k8sManager).Start(mgrCtx)
Expect(err).ToNot(HaveOccurred())
}()
if len(webhookPaths) != 0 {
// wait for the webhook server to get ready
webhookInstallOptions := &testEnv.WebhookInstallOptions
dialer := &net.Dialer{Timeout: 60 * time.Second}
addrPort := fmt.Sprintf("%s:%d", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort)
Eventually(func() error {
conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return err
}
conn.Close()
return nil
}, 60*time.Second, 5*time.Second).Should(Succeed())
}
close(done)
}, 600)
AfterSuite(func() {
testEnvLock.Lock()
defer testEnvLock.Unlock()
By("Stopping control plane")
mgrCancel()
Expect(testEnv.Stop()).To(Succeed())
})
RegisterFailHandler(Fail)
RunSpecsWithDefaultAndCustomReporters(t,
description,
[]Reporter{printer.NewlineReporter{}})
}
var (
// Base image names, to be combined with PROW_IMAGE_{TAG,REPO}.
dbInitImage = "oracle.db.anthosapis.com/dbinit"
loggingSidecarImage = "oracle.db.anthosapis.com/loggingsidecar"
monitoringAgentImage = "oracle.db.anthosapis.com/monitoring"
operatorImage = "oracle.db.anthosapis.com/operator"
// Used by pitr test directly.
PitrAgentImage = "oracle.db.anthosapis.com/pitragent"
)
// Set up kubectl config targeting PROW_PROJECT / PROW_CLUSTER / PROW_CLUSTER_ZONE
// Set envtest environment pointing to that cluster
// Create k8s client
// Install CRDs
// Create the new control plane namespace
func initK8sCluster(namespace *string) (envtest.Environment, context.Context, client.Client) {
CdToRoot(nil)
klog.SetOutput(GinkgoWriter)
logf.SetLogger(klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog)))
log := logf.FromContext(nil)
// Generate credentials for our test cluster.
Expect(os.Setenv("KUBECONFIG", fmt.Sprintf("/tmp/.kubectl/config-%v", *namespace))).Should(Succeed())
// Allow local runs to target their own GKE cluster to prevent collisions with Prow.
var targetProject, targetCluster, targetZone string
if targetProject = os.Getenv("PROW_PROJECT"); targetProject == "" {
Expect(errors.New("PROW_PROJECT envvar was not set. Did you try to test without make?")).NotTo(HaveOccurred())
}
if targetCluster = os.Getenv("PROW_CLUSTER"); targetCluster == "" {
Expect(errors.New("PROW_CLUSTER envar was not set. Did you try to test without make?")).NotTo(HaveOccurred())
}
if targetZone = os.Getenv("PROW_CLUSTER_ZONE"); targetZone == "" {
Expect(errors.New("PROW_CLUSTER_ZONE envar was not set. Did you try to test without make?")).NotTo(HaveOccurred())
}
// Set up k8s credentials.
// This operation might need retrying when executing tests in parallel.
Expect(retry.OnError(retry.DefaultBackoff, func(error) bool { return true }, func() error {
cmdGetCreds := exec.Command("gcloud", "container", "clusters", "get-credentials", targetCluster, "--project="+targetProject, "--zone="+targetZone)
out, err := cmdGetCreds.CombinedOutput()
log.Info("gcloud get-credentials", "output", string(out))
return err
})).Should(Succeed())
// load the test gcp project config
cfg, err := config.GetConfig()
log.Info("Load kubectl config")
Expect(err).NotTo(HaveOccurred())
trueValue := true
env := envtest.Environment{
UseExistingCluster: &trueValue,
Config: cfg,
CRDDirectoryPaths: []string{
filepath.Join("config", "crd", "bases"),
},
CRDInstallOptions: envtest.CRDInstallOptions{CleanUpAfterUse: false},
}
var CRDBackoff = wait.Backoff{
Steps: 6,
Duration: 100 * time.Millisecond,
Factor: 5.0,
Jitter: 0.1,
}
// env.Start() may fail on the same set of CRDs during parallel execution
// need to retry in that case.
Expect(retry.OnError(CRDBackoff, func(error) bool { return true }, func() error {
_, err = env.Start()
if err != nil {
log.Error(err, "Envtest startup failed: CRD conflict, retrying")
}
return err
})).Should(Succeed())
err = v1alpha1.AddToScheme(scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
err = snapv1.AddToScheme(scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
k8sClient, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
nsObj := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: *namespace,
Labels: map[string]string{
"control-plane": "controller-manager",
},
},
}
ctx := context.Background()
Expect(k8sClient.Create(ctx, nsObj)).Should(Succeed())
return env, ctx, k8sClient
}
// Remove namespace (and all corresponding objects).
// Remove kubectl config.
func cleanupK8Cluster(CPNamespace string, DPNamespace string, k8sClient client.Client) {
cpnsObj := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: CPNamespace,
Labels: map[string]string{
"control-plane": "controller-manager",
},
},
}
dpnsObj := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: DPNamespace,
},
}
if k8sClient != nil {
policy := metav1.DeletePropagationForeground
k8sClient.Delete(context.Background(), cpnsObj, &client.DeleteOptions{
PropagationPolicy: &policy,
})
k8sClient.Delete(context.Background(), dpnsObj, &client.DeleteOptions{
PropagationPolicy: &policy,
})
}
os.Remove(fmt.Sprintf("/tmp/.kubectl/config-%v", CPNamespace))
}
// EnableGsmApi ensures the GSM API enabled for PROW_PROJECT.
func EnableGsmApi() {
// Enable GSM API.
log := logg.New(GinkgoWriter, "", 0)
projectId := os.Getenv("PROW_PROJECT")
Expect(projectId).ToNot(BeEmpty())
cmd := exec.Command("gcloud", "services", "enable", "secretmanager.googleapis.com", fmt.Sprintf("--project=%s", projectId))
out, err := cmd.CombinedOutput()
log.Printf("gcloud services enable secretmanager.googleapis.com output=%s", string(out))
Expect(err).NotTo(HaveOccurred())
}
// EnableIamApi ensures the IAM API enabled for PROW_PROJECT.
func EnableIamApi() {
// Enable IAM API.
log := logg.New(GinkgoWriter, "", 0)
projectId := os.Getenv("PROW_PROJECT")
Expect(projectId).ToNot(BeEmpty())
cmd := exec.Command("gcloud", "services", "enable", "iamcredentials.googleapis.com", fmt.Sprintf("--project=%s", projectId))
out, err := cmd.CombinedOutput()
log.Printf("gcloud services enable iamcredentials.googleapis.com output=%s", string(out))
Expect(err).NotTo(HaveOccurred())
}
// EnableWiWithNodePool ensures workload identity enabled for PROW_CLUSTER.
func EnableWiWithNodePool() {
log := logg.New(GinkgoWriter, "", 0)
projectId := os.Getenv("PROW_PROJECT")
targetCluster := os.Getenv("PROW_CLUSTER")
targetZone := os.Getenv("PROW_CLUSTER_ZONE")
Expect(projectId).ToNot(BeEmpty())
Expect(targetCluster).ToNot(BeEmpty())
Expect(targetZone).NotTo(BeEmpty())
// Enable workload identify on existing cluster.
cmd := exec.Command("gcloud", "container", "clusters", "update", targetCluster, "--workload-pool="+projectId+".svc.id.goog", "--zone="+targetZone, fmt.Sprintf("--project=%s", projectId))
out, err := cmd.CombinedOutput()
log.Printf("gcloud container clusters update output=%s", string(out))
Expect(err).NotTo(HaveOccurred())
// Migrate applications to Workload Identity with Node pool modification.
cmd = exec.Command("gcloud", "container", "node-pools", "update", "default-pool", "--cluster="+targetCluster, "--workload-metadata=GKE_METADATA", "--zone="+targetZone, fmt.Sprintf("--project=%s", projectId))
out, err = cmd.CombinedOutput()
log.Printf("gcloud container node-pools update output=%s", string(out))
Expect(err).NotTo(HaveOccurred())
}
// PrintEvents for all namespaces in the cluster.
func PrintEvents() {
cmd := exec.Command("kubectl", "get", "events", "-A", "-o", "custom-columns=LastSeen:.metadata.creationTimestamp,From:.source.component,Type:.type,Reason:.reason,Message:.message", "--sort-by=.metadata.creationTimestamp")
out, err := cmd.CombinedOutput()
if err != nil {
logf.FromContext(nil).Error(err, "Failed to get events")
return
}
log := logg.New(GinkgoWriter, "", 0)
log.Println("=============================")
log.Printf("Last events:\n %s\n", out)
}
// Print pods for all namespaces in the cluster
func PrintPods() {
cmd := exec.Command("kubectl", "get", "pods", "-A", "-o", "wide")
out, err := cmd.CombinedOutput()
if err != nil {
logf.FromContext(nil).Error(err, "Failed to get pods")
return
}
log := logg.New(GinkgoWriter, "", 0)
log.Println("=============================")
log.Printf("Pods:\n %s\n", out)
}
// Print svcs for all namespaces in the cluster
func PrintSVCs() {
cmd := exec.Command("kubectl", "get", "svc", "-A", "-o", "wide")
out, err := cmd.CombinedOutput()
if err != nil {
logf.FromContext(nil).Error(err, "Failed to get svcs")
return
}
log := logg.New(GinkgoWriter, "", 0)
log.Println("=============================")
log.Printf("SVCs:\n %s\n", out)
}
// Print PVCs for all namespaces in the cluster
func PrintPVCs() {
cmd := exec.Command("kubectl", "get", "pvc", "-A", "-o", "wide")
out, err := cmd.CombinedOutput()
if err != nil {
logf.FromContext(nil).Error(err, "Failed to get pvcs")
return
}
log := logg.New(GinkgoWriter, "", 0)
log.Println("=============================")
log.Printf("PVCs:\n %s\n", out)
}
// Print ENV variables
func PrintENV() {
log := logg.New(GinkgoWriter, "", 0)
log.Println("=============================")
log.Println("ENV:")
for _, e := range os.Environ() {
log.Println(e)
}
}
// Prints logs for a typical single-instance test scenario in case of failure:
// Prints logs for 'manager', 'dbdaemon', 'oracledb' containers.
// Prints cluster objects.
// Stores Oracle trace logs to a local dir (or Prow Artifacts).
func PrintSimpleDebugInfo(k8sEnv K8sOperatorEnvironment, instanceName string, CDBName string) {
PrintLogs(k8sEnv.CPNamespace, k8sEnv.DPNamespace, k8sEnv.Env, []string{"manager", "dbdaemon", "oracledb"}, []string{instanceName})
PrintClusterObjects()
var pod = instanceName + "-sts-0"
if err := StoreOracleLogs(pod, k8sEnv.DPNamespace, instanceName, CDBName); err != nil {
logf.FromContext(nil).Error(err, "StoreOracleLogs failed")
}
}
// Print cluster objects - events, pods, pvcs for all namespaces in the cluster
func PrintClusterObjects() {
PrintENV()
PrintEvents()
PrintPods()
PrintPVCs()
PrintSVCs()
}
// Print logs from requested containers
func PrintLogs(CPNamespace string, DPNamespace string, env envtest.Environment, dumpLogsFor []string, instances []string) {
log := logg.New(GinkgoWriter, "", 0)
for _, c := range dumpLogsFor {
var logs string
var err error
// Make the log start a bit easier to distinguish.
log.Println("=============================")
if c == "manager" {
logs, err = getOperatorLogs(context.Background(), env.Config, CPNamespace)
if err != nil {
log.Printf("Failed to get %s logs: %s\n", c, err)
} else {
log.Printf("%s logs:\n %s\n", c, logs)
}
} else {
for _, inst := range instances {
logs, err = getAgentLogs(context.Background(), env.Config, DPNamespace, inst, c)
if err != nil {
log.Printf("Failed to get %s %s logs: %s\n", inst, c, err)
} else {
log.Printf("%s %s logs:\n %s\n", inst, c, logs)
}
}
}
}
}
// DeployOperator deploys an operator and returns a cleanup function to delete
// all cluster level objects created outside of the namespace.
func deployOperator(ctx context.Context, k8sClient client.Client, CPNamespace, DPNamespace string) (func() error, error) {
var agentImageTag, agentImageRepo, agentImageProject string
if agentImageTag = os.Getenv("PROW_IMAGE_TAG"); agentImageTag == "" {
return nil, errors.New("PROW_IMAGE_TAG envvar was not set. Did you try to test without make?")
}
if agentImageRepo = os.Getenv("PROW_IMAGE_REPO"); agentImageRepo == "" {
return nil, errors.New("PROW_IMAGE_REPO envar was not set. Did you try to test without make?")
}
if agentImageProject = os.Getenv("PROW_PROJECT"); agentImageProject == "" {
return nil, errors.New("PROW_PROJECT envar was not set. Did you try to test without make?")
}
dbInitImage := fmt.Sprintf("%s/%s/%s:%s", agentImageRepo, agentImageProject, dbInitImage, agentImageTag)
loggingSidecarImage := fmt.Sprintf("%s/%s/%s:%s", agentImageRepo, agentImageProject, loggingSidecarImage, agentImageTag)
monitoringAgentImage := fmt.Sprintf("%s/%s/%s:%s", agentImageRepo, agentImageProject, monitoringAgentImage, agentImageTag)
operatorImage := fmt.Sprintf("%s/%s/%s:%s", agentImageRepo, agentImageProject, operatorImage, agentImageTag)
// Global modified for usage in pitr test.
PitrAgentImage = fmt.Sprintf("%s/%s/%s:%s", agentImageRepo, agentImageProject, PitrAgentImage, agentImageTag)
objs, err := readYamls([]string{
"config/manager/manager.yaml",
"config/rbac/role.yaml",
"config/rbac/role_binding.yaml",
})
if err != nil {
return nil, err
}
// minimal set of operator.yaml we need to deploy.
var d *appsv1.Deployment
var cr *rbacv1.ClusterRole
var crb *rbacv1.ClusterRoleBinding
for _, obj := range objs {
if _, ok := obj.(*appsv1.Deployment); ok {
d = obj.(*appsv1.Deployment)
}
if _, ok := obj.(*rbacv1.ClusterRole); ok {
if cr != nil {
return nil, fmt.Errorf("test needs to be updated to handle multiple ClusterRoles")
}
cr = obj.(*rbacv1.ClusterRole)
}
if _, ok := obj.(*rbacv1.ClusterRoleBinding); ok {
if crb != nil {
return nil, fmt.Errorf("test needs to be updated to handle multiple ClusterRoleBindings")
}
crb = obj.(*rbacv1.ClusterRoleBinding)
}
}
//Check DPNamespace against CPNamespace. If they're different, create the DPNamespace.
if CPNamespace != DPNamespace {
By("Deploying data plane in " + DPNamespace)
nsObj := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: DPNamespace,
},
}
ctx := context.Background()
Expect(k8sClient.Create(ctx, nsObj)).Should(Succeed())
}
// Add in our overrides.
cr.ObjectMeta.Name = "manager-role-" + CPNamespace
crb.ObjectMeta.Name = "manager-rolebinding-" + CPNamespace
crb.RoleRef.Name = cr.ObjectMeta.Name
crb.Subjects[0].Namespace = CPNamespace
d.Namespace = CPNamespace
d.Spec.Template.Spec.Containers[0].Image = operatorImage
d.Spec.Template.Spec.Containers[0].ImagePullPolicy = corev1.PullAlways
d.Spec.Template.Spec.Containers[0].Args = []string{
"--logtostderr=true",
"--enable-leader-election=false",
"--namespace=" + DPNamespace,
"--db_init_image_uri=" + dbInitImage,
"--logging_sidecar_image_uri=" + loggingSidecarImage,
"--monitoring_agent_image_uri=" + monitoringAgentImage,
}
// Ensure account has cluster admin to create ClusterRole/Binding. You
// can figure out the k8s account name from a GCE service account name
// using the `uniqueId` property from `gcloud iam service-accounts
// describe some@service.account`.
if err := k8sClient.Create(ctx, cr); err != nil {
return nil, err
}
if err := k8sClient.Create(ctx, crb); err != nil {
k8sClient.Delete(ctx, cr)
return nil, err
}
if err := k8sClient.Create(ctx, d); err != nil {
k8sClient.Delete(ctx, cr)
k8sClient.Delete(ctx, crb)
return nil, err
}
// Ensure deployment succeeds.
instKey := client.ObjectKey{Namespace: CPNamespace, Name: d.Name}
Eventually(func() int {
err := k8sClient.Get(ctx, instKey, d)
if err != nil {
return 0
}
return int(d.Status.ReadyReplicas)
}, 10*time.Minute, 5*time.Second).Should(Equal(1))
return func() error {
if err := k8sClient.Delete(ctx, cr); err != nil {
return err
}
if err := k8sClient.Delete(ctx, crb); err != nil {
return err
}
return nil
}, nil
}
func readYamls(files []string) ([]runtime.Object, error) {
var objs []runtime.Object
decoder := serializer.NewCodecFactory(scheme.Scheme).UniversalDeserializer()
for _, f := range files {
data, err := ioutil.ReadFile(f)
if err != nil {
return nil, fmt.Errorf("error reading '%s': %v", f, err)
}
parts := bytes.Split(data, []byte("\n---"))
// role.yaml is generated by kubebuilder with an empty yaml
// doc, this wont decode so we need to filter it out first.
for _, part := range parts {
if cleaned := bytes.TrimSpace(part); len(cleaned) > 0 {
obj, err := runtime.Decode(decoder, cleaned)
if err != nil {
return nil, fmt.Errorf("error decoding '%s': %v", f, err)
}
objs = append(objs, obj)
}
}
}
return objs, nil
}
func getOperatorLogs(ctx context.Context, config *rest.Config, namespace string) (string, error) {
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return "", err
}
pod, err := FindPodFor(ctx, clientSet, namespace, "control-plane=controller-manager")
if err != nil {
return "", err
}
return getContainerLogs(ctx, clientSet, namespace, pod.Name, "manager")
}
func getAgentLogs(ctx context.Context, config *rest.Config, namespace, instance, agent string) (string, error) {
// The label selector to find the target agent container. Different
// labels are use for the CSA/NCSA agents to associate the deployments
// with the instance.
agentToQuery := map[string]string{
// NCSA Agents
"oracle-monitoring": "deployment=" + instance + "-agent-deployment",
// CSA Agents
"oracledb": "instance=" + instance,
"dbdaemon": "instance=" + instance,
"alert-log-sidecar": "instance=" + instance,
"listener-log-sidecar": "instance=" + instance,
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return "", err
}
pod, err := FindPodFor(ctx, clientSet, namespace, agentToQuery[agent])
if err != nil {
return "", err
}
return getContainerLogs(ctx, clientSet, namespace, pod.Name, agent)
}
func getContainerLogs(ctx context.Context, clientSet *kubernetes.Clientset, ns, p, c string) (string, error) {
logOpts := corev1.PodLogOptions{
Container: c,
}
req := clientSet.CoreV1().Pods(ns).GetLogs(p, &logOpts)
podLogs, err := req.Stream(context.Background())
if err != nil {
return "", err
}
sb := strings.Builder{}
_, err = io.Copy(&sb, podLogs)
if err != nil {
return "", err
}
return sb.String(), nil
}
func FindPodFor(ctx context.Context, clientSet *kubernetes.Clientset, ns, filter string) (*corev1.Pod, error) {
listOpts := metav1.ListOptions{
LabelSelector: filter,
}
pods, err := clientSet.CoreV1().Pods(ns).List(ctx, listOpts)
if err != nil {
return nil, err
}
if len(pods.Items) < 1 {
return nil, fmt.Errorf("couldnt find Pod in %q matching %q", ns, filter)
}
if len(pods.Items) > 1 {
return nil, fmt.Errorf("found multiple Pods in %q matching %q:\n%+v", ns, filter, pods.Items)
}
return &pods.Items[0], nil
}
// GCloudServiceAccount returns the GCloud service account name.
func GCloudServiceAccount() string {
return fmt.Sprintf(
"%s@%s.iam.gserviceaccount.com",
os.Getenv("PROW_INT_TEST_SA"),
os.Getenv("PROW_PROJECT"))
}
/*
K8sOperatorEnvironment is a helper for integration testing.
Encapsulates all necessary variables to work with the test cluster
Can be created/destroyed multiple times within one test suite
Depends on the Ginkgo asserts
Example usage:
// Global variable, to be accessible by AfterSuite.
var k8sEnv = testhelpers.K8sEnvironment{}
// In case of Ctrl-C, clean up the last valid k8sEnv.
AfterSuite(func() {
k8sEnv.Close()
})
...
BeforeEach(func() {
k8sEnv.Init(testhelpers.RandName("k8s-env-stress-test"))
})
AfterEach(func() {
k8sEnv.Close()
})
*/
type K8sOperatorEnvironment struct {
Env envtest.Environment
CPNamespace string
DPNamespace string
Ctx context.Context
K8sClient client.Client
OperCleanup func() error // Operator deployment cleanup callback.
TestFailed bool // If true then dump container logs.
K8sServiceAccount string
}
// Init the environment, install CRDs, deploy operator, declare namespaces for control plane and data plane.
func (k8sEnv *K8sOperatorEnvironment) Init(CPNamespace string, DPNamespace string) {
// K8S Service account
k8sEnv.K8sServiceAccount = os.Getenv("PROW_PROJECT") + ".svc.id.goog[" + CPNamespace + "/default]"
By("Starting control plane " + CPNamespace)
// Init cluster
k8sEnv.CPNamespace = CPNamespace
k8sEnv.DPNamespace = DPNamespace
k8sEnv.Env, k8sEnv.Ctx, k8sEnv.K8sClient = initK8sCluster(&k8sEnv.CPNamespace)
// Deploy operator
By("Deploying operator in " + CPNamespace)
// Deploy Operator, retry if necessary
Expect(retry.OnError(retry.DefaultBackoff, func(error) bool { return true }, func() error {
defer GinkgoRecover()
var err error
k8sEnv.OperCleanup, err = deployOperator(k8sEnv.Ctx, k8sEnv.K8sClient, k8sEnv.CPNamespace, k8sEnv.DPNamespace)
if err != nil {
logf.FromContext(nil).Error(err, "DeployOperator failed, retrying")
}
return err
})).Should(Succeed())
}
// Close cleans cluster objects and uninstalls operator.
func (k8sEnv *K8sOperatorEnvironment) Close() {
if k8sEnv.CPNamespace == "" && k8sEnv.DPNamespace == "" {
return
}
By("Stopping control plane " + k8sEnv.CPNamespace)
Expect(k8sEnv.Env.Stop()).To(Succeed())
if k8sEnv.OperCleanup != nil {
By("Uninstalling operator " + k8sEnv.CPNamespace)
k8sEnv.OperCleanup()
}
if k8sEnv.K8sClient == nil {
return
}
cleanupK8Cluster(k8sEnv.CPNamespace, k8sEnv.DPNamespace, k8sEnv.K8sClient)
k8sEnv.CPNamespace = ""
k8sEnv.DPNamespace = ""
}
// Instance-specific helper functions.
// TestImageForVersion returns service image for integration tests.
// Image paths are predefined in the env variables TEST_IMAGE_ORACLE_*.
func TestImageForVersion(version string, edition string, extra string) string {
switch edition {
case "XE":
{
switch version {
case "18c":
{
switch extra {
default:
return os.Getenv("TEST_IMAGE_ORACLE_18_XE_SEEDED")
}
}
}
}
case "EE":
{
switch version {
case "19.3":
{
switch extra {
case "unseeded-32545013":
return os.Getenv("TEST_IMAGE_ORACLE_19_3_EE_UNSEEDED_32545013")
case "unseeded":
return os.Getenv("TEST_IMAGE_ORACLE_19_3_EE_UNSEEDED_32545013")
case "seeded-buggy":
return os.Getenv("TEST_IMAGE_ORACLE_19_3_EE_SEEDED_BUGGY")
case "ocr":
return os.Getenv("TEST_IMAGE_OCR_ORACLE_19_3_EE_UNSEEDED_29517242")
default:
return os.Getenv("TEST_IMAGE_ORACLE_19_3_EE_SEEDED")
}
}
}
}
}
return "INVALID_VERSION"
}
// CreateSimpleInstance creates a basic v1alpha1.Instance object named 'instanceName'.
// 'version' and 'edition' should match rules of TestImageForVersion().
// Depends on the Ginkgo asserts.
func CreateSimpleInstance(k8sEnv K8sOperatorEnvironment, instanceName string, version string, edition string) {
instance := &v1alpha1.Instance{
ObjectMeta: metav1.ObjectMeta{
Name: instanceName,
Namespace: k8sEnv.DPNamespace,
},
Spec: v1alpha1.InstanceSpec{
CDBName: "GCLOUD",
InstanceSpec: commonv1alpha1.InstanceSpec{
Version: version,
Disks: []commonv1alpha1.DiskSpec{
{
Name: "DataDisk",
Size: resource.MustParse("45Gi"),
},
{
Name: "LogDisk",
Size: resource.MustParse("55Gi"),
},
},
DatabaseResources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceMemory: resource.MustParse("9Gi"),
},
},
Images: map[string]string{
"service": TestImageForVersion(version, edition, ""),
},
DBLoadBalancerOptions: &commonv1alpha1.DBLoadBalancerOptions{
GCP: commonv1alpha1.DBLoadBalancerOptionsGCP{LoadBalancerType: "Internal"},
},
},
},
}
K8sCreateWithRetry(k8sEnv.K8sClient, k8sEnv.Ctx, instance)
instKey := client.ObjectKey{Namespace: k8sEnv.DPNamespace, Name: instanceName}
// Wait until the instance is "Ready" (requires 5+ minutes to download image).
WaitForInstanceConditionState(k8sEnv, instKey, k8s.Ready, metav1.ConditionTrue, k8s.CreateComplete, 20*time.Minute)
}
// CreateSimplePdbWithDbObj creates simple PDB by given database object.
func CreateSimplePdbWithDbObj(k8sEnv K8sOperatorEnvironment, database *v1alpha1.Database) {
pod := database.Spec.Instance + "-sts-0"
K8sCreateWithRetry(k8sEnv.K8sClient, k8sEnv.Ctx, database)
// Wait for the PDB to come online (UserReady = "SyncComplete").
emptyObj := &v1alpha1.Database{}
objectKey := client.ObjectKey{Namespace: k8sEnv.DPNamespace, Name: database.Name}
WaitForObjectConditionState(k8sEnv, objectKey, emptyObj, k8s.UserReady, metav1.ConditionTrue, k8s.SyncComplete, 7*time.Minute, k8s.FindConditionOrFailed)
// Open PDBs.
out := K8sExecuteSqlOrFail(pod, k8sEnv.DPNamespace, "alter pluggable database all open;")
Expect(out).To(Equal(""))
}
// CreateSimplePDB creates a simple PDB 'pdb1' inside 'instanceName' Instance.
// Depends on the Ginkgo asserts.
func CreateSimplePDB(k8sEnv K8sOperatorEnvironment, instanceName string) {
CreateSimplePdbWithDbObj(k8sEnv, &v1alpha1.Database{
ObjectMeta: metav1.ObjectMeta{
Namespace: k8sEnv.DPNamespace,
Name: "pdb1",