forked from Azure/acs-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
387 lines (355 loc) · 11.9 KB
/
cli.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package azure
import (
"encoding/json"
"errors"
"fmt"
"log"
"os/exec"
"strconv"
"time"
"github.com/Azure/acs-engine/test/e2e/engine"
"github.com/Azure/acs-engine/test/e2e/kubernetes/util"
"github.com/kelseyhightower/envconfig"
)
// Storage provides access to StorageAccount objects
type Storage interface {
CreateStorageAccount() error
SetConnectionString() error
CreateFileShare(name string) error
UploadFiles(source, destination string) error
DownloadFiles(source, destination string) error
DeleteFiles(source string) error
}
// Account represents an Azure account
type Account struct {
User *User `json:"user"`
TenantID string `json:"tenantId" envconfig:"TENANT_ID" required:"true"`
SubscriptionID string `json:"id" envconfig:"SUBSCRIPTION_ID" required:"true"`
ResourceGroup ResourceGroup
Deployment Deployment
}
// ResourceGroup represents a collection of azure resources
type ResourceGroup struct {
Name string `json:"name"`
Location string `json:"location"`
Tags map[string]string `json:"tags"`
}
// VM represents an azure vm
type VM struct {
Name string `json:"name"`
}
// Deployment represents a deployment of an acs cluster
type Deployment struct {
Name string // Name of the deployment
TemplateDirectory string // engine.GeneratedDefinitionPath
}
// StorageAccount represents an azure storage account
type StorageAccount struct {
Name string
ConnectionString string `json:"connectionString"`
ResourceGroup ResourceGroup
}
// User represents the user currently logged into an Account
type User struct {
ID string `json:"name" envconfig:"CLIENT_ID" required:"true"`
Secret string `envconfig:"CLIENT_SECRET" required:"true"`
Type string `json:"type"`
}
// NewAccount will parse env vars and return a new account struct
func NewAccount() (*Account, error) {
a := new(Account)
if err := envconfig.Process("account", a); err != nil {
return nil, err
}
u := new(User)
if err := envconfig.Process("user", u); err != nil {
return nil, err
}
a.User = u
return a, nil
}
// Login will login to a given subscription
func (a *Account) Login() error {
output, err := exec.Command("az", "login",
"--service-principal",
"--username", a.User.ID,
"--password", a.User.Secret,
"--tenant", a.TenantID).CombinedOutput()
if err != nil {
log.Printf("output:%s\n", output)
return err
}
return nil
}
// SetSubscription will call az account set --subscription for the given Account
func (a *Account) SetSubscription() error {
cmd := exec.Command("az", "account", "set", "--subscription", a.SubscriptionID)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to set subscription (%s):%s", a.SubscriptionID, err)
log.Printf("Output:%s\n", out)
return err
}
return nil
}
// CreateGroup will create a resource group in a given location
//--tags "type=${RESOURCE_GROUP_TAG_TYPE:-}" "now=$(date +%s)" "job=${JOB_BASE_NAME:-}" "buildno=${BUILD_NUM:-}"
func (a *Account) CreateGroup(name, location string) error {
now := fmt.Sprintf("now=%v", time.Now().Unix())
cmd := exec.Command("az", "group", "create", "--name", name, "--location", location, "--tags", now)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to create resource group (%s) in %s:%s", name, location, err)
log.Printf("Output:%s\n", out)
return err
}
r := ResourceGroup{
Name: name,
Location: location,
Tags: map[string]string{
"now": now,
},
}
a.ResourceGroup = r
return nil
}
// DeleteGroup deletes a given resource group by name
func (a *Account) DeleteGroup(name string, wait bool) error {
var cmd *exec.Cmd
if !wait {
cmd = exec.Command("az", "group", "delete", "--name", name, "--no-wait", "--yes")
} else {
cmd = exec.Command("az", "group", "delete", "--name", name, "--yes")
}
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to delete resource group (%s):%s", name, out)
return err
}
return nil
}
// CreateDeployment will deploy a cluster to a given resource group using the template and parameters on disk
func (a *Account) CreateDeployment(name string, e *engine.Engine) error {
d := Deployment{
Name: name,
TemplateDirectory: e.Config.GeneratedDefinitionPath,
}
ticker := time.NewTicker(1 * time.Minute)
quit := make(chan bool)
go func() {
for {
select {
case <-ticker.C:
fmt.Print(".")
case <-quit:
fmt.Print("\n")
ticker.Stop()
return
}
}
}()
cmd := exec.Command("az", "group", "deployment", "create",
"--name", d.Name,
"--resource-group", a.ResourceGroup.Name,
"--template-file", e.Config.GeneratedTemplatePath,
"--parameters", e.Config.GeneratedParametersPath)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("\nError from deployment for %s in resource group %s:%s\n", d.Name, a.ResourceGroup.Name, err)
log.Printf("Command Output: %s\n", out)
return err
}
quit <- true
a.Deployment = d
return nil
}
// GetCurrentAccount will run an az account show and parse that into an account strcut
func GetCurrentAccount() (*Account, error) {
cmd := exec.Command("az", "account", "show")
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error trying to run 'account show':%s\n", err)
return nil, err
}
a := Account{}
err = json.Unmarshal(out, &a)
if err != nil {
log.Printf("Error unmarshalling account json:%s\n", err)
log.Printf("JSON:%s\n", out)
}
return &a, nil
}
// CreateVnet will create a vnet in a resource group
func (a *Account) CreateVnet(vnet, addressPrefixes, subnetName, subnetPrefix string) error {
cmd := exec.Command("az", "network", "vnet", "create", "-g", a.ResourceGroup.Name, "-n", vnet, "--address-prefixes", addressPrefixes, "--subnet-name", subnetName, "--subnet-prefix", subnetPrefix)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to create vnet with the following command:\n az network vnet create -g %s -n %s --address-prefixes %s --subnet-name %s --subnet-prefix %s \n Output:%s\n", a.ResourceGroup.Name, vnet, addressPrefixes, subnetName, subnetPrefix, out)
return err
}
return nil
}
// RouteTable holds information from running az network route-table list
type RouteTable struct {
ID string `json:"id"`
Location string `json:"location"`
Name string `json:"name"`
ProvisioningState string `json:"provisioningState"`
ResourceGroup string `json:"resourceGroup"`
}
// UpdateRouteTables is used to updated a vnet with the appropriate route tables
func (a *Account) UpdateRouteTables(subnet, vnet string) error {
cmd := exec.Command("az", "network", "route-table", "list", "-g", a.ResourceGroup.Name)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to get route table list!\n Output:%s\n", out)
return err
}
rts := []RouteTable{}
json.Unmarshal(out, &rts)
cmd = exec.Command("az", "network", "vnet", "subnet", "update", "-n", subnet, "-g", a.ResourceGroup.Name, "--vnet-name", vnet, "--route-table", rts[0].Name)
util.PrintCommand(cmd)
out, err = cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to update vnet route tables:%s\n", out)
return err
}
return nil
}
// GetHosts will get a list of vms in the resource group
func (a *Account) GetHosts(name string) ([]VM, error) {
var resourceGroup string
if name != "" {
resourceGroup = name
} else {
resourceGroup = a.ResourceGroup.Name
}
cmd := exec.Command("az", "vm", "list", "-g", resourceGroup)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to get vm list:%s\n", out)
return nil, err
}
v := []VM{{}}
err = json.Unmarshal(out, &v)
if err != nil {
log.Printf("Error unmarshalling VM json:%s\n", err)
log.Printf("JSON:%s\n", out)
return nil, err
}
return v, nil
}
// SetResourceGroup will set the account resource group
func (a *Account) SetResourceGroup(name string) error {
if a.ResourceGroup.Name != "" {
return nil
}
cmd := exec.Command("az", "group", "show", "-g", name)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to show resource group:%s\n", out)
return err
}
if len(out) == 0 {
log.Printf("Resource group %s does not exist\n", name)
return errors.New("Resource group not found")
}
a.ResourceGroup = ResourceGroup{}
err = json.Unmarshal(out, &a.ResourceGroup)
if err != nil {
log.Printf("Error unmarshalling resource group json:%s\n", err)
log.Printf("JSON:%s\n", out)
return err
}
return nil
}
// IsClusterExpired will return true if a deployment was created more than t nanoseconds ago, or if timestamp is not found
func (a *Account) IsClusterExpired(d time.Duration) bool {
tag, err := strconv.ParseInt(a.ResourceGroup.Tags["now"], 10, 64)
if err != nil {
log.Printf("Error parsing RG now tag:%s\n", err)
return true
}
t := time.Unix(tag, 0)
return time.Since(t) > d
}
// CreateStorageAccount will create a new Azure Storage Account
func (sa *StorageAccount) CreateStorageAccount() error {
cmd := exec.Command("az", "storage", "account", "create", "--name", sa.Name, "--resource-group", sa.ResourceGroup.Name)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to create storage account: %s", out)
return err
}
return nil
}
// SetConnectionString will set the storage account connection string
func (sa *StorageAccount) SetConnectionString() error {
cmd := exec.Command("az", "storage", "account", "show-connection-string", "-g", sa.ResourceGroup.Name, "-n", sa.Name)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to get connection-string:%s\n", out)
return err
}
err = json.Unmarshal(out, &sa)
if err != nil {
log.Printf("Error unmarshalling account json:%s\n", err)
log.Printf("JSON:%s\n", out)
return err
}
return nil
}
// CreateFileShare will create a file share in a storage account if it doesn't already exist
func (sa *StorageAccount) CreateFileShare(name string) error {
cmd := exec.Command("az", "storage", "share", "create", "--name", name, "--account-name", sa.Name, "--connection-string", sa.ConnectionString)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to create file share: %s", out)
return err
}
return nil
}
// UploadFiles will upload the output directory to storage
func (sa *StorageAccount) UploadFiles(source, destination string) error {
cmd := exec.Command("az", "storage", "file", "upload-batch", "--destination", destination, "--source", source, "--account-name", sa.Name, "--connection-string", sa.ConnectionString)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying upload files to file share:%s\n", out)
return err
}
return nil
}
// DownloadFiles will download the output directory from storage
func (sa *StorageAccount) DownloadFiles(source, destination string) error {
cmd := exec.Command("az", "storage", "file", "download-batch", "--destination", destination, "--source", source, "--account-name", sa.Name, "--connection-string", sa.ConnectionString)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying download files from %s in storage account %s: %s\n", source, sa.Name, out)
return err
}
return nil
}
// DeleteFiles deletes files from an Azure storage file share
func (sa *StorageAccount) DeleteFiles(source string) error {
cmd := exec.Command("az", "storage", "file", "delete-batch", "--source", source, "--account-name", sa.Name, "--connection-string", sa.ConnectionString)
util.PrintCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error while trying to delete files from %s: %s", source, out)
return err
}
return nil
}