-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeploy_via_operator.go
More file actions
877 lines (768 loc) · 26.5 KB
/
Copy pathdeploy_via_operator.go
File metadata and controls
877 lines (768 loc) · 26.5 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
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
package deployer
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/stackrox/roxie/internal/env"
"github.com/stackrox/roxie/internal/helpers"
"github.com/stackrox/roxie/internal/k8s"
"gopkg.in/yaml.v3"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
var (
smallScale = map[string]interface{}{
"autoScaling": "Enabled",
"replicas": 1,
}
noScaling = map[string]interface{}{
"autoScaling": "Disabled",
"replicas": 1,
}
)
// deployOperatorOnly deploys only the operator without any Central or SecuredCluster resources
func (d *Deployer) deployOperatorOnly(ctx context.Context) error {
d.logger.Info("🚀 Deploying Operator only...")
if err := d.ensureOperatorDeployed(ctx); err != nil {
return err
}
d.logger.Success("✓ Operator deployed successfully")
d.logger.Info("You can now deploy Central or SecuredCluster components separately")
return nil
}
// ensureOperatorDeployed ensures the operator is deployed with the correct version and mode
func (d *Deployer) ensureOperatorDeployed(ctx context.Context) error {
// Skip operator deployment/checks if flag is set to false
if !d.shouldDeployOperator {
d.logger.Info("ℹ️ Skipping operator deployment checks (--deploy-operator=false)")
d.logger.Info(" Assuming operator is already running...")
return nil
}
if err := d.ensureCRDsInstalled(ctx); err != nil {
return fmt.Errorf("failed to ensure CRDs installed: %w", err)
}
// Detect current operator deployment mode
operatorExists, currentMode, err := d.detectOperatorDeploymentMode(ctx)
if err != nil {
return fmt.Errorf("detecting operator deployment mode: %w", err)
}
needsDeployment := false
needsTeardown := false
if !operatorExists {
needsDeployment = true
} else if d.useOLM && currentMode == OperatorModeNonOLM {
// Switching from non-OLM to OLM
d.logger.Info("🔄 Switching operator from non-OLM to OLM mode...")
needsTeardown = true
needsDeployment = true
} else if !d.useOLM && currentMode == OperatorModeOLM {
// Switching from OLM to non-OLM
d.logger.Info("🔄 Switching operator from OLM to non-OLM mode...")
needsTeardown = true
needsDeployment = true
} else {
// Same mode, check version
if d.isOperatorVersionCorrect(ctx) {
d.logger.Info("✓ Operator already deployed with correct version")
} else {
d.logger.Info("🔄 Operator version mismatch, redeploying...")
needsTeardown = true
needsDeployment = true
}
}
if needsTeardown {
// Perform teardown for the current mode
if currentMode == OperatorModeOLM {
if err := d.teardownOperatorOLM(ctx); err != nil {
return fmt.Errorf("failed to teardown OLM operator: %w", err)
}
} else {
if err := d.teardownOperatorNonOLM(ctx); err != nil {
return fmt.Errorf("failed to teardown non-OLM operator: %w", err)
}
}
}
if needsDeployment {
if d.useOLM {
if err := d.deployOperatorViaOLM(ctx); err != nil {
return fmt.Errorf("failed to deploy operator via OLM: %w", err)
}
} else {
if err := d.deployOperatorNonOLM(ctx); err != nil {
return fmt.Errorf("failed to deploy operator: %w", err)
}
}
}
return nil
}
// deployCentralOperator deploys Central using the operator
func (d *Deployer) deployCentralOperator(ctx context.Context, resources, exposure string) error {
d.logger.Info("🚀 Deploying Central via Operator...")
needPullSecrets := env.GetCurrentClusterType() != env.InfraOpenShift4
if err := d.prepareNamespace(ctx, d.centralNamespace, needPullSecrets); err != nil {
return fmt.Errorf("failed to prepare namespace: %w", err)
}
if err := d.createAdminPasswordSecret(ctx); err != nil {
return fmt.Errorf("failed to create admin password secret: %w", err)
}
centralCR, err := d.createCentralCR(resources, exposure)
if err != nil {
return fmt.Errorf("failed to create Central CR: %w", err)
}
if err := d.applyCentralCR(ctx, centralCR); err != nil {
return fmt.Errorf("failed to apply Central CR: %w", err)
}
if err := d.waitForCentralReady(ctx, d.centralWaitTimeout); err != nil {
return fmt.Errorf("failed waiting for Central: %w", err)
}
if err := d.maybeAddPauseReconcileAnnotation(ctx, "central", "stackrox-central-services", d.centralNamespace); err != nil {
d.logger.Warningf("failed to add pause-reconcile annotation: %v", err)
}
return d.configureCentralEndpoint(ctx, exposure)
}
// isOperatorVersionCorrect checks if the deployed operator matches the desired version
func (d *Deployer) isOperatorVersionCorrect(ctx context.Context) bool {
currentImage, err := d.getDeployedOperatorImage(ctx)
if err != nil {
d.logger.Warningf("Could not retrieve operator image: %v", err)
return false
}
// Extract the tag from the current image
parts := strings.SplitN(currentImage, ":", 2)
if len(parts) < 2 {
d.logger.Warningf("Could not parse operator image tag from: %s", currentImage)
return false
}
currentTag := parts[1]
if currentTag != d.operatorTag {
d.logger.Info("Operator version mismatch detected:")
d.logger.Infof(" Current: %s", currentTag)
d.logger.Infof(" Desired: %s", d.operatorTag)
return false
}
return true
}
// getDeployedOperatorImage gets the image of the currently deployed operator
func (d *Deployer) getDeployedOperatorImage(ctx context.Context) (string, error) {
result, err := d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"get", "deployment", operatorDeploymentName, "-n", operatorNamespace,
"-o", "jsonpath={.spec.template.spec.containers[0].image}"},
})
if err != nil {
return "", err
}
image := strings.TrimSpace(result.Stdout)
return image, nil
}
// prepareNamespace creates pull secrets in the namespace if needed
func (d *Deployer) prepareNamespace(ctx context.Context, namespace string, needPullSecrets bool) error {
d.logger.Infof("Preparing namespace %s", namespace)
if err := d.ensureNamespaceExists(namespace); err != nil {
return err
}
if needPullSecrets {
if err := d.ensurePullSecretExists(ctx, namespace); err != nil {
return fmt.Errorf("ensuring image pull secret exists: %w", err)
}
}
return nil
}
func (d *Deployer) ensurePullSecretExists(ctx context.Context, namespace string) error {
if d.dockerCreds == nil {
return errors.New("no pull secrets available to set up on the cluster")
}
pullSecretYAML := d.dockerAuth.CreatePullSecretYAMLFromCredentials(*d.dockerCreds, namespace)
_, err := d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"apply", "-f", "-"},
Stdin: strings.NewReader(pullSecretYAML),
})
if err != nil {
d.logger.Warningf("Could not apply pull secret: %v", err)
}
return nil
}
// createAdminPasswordSecret creates the admin password secret
func (d *Deployer) createAdminPasswordSecret(ctx context.Context) error {
secret := map[string]interface{}{
"apiVersion": "v1",
"kind": "Secret",
"metadata": map[string]interface{}{
"name": adminPasswordSecretName,
"namespace": d.centralNamespace,
},
"type": "Opaque",
"stringData": map[string]string{
"password": d.centralPassword,
},
}
yamlData, err := yaml.Marshal(secret)
if err != nil {
return fmt.Errorf("failed to marshal secret: %w", err)
}
_, err = d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"apply", "-f", "-"},
Stdin: bytes.NewReader(yamlData),
})
if err != nil {
return fmt.Errorf("failed to create admin password secret: %w", err)
}
d.logger.Success("✓ Admin password secret created")
return nil
}
// createCentralCR creates the Central custom resource
func (d *Deployer) createCentralCR(resources, exposure string) (map[string]interface{}, error) {
base := map[string]interface{}{
"apiVersion": "platform.stackrox.io/v1alpha1",
"kind": "Central",
"metadata": map[string]interface{}{
"name": "stackrox-central-services",
"namespace": d.centralNamespace,
"labels": map[string]string{
"app": "stackrox-central",
},
},
"spec": map[string]interface{}{
"central": map[string]interface{}{
"exposure": d.getCentralExposureConfig(exposure),
"adminPasswordSecret": map[string]interface{}{
"name": adminPasswordSecretName,
},
"telemetry": map[string]interface{}{
"enabled": false,
},
},
},
}
d.logger.Infof("Using Central resource profile: %s", resources)
resourcesOverlay := d.getCentralResourcesOperator(resources)
merged := helpers.MergeMaps(base, resourcesOverlay, d.centralOverrides)
// Apply feature flag overrides last with smart envVars merging
if d.featureFlagOverrides != nil {
merged = mergeWithEnvVarSupport(merged, d.featureFlagOverrides)
}
return merged, nil
}
func (d *Deployer) getCentralResourcesOperator(resourcesName string) map[string]interface{} {
switch resourcesName {
case "small":
return map[string]interface{}{
"spec": map[string]interface{}{
"central": map[string]interface{}{
"resources": centralResourcesSmall,
"db": map[string]interface{}{
"resources": centralDbResourcesSmall,
"persistence": map[string]interface{}{
"persistentVolumeClaim": map[string]interface{}{
"size": centralDbPVCSizeSmall,
},
},
},
},
"scanner": map[string]interface{}{
"scannerComponent": "Disabled",
"analyzer": map[string]interface{}{
"scaling": noScaling,
"resources": centralScannerResourcesSmall,
},
"db": map[string]interface{}{
"resources": centralScannerDbResourcesSmall,
},
},
"scannerV4": map[string]interface{}{
"db": map[string]interface{}{
"resources": centralScannerV4DbResourcesSmall,
},
"indexer": map[string]interface{}{
"resources": centralScannerV4IndexerResourcesSmall,
"scaling": noScaling,
},
"matcher": map[string]interface{}{
"resources": centralScannerV4MatcherResourcesSmall,
"scaling": noScaling,
},
},
},
}
case "medium":
return map[string]interface{}{
"spec": map[string]interface{}{
"central": map[string]interface{}{
"resources": centralResourcesMedium,
"db": map[string]interface{}{
"resources": centralDbResourcesMedium,
},
},
"scanner": map[string]interface{}{
"analyzer": map[string]interface{}{
"scaling": noScaling,
"resources": centralScannerResourcesMedium,
},
"db": map[string]interface{}{
"resources": centralScannerDbResourcesMedium,
},
},
"scannerV4": map[string]interface{}{
"db": map[string]interface{}{
"resources": centralScannerV4DbResourcesMedium,
},
"indexer": map[string]interface{}{
"resources": centralScannerV4IndexerResourcesMedium,
"scaling": noScaling,
},
"matcher": map[string]interface{}{
"resources": centralScannerV4MatcherResourcesMedium,
"scaling": noScaling,
},
},
},
}
case "ci":
return map[string]interface{}{
"spec": map[string]interface{}{
"central": map[string]interface{}{
"db": map[string]interface{}{
"resources": centralDbResourcesCI,
},
},
"scanner": map[string]interface{}{
"analyzer": map[string]interface{}{
"scaling": noScaling,
},
},
"scannerV4": map[string]interface{}{
"db": map[string]interface{}{
"resources": centralScannerV4DbResourcesCI,
},
"indexer": map[string]interface{}{
"resources": centralScannerV4IndexerResourcesCI,
"scaling": noScaling,
},
"matcher": map[string]interface{}{
"resources": centralScannerV4MatcherResourcesCI,
"scaling": noScaling,
},
},
},
}
default:
return nil
}
}
// getCentralExposureConfig returns the exposure configuration
func (d *Deployer) getCentralExposureConfig(exposure string) map[string]interface{} {
switch exposure {
case "loadbalancer":
return map[string]interface{}{
"loadBalancer": map[string]interface{}{
"enabled": true,
"port": 443,
},
}
case "none":
return map[string]interface{}{
"nodePort": map[string]interface{}{
"enabled": false,
},
"loadBalancer": map[string]interface{}{
"enabled": false,
},
"route": map[string]interface{}{
"enabled": false,
},
}
default:
return map[string]interface{}{
"loadBalancer": map[string]interface{}{
"enabled": true,
"port": 443,
},
}
}
}
// applyCentralCR applies the Central CR to the cluster
func (d *Deployer) applyCentralCR(ctx context.Context, cr map[string]interface{}) error {
d.logger.Info("Applying Central custom resource")
yamlData, err := yaml.Marshal(cr)
if err != nil {
return fmt.Errorf("failed to marshal Central CR: %w", err)
}
if d.verbose {
if env.RunningInteractively {
d.logger.Dim("Central CR YAML:")
d.logger.Dim(string(yamlData))
} else {
d.logger.Dim("Skipping emitting Central CR in non-interactive mode, because it could leak confidential information")
}
}
result, err := d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"apply", "-f", "-"},
Stdin: bytes.NewReader(yamlData),
})
if err != nil {
d.logger.Errorf("kubectl stdout: %s", result.Stdout)
d.logger.Errorf("kubectl stderr: %s", result.Stderr)
return fmt.Errorf("failed to apply Central CR: %w\nStderr: %s", err, result.Stderr)
}
d.logger.Success("✓ Central Custom Resource applied")
return nil
}
// waitForCentralReady waits for Central to be ready
func (d *Deployer) waitForCentralReady(ctx context.Context, timeout time.Duration) error {
d.logger.Infof("⏳ Waiting for Central to become ready (timeout: %s)...", timeout)
// Track seen deployments and their states to avoid duplicate messages
seenDeployments := make(map[string]string)
seenPods := make(map[string]string)
start := time.Now()
checkInterval := 3 * time.Second
for time.Since(start) < timeout {
// Check for new deployments
d.checkDeploymentProgress(ctx, seenDeployments)
// Check for pod events if in early readiness mode or verbose
if d.earlyReadiness || d.verbose {
d.checkPodProgress(ctx, seenPods)
}
// Check if central deployment is ready
result, err := d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"get", "deployment", "central", "-n", d.centralNamespace, "-o", "jsonpath={.status.readyReplicas}"},
})
if err == nil && result.Stdout != "" {
replicas := strings.TrimSpace(result.Stdout)
if replicas != "0" && replicas != "" {
d.logger.Successf("✓ Central is ready (%s replicas)", replicas)
return nil
}
}
// TODO(ROX-34499): using `kubectl wait` (which in turn - I hope - uses a watch) instead of
// polling would allow us to not waste time here
time.Sleep(checkInterval)
}
return errors.New("timeout waiting for Central to become ready")
}
// checkDeploymentProgress checks for deployment state changes and reports them
func (d *Deployer) checkDeploymentProgress(ctx context.Context, seenDeployments map[string]string) {
d.checkDeploymentProgressInNamespace(ctx, d.centralNamespace, seenDeployments)
}
// checkPodProgress checks for pod state changes and reports them
func (d *Deployer) checkPodProgress(ctx context.Context, seenPods map[string]string) {
d.checkPodProgressInNamespace(ctx, d.centralNamespace, seenPods)
}
// waitForLoadBalancer waits for a LoadBalancer service to get an external IP.
// Returns the endpoint as "host:port", with no https:// prefix.
func (d *Deployer) waitForLoadBalancer(ctx context.Context, namespace, serviceName string, timeout int) (string, error) {
d.logger.Infof("⏳ Waiting for LoadBalancer %s to get external IP...", serviceName)
start := time.Now()
for time.Since(start) < time.Duration(timeout)*time.Second {
result, err := d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"get", "svc", serviceName, "-n", namespace, "-o", "jsonpath={.status.loadBalancer.ingress[0].ip}"},
})
if err == nil && result.Stdout != "" {
ip := strings.TrimSpace(result.Stdout)
if ip != "" && ip != "<pending>" {
if env.RunningInteractively {
d.logger.Successf("✓ LoadBalancer IP: %s", ip)
} else {
d.logger.Success("✓ LoadBalancer IP")
}
return fmt.Sprintf("%s:443", ip), nil
}
}
// Also check for hostname (some cloud providers use hostname instead of IP)
result, err = d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"get", "svc", serviceName, "-n", namespace, "-o", "jsonpath={.status.loadBalancer.ingress[0].hostname}"},
})
if err == nil && result.Stdout != "" {
hostname := strings.TrimSpace(result.Stdout)
if hostname != "" && hostname != "<pending>" {
if env.RunningInteractively {
d.logger.Successf("✓ LoadBalancer hostname: %s", hostname)
} else {
d.logger.Success("✓ LoadBalancer hostname")
}
return fmt.Sprintf("%s:443", hostname), nil
}
}
time.Sleep(5 * time.Second)
}
return "", errors.New("timeout waiting for LoadBalancer to get external address")
}
// fetchCentralCACert fetches the Central CA certificate
func (d *Deployer) fetchCentralCACert(ctx context.Context) error {
d.logger.Info("Fetching Central CA certificate...")
result, err := d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"get", "secret", "central-tls", "-n", d.centralNamespace, "-o", "jsonpath={.data.ca\\.pem}"},
})
if err != nil {
return fmt.Errorf("failed to get CA cert from secret: %w", err)
}
caCertBase64 := strings.TrimSpace(result.Stdout)
if caCertBase64 == "" {
return errors.New("CA certificate is empty")
}
decodeCmd := exec.CommandContext(ctx, "base64", "-d")
decodeCmd.Stdin = strings.NewReader(caCertBase64)
caCert, err := decodeCmd.Output()
if err != nil {
return fmt.Errorf("failed to decode CA cert: %w", err)
}
caCertFile, err := os.CreateTemp(d.tempDir, "roxie-central-ca-*.pem")
if err != nil {
return fmt.Errorf("failed to create temp file for CA cert: %w", err)
}
d.roxCACertFile = caCertFile.Name()
if _, err := caCertFile.Write(caCert); err != nil {
_ = caCertFile.Close()
_ = os.Remove(d.roxCACertFile)
return fmt.Errorf("failed to write CA cert: %w", err)
}
if err := caCertFile.Close(); err != nil {
return fmt.Errorf("failed to close CA cert file: %w", err)
}
d.logger.Successf("✓ CA certificate saved to: %s", d.roxCACertFile)
return nil
}
// configureCentralEndpoint configures the central endpoint based on exposure settings
func (d *Deployer) configureCentralEndpoint(ctx context.Context, exposure string) error {
if d.portForwardEnabled {
// Start port-forward for CLI tool access via localhost:8443
serviceName := "central"
if exposure == "loadbalancer" {
_, err := d.waitForLoadBalancer(ctx, d.centralNamespace, "central-loadbalancer", 300)
if err != nil {
d.logger.Warningf("LoadBalancer not ready: %v", err)
} else {
serviceName = "central-loadbalancer"
}
}
if d.envrcFile != "" {
endpoint, pid, err := d.portForward.StartDetached(d.centralNamespace, serviceName, 443, 8443)
if err != nil {
return fmt.Errorf("failed to start detached port-forward: %w", err)
}
d.centralEndpoint = endpoint
d.portForwardPID = pid
} else {
endpoint, err := d.portForward.Start(d.centralNamespace, serviceName, 443, 8443)
if err != nil {
return fmt.Errorf("failed to start port-forward: %w", err)
}
d.centralEndpoint = endpoint
}
} else if exposure == "loadbalancer" {
endpoint, err := d.waitForLoadBalancer(ctx, d.centralNamespace, "central-loadbalancer", 300)
if err != nil {
return fmt.Errorf("failed to get LoadBalancer endpoint: %w", err)
}
d.centralEndpoint = endpoint
} else {
d.centralEndpoint = "central." + centralNamespace + ".svc:443"
}
if err := d.fetchCentralCACert(ctx); err != nil {
d.logger.Warningf("Could not fetch CA cert: %v", err)
}
if env.RunningInteractively {
d.logger.Successf("✓ Central is ready at: %s", d.centralEndpoint)
d.logger.Successf("✓ Admin password: %s", d.centralPassword)
}
return nil
}
// deploySecuredClusterOperator deploys SecuredCluster using the operator.
func (d *Deployer) deploySecuredClusterOperator(ctx context.Context, resources string) error {
d.logger.Info("🚀 Deploying SecuredCluster via Operator...")
needPullSecrets := env.GetCurrentClusterType() != env.InfraOpenShift4
if err := d.prepareNamespace(ctx, d.sensorNamespace, needPullSecrets); err != nil {
return fmt.Errorf("failed to prepare namespace: %w", err)
}
securedClusterCR, err := d.createSecuredClusterCR(resources)
if err != nil {
return fmt.Errorf("failed to create SecuredCluster CR: %w", err)
}
clusterName, found, err := unstructured.NestedString(securedClusterCR, "spec", "clusterName")
if err != nil {
return fmt.Errorf("failed to get cluster name from SecuredCluster CR: %w", err)
}
if !found || clusterName == "" {
return fmt.Errorf("cluster name not found in SecuredCluster CR")
}
d.logger.Infof("Using cluster name: %s", clusterName)
crsContent, err := d.generateCRS(ctx, clusterName)
if err != nil {
return fmt.Errorf("failed to generate CRS: %w", err)
}
if err := d.applyCRS(ctx, crsContent); err != nil {
return fmt.Errorf("failed to apply CRS: %w", err)
}
if err := d.applySecuredClusterCR(ctx, securedClusterCR); err != nil {
return fmt.Errorf("failed to apply SecuredCluster CR: %w", err)
}
if err := d.waitForSecuredClusterReady(ctx, d.securedClusterWaitTimeout); err != nil {
return fmt.Errorf("failed waiting for SecuredCluster: %w", err)
}
if err := d.maybeAddPauseReconcileAnnotation(ctx, "securedcluster", "stackrox-secured-cluster-services", d.sensorNamespace); err != nil {
d.logger.Warningf("failed to add pause-reconcile annotation: %v", err)
}
d.logger.Successf("✓ SecuredCluster '%s' is ready", clusterName)
return nil
}
// createSecuredClusterCR creates the SecuredCluster custom resource.
func (d *Deployer) createSecuredClusterCR(resources string) (map[string]interface{}, error) {
base := map[string]interface{}{
"apiVersion": "platform.stackrox.io/v1alpha1",
"kind": "SecuredCluster",
"metadata": map[string]interface{}{
"name": "stackrox-secured-cluster-services",
"namespace": d.sensorNamespace,
"labels": map[string]string{
"app": "stackrox-secured-cluster",
},
},
"spec": map[string]interface{}{
"clusterName": generateClusterName(), // Just a default, can be overwritten.
"centralEndpoint": internalCentralEndpoint(d.centralNamespace),
"imagePullSecrets": []map[string]string{
{"name": "stackrox"},
},
},
}
resourcesOverlay := d.getSecuredClusterResourcesOperator(resources)
merged := helpers.MergeMaps(base, resourcesOverlay, d.securedClusterOverrides)
// Apply feature flag overrides last with smart envVars merging
if d.featureFlagOverrides != nil {
merged = mergeWithEnvVarSupport(merged, d.featureFlagOverrides)
}
return merged, nil
}
func (d *Deployer) getSecuredClusterResourcesOperator(resourcesName string) map[string]interface{} {
switch resourcesName {
case "small":
return map[string]interface{}{
"spec": map[string]interface{}{
"sensor": map[string]interface{}{
"resources": securedClusterSensorResourcesSmall,
},
"scanner": map[string]interface{}{
"scannerComponent": "Disabled",
"analyzer": map[string]interface{}{
"scaling": smallScale,
},
},
"scannerV4": map[string]interface{}{
"indexer": map[string]interface{}{
"scaling": noScaling,
},
},
},
}
case "medium":
return map[string]interface{}{
"spec": map[string]interface{}{
"admissionControl": map[string]interface{}{
"replicas": 1,
},
"scanner": map[string]interface{}{
"analyzer": map[string]interface{}{
"scaling": smallScale,
},
},
"sensor": map[string]interface{}{
"resources": securedClusterSensorResourcesMedium,
},
"scannerV4": map[string]interface{}{
"indexer": map[string]interface{}{
"scaling": noScaling,
},
},
},
}
case "ci":
return map[string]interface{}{
"spec": map[string]interface{}{
"sensor": map[string]interface{}{
"resources": securedClusterSensorResourcesCI,
},
},
}
default:
return nil
}
}
// applySecuredClusterCR applies the SecuredCluster CR to the cluster
func (d *Deployer) applySecuredClusterCR(ctx context.Context, cr map[string]interface{}) error {
d.logger.Info("Applying SecuredCluster custom resource")
yamlData, err := yaml.Marshal(cr)
if err != nil {
return fmt.Errorf("failed to marshal SecuredCluster CR: %w", err)
}
if d.verbose {
if env.RunningInteractively {
d.logger.Dim("SecuredCluster CR YAML:")
d.logger.Dim(string(yamlData))
} else {
d.logger.Dim("Skipping emitting SecuredCluster CR in non-interactive mode, because it could leak confidential information")
}
}
result, err := d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"apply", "-n", d.sensorNamespace, "-f", "-"},
Stdin: bytes.NewReader(yamlData),
})
if err != nil {
d.logger.Errorf("kubectl error: %s", result.Stderr)
return fmt.Errorf("failed to apply SecuredCluster CR: %w", err)
}
d.logger.Success("✓ SecuredCluster CR applied")
return nil
}
// waitForSecuredClusterReady waits for SecuredCluster to be ready
func (d *Deployer) waitForSecuredClusterReady(ctx context.Context, timeout time.Duration) error {
d.logger.Infof("⏳ Waiting for SecuredCluster to become ready (timeout: %s)...", timeout)
// Track seen deployments and their states to avoid duplicate messages
seenDeployments := make(map[string]string)
seenPods := make(map[string]string)
start := time.Now()
checkInterval := 3 * time.Second
for time.Since(start) < timeout {
d.checkDeploymentProgressInNamespace(ctx, d.sensorNamespace, seenDeployments)
if d.earlyReadiness || d.verbose {
d.checkPodProgressInNamespace(ctx, d.sensorNamespace, seenPods)
}
allReady := true
// Check sensor deployment
result, err := d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"get", "deployment", "sensor", "-n", d.sensorNamespace, "-o", "jsonpath={.status.readyReplicas}"},
})
if err != nil || result.Stdout == "" {
allReady = false
} else {
replicas := strings.TrimSpace(result.Stdout)
if replicas == "0" || replicas == "" {
allReady = false
}
}
// Only check additional workloads if early-readiness is not enabled
if !d.earlyReadiness {
// Check admission-control deployment
result, err = d.runKubectl(ctx, k8s.KubectlOptions{
Args: []string{"get", "deployment", "admission-control", "-n", d.sensorNamespace, "-o", "jsonpath={.status.readyReplicas}"},
})
if err != nil || result.Stdout == "" {
allReady = false
} else {
replicas := strings.TrimSpace(result.Stdout)
if replicas == "0" || replicas == "" {
allReady = false
}
}
// collector seems to be crashing on some local cluster types/versions.
// TODO(ROX-34499): skip the check only on local clusters, then?
}
if allReady {
d.logger.Success("✓ SecuredCluster is ready")
return nil
}
time.Sleep(checkInterval)
}
return errors.New("timeout waiting for SecuredCluster to become ready")
}