This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
deployment.go
571 lines (434 loc) · 13.5 KB
/
deployment.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
package director
import (
"encoding/json"
"fmt"
"net/http"
gourl "net/url"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
type DeploymentImpl struct {
client Client
name string
cloudConfig string
manifest string
releases []Release
stemcells []Stemcell
teams []string
fetched bool
fetchErr error
}
type ExportReleaseResult struct {
BlobstoreID string
SHA1 string
}
type ExportReleaseResp struct {
BlobstoreID string `json:"blobstore_id"`
SHA1 string `json:"sha1"`
}
type LogsResult struct {
BlobstoreID string
SHA1 string
}
type VariableResult struct {
ID string `json:"id"`
Name string `json:"name"`
}
func (d DeploymentImpl) Name() string { return d.name }
func (d *DeploymentImpl) CloudConfig() (string, error) {
d.fetch()
return d.cloudConfig, d.fetchErr
}
func (d *DeploymentImpl) Releases() ([]Release, error) {
d.fetch()
return d.releases, d.fetchErr
}
func (d *DeploymentImpl) Stemcells() ([]Stemcell, error) {
d.fetch()
return d.stemcells, d.fetchErr
}
func (d *DeploymentImpl) Teams() ([]string, error) {
d.fetch()
return d.teams, d.fetchErr
}
func (d *DeploymentImpl) fetch() {
if d.fetched {
return
}
resps, err := d.client.Deployments()
if err != nil {
d.fetchErr = err
return
}
for _, resp := range resps {
if resp.Name == d.name {
d.fill(resp)
return
}
}
d.fetchErr = bosherr.Errorf("Expected to find deployment '%s'", d.name)
}
func (d *DeploymentImpl) fill(resp DeploymentResp) {
d.fetched = true
rels, err := newReleasesFromResps(resp.Releases, d.client)
if err != nil {
d.fetchErr = err
return
}
stems, err := newStemcellsFromResps(resp.Stemcells, d.client)
if err != nil {
d.fetchErr = err
return
}
d.releases = rels
d.stemcells = stems
d.teams = resp.Teams
d.cloudConfig = resp.CloudConfig
}
func (d DeploymentImpl) Manifest() (string, error) {
resp, err := d.client.Deployment(d.name)
if err != nil {
return "", bosherr.WrapErrorf(err, "Fetching manifest")
}
return resp.Manifest, nil
}
func (d DeploymentImpl) FetchLogs(slug AllOrInstanceGroupOrInstanceSlug, filters []string, agent bool) (LogsResult, error) {
blobID, sha1, err := d.client.FetchLogs(d.name, slug.Name(), slug.IndexOrID(), filters, agent)
if err != nil {
return LogsResult{}, err
}
return LogsResult{BlobstoreID: blobID, SHA1: sha1}, nil
}
func (d DeploymentImpl) EnableResurrection(slug InstanceSlug, enabled bool) error {
return d.client.EnableResurrection(d.name, slug.Name(), slug.IndexOrID(), enabled)
}
func (d DeploymentImpl) Ignore(slug InstanceSlug, enabled bool) error {
return d.client.Ignore(d.name, slug.Name(), slug.IndexOrID(), enabled)
}
func (d DeploymentImpl) Start(slug AllOrInstanceGroupOrInstanceSlug, opts StartOpts) error {
return d.changeJobState("started", slug, false, false, false, false, opts.Canaries, opts.MaxInFlight)
}
func (d DeploymentImpl) Stop(slug AllOrInstanceGroupOrInstanceSlug, opts StopOpts) error {
if opts.Hard {
return d.changeJobState("detached", slug, opts.SkipDrain, opts.Force, false, false, opts.Canaries, opts.MaxInFlight)
}
return d.changeJobState("stopped", slug, opts.SkipDrain, opts.Force, false, false, opts.Canaries, opts.MaxInFlight)
}
func (d DeploymentImpl) Restart(slug AllOrInstanceGroupOrInstanceSlug, opts RestartOpts) error {
return d.changeJobState("restart", slug, opts.SkipDrain, opts.Force, false, false, opts.Canaries, opts.MaxInFlight)
}
func (d DeploymentImpl) Recreate(slug AllOrInstanceGroupOrInstanceSlug, opts RecreateOpts) error {
return d.changeJobState("recreate", slug, opts.SkipDrain, opts.Force, opts.Fix, opts.DryRun, opts.Canaries, opts.MaxInFlight)
}
func (d DeploymentImpl) changeJobState(state string, slug AllOrInstanceGroupOrInstanceSlug, skipDrain bool, force bool, fix bool, dryRun bool, canaries string, maxInFlight string) error {
return d.client.ChangeJobState(
state, d.name, slug.Name(), slug.IndexOrID(), skipDrain, force, fix, dryRun, canaries, maxInFlight)
}
func (d DeploymentImpl) ExportRelease(release ReleaseSlug, os OSVersionSlug, jobs []string) (ExportReleaseResult, error) {
resp, err := d.client.ExportRelease(d.name, release, os, jobs)
if err != nil {
return ExportReleaseResult{}, err
}
return ExportReleaseResult{BlobstoreID: resp.BlobstoreID, SHA1: resp.SHA1}, nil
}
func (d DeploymentImpl) Update(manifest []byte, opts UpdateOpts) error {
return d.client.UpdateDeployment(manifest, opts)
}
func (d DeploymentImpl) Delete(force bool) error {
err := d.client.DeleteDeployment(d.name, force)
if err != nil {
resps, listErr := d.client.Deployments()
if listErr != nil {
return err
}
for _, resp := range resps {
if resp.Name == d.name {
return err
}
}
}
return nil
}
func (d DeploymentImpl) AttachDisk(slug InstanceSlug, diskCID string) error {
values := gourl.Values{}
values.Add("deployment", d.Name())
values.Add("job", slug.Name())
values.Add("instance_id", slug.IndexOrID())
path := fmt.Sprintf("/disks/%s/attachments?%s", diskCID, values.Encode())
_, err := d.client.taskClientRequest.PutResult(path, []byte{}, func(*http.Request) {})
return err
}
func (d DeploymentImpl) IsInProgress() (bool, error) {
lockResps, err := d.client.Locks()
if err != nil {
return false, err
}
for _, r := range lockResps {
if r.IsForDeployment(d.name) {
return true, nil
}
}
return false, nil
}
func (d DeploymentImpl) Variables() ([]VariableResult, error) {
path := fmt.Sprintf("/deployments/%s/variables", d.name)
response := []VariableResult{}
if err := d.client.clientRequest.Get(path, &response); err != nil {
return nil, bosherr.WrapErrorf(err, "Error fetching variables for deployment '%s'", d.name)
}
return response, nil
}
func (c Client) FetchLogs(deploymentName, job, indexOrID string, filters []string, agent bool) (string, string, error) {
if len(deploymentName) == 0 {
return "", "", bosherr.Error("Expected non-empty deployment name")
}
if len(job) == 0 {
job = "*"
}
if len(indexOrID) == 0 {
indexOrID = "*"
}
query := gourl.Values{}
if len(filters) > 0 {
query.Add("filters", strings.Join(filters, ","))
}
if agent {
query.Add("type", "agent")
} else {
query.Add("type", "job")
}
path := fmt.Sprintf("/deployments/%s/jobs/%s/%s/logs?%s",
deploymentName, job, indexOrID, query.Encode())
taskID, _, err := c.taskClientRequest.GetResult(path)
if err != nil {
return "", "", bosherr.WrapErrorf(err, "Fetching logs")
}
taskResp, err := c.Task(taskID)
if err != nil {
return "", "", err
}
return taskResp.Result, "", nil
}
func (c Client) Ignore(deploymentName, instanceGroup, indexOrID string, enabled bool) error {
if len(deploymentName) == 0 {
return bosherr.Error("Expected non-empty deployment name")
}
if len(instanceGroup) == 0 {
return bosherr.Error("Expected non-empty instance group name")
}
if len(indexOrID) == 0 {
return bosherr.Error("Expected non-empty index or ID")
}
headers := func(req *http.Request) {
req.Header.Add("Content-Type", "application/json")
}
body := map[string]bool{"ignore": enabled}
reqBody, err := json.Marshal(body)
if err != nil {
return bosherr.WrapErrorf(err, "Marshaling request body")
}
path := fmt.Sprintf("/deployments/%s/instance_groups/%s/%s/ignore",
deploymentName, instanceGroup, indexOrID)
_, _, err = c.clientRequest.RawPut(path, reqBody, headers)
if err != nil {
msg := "Changing ignore state for '%s/%s' in deployment '%s'"
return bosherr.WrapErrorf(err, msg, instanceGroup, indexOrID, deploymentName)
}
return nil
}
func (c Client) EnableResurrection(deploymentName, job, indexOrID string, enabled bool) error {
if len(deploymentName) == 0 {
return bosherr.Error("Expected non-empty deployment name")
}
if len(job) == 0 {
return bosherr.Error("Expected non-empty job name")
}
if len(indexOrID) == 0 {
return bosherr.Error("Expected non-empty index or ID")
}
path := fmt.Sprintf("/deployments/%s/jobs/%s/%s/resurrection",
deploymentName, job, indexOrID)
body := map[string]bool{"resurrection_paused": !enabled}
reqBody, err := json.Marshal(body)
if err != nil {
return bosherr.WrapErrorf(err, "Marshaling request body")
}
setHeaders := func(req *http.Request) {
req.Header.Add("Content-Type", "application/json")
}
_, _, err = c.clientRequest.RawPut(path, reqBody, setHeaders)
if err != nil {
msg := "Changing VM resurrection state for '%s/%s' in deployment '%s'"
return bosherr.WrapErrorf(err, msg, job, indexOrID, deploymentName)
}
return nil
}
func (c Client) ChangeJobState(state, deploymentName, job, indexOrID string, skipDrain bool, force bool, fix bool, dryRun bool, canaries string, maxInFlight string) error {
if len(state) == 0 {
return bosherr.Error("Expected non-empty job state")
}
if len(deploymentName) == 0 {
return bosherr.Error("Expected non-empty deployment name")
}
// allows to have empty job and indexOrID
query := gourl.Values{}
query.Add("state", state)
if skipDrain {
query.Add("skip_drain", "true")
}
if force {
query.Add("force", "true")
}
if fix {
query.Add("fix", "true")
}
if dryRun {
query.Add("dry_run", "true")
}
if canaries != "" {
query.Add("canaries", canaries)
}
if maxInFlight != "" {
query.Add("max_in_flight", maxInFlight)
}
path := fmt.Sprintf("/deployments/%s/jobs", deploymentName)
if len(job) > 0 {
path += "/" + job
if len(indexOrID) > 0 {
path += "/" + indexOrID
}
} else {
path += "/*"
}
path += "?" + query.Encode()
setHeaders := func(req *http.Request) {
req.Header.Add("Content-Type", "text/yaml")
}
_, err := c.taskClientRequest.PutResult(path, []byte{}, setHeaders)
if err != nil {
return bosherr.WrapErrorf(err, "Changing state")
}
return nil
}
func (c Client) ExportRelease(deploymentName string, release ReleaseSlug, os OSVersionSlug, jobs []string) (ExportReleaseResp, error) {
var resp ExportReleaseResp
if len(deploymentName) == 0 {
return resp, bosherr.Error("Expected non-empty deployment name")
}
if len(release.Name()) == 0 {
return resp, bosherr.Error("Expected non-empty release name")
}
if len(release.Version()) == 0 {
return resp, bosherr.Error("Expected non-empty release version")
}
if len(os.OS()) == 0 {
return resp, bosherr.Error("Expected non-empty OS name")
}
if len(os.Version()) == 0 {
return resp, bosherr.Error("Expected non-empty OS version")
}
jobFilters := []map[string]string{}
for _, job := range jobs {
jobFilters = append(jobFilters, map[string]string{"name": job})
}
path := "/releases/export"
body := map[string]interface{}{
"deployment_name": deploymentName,
"release_name": release.Name(),
"release_version": release.Version(),
"stemcell_os": os.OS(),
"stemcell_version": os.Version(),
"sha2": true,
"jobs": jobFilters,
}
reqBody, err := json.Marshal(body)
if err != nil {
return resp, bosherr.WrapErrorf(err, "Marshaling request body")
}
setHeaders := func(req *http.Request) {
req.Header.Add("Content-Type", "application/json")
}
resultBytes, err := c.taskClientRequest.PostResult(path, reqBody, setHeaders)
if err != nil {
return resp, bosherr.WrapErrorf(err, "Exporting release")
}
err = json.Unmarshal(resultBytes, &resp)
if err != nil {
return resp, bosherr.WrapErrorf(err, "Unmarshaling export release result")
}
return resp, nil
}
func (c Client) UpdateDeployment(manifest []byte, opts UpdateOpts) error {
query := gourl.Values{}
if opts.Recreate {
query.Add("recreate", "true")
}
if opts.Fix {
query.Add("fix", "true")
}
if len(opts.SkipDrain.AsQueryValue()) > 0 {
query.Add("skip_drain", opts.SkipDrain.AsQueryValue())
}
if opts.Canaries != "" {
query.Add("canaries", opts.Canaries)
}
if opts.MaxInFlight != "" {
query.Add("max_in_flight", opts.MaxInFlight)
}
if opts.DryRun {
query.Add("dry_run", "true")
}
if len(opts.Diff.context) != 0 {
context := map[string]interface{}{}
for key, value := range opts.Diff.context {
context[key] = value
}
contextJson, err := json.Marshal(context)
if err != nil {
return bosherr.WrapErrorf(err, "Marshaling context")
}
query.Add("context", string(contextJson))
}
path := fmt.Sprintf("/deployments?%s", query.Encode())
setHeaders := func(req *http.Request) {
req.Header.Add("Content-Type", "text/yaml")
}
_, err := c.taskClientRequest.PostResult(path, manifest, setHeaders)
if err != nil {
return bosherr.WrapErrorf(err, "Updating deployment")
}
return nil
}
func (c Client) DeleteDeployment(deploymentName string, force bool) error {
if len(deploymentName) == 0 {
return bosherr.Error("Expected non-empty deployment name")
}
query := gourl.Values{}
if force {
query.Add("force", "true")
}
path := fmt.Sprintf("/deployments/%s?%s", deploymentName, query.Encode())
_, err := c.taskClientRequest.DeleteResult(path)
if err != nil {
return bosherr.WrapErrorf(err, "Deleting deployment '%s'", deploymentName)
}
return nil
}
type DeploymentVMResp struct {
JobName string `json:"job"` // e.g. dummy1
JobIndex int `json:"index"` // e.g. 0,1,2
AgentID string `json:"agent_id"` // e.g. 3b30123e-dfa6-4eff-abe6-63c2d5a88938
CID string // e.g. vm-ce10ae6a-6c31-413b-a134-7179f49e0bda
}
func (c Client) DeploymentVMs(deploymentName string) ([]DeploymentVMResp, error) {
if len(deploymentName) == 0 {
return nil, bosherr.Error("Expected non-empty deployment name")
}
var vms []DeploymentVMResp
path := fmt.Sprintf("/deployments/%s/vms", deploymentName)
err := c.clientRequest.Get(path, &vms)
if err != nil {
return vms, bosherr.WrapErrorf(err, "Listing deployment '%s' VMs", deploymentName)
}
return vms, nil
}