forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_metadata_service.go
315 lines (264 loc) · 8.37 KB
/
http_metadata_service.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
package infrastructure
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
boshplat "github.com/cloudfoundry/bosh-agent/platform"
boshsettings "github.com/cloudfoundry/bosh-agent/settings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
"github.com/cloudfoundry/bosh-utils/httpclient"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
type HTTPMetadataService struct {
client *httpclient.HTTPClient
metadataHost string
metadataHeaders map[string]string
userdataPath string
instanceIDPath string
sshKeysPath string
resolver DNSResolver
platform boshplat.Platform
logTag string
logger boshlog.Logger
}
func NewHTTPMetadataService(
metadataHost string,
metadataHeaders map[string]string,
userdataPath string,
instanceIDPath string,
sshKeysPath string,
resolver DNSResolver,
platform boshplat.Platform,
logger boshlog.Logger,
) DynamicMetadataService {
return HTTPMetadataService{
client: createRetryClient(1*time.Second, logger),
metadataHost: metadataHost,
metadataHeaders: metadataHeaders,
userdataPath: userdataPath,
instanceIDPath: instanceIDPath,
sshKeysPath: sshKeysPath,
resolver: resolver,
platform: platform,
logTag: "httpMetadataService",
logger: logger,
}
}
func NewHTTPMetadataServiceWithCustomRetryDelay(
metadataHost string,
metadataHeaders map[string]string,
userdataPath string,
instanceIDPath string,
sshKeysPath string,
resolver DNSResolver,
platform boshplat.Platform,
logger boshlog.Logger,
retryDelay time.Duration,
) DynamicMetadataService {
return HTTPMetadataService{
client: createRetryClient(retryDelay, logger),
metadataHost: metadataHost,
metadataHeaders: metadataHeaders,
userdataPath: userdataPath,
instanceIDPath: instanceIDPath,
sshKeysPath: sshKeysPath,
resolver: resolver,
platform: platform,
logTag: "httpMetadataService",
logger: logger,
}
}
func (ms HTTPMetadataService) Load() error {
return nil
}
func (ms HTTPMetadataService) GetPublicKey() (string, error) {
if ms.sshKeysPath == "" {
return "", nil
}
err := ms.ensureMinimalNetworkSetup()
if err != nil {
return "", err
}
url := fmt.Sprintf("%s%s", ms.metadataHost, ms.sshKeysPath)
resp, err := ms.client.GetCustomized(url, ms.addHeaders())
if err != nil {
return "", bosherr.WrapErrorf(err, "Getting open ssh key from url %s", url)
}
if resp != nil && resp.StatusCode == http.StatusNotFound {
ms.logger.Warn(ms.logTag, "The open ssh keys path is not present: %s.", url)
return "", nil
}
defer func() {
if err := resp.Body.Close(); err != nil {
ms.logger.Warn(ms.logTag, "Failed to close response body when getting ssh key: %s", err.Error())
}
}()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", bosherr.WrapError(err, "Reading ssh key response body")
}
return string(bytes), nil
}
func (ms HTTPMetadataService) GetInstanceID() (string, error) {
if ms.instanceIDPath == "" {
return "", nil
}
err := ms.ensureMinimalNetworkSetup()
if err != nil {
return "", err
}
url := fmt.Sprintf("%s%s", ms.metadataHost, ms.instanceIDPath)
resp, err := ms.client.GetCustomized(url, ms.addHeaders())
if err != nil {
return "", bosherr.WrapErrorf(err, "Getting instance id from url %s", url)
}
defer func() {
if err := resp.Body.Close(); err != nil {
ms.logger.Warn(ms.logTag, "Failed to close response body when getting instance id: %s", err.Error())
}
}()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", bosherr.WrapError(err, "Reading instance id response body")
}
return string(bytes), nil
}
func (ms HTTPMetadataService) GetValueAtPath(path string) (string, error) {
if path == "" {
return "", fmt.Errorf("Can not retrieve metadata value for empty path")
}
err := ms.ensureMinimalNetworkSetup()
if err != nil {
return "", err
}
url := fmt.Sprintf("%s%s", ms.metadataHost, path)
resp, err := ms.client.GetCustomized(url, ms.addHeaders())
if err != nil {
return "", bosherr.WrapErrorf(err, "Getting value from url %s", url)
}
defer func() {
if err := resp.Body.Close(); err != nil {
ms.logger.Warn(ms.logTag, "Failed to close response body when getting value from path: %s", err.Error())
}
}()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", bosherr.WrapError(err, fmt.Sprintf("Reading response body from %s", url))
}
return string(bytes), nil
}
func (ms HTTPMetadataService) GetServerName() (string, error) {
userData, err := ms.getUserData()
if err != nil {
return "", bosherr.WrapError(err, "Getting user data")
}
serverName := userData.Server.Name
if len(serverName) == 0 {
return "", bosherr.Error("Empty server name")
}
return serverName, nil
}
func (ms HTTPMetadataService) GetRegistryEndpoint() (string, error) {
userData, err := ms.getUserData()
if err != nil {
return "", bosherr.WrapError(err, "Getting user data")
}
endpoint := userData.Registry.Endpoint
nameServers := userData.DNS.Nameserver
if len(nameServers) > 0 {
endpoint, err = ms.resolver.LookupHost(nameServers, endpoint)
if err != nil {
return "", bosherr.WrapError(err, "Resolving registry endpoint")
}
}
return endpoint, nil
}
func (ms HTTPMetadataService) GetNetworks() (boshsettings.Networks, error) {
return nil, nil
}
func (ms HTTPMetadataService) IsAvailable() bool { return true }
func (ms HTTPMetadataService) GetSettings() (boshsettings.Settings, error) {
userData, err := ms.getUserData()
if err != nil {
return boshsettings.Settings{}, bosherr.WrapError(err, "Getting user data")
}
settings := userData.Settings
if settings.AgentID == "" {
return boshsettings.Settings{}, bosherr.Error("Metadata does not provide settings")
}
return settings, nil
}
func (ms HTTPMetadataService) getUserData() (UserDataContentsType, error) {
var userData UserDataContentsType
err := ms.ensureMinimalNetworkSetup()
if err != nil {
return userData, err
}
userDataURL := fmt.Sprintf("%s%s", ms.metadataHost, ms.userdataPath)
userDataResp, err := ms.client.GetCustomized(userDataURL, ms.addHeaders())
if err != nil {
return userData, bosherr.WrapErrorf(err, "request failed from url %s", userDataURL)
}
defer userDataResp.Body.Close()
if !isSuccessful(userDataResp) {
return userData, fmt.Errorf("invalid status from url %s: %d", userDataURL, userDataResp.StatusCode)
}
userDataBytes, err := ioutil.ReadAll(userDataResp.Body)
if err != nil {
return userData, bosherr.WrapError(err, "Reading user data response body")
}
err = json.Unmarshal(userDataBytes, &userData)
if err != nil {
userDataBytesWithoutQuotes := strings.Replace(string(userDataBytes), `"`, ``, -1)
decodedUserData, err := base64.RawURLEncoding.DecodeString(userDataBytesWithoutQuotes)
if err != nil {
return userData, bosherr.WrapError(err, "Decoding url encoded user data")
}
err = json.Unmarshal([]byte(decodedUserData), &userData)
if err != nil {
return userData, bosherr.WrapErrorf(err, "Unmarshalling url decoded user data '%s'", decodedUserData)
}
}
return userData, nil
}
func (ms HTTPMetadataService) ensureMinimalNetworkSetup() error {
// We check for configuration presence instead of verifying
// that network is reachable because we want to preserve
// network configuration that was passed to agent.
configuredInterfaces, err := ms.platform.GetConfiguredNetworkInterfaces()
if err != nil {
return bosherr.WrapError(err, "Getting configured network interfaces")
}
if len(configuredInterfaces) == 0 {
ms.logger.Debug(ms.logTag, "No configured networks found, setting up DHCP network")
err = ms.platform.SetupNetworking(boshsettings.Networks{
"eth0": {
Type: boshsettings.NetworkTypeDynamic,
},
})
if err != nil {
return bosherr.WrapError(err, "Setting up initial DHCP network")
}
}
return nil
}
func (ms HTTPMetadataService) addHeaders() func(*http.Request) {
return func(req *http.Request) {
for key, value := range ms.metadataHeaders {
req.Header.Add(key, value)
}
}
}
func createRetryClient(delay time.Duration, logger boshlog.Logger) *httpclient.HTTPClient {
return httpclient.NewHTTPClient(
httpclient.NewRetryClient(
httpclient.CreateDefaultClient(nil), 10, delay, logger),
logger)
}
func isSuccessful(resp *http.Response) bool {
return resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices
}