-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprovider_aws.go
313 lines (265 loc) · 8.5 KB
/
provider_aws.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
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
/******************************************************************************\
* Copyright (C) 2024-2024 The Molibackup Authors. All rights reserved. *
* Licensed under the Apache version 2.0 License *
* Homepage: https://github.com/fdupoux/molibackup *
\******************************************************************************/
package main
import (
"context"
"fmt"
"io"
"os"
"golang.org/x/exp/slices"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
)
type ProviderAwsEc2Instance struct {
instanceId string
instanceName string
instanceOwner string
}
type ProviderAwsEbsVolume struct {
volumeId string
volumeName string
}
type ProviderAwsEbsSnapshot struct {
volumeId string
snapshotId string
snapshotDesc string
snapshotTime int64
}
func ProviderAwsLoadConfig(region string, accesskey_id string, accesskey_secret string) (aws.Config, error) {
var cfg aws.Config
var err error
os.Setenv("AWS_REGION", region)
// Load the configuration using an access key pair if it has been provided in the configuration
if accesskey_id != "" && accesskey_secret != "" {
staticProvider := credentials.NewStaticCredentialsProvider(accesskey_id, accesskey_secret, "")
cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(staticProvider))
if err != nil {
return cfg, fmt.Errorf("failed to load the aws configuration with explicit access key pair: %v", err)
}
} else {
cfg, err = config.LoadDefaultConfig(context.TODO())
if err != nil {
return cfg, fmt.Errorf("failed to load the aws configuration without an explicit access key pair: %v", err)
}
}
return cfg, nil
}
func ProviderAwsNewEc2Client(cfg aws.Config) *ec2.Client {
return ec2.NewFromConfig(cfg)
}
// Get the InstanceId of the EC2 instance currently running this program
func ProviderAwsGetCurrentInstance(cfg aws.Config) (string, error) {
var instanceId string
clientImds := imds.NewFromConfig(cfg)
res1, err := clientImds.GetMetadata(context.TODO(), &imds.GetMetadataInput{
Path: "instance-id",
})
if err != nil {
return instanceId, fmt.Errorf("unable to determine the EC2 instance ID: %v", err)
}
defer res1.Content.Close()
res2, err := io.ReadAll(res1.Content)
if err != nil {
return instanceId, fmt.Errorf("unable to retrieve the EC2 instance ID: %v", err)
}
instanceId = string(res2)
return instanceId, nil
}
// Return basic information about all instances that match conditions specified in the arguments
func ProviderAwsGetEc2Instances(client *ec2.Client, instanceId string, instanceTags map[string]string) ([]ProviderAwsEc2Instance, error) {
var results []ProviderAwsEc2Instance
var params *ec2.DescribeInstancesInput
var filters []types.Filter
var filtcnt int
var count int
if instanceId != "" {
curfilter := types.Filter{
Name: aws.String("instance-id"),
Values: []string{instanceId},
}
filters = append(filters, curfilter)
filtcnt++
}
for tagkey := range instanceTags {
curfilter := types.Filter{
Name: aws.String("tag-key"),
Values: []string{tagkey},
}
filters = append(filters, curfilter)
filtcnt++
}
params = &ec2.DescribeInstancesInput{Filters: filters}
res, err := client.DescribeInstances(context.TODO(), params)
if err != nil {
return nil, fmt.Errorf("DescribeInstances() has failed: %v", err)
}
for _, reservation := range res.Reservations {
for _, instance := range reservation.Instances {
// Collect all tags in a map
tagsdict := make(map[string]string)
for _, curtag := range instance.Tags {
tagsdict[*curtag.Key] = *curtag.Value
}
// Check if all tags specified in instance_tags match
tagsmatch := true
for tagkey, tagval := range instanceTags {
val, ok := tagsdict[tagkey]
if (ok == false) || (val != tagval) {
tagsmatch = false
}
}
// Add instance to the results if all the tags required match
if tagsmatch == true {
instdata := ProviderAwsEc2Instance{}
instdata.instanceId = string(*instance.InstanceId)
instdata.instanceName = string(tagsdict["Name"])
instdata.instanceOwner = string(*reservation.OwnerId)
results = append(results, instdata)
count++
}
}
}
return results, nil
}
// Return basic information about all volumes that match conditions specified in the arguments
func ProviderAwsGetEbsVolumes(client *ec2.Client, instanceId string, volumeTags map[string]string) ([]ProviderAwsEbsVolume, error) {
var results []ProviderAwsEbsVolume
params := &ec2.DescribeVolumesInput{
Filters: []types.Filter{
{
Name: aws.String("attachment.instance-id"),
Values: []string{instanceId},
},
{
Name: aws.String("attachment.status"),
Values: []string{"attached"},
},
},
}
resvols, err := client.DescribeVolumes(context.TODO(), params)
if err != nil {
return nil, fmt.Errorf("DescribeVolumes() has failed: %v", err)
}
for _, volume := range resvols.Volumes {
// Collect all tags in a map
tagsdict := make(map[string]string)
for _, curtag := range volume.Tags {
tagsdict[*curtag.Key] = *curtag.Value
}
// Check if all tags specified in volume_tags match
tagsmatch := true
for tagkey, tagval := range volumeTags {
val, ok := tagsdict[tagkey]
if (ok == false) || (val != tagval) {
tagsmatch = false
}
}
// Add volume to the results if all the tags required match
if tagsmatch == true {
voldata := ProviderAwsEbsVolume{}
voldata.volumeId = string(*volume.VolumeId)
voldata.volumeName = string(tagsdict["Name"])
results = append(results, voldata)
}
}
return results, nil
}
// Get basic information about snapshots which are related to a particular volume
func ProviderAwsGetEbsSnapshots(client *ec2.Client, volumeId string) ([]ProviderAwsEbsSnapshot, error) {
var results []ProviderAwsEbsSnapshot
params := &ec2.DescribeSnapshotsInput{
Filters: []types.Filter{
{
Name: aws.String("tag:CreatedBy"),
Values: []string{
"molibackup",
},
},
{
Name: aws.String("volume-id"),
Values: []string{
volumeId,
},
},
},
}
ressnaps, err := client.DescribeSnapshots(context.TODO(), params)
if err != nil {
return nil, fmt.Errorf("DescribeSnapshots() has failed: %v", err)
}
for _, snapshot := range ressnaps.Snapshots {
snapdata := ProviderAwsEbsSnapshot{}
snapdata.volumeId = string(*snapshot.VolumeId)
snapdata.snapshotId = string(*snapshot.SnapshotId)
snapdata.snapshotDesc = string(*snapshot.Description)
snapdata.snapshotTime = (*snapshot.StartTime).Unix()
results = append(results, snapdata)
}
return results, nil
}
func ProviderAwsCreateEbsSnapshot(client *ec2.Client, volumeId string, snapname string, snapdate string, snaptime string, lockmode string, lockduration int32) (string, error) {
params1 := &ec2.CreateSnapshotInput{
VolumeId: &volumeId,
Description: &snapname,
TagSpecifications: []types.TagSpecification{
{
ResourceType: types.ResourceTypeSnapshot,
Tags: []types.Tag{
{
Key: aws.String("Name"),
Value: aws.String(snapname),
},
{
Key: aws.String("CreatedBy"),
Value: aws.String("molibackup"),
},
{
Key: aws.String("CreateDate"),
Value: aws.String(snapdate),
},
{
Key: aws.String("Timestamp"),
Value: aws.String(snaptime),
},
},
},
},
}
// Create snapshot of the volume
result, err := client.CreateSnapshot(context.TODO(), params1)
if err != nil {
return "", fmt.Errorf("CreateSnapshot() has failed for volume %s: %v", volumeId, err)
}
snapid := *result.SnapshotId
// Lock the new snapshot is this has been requested
curmode := types.LockMode(lockmode)
lockmodes := curmode.Values()
if slices.Contains(lockmodes, curmode) {
params2 := &ec2.LockSnapshotInput{
SnapshotId: &snapid,
LockMode: curmode,
LockDuration: &lockduration,
}
if _, err := client.LockSnapshot(context.TODO(), params2); err != nil {
return snapid, fmt.Errorf("LockSnapshot() has failed for snapshot %s: %v", snapid, err)
}
}
return snapid, nil
}
func ProviderAwsDeleteEbsSnapshot(client *ec2.Client, snapshotId string) error {
params := &ec2.DeleteSnapshotInput{
SnapshotId: &snapshotId,
}
_, err := client.DeleteSnapshot(context.TODO(), params)
if err != nil {
return fmt.Errorf("DeleteSnapshot() has failed for snapshot %s: %v", snapshotId, err)
}
return nil
}