-
Notifications
You must be signed in to change notification settings - Fork 13
/
attach.go
90 lines (80 loc) · 2.61 KB
/
attach.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
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/service/ec2"
log "github.com/sirupsen/logrus"
"github.com/sevagh/goat/filesystem"
)
//AttachEbsVolumes attaches the given map of {'VolumeName':[]EbsVol} with the EC2 client in the provided ec2Instance
func (e *EC2Instance) AttachEbsVolumes() {
var deviceName string
var err error
localVolumes := map[string][]EbsVol{}
for key, volumes := range e.Vols {
localVolumes[key] = []EbsVol{}
for _, volume := range volumes {
volLogger := log.WithFields(log.Fields{"vol_id": volume.EbsVolID, "vol_name": volume.VolumeName})
if volume.AttachedName == "" {
volLogger.Info("Volume is unattached, picking drive name")
if deviceName, err = randDriveNamePicker(); err != nil {
volLogger.Fatal("Couldn't find an unused drive name")
}
attachVolIn := &ec2.AttachVolumeInput{
Device: &deviceName,
InstanceId: &e.InstanceID,
VolumeId: &volume.EbsVolID,
}
volLogger.Info("Executing AWS SDK attach command")
volAttachments, err := e.EC2Client.AttachVolume(attachVolIn)
if err != nil {
volLogger.Fatalf("Couldn't attach: %v", err)
}
volLogger.Info(volAttachments)
if !filesystem.DoesDriveExistWithTimeout(deviceName, 10) {
volLogger.Fatalf("Drive %s doesn't exist after attaching - checked with stat 10 times", deviceName)
}
} else {
deviceName = volume.AttachedName
}
realDeviceName, err := filesystem.GetActualBlockDeviceName(deviceName)
if err != nil {
volLogger.Fatalf("Couldn't get real device name of %s", deviceName)
}
volume.AttachedName = realDeviceName
localVolumes[key] = append(localVolumes[key], volume)
}
}
e.Vols = localVolumes
}
//AttachEnis attaches the given array of Eni Ids with the EC2 client in the provided ec2Instance
func (e *EC2Instance) AttachEnis() {
for eniIdx, eni := range e.Enis {
eniLogger := log.WithFields(log.Fields{"eni_id": eni})
deviceIdx := int64(eniIdx + 1)
attachEniIn := &ec2.AttachNetworkInterfaceInput{
NetworkInterfaceId: &eni,
InstanceId: &e.InstanceID,
DeviceIndex: &deviceIdx,
}
eniLogger.Info("Executing AWS SDK attach command")
_, err := e.EC2Client.AttachNetworkInterface(attachEniIn)
if err != nil {
eniLogger.Fatalf("Couldn't attach: %v", err)
}
}
}
func randDriveNamePicker() (string, error) {
ctr := 0
deviceName := "/dev/xvd"
runes := []rune("fghijklmnopqrstuvwxyz")
for {
if ctr >= len(runes) {
return "", fmt.Errorf("Ran out of drive names")
}
if !filesystem.DoesDriveExist(deviceName + string(runes[ctr])) {
break
}
ctr++
}
return deviceName + string(runes[ctr]), nil
}