forked from apporbit/libretto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
353 lines (295 loc) · 10.8 KB
/
util.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
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
// Copyright 2016 Apcera Inc. All rights reserved.
package arm
import (
"encoding/json"
"fmt"
"math/rand"
"net"
"strconv"
"time"
armStorage "github.com/Azure/azure-sdk-for-go/arm/storage"
lvm "github.com/apcera/libretto/virtualmachine"
"github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
"github.com/Azure/azure-sdk-for-go/storage"
"github.com/Azure/go-autorest/autorest/azure"
)
// getServicePrincipalToken retrieves a new ServicePrincipalToken using values of the
// passed credentials map.
func getServicePrincipalToken(creds *OAuthCredentials, scope string) (*azure.ServicePrincipalToken, error) {
oauthConfig, err := azure.PublicCloud.OAuthConfigForTenant(creds.TenantID)
if err != nil {
return nil, err
}
return azure.NewServicePrincipalToken(*oauthConfig, creds.ClientID, creds.ClientSecret, scope)
}
type armParameter struct {
Value string `json:"value"`
}
type armParameters struct {
AdminUsername *armParameter `json:"username,omitempty"`
AdminPassword *armParameter `json:"password,omitempty"`
ImageOffer *armParameter `json:"image_offer,omitempty"`
ImagePublisher *armParameter `json:"image_publisher,omitempty"`
ImageSku *armParameter `json:"image_sku,omitempty"`
NetworkSecurityGroup *armParameter `json:"network_security_group,omitempty"`
NicName *armParameter `json:"nic,omitempty"`
OSFileName *armParameter `json:"os_file,omitempty"`
PublicIPName *armParameter `json:"public_ip,omitempty"`
SSHAuthorizedKey *armParameter `json:"ssh_authorized_key,omitempty"`
SubnetName *armParameter `json:"subnet,omitempty"`
VirtualNetworkName *armParameter `json:"virtual_network,omitempty"`
StorageAccountName *armParameter `json:"storage_account,omitempty"`
StorageContainerName *armParameter `json:"storage_container,omitempty"`
VMSize *armParameter `json:"vm_size,omitempty"`
VMName *armParameter `json:"vm_name,omitempty"`
DiskSize *armParameter `json:"disk_size,omitempty"`
DiskFile *armParameter `json:"disk_file,omitempty"`
AdditionalDisk *armParameter `json:"additional_disk,omitempty"`
}
// Translates the given VM to arm parameters
func (vm *VM) toARMParameters() *armParameters {
out := &armParameters{
AdminUsername: &armParameter{vm.SSHCreds.SSHUser},
AdminPassword: &armParameter{vm.SSHCreds.SSHPassword},
ImageOffer: &armParameter{vm.ImageOffer},
ImagePublisher: &armParameter{vm.ImagePublisher},
ImageSku: &armParameter{vm.ImageSku},
NetworkSecurityGroup: &armParameter{vm.NetworkSecurityGroup},
NicName: &armParameter{vm.Nic},
OSFileName: &armParameter{vm.OsFile},
PublicIPName: &armParameter{vm.PublicIP},
SSHAuthorizedKey: &armParameter{vm.SSHPublicKey},
StorageAccountName: &armParameter{vm.StorageAccount},
StorageContainerName: &armParameter{vm.StorageContainer},
SubnetName: &armParameter{vm.Subnet},
VirtualNetworkName: &armParameter{vm.VirtualNetwork},
VMSize: &armParameter{vm.Size},
VMName: &armParameter{vm.Name},
DiskSize: &armParameter{strconv.Itoa(vm.DiskSize)},
DiskFile: &armParameter{vm.DiskFile},
AdditionalDisk: &armParameter{"false"},
}
if vm.DiskSize > 0 {
out.AdditionalDisk = &armParameter{"true"}
}
return out
}
// validateVM validates the members of given VM object
func validateVM(vm *VM) error {
// Validate the OAUTH Credentials
if vm.Creds.ClientID == "" {
return fmt.Errorf("a client id must be specified")
}
if vm.Creds.ClientSecret == "" {
return fmt.Errorf("a client secret must be specified")
}
if vm.Creds.TenantID == "" {
return fmt.Errorf("a tenant id must be specified")
}
if vm.Creds.SubscriptionID == "" {
return fmt.Errorf("a subscription id must be specified")
}
// Validate the image
if vm.ImagePublisher == "" {
return fmt.Errorf("an image publisher must be specified")
}
if vm.ImageOffer == "" {
return fmt.Errorf("an image offer must be specified")
}
if vm.ImageSku == "" {
return fmt.Errorf("an image sku must be specified")
}
// Validate the deployment
if vm.ResourceGroup == "" {
return fmt.Errorf("a resource group must be specified")
}
if vm.StorageAccount == "" {
return fmt.Errorf("a storage account must be specified")
}
// Validate the network
if vm.NetworkSecurityGroup == "" {
return fmt.Errorf("a network security group must be specified")
}
if vm.Subnet == "" {
return fmt.Errorf("a subnet must be specified")
}
if vm.VirtualNetwork == "" {
return fmt.Errorf("a virtual network must be specified")
}
return nil
}
// deploy deploys the given VM based on the default Linux arm template over the
// VM's resource group.
func (vm *VM) deploy() error {
// Set up the authorizer
authorizer, err := getServicePrincipalToken(&vm.Creds, azure.PublicCloud.ResourceManagerEndpoint)
if err != nil {
return err
}
// Pass the parameters to the arm templacte
vmParams := vm.toARMParameters()
deployment, err := createDeployment(Linux, *vmParams)
if err != nil {
return err
}
// Create and send the deployment to the resource group
deploymentsClient := resources.NewDeploymentsClient(vm.Creds.SubscriptionID)
deploymentsClient.Authorizer = authorizer
_, err = deploymentsClient.CreateOrUpdate(vm.ResourceGroup, vm.DeploymentName, *deployment, nil)
if err != nil {
return err
}
// Make sure the deployment is succeeded
for i := 0; i < actionTimeout; i++ {
result, err := deploymentsClient.Get(vm.ResourceGroup, vm.DeploymentName)
if err != nil {
return err
}
if result.Properties != nil && result.Properties.ProvisioningState != nil {
if *result.Properties.ProvisioningState == succeeded {
return nil
}
}
time.Sleep(1 * time.Second)
}
return ErrActionTimeout
}
// getPublicIP returns the public IP of the given VM, if exists one.
func (vm *VM) getPublicIP(authorizer *azure.ServicePrincipalToken) (net.IP, error) {
publicIPAddressesClient := network.NewPublicIPAddressesClient(vm.Creds.SubscriptionID)
publicIPAddressesClient.Authorizer = authorizer
resPublicIP, err := publicIPAddressesClient.Get(vm.ResourceGroup, vm.PublicIP, "")
if err != nil {
return nil, err
}
if resPublicIP.Properties == nil || resPublicIP.Properties.IPAddress == nil ||
*resPublicIP.Properties.IPAddress == "" {
return nil, fmt.Errorf("VM has no public IP address")
}
return net.ParseIP(*resPublicIP.Properties.IPAddress), nil
}
// getPrivateIP returns the private IP of the given VM, if exists one.
func (vm *VM) getPrivateIP(authorizer *azure.ServicePrincipalToken) (net.IP, error) {
interfaceClient := network.NewInterfacesClient(vm.Creds.SubscriptionID)
interfaceClient.Authorizer = authorizer
resPrivateIP, err := interfaceClient.Get(vm.ResourceGroup, vm.Nic, "")
if err != nil {
return nil, err
}
if resPrivateIP.Properties == nil || resPrivateIP.Properties.IPConfigurations == nil ||
len(*resPrivateIP.Properties.IPConfigurations) == 0 {
return nil, fmt.Errorf("VM has no private IP address")
}
ipConfigs := *resPrivateIP.Properties.IPConfigurations
if len(ipConfigs) > 1 {
return nil, fmt.Errorf("VM has multiple private IP addresses")
}
return net.ParseIP(*ipConfigs[0].Properties.PrivateIPAddress), nil
}
// deleteOSFile deletes the OS file from the VM's storage account, returns an error if the operation
// does not succeed.
func (vm *VM) deleteVMFiles(authorizer *azure.ServicePrincipalToken) error {
storageAccountsClient := armStorage.NewAccountsClient(vm.Creds.SubscriptionID)
storageAccountsClient.Authorizer = authorizer
accountKeys, err := storageAccountsClient.ListKeys(vm.ResourceGroup, vm.StorageAccount)
if err != nil {
return err
}
storageClient, err := storage.NewBasicClient(vm.StorageAccount, *accountKeys.Key1)
if err != nil {
return err
}
blobStorageClient := storageClient.GetBlobService()
err = blobStorageClient.DeleteBlob(vm.StorageContainer, vm.OsFile, nil)
if err != nil {
return err
}
if vm.DiskSize <= 0 {
return nil
}
return blobStorageClient.DeleteBlob(vm.StorageContainer, vm.DiskFile, nil)
}
// deleteNic deletes the network interface for the given VM from the VM's resource group, returns an error
// if the operation does not succeed.
func (vm *VM) deleteNic(authorizer *azure.ServicePrincipalToken) error {
interfaceClient := network.NewInterfacesClient(vm.Creds.SubscriptionID)
interfaceClient.Authorizer = authorizer
_, err := interfaceClient.Delete(vm.ResourceGroup, vm.Nic, nil)
return err
}
// deletePublicIP deletes the reserved Public IP of the given VM from the VM's resource group, returns an error
// if the operation does not succeed.
func (vm *VM) deletePublicIP(authorizer *azure.ServicePrincipalToken) error {
// Delete the Public IP of this VM
publicIPAddressesClient := network.NewPublicIPAddressesClient(vm.Creds.SubscriptionID)
publicIPAddressesClient.Authorizer = authorizer
_, err := publicIPAddressesClient.Delete(vm.ResourceGroup, vm.PublicIP, nil)
return err
}
// deleteDeployment deletes the deployed azure arm template for this vm.
func (vm *VM) deleteDeployment(authorizer *azure.ServicePrincipalToken) error {
// Get the deployments client
deploymentsClient := resources.NewDeploymentsClient(vm.Creds.SubscriptionID)
deploymentsClient.Authorizer = authorizer
// Delete the deployment
_, err := deploymentsClient.Delete(vm.ResourceGroup, vm.DeploymentName, nil)
return err
}
func createDeployment(template string, params armParameters) (*resources.Deployment, error) {
templateMap, err := unmarshalTemplate(template)
if err != nil {
return nil, err
}
parametersMap, err := unmarshalParameters(params)
if err != nil {
return nil, err
}
return &resources.Deployment{
Properties: &resources.DeploymentProperties{
Mode: resources.Incremental,
Template: templateMap,
Parameters: parametersMap,
},
}, nil
}
func unmarshalTemplate(template string) (*map[string]interface{}, error) {
var t map[string]interface{}
err := json.Unmarshal([]byte(template), &t)
if err != nil {
return nil, err
}
return &t, nil
}
func unmarshalParameters(params armParameters) (*map[string]interface{}, error) {
b, err := json.Marshal(params)
if err != nil {
return nil, err
}
var t map[string]interface{}
err = json.Unmarshal(b, &t)
if err != nil {
return nil, err
}
return &t, nil
}
// translateState converts an Azure state to a libretto state.
func translateState(azureState string) string {
switch azureState {
case running:
return lvm.VMRunning
case stopped:
return lvm.VMHalted
default:
return lvm.VMUnknown
}
}
func randStringRunes(n int) string {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz")
r := rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[r.Intn(len(letterRunes))]
}
return string(b)
}