/
save_dev_env_data.go
109 lines (82 loc) · 2.48 KB
/
save_dev_env_data.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package service
import (
"encoding/json"
"sync"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/recode-sh/aws-cloud-provider/infrastructure"
"github.com/recode-sh/recode/entities"
)
func SaveDevEnvData(
config *entities.Config,
cluster *entities.Cluster,
devEnv *entities.DevEnv,
) (*string, error) {
var devEnvInfra *DevEnvInfrastructure
err := json.Unmarshal([]byte(devEnv.InfrastructureJSON), &devEnvInfra)
if err != nil {
return nil, err
}
ec2Client := ec2.NewFromConfig(*aws.NewConfig())
prefixResource := prefixDevEnvResource(cluster.GetNameSlug(), devEnv.GetNameSlug())
var createSnapshotWG sync.WaitGroup
createSnapshotErrors := make([]error, len(devEnvInfra.Instance.Volumes))
devEnvInfraUpdatedVolumes := make([]infrastructure.InstanceVolume, len(devEnvInfra.Instance.Volumes))
for i, volume := range devEnvInfra.Instance.Volumes {
createSnapshotWG.Add(1)
go func(i int, volume infrastructure.InstanceVolume) {
defer createSnapshotWG.Done()
snapshotName := "root-volume-snapshot"
createSnapshotForVolumeResp := infrastructure.CreateSnapshotForVolume(
ec2Client,
prefixResource(snapshotName),
volume.ID,
)
if createSnapshotForVolumeResp.Err != nil {
createSnapshotErrors[i] = createSnapshotForVolumeResp.Err
return
}
if len(volume.SnapshotID) > 0 { // Volume has old snapshot
removeVolumeSnapshotResp := infrastructure.RemoveVolumeSnapshot(ec2Client, volume.SnapshotID)
if removeVolumeSnapshotResp.Err != nil {
createSnapshotErrors[i] = removeVolumeSnapshotResp.Err
return
}
}
devEnvInfraUpdatedVolumes[i] = volume
devEnvInfraUpdatedVolumes[i].SnapshotID = createSnapshotForVolumeResp.SnapshotID
detachVolumeResp := infrastructure.DetachVolume(
ec2Client,
devEnvInfra.Instance.ID,
volume.ID,
volume.DeviceName,
)
if detachVolumeResp.Err != nil {
createSnapshotErrors[i] = detachVolumeResp.Err
return
}
removeVolumeResp := infrastructure.RemoveVolume(
ec2Client,
volume.ID,
)
if removeVolumeResp.Err != nil {
createSnapshotErrors[i] = removeVolumeResp.Err
return
}
}(i, volume)
}
createSnapshotWG.Wait()
for _, err := range createSnapshotErrors {
if err == nil {
continue
}
return nil, err
}
devEnvInfra.Instance.Volumes = devEnvInfraUpdatedVolumes
devEnvInfraJSON, err := json.Marshal(devEnvInfra)
if err != nil {
return nil, err
}
s := string(devEnvInfraJSON)
return &s, nil
}