forked from Netflix/chaosmonkey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spinnaker.go
453 lines (377 loc) · 12.3 KB
/
spinnaker.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
// Copyright 2016 Netflix, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package spinnaker provides an interface to the Spinnaker API
package spinnaker
import (
"crypto/tls"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"golang.org/x/crypto/pkcs12"
"github.com/pkg/errors"
"github.com/Netflix/chaosmonkey"
"github.com/Netflix/chaosmonkey/config"
D "github.com/Netflix/chaosmonkey/deploy"
"github.com/Netflix/chaosmonkey/deps"
)
// Spinnaker implements the deploy.Deployment interface by querying Spinnaker
// and the chaosmonkey.Termination interface by terminating via Spinnaker API
// calls
type Spinnaker struct {
endpoint string
client *http.Client
user string
}
// spinnakerClusters maps account name (e.g., "prod", "test") to a list
// of cluster names
type spinnakerClusters map[string][]string
// spinnakerServerGroup represents an autoscaling group, also called a server group,
// as represented by Spinnaker API
type spinnakerServerGroup struct {
Name string
Region string
Disabled bool
Instances []spinnakerInstance
}
// spinnakerInstance represents an instance as represented by Spinnaker API
type spinnakerInstance struct {
Name string
}
// getClient takes PKCS#12 data (encrypted cert data in .p12 format) and the
// password for the encrypted cert, and returns an http client that does TLS client auth
func getClient(pfxData []byte, password string) (*http.Client, error) {
blocks, err := pkcs12.ToPEM(pfxData, password)
if err != nil {
return nil, errors.Wrap(err, "pkcs.ToPEM failed")
}
// The first block is the cert and the last block is the private key
certPEMBlock := pem.EncodeToMemory(blocks[0])
keyPEMBlock := pem.EncodeToMemory(blocks[len(blocks)-1])
cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
if err != nil {
return nil, errors.Wrap(err, "tls.X509KeyPair failed")
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
transport := &http.Transport{TLSClientConfig: tlsConfig}
return &http.Client{Transport: transport}, nil
}
// NewFromConfig returns a Spinnaker based on config
func NewFromConfig(cfg *config.Monkey) (Spinnaker, error) {
spinnakerEndpoint := cfg.SpinnakerEndpoint()
certPath := cfg.SpinnakerCertificate()
encryptedPassword := cfg.SpinnakerEncryptedPassword()
user := cfg.SpinnakerUser()
if spinnakerEndpoint == "" {
return Spinnaker{}, errors.New("FATAL: no spinnaker endpoint specified in config")
}
var password string
var err error
var decryptor chaosmonkey.Decryptor
if encryptedPassword != "" {
decryptor, err = deps.GetDecryptor(cfg)
if err != nil {
return Spinnaker{}, err
}
password, err = decryptor.Decrypt(encryptedPassword)
if err != nil {
return Spinnaker{}, err
}
}
return New(spinnakerEndpoint, certPath, password, user)
}
// New returns a Spinnaker using a .p12 cert at certPath encrypted with
// password. The user argument identifies the email address of the user which is
// sent in the payload of the terminateInstances task API call
func New(endpoint string, certPath string, password string, user string) (Spinnaker, error) {
var client *http.Client
if certPath != "" {
pfxData, err := ioutil.ReadFile(certPath)
if err != nil {
return Spinnaker{}, errors.Wrapf(err, "failed to read file %s", certPath)
}
client, err = getClient(pfxData, password)
if err != nil {
return Spinnaker{}, err
}
} else {
client = new(http.Client)
}
return Spinnaker{endpoint: endpoint, client: client, user: user}, nil
}
// AccountID returns numerical ID associated with an AWS account
func (s Spinnaker) AccountID(name string) (id string, err error) {
url := s.accountURL(name)
resp, err := s.client.Get(url)
if err != nil {
return "", errors.Wrapf(err, "could not retrieve account info for %s from spinnaker url %s", name, url)
}
defer func() {
if cerr := resp.Body.Close(); cerr != nil && err == nil {
err = errors.Wrapf(err, "failed to close response body from %s", url)
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrapf(err, "failed to read body from url %s", url)
}
var info struct {
AccountID string `json:"accountId"`
Error string `json:"error"`
}
err = json.Unmarshal(body, &info)
if err != nil {
return "", errors.Wrapf(err, "could not parse body of %s as json, body: %s, error", url, body)
}
if resp.StatusCode != http.StatusOK {
if info.Error == "" {
return "", errors.Errorf("%s returned unexpected status code: %d, body: %s", url, resp.StatusCode, body)
}
return "", errors.New(info.Error)
}
// Some backends may not have associated account ids
if info.AccountID == "" {
return s.alternateAccountID(name)
}
return info.AccountID, nil
}
// alternateAccountID returns an account ID for accounts that don't have their
// own ids.
func (s Spinnaker) alternateAccountID(name string) (string, error) {
// Sanity check: this should never be called with "prod" or "test" as an
// argument, since this would result in infinite recursion
if name == "prod" || name == "test" {
return "", fmt.Errorf("alternateAccountID called with forbidden arg: %s", name)
}
// Heuristic: if account name has "test" in the name, we return the "test"
// account id, otherwise with we use the "prod" account id
if strings.Contains(name, "test") {
return s.AccountID("test")
}
return s.AccountID("prod")
}
// Apps implements deploy.Deployment.Apps
func (s Spinnaker) Apps(c chan<- *D.App, appNames []string) {
// Close the channel we're done
defer close(c)
for _, appName := range appNames {
app, err := s.GetApp(appName)
if err != nil {
// If we have a problem with one app, we go to the next one
log.Printf("WARNING: GetApp failed for %s: %v", appName, err)
continue
}
c <- app
}
}
// GetApp implements deploy.Deployment.GetApp
func (s Spinnaker) GetApp(appName string) (*D.App, error) {
// data arg is a map like {accountName: {clusterName: {regionName: {asgName: [instanceId]}}}}
data := make(D.AppMap)
for account, clusters := range s.clusters(appName) {
cloudProvider, err := s.CloudProvider(account)
if err != nil {
return nil, errors.Wrap(err, "retrieve cloud provider failed")
}
account := D.AccountName(account)
data[account] = D.AccountInfo{
CloudProvider: cloudProvider,
Clusters: make(map[D.ClusterName]map[D.RegionName]map[D.ASGName][]D.InstanceID),
}
for _, clusterName := range clusters {
clusterName := D.ClusterName(clusterName)
data[account].Clusters[clusterName] = make(map[D.RegionName]map[D.ASGName][]D.InstanceID)
asgs, err := s.asgs(appName, string(account), string(clusterName))
if err != nil {
log.Printf("WARNING: could not retrieve asgs for app:%s account:%s cluster:%s : %v", appName, account, clusterName, err)
continue
}
for _, asg := range asgs {
// We don't terminate instances in disabled ASGs
if asg.Disabled {
continue
}
region := D.RegionName(asg.Region)
asgName := D.ASGName(asg.Name)
_, present := data[account].Clusters[clusterName][region]
if !present {
data[account].Clusters[clusterName][region] = make(map[D.ASGName][]D.InstanceID)
}
data[account].Clusters[clusterName][region][asgName] = make([]D.InstanceID, len(asg.Instances))
for i, instance := range asg.Instances {
data[account].Clusters[clusterName][region][asgName][i] = D.InstanceID(instance.Name)
}
}
}
}
return D.NewApp(appName, data), nil
}
// AppNames returns list of names of all apps
func (s Spinnaker) AppNames() (appnames []string, err error) {
url := s.appsURL()
resp, err := s.client.Get(url)
if err != nil {
return nil, fmt.Errorf("could not retrieve list of apps from spinnaker url %s: %v", url, err)
}
defer func() {
if cerr := resp.Body.Close(); cerr != nil && err == nil {
err = fmt.Errorf("failed to close response body from %s: %v", url, err)
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body when retrieving spinnaker app names from %s: %v", url, err)
}
var apps []spinnakerApp
err = json.Unmarshal(body, &apps)
if err != nil {
return nil, fmt.Errorf("could not parse spinnaker apps list from %s: body: \"%s\": %v", url, string(body), err)
}
result := make([]string, len(apps))
for i, app := range apps {
result[i] = app.Name
}
return result, nil
}
// spinnakerApp returns an app as represented by the Spinnaker API
type spinnakerApp struct {
Name string
}
// clusters returns a map from account name to list of cluster names
func (s Spinnaker) clusters(appName string) spinnakerClusters {
url := s.clustersURL(appName)
resp, err := s.client.Get(url)
if err != nil {
log.Println("Error connecting to spinnaker clusters endpoint")
log.Println(url)
log.Fatalln(err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Printf("Error closing response body of %s: %v", url, err)
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Error retrieving spinnaker clusters for app", appName)
log.Println(url)
log.Println(string(body))
log.Fatalln(err)
}
// Example cluster output:
/*
{
"prod": [
"abc-prod"
],
"test": [
"abc-beta"
]
}
*/
var m spinnakerClusters
err = json.Unmarshal(body, &m)
if err != nil {
log.Println("Error parsing body when retrieving cluster info for", appName)
log.Println(url)
log.Println(string(body))
log.Fatalln(err)
}
return m
}
// asgs returns a slice of autoscaling groups associated with the given cluster
func (s Spinnaker) asgs(appName, account, clusterName string) (result []spinnakerServerGroup, err error) {
url := s.serverGroupsURL(appName, account, clusterName)
resp, err := s.client.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to retrieve server groups url (%s): %v", url, err)
}
defer func() {
if cerr := resp.Body.Close(); cerr != nil && err == nil {
err = fmt.Errorf("failed to close response body of %s: %v", url, err)
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body of server groups url (%s): body: '%s': %v", url, string(body), err)
}
// Example:
/*
[
{
"name": "abc-prod-v016",
"region": "us-east-1",
"zones": [
"us-east-1c",
"us-east-1d",
"us-east-1e"
],
"disabled": false,
"instances": [
{
"name": "i-f9ffb752",
...
},
...
]
}
]
*/
var asgs []spinnakerServerGroup
err = json.Unmarshal(body, &asgs)
if err != nil {
return nil, fmt.Errorf("failed to parse body of spinnaker asgs url (%s): body: '%s'. %v", url, string(body), err)
}
return asgs, nil
}
// CloudProvider returns the cloud provider for a given account
func (s Spinnaker) CloudProvider(account string) (provider string, err error) {
url := s.accountURL(account)
resp, err := s.client.Get(url)
if err != nil {
return "", errors.Wrap(err, fmt.Sprintf("http get failed at %s", url))
}
defer func() {
if cerr := resp.Body.Close(); cerr != nil && err == nil {
err = errors.Wrap(err, fmt.Sprintf("body close failed at %s", url))
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, fmt.Sprintf("body read failed at %s", url))
}
var fields struct {
CloudProvider string `json:"cloudProvider"`
Error string `json:"error"`
}
err = json.Unmarshal(body, &fields)
if err != nil {
return "", errors.Wrap(err, "json unmarshal failed")
}
if resp.StatusCode != http.StatusOK {
if fields.Error == "" {
return "", fmt.Errorf("unexpected status code: %d. body: %s", resp.StatusCode, body)
}
return "", fmt.Errorf("unexpected status code: %d. error: %s", resp.StatusCode, fields.Error)
}
if fields.CloudProvider == "" {
return "", fmt.Errorf("no cloudProvider field in response body")
}
return fields.CloudProvider, nil
}