-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcommands.go
745 lines (622 loc) · 17 KB
/
commands.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
package main
import (
"bytes"
"errors"
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/rosti-cz/cli/src/config"
"github.com/rosti-cz/cli/src/parser"
"github.com/rosti-cz/cli/src/rostiapi"
"github.com/rosti-cz/cli/src/scanner"
"github.com/rosti-cz/cli/src/ssh"
"github.com/rosti-cz/cli/src/state"
"github.com/urfave/cli/v2"
"golang.org/x/crypto/ssh/terminal"
"gopkg.in/yaml.v2"
)
// Import existing application
func commandImport(c *cli.Context) error {
cYellow.Println(".. loading configuration")
config := config.Load()
cYellow.Println(".. setting up API client")
client := rostiapi.Client{
Token: config.Token,
ExtraError: os.Stderr,
}
appState := state.RostiState{}
// Pick the right company
cYellow.Println(".. loading list of your companies")
companyID, err := findCompany(&client, &appState, c)
if err != nil {
return err
}
appState.CompanyID = companyID
client.CompanyID = companyID
appID, err := selectApp(&client)
if err != nil {
return err
}
appState.ApplicationID = appID
cGreen.Println(".. done")
cYellow.Println(".. writing .rosti.state")
err = state.Write(&appState)
if err != nil {
return err
}
return nil
}
// Deploys or re-deploys an application
func commandUp(c *cli.Context) error {
config := config.Load()
// Rostifile and statefile
cYellow.Println(".. loading Rostifile")
rostifile, err := parser.Parse()
if err != nil {
return err
}
client := rostiapi.Client{
Token: config.Token,
ExtraError: os.Stderr,
}
cYellow.Println(".. loading state file")
appState, err := state.Load()
if err != nil {
return err
}
defer state.Write(appState)
// SSH key
if len(appState.SSHKeyPath) == 0 {
cYellow.Println(".. SSH key not found in the state file, trying to figure this out")
privateSSHKeyPath, _, err := findSSHKey()
if err != nil {
return fmt.Errorf("SSH key problem: %w", err)
}
appState.SSHKeyPath = privateSSHKeyPath
} else {
_, err := os.Stat(appState.SSHKeyPath)
if os.IsNotExist(err) {
cYellow.Println(".. SSH key configured in state file but the file doesn't not exist, trying to figure this out")
privateSSHKeyPath, _, err := findSSHKey()
if err != nil {
return fmt.Errorf("SSH key problem: %w", err)
}
appState.SSHKeyPath = privateSSHKeyPath
}
}
// Pick the right company
if appState.CompanyID == 0 {
cYellow.Println(".. loading list of your companies")
companyID, err := findCompany(&client, appState, c)
if err != nil {
return err
}
appState.CompanyID = companyID
}
client.CompanyID = appState.CompanyID
// Select plan
planID, err := selectPlan(&client, rostifile)
if err != nil {
return err
}
// Select the right runtime
selectedRuntime, err := selectRuntime(&client, rostifile)
if err != nil {
return err
}
// Figure out mode
var mode string
if rostifile.HTTPS {
mode = "https+le"
} else {
mode = "http"
}
// Create or update the application
var newApp *rostiapi.App
var appCreated bool // if true the app was just created
// Update existing app
if appState.ApplicationID > 0 {
cYellow.Println(".. loading current state of the application")
app, err := client.GetApp(appState.ApplicationID)
if err != nil {
return err
}
// If it's down let's start it
if !app.Enabled {
cYellow.Println(".. starting the application because it was off")
err = client.DoApp(appState.ApplicationID, "start")
if err != nil {
return err
}
}
sshPubKey, err := readLocalSSHPubKey(appState.SSHPublicKeyPath())
if err != nil {
return err
}
// Use update
cYellow.Printf(".. updating existing application %s_%d \n", rostifile.Name, appState.ApplicationID)
app = rostiapi.App{
ID: appState.ApplicationID,
Name: rostifile.Name,
Image: selectedRuntime,
Domains: rostifile.Domains,
Mode: mode,
Plan: planID,
SSHKeys: []string{sshPubKey},
AppPort: rostifile.AppPort,
}
// TODO: save assigned domains into Rostifile
newApp, err = client.UpdateApp(&app)
if err != nil {
return err
}
} else {
// Create a new app
cYellow.Printf(".. creating a new application %s \n", rostifile.Name)
sshPubKey, err := readLocalSSHPubKey(appState.SSHPublicKeyPath())
if err != nil {
return err
}
app := rostiapi.App{
Name: rostifile.Name,
Image: selectedRuntime,
Domains: rostifile.Domains,
Mode: mode,
Plan: planID,
SSHKeys: []string{sshPubKey},
AppPort: rostifile.AppPort,
}
newApp, err = client.CreateApp(&app)
if err != nil {
return err
}
appState.ApplicationID = newApp.ID
appCreated = true
}
// SSH client initialization
if len(newApp.SSHAccess) == 0 {
return errors.New("no SSH access found")
}
sshClient := ssh.Client{
Server: newApp.SSHAccess[0].Hostname,
Port: int(newApp.SSHAccess[0].Port),
Username: newApp.SSHAccess[0].Username,
SSHKeyPath: appState.SSHKeyPath,
}
if sshClient.IsKeyPasswordProtected() {
counter := 0
for {
fmt.Print("SSH key password: ")
sshClient.Passphrase, err = terminal.ReadPassword(0)
fmt.Println()
if err != nil {
return fmt.Errorf("ssh key password input error: %v", err)
}
ok, err := sshClient.IsPasswordOk()
if err != nil {
return fmt.Errorf("ssh key password check error: %v", err)
}
if ok {
break
}
counter += 1
if counter >= 3 {
return fmt.Errorf("too many attempts for the SSH key password")
}
}
}
// Test SSH connection
cYellow.Println(".. waiting for SSH daemon to get ready")
testCounter := 0
for {
_, err := sshClient.Run("echo 1")
if err == nil {
cGreen.Println(" ready")
break
}
if testCounter > 12 {
// This prints the last error that occurs. It turned out the problem can actually be
// something else because this is the first time we try to connect to the SSH server.
cRed.Println(err.Error())
return errors.New("SSH daemon has not started in time")
}
testCounter++
time.Sleep(5 * time.Second)
}
// Setup technology
if appCreated { // This is processes only when app is freshly created
// Call rosti.sh to setup environment for selected technology
if len(rostifile.Technology) > 0 {
cRed.Println(".. deleting default code")
// Clean /srv/app and clean /srv/conf/supervisor.d/app.conf because we don't want the default application
cmd := "/bin/sh -c 'rm -rf /srv/app/* && rm -rf /srv/conf/supervisor.d/app.conf && supervisorctl reread && supervisorctl update'"
buf, err := sshClient.Run(cmd)
if err != nil {
cYellow.Print("Command '")
cWhite.Print(cmd)
cYellow.Println("' return an error:")
fmt.Println(buf.String())
return err
}
}
}
cYellow.Println(".. loading application status")
status, err := client.GetAppStatus(appState.ApplicationID)
if err != nil {
return fmt.Errorf("GetAppStatus error: %v", err)
}
var buf *bytes.Buffer
if status.PrimaryTech.Name != rostifile.Technology || (status.PrimaryTech.Version != rostifile.TechnologyVersion && rostifile.TechnologyVersion != "") {
cYellow.Print(".. technology change detected, settings up ")
cWhite.Print(rostifile.Technology)
cYellow.Println(" environment")
cmd := "/usr/local/bin/rosti " + rostifile.Technology
if rostifile.TechnologyVersion != "" {
cmd = "/usr/local/bin/rosti " + rostifile.Technology + " " + rostifile.TechnologyVersion
}
buf, err = sshClient.Run(cmd)
if err != nil {
fmt.Print("Command '")
cWhite.Print(cmd)
cYellow.Println("' error:")
cRed.Println(buf.String())
return err
}
}
// Initial commands
if appCreated || c.Bool("force-init") {
for _, cmd := range rostifile.InitialCommands {
buf, err := sshClient.Run(cmd)
if err != nil {
fmt.Print("Command '")
cWhite.Print(cmd)
cYellow.Println("' error:")
cRed.Println(buf.String())
return err
}
}
}
// Deploy files
cYellow.Println(".. creating an archive")
err = createArchive(rostifile.SourcePath, "/tmp/_archive.tar", rostifile.Exclude) // TODO: create a proper temporary file here
if err != nil {
return err
}
cYellow.Println(".. copying archive into the container")
archive, err := os.Open("/tmp/_archive.tar")
if err != nil {
return err
}
defer archive.Close()
err = sshClient.StreamFile("/srv/_archive.tar", archive)
if err != nil {
return err
}
// Before commands
for _, cmd := range rostifile.BeforeCommands {
cYellow.Print(".. running command:")
cWhite.Println(cmd)
buf, err = sshClient.Run("/bin/sh -c '" + cmd + "'")
if err != nil {
fmt.Print("Command '")
cWhite.Print(cmd)
cYellow.Println("' error:")
cRed.Println(buf.String())
return err
}
}
// Finishing deploying files
cYellow.Println(".. un-archiving code in the container")
cmd := "/bin/sh -c \"mkdir -p /srv/app && mv _archive.tar /srv/app/ && cd /srv/app && tar xf _archive.tar && rm _archive.tar\""
buf, err = sshClient.Run(cmd)
if err != nil {
cRed.Println("Un-archiving error. Command output:")
cRed.Println(buf.String())
return err
}
// Setup crontab
if len(rostifile.Crontabs) > 0 {
cYellow.Println(".. setting up crontabs")
err = sshClient.SendFile("/srv/conf/crontab", strings.Join(rostifile.Crontabs, "\n")+"\n")
if err != nil {
return fmt.Errorf("uploading crontabs error: %w", err)
}
_, err = sshClient.Run("crontab /srv/conf/crontab")
if err != nil {
return fmt.Errorf("refreshing crontab error: %w", err)
}
}
// Setup background processes
if len(rostifile.Processes) > 0 {
cYellow.Println(".. setting up supervisor processes")
var processes []string
for _, process := range rostifile.Processes {
processTemplate := `[program:` + process.Name + `]
command=` + process.Command + `
environment=PATH="/srv/bin/primary_tech:/usr/local/bin:/usr/bin:/bin:/srv/.npm-packages/bin"
autostart=true
autorestart=true
directory=/srv/app
process_name=` + process.Name + `
stdout_logfile=/srv/log/` + process.Name + `.log
stdout_logfile_maxbytes=2MB
stdout_logfile_backups=5
stdout_capture_maxbytes=2MB
stdout_events_enabled=false
redirect_stderr=true
`
if process.StopKillAsGroup {
processTemplate += "stopasgroup=true\n"
processTemplate += "killasgroup=true\n"
}
processes = append(processes, processTemplate)
}
err = sshClient.SendFile("/srv/conf/supervisor.d/rostictl.conf", "# This file is gonna be rewritten by rostictl\n\n"+strings.Join(processes, "\n")+"\n")
if err != nil {
return fmt.Errorf("updating supervisor config error: %w", err)
}
_, err = sshClient.Run("supervisorctl reread")
if err != nil {
return fmt.Errorf("refreshing supervisor error: %w", err)
}
_, err = sshClient.Run("supervisorctl update")
if err != nil {
return fmt.Errorf("updating supervisor error: %w", err)
}
}
// Setup after commands
for _, cmd := range rostifile.AfterCommands {
cYellow.Print(".. running command:")
fmt.Printf(" %s\n", cmd)
buf, err = sshClient.Run("/bin/sh -c '" + cmd + "'")
if err != nil {
cRed.Println("error: ", err)
cRed.Println(buf.String())
return err
}
}
// Done
cYellow.Println(".. all done, let's check status of the application")
// Check app's status
cYellow.Println(".. loading application status")
status, err = client.GetAppStatus(appState.ApplicationID)
if err != nil {
return err
}
cYellow.Println(".. loading application configuration")
app, err := client.GetApp(appState.ApplicationID)
if err != nil {
return err
}
fmt.Println("")
printAppStatus(app.Domains, status, app, false)
fmt.Println("")
fmt.Println("Note: This output doesn't have to be precise, because container")
fmt.Println("hasn't had to boot up fully or DNS hasn't propagated into the world.")
fmt.Println("Run `rostictl status` to run these checks again later to find out what's")
fmt.Println("the status of this application.")
return nil
}
func commandDown(c *cli.Context) error {
config := config.Load()
cYellow.Println(".. loading state file")
appState, err := state.Load()
if err != nil {
return err
}
defer state.Write(appState)
client := rostiapi.Client{
Token: config.Token,
CompanyID: appState.CompanyID,
ExtraError: os.Stderr,
}
cYellow.Println(".. loading Rostifile")
rostifile, err := parser.Parse()
if err != nil {
return err
}
cYellow.Printf(".. stopping application %s_%d\n", rostifile.Name, appState.ApplicationID)
err = client.DoApp(appState.ApplicationID, "stop")
if err != nil {
return err
}
cGreen.Println(".. all done!")
return nil
}
func commandStart(c *cli.Context) error {
config := config.Load()
cYellow.Println(".. loading state file")
appState, err := state.Load()
if err != nil {
return err
}
defer state.Write(appState)
client := rostiapi.Client{
Token: config.Token,
CompanyID: appState.CompanyID,
ExtraError: os.Stderr,
}
cYellow.Println(".. loading Rostifile")
rostifile, err := parser.Parse()
if err != nil {
return err
}
cYellow.Print(".. starting application ")
cWhite.Println(fmt.Sprintf("%s_%d", rostifile.Name, appState.ApplicationID))
err = client.DoApp(appState.ApplicationID, "start")
if err != nil {
return err
}
cGreen.Println(".. all done")
return nil
}
func commandRemove(c *cli.Context) error {
config := config.Load()
cYellow.Println(".. loading state file")
appState, err := state.Load()
if err != nil {
return err
}
client := rostiapi.Client{
Token: config.Token,
CompanyID: appState.CompanyID,
}
cYellow.Println(".. loading Rostifile")
rostifile, err := parser.Parse()
if err != nil {
return err
}
cRed.Print(".. removing application ")
cWhite.Println(fmt.Sprintf("%s_%d\n", rostifile.Name, appState.ApplicationID))
err = client.DeleteApp(appState.ApplicationID)
if err != nil {
return err
}
cRed.Println(".. removing .rosti.state file")
err = state.Remove()
if err != nil {
return err
}
cGreen.Println(".. all done!")
return nil
}
func commandStatus(c *cli.Context) error {
config := config.Load()
cYellow.Println(".. loading state file")
appState, err := state.Load()
if err != nil {
return err
}
client := rostiapi.Client{
Token: config.Token,
CompanyID: appState.CompanyID,
ExtraError: os.Stderr,
}
cYellow.Println(".. loading application status")
status, err := client.GetAppStatus(appState.ApplicationID)
if err != nil {
return fmt.Errorf("GetAppStatus error: %v", err)
}
app, err := client.GetApp(appState.ApplicationID)
if err != nil {
return fmt.Errorf("GetApp error: %v", err)
}
domains := app.Domains
fmt.Println()
printAppStatus(domains, status, app, true)
return nil
}
func commandPlans(c *cli.Context) error {
config := config.Load()
cYellow.Println(".. loading state file")
appState, err := state.Load()
if err != nil {
return err
}
client := rostiapi.Client{
Token: config.Token,
CompanyID: appState.CompanyID,
ExtraError: os.Stderr,
}
plans, err := client.GetPlans()
if err != nil {
return err
}
cGrey.Printf("\n %12s Plan\n", "Slug")
cGrey.Printf(" %12s ------------\n", "------------")
for _, plan := range plans {
fmt.Printf(" %21s %s\n", cYellow.Sprint(strings.ToLower(plan.Name)), cGrey.Sprint(plan.Name))
}
fmt.Println("")
fmt.Println("Note: Use slug in your Rostifile.")
return nil
}
func commandCompanies(c *cli.Context) error {
config := config.Load()
client := rostiapi.Client{
Token: config.Token,
ExtraError: os.Stderr,
}
companies, err := client.GetCompanies()
if err != nil {
return err
}
cGrey.Printf("\n %6s Company name\n", "ID")
cGrey.Printf(" %6s ------------\n", "------")
for _, company := range companies {
fmt.Printf(" %6s %s\n", cYellow.Sprint(strconv.Itoa(int(company.ID))), cWhite.Sprint(company.Name))
}
return nil
}
func commandRuntimes(c *cli.Context) error {
config := config.Load()
cYellow.Println(".. loading state file")
appState, err := state.Load()
if err != nil {
return err
}
client := rostiapi.Client{
Token: config.Token,
CompanyID: appState.CompanyID,
ExtraError: os.Stderr,
}
runtimes, err := client.GetRuntimes()
if err != nil {
return err
}
cGrey.Printf("\n Runtime\n")
cGrey.Printf(" ---------------------------\n")
for _, runtime := range runtimes {
if runtime.Default {
cGreen.Printf(" *%s\n", runtime.Image)
} else {
cYellow.Printf(" %s\n", runtime.Image)
}
}
return nil
}
func commandInit(c *cli.Context) error {
_, err := os.Stat("./Rostifile")
if !os.IsNotExist(err) {
cRed.Println("Rostifile already exists in this directory")
os.Exit(1)
}
rostifile, err := parser.Init()
if err != nil {
return err
}
bits, err := scanner.Scan(rostifile.SourcePath)
if err != nil {
return err
}
rostifile.AfterCommands = bits.AfterCommands
rostifile.BeforeCommands = bits.BeforeCommands
rostifile.Processes = bits.Processes
rostifile.AppPort = bits.AppPort
rostifile.Technology = bits.Technology
err = parser.Write(rostifile)
if err != nil {
return err
}
return nil
}
func commandVersion(c *cli.Context) error {
fmt.Println("Version:", version)
return nil
}
func commandRostifile(c *cli.Context) error {
rostifile, err := parser.Parse()
if err != nil {
return err
}
fmt.Println("Rostifile:")
fmt.Println("----------")
body, err := yaml.Marshal(rostifile)
if err != nil {
return err
}
fmt.Println(string(body))
return nil
}