-
Notifications
You must be signed in to change notification settings - Fork 159
/
empire.go
816 lines (645 loc) · 18.1 KB
/
empire.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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
package empire // import "github.com/remind101/empire"
import (
"errors"
"fmt"
"io"
"time"
"github.com/jinzhu/gorm"
"github.com/remind101/empire/pkg/image"
"golang.org/x/net/context"
)
const (
// webProcessType is the process type we assume are web server processes.
webProcessType = "web"
)
// Various errors that may be returned.
var (
ErrDomainInUse = errors.New("Domain currently in use by another app.")
ErrDomainAlreadyAdded = errors.New("Domain already added to this app.")
ErrDomainNotFound = errors.New("Domain could not be found.")
ErrUserName = errors.New("Name is required")
ErrNoReleases = errors.New("no releases")
// ErrInvalidName is used to indicate that the app name is not valid.
ErrInvalidName = &ValidationError{
errors.New("An app name must be alphanumeric and dashes only, 3-30 chars in length."),
}
)
// AllowedCommands specifies what commands are allowed to be Run with Empire.
type AllowedCommands int
const (
// AllowCommandAny will allow any command to be run.
AllowCommandAny AllowedCommands = iota
// AllowCommandProcfile will only allow commands specified in the
// Procfile (the key itself) to be run. Any other command will return an
// error.
AllowCommandProcfile
)
// An error that is returned when a command is not whitelisted to be Run.
type CommandNotAllowedError struct {
Command Command
}
// commandNotInFormation returns a new CommandNotAllowedError for a command
// that's not in the formation.
func commandNotInFormation(command Command, formation Formation) *CommandNotAllowedError {
return &CommandNotAllowedError{Command: command}
}
// Error implements the error interface.
func (c *CommandNotAllowedError) Error() string {
return fmt.Sprintf("command not allowed: %v\n", c.Command)
}
// NoCertError is returned when the Procfile specifies an https/ssl listener but
// there is no attached certificate.
type NoCertError struct {
Process string
}
func (e *NoCertError) Error() string {
return fmt.Sprintf("the %s process does not have a certificate attached", e.Process)
}
// Empire provides the core public API for Empire. Refer to the package
// documentation for details.
type Empire struct {
DB *DB
db *gorm.DB
apps *appsService
configs *configsService
domains *domainsService
tasks *tasksService
releases *releasesService
deployer *deployerService
runner *runnerService
slugs *slugsService
certs *certsService
// Scheduler is the backend scheduler used to run applications.
Scheduler Scheduler
// LogsStreamer is the backend used to stream application logs.
LogsStreamer LogsStreamer
// ImageRegistry is used to interract with container images.
ImageRegistry ImageRegistry
// Environment represents the environment this Empire server is responsible for
Environment string
// EventStream service for publishing Empire events.
EventStream
// RunRecorder is used to record the logs from interactive runs.
RunRecorder RunRecorder
// MessagesRequired is a boolean used to determine if messages should be required for events.
MessagesRequired bool
// Configures what type of commands are allowed to be run with the Run
// method. The zero value allows all commands to be run.
AllowedCommands AllowedCommands
}
// New returns a new Empire instance.
func New(db *DB) *Empire {
e := &Empire{
LogsStreamer: logsDisabled,
EventStream: NullEventStream,
DB: db,
db: db.DB,
}
e.apps = &appsService{Empire: e}
e.configs = &configsService{Empire: e}
e.deployer = &deployerService{Empire: e}
e.domains = &domainsService{Empire: e}
e.slugs = &slugsService{Empire: e}
e.tasks = &tasksService{Empire: e}
e.runner = &runnerService{Empire: e}
e.releases = &releasesService{Empire: e}
e.certs = &certsService{Empire: e}
return e
}
// AppsFind finds the first app matching the query.
func (e *Empire) AppsFind(q AppsQuery) (*App, error) {
return appsFind(e.db, q)
}
// Apps returns all Apps.
func (e *Empire) Apps(q AppsQuery) ([]*App, error) {
return apps(e.db, q)
}
func (e *Empire) requireMessages(m string) error {
if e.MessagesRequired && m == "" {
return &MessageRequiredError{}
}
return nil
}
// CreateOpts are options that are provided when creating a new application.
type CreateOpts struct {
// User performing the action.
User *User
// Name of the application.
Name string
// Commit message
Message string
}
func (opts CreateOpts) Event() CreateEvent {
return CreateEvent{
User: opts.User.Name,
Name: opts.Name,
Message: opts.Message,
}
}
func (opts CreateOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// Create creates a new app.
func (e *Empire) Create(ctx context.Context, opts CreateOpts) (*App, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
a, err := appsCreate(e.db, &App{Name: opts.Name})
if err != nil {
return a, err
}
return a, e.PublishEvent(opts.Event())
}
// DestroyOpts are options provided when destroying an application.
type DestroyOpts struct {
// User performing the action.
User *User
// The associated app.
App *App
// Commit message
Message string
}
func (opts DestroyOpts) Event() DestroyEvent {
return DestroyEvent{
User: opts.User.Name,
App: opts.App.Name,
Message: opts.Message,
}
}
func (opts DestroyOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// Destroy destroys an app.
func (e *Empire) Destroy(ctx context.Context, opts DestroyOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
tx := e.db.Begin()
if err := e.apps.Destroy(ctx, tx, opts.App); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit().Error; err != nil {
return err
}
return e.PublishEvent(opts.Event())
}
// Config returns the current Config for a given app.
func (e *Empire) Config(app *App) (*Config, error) {
tx := e.db.Begin()
c, err := e.configs.Config(tx, app)
if err != nil {
tx.Rollback()
return c, err
}
if err := tx.Commit().Error; err != nil {
return c, err
}
return c, nil
}
type SetMaintenanceModeOpts struct {
// User performing the action.
User *User
// The associated app.
App *App
// Wheather maintenance mode should be enabled or not.
Maintenance bool
// Commit message
Message string
}
func (opts SetMaintenanceModeOpts) Event() MaintenanceEvent {
return MaintenanceEvent{
User: opts.User.Name,
App: opts.App.Name,
Maintenance: opts.Maintenance,
Message: opts.Message,
}
}
func (opts SetMaintenanceModeOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// SetMaintenanceMode enables or disables "maintenance mode" on the app. When an
// app is in maintenance mode, all processes will be scaled down to 0. When
// taken out of maintenance mode, all processes will be scaled up back to their
// existing values.
func (e *Empire) SetMaintenanceMode(ctx context.Context, opts SetMaintenanceModeOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
tx := e.db.Begin()
app := opts.App
app.Maintenance = opts.Maintenance
if err := appsUpdate(tx, app); err != nil {
tx.Rollback()
return err
}
if err := e.releases.ReleaseApp(ctx, tx, app, nil); err != nil {
tx.Rollback()
if err == ErrNoReleases {
return nil
}
return err
}
if err := tx.Commit().Error; err != nil {
return err
}
return e.PublishEvent(opts.Event())
}
// SetOpts are options provided when setting new config vars on an app.
type SetOpts struct {
// User performing the action.
User *User
// The associated app.
App *App
// The new vars to merge into the old config.
Vars Vars
// Commit message
Message string
}
func (opts SetOpts) Event() SetEvent {
var changed []string
for k := range opts.Vars {
changed = append(changed, string(k))
}
return SetEvent{
User: opts.User.Name,
App: opts.App.Name,
Changed: changed,
Message: opts.Message,
app: opts.App,
}
}
func (opts SetOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// Set applies the new config vars to the apps current Config, returning the new
// Config. If the app has a running release, a new release will be created and
// run.
func (e *Empire) Set(ctx context.Context, opts SetOpts) (*Config, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
c, err := e.configs.Set(ctx, tx, opts)
if err != nil {
tx.Rollback()
return c, err
}
if err := tx.Commit().Error; err != nil {
return c, err
}
return c, e.PublishEvent(opts.Event())
}
// DomainsFind returns the first domain matching the query.
func (e *Empire) DomainsFind(q DomainsQuery) (*Domain, error) {
return domainsFind(e.db, q)
}
// Domains returns all domains matching the query.
func (e *Empire) Domains(q DomainsQuery) ([]*Domain, error) {
return domains(e.db, q)
}
// DomainsCreate adds a new Domain for an App.
func (e *Empire) DomainsCreate(ctx context.Context, domain *Domain) (*Domain, error) {
tx := e.db.Begin()
d, err := e.domains.DomainsCreate(ctx, tx, domain)
if err != nil {
tx.Rollback()
return d, err
}
if err := tx.Commit().Error; err != nil {
return d, err
}
return d, nil
}
// DomainsDestroy removes a Domain for an App.
func (e *Empire) DomainsDestroy(ctx context.Context, domain *Domain) error {
tx := e.db.Begin()
if err := e.domains.DomainsDestroy(ctx, tx, domain); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit().Error; err != nil {
return err
}
return nil
}
// Tasks returns the Tasks for the given app.
func (e *Empire) Tasks(ctx context.Context, app *App) ([]*Task, error) {
return e.tasks.Tasks(ctx, app)
}
// RestartOpts are options provided when restarting an app.
type RestartOpts struct {
// User performing the action.
User *User
// The associated app.
App *App
// If provided, a PID that will be killed. Generally used for killing
// detached processes.
PID string
// Commit message
Message string
}
func (opts RestartOpts) Event() RestartEvent {
return RestartEvent{
User: opts.User.Name,
App: opts.App.Name,
PID: opts.PID,
Message: opts.Message,
app: opts.App,
}
}
func (opts RestartOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// Restart restarts processes matching the given prefix for the given Release.
// If the prefix is empty, it will match all processes for the release.
func (e *Empire) Restart(ctx context.Context, opts RestartOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
if err := e.apps.Restart(ctx, e.db, opts); err != nil {
return err
}
return e.PublishEvent(opts.Event())
}
// RunOpts are options provided when running an attached/detached process.
type RunOpts struct {
// User performing this action.
User *User
// Related app.
App *App
// The command to run.
Command Command
// Commit message
Message string
// Input/Output streams. The caller is responsible for closing these
// streams.
Stdin io.Reader
Stdout, Stderr io.Writer
// Extra environment variables to set.
Env map[string]string
// Optional memory/cpu/nproc constraints.
Constraints *Constraints
}
func (opts RunOpts) Event() RunEvent {
var attached bool
if opts.Stdout != nil || opts.Stderr != nil {
attached = true
}
return RunEvent{
User: opts.User.Name,
App: opts.App.Name,
Command: opts.Command,
Attached: attached,
Message: opts.Message,
app: opts.App,
}
}
func (opts RunOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// Run runs a one-off process for a given App and command.
func (e *Empire) Run(ctx context.Context, opts RunOpts) error {
event := opts.Event()
if err := opts.Validate(e); err != nil {
return err
}
if e.RunRecorder != nil && (opts.Stdout != nil || opts.Stderr != nil) {
w, err := e.RunRecorder()
if err != nil {
return err
}
// Add the log url to the event, if there is one.
if w, ok := w.(interface {
URL() string
}); ok {
event.URL = w.URL()
}
msg := fmt.Sprintf("Running `%s` on %s as %s", opts.Command, opts.App.Name, opts.User.Name)
msg = appendCommitMessage(msg, opts.Message)
io.WriteString(w, fmt.Sprintf("%s\n", msg))
// Write output to both the original output as well as the
// record.
if opts.Stdout != nil {
opts.Stdout = io.MultiWriter(w, opts.Stdout)
}
if opts.Stderr != nil {
opts.Stderr = io.MultiWriter(w, opts.Stderr)
}
}
if err := e.PublishEvent(event); err != nil {
return err
}
if err := e.runner.Run(ctx, opts); err != nil {
return err
}
event.Finish()
return e.PublishEvent(event)
}
// Releases returns all Releases for a given App.
func (e *Empire) Releases(q ReleasesQuery) ([]*Release, error) {
return releases(e.db, q)
}
// ReleasesFind returns the first releases for a given App.
func (e *Empire) ReleasesFind(q ReleasesQuery) (*Release, error) {
return releasesFind(e.db, q)
}
// RollbackOpts are options provided when rolling back to an old release.
type RollbackOpts struct {
// The user performing the action.
User *User
// The associated app.
App *App
// The release version to rollback to.
Version int
// Commit message
Message string
}
func (opts RollbackOpts) Event() RollbackEvent {
return RollbackEvent{
User: opts.User.Name,
App: opts.App.Name,
Version: opts.Version,
Message: opts.Message,
app: opts.App,
}
}
func (opts RollbackOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// Rollback rolls an app back to a specific release version. Returns a
// new release.
func (e *Empire) Rollback(ctx context.Context, opts RollbackOpts) (*Release, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
r, err := e.releases.Rollback(ctx, tx, opts)
if err != nil {
tx.Rollback()
return r, err
}
if err := tx.Commit().Error; err != nil {
return r, err
}
return r, e.PublishEvent(opts.Event())
}
// DeployOpts represents options that can be passed when deploying to
// an application.
type DeployOpts struct {
// User the user that is triggering the deployment.
User *User
// App is the app that is being deployed to.
App *App
// Image is the image that's being deployed.
Image image.Image
// Environment is the environment where the image is being deployed
Environment string
// Output is a DeploymentStream where deployment output and events will
// be streamed in jsonmessage format.
Output *DeploymentStream
// Commit message
Message string
// Stream boolean for whether or not a status stream should be created.
Stream bool
}
func (opts DeployOpts) Event() DeployEvent {
e := DeployEvent{
User: opts.User.Name,
Image: opts.Image.String(),
Message: opts.Message,
}
if opts.App != nil {
e.App = opts.App.Name
e.app = opts.App
}
return e
}
func (opts DeployOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// Deploy deploys an image and streams the output to w.
func (e *Empire) Deploy(ctx context.Context, opts DeployOpts) (*Release, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
r, err := e.deployer.Deploy(ctx, opts)
if err != nil {
return r, err
}
event := opts.Event()
event.Release = r.Version
event.Environment = e.Environment
// Deals with new app creation on first deploy
if event.App == "" && r.App != nil {
event.App = r.App.Name
event.app = r.App
}
return r, e.PublishEvent(event)
}
type ProcessUpdate struct {
// The process to scale.
Process string
// The desired quantity of processes.
Quantity int
// If provided, new memory and CPU constraints for the process.
Constraints *Constraints
}
// ScaleOpts are options provided when scaling a process.
type ScaleOpts struct {
// User that's performing the action.
User *User
// The associated app.
App *App
Updates []*ProcessUpdate
// Commit message
Message string
}
func (opts ScaleOpts) Event() ScaleEvent {
e := ScaleEvent{
User: opts.User.Name,
App: opts.App.Name,
Message: opts.Message,
app: opts.App,
}
var updates []*ScaleEventUpdate
for _, up := range opts.Updates {
event := &ScaleEventUpdate{
Process: up.Process,
Quantity: up.Quantity,
}
if up.Constraints != nil {
event.Constraints = *up.Constraints
}
updates = append(updates, event)
}
e.Updates = updates
return e
}
func (opts ScaleOpts) Validate(e *Empire) error {
return e.requireMessages(opts.Message)
}
// Scale scales an apps processes.
func (e *Empire) Scale(ctx context.Context, opts ScaleOpts) ([]*Process, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
ps, err := e.apps.Scale(ctx, tx, opts)
if err != nil {
tx.Rollback()
return ps, err
}
return ps, tx.Commit().Error
}
// ListScale lists the current scale settings for a given App
func (e *Empire) ListScale(ctx context.Context, app *App) (Formation, error) {
return currentFormation(e.db, app)
}
// Streamlogs streams logs from an app.
func (e *Empire) StreamLogs(app *App, w io.Writer, duration time.Duration) error {
if err := e.LogsStreamer.StreamLogs(app, w, duration); err != nil {
return fmt.Errorf("error streaming logs: %v", err)
}
return nil
}
type CertsAttachOpts struct {
// The certificate to attach.
Cert string
// The app to attach the cert to.
App *App
// An optional process to attach the cert to. If not provided, "web"
// will be used.
Process string
}
// CertsAttach attaches an SSL certificate to the app.
func (e *Empire) CertsAttach(ctx context.Context, opts CertsAttachOpts) error {
tx := e.db.Begin()
if err := e.certs.CertsAttach(ctx, tx, opts); err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
// Reset resets empire.
func (e *Empire) Reset() error {
return e.DB.Reset()
}
// IsHealthy returns true if Empire is healthy, which means it can connect to
// the services it depends on.
func (e *Empire) IsHealthy() error {
return e.DB.IsHealthy()
}
// ValidationError is returned when a model is not valid.
type ValidationError struct {
Err error
}
func (e *ValidationError) Error() string {
return e.Err.Error()
}
// MessageRequiredError is an error implementation, which is returned by Empire
// when a commit message is required for the operation.
type MessageRequiredError struct{}
func (e *MessageRequiredError) Error() string {
return "Missing required option: 'Message'"
}