This repository has been archived by the owner on Jul 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 100
/
deployer.go
473 lines (441 loc) · 12.7 KB
/
deployer.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package arm
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
az "github.com/Azure/open-service-broker-azure/pkg/azure"
"github.com/Azure/open-service-broker-azure/pkg/template"
log "github.com/Sirupsen/logrus"
)
type deploymentStatus string
const (
deploymentStatusNotFound deploymentStatus = "NOT_FOUND"
deploymentStatusRunning deploymentStatus = "RUNNING"
deploymentStatusSucceeded deploymentStatus = "SUCCEEDED"
deploymentStatusFailed deploymentStatus = "FAILED"
deploymentStatusUnknown deploymentStatus = "UNKNOWN"
)
// Deployer is an interface to be implemented by any component capable of
// deploying resource to Azure using an ARM template
type Deployer interface {
Deploy(
deploymentName string,
resourceGroupName string,
location string,
template []byte,
goParams interface{},
armParams map[string]interface{},
tags map[string]string,
) (map[string]interface{}, error)
Delete(deploymentName string, resourceGroupName string) error
}
// deployer is an ARM-based implementation of the Deployer interface
type deployer struct {
azureEnvironment azure.Environment
subscriptionID string
tenantID string
clientID string
clientSecret string
}
// NewDeployer returns a new ARM-based implementation of the Deployer interface
func NewDeployer() (Deployer, error) {
azureConfig, err := az.GetConfig()
if err != nil {
return nil, err
}
azureEnvironment, err := azure.EnvironmentFromName(azureConfig.Environment)
if err != nil {
return nil, fmt.Errorf(
`error parsing Azure environment name "%s"`,
azureConfig.Environment,
)
}
return &deployer{
azureEnvironment: azureEnvironment,
subscriptionID: azureConfig.SubscriptionID,
tenantID: azureConfig.TenantID,
clientID: azureConfig.ClientID,
clientSecret: azureConfig.ClientSecret,
}, nil
}
// Deploy idempotently handles ARM deployments. To do this, it checks for the
// existence and status of a deployment before choosing to create a new one,
// poll until success or failure, or return an error.
func (d *deployer) Deploy(
deploymentName string,
resourceGroupName string,
location string,
template []byte,
goParams interface{},
armParams map[string]interface{},
tags map[string]string,
) (map[string]interface{}, error) {
logFields := log.Fields{
"resourceGroup": resourceGroupName,
"deployment": deploymentName,
}
authorizer, err := az.GetBearerTokenAuthorizer(
d.azureEnvironment,
d.tenantID,
d.clientID,
d.clientSecret,
)
if err != nil {
return nil, fmt.Errorf(
`error deploying "%s" in resource group "%s": error getting bearer `+
`token authorizer: %s`,
deploymentName,
resourceGroupName,
err,
)
}
deploymentsClient := resources.NewDeploymentsClientWithBaseURI(
d.azureEnvironment.ResourceManagerEndpoint,
d.subscriptionID,
)
deploymentsClient.Authorizer = authorizer
deploymentsClient.UserAgent = userAgent()
// Get the deployment and its current status
deployment, ds, err := getDeploymentAndStatus(
deploymentsClient,
deploymentName,
resourceGroupName,
)
if err != nil {
return nil, fmt.Errorf(
`error deploying "%s" in resource group "%s": error getting `+
`deployment: %s`,
deploymentName,
resourceGroupName,
err,
)
}
// Handle according to status...
switch ds {
case deploymentStatusNotFound:
// The deployment wasn't found, which means we are free to proceed with
// initiating a new deployment
log.WithFields(logFields).Debug(
"deployment does not already exist; beginning new deployment",
)
if deployment, err = d.doNewDeployment(
deploymentsClient,
authorizer,
deploymentName,
resourceGroupName,
location,
template,
goParams,
armParams,
tags,
); err != nil {
return nil, fmt.Errorf(
`error deploying "%s" in resource group "%s": %s`,
deploymentName,
resourceGroupName,
err,
)
}
case deploymentStatusRunning:
// The deployment exists and is currently running, which means we'll poll
// until it completes. The return at the end of the function will return the
// deployment's outputs.
log.WithFields(logFields).Debug(
"deployment exists and is in-progress; polling until complete",
)
if deployment, err = d.pollUntilComplete(
deploymentsClient,
deploymentName,
resourceGroupName,
); err != nil {
return nil, fmt.Errorf(
`error deploying "%s" in resource group "%s": %s`,
deploymentName,
resourceGroupName,
err,
)
}
case deploymentStatusSucceeded:
// The deployment exists and has succeeded already. There's nothing to do.
// The return at the end of the function will return the deployment's
// outputs.
log.WithFields(logFields).Debug(
"deployment exists and has already succeeded",
)
case deploymentStatusFailed:
// The deployment exists and has failed already.
return nil, fmt.Errorf(
`error deploying "%s" in resource group "%s": deployment is in failed `+
`state`,
deploymentName,
resourceGroupName,
)
case deploymentStatusUnknown:
fallthrough
default:
// Unrecognized state
return nil, fmt.Errorf(
`error deploying "%s" in resource group "%s": deployment is in an `+
`unrecognized state`,
deploymentName,
resourceGroupName,
)
}
return getOutputs(deployment), nil
}
func (d *deployer) Delete(
deploymentName string,
resourceGroupName string,
) error {
authorizer, err := az.GetBearerTokenAuthorizer(
d.azureEnvironment,
d.tenantID,
d.clientID,
d.clientSecret,
)
if err != nil {
return fmt.Errorf(
`error deleting deployment "%s" from resource group "%s": error `+
`getting bearer token authorizer: %s`,
deploymentName,
resourceGroupName,
err,
)
}
deploymentsClient := resources.NewDeploymentsClientWithBaseURI(
d.azureEnvironment.ResourceManagerEndpoint,
d.subscriptionID,
)
deploymentsClient.UserAgent = userAgent()
deploymentsClient.Authorizer = authorizer
cancelCh := make(chan struct{})
defer close(cancelCh)
_, errChan := deploymentsClient.Delete(
resourceGroupName,
deploymentName,
cancelCh,
)
timer := time.NewTimer(time.Minute * 20)
defer timer.Stop()
select {
case err := <-errChan:
if err != nil {
return fmt.Errorf(
`error deleting deployment "%s" from resource group "%s": %s`,
deploymentName,
resourceGroupName,
err,
)
}
case <-timer.C:
return fmt.Errorf(
`timed out deleting deployment "%s" from resource group "%s"`,
deploymentName,
resourceGroupName,
)
}
return nil
}
// getDeploymentAndStatus attempts to retrieve and return a deployment. Whether
// it's found or not, a status is returned. (It's not enough to just return the
// deployment and let the caller check status itself, because in the case a
// given deployment doesn't exist, there isn't one to return. Returning a
// separate status indicator resolves that problem.)
func getDeploymentAndStatus(
deploymentsClient resources.DeploymentsClient,
deploymentName string,
resourceGroupName string,
) (*resources.DeploymentExtended, deploymentStatus, error) {
deployment, err := deploymentsClient.Get(resourceGroupName, deploymentName)
if err != nil {
detailedErr, ok := err.(autorest.DetailedError)
if !ok || detailedErr.StatusCode != http.StatusNotFound {
return nil, "", err
}
return nil, deploymentStatusNotFound, nil
}
switch *deployment.Properties.ProvisioningState {
case "Running":
return &deployment, deploymentStatusRunning, nil
case "Succeeded":
return &deployment, deploymentStatusSucceeded, nil
case "Failed":
return &deployment, deploymentStatusFailed, nil
default:
return &deployment, deploymentStatusUnknown, nil
}
}
func (d *deployer) doNewDeployment(
deploymentsClient resources.DeploymentsClient,
authorizer autorest.Authorizer,
deploymentName string,
resourceGroupName string,
location string,
armTemplate []byte,
goParams interface{},
armParams map[string]interface{},
tags map[string]string,
) (*resources.DeploymentExtended, error) {
groupsClient := resources.NewGroupsClientWithBaseURI(
d.azureEnvironment.ResourceManagerEndpoint,
d.subscriptionID,
)
groupsClient.UserAgent = userAgent()
groupsClient.Authorizer = authorizer
res, err := groupsClient.CheckExistence(resourceGroupName)
if err != nil {
return nil, fmt.Errorf(
"error checking existence of resource group: %s",
err,
)
}
if res.StatusCode == http.StatusNotFound {
if _, err = groupsClient.CreateOrUpdate(
resourceGroupName,
resources.Group{
Name: &resourceGroupName,
Location: &location,
},
); err != nil {
return nil, fmt.Errorf(
"error creating resource group: %s",
err,
)
}
}
finalArmTemplate := armTemplate
// The template could be a Go text template that renders down to an ARM
// template, so deal with that possibility first.
if goParams != nil {
finalArmTemplate, err = template.Render(armTemplate, goParams)
if err != nil {
return nil, err
}
}
// Unmarshal the template into a map
var armTemplateMap map[string]interface{}
err = json.Unmarshal(finalArmTemplate, &armTemplateMap)
if err != nil {
return nil, fmt.Errorf("error unmarshaling ARM template: %s", err)
}
// Augment the params with location
armParams["location"] = location
// Deal with the possibility that tags == nil
if tags == nil {
tags = make(map[string]string)
}
// Augment the provided tags with heritage information
tags["heritage"] = "open-service-broker-azure"
// Deal with the possiiblity that params == nil
if armParams == nil {
armParams = make(map[string]interface{})
}
// Augment the params with tags
armParams["tags"] = tags
// Convert a simple map[string]interface{} to the more complex
// map[string]map[string]interface{} required by the deployments client
armParamsMap := map[string]interface{}{}
for key, val := range armParams {
armParamsMap[key] = map[string]interface{}{
"value": val,
}
}
// Deploy the template
cancelCh := make(chan struct{})
defer close(cancelCh)
_, errChan := deploymentsClient.CreateOrUpdate(
resourceGroupName,
deploymentName,
resources.Deployment{
Properties: &resources.DeploymentProperties{
Template: &armTemplateMap,
Parameters: &armParamsMap,
Mode: resources.Incremental,
},
},
cancelCh,
)
timer := time.NewTimer(time.Minute * 30)
defer timer.Stop()
select {
case err = <-errChan:
if err != nil {
return nil, fmt.Errorf("error submitting ARM template: %s", err)
}
case <-timer.C:
return nil, errors.New("timed out waiting for deployment to complete")
}
// Deployment object found on the result channel doesn't include properties,
// so we need to make a separate call to retrieve the deployment
deployment, err := deploymentsClient.Get(resourceGroupName, deploymentName)
if err != nil {
return nil, fmt.Errorf("error retrieving completed deployment: %s", err)
}
return &deployment, nil
}
// pollUntilComplete polls the status of a deployment periodically until the
// deployment succeeds or fails, polling fails, or a timeout is reached
func (d *deployer) pollUntilComplete(
deploymentsClient resources.DeploymentsClient,
deploymentName string,
resourceGroupName string,
) (*resources.DeploymentExtended, error) {
ticker := time.NewTicker(time.Second * 10)
defer ticker.Stop()
timer := time.NewTimer(time.Minute * 30)
defer timer.Stop()
var deployment *resources.DeploymentExtended
var ds deploymentStatus
var err error
for {
select {
case <-ticker.C:
if deployment, ds, err = getDeploymentAndStatus(
deploymentsClient,
deploymentName,
resourceGroupName,
); err != nil {
return nil, err
}
switch ds {
case deploymentStatusNotFound:
// This is an error. We'd only be polling for status on a deployment
// that exists. If it no longer exists, something is very wrong.
return nil, errors.New(
"error polling deployment status; deployment should exist, but " +
"does not",
)
case deploymentStatusRunning:
// Do nothing == continue the loop
case deploymentStatusSucceeded:
// We're done
return deployment, nil
case deploymentStatusFailed:
// The deployment has failed
return nil, errors.New("deployment has failed")
case deploymentStatusUnknown:
fallthrough
default:
// The deployment has entered an unknown state
return nil, errors.New("deployment is in an unrecognized state")
}
case <-timer.C:
// We've reached a timeout
return nil, errors.New("timed out waiting for deployment to complete")
}
}
}
func getOutputs(
deployment *resources.DeploymentExtended,
) map[string]interface{} {
outputs := make(map[string]interface{})
for k, v := range *deployment.Properties.Outputs {
outputs[k] = v.(map[string]interface{})["value"]
}
return outputs
}