-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgcp.go
More file actions
1532 lines (1354 loc) · 47.8 KB
/
gcp.go
File metadata and controls
1532 lines (1354 loc) · 47.8 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
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 (c) Codesphere Inc.
// SPDX-License-Identifier: Apache-2.0
package gcp
import (
"context"
"errors"
"fmt"
"slices"
"sort"
"strings"
"sync"
"time"
"cloud.google.com/go/compute/apiv1/computepb"
"github.com/codesphere-cloud/oms/internal/bootstrap"
"github.com/codesphere-cloud/oms/internal/env"
"github.com/codesphere-cloud/oms/internal/installer"
"github.com/codesphere-cloud/oms/internal/installer/files"
"github.com/codesphere-cloud/oms/internal/installer/node"
"github.com/codesphere-cloud/oms/internal/portal"
"github.com/codesphere-cloud/oms/internal/util"
"github.com/lithammer/shortuuid"
"google.golang.org/api/dns/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type RegistryType string
const (
RegistryTypeLocalContainer RegistryType = "local-container"
RegistryTypeArtifactRegistry RegistryType = "artifact-registry"
RegistryTypeGitHub RegistryType = "github"
)
type VMDef struct {
Name string
MachineType string
Tags []string
AdditionalDisks []int64
ExternalIP bool
}
// Example VM definitions (expand as needed)
var vmDefs = []VMDef{
{"jumpbox", "e2-medium", []string{"jumpbox", "ssh"}, []int64{}, true},
{"postgres", "e2-standard-8", []string{"postgres"}, []int64{}, true},
{"ceph-1", "e2-standard-8", []string{"ceph"}, []int64{20, 200}, false},
{"ceph-2", "e2-standard-8", []string{"ceph"}, []int64{20, 200}, false},
{"ceph-3", "e2-standard-8", []string{"ceph"}, []int64{20, 200}, false},
{"ceph-4", "e2-standard-8", []string{"ceph"}, []int64{20, 200}, false},
{"k0s-1", "e2-standard-16", []string{"k0s"}, []int64{}, false},
{"k0s-2", "e2-standard-16", []string{"k0s"}, []int64{}, false},
{"k0s-3", "e2-standard-16", []string{"k0s"}, []int64{}, false},
}
var DefaultExperiments []string = []string{
"managed-services",
"vcluster",
"custom-service-image",
"ms-in-ls",
"secret-management",
"sub-path-mount",
}
type GCPBootstrapper struct {
ctx context.Context
stlog *bootstrap.StepLogger
fw util.FileIO
icg installer.InstallConfigManager
GCPClient GCPClientManager
// Environment
Env *CodesphereEnvironment
// SSH command runner
NodeClient node.NodeClient
PortalClient portal.Portal
}
type CodesphereEnvironment struct {
ProjectID string `json:"project_id"`
ProjectName string `json:"project_name"`
DNSProjectID string `json:"dns_project_id"`
Jumpbox *node.Node `json:"jumpbox"`
PostgreSQLNode *node.Node `json:"postgres_node"`
ControlPlaneNodes []*node.Node `json:"control_plane_nodes"`
CephNodes []*node.Node `json:"ceph_nodes"`
ContainerRegistryURL string `json:"-"`
ExistingConfigUsed bool `json:"-"`
InstallVersion string `json:"install_version"`
InstallHash string `json:"install_hash"`
InstallSkipSteps []string `json:"install_skip_steps"`
Preemptible bool `json:"preemptible"`
WriteConfig bool `json:"-"`
GatewayIP string `json:"gateway_ip"`
PublicGatewayIP string `json:"public_gateway_ip"`
RegistryType RegistryType `json:"registry_type"`
GitHubPAT string `json:"-"`
GitHubAppName string `json:"-"`
RegistryUser string `json:"-"`
Experiments []string `json:"experiments"`
FeatureFlags []string `json:"feature_flags"`
// Config
InstallConfigPath string `json:"-"`
SecretsFilePath string `json:"-"`
InstallConfig *files.RootConfig `json:"-"`
Secrets *files.InstallVault `json:"-"`
// GCP Specific
ProjectDisplayName string `json:"project_display_name"`
BillingAccount string `json:"billing_account"`
BaseDomain string `json:"base_domain"`
GithubAppClientID string `json:"-"`
GithubAppClientSecret string `json:"-"`
SecretsDir string `json:"secrets_dir"`
FolderID string `json:"folder_id"`
SSHPublicKeyPath string `json:"-"`
SSHPrivateKeyPath string `json:"-"`
DatacenterID int `json:"-"`
CustomPgIP string `json:"custom_pg_ip"`
Region string `json:"region"`
Zone string `json:"zone"`
DNSZoneName string `json:"dns_zone_name"`
}
func NewGCPBootstrapper(
ctx context.Context,
env env.Env,
stlog *bootstrap.StepLogger,
CodesphereEnv *CodesphereEnvironment,
icg installer.InstallConfigManager,
gcpClient GCPClientManager,
fw util.FileIO,
sshRunner node.NodeClient,
portalClient portal.Portal,
) (*GCPBootstrapper, error) {
return &GCPBootstrapper{
ctx: ctx,
stlog: stlog,
fw: fw,
icg: icg,
GCPClient: gcpClient,
Env: CodesphereEnv,
NodeClient: sshRunner,
PortalClient: portalClient,
}, nil
}
func GetInfraFilePath() string {
workdir := env.NewEnv().GetOmsWorkdir()
return fmt.Sprintf("%s/gcp-infra.json", workdir)
}
func (b *GCPBootstrapper) Bootstrap() error {
if b.Env.InstallVersion != "" {
err := b.stlog.Step("Validate input", b.ValidateInput)
if err != nil {
return fmt.Errorf("invalid input: %w", err)
}
}
err := b.stlog.Step("Ensure install config", b.EnsureInstallConfig)
if err != nil {
return fmt.Errorf("failed to ensure install config: %w", err)
}
err = b.stlog.Step("Ensure secrets", b.EnsureSecrets)
if err != nil {
return fmt.Errorf("failed to ensure secrets: %w", err)
}
err = b.stlog.Step("Ensure project", b.EnsureProject)
if err != nil {
return fmt.Errorf("failed to ensure GCP project: %w", err)
}
err = b.stlog.Step("Ensure billing", b.EnsureBilling)
if err != nil {
return fmt.Errorf("failed to ensure billing is enabled: %w", err)
}
err = b.stlog.Step("Ensure APIs enabled", b.EnsureAPIsEnabled)
if err != nil {
return fmt.Errorf("failed to enable required APIs: %w", err)
}
if b.Env.RegistryType == RegistryTypeArtifactRegistry {
err = b.stlog.Step("Ensure artifact registry", b.EnsureArtifactRegistry)
if err != nil {
return fmt.Errorf("failed to ensure artifact registry: %w", err)
}
}
err = b.stlog.Step("Ensure service accounts", b.EnsureServiceAccounts)
if err != nil {
return fmt.Errorf("failed to ensure service accounts: %w", err)
}
err = b.stlog.Step("Ensure IAM roles", b.EnsureIAMRoles)
if err != nil {
return fmt.Errorf("failed to ensure IAM roles: %w", err)
}
err = b.stlog.Step("Ensure VPC", b.EnsureVPC)
if err != nil {
return fmt.Errorf("failed to ensure VPC: %w", err)
}
err = b.stlog.Step("Ensure firewall rules", b.EnsureFirewallRules)
if err != nil {
return fmt.Errorf("failed to ensure firewall rules: %w", err)
}
err = b.stlog.Step("Ensure compute instances", b.EnsureComputeInstances)
if err != nil {
return fmt.Errorf("failed to ensure compute instances: %w", err)
}
err = b.stlog.Step("Ensure gateway IP addresses", b.EnsureGatewayIPAddresses)
if err != nil {
return fmt.Errorf("failed to ensure external IP addresses: %w", err)
}
err = b.stlog.Step("Ensure root login enabled", b.EnsureRootLoginEnabled)
if err != nil {
return fmt.Errorf("failed to ensure root login is enabled: %w", err)
}
err = b.stlog.Step("Ensure jumpbox configured", b.EnsureJumpboxConfigured)
if err != nil {
return fmt.Errorf("failed to ensure jumpbox is configured: %w", err)
}
err = b.stlog.Step("Ensure hosts are configured", b.EnsureHostsConfigured)
if err != nil {
return fmt.Errorf("failed to ensure hosts are configured: %w", err)
}
if b.Env.RegistryType == RegistryTypeLocalContainer {
err = b.stlog.Step("Ensure local container registry", b.EnsureLocalContainerRegistry)
if err != nil {
return fmt.Errorf("failed to ensure local container registry: %w", err)
}
}
if b.Env.RegistryType == RegistryTypeGitHub {
err = b.stlog.Step("Ensure GitHub access configured", b.EnsureGitHubAccessConfigured)
if err != nil {
return fmt.Errorf("failed to update install config: %w", err)
}
}
if b.Env.WriteConfig {
err = b.stlog.Step("Update install config", b.UpdateInstallConfig)
if err != nil {
return fmt.Errorf("failed to update install config: %w", err)
}
err = b.stlog.Step("Ensure age key", b.EnsureAgeKey)
if err != nil {
return fmt.Errorf("failed to ensure age key: %w", err)
}
err = b.stlog.Step("Encrypt vault", b.EncryptVault)
if err != nil {
return fmt.Errorf("failed to encrypt vault: %w", err)
}
}
err = b.stlog.Step("Ensure DNS records", b.EnsureDNSRecords)
if err != nil {
return fmt.Errorf("failed to ensure DNS records: %w", err)
}
err = b.stlog.Step("Generate k0s config script", b.GenerateK0sConfigScript)
if err != nil {
return fmt.Errorf("failed to generate k0s config script: %w", err)
}
if b.Env.InstallVersion != "" {
err = b.stlog.Step("Install Codesphere", b.InstallCodesphere)
if err != nil {
return fmt.Errorf("failed to install Codesphere: %w", err)
}
err = b.stlog.Step("Run k0s config script", b.RunK0sConfigScript)
if err != nil {
return fmt.Errorf("failed to run k0s config script: %w", err)
}
}
return nil
}
func (b *GCPBootstrapper) ValidateInput() error {
build, err := b.PortalClient.GetBuild(portal.CodesphereProduct, b.Env.InstallVersion, b.Env.InstallHash)
if err != nil {
return fmt.Errorf("failed to get codesphere package: %w", err)
}
requiredFilename := "installer.tar.gz"
if b.Env.RegistryType == RegistryTypeGitHub {
requiredFilename = "installer-lite.tar.gz"
}
filenames := []string{}
// Validate required file exists in package artifacts
for _, artifact := range build.Artifacts {
filenames = append(filenames, artifact.Filename)
if artifact.Filename == requiredFilename {
return nil
}
}
ghParams := []string{b.Env.GitHubAppName, b.Env.GithubAppClientID, b.Env.GithubAppClientSecret}
if slices.Contains(ghParams, "") && strings.Join(ghParams, "") != "" {
return fmt.Errorf("GitHub app credentials are not fully specified (all or none of GitHubAppName, GithubAppClientID, GithubAppClientSecret must be set)")
}
return fmt.Errorf("specified package does not contain required installer artifact %s. Existing artifacts: %s", requiredFilename, strings.Join(filenames, ", "))
}
func (b *GCPBootstrapper) EnsureInstallConfig() error {
if b.fw.Exists(b.Env.InstallConfigPath) {
err := b.icg.LoadInstallConfigFromFile(b.Env.InstallConfigPath)
if err != nil {
return fmt.Errorf("failed to load config file: %w", err)
}
b.Env.ExistingConfigUsed = true
} else {
err := b.icg.ApplyProfile("dev")
if err != nil {
return fmt.Errorf("failed to apply profile: %w", err)
}
}
b.Env.InstallConfig = b.icg.GetInstallConfig()
return nil
}
func (b *GCPBootstrapper) EnsureSecrets() error {
if b.fw.Exists(b.Env.SecretsFilePath) {
err := b.icg.LoadVaultFromFile(b.Env.SecretsFilePath)
if err != nil {
return fmt.Errorf("failed to load vault file: %w", err)
}
err = b.icg.MergeVaultIntoConfig()
if err != nil {
return fmt.Errorf("failed to merge vault into config: %w", err)
}
}
b.Env.Secrets = b.icg.GetVault()
return nil
}
func (b *GCPBootstrapper) EnsureProject() error {
parent := ""
if b.Env.FolderID != "" {
parent = fmt.Sprintf("folders/%s", b.Env.FolderID)
}
existingProject, err := b.GCPClient.GetProjectByName(b.Env.FolderID, b.Env.ProjectName)
if err == nil {
b.Env.ProjectID = existingProject.ProjectId
b.Env.ProjectName = existingProject.Name
return nil
}
if err.Error() == fmt.Sprintf("project not found: %s", b.Env.ProjectName) {
projectId := b.GCPClient.CreateProjectID(b.Env.ProjectName)
_, err = b.GCPClient.CreateProject(parent, projectId, b.Env.ProjectName)
if err != nil {
return fmt.Errorf("failed to create project: %w", err)
}
b.Env.ProjectID = projectId
return nil
}
return fmt.Errorf("failed to get project: %w", err)
}
func (b *GCPBootstrapper) EnsureBilling() error {
bi, err := b.GCPClient.GetBillingInfo(b.Env.ProjectID)
if err != nil {
return fmt.Errorf("failed to get billing info: %w", err)
}
if bi.BillingEnabled && bi.BillingAccountName == b.Env.BillingAccount {
return nil
}
err = b.GCPClient.EnableBilling(b.Env.ProjectID, b.Env.BillingAccount)
if err != nil {
return fmt.Errorf("failed to enable billing: %w", err)
}
return nil
}
func (b *GCPBootstrapper) EnsureAPIsEnabled() error {
apis := []string{
"compute.googleapis.com",
"serviceusage.googleapis.com",
"artifactregistry.googleapis.com",
"dns.googleapis.com",
}
err := b.GCPClient.EnableAPIs(b.Env.ProjectID, apis)
if err != nil {
return fmt.Errorf("failed to enable APIs: %w", err)
}
return nil
}
func (b *GCPBootstrapper) EnsureArtifactRegistry() error {
repoName := "codesphere-registry"
repo, err := b.GCPClient.GetArtifactRegistry(b.Env.ProjectID, b.Env.Region, repoName)
if err == nil && repo != nil {
b.Env.InstallConfig.Registry.Server = repo.GetRegistryUri()
return nil
}
repo, err = b.GCPClient.CreateArtifactRegistry(b.Env.ProjectID, b.Env.Region, repoName)
if err != nil || repo == nil {
return fmt.Errorf("failed to create artifact registry: %w, repo: %v", err, repo)
}
return nil
}
func (b *GCPBootstrapper) EnsureServiceAccounts() error {
_, _, err := b.GCPClient.CreateServiceAccount(b.Env.ProjectID, "cloud-controller", "cloud-controller")
if err != nil {
return err
}
if b.Env.RegistryType == RegistryTypeArtifactRegistry {
sa, newSa, err := b.GCPClient.CreateServiceAccount(b.Env.ProjectID, "artifact-registry-writer", "artifact-registry-writer")
if err != nil {
return err
}
if !newSa && b.Env.InstallConfig.Registry.Password != "" {
return nil
}
for retries := range 5 {
privateKey, err := b.GCPClient.CreateServiceAccountKey(b.Env.ProjectID, sa)
if err != nil && status.Code(err) != codes.AlreadyExists {
if retries > 3 {
return fmt.Errorf("failed to create service account key: %w", err)
}
b.stlog.LogRetry()
time.Sleep(5 * time.Second)
continue
}
b.Env.InstallConfig.Registry.Password = string(privateKey)
b.Env.InstallConfig.Registry.Username = "_json_key_base64"
break
}
}
return nil
}
func (b *GCPBootstrapper) EnsureIAMRoles() error {
err := b.ensureIAMRoleWithRetry(b.Env.ProjectID, "cloud-controller", b.Env.ProjectID, []string{"roles/compute.admin"})
if err != nil {
return err
}
err = b.ensureDnsPermissions()
if err != nil {
return err
}
if b.Env.RegistryType != RegistryTypeArtifactRegistry {
return nil
}
err = b.ensureIAMRoleWithRetry(b.Env.ProjectID, "artifact-registry-writer", b.Env.ProjectID, []string{"roles/artifactregistry.writer"})
return err
}
func (b *GCPBootstrapper) ensureIAMRoleWithRetry(projectID string, serviceAccount string, serviceAccountProjectID string, roles []string) error {
var err error
for retries := range 5 {
err = b.GCPClient.AssignIAMRole(projectID, serviceAccount, serviceAccountProjectID, roles)
if err == nil {
return nil
}
if retries < 4 {
b.stlog.LogRetry()
time.Sleep(5 * time.Second)
}
}
return fmt.Errorf("failed to assign roles %v to service account %s: %w", roles, serviceAccount, err)
}
func (b *GCPBootstrapper) ensureDnsPermissions() error {
dnsProject := b.Env.DNSProjectID
if b.Env.DNSProjectID == "" {
dnsProject = b.Env.ProjectID
}
err := b.ensureIAMRoleWithRetry(dnsProject, "cloud-controller", b.Env.ProjectID, []string{"roles/dns.admin"})
if err != nil {
return err
}
return nil
}
func (b *GCPBootstrapper) EnsureVPC() error {
networkName := fmt.Sprintf("%s-vpc", b.Env.ProjectID)
subnetName := fmt.Sprintf("%s-%s-subnet", b.Env.ProjectID, b.Env.Region)
routerName := fmt.Sprintf("%s-router", b.Env.ProjectID)
natName := fmt.Sprintf("%s-nat-gateway", b.Env.ProjectID)
// Create VPC
err := b.GCPClient.CreateVPC(b.Env.ProjectID, b.Env.Region, networkName, subnetName, routerName, natName)
if err != nil {
return fmt.Errorf("failed to ensure VPC: %w", err)
}
return nil
}
func (b *GCPBootstrapper) EnsureFirewallRules() error {
networkName := fmt.Sprintf("%s-vpc", b.Env.ProjectID)
// Allow external SSH to Jumpbox
sshRule := &computepb.Firewall{
Name: protoString("allow-ssh-ext"),
Network: protoString(fmt.Sprintf("projects/%s/global/networks/%s", b.Env.ProjectID, networkName)),
Direction: protoString("INGRESS"),
Priority: protoInt32(1000),
Allowed: []*computepb.Allowed{
{
IPProtocol: protoString("tcp"),
Ports: []string{"22"},
},
},
SourceRanges: []string{"0.0.0.0/0"},
TargetTags: []string{"ssh"},
Description: protoString("Allow external SSH to Jumpbox"),
}
err := b.GCPClient.CreateFirewallRule(b.Env.ProjectID, sshRule)
if err != nil {
return fmt.Errorf("failed to create jumpbox ssh firewall rule: %w", err)
}
// Allow all internal traffic
internalRule := &computepb.Firewall{
Name: protoString("allow-internal"),
Network: protoString(fmt.Sprintf("projects/%s/global/networks/%s", b.Env.ProjectID, networkName)),
Direction: protoString("INGRESS"),
Priority: protoInt32(1000),
Allowed: []*computepb.Allowed{
{IPProtocol: protoString("all")},
},
SourceRanges: []string{"10.10.0.0/20"},
Description: protoString("Allow all internal traffic"),
}
err = b.GCPClient.CreateFirewallRule(b.Env.ProjectID, internalRule)
if err != nil {
return fmt.Errorf("failed to create internal firewall rule: %w", err)
}
// Allow all egress
egressRule := &computepb.Firewall{
Name: protoString("allow-all-egress"),
Network: protoString(fmt.Sprintf("projects/%s/global/networks/%s", b.Env.ProjectID, networkName)),
Direction: protoString("EGRESS"),
Priority: protoInt32(1000),
Allowed: []*computepb.Allowed{
{IPProtocol: protoString("all")},
},
DestinationRanges: []string{"0.0.0.0/0"},
Description: protoString("Allow all egress"),
}
err = b.GCPClient.CreateFirewallRule(b.Env.ProjectID, egressRule)
if err != nil {
return fmt.Errorf("failed to create egress firewall rule: %w", err)
}
// Allow ingress for web (HTTP/HTTPS)
webRule := &computepb.Firewall{
Name: protoString("allow-ingress-web"),
Network: protoString(fmt.Sprintf("projects/%s/global/networks/%s", b.Env.ProjectID, networkName)),
Direction: protoString("INGRESS"),
Priority: protoInt32(1000),
Allowed: []*computepb.Allowed{
{IPProtocol: protoString("tcp"), Ports: []string{"80", "443"}},
},
SourceRanges: []string{"0.0.0.0/0"},
Description: protoString("Allow HTTP/HTTPS ingress"),
}
err = b.GCPClient.CreateFirewallRule(b.Env.ProjectID, webRule)
if err != nil {
return fmt.Errorf("failed to create web firewall rule: %w", err)
}
// Allow ingress for PostgreSQL
postgresRule := &computepb.Firewall{
Name: protoString("allow-ingress-postgres"),
Network: protoString(fmt.Sprintf("projects/%s/global/networks/%s", b.Env.ProjectID, networkName)),
Direction: protoString("INGRESS"),
Priority: protoInt32(1000),
Allowed: []*computepb.Allowed{
{IPProtocol: protoString("tcp"), Ports: []string{"5432"}},
},
SourceRanges: []string{"0.0.0.0/0"},
TargetTags: []string{"postgres"},
Description: protoString("Allow external access to PostgreSQL"),
}
err = b.GCPClient.CreateFirewallRule(b.Env.ProjectID, postgresRule)
if err != nil {
return fmt.Errorf("failed to create postgres firewall rule: %w", err)
}
return nil
}
type vmResult struct {
vmType string // jumpbox, postgres, ceph, k0s
name string
externalIP string
internalIP string
}
func (b *GCPBootstrapper) EnsureComputeInstances() error {
projectID := b.Env.ProjectID
region := b.Env.Region
zone := b.Env.Zone
network := fmt.Sprintf("projects/%s/global/networks/%s-vpc", projectID, projectID)
subnetwork := fmt.Sprintf("projects/%s/regions/%s/subnetworks/%s-%s-subnet", projectID, region, projectID, region)
diskType := fmt.Sprintf("projects/%s/zones/%s/diskTypes/pd-ssd", projectID, zone)
// Create VMs in parallel
wg := sync.WaitGroup{}
errCh := make(chan error, len(vmDefs))
resultCh := make(chan vmResult, len(vmDefs))
rootDiskSize := int64(200)
if b.Env.RegistryType == RegistryTypeGitHub {
rootDiskSize = 50
}
for _, vm := range vmDefs {
wg.Add(1)
go func(vm VMDef) {
defer wg.Done()
disks := []*computepb.AttachedDisk{
{
Boot: protoBool(true),
AutoDelete: protoBool(true),
Type: protoString("PERSISTENT"),
InitializeParams: &computepb.AttachedDiskInitializeParams{
DiskType: &diskType,
DiskSizeGb: protoInt64(rootDiskSize),
SourceImage: protoString("projects/ubuntu-os-cloud/global/images/family/ubuntu-2204-lts"),
},
},
}
for _, diskSize := range vm.AdditionalDisks {
disks = append(disks, &computepb.AttachedDisk{
Boot: protoBool(false),
AutoDelete: protoBool(true),
Type: protoString("PERSISTENT"),
InitializeParams: &computepb.AttachedDiskInitializeParams{
DiskSizeGb: protoInt64(diskSize),
DiskType: &diskType,
},
})
}
pubKey, err := b.readSSHKey(b.Env.SSHPublicKeyPath)
if err != nil {
errCh <- fmt.Errorf("failed to read SSH public key: %w", err)
return
}
serviceAccount := fmt.Sprintf("cloud-controller@%s.iam.gserviceaccount.com", projectID)
instance := &computepb.Instance{
Name: protoString(vm.Name),
ServiceAccounts: []*computepb.ServiceAccount{
{
Email: protoString(serviceAccount),
Scopes: []string{"https://www.googleapis.com/auth/cloud-platform"},
},
},
MachineType: protoString(fmt.Sprintf("zones/%s/machineTypes/%s", zone, vm.MachineType)),
Tags: &computepb.Tags{
Items: vm.Tags,
},
Scheduling: &computepb.Scheduling{
Preemptible: &b.Env.Preemptible,
},
NetworkInterfaces: []*computepb.NetworkInterface{
{
Network: protoString(network),
Subnetwork: protoString(subnetwork),
},
},
Disks: disks,
Metadata: &computepb.Metadata{
Items: []*computepb.Items{
{
Key: protoString("ssh-keys"),
Value: protoString(fmt.Sprintf("root:%s\nubuntu:%s", pubKey+"root", pubKey+"ubuntu")),
},
},
},
}
// Configure external IP if needed
if vm.ExternalIP {
instance.NetworkInterfaces[0].AccessConfigs = []*computepb.AccessConfig{
{
Name: protoString("External NAT"),
Type: protoString("ONE_TO_ONE_NAT"),
},
}
}
err = b.GCPClient.CreateInstance(projectID, zone, instance)
if err != nil && !isAlreadyExistsError(err) {
errCh <- fmt.Errorf("failed to create instance %s: %w", vm.Name, err)
return
}
// Find out the IP addresses of the created instance
resp, err := b.GCPClient.GetInstance(projectID, zone, vm.Name)
if err != nil {
errCh <- fmt.Errorf("failed to get instance %s: %w", vm.Name, err)
return
}
externalIP := ""
internalIP := ""
if len(resp.GetNetworkInterfaces()) > 0 {
internalIP = resp.GetNetworkInterfaces()[0].GetNetworkIP()
if len(resp.GetNetworkInterfaces()[0].GetAccessConfigs()) > 0 {
externalIP = resp.GetNetworkInterfaces()[0].GetAccessConfigs()[0].GetNatIP()
}
}
// Send result through channel instead of creating nodes in goroutine
resultCh <- vmResult{
vmType: vm.Tags[0],
name: vm.Name,
externalIP: externalIP,
internalIP: internalIP,
}
}(vm)
}
wg.Wait()
close(errCh)
close(resultCh)
var errs []error
for err := range errCh {
errs = append(errs, err)
}
if len(errs) > 0 {
return fmt.Errorf("error ensuring compute instances: %w", errors.Join(errs...))
}
// Create nodes from results (in main goroutine, not in spawned goroutines)
b.Env.Jumpbox = &node.Node{
NodeClient: b.NodeClient,
FileIO: b.fw,
}
for result := range resultCh {
switch result.vmType {
case "jumpbox":
b.Env.Jumpbox.UpdateNode(result.name, result.externalIP, result.internalIP)
case "postgres":
b.Env.PostgreSQLNode = b.Env.Jumpbox.CreateSubNode(result.name, result.externalIP, result.internalIP)
case "ceph":
node := b.Env.Jumpbox.CreateSubNode(result.name, result.externalIP, result.internalIP)
b.Env.CephNodes = append(b.Env.CephNodes, node)
case "k0s":
node := b.Env.Jumpbox.CreateSubNode(result.name, result.externalIP, result.internalIP)
b.Env.ControlPlaneNodes = append(b.Env.ControlPlaneNodes, node)
}
}
//sort ceph nodes by name to ensure consistent ordering
sort.Slice(b.Env.CephNodes, func(i, j int) bool {
return b.Env.CephNodes[i].GetName() < b.Env.CephNodes[j].GetName()
})
//sort control plane nodes by name to ensure consistent ordering
sort.Slice(b.Env.ControlPlaneNodes, func(i, j int) bool {
return b.Env.ControlPlaneNodes[i].GetName() < b.Env.ControlPlaneNodes[j].GetName()
})
return nil
}
// EnsureGatewayIPAddresses reserves 2 static external IP addresses for the ingress
// controllers of the cluster.
func (b *GCPBootstrapper) EnsureGatewayIPAddresses() error {
var err error
b.Env.GatewayIP, err = b.EnsureExternalIP("gateway")
if err != nil {
return fmt.Errorf("failed to ensure gateway IP: %w", err)
}
b.Env.PublicGatewayIP, err = b.EnsureExternalIP("public-gateway")
if err != nil {
return fmt.Errorf("failed to ensure public gateway IP: %w", err)
}
return nil
}
// EnsureExternalIP ensures that a static external IP address with the given name exists.
func (b *GCPBootstrapper) EnsureExternalIP(name string) (string, error) {
desiredAddress := &computepb.Address{
Name: &name,
AddressType: protoString("EXTERNAL"),
Region: &b.Env.Region,
}
// Figure out if address already exists and get IP
address, err := b.GCPClient.GetAddress(b.Env.ProjectID, b.Env.Region, name)
if err == nil && address != nil {
return address.GetAddress(), nil
}
createdIP, err := b.GCPClient.CreateAddress(b.Env.ProjectID, b.Env.Region, desiredAddress)
if err != nil && !isAlreadyExistsError(err) {
return "", fmt.Errorf("failed to create address %s: %w", name, err)
}
if createdIP != "" {
return createdIP, nil
}
address, err = b.GCPClient.GetAddress(b.Env.ProjectID, b.Env.Region, name)
if err == nil && address != nil {
return address.GetAddress(), nil
}
return "", fmt.Errorf("failed to get address %s after creation", name)
}
func (b *GCPBootstrapper) EnsureRootLoginEnabled() error {
allNodes := []*node.Node{
b.Env.Jumpbox,
}
allNodes = append(allNodes, b.Env.ControlPlaneNodes...)
allNodes = append(allNodes, b.Env.PostgreSQLNode)
allNodes = append(allNodes, b.Env.CephNodes...)
for _, node := range allNodes {
err := b.stlog.Substep(fmt.Sprintf("Ensuring root login enabled on %s", node.GetName()), func() error {
return b.ensureRootLoginEnabledInNode(node)
})
if err != nil {
return err
}
}
return nil
}
func (b *GCPBootstrapper) ensureRootLoginEnabledInNode(node *node.Node) error {
err := node.NodeClient.WaitReady(node, 30*time.Second)
if err != nil {
return fmt.Errorf("timed out waiting for SSH service to start on %s: %w", node.GetName(), err)
}
hasRootLogin := node.HasRootLoginEnabled()
if hasRootLogin {
return nil
}
for i := range 3 {
err := node.EnableRootLogin()
if err == nil {
break
}
if i == 2 {
return fmt.Errorf("failed to enable root login on %s: %w", node.GetName(), err)
}
b.stlog.LogRetry()
time.Sleep(10 * time.Second)
}
return nil
}
func (b *GCPBootstrapper) EnsureJumpboxConfigured() error {
if !b.Env.Jumpbox.HasAcceptEnvConfigured() {
err := b.Env.Jumpbox.ConfigureAcceptEnv()
if err != nil {
return fmt.Errorf("failed to configure AcceptEnv on jumpbox: %w", err)
}
}
hasOms := b.Env.Jumpbox.HasCommand("oms-cli")
if hasOms {
return nil
}
err := b.Env.Jumpbox.InstallOms()
if err != nil {
return fmt.Errorf("failed to install OMS on jumpbox: %w", err)
}
return nil
}
func (b *GCPBootstrapper) EnsureHostsConfigured() error {
allNodes := append(b.Env.ControlPlaneNodes, b.Env.PostgreSQLNode)
allNodes = append(allNodes, b.Env.CephNodes...)
for _, node := range allNodes {
if !node.HasInotifyWatchesConfigured() {
err := node.ConfigureInotifyWatches()
if err != nil {
return fmt.Errorf("failed to configure inotify watches on %s: %w", node.GetName(), err)
}
}
if !node.HasMemoryMapConfigured() {
err := node.ConfigureMemoryMap()
if err != nil {
return fmt.Errorf("failed to configure memory map on %s: %w", node.GetName(), err)
}
}
}
return nil
}
// EnsureLocalContainerRegistry installs a docker registry on the postgres node to speed up image loading time
func (b *GCPBootstrapper) EnsureLocalContainerRegistry() error {
localRegistryServer := b.Env.PostgreSQLNode.GetInternalIP() + ":5000"
// Figure out if registry is already running
b.stlog.Logf("Checking if local container registry is already running on postgres node")
checkCommand := `test "$(podman ps --filter 'name=registry' --format '{{.Names}}' | wc -l)" -eq "1"`
err := b.Env.PostgreSQLNode.RunSSHCommand("root", checkCommand)
if err == nil && b.Env.InstallConfig.Registry != nil && b.Env.InstallConfig.Registry.Server == localRegistryServer &&
b.Env.InstallConfig.Registry.Username != "" && b.Env.InstallConfig.Registry.Password != "" {
b.stlog.Logf("Local container registry already running on postgres node")
return nil
}
b.Env.InstallConfig.Registry.Server = localRegistryServer
b.Env.InstallConfig.Registry.Username = "custom-registry"
b.Env.InstallConfig.Registry.Password = shortuuid.New()
commands := []string{
"apt-get update",
"apt-get install -y podman apache2-utils",
"htpasswd -bBc /root/registry.password " + b.Env.InstallConfig.Registry.Username + " " + b.Env.InstallConfig.Registry.Password,
"openssl req -newkey rsa:4096 -nodes -sha256 -keyout /root/registry.key -x509 -days 365 -out /root/registry.crt -subj \"/C=DE/ST=BW/L=Karlsruhe/O=Codesphere/CN=" + b.Env.PostgreSQLNode.GetInternalIP() + "\" -addext \"subjectAltName = DNS:postgres,IP:" + b.Env.PostgreSQLNode.GetInternalIP() + "\"",
"podman rm -f registry || true",
`podman run -d \
--restart=always --name registry --net=host\
--env REGISTRY_HTTP_ADDR=0.0.0.0:5000 \
--env REGISTRY_AUTH=htpasswd \
--env REGISTRY_AUTH_HTPASSWD_REALM='Registry Realm' \
--env REGISTRY_AUTH_HTPASSWD_PATH=/auth/registry.password \
-v /root/registry.password:/auth/registry.password \
--env REGISTRY_HTTP_TLS_CERTIFICATE=/certs/registry.crt \
--env REGISTRY_HTTP_TLS_KEY=/certs/registry.key \
-v /root/registry.crt:/certs/registry.crt \
-v /root/registry.key:/certs/registry.key \
registry:2`,
`mkdir -p /etc/docker/certs.d/` + b.Env.InstallConfig.Registry.Server,
`cp /root/registry.crt /etc/docker/certs.d/` + b.Env.InstallConfig.Registry.Server + `/ca.crt`,
}
for _, cmd := range commands {
b.stlog.Logf("Running command on postgres node: %s", util.Truncate(cmd, 12))
err := b.Env.PostgreSQLNode.RunSSHCommand("root", cmd)
if err != nil {
return fmt.Errorf("failed to run command on postgres node: %w", err)
}
}
allNodes := append(b.Env.ControlPlaneNodes, b.Env.CephNodes...)
for _, node := range allNodes {
b.stlog.Logf("Configuring node '%s' to trust local registry certificate", node.GetName())
err := b.Env.PostgreSQLNode.RunSSHCommand("root", "scp -o StrictHostKeyChecking=no /root/registry.crt root@"+node.GetInternalIP()+":/usr/local/share/ca-certificates/registry.crt")
if err != nil {
return fmt.Errorf("failed to copy registry certificate to node %s: %w", node.GetInternalIP(), err)
}
err = node.RunSSHCommand("root", "update-ca-certificates")
if err != nil {
return fmt.Errorf("failed to update CA certificates on node %s: %w", node.GetInternalIP(), err)