@@ -8,8 +8,10 @@ import (
8
8
"net/http"
9
9
"time"
10
10
11
- "github.com/nais/device/pkg/bootstrap"
12
11
log "github.com/sirupsen/logrus"
12
+
13
+ "github.com/nais/device/pkg/bootstrap"
14
+ "github.com/nais/device/pkg/ioconvenience"
13
15
)
14
16
15
17
func BootstrapDevice (deviceInfo * bootstrap.DeviceInfo , bootstrapAPI string , client * http.Client ) (* bootstrap.Config , error ) {
@@ -35,11 +37,12 @@ func postDeviceInfo(url string, deviceInfo *bootstrap.DeviceInfo, client *http.C
35
37
}
36
38
37
39
resp , err := client .Post (url , "application/json" , bytes .NewReader (dib ))
38
-
39
40
if err != nil {
40
41
return fmt .Errorf ("posting device info to bootstrap API (%v): %w" , url , err )
41
42
}
42
43
44
+ defer ioconvenience .CloseReader (resp .Body )
45
+
43
46
if resp .StatusCode != http .StatusCreated {
44
47
body , err := ioutil .ReadAll (resp .Body )
45
48
if err != nil {
@@ -53,20 +56,40 @@ func postDeviceInfo(url string, deviceInfo *bootstrap.DeviceInfo, client *http.C
53
56
}
54
57
55
58
func getBootstrapConfig (url string , client * http.Client ) (* bootstrap.Config , error ) {
59
+ get := func () (* bootstrap.Config , error ) {
60
+ resp , err := client .Get (url )
61
+ if err != nil {
62
+ return nil , err
63
+ }
64
+
65
+ defer ioconvenience .CloseReader (resp .Body )
66
+
67
+ if resp .StatusCode != 200 {
68
+ return nil , fmt .Errorf ("got statuscode %d from bootstrap api" , resp .StatusCode )
69
+ }
70
+
71
+ bootstrapConfig := & bootstrap.Config {}
72
+ err = json .NewDecoder (resp .Body ).Decode (bootstrapConfig )
73
+ if err != nil {
74
+ return nil , err
75
+ }
76
+
77
+ return bootstrapConfig , nil
78
+ }
79
+
56
80
attempts := 3
57
81
58
82
for i := 0 ; i < attempts ; i ++ {
59
- resp , err := client .Get (url )
60
-
61
- if err == nil && resp .StatusCode == 200 {
62
- var bootstrapConfig bootstrap.Config
63
- if err := json .NewDecoder (resp .Body ).Decode (& bootstrapConfig ); err == nil {
64
- log .Debugf ("Got bootstrap config from bootstrap api: %v" , bootstrapConfig )
65
- return & bootstrapConfig , nil
66
- }
83
+ bootstrapConfig , err := get ()
84
+ if err != nil {
85
+ log .Warnf ("Attempt %d/%d at getting bootstrap config failed: %s" , i + 1 , attempts , err )
86
+ time .Sleep (1 * time .Second )
87
+ continue
67
88
}
68
- time .Sleep (1 * time .Second )
69
- continue
89
+
90
+ log .Debugf ("Got bootstrap config from bootstrap api: %v" , bootstrapConfig )
91
+ return bootstrapConfig , nil
70
92
}
93
+
71
94
return nil , fmt .Errorf ("unable to get boostrap config in %v attempts from %v" , attempts , url )
72
95
}
0 commit comments