/
virtualmachine.go
286 lines (252 loc) · 9.13 KB
/
virtualmachine.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
/* (c) 2019, Blender Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package azvm
import (
"context"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"github.com/sirupsen/logrus"
"github.com/Azure/flamenco-manager-azure/azauth"
"github.com/Azure/flamenco-manager-azure/azconfig"
"github.com/Azure/flamenco-manager-azure/azdebug"
"github.com/Azure/flamenco-manager-azure/aznetwork"
"github.com/Azure/flamenco-manager-azure/textio"
)
func getVMClient(config azconfig.AZConfig) compute.VirtualMachinesClient {
vmClient := compute.NewVirtualMachinesClient(config.SubscriptionID)
vmClient.Authorizer = azauth.Load(azure.PublicCloud.ServiceManagementEndpoint)
vmClient.RequestInspector = azdebug.LogRequest()
vmClient.ResponseInspector = azdebug.LogResponse()
return vmClient
}
// ListVMs fetches a list of available virtual machine names.
func ListVMs(ctx context.Context, config azconfig.AZConfig) []string {
vmClient := getVMClient(config)
logger := logrus.WithFields(logrus.Fields{
"resourceGroup": config.ResourceGroup,
"location": config.Location,
})
logger.Info("fetching VM list")
vmNames := []string{}
vmListPage, err := vmClient.List(ctx, config.ResourceGroup)
if err != nil {
logger.WithError(err).Fatal("unable to fetch list of existing VMs")
}
for vmListPage.NotDone() {
for _, vmInfo := range vmListPage.Values() {
locationMatches := config.Location == *vmInfo.Location
logger.WithFields(logrus.Fields{
"id": *vmInfo.ID,
"name": *vmInfo.Name,
"location": *vmInfo.Location,
"locationMatches": locationMatches,
}).Debug("found VM")
if !locationMatches {
continue
}
vmNames = append(vmNames, *vmInfo.Name)
}
if err := vmListPage.NextWithContext(ctx); err != nil {
logger.WithError(err).Fatal("unable to fetch next page of VMs")
}
}
return vmNames
}
// ChooseVM lets the user pick a virtual machine.
// if vmName is not empty, that name is used instead, and this function just determines whether that VM already exists.
func ChooseVM(ctx context.Context, config *azconfig.AZConfig, vmName, defaultName string) (chosenVMName string, isExisting bool) {
vmNames := ListVMs(ctx, *config)
vmChoices := textio.StrMap(vmNames)
logger := logrus.WithFields(logrus.Fields{
"resourceGroup": config.ResourceGroup,
"location": config.Location,
})
logger.WithFields(logrus.Fields{
"numVMs": len(vmNames),
"names": vmNames,
}).Info("retrieved list of existing VMs")
// If a name was already given, we don't need to prompt any more.
if vmName != "" {
config.VMName = vmName
config.Save()
return vmName, vmChoices[vmName]
}
if config.VMName != "" {
return config.VMName, vmChoices[config.VMName]
}
if len(vmNames) > 0 {
vmName, isExisting = textio.Choose(ctx, vmNames, "Desired VM name, can be new or an existing name")
} else {
vmName = textio.ReadLineWithDefault(ctx, "Flamenco manager VM name", defaultName)
}
if vmName == "" {
logger.Fatal("no name given, aborting")
}
config.VMName = vmName
config.Save()
return vmName, isExisting
}
// EnsureVM either returns the VM info (isExisting=true) or creates a new VM (isExisting=false)
func EnsureVM(ctx context.Context, config azconfig.AZConfig, vmName string, isExisting bool) (compute.VirtualMachine, aznetwork.NetworkStack) {
vmClient := getVMClient(config)
logger := logrus.WithFields(logrus.Fields{
"resourceGroup": config.ResourceGroup,
"location": config.Location,
"vmName": vmName,
})
if !isExisting {
logger.Info("creating new VM")
return createVM(ctx, config, vmName)
}
logger.Info("retrieving existing VM")
vm, err := vmClient.Get(ctx, config.ResourceGroup, vmName, compute.InstanceView)
if err != nil {
logger.WithError(err).Fatal("unable to retrieve VM info")
}
stack := findVMNetworkStack(ctx, config, vm)
return vm, stack
}
func loadSSHKey() string {
// TODO: make this configurable/promptable and/or support ssh-agent
sshPublicKeyPath := os.ExpandEnv("$HOME/.ssh/id_rsa.pub")
logger := logrus.WithField("sshPublicKeyPath", sshPublicKeyPath)
sshBytes, err := ioutil.ReadFile(sshPublicKeyPath)
if err != nil {
logger.WithError(err).Fatal("failed to read SSH key data")
}
return string(sshBytes)
}
func askVMSize(ctx context.Context) compute.VirtualMachineSizeTypes {
// TODO(fsiddi): Ensure that the VM size is valid
containerServiceVMSizeType := textio.ReadLineWithDefault(ctx, "Desired Flamenco Manager VM size", "Standard_D12_v2")
// Verify is containerServiceVMSizeType is valid
return compute.VirtualMachineSizeTypes(containerServiceVMSizeType)
}
func createVM(ctx context.Context, config azconfig.AZConfig, vmName string) (compute.VirtualMachine, aznetwork.NetworkStack) {
sshKeyData := loadSSHKey()
adminPassword := RandStringBytes(32)
logger := logrus.WithFields(logrus.Fields{
"resourceGroup": config.ResourceGroup,
"location": config.Location,
"vmName": vmName,
})
vmSize := askVMSize(ctx)
netstack := aznetwork.CreateNetworkStack(ctx, config, vmName)
logger.Info("creating virtual machine")
vmClient := getVMClient(config)
future, err := vmClient.CreateOrUpdate(
ctx,
config.ResourceGroup,
vmName,
compute.VirtualMachine{
Location: to.StringPtr(config.Location),
VirtualMachineProperties: &compute.VirtualMachineProperties{
HardwareProfile: &compute.HardwareProfile{
VMSize: vmSize,
},
StorageProfile: &compute.StorageProfile{
ImageReference: &compute.ImageReference{
Publisher: to.StringPtr(publisher),
Offer: to.StringPtr(offer),
Sku: to.StringPtr(sku),
Version: to.StringPtr("latest"),
},
},
OsProfile: &compute.OSProfile{
ComputerName: to.StringPtr(vmName),
AdminUsername: to.StringPtr(adminUsername),
AdminPassword: to.StringPtr(adminPassword),
LinuxConfiguration: &compute.LinuxConfiguration{
SSH: &compute.SSHConfiguration{
PublicKeys: &[]compute.SSHPublicKey{{
Path: to.StringPtr(fmt.Sprintf("/home/%s/.ssh/authorized_keys", adminUsername)),
KeyData: to.StringPtr(sshKeyData),
}},
},
},
},
NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{{
ID: netstack.Interface.ID,
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true),
},
}},
},
},
},
)
if err != nil {
logger.WithError(err).Fatal("error creating VM")
}
err = future.WaitForCompletionRef(ctx, vmClient.Client)
if err != nil {
logger.WithError(err).Fatal("error creating VM")
}
vm, err := future.Result(vmClient)
if err != nil {
logger.WithError(err).Fatal("error creating VM")
}
return vm, netstack
}
func findVMNetworkStack(ctx context.Context, config azconfig.AZConfig, vm compute.VirtualMachine) aznetwork.NetworkStack {
if vm.NetworkProfile == nil || vm.NetworkProfile.NetworkInterfaces == nil || len(*vm.NetworkProfile.NetworkInterfaces) == 0 {
logrus.Fatal("this VM has no network interface")
}
nicRef := (*vm.NetworkProfile.NetworkInterfaces)[0]
return aznetwork.GetNetworkStack(ctx, config, *nicRef.ID)
}
// WaitForReady regularly polls a VM until it has the required status.
func WaitForReady(ctx context.Context, config azconfig.AZConfig, vmName string) {
logger := logrus.WithFields(logrus.Fields{
"resourceGroup": config.ResourceGroup,
"location": config.Location,
"vmName": vmName,
})
vmClient := getVMClient(config)
for {
logger.Info("checking VM status")
vmInfo, err := vmClient.InstanceView(ctx, config.ResourceGroup, vmName)
if err != nil {
logger.WithError(err).Fatal("error fetching VM")
}
statuses := map[string]bool{}
for _, status := range *vmInfo.Statuses {
statuses[*status.Code] = true
}
if statuses["ProvisioningState/succeeded"] && statuses["PowerState/running"] {
logger.WithField("statuses", statuses).Info("VM is ready")
return
}
select {
case <-ctx.Done():
logger.Error("aborted")
return
case <-time.After(1 * time.Second):
}
}
}