-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathMagefile.go
More file actions
2021 lines (1672 loc) · 55.3 KB
/
Magefile.go
File metadata and controls
2021 lines (1672 loc) · 55.3 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
// SPDX-FileCopyrightText: 2025 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
package mage
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"text/template"
"time"
"github.com/bitfield/script"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"gopkg.in/yaml.v3"
)
const (
kindOrchClusterName = "kind" // TODO: Keep for backwards compatibility until all Mage is moved to root
deploymentTimeoutEnv = "DEPLOYMENT_TIMEOUT"
defaultDeploymentTimeout = "1200s" // timeout must be a valid string
argoVersion = "8.2.7"
argoRetryCount = 30
argoRetryInterval = 30
giteaVersion = "10.6.0"
)
var (
edgeClusterName = "demo-cluster"
defaultClusterDomain = "kind.internal"
)
var argoNamespaces = []string{
"dev",
"argocd",
"gitea",
"orch-platform", // used when creating a secret for gitea
"orch-sre", // used when creating a secret for kindAll
"orch-harbor", // used when creating a secret for integration
"orch-infra", // used when creating a secret for mailpit
}
var EMFRepos = []string{
"https://github.com/open-edge-platform/edge-manageability-framework",
}
// Public GitHub repositories can be useful for specific development workflows.
var githubRepos = []string{
"https://github.com/open-edge-platform/edge-manageability-framework",
"https://github.com/open-edge-platform/orch-utils",
}
var globalAsdf = []string{
"kubectl",
}
// autoCert is a package-level variable initialized during startup.
var autoCert = func() bool {
value := os.Getenv("AUTO_CERT")
return value == "1"
}()
var coderEnv = func() bool {
value, exists := os.LookupEnv("CODER_WORKSPACE_NAME")
return exists && value != ""
}()
// serviceDomain is a package-level variable initialized during startup.
var serviceDomain = func() string {
sd := os.Getenv("E2E_SVC_DOMAIN")
// retrieve svcdomain from configmap
// if it does not exist there, then use the defaultservicedomain
if sd == "" {
domain, err := LookupOrchestratorDomain()
if err != nil {
// Could not locate in the configmap, also attempt to build the domain if this is an autocert (coder) deployment
if autoCert && coderEnv {
// retrieve the subdomain name
subDomain := os.Getenv("ORCH_DOMAIN")
if subDomain == "" {
fmt.Printf("error retrieving the orchestrator domain from autocert aws lookup\n")
return defaultClusterDomain
}
return subDomain
}
return defaultClusterDomain
}
if len(domain) > 0 {
sd = domain
} else {
sd = defaultClusterDomain
}
}
return sd
}()
func updateEdgeName() {
name, exists := os.LookupEnv("EDGE_CLUSTER_NAME")
if exists {
edgeClusterName = name
}
}
// Install ASDF plugins.
func AsdfPlugins() error {
// Check if ASDF is installed
if _, err := exec.LookPath("asdf"); err != nil {
return fmt.Errorf("asdf is not installed: %w", err)
}
// Install remaining tools
if _, err := script.File(".tool-versions").Column(1).
MatchRegexp(regexp.MustCompile(`^[^\#]`)).ExecForEach("asdf plugin add {{.}}").Stdout(); err != nil {
return fmt.Errorf("error running 'asdf plugin add': %w", err)
}
if _, err := script.File(".tool-versions").
MatchRegexp(regexp.MustCompile(`^[^\#]\S+\s+\S+$`)).ExecForEach("asdf install {{.}}").Stdout(); err != nil {
return fmt.Errorf("error running 'asdf install': %w", err)
}
if _, err := script.Exec("asdf current").Stdout(); err != nil {
return fmt.Errorf("error running 'asdf current': %w", err)
}
// Set plugins listed in globalAsdf as global
for _, name := range globalAsdf {
if _, err := script.File(".tool-versions").MatchRegexp(regexp.MustCompile(name)).Column(2).
ExecForEach(fmt.Sprintf("asdf set --home %s {{.}}", name)).Stdout(); err != nil {
return fmt.Errorf("error setting plugins listed in globalAsdf as global: %w", err)
}
}
fmt.Printf("asdf plugins updated🔌\n")
return nil
}
// Cleans up the local environment by removing all generated files and directories 🧹
func Clean(ctx context.Context) error {
for _, path := range []string{
// Keep list sorted in ascending order for easier maintenance
"cloudFull_edge-manageability-framework_*.tgz",
"COMMIT_ID",
"onpremFull_edge-manageability-framework_*.tgz",
"edge-manageability-framework",
} {
matches, err := filepath.Glob(path)
if err != nil {
return fmt.Errorf("failed to glob %s: %w", path, err)
}
for _, match := range matches {
fmt.Printf("Cleaning path: %s\n", match)
if err := os.RemoveAll(match); err != nil {
return fmt.Errorf("failed to remove %s: %w", match, err)
}
}
}
fmt.Println("Cleanup completed successfully 🧹")
return nil
}
// Namespace contains Undeploy targets.
type Undeploy mg.Namespace
// Undeploy Deletes all local KinD clusters.
func (Undeploy) Kind() error {
clusters, err := sh.Output("kind", "get", "clusters")
if err != nil {
return err
}
// No kind clusters found.
if clusters == "" {
return nil
}
clusterList := strings.Split(clusters, "\n")
for _, clusterName := range clusterList {
if err := sh.RunV("kind", "-v", strconv.Itoa(verboseLevel), "delete", "cluster",
"--name", clusterName); err != nil {
return err
}
}
return nil
}
// Deletes ENiC and cluster, input required: mage undeploy:edgeCluster <org-name> <project-name>
func (Undeploy) EdgeCluster(orgName, projectName string) error {
updateEdgeName()
ctx := context.TODO()
if err := (TenantUtils{}).GetProject(ctx, orgName, projectName); err != nil {
return fmt.Errorf("failed to get project %s: %w", projectName, err)
}
edgeInfraUser, _, err := getEdgeAndApiUsers(ctx, orgName)
if err != nil {
return fmt.Errorf("failed to get edge user: %w", err)
}
edgeMgrUser = edgeInfraUser
project = projectName
projectId, err := projectId(projectName)
if err != nil {
return fmt.Errorf("failed to get project id: %w", err)
}
fleetNamespace = projectId
if err := cleanUpEnic(); err != nil {
return fmt.Errorf("failed to cleanup enic: %w", err)
}
fmt.Println("\nENiC cluster deleted 😊")
return nil
}
type Deps mg.Namespace
func (Deps) Terraform() error {
terraformDir := "terraform"
dirs, err := os.ReadDir(terraformDir)
if err != nil {
return fmt.Errorf("failed to read terraform directory: %w", err)
}
for _, dir := range dirs {
if dir.IsDir() {
if err := sh.RunV(
"terraform",
"-chdir="+filepath.Join(terraformDir, dir.Name()),
"init",
"--upgrade",
); err != nil {
return fmt.Errorf("terraform init failed for directory %s: %w", dir.Name(), err)
}
}
}
return nil
}
// Checks if running on Ubuntu Linux.
func (Deps) EnsureUbuntu() error {
if runtime.GOOS != "linux" {
return fmt.Errorf("%s OS not supported. Submit a PR? 🤔", runtime.GOOS)
}
contents, err := os.ReadFile("/etc/issue")
if err != nil {
return fmt.Errorf("read system identification file: %w", err)
}
if !bytes.Contains(contents, []byte("Ubuntu")) {
return fmt.Errorf("ubuntu is the only supported distro at this time. Submit a PR? 🤔")
}
fmt.Println("Running on Ubuntu 🐧")
return nil
}
// Installs FPM (Effing Package Management) for creating OS packages.
func (d Deps) FPM(ctx context.Context) error {
mg.SerialCtxDeps(
ctx,
d.EnsureUbuntu,
)
// Check if FPM is already installed and its version is 1.16.0
if output, err := exec.Command("fpm", "--version").Output(); err == nil {
if strings.TrimSpace(string(output)) == "1.16.0" {
fmt.Println("FPM version 1.16.0 is already installed ✅")
return nil
}
fmt.Println("A different version of FPM is installed. Updating to version 1.16.0...")
}
// Check if Ruby is already installed
if _, err := exec.LookPath("ruby"); err == nil {
fmt.Println("Ruby is already installed ✅")
} else {
// Ruby is just needed for this target and is not necessarily needed for general development.
if err := sh.RunV("sudo", "apt-get", "update", "--assume-yes"); err != nil {
return fmt.Errorf("failed to update apt-get: %w", err)
}
if err := sh.RunV("sudo", "apt-get", "install", "--assume-yes", "ruby-full"); err != nil {
return fmt.Errorf("failed to install ruby: %w", err)
}
}
// Install or update FPM to version 1.16.0
return sh.RunV("sudo", "gem", "install", "fpm", "--version", "1.16.0")
}
// Installs libvirt dependencies. This is required for running an Orchestrator and Edge Node using KVM. Only Ubuntu
// 22.04 is supported.
func (d Deps) Libvirt(ctx context.Context) error {
mg.CtxDeps(ctx, d.EnsureUbuntu)
return sh.RunV(filepath.Join("tools", "setup-libvirt.bash"))
}
// Destroys the edge network deployed locally.
func (u Undeploy) EdgeNetwork(ctx context.Context) error {
mg.SerialCtxDeps(
ctx,
Deps{}.EnsureUbuntu,
Deps{}.Terraform,
u.EdgeNetworkDNS,
)
return sh.RunV(
"terraform",
"-chdir="+filepath.Join("terraform", "edge-network"),
"destroy",
"-var=dns_resolvers=[]",
"--auto-approve",
)
}
// Removes the edge network DNS resolver as the default resolver on the host machine.
func (Undeploy) EdgeNetworkDNS(ctx context.Context) error {
mg.CtxDeps(
ctx,
Deps{}.EnsureUbuntu,
)
if _, err := os.Stat("/etc/systemd/resolved.conf.bak"); err != nil {
fmt.Printf("Backup of resolved.conf not found. Was `mage deploy:edgeNetworkDNS` ever run?")
return nil
}
if err := sh.RunV("sudo", "mv", "/etc/systemd/resolved.conf.bak", "/etc/systemd/resolved.conf"); err != nil {
return fmt.Errorf("failed to restore backup of resolved.conf: %w", err)
}
if err := sh.RunV("sudo", "systemctl", "daemon-reload"); err != nil {
return fmt.Errorf("failed to reload systemd daemon: %w", err)
}
if err := sh.RunV("sudo", "systemctl", "restart", "systemd-resolved"); err != nil {
return fmt.Errorf("failed to restart systemd-resolved: %w", err)
}
fmt.Println("Edge network DNS integration removed successfully 🧑🔧")
return nil
}
// Destroys the edge storage pool deployed locally.
func (Undeploy) EdgeStoragePool(ctx context.Context) error {
mg.SerialCtxDeps(
ctx,
Deps{}.EnsureUbuntu,
Deps{}.Terraform,
)
return sh.RunV(
"terraform",
"-chdir="+filepath.Join("terraform", "edge-storage-pool"),
"destroy",
"--auto-approve",
)
}
// Destroys the on-premise Orchestrator, edge network, and edge storage pool deployed locally.
func (u Undeploy) OnPrem(ctx context.Context) error {
mg.SerialCtxDeps(
ctx,
Deps{}.EnsureUbuntu,
Deps{}.Terraform,
)
// Check if TF_VAR_FILE is defined, if not, set it to a default value
if os.Getenv("TF_VAR_FILE") == "" {
if err := os.Setenv("TF_VAR_FILE", "terraform.tfvars"); err != nil {
return fmt.Errorf("failed to set TF_VAR_FILE: %w", err)
}
}
tfvarsFile := os.Getenv("TF_VAR_FILE")
if err := sh.RunV(
"terraform",
"-chdir="+filepath.Join("terraform", "orchestrator"),
"destroy",
"--var-file="+tfvarsFile,
fmt.Sprintf("--parallelism=%d", runtime.NumCPU()), // Set parallelism to the number of CPUs on the machine
"--auto-approve",
); err != nil {
return fmt.Errorf("terraform destroy failed: %w", err)
}
// Sometimes the destroy command fails to remove the VM,
// so we need to undefine it manually
// Check if a VM named "orch-tf" still exists
_, err := exec.Command("sudo", "virsh", "domuuid", "orch-tf").Output()
if err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
fmt.Printf("no VM named 'orch-tf' found, nothing to destroy.\n")
}
} else {
// Try to destroy the VM if it's running
if err := sh.RunV("sudo", "virsh", "destroy", "orch-tf"); err != nil {
fmt.Printf("virsh destroy failed (may not be running): %v\n", err)
}
// Undefine and remove all storage
if err := sh.RunV("sudo", "virsh", "undefine", "orch-tf", "--remove-all-storage"); err != nil {
fmt.Printf("virsh undefine failed: %v\n", err)
}
}
mg.CtxDeps(
ctx,
u.EdgeNetwork,
u.EdgeStoragePool,
)
fmt.Println("Orchestrator deployment destroyed 🗑️")
return nil
}
// Destroys any local Virtual Edge Nodes.
func (Undeploy) VEN(ctx context.Context, serialNumber string) error {
mg.CtxDeps(
ctx,
Deps{}.EnsureUbuntu,
)
if err := sh.RunV("sudo", "virsh", "destroy", fmt.Sprintf("edge-node-%s", serialNumber)); err != nil {
fmt.Printf("virsh undefine failed: %v\n", err)
}
if err := sh.RunV("sudo", "virsh", "undefine", fmt.Sprintf("edge-node-%s", serialNumber), "--nvram"); err != nil {
fmt.Printf("virsh undefine failed: %v\n", err)
}
return nil
}
type Deploy mg.Namespace
// TBD: Replace with default and custom driven by external config / config UI
// Deploy kind cluster, Argo CD, and all Orchestrator services.
func (d Deploy) KindAll() error {
return d.all("dev")
}
// Deploy kind cluster, Argo CD, and all Orchestrator services except o11y and kyverno.
func (d Deploy) KindMinimal() error {
return d.all("dev-minimal")
}
// Deploy kind cluster, Argo CD, and Orchestrator services with customized settings.
func (d Deploy) KindCustom() error {
fmt.Println("Interactive cluster configuration is not currently supported.")
fmt.Println("Use config:usePreset with a manually generated preset file until this functionality is supported.")
return fmt.Errorf("unsupported")
}
// Deploy kind cluster, Argo CD, and Orchestrator services with preset settings.
func (d Deploy) KindPreset(clusterPreset string) error {
targetEnv, err := Config{}.usePreset(clusterPreset)
if err != nil {
return fmt.Errorf("failed to apply cluster preset: %w", err)
}
return d.all(targetEnv)
}
// Deploy kind cluster and Argo CD.
func (d Deploy) Kind(targetEnv string) error {
if err := d.kind(targetEnv); err != nil {
return err
}
return d.preOrchDeploy(targetEnv)
}
func (d Deploy) Gitea(targetEnv string) error {
err := (Config{}).renderTargetConfigTemplate(targetEnv, "orch-configs/templates/bootstrap/gitea.tpl", ".deploy/bootstrap/gitea.yaml")
if err != nil {
return fmt.Errorf("failed to render gitea configuration: %w", err)
}
giteaBootstrapValues := []string{".deploy/bootstrap/gitea.yaml"}
return d.gitea(giteaBootstrapValues, targetEnv)
}
func (d Deploy) StartGiteaProxy() error {
err := d.StopGiteaProxy()
if err != nil {
return fmt.Errorf("failed to stop Gitea proxy: %w", err)
}
portForwardCmd, err := d.startGiteaPortForward()
if err != nil {
return fmt.Errorf("failed to start Gitea port forwarding: %w", err)
}
// Save the PID to a .gitea-proxy file
pid := portForwardCmd.Process.Pid
pidFile := ".gitea-proxy"
if err := os.WriteFile(pidFile, []byte(strconv.Itoa(pid)), 0o644); err != nil {
return fmt.Errorf("failed to write PID to %s: %w", pidFile, err)
}
fmt.Printf("Gitea proxy PID saved to %s\n", pidFile)
return nil
}
func (d Deploy) StopAllKubectlProxies() error {
// List all kubectl port-forward processes
cmd := exec.Command("pgrep", "-af", "kubectl port-forward")
output, err := cmd.Output()
if err != nil {
fmt.Printf("failed to list kubectl port-forward processes: %v\n", err)
return nil
}
fmt.Println("kubectl port-forward processes:")
fmt.Println(string(output))
// Stop all kubectl port-forward processes
cmd = exec.Command("pkill", "-f", "kubectl port-forward")
if err := cmd.Run(); err != nil {
fmt.Printf("failed to stop kubectl port-forward processes: %v", err)
}
cmd = exec.Command("pgrep", "-af", "kubectl port-forward")
output, err = cmd.Output()
if err != nil {
fmt.Printf("failed to list kubectl port-forward processes: %v\n", err)
return nil
}
fmt.Println("Any remaining kubectl port-forward processes after pkill:")
fmt.Println(string(output))
return nil
}
func (d Deploy) StopGiteaProxy() error {
pidFile := ".gitea-proxy"
if _, err := os.Stat(pidFile); os.IsNotExist(err) {
fmt.Println("Gitea proxy PID file not found, nothing to stop")
return nil
}
defer func() {
if err := os.Remove(pidFile); err != nil {
fmt.Printf("failed to remove PID file %s: %v\n", pidFile, err)
}
}()
pidBytes, err := os.ReadFile(pidFile)
if err != nil {
fmt.Printf("failed to read PID file %s\n", pidFile)
return nil
}
pid, err := strconv.Atoi(strings.TrimSpace(string(pidBytes)))
if err != nil {
fmt.Printf("failed to parse PID from %s\n", pidFile)
return nil
}
portForwardCmd := exec.Command("kill", "-9", strconv.Itoa(pid))
if err := portForwardCmd.Run(); err != nil {
fmt.Printf("failed to stop Gitea port forwarding process: %d", pid)
} else {
fmt.Printf("Gitea proxy with PID %d stopped\n", pid)
}
return nil
}
// Deploy Argo CD in kind cluster.
func (d Deploy) Argocd(targetEnv string) error {
err := (Config{}).renderTargetConfigTemplate(targetEnv, "orch-configs/templates/bootstrap/argocd.tpl", ".deploy/bootstrap/argocd.yaml")
if err != nil {
return fmt.Errorf("failed to render argocd proxy configuration: %w", err)
}
// Set argoBootstrapValues to the default set for a kind dev environment
argoBootstrapValues := []string{
".deploy/bootstrap/argocd.yaml",
}
return d.argocd(argoBootstrapValues, targetEnv)
}
// Deploy the edge network locally.
func (d Deploy) EdgeNetwork(ctx context.Context) error {
mg.CtxDeps(
ctx,
Deps{}.EnsureUbuntu,
Deps{}.Terraform,
)
dnsResolversBytes, err := exec.Command("resolvectl", "dns").Output()
if err != nil {
return fmt.Errorf("failed to get DNS resolvers: %w", err)
}
dnsResolversOutput := strings.TrimSpace(string(dnsResolversBytes))
// Extract IP addresses from the output. There can be multiple lines, so we split by newline. Each line can have
// multiple IP addresses, so we split by space and parse to determine if it's a valid IP address. Finally, we store
// the valid IP addresses in a set to ensure uniqueness.
dnsResolvers := map[string]struct{}{}
for _, line := range strings.Split(dnsResolversOutput, "\n") {
for _, field := range strings.Fields(line) {
if net.ParseIP(field) != nil {
dnsResolvers[field] = struct{}{}
}
}
}
// Convert the set to a slice of strings that are comma separated and wrapped in double quotes
var resolvers []string
for ip := range dnsResolvers {
resolvers = append(resolvers, fmt.Sprintf("\"%s\"", ip))
}
resolversStr := strings.Join(resolvers, ",")
fmt.Printf("Using DNS resolvers: %s\n", resolversStr)
// Pass parent context to the command to allow for cancellation
cmd := exec.CommandContext(
ctx,
"terraform",
"-chdir="+filepath.Join("terraform", "edge-network"),
"apply",
fmt.Sprintf("-var=dns_resolvers=[%s]", resolversStr),
fmt.Sprintf("--parallelism=%d", runtime.NumCPU()), // Set parallelism to the number of CPUs on the machine
"--auto-approve")
// Stream the output to stdout and stderr
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("terraform apply failed: %w", err)
}
return nil
}
// Sets the edge network DNS resolver as the default resolver on the host machine.
func (d Deploy) EdgeNetworkDNS(ctx context.Context) error {
mg.SerialCtxDeps(
ctx,
Deps{}.EnsureUbuntu,
Undeploy{}.EdgeNetworkDNS,
)
output, err := exec.CommandContext(
ctx,
"terraform",
"-chdir="+filepath.Join("terraform", "edge-network"),
"output",
"-json",
).Output()
if err != nil {
return fmt.Errorf("failed to get terraform output: %w", err)
}
var terraformOutput struct {
NetworkSubnetCIDRs struct {
Value []string `json:"value"`
} `json:"network_subnet_cidrs"`
}
if err := json.Unmarshal(output, &terraformOutput); err != nil {
return fmt.Errorf("failed to unmarshal terraform output: %w", err)
}
if len(terraformOutput.NetworkSubnetCIDRs.Value) == 0 {
return fmt.Errorf("no network subnet CIDRs found in terraform output")
}
ip, _, err := net.ParseCIDR(terraformOutput.NetworkSubnetCIDRs.Value[0])
if err != nil {
return fmt.Errorf("failed to parse CIDR: %w", err)
}
// The bridge IP is the first address in the subnet e.g., if the subnet is 192.168.99.0/24, the bridge IP is
// 192.168.99.1
ipv4 := ip.To4()
if ipv4 == nil {
return fmt.Errorf("IP address is not IPv4: %s", ip)
}
ipv4[3] = 1
bridgeIP := ipv4
fmt.Printf("Using bridge IP: %s\n", bridgeIP.String())
// Check if backup of resolved.conf already exists
if _, err := os.Stat("/etc/systemd/resolved.conf.bak"); err == nil {
return fmt.Errorf("backup of resolved.conf already exists. Did you forget to run `mage undeploy:edgeNetwork`?")
}
// Create a backup of the existing resolved.conf file
if err := sh.RunV("sudo", "cp", "/etc/systemd/resolved.conf", "/etc/systemd/resolved.conf.bak"); err != nil {
return fmt.Errorf("failed to create backup of resolved.conf: %w", err)
}
contents := fmt.Sprintf(`[Resolve]
DNS=%s
DNSStubListener=yes
`, bridgeIP.String())
cmd := exec.Command("sudo", "tee", "/etc/systemd/resolved.conf")
cmd.Stdin = strings.NewReader(contents)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to write edge-network-resolved.sh: %w", err)
}
if err := sh.RunV("sudo", "systemctl", "daemon-reload"); err != nil {
return fmt.Errorf("failed to reload systemd daemon: %w", err)
}
if err := sh.RunV("sudo", "systemctl", "restart", "systemd-resolved"); err != nil {
return fmt.Errorf("failed to restart systemd-resolved: %w", err)
}
fmt.Println("Edge network DNS successfully set as default DNS resolver 🧑🔧")
return nil
}
func (Deploy) EdgeStoragePool(ctx context.Context) error {
mg.CtxDeps(
ctx,
Deps{}.EnsureUbuntu,
Deps{}.Terraform,
)
// Pass parent context to the command to allow for cancellation
cmd := exec.CommandContext(
ctx,
"terraform",
"-chdir="+filepath.Join("terraform", "edge-storage-pool"),
"apply",
fmt.Sprintf("--parallelism=%d", runtime.NumCPU()), // Set parallelism to the number of CPUs on the machine
"--auto-approve")
// Stream the output to stdout and stderr
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("terraform apply failed: %w", err)
}
return nil
}
// Deploy orchestrator locally using edge-manageability-framework revision defined by local git HEAD.
func (d Deploy) OnPrem(ctx context.Context) error {
// Ensure the required dependencies are installed first
mg.SerialCtxDeps(
ctx,
Deps{}.EnsureUbuntu,
Deps{}.Libvirt,
Deps{}.Terraform,
Undeploy{}.OnPrem,
)
// Create the underlying network and storage pool
mg.CtxDeps(
ctx,
d.EdgeNetwork,
d.EdgeStoragePool,
)
// TODO: Build DEB packages so they can be copied into the Orchestrator
// Check if TF_VAR_FILE is defined, if not, set it to a default value
if os.Getenv("TF_VAR_FILE") == "" {
if err := os.Setenv("TF_VAR_FILE", "terraform.tfvars"); err != nil {
return fmt.Errorf("failed to set TF_VAR_FILE: %w", err)
}
}
tfvarsFile := os.Getenv("TF_VAR_FILE")
// Pass parent context to the command to allow for cancellation
cmd := exec.CommandContext(
ctx,
"terraform",
"-chdir="+filepath.Join("terraform", "orchestrator"),
"apply",
"--var-file="+tfvarsFile,
fmt.Sprintf("--parallelism=%d", runtime.NumCPU()), // Set parallelism to the number of CPUs on the machine
"--auto-approve")
// Stream the output to stdout and stderr
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("terraform apply failed: %w", err)
}
dir, err := os.Getwd()
if err != nil {
return fmt.Errorf("failed to get current directory: %w", err)
}
kubeconfigPath := filepath.Join(dir, "terraform", "orchestrator", "files", "kubeconfig")
fmt.Printf("Orchestrator deployment started 🚀\n")
fmt.Printf(`
This generally takes ~35 minutes to complete. You can check the status of the deployment by running:
export KUBECONFIG=%s
mage deploy:waitUntilComplete
Once the deployment is complete, you can access the K8s cluster with kubectl:
kubectl get pods -A
In order to access the Orchestrator, you will need to install the Orchestrator TLS certificate into your local machine's
trust store and configure DNS to resolve the orchestrator domain to the kind cluster IP. Execute:
mage deploy:OrchCA deploy:EdgeNetworkDNS
Congrats! You should now be able to access the Orchestrator on this host at https://web-ui.cluster.onprem 🎉
`, kubeconfigPath)
return nil
}
// OnboardingFlow defines the onboarding flow type for the edge node.
type OnboardingFlow string
var (
InteractiveOnboardingFlow OnboardingFlow = "io"
NonInteractiveOnboardingFlow OnboardingFlow = "nio"
)
func (flow OnboardingFlow) IsValid() bool {
return flow == InteractiveOnboardingFlow || flow == NonInteractiveOnboardingFlow
}
// Deploy a local Virtual Edge Node using libvirt. An Orchestrator must be running locally.
func (d Deploy) VEN(ctx context.Context, flow string, serialNumber string) error {
err := d.VENWithFlow(ctx, flow, serialNumber)
if err != nil {
return fmt.Errorf("failed to deploy virtual Edge Node: %w", err)
}
fmt.Printf("Successfully deployed virtual Edge Node with serial number: %s\n", serialNumber)
return nil
}
// VENWithFlow deploys a local Virtual Edge Node using libvirt and returns the serial number of the deployed node.
func (d Deploy) VENWithFlow(ctx context.Context, flow string, serialNumber string) error { //nolint:gocyclo,maintidx
mg.CtxDeps(
ctx,
Deps{}.EnsureUbuntu,
)
if !OnboardingFlow(flow).IsValid() {
return fmt.Errorf("invalid onboarding flow: %s", flow)
}
if serialNumber == "" {
return fmt.Errorf("serial number is required")
}
if serviceDomain == "" {
return fmt.Errorf("cluster service domain name is not set")
}
fmt.Printf("Using Orchestrator domain: %s\n", serviceDomain)
password, err := GetDefaultOrchPassword()
if err != nil {
return fmt.Errorf("failed to get default Orchestrator password: %w", err)
}
tempDir, err := os.MkdirTemp("", "ven-clone")
if err != nil {
return fmt.Errorf("failed to create temporary directory: %w", err)
}
defer func() {
if err := os.RemoveAll(tempDir); err != nil {
fmt.Printf("Warning: failed to remove temporary directory %s: %v\n", tempDir, err)
}
}()
fmt.Printf("Temporary directory created: %s\n", tempDir)
if err := os.Chdir(tempDir); err != nil {
return fmt.Errorf("failed to change directory to temporary directory: %w", err)
}
if err := sh.RunV("git", "clone", "https://github.com/open-edge-platform/virtual-edge-node", "ven"); err != nil {
return fmt.Errorf("failed to clone repository: %w", err)
}
if err := os.Chdir("ven"); err != nil {
return fmt.Errorf("failed to change directory to 'ven': %w", err)
}
if err := sh.RunV("git", "checkout", "pico/1.5.6"); err != nil {
return fmt.Errorf("failed to checkout specific commit: %w", err)
}
if err := sh.RunV("sudo", "mkdir", "-p", "/etc/apparmor.d/disable/"); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
for _, link := range []string{
"/etc/apparmor.d/usr.sbin.libvirtd",
"/etc/apparmor.d/usr.lib.libvirt.virt-aa-helper",
} {
if err := sh.RunV("sudo", "ln", "-sf", link, "/etc/apparmor.d/disable/"); err != nil {
return fmt.Errorf("failed to create symlink: %w", err)
}
}
for _, profile := range []string{
"/etc/apparmor.d/usr.sbin.libvirtd",
"/etc/apparmor.d/usr.lib.libvirt.virt-aa-helper",
} {
if err := sh.RunV("sudo", "apparmor_parser", "-R", profile); err != nil {
fmt.Printf("failed to remove apparmor profile: %v\n", err)
}
}
if err := sh.RunV("sudo", "systemctl", "restart", "libvirtd"); err != nil {
return fmt.Errorf("failed to restart libvirtd: %w", err)
}
if err := sh.RunV("sudo", "systemctl", "reload", "apparmor"); err != nil {
return fmt.Errorf("failed to reload apparmor: %w", err)
}
venDir, err := os.Getwd()
if err != nil {
return fmt.Errorf("failed to get current working directory: %w", err)
}
if err := os.Chdir("vm-provisioning"); err != nil {
return fmt.Errorf("failed to change directory to 'vm-provisioning': %w", err)
}
if err := os.Setenv("LIBVIRT_DEFAULT_URI", "qemu:///system"); err != nil {
return fmt.Errorf("failed to set LIBVIRT_DEFAULT_URI: %w", err)
}
tmpl, err := template.New("config").Parse(`
CLUSTER='{{.ServiceDomain}}'
# IO Flow Configurations
ONBOARDING_USERNAME='{{.OnboardingUsername}}'
ONBOARDING_PASSWORD='{{.OnboardingPassword}}'
# NIO Flow Configurations
PROJECT_NAME='{{.ProjectName}}'
PROJECT_API_USER='{{.ProjectApiUser}}'
PROJECT_API_PASSWORD='{{.ProjectApiPassword}}'
# VM Resources
RAM_SIZE='{{.RamSize}}'
NO_OF_CPUS='{{.NoOfCpus}}'
SDA_DISK_SIZE='{{.SdaDiskSize}}'
LIBVIRT_DRIVER='{{.LibvirtDriver}}'
USERNAME_LINUX='{{.UsernameLinux}}'
PASSWORD_LINUX='{{.PasswordLinux}}'
CI_CONFIG='{{.CiConfig}}'
# Optional: Advance Settings
BRIDGE_NAME='{{.BridgeName}}'
INTF_NAME='{{.IntfName}}'
VM_NAME='{{.VmName}}'