/
create.go
428 lines (343 loc) · 10.3 KB
/
create.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
package ops
import (
"crypto/tls"
"fmt"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/pkg/errors"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"runtime"
"text/tabwriter"
"time"
)
const ERR_SSH_GENERAL = "SSH error. Is your ssh-agent running? Keys loaded? Can't bootstrap Orion PTT System without it."
var TESTING bool
// Create Instantiates an instance of the Orion PTT System in AWS via CloudFormation
func (s *Stack) Create(stageOnly bool) (err error) {
exists := s.Exists()
if exists {
err = errors.New(fmt.Sprintf("Stack %s already exists.", s.Config.StackName))
return err
}
totalStart := time.Now()
fmt.Printf("Creating stack %q.\n", s.Config.StackName)
// Initialize the CF stack
_, err = s.Init()
if err != nil {
err = errors.Wrapf(err, "Failed creating stack %q", s.Config.StackName)
return err
}
fmt.Printf("Stack initialized. Polling for status.\n")
start := time.Now()
fmt.Printf("Checking Status\n")
// Poll CloudFormation for status
rollback := false
_, err = RetryUntil(func() (err error) {
status, err := s.Status()
if err != nil {
return err
}
err = errors.New(status)
if status == "CREATE_COMPLETE" {
err = nil
}
if status == "ROLLBACK_COMPLETE" {
rollback = true
err = nil
}
return err
}, 15)
// Stack creation might fail and auto-rollback. If that happens we need to destroy the stack. If we don't, then the stack will need to be manually destroyed, which is annoying.
if s.AutoRollback {
if rollback {
fmt.Printf("Init failed. Deleting Stack %q.\n", s.Config.StackName)
err = s.Delete()
if err != nil {
err = errors.Wrapf(err, "failed destroying stack %s", s.Config.StackName)
return err
}
fmt.Printf("Checking Status\n")
dur, err := RetryUntil(func() (err error) {
status, err := s.Status()
if err != nil {
fmt.Printf(" DELETE_COMPLETE\n")
return nil
} else {
err = errors.New(status)
}
return err
}, 15)
if err != nil {
}
fmt.Printf("Stack Deletion took %f minutes.\n", dur.Minutes())
os.Exit(0)
}
}
finish := time.Now()
dur := finish.Sub(start)
fmt.Printf("Stack Creation took %f minutes.\n", dur.Minutes())
// Get the Outputs so we can check the various services for readiness
var address string
var caHost string
var datastore string
var eventstream string
var media string
var api string
var login string
var cdn string
// fetch the stack outputs from CF
outputs, err := s.Outputs()
if err != nil {
err = errors.Wrapf(err, "Error fetching Stack Outputs")
return err
}
for _, o := range outputs {
switch *o.OutputKey {
case "Address":
address = *o.OutputValue
case "Datastore":
datastore = *o.OutputValue
case "EventStream":
eventstream = *o.OutputValue
case "Media":
media = *o.OutputValue
case "Login":
login = *o.OutputValue
case "Api":
api = *o.OutputValue
case "CDN":
cdn = *o.OutputValue
case "CA":
caHost = *o.OutputValue
}
}
// a programmatic SSH client we can use to perform the rest of the work
sshClient, err := SshClient(address, 22, s.Config.Username)
if err != nil {
err = errors.Wrapf(err, "failed to create client")
return err
}
err = s.StageLicense(sshClient)
if err != nil {
err = errors.Wrapf(err, "failed staging license file")
//err = errors.New(ERR_SSH_GENERAL)
return err
}
// Create and stage the config file.
err = s.StageConfig(sshClient)
if err != nil {
err = errors.Wrapf(err, "failed staging kots config")
//err = errors.New(ERR_SSH_GENERAL)
return err
}
// Exit early after staging files if told to do so
if stageOnly {
return
}
// Poll kotsadm console
err = s.PollKotsadmConsole(address)
if err != nil {
err = errors.Wrapf(err, "failed polling kotsadm")
return err
}
// Poll for presence of kotsadm itself
err = s.PollKotsadm(sshClient)
// Install Kots app
err = s.KotsInstall(sshClient)
if err != nil {
err = errors.Wrapf(err, "failed installing kots app")
return err
}
// Check the CA endpoint
err = s.PollEndpoint(fmt.Sprintf("https://%s/v1/pki/ca/pem", caHost))
if err != nil {
err = errors.Wrapf(err, "failed polliing CA endpoint")
return err
}
// Check API
err = s.PollEndpoint(fmt.Sprintf("https://%s", api))
if err != nil {
err = errors.Wrapf(err, "failed polliing api endpoint")
return err
}
// Check Login
err = s.PollEndpoint(fmt.Sprintf("https://%s", login))
if err != nil {
err = errors.Wrapf(err, "failed polliing login endpoint")
return err
}
// Check Media
err = s.PollEndpoint(fmt.Sprintf("https://%s", media))
if err != nil {
err = errors.Wrapf(err, "failed polliing media endpoint")
return err
}
// Check Datastore
err = s.PollEndpoint(fmt.Sprintf("https://%s", datastore))
if err != nil {
err = errors.Wrapf(err, "failed polliing datastore endpoint")
return err
}
// Check Eventstream
err = s.PollEndpoint(fmt.Sprintf("https://%s", eventstream))
if err != nil {
err = errors.Wrapf(err, "failed polliing eventstream endpoint")
return err
}
// Check CDN
err = s.PollEndpoint(fmt.Sprintf("https://%s", cdn))
if err != nil {
err = errors.Wrapf(err, "failed polliing cdn endpoint")
return err
}
err = s.TrustCA(caHost)
if err != nil {
err = errors.Wrapf(err, "failed to fetch CA cert.")
return err
}
// Show the outputs
s.PrintOutputs(outputs)
totalFinish := time.Now()
dur = totalFinish.Sub(totalStart)
fmt.Printf("\n\nEnd to end creation took %f minutes.\n\nHappy Hacking!\n\n", dur.Minutes())
if !TESTING {
if runtime.GOOS == "darwin" {
cmd := exec.Command("open", fmt.Sprintf("https://%s", login))
err = cmd.Run()
if err != nil {
err = errors.Wrapf(err, "Failed to open login url")
return err
}
}
}
return err
}
func (s *Stack) PrintOutputs(outputs []*cloudformation.Output) {
fmt.Printf("Stack Outputs:\n")
w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
for _, o := range outputs {
_, _ = fmt.Fprintf(w, " %s: \t %s\n", *o.OutputKey, *o.OutputValue)
}
_ = w.Flush()
}
func (s *Stack) PollEndpoint(address string) (err error) {
fmt.Printf("Now polling the endpoint %s.\n\n", address)
dur, err := RetryUntil(func() (err error) {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
_, err = http.Get(address)
return err
}, 15)
fmt.Printf("Service initialization took %f minutes.\n", dur.Minutes())
return err
}
func (s *Stack) PollKotsadmConsole(address string) (err error) {
consoleUrl := fmt.Sprintf("http://%s:8800", address)
fmt.Printf("Polling %s for Kotsadm to be ready.\n", consoleUrl)
dur, err := RetryUntil(func() (err error) {
return s.PollEndpoint(consoleUrl)
}, 15)
if err != nil {
err = errors.Wrapf(err, "failed polling kotsadm")
return err
}
fmt.Printf("Kubernetes installation took %f minutes.\n", dur.Minutes())
return err
}
func (s *Stack) PollKotsadm(sshClient *SshProgClient) (err error) {
fmt.Printf("Polling %s for the kots plugin to be installed.\n", sshClient.Host)
// just check to see if the binary exists
cmd := "kubectl kots --help"
_, err = RetryUntil(
func() (err error) {
return sshClient.RpcCall([]byte(cmd), os.Stdout, os.Stderr)
}, 5)
return err
}
func (s *Stack) KotsInstall(sshClient *SshProgClient) (err error) {
start := time.Now()
cmd := fmt.Sprintf("sudo -i kubectl kots install orion-ptt-system --license-file /home/%s/license.yaml --namespace default --config-values /home/%s/config.yaml --shared-password %q", s.Config.Username, s.Config.Username, s.Config.KotsadmPassword)
fmt.Printf("Installing Kots app with the following command:\n\n %s\n\nThis will take a couple minutes.\n\n", cmd)
err = sshClient.RpcCall([]byte(cmd), os.Stdout, os.Stderr)
if err != nil {
err = errors.Wrapf(err, "error running kots install")
return err
}
finish := time.Now()
dur := finish.Sub(start)
fmt.Printf("Kots installation took %f minutes.\n\n", dur.Minutes())
return err
}
func (s *Stack) StageConfig(sshClient *SshProgClient) (err error) {
configContent, err := s.CreateConfig()
if err != nil {
err = errors.Wrapf(err, "failed creating config from template")
return err
}
err = sshClient.SCPFile(configContent, "config.yaml")
if err != nil {
err = errors.Wrapf(err, "Error staging config file")
return err
}
fmt.Printf("Config staged to /home/%s/config.yaml\n", s.Config.Username)
return err
}
func (s *Stack) StageLicense(sshClient *SshProgClient) (err error) {
fmt.Printf("Staging license file via ssh %s@%s:22\n", s.Config.Username, sshClient.Host)
licenseContentBytes, err := ioutil.ReadFile(s.Config.LicenseFile)
if err != nil {
err = errors.Wrapf(err, "failed to read file %s", s.Config.LicenseFile)
return err
}
licenseContent := string(licenseContentBytes)
_, err = RetryUntil(func() (err error) {
err = sshClient.SCPFile(licenseContent, "license.yaml")
return err
}, 5)
fmt.Printf("License staged to /home/%s/license.yaml\n", s.Config.Username)
return err
}
func (s *Stack) TrustCA(host string) (err error) {
caURL := fmt.Sprintf("https://%s/v1/pki/ca/pem", host)
fmt.Printf("Fetching CA Certificate from: %s\n", caURL)
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
resp, err := http.Get(caURL)
if err != nil {
err = errors.Wrapf(err, "failed to fetch CA certificate from %s", caURL)
return err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
certBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Failed to read CA certificate from response body: %s", err)
}
fileName := fmt.Sprintf("%s-ca.pem", host)
err = ioutil.WriteFile(fileName, certBytes, 0644)
if err != nil {
log.Fatalf("Failed to write %s: %s", fileName, err)
}
fmt.Printf("CA certificate written to: %s\n\n", fileName)
if !TESTING {
if runtime.GOOS == "darwin" {
fmt.Printf("Importing to keychain\n")
sudo, err := exec.LookPath("sudo")
if err != nil {
log.Fatalf("'sudo' tool not found: %s", err)
}
cmd := exec.Command(sudo, "security", "add-trusted-cert", "-d", "-r", "trustRoot", "-k", "/Library/Keychains/System.keychain", fileName)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err = cmd.Run()
if err != nil {
log.Fatalf("error trusting CA cert: %s", err)
}
}
}
}
fmt.Printf("CA trusted. You should be good to go.\n")
return err
}