/
jupiterbrain.go
753 lines (621 loc) · 20.5 KB
/
jupiterbrain.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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
package backend
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"regexp"
"strconv"
"time"
gocontext "context"
"github.com/cenk/backoff"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/travis-ci/worker/config"
"github.com/travis-ci/worker/context"
"github.com/travis-ci/worker/image"
"github.com/travis-ci/worker/metrics"
"github.com/travis-ci/worker/ssh"
)
const (
defaultJupiterBrainImageSelectorType = "env"
defaultBootPollDialTimeout = 3 * time.Second
defaultBootPollWaitForError = 2 * time.Second
defaultJupiterBrainSSHDialTimeout = 5 * time.Second
)
var (
metricNameCleanRegexp = regexp.MustCompile(`[^A-Za-z0-9.:-_]+`)
jupiterBrainHelp = map[string]string{
"ENDPOINT": "[REQUIRED] url to Jupiter Brain server, including auth",
"SSH_KEY_PATH": "[REQUIRED] path to SSH key used to access job VMs",
"SSH_KEY_PASSPHRASE": "[REQUIRED] passphrase for SSH key given as SSH_KEY_PATH",
"KEYCHAIN_PASSWORD": "[REQUIRED] password used ... somehow",
"IMAGE_SELECTOR_TYPE": fmt.Sprintf("image selector type (\"env\" or \"api\", default %q)", defaultJupiterBrainImageSelectorType),
"IMAGE_SELECTOR_URL": "URL for image selector API, used only when image selector is \"api\"",
"IMAGE_ALIASES": "comma-delimited strings used as stable names for images (default: \"\")",
"IMAGE_ALIAS_{ALIAS}": "full name for a given alias given via IMAGE_ALIASES, where the alias form in the key is uppercased and normalized by replacing non-alphanumerics with _",
"BOOT_POLL_SLEEP": "sleep interval between polling server for instance status (default 3s)",
"BOOT_POLL_DIAL_TIMEOUT": "how long to wait for a TCP connection to be made when polling SSH port (default 3s)",
"BOOT_POLL_WAIT_FOR_ERROR": "time to wait for an error message after cancelling the boot polling (default 2s)",
"SSH_DIAL_TIMEOUT": fmt.Sprintf("connection timeout for ssh connections (default %v)", defaultJupiterBrainSSHDialTimeout),
}
)
const (
wrapperSh = `#!/bin/bash
[[ $(uname) = Linux ]] && exec bash ~/build.sh
[[ -f ~/build.sh.exit ]] && rm ~/build.sh.exit
until nc 127.0.0.1 15782; do sleep 1; done
until [[ -f ~/build.sh.exit ]]; do sleep 1; done
exit $(cat ~/build.sh.exit)
`
)
func init() {
Register("jupiterbrain", "Jupiter Brain", jupiterBrainHelp, newJupiterBrainProvider)
}
type jupiterBrainProvider struct {
sshDialer ssh.Dialer
sshDialTimeout time.Duration
keychainPassword string
bootPollSleep time.Duration
bootPollDialTimeout time.Duration
bootPollWaitForError time.Duration
imageSelectorType string
imageSelector image.Selector
defaultInstanceCPUs int
defaultInstanceRAM int
apiClient *jupiterBrainAPIClient
}
type jupiterBrainInstance struct {
payload *jupiterBrainInstancePayload
provider *jupiterBrainProvider
progresser Progresser
startupDuration time.Duration
}
type jupiterBrainInstancePayload struct {
ID string `json:"id"`
IPAddresses []string `json:"ip-addresses"`
State string `json:"state"`
BaseImage string `json:"base-image,omitempty"`
Type string `json:"type,omitempty"`
}
type jupiterBrainDataResponse struct {
Data []*jupiterBrainInstancePayload `json:"data"`
}
func newJupiterBrainProvider(cfg *config.ProviderConfig) (Provider, error) {
if !cfg.IsSet("ENDPOINT") {
return nil, ErrMissingEndpointConfig
}
baseURL, err := url.Parse(cfg.Get("ENDPOINT"))
if err != nil {
return nil, errors.Wrap(err, "error parsing Jupiter Brain endpoint URL")
}
sshDialTimeout := defaultJupiterBrainSSHDialTimeout
if cfg.IsSet("SSH_DIAL_TIMEOUT") {
sshDialTimeout, err = time.ParseDuration(cfg.Get("SSH_DIAL_TIMEOUT"))
if err != nil {
return nil, err
}
}
if !cfg.IsSet("SSH_KEY_PATH") {
return nil, errors.Errorf("expected SSH_KEY_PATH config key")
}
sshKeyPath := cfg.Get("SSH_KEY_PATH")
if !cfg.IsSet("SSH_KEY_PASSPHRASE") {
return nil, errors.Errorf("expected SSH_KEY_PASSPHRASE config key")
}
sshKeyPassphrase := cfg.Get("SSH_KEY_PASSPHRASE")
if !cfg.IsSet("KEYCHAIN_PASSWORD") {
return nil, errors.Errorf("expected KEYCHAIN_PASSWORD config key")
}
sshDialer, err := ssh.NewDialer(sshKeyPath, sshKeyPassphrase)
if err != nil {
return nil, errors.Wrap(err, "couldn't set up SSH dialer")
}
keychainPassword := cfg.Get("KEYCHAIN_PASSWORD")
bootPollSleep := 3 * time.Second
if cfg.IsSet("BOOT_POLL_SLEEP") {
si, err := time.ParseDuration(cfg.Get("BOOT_POLL_SLEEP"))
if err != nil {
return nil, errors.Wrap(err, "error parsing boot pool sleep duration")
}
bootPollSleep = si
}
bootPollDialTimeout := defaultBootPollDialTimeout
if cfg.IsSet("BOOT_POLL_DIAL_TIMEOUT") {
si, err := time.ParseDuration(cfg.Get("BOOT_POLL_DIAL_TIMEOUT"))
if err != nil {
return nil, errors.Wrap(err, "error parsing boot pool dial timeout duration")
}
bootPollDialTimeout = si
}
bootPollWaitForError := defaultBootPollWaitForError
if cfg.IsSet("BOOT_POLL_WAIT_FOR_ERROR") {
si, err := time.ParseDuration(cfg.Get("BOOT_POLL_WAIT_FOR_ERROR"))
if err != nil {
return nil, errors.Wrap(err, "error parsing boot pool wait for error duration")
}
bootPollWaitForError = si
}
imageSelectorType := defaultJupiterBrainImageSelectorType
if cfg.IsSet("IMAGE_SELECTOR_TYPE") {
imageSelectorType = cfg.Get("IMAGE_SELECTOR_TYPE")
}
imageSelector, err := buildJupiterBrainImageSelector(imageSelectorType, cfg)
if err != nil {
return nil, err
}
var defaultInstanceCPUs int
if cfg.IsSet("INSTANCE_CPUS") {
defaultInstanceCPUs, err = strconv.Atoi(cfg.Get("INSTANCE_CPUS"))
if err != nil {
return nil, errors.Wrap(err, "error parsing image CPU count")
}
}
var defaultInstanceRAM int
if cfg.IsSet("INSTANCE_RAM") {
defaultInstanceRAM, err = strconv.Atoi(cfg.Get("INSTANCE_RAM"))
if err != nil {
return nil, errors.Wrap(err, "error parsing image RAM amount")
}
}
return &jupiterBrainProvider{
sshDialer: sshDialer,
sshDialTimeout: sshDialTimeout,
keychainPassword: keychainPassword,
bootPollSleep: bootPollSleep,
bootPollDialTimeout: bootPollDialTimeout,
bootPollWaitForError: bootPollWaitForError,
imageSelectorType: imageSelectorType,
imageSelector: imageSelector,
defaultInstanceCPUs: defaultInstanceCPUs,
defaultInstanceRAM: defaultInstanceRAM,
apiClient: &jupiterBrainAPIClient{
client: http.DefaultClient,
baseURL: baseURL,
},
}, nil
}
func buildJupiterBrainImageSelector(selectorType string, cfg *config.ProviderConfig) (image.Selector, error) {
switch selectorType {
case "env":
return image.NewEnvSelector(cfg)
case "api":
baseURL, err := url.Parse(cfg.Get("IMAGE_SELECTOR_URL"))
if err != nil {
return nil, errors.Wrap(err, "error parsing image selector URL")
}
return image.NewAPISelector(baseURL), nil
default:
return nil, fmt.Errorf("invalid image selector type %q", selectorType)
}
}
func (p *jupiterBrainProvider) SupportsProgress() bool {
return true
}
func (p *jupiterBrainProvider) Start(ctx gocontext.Context, startAttributes *StartAttributes) (Instance, error) {
return p.StartWithProgress(ctx, startAttributes, NewTextProgresser(nil))
}
func (p *jupiterBrainProvider) StartWithProgress(ctx gocontext.Context, startAttributes *StartAttributes, progresser Progresser) (Instance, error) {
var (
imageName string
err error
)
if startAttributes.ImageName != "" {
imageName = startAttributes.ImageName
} else {
imageName, err = p.getImageName(ctx, startAttributes)
if err != nil {
progresser.Progress(&ProgressEntry{
Message: "could not select image",
State: ProgressFailure,
})
return nil, errors.Wrap(err, "couldn't get image name")
}
}
progresser.Progress(&ProgressEntry{
Message: fmt.Sprintf("selected image %q", imageName),
State: ProgressSuccess,
})
logger := context.LoggerFromContext(ctx).WithField("self", "backend/jupiterbrain_provider")
logger.WithFields(logrus.Fields{
"image_name": imageName,
"osx_image": startAttributes.OsxImage,
"language": startAttributes.Language,
"dist": startAttributes.Dist,
"group": startAttributes.Group,
"os": startAttributes.OS,
}).Info("selected image name")
startBooting := time.Now()
// Start the instance
instancePayload, err := p.apiClient.Start(ctx, imageName, p.defaultInstanceCPUs, p.defaultInstanceRAM)
if err != nil {
progresser.Progress(&ProgressEntry{
Message: "could not create instance",
State: ProgressFailure,
})
return nil, errors.Wrap(err, "error creating instance in Jupiter Brain")
}
progresser.Progress(&ProgressEntry{
Message: "started instance",
State: ProgressSuccess,
})
progresser.Progress(&ProgressEntry{
Message: fmt.Sprintf("sleeping %s before checking instance start", p.bootPollSleep),
State: ProgressNeutral,
})
// Sleep to allow the new instance to be fully visible
time.Sleep(p.bootPollSleep)
progresser.Progress(&ProgressEntry{
Message: "polling for instance start completion...",
State: ProgressNeutral,
Continues: true,
})
// Wait for instance to get IP address
ip, payload, err := p.waitForIP(ctx, instancePayload.ID, progresser)
if err != nil {
if ctx.Err() == gocontext.DeadlineExceeded {
progresser.Progress(&ProgressEntry{
Message: "timeout waiting for instance to be ready",
State: ProgressFailure,
Interrupts: true,
})
metrics.Mark("worker.vm.provider.jupiterbrain.boot.timeout")
}
instance := &jupiterBrainInstance{
payload: instancePayload,
provider: p,
progresser: progresser,
}
instance.Stop(ctx)
return nil, err
}
progresser.Progress(&ProgressEntry{
Message: "waiting for ssh connectivity...",
State: ProgressNeutral,
Interrupts: true,
Continues: true,
})
// Wait for SSH to be ready
err = p.waitForSSH(ctx, ip, progresser)
if err != nil {
if ctx.Err() == gocontext.DeadlineExceeded {
metrics.Mark("worker.vm.provider.jupiterbrain.boot.timeout")
}
instance := &jupiterBrainInstance{
payload: instancePayload,
provider: p,
progresser: progresser,
}
instance.Stop(ctx)
return nil, err
}
timeToSsh := time.Now().UTC().Sub(startBooting).Truncate(time.Millisecond)
progresser.Progress(&ProgressEntry{
Message: fmt.Sprintf("instance is ready (%s)", timeToSsh),
State: ProgressSuccess,
Interrupts: true,
})
metrics.TimeSince("worker.vm.provider.jupiterbrain.boot", startBooting)
normalizedImageName := string(metricNameCleanRegexp.ReplaceAll([]byte(imageName), []byte("-")))
metrics.TimeSince(fmt.Sprintf("worker.vm.provider.jupiterbrain.boot.image.%s", normalizedImageName), startBooting)
logger.WithField("instance_uuid", payload.ID).Info("booted instance")
if payload.BaseImage == "" {
payload.BaseImage = imageName
}
return &jupiterBrainInstance{
payload: payload,
provider: p,
progresser: progresser,
startupDuration: time.Now().UTC().Sub(startBooting),
}, nil
}
func (p *jupiterBrainProvider) Setup(ctx gocontext.Context) error {
return nil
}
func (i *jupiterBrainInstance) Warmed() bool {
return false
}
func (i *jupiterBrainInstance) SupportsProgress() bool {
return true
}
func (i *jupiterBrainInstance) UploadScript(ctx gocontext.Context, script []byte) error {
waitStart := time.Now().UTC()
i.progresser.Progress(&ProgressEntry{
Message: "waiting for ssh connectivity...",
State: ProgressNeutral,
Continues: true,
})
conn, err := i.sshConnection()
if err != nil {
return errors.Wrap(err, "couldn't connect to SSH server")
}
defer conn.Close()
timeToSsh := time.Now().UTC().Sub(waitStart).Truncate(time.Millisecond)
i.progresser.Progress(&ProgressEntry{
Message: fmt.Sprintf("ssh connectivity established (%s)", timeToSsh),
State: ProgressSuccess,
Interrupts: true,
})
existed, err := conn.UploadFile("build.sh", script)
if existed {
i.progresser.Progress(&ProgressEntry{
Message: "existing script detected",
State: ProgressFailure,
Interrupts: true,
})
return ErrStaleVM
}
if err != nil {
return errors.Wrap(err, "couldn't upload build script")
}
i.progresser.Progress(&ProgressEntry{
Message: "uploaded script",
State: ProgressSuccess,
})
_, err = conn.UploadFile("wrapper.sh", []byte(wrapperSh))
if err != nil {
return errors.Wrap(err, "couldn't upload wrapper.sh script")
}
i.progresser.Progress(&ProgressEntry{
Message: "uploaded wrapper.sh script",
State: ProgressSuccess,
})
return nil
}
func (i *jupiterBrainInstance) RunScript(ctx gocontext.Context, output io.Writer) (*RunResult, error) {
conn, err := i.sshConnection()
if err != nil {
return &RunResult{Completed: false}, errors.Wrap(err, "couldn't connect to SSH server")
}
defer conn.Close()
resultChan := make(chan struct {
exitStatus int32
err error
}, 1)
go func() {
exitStatus, err := conn.RunCommand("bash ~/wrapper.sh", output)
resultChan <- struct {
exitStatus int32
err error
}{
exitStatus,
err,
}
}()
select {
case <-ctx.Done():
return &RunResult{Completed: false}, ctx.Err()
case result := <-resultChan:
return &RunResult{Completed: result.err != nil, ExitCode: result.exitStatus}, errors.Wrap(err, "error running script")
}
}
func (i *jupiterBrainInstance) DownloadTrace(ctx gocontext.Context) ([]byte, error) {
conn, err := i.sshConnection()
if err != nil {
return nil, errors.Wrap(err, "couldn't connect to SSH server")
}
defer conn.Close()
buf, err := conn.DownloadFile("/tmp/build.trace")
if err != nil {
return nil, errors.Wrap(err, "couldn't download trace")
}
return buf, nil
}
func (i *jupiterBrainInstance) Stop(ctx gocontext.Context) error {
err := i.provider.apiClient.Stop(ctx, i.payload.ID)
return errors.Wrap(err, "error sending Stop request to Jupiter Brain")
}
func (i *jupiterBrainInstance) ID() string {
if i.payload == nil {
return "{unidentified}"
}
return i.payload.ID
}
func (i *jupiterBrainInstance) ImageName() string {
if i.payload == nil {
return "{unidentified}"
}
return i.payload.BaseImage
}
func (i *jupiterBrainInstance) StartupDuration() time.Duration {
return i.startupDuration
}
func (i *jupiterBrainInstance) sshConnection() (ssh.Connection, error) {
var ip net.IP
for _, ipString := range i.payload.IPAddresses {
curIP := net.ParseIP(ipString)
if curIP.To4() != nil {
ip = curIP
break
}
}
if ip == nil {
return nil, errors.Errorf("no valid IPv4 address")
}
return i.provider.sshDialer.Dial(fmt.Sprintf("%s:22", ip.String()), "travis", i.provider.sshDialTimeout)
}
func (p *jupiterBrainProvider) getImageName(ctx gocontext.Context, startAttributes *StartAttributes) (string, error) {
defer context.TimeSince(ctx, "image_select", time.Now())
jobID, _ := context.JobIDFromContext(ctx)
repo, _ := context.RepositoryFromContext(ctx)
return p.imageSelector.Select(ctx, &image.Params{
Infra: "jupiterbrain",
Language: startAttributes.Language,
OsxImage: startAttributes.OsxImage,
Dist: startAttributes.Dist,
Group: startAttributes.Group,
OS: startAttributes.OS,
JobID: jobID,
Repo: repo,
})
}
func (p *jupiterBrainProvider) waitForIP(ctx gocontext.Context, id string, progresser Progresser) (net.IP, *jupiterBrainInstancePayload, error) {
defer context.TimeSince(ctx, "boot_poll_ip", time.Now())
for {
if ctx.Err() != nil {
progresser.Progress(&ProgressEntry{
Message: "cancelling waiting for instance start",
State: ProgressFailure,
Interrupts: true,
})
return nil, nil, errors.Errorf("cancelling waiting for instance to boot, was waiting for IP")
}
payload, err := p.apiClient.Get(ctx, id)
if err != nil {
progresser.Progress(&ProgressEntry{
Message: "could not check for instance start",
State: ProgressFailure,
Interrupts: true,
})
return nil, nil, errors.Wrap(err, "error trying to refresh instance waiting for IP address")
}
for _, ipString := range payload.IPAddresses {
curIP := net.ParseIP(ipString)
if curIP.To4() != nil {
return curIP, payload, nil
}
}
progresser.Progress(&ProgressEntry{Message: ".", Raw: true})
select {
case <-time.After(p.bootPollSleep):
case <-ctx.Done():
}
}
}
func (p *jupiterBrainProvider) waitForSSH(ctx gocontext.Context, ip net.IP, progresser Progresser) error {
defer context.TimeSince(ctx, "boot_poll_ssh", time.Now())
for {
if ctx.Err() != nil {
return errors.Errorf("cancelling waiting for instance to boot, was waiting for SSH to come up")
}
dialer := &net.Dialer{
Timeout: p.bootPollDialTimeout,
}
conn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("%s:22", ip.String()))
if conn != nil {
conn.Close()
}
if err == nil {
return nil
}
progresser.Progress(&ProgressEntry{Message: ".", Raw: true})
select {
case <-time.After(p.bootPollSleep):
case <-ctx.Done():
}
}
}
type jupiterBrainAPIClient struct {
client *http.Client
baseURL *url.URL
}
func (ac *jupiterBrainAPIClient) Start(ctx gocontext.Context, baseImage string, cpus int, ram int) (*jupiterBrainInstancePayload, error) {
bodyPayload := map[string]map[string]interface{}{
"data": {
"type": "instances",
"base-image": baseImage,
},
}
if cpus != 0 {
bodyPayload["data"]["cpus"] = cpus
}
if ram != 0 {
bodyPayload["data"]["ram"] = ram
}
jsonBody, err := json.Marshal(bodyPayload)
if err != nil {
return nil, errors.Wrap(err, "couldn't marshal instance create request to JSON")
}
u, err := ac.baseURL.Parse("instances")
if err != nil {
return nil, errors.Wrap(err, "couldn't create create-instance URL")
}
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(jsonBody))
if err != nil {
return nil, errors.Wrap(err, "couldn't create instance create request")
}
req.Header.Set("Content-Type", "application/vnd.api+json")
resp, err := ac.httpDo(req)
if err != nil {
return nil, errors.Wrap(err, "error sending create instance request")
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
return nil, errors.Errorf("expected 2xx from Jupiter Brain API, got %d (error: %s)", resp.StatusCode, body)
}
dataPayload := &jupiterBrainDataResponse{}
err = json.NewDecoder(resp.Body).Decode(dataPayload)
if err != nil {
return nil, errors.Wrap(err, "couldn't decode payload from Jupiter Brain")
}
if len(dataPayload.Data) != 1 {
return nil, errors.Wrapf(err, "expected 1 instance to be returned, but got %d", len(dataPayload.Data))
}
return dataPayload.Data[0], nil
}
func (ac *jupiterBrainAPIClient) Get(ctx gocontext.Context, id string) (*jupiterBrainInstancePayload, error) {
u, err := ac.baseURL.Parse(fmt.Sprintf("instances/%s", url.QueryEscape(id)))
if err != nil {
return nil, errors.Wrap(err, "couldn't create fetch-instance URL")
}
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "couldn't create instance fetch request")
}
resp, err := ac.httpDo(req)
if err != nil {
return nil, errors.Wrap(err, "error sending fetch instance request")
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := ioutil.ReadAll(resp.Body)
return nil, errors.Errorf("unknown status code: %d, expected 200 (body: %q)", resp.StatusCode, string(body))
}
dataPayload := &jupiterBrainDataResponse{}
err = json.NewDecoder(resp.Body).Decode(dataPayload)
if err != nil {
_ = resp.Body.Close()
return nil, errors.Wrap(err, "couldn't decode payload from Jupiter Brain")
}
if len(dataPayload.Data) != 1 {
return nil, errors.Wrapf(err, "expected 1 instance to be returned, but got %d", len(dataPayload.Data))
}
return dataPayload.Data[0], nil
}
func (ac *jupiterBrainAPIClient) Stop(ctx gocontext.Context, id string) error {
u, err := ac.baseURL.Parse(fmt.Sprintf("instances/%s", url.QueryEscape(id)))
if err != nil {
return errors.Wrap(err, "error creating instance stop URL")
}
req, err := http.NewRequest("DELETE", u.String(), nil)
if err != nil {
return errors.Wrap(err, "error creating instance stop request")
}
resp, err := ac.httpDo(req)
if err != nil {
return errors.Wrap(err, "error sending instance stop request")
}
resp.Body.Close()
return nil
}
func (ac *jupiterBrainAPIClient) httpDo(req *http.Request) (*http.Response, error) {
if req.URL.User != nil {
token := req.URL.User.Username()
req.URL.User = nil
req.Header.Set("Authorization", "token "+token)
}
var resp *http.Response
b := backoff.NewExponentialBackOff()
b.MaxInterval = 10 * time.Second
b.MaxElapsedTime = time.Minute
err := backoff.Retry(func() (err error) {
resp, err = ac.client.Do(req)
return
}, b)
return resp, err
}