This repository was archived by the owner on Mar 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
3655 lines (3132 loc) · 103 KB
/
main.go
File metadata and controls
3655 lines (3132 loc) · 103 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
package main
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"embed"
"github.com/manifoldco/promptui"
"golang.org/x/crypto/bcrypt"
"golang.org/x/exp/rand"
)
const (
// ANSI color codes
colorRed = "\033[0;31m"
colorGreen = "\033[0;32m"
colorYellow = "\033[1;33m"
colorNC = "\033[0m"
// API constants
keygenAccountID = "53666519-ebe7-4ca2-9c1a-d026831e4b56"
keygenBaseURL = "https://api.keygen.sh/v1/accounts/" + keygenAccountID
timeFormat = "2006-01-02-15-04-05"
logTimeFormat = "2006/01/02 15:04:05"
// CLI constants
//nolint:unused
cliName = "shapeblock-installer"
//nolint:unused
cliVersion = "1.0.0"
)
//go:embed assets/tekton/*
var tektonAssets embed.FS
var logger *log.Logger
//go:embed assets/dashboards/*
var dashboardAssets embed.FS
//go:embed assets/kpack/*
var kpackAssets embed.FS
//go:embed assets/helm-repos/*
var helmReposAssets embed.FS
//go:embed assets/shapeblock/*
var shapeblockcrdAssets embed.FS
// Add this near the top of the file with other constants
var githubToken string // Will be set during compilation
func initLogger() error {
timestamp := time.Now().Format(timeFormat)
logFile := fmt.Sprintf("install-%s.log", timestamp)
// Check if log file already exists
if _, err := os.Stat(logFile); err == nil {
// File exists, append to it
file, err := os.OpenFile(logFile, os.O_APPEND|os.O_WRONLY, 0666)
if err != nil {
return fmt.Errorf("failed to open existing log file: %v", err)
}
logger = log.New(file, "", 0)
logger.Printf("=== Installation resumed at %s ===", time.Now().Format(logTimeFormat))
return nil
}
// Create new log file
file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return fmt.Errorf("failed to create log file: %v", err)
}
logger = log.New(file, "", 0)
logger.Printf("=== Installation started at %s ===", time.Now().Format(logTimeFormat))
return nil
}
func logMessage(level, msg string) {
timestamp := time.Now().Format(logTimeFormat)
logger.Printf("[%s] %s: %s", timestamp, level, msg)
}
type Config struct {
LicenseKey string
AdminEmail string
AdminPassword string
DomainName string
EnableAutoUpdate bool
AllowRegistrations bool
AdminFirstName string
AdminLastName string
AppName string
}
type BackendConfig struct {
ServiceAccountToken string
PostgresUsername string
PostgresPassword string
PostgresDatabase string
PostgresRootPW string
TFStateUsername string
TFStatePassword string
TFStateDatabase string
LicenseKey string
}
// Create email config struct
type EmailConfig struct {
Host string
Port string
User string
Password string
}
func printStatus(msg string) {
fmt.Printf("%s==>%s %s\n", colorGreen, colorNC, msg)
logMessage("INFO", msg)
}
func printError(msg string) {
fmt.Printf("%sError:%s %s\n", colorRed, colorNC, msg)
logMessage("ERROR", msg)
}
func printWarning(msg string) {
fmt.Printf("%sWarning:%s %s\n", colorYellow, colorNC, msg)
logMessage("WARN", msg)
}
type Spinner struct {
stopChan chan struct{}
message string
}
func NewSpinner(message string) *Spinner {
return &Spinner{
stopChan: make(chan struct{}),
message: message,
}
}
// helper function for slugifying
func slugify(s string) string {
// Convert to lowercase
s = strings.ToLower(s)
// Replace spaces with hyphens
s = strings.ReplaceAll(s, " ", "-")
// Remove special characters
reg := regexp.MustCompile("[^a-z0-9-]")
s = reg.ReplaceAllString(s, "")
return s
}
func (s *Spinner) Start() {
go func() {
frames := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for i := 0; ; i++ {
select {
case <-s.stopChan:
return
case <-ticker.C:
// Clear the line and move cursor to beginning
fmt.Printf("\r\033[K%s %s", frames[i%len(frames)], s.message)
}
}
}()
}
func (s *Spinner) Stop() {
s.stopChan <- struct{}{}
// Clear the line
fmt.Print("\r\033[K")
}
func runCommand(command string, args ...string) error {
// Append kubeconfig flag for kubectl and helm commands
if command == "kubectl" || command == "helm" {
args = append(args, "--kubeconfig=/etc/rancher/k3s/k3s.yaml")
}
// For reset_admin_password command, print a generic message
if strings.Contains(command, "reset_admin_password") || strings.Contains(strings.Join(args, " "), "reset_admin_password") {
fmt.Println("==> Running: Resetting admin password...")
} else {
// Print the command first
fmt.Printf("==> Running: %s %s\n", command, strings.Join(args, " "))
}
// Start spinner without the command text
spinner := NewSpinner("Processing...")
spinner.Start()
defer spinner.Stop()
// Special handling for k3sup install command
if command == "k3sup" && len(args) > 0 && args[0] == "install" {
// Use shell to preserve single quotes
shellCmd := fmt.Sprintf("%s %s", command, strings.Join(args, " "))
cmd := exec.Command("sh", "-c", shellCmd)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("command \"%s\" failed: %v\nOutput: %s", shellCmd, err, string(output))
}
return nil
}
cmd := exec.Command(command, args...)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("command \"%s\" failed: %v\nOutput: %s", cmd, err, string(output))
}
return nil
}
func checkMemory() error {
printStatus("Checking system memory...")
content, err := os.ReadFile("/proc/meminfo")
if err != nil {
return fmt.Errorf("failed to read meminfo: %v", err)
}
var totalKB int64
for _, line := range strings.Split(string(content), "\n") {
if strings.HasPrefix(line, "MemTotal:") {
fmt.Sscanf(line, "MemTotal: %d kB", &totalKB)
break
}
}
if totalKB < 4000000 {
return fmt.Errorf("insufficient memory. ShapeBlock requires at least 4GB RAM. Current: %.1fGB", float64(totalKB)/1024/1024)
}
return nil
}
func installPrerequisites() error {
printStatus("Installing prerequisites...")
// Install jq
if _, err := exec.LookPath("jq"); err != nil {
printStatus("Installing jq...")
if err := runCommand("sudo", "apt-get", "update"); err != nil {
if err := runCommand("sudo", "yum", "install", "-y", "jq"); err != nil {
return fmt.Errorf("failed to install jq: %v", err)
}
} else {
if err := runCommand("sudo", "apt-get", "install", "-y", "jq"); err != nil {
return fmt.Errorf("failed to install jq: %v", err)
}
}
}
// Install kubectl
if _, err := exec.LookPath("kubectl"); err != nil {
printStatus("Installing kubectl...")
// Get latest stable version
cmd := exec.Command("curl", "-L", "-s", "https://dl.k8s.io/release/stable.txt")
version, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to get kubectl version: %v", err)
}
// Download kubectl
downloadURL := fmt.Sprintf("https://dl.k8s.io/release/%s/bin/linux/amd64/kubectl", strings.TrimSpace(string(version)))
if err := runCommand("curl", "-LO", downloadURL); err != nil {
return fmt.Errorf("failed to download kubectl: %v", err)
}
// Make kubectl executable and move it
if err := runCommand("chmod", "+x", "kubectl"); err != nil {
return fmt.Errorf("failed to make kubectl executable: %v", err)
}
if err := runCommand("sudo", "mv", "kubectl", "/usr/local/bin/"); err != nil {
return fmt.Errorf("failed to move kubectl to /usr/local/bin: %v", err)
}
}
// Install helm
if _, err := exec.LookPath("helm"); err != nil {
printStatus("Installing helm...")
// Download helm install script
if err := runCommand("curl", "-fsSL", "-o", "get_helm.sh",
"https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3"); err != nil {
return fmt.Errorf("failed to download helm script: %v", err)
}
// Make script executable and run it
if err := runCommand("chmod", "+x", "get_helm.sh"); err != nil {
return fmt.Errorf("failed to make helm script executable: %v", err)
}
if err := runCommand("./get_helm.sh"); err != nil {
return fmt.Errorf("failed to install helm: %v", err)
}
// Clean up
if err := os.Remove("get_helm.sh"); err != nil {
printWarning(fmt.Sprintf("Failed to remove helm installation script: %v", err))
}
}
// Install k3sup
if _, err := exec.LookPath("k3sup"); err != nil {
printStatus("Installing k3sup...")
// Download k3sup
if err := runCommand("curl", "-sLS", "https://get.k3sup.dev", "-o", "k3sup_install.sh"); err != nil {
return fmt.Errorf("failed to download k3sup script: %v", err)
}
// Make script executable and run it
if err := runCommand("chmod", "+x", "k3sup_install.sh"); err != nil {
return fmt.Errorf("failed to make k3sup script executable: %v", err)
}
if err := runCommand("./k3sup_install.sh"); err != nil {
return fmt.Errorf("failed to install k3sup: %v", err)
}
// Clean up
if err := os.Remove("k3sup_install.sh"); err != nil {
printWarning(fmt.Sprintf("Failed to remove k3sup installation script: %v", err))
}
}
return nil
}
func addHelmRepo(name, url string) error {
printStatus(fmt.Sprintf("Adding helm repo %s...", name))
// Check if repo already exists
output, _ := exec.Command("helm", "repo", "list").Output()
if strings.Contains(string(output), name) {
printStatus(fmt.Sprintf("Helm repo %s already exists", name))
return nil
}
if err := runCommand("helm", "repo", "add", name, url); err != nil {
return fmt.Errorf("failed to add helm repo %s: %v", name, err)
}
return nil
}
func resourceExists(kind, name, namespace string) bool {
if kind == "node" {
// Nodes do not require a namespace
return runCommand("kubectl", "get", kind) == nil
}
if kind == "clusterissuer" {
// Cluster issuers do not require a namespace
return runCommand("kubectl", "get", kind, name) == nil
}
return runCommand("kubectl", "get", kind, name, "-n", namespace) == nil
}
func installNginxIngress() error {
if resourceExists("deployment", "nginx-ingress", "shapeblock") {
printStatus("Nginx Ingress already installed")
return nil
}
printStatus("Installing Nginx Ingress...")
if err := addHelmRepo("bitnami", "https://charts.bitnami.com/bitnami"); err != nil {
return err
}
if err := runCommand("helm", "repo", "update"); err != nil {
printError(fmt.Sprintf("Failed to update helm repos: %v", err))
return err
}
return runCommand("helm", "upgrade", "--install",
"nginx-ingress", "bitnami/nginx-ingress-controller",
"--version", "11.3.18",
"--namespace", "shapeblock",
"--create-namespace",
"--timeout", "600s")
}
func installCertManager() error {
if resourceExists("deployment", "cert-manager", "cert-manager") {
printStatus("Cert Manager already installed")
return nil
}
printStatus("Installing Cert Manager...")
if err := addHelmRepo("bitnami", "https://charts.bitnami.com/bitnami"); err != nil {
return err
}
return runCommand("helm", "upgrade", "--install",
"cert-manager", "bitnami/cert-manager",
"--version", "1.3.16",
"--namespace", "cert-manager",
"--create-namespace",
"--set", "installCRDs=true",
"--timeout", "600s")
}
func installClusterIssuer(email string) error {
if resourceExists("clusterissuer", "letsencrypt-prod", "") {
printStatus("ClusterIssuer already installed")
return nil
}
printStatus("Installing ClusterIssuer...")
// Wait for cert-manager to be ready
printStatus("Waiting 30 seconds for cert-manager to be ready...")
time.Sleep(30 * time.Second)
// Create cluster issuer YAML with the provided email
issuerYAML := fmt.Sprintf(`apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
email: %s
server: https://acme-v02.api.letsencrypt.org/directory
privateKeySecretRef:
name: letsencrypt-secret-prod
solvers:
- http01:
ingress:
class: nginx`, email)
// Write YAML to temporary file
tmpfile, err := os.CreateTemp("", "cluster-issuer-*.yaml")
if err != nil {
printError(fmt.Sprintf("Failed to create temp file: %v", err))
return err
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.WriteString(issuerYAML); err != nil {
printError(fmt.Sprintf("Failed to write YAML: %v", err))
return err
}
tmpfile.Close()
// Apply the cluster issuer
if err := runCommand("kubectl", "apply", "-f", tmpfile.Name()); err != nil {
printError(fmt.Sprintf("Failed to apply cluster issuer: %v", err))
return err
}
return nil
}
func installTekton() error {
if resourceExists("deployment", "tekton-pipelines-controller", "tekton-pipelines") {
printStatus("Tekton already installed")
return nil
}
// Define versions
tektonVersion := "v0.74.0"
dashboardVersion := "v0.52.0"
printStatus(fmt.Sprintf("Installing Tekton %s and Dashboard %s...", tektonVersion, dashboardVersion))
// Install Tekton Pipelines
releaseURL := fmt.Sprintf("https://storage.googleapis.com/tekton-releases/operator/previous/%s/release.yaml", tektonVersion)
if err := runCommand("kubectl", "apply", "-f", releaseURL); err != nil {
printError(fmt.Sprintf("Failed to install Tekton: %v", err))
return fmt.Errorf("failed to install Tekton: %v", err)
}
// Wait for Tekton to be ready
printStatus("Waiting 60 seconds for Tekton to be ready...")
time.Sleep(60 * time.Second)
// Install Tekton Dashboard
dashboardURL := fmt.Sprintf("https://storage.googleapis.com/tekton-releases/dashboard/previous/%s/release.yaml", dashboardVersion)
if err := runCommand("kubectl", "apply", "-f", dashboardURL); err != nil {
printError(fmt.Sprintf("Failed to install Tekton Dashboard: %v", err))
return fmt.Errorf("failed to install Tekton Dashboard: %v", err)
}
return nil
}
func installTektonResources() error {
printStatus("Installing/Updating Tekton resources...")
resources := []string{
// Tasks
"assets/tekton/tasks/cluster-artefacts-task.yaml",
"assets/tekton/tasks/destroy-cluster-task.yaml",
"assets/tekton/tasks/k3s-remove-node-task.yaml",
"assets/tekton/tasks/k3sup-task.yaml",
"assets/tekton/tasks/kubectl-task.yaml",
"assets/tekton/tasks/terraform-infra-task.yaml",
// Pipelines
"assets/tekton/pipelines/create-cluster-pipeline.yaml",
"assets/tekton/pipelines/scale-down-cluster-pipeline.yaml",
"assets/tekton/pipelines/scale-up-cluster-pipeline.yaml",
"assets/tekton/pipelines/ssh-cluster-pipeline.yaml",
}
for _, resource := range resources {
// Read embedded file
content, err := tektonAssets.ReadFile(resource)
if err != nil {
printError(fmt.Sprintf("Failed to read resource %s: %v", resource, err))
return err
}
// Create temporary file
tmpfile, err := os.CreateTemp("", "tekton-*.yaml")
if err != nil {
printError(fmt.Sprintf("Failed to create temp file: %v", err))
return err
}
defer os.Remove(tmpfile.Name())
// Write content to temp file
if _, err := tmpfile.Write(content); err != nil {
printError(fmt.Sprintf("Failed to write to temp file: %v", err))
return err
}
tmpfile.Close()
// Apply the resource
if err := runCommand("kubectl", "apply", "-f", tmpfile.Name(), "-n", "shapeblock"); err != nil {
printError(fmt.Sprintf("Failed to install Tekton resource %s: %v", resource, err))
return err
}
}
return nil
}
func getServiceAccountToken() (string, error) {
output, err := exec.Command("kubectl", "get", "secret", "tasks-runner-token", "-n", "shapeblock", "-o", "jsonpath={.data.token}", "--kubeconfig=/etc/rancher/k3s/k3s.yaml").Output()
if err != nil {
printError(fmt.Sprintf("Failed to get token: %v", err))
return "", err
}
token, err := base64.StdEncoding.DecodeString(string(output))
if err != nil {
printError(fmt.Sprintf("Failed to decode token: %v", err))
return "", err
}
return string(token), nil
}
func createServiceAccount(backendConfig *BackendConfig) error {
if resourceExists("serviceaccount", "tasks-runner", "shapeblock") {
printStatus("Service account already exists")
// Still get the token as we need it
token, err := getServiceAccountToken()
if err != nil {
return err
}
backendConfig.ServiceAccountToken = token
return nil
}
printStatus("Creating service account and RBAC resources...")
// Role YAML
roleYAML := `apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: sb-tasks
rules:
- apiGroups: ["tekton.dev"]
resources: ["taskruns", "pipelineruns"]
verbs: ["get", "watch", "list", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["configmaps", "secrets", "persistentvolumeclaims", "pods", "pods/log"]
verbs: ["get", "watch", "list"]`
// Service Account YAML
saYAML := `apiVersion: v1
kind: ServiceAccount
metadata:
name: tasks-runner`
// Token Secret YAML
tokenYAML := `apiVersion: v1
kind: Secret
metadata:
name: tasks-runner-token
annotations:
kubernetes.io/service-account.name: tasks-runner
type: kubernetes.io/service-account-token`
// Role Binding YAML
bindingYAML := `apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: sb-tasks-runner
subjects:
- kind: ServiceAccount
name: tasks-runner
roleRef:
kind: Role
name: sb-tasks
apiGroup: rbac.authorization.k8s.io`
// Create temporary files and apply each resource
for name, content := range map[string]string{
"role.yaml": roleYAML,
"sa.yaml": saYAML,
"token.yaml": tokenYAML,
"binding.yaml": bindingYAML,
} {
tmpfile, err := os.CreateTemp("", name)
if err != nil {
printError(fmt.Sprintf("Failed to create temp file: %v", err))
return err
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.WriteString(content); err != nil {
printError(fmt.Sprintf("Failed to write YAML: %v", err))
return err
}
tmpfile.Close()
if err := runCommand("kubectl", "apply", "-f", tmpfile.Name(), "-n", "shapeblock", "--kubeconfig=/etc/rancher/k3s/k3s.yaml"); err != nil {
printError(fmt.Sprintf("Failed to apply %s: %v", name, err))
return err
}
}
// Wait for 10 seconds before getting the token
printStatus("Waiting 10 seconds for service account token to be created...")
time.Sleep(10 * time.Second)
// Get and store the token
token, err := getServiceAccountToken()
if err != nil {
return fmt.Errorf("failed to get service account token: %v", err)
}
backendConfig.ServiceAccountToken = token
printStatus("Service account and RBAC resources created successfully")
return nil
}
func getNodeIP() (string, error) {
output, err := exec.Command("hostname", "-I").Output()
if err != nil {
return "", fmt.Errorf("failed to get IP: %v", err)
}
// Get first IP address
ip := strings.Fields(string(output))[0]
return ip, nil
}
func generatePassword() string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
length := 16
b := make([]byte, length)
for i := range b {
b[i] = charset[rand.Intn(len(charset))]
}
return string(b)
}
func installPostgres(backendConfig *BackendConfig) error {
printStatus("Installing PostgreSQL...")
if resourceExists("statefulset", "db-postgresql", "shapeblock") {
printStatus("PostgreSQL already installed")
return nil
}
if err := addHelmRepo("bitnami", "https://charts.bitnami.com/bitnami"); err != nil {
return err
}
// Generate passwords for both users and root
mainPassword := generatePassword()
tfstatePassword := generatePassword()
rootPW := generatePassword()
// Store credentials in backend config
backendConfig.PostgresUsername = "shapeblock"
backendConfig.PostgresDatabase = "shapeblock"
backendConfig.PostgresPassword = mainPassword
backendConfig.PostgresRootPW = rootPW
backendConfig.TFStateUsername = "tfstate"
backendConfig.TFStateDatabase = "tfstate"
backendConfig.TFStatePassword = tfstatePassword
// Log the credentials for debugging
logMessage("INFO", fmt.Sprintf("PostgreSQL main credentials - username: %s, database: %s, password: %s",
backendConfig.PostgresUsername, backendConfig.PostgresDatabase, mainPassword))
logMessage("INFO", fmt.Sprintf("PostgreSQL tfstate credentials - username: %s, database: %s, password: %s",
backendConfig.TFStateUsername, backendConfig.TFStateDatabase, tfstatePassword))
// Create values with initialization scripts for both databases
values := fmt.Sprintf(`
auth:
database: %s
username: %s
password: %s
postgresPassword: %s
architecture: standalone
primary:
persistence:
size: 2Gi
initdb:
scripts:
init_db_and_users.sql: |
-- Create tfstate user and database
CREATE USER %s WITH PASSWORD '%s';
CREATE DATABASE %s OWNER %s;
GRANT ALL PRIVILEGES ON DATABASE %s TO %s;
-- Create shapeblock user and database
CREATE USER %s WITH PASSWORD '%s';
CREATE DATABASE %s OWNER %s;
GRANT ALL PRIVILEGES ON DATABASE %s TO %s;
tls:
enabled: true
autoGenerated: true`,
backendConfig.PostgresDatabase, // Initial database
backendConfig.PostgresUsername, // Initial user
backendConfig.PostgresPassword,
backendConfig.PostgresRootPW,
// tfstate database and user creation
backendConfig.TFStateUsername,
backendConfig.TFStatePassword,
backendConfig.TFStateDatabase,
backendConfig.TFStateUsername,
backendConfig.TFStateDatabase,
backendConfig.TFStateUsername,
// shapeblock database and user creation
backendConfig.PostgresUsername,
backendConfig.PostgresPassword,
backendConfig.PostgresDatabase,
backendConfig.PostgresUsername,
backendConfig.PostgresDatabase,
backendConfig.PostgresUsername)
// Write values to temporary file
tmpfile, err := os.CreateTemp("", "postgres-values-*.yaml")
if err != nil {
printError(fmt.Sprintf("Failed to create temp file: %v", err))
return err
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.WriteString(values); err != nil {
printError(fmt.Sprintf("Failed to write values: %v", err))
return err
}
tmpfile.Close()
// Install PostgreSQL
if err := runCommand("helm", "upgrade", "--install",
"db", "bitnami/postgresql",
"--version", "16.2.3",
"--namespace", "shapeblock",
"--values", tmpfile.Name(),
"--timeout", "600s"); err != nil {
printError(fmt.Sprintf("Failed to install PostgreSQL: %v", err))
return err
}
printStatus("PostgreSQL installed successfully with both databases")
return nil
}
func createTerraformSecret(backendConfig *BackendConfig) error {
printStatus("Creating Terraform credentials secret...")
if resourceExists("secret", "terraform-creds", "shapeblock") {
printStatus("Terraform credentials secret already exists")
return nil
}
// Create connection string
connStr := fmt.Sprintf("postgres://%s:%s@db-postgresql/%s",
backendConfig.TFStateUsername,
backendConfig.TFStatePassword,
backendConfig.TFStateDatabase)
// Create secret
if err := runCommand("kubectl", "create", "secret", "generic",
"terraform-creds",
fmt.Sprintf("--from-literal=PG_CONN_STR=%s", connStr),
"-n", "shapeblock", "--kubeconfig=/etc/rancher/k3s/k3s.yaml"); err != nil {
printError(fmt.Sprintf("Failed to create Terraform credentials secret: %v", err))
return err
}
printStatus("Terraform credentials secret created successfully")
return nil
}
func installRedis() error {
printStatus("Installing Redis...")
if resourceExists("statefulset", "redis-master", "shapeblock") {
printStatus("Redis already installed")
return nil
}
if err := addHelmRepo("bitnami", "https://charts.bitnami.com/bitnami"); err != nil {
return err
}
// Create values.yaml
values := `
architecture: standalone
auth:
enabled: false
master:
persistence:
size: 2Gi`
// Write values to temporary file
tmpfile, err := os.CreateTemp("", "redis-values-*.yaml")
if err != nil {
printError(fmt.Sprintf("Failed to create temp file: %v", err))
return err
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.WriteString(values); err != nil {
printError(fmt.Sprintf("Failed to write values: %v", err))
return err
}
tmpfile.Close()
// Install Redis
if err := runCommand("helm", "upgrade", "--install",
"redis", "bitnami/redis",
"--version", "18.4.0",
"--namespace", "shapeblock",
"--values", tmpfile.Name(),
"--timeout", "600s"); err != nil {
printError(fmt.Sprintf("Failed to install Redis: %v", err))
return err
}
printStatus("Redis installed successfully")
return nil
}
func install(config *Config, backendConfig *BackendConfig) error {
// Check if Kubernetes is already installed
printStatus("Checking if Kubernetes is already installed...")
if !resourceExists("node", "", "") {
printStatus("Kubernetes not found. Installing Kubernetes using k3sup...")
// Generate SSH keys
_, publicKey, err := generateSSHKeys()
if err != nil {
return fmt.Errorf("failed to generate SSH keys: %v", err)
}
// Add public key to authorized_keys
sshDir := filepath.Join(os.Getenv("HOME"), ".ssh")
if err := os.MkdirAll(sshDir, 0700); err != nil {
return fmt.Errorf("failed to create .ssh directory: %v", err)
}
authorizedKeysPath := filepath.Join(sshDir, "authorized_keys")
f, err := os.OpenFile(authorizedKeysPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("failed to open authorized_keys: %v", err)
}
if _, err := f.WriteString(publicKey + "\n"); err != nil {
f.Close()
return fmt.Errorf("failed to write public key: %v", err)
}
f.Close()
// Get current user and IP
currentUser := os.Getenv("USER")
if currentUser == "" {
currentUser = "root"
}
ip, err := getNodeIP()
if err != nil {
return fmt.Errorf("failed to get node IP: %v", err)
}
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %v", err)
}
// Install k3s using k3sup with SSH
if err := runCommand("k3sup", "install",
"--ip", ip,
"--user", currentUser,
"--ssh-key", filepath.Join(homeDir, "sb"),
"--k3s-extra-args", "'--disable traefik'"); err != nil {
return fmt.Errorf("failed to install Kubernetes: %v", err)
}
// Wait a moment for the cluster to initialize
printStatus("Waiting for Kubernetes cluster to initialize...")
time.Sleep(60 * time.Second)
} else {
printStatus("Kubernetes is already installed")
}
if err := installPrerequisites(); err != nil {
return err
}
if err := installNginxIngress(); err != nil {
return fmt.Errorf("failed to install nginx ingress: %v", err)
}
if err := installCertManager(); err != nil {
return fmt.Errorf("failed to install cert-manager: %v", err)
}
if err := installClusterIssuer(config.AdminEmail); err != nil {
return fmt.Errorf("failed to install cluster issuer: %v", err)
}
if err := installTekton(); err != nil {
return fmt.Errorf("failed to install Tekton: %v", err)
}
if err := installTektonResources(); err != nil {
return fmt.Errorf("failed to install Tekton resources: %v", err)
}
if err := createServiceAccount(backendConfig); err != nil {
return fmt.Errorf("failed to create service account: %v", err)
}
// Install PostgreSQL instance
if err := installPostgres(backendConfig); err != nil {
return fmt.Errorf("failed to install PostgreSQL: %v", err)
}
// Create Terraform credentials secret
if err := createTerraformSecret(backendConfig); err != nil {
return fmt.Errorf("failed to create Terraform credentials secret: %v", err)
}
if err := installRedis(); err != nil {
return fmt.Errorf("failed to install Redis: %v", err)
}
if err := installBackend(config, backendConfig); err != nil {
return fmt.Errorf("failed to install shapeblock backend: %v", err)
}
// Add bootstrap step
if err := bootstrapBackend(config, backendConfig); err != nil {
return fmt.Errorf("failed to bootstrap backend: %v", err)
}
if err := installFrontend(config); err != nil {
return fmt.Errorf("failed to install frontend: %v", err)
}
// Install Docker Registry
if err := installRegistry(config); err != nil {
return fmt.Errorf("failed to install registry: %v", err)
}
// Install kpack
if err := installKpack(); err != nil {
return fmt.Errorf("failed to install kpack: %v", err)
}
// Install kpack resources
if err := installKpackResources(); err != nil {
return fmt.Errorf("failed to install kpack resources: %v", err)