forked from remind101/empire
/
empire.go
576 lines (459 loc) · 13.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
package empire // import "github.com/remind101/empire"
import (
"io"
"io/ioutil"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/fsouza/go-dockerclient"
"github.com/inconshreveable/log15"
"github.com/jinzhu/gorm"
"github.com/remind101/empire/pkg/dockerutil"
"github.com/remind101/empire/pkg/image"
"github.com/remind101/empire/procfile"
"github.com/remind101/empire/scheduler"
"github.com/remind101/pkg/reporter"
"golang.org/x/net/context"
)
var (
// DefaultOptions is a default Options instance that can be passed when
// intializing a new Empire.
DefaultOptions = Options{}
// DefaultReporter is the default reporter.Reporter to use.
DefaultReporter = reporter.NewLogReporter()
)
const (
// WebPort is the default PORT to set on web processes.
WebPort = 8080
// WebProcessType is the process type we assume are web server processes.
WebProcessType = "web"
)
// ProcfileExtractor is a function that can extract a Procfile from an image.
type ProcfileExtractor func(context.Context, image.Image, io.Writer) (procfile.Procfile, error)
// Options is provided to New to configure the Empire services.
type Options struct {
Secret string
}
// Empire is a context object that contains a collection of services.
type Empire struct {
// Reporter is an reporter.Reporter that will be used to report errors to
// an external system.
reporter.Reporter
// Logger is a log15 logger that will be used for logging.
Logger log15.Logger
DB *DB
db *gorm.DB
accessTokens *accessTokensService
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.Scheduler
// LogsStreamer is the backend used to stream application logs.
LogsStreamer LogsStreamer
// ExtractProcfile is called during deployments to extract the Procfile
// from the newly deployed image.
ExtractProcfile ProcfileExtractor
// EventStream service for publishing Empire events.
EventStream
}
// New returns a new Empire instance.
func New(db *DB, options Options) *Empire {
e := &Empire{
Logger: nullLogger(),
LogsStreamer: logsDisabled,
EventStream: NullEventStream,
DB: db,
db: db.DB,
}
e.accessTokens = &accessTokensService{Secret: []byte(options.Secret)}
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
}
// AccessTokensFind finds an access token.
func (e *Empire) AccessTokensFind(token string) (*AccessToken, error) {
return e.accessTokens.AccessTokensFind(token)
}
// AccessTokensCreate creates a new AccessToken.
func (e *Empire) AccessTokensCreate(accessToken *AccessToken) (*AccessToken, error) {
return e.accessTokens.AccessTokensCreate(accessToken)
}
// 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)
}
// 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
}
func (opts CreateOpts) Event() CreateEvent {
return CreateEvent{
User: opts.User.Name,
Name: opts.Name,
}
}
// Create creates a new app.
func (e *Empire) Create(ctx context.Context, opts CreateOpts) (*App, error) {
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
}
func (opts DestroyOpts) Event() DestroyEvent {
return DestroyEvent{
User: opts.User.Name,
App: opts.App.Name,
}
}
// Destroy destroys an app.
func (e *Empire) Destroy(ctx context.Context, opts DestroyOpts) error {
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
}
// 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
}
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,
}
}
// 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) {
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
}
func (opts RestartOpts) Event() RestartEvent {
return RestartEvent{
User: opts.User.Name,
App: opts.App.Name,
PID: opts.PID,
}
}
// 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 := 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 string
// If provided, input will be read from this.
Input io.Reader
// If provided, output will be written to this.
Output io.Writer
// Extra environment variables to set.
Env map[string]string
}
func (opts RunOpts) Event() RunEvent {
var attached bool
if opts.Output != nil {
attached = true
}
return RunEvent{
User: opts.User.Name,
App: opts.App.Name,
Command: opts.Command,
Attached: attached,
}
}
// Run runs a one-off process for a given App and command.
func (e *Empire) Run(ctx context.Context, opts RunOpts) error {
if err := e.runner.Run(ctx, opts); err != nil {
return err
}
return e.PublishEvent(opts.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
}
func (opts RollbackOpts) Event() RollbackEvent {
return RollbackEvent{
User: opts.User.Name,
App: opts.App.Name,
Version: opts.Version,
}
}
// 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) {
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())
}
// DeploymentsCreateOpts represents options that can be passed when deploying to
// an application.
type DeploymentsCreateOpts 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
// Output is an io.Writer where deployment output and events will be
// streamed in jsonmessage format.
Output io.Writer
}
func (opts DeploymentsCreateOpts) Event() DeployEvent {
e := DeployEvent{
User: opts.User.Name,
Image: opts.Image.String(),
}
if opts.App != nil {
e.App = opts.App.Name
}
return e
}
// Deploy deploys an image and streams the output to w.
func (e *Empire) Deploy(ctx context.Context, opts DeploymentsCreateOpts) (*Release, error) {
tx := e.db.Begin()
r, err := e.deployer.Deploy(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())
}
// ScaleOpts are options provided when scaling a process.
type ScaleOpts struct {
// User that's performing the action.
User *User
// The associated app.
App *App
// The process type to scale.
Process ProcessType
// The desired quantity of processes.
Quantity int
// If provided, new memory and CPU constraints for the process.
Constraints *Constraints
}
func (opts ScaleOpts) Event() ScaleEvent {
return ScaleEvent{
User: opts.User.Name,
App: opts.App.Name,
Process: string(opts.Process),
Quantity: opts.Quantity,
}
}
// Scale scales an apps process.
func (e *Empire) Scale(ctx context.Context, opts ScaleOpts) (*Process, error) {
tx := e.db.Begin()
p, err := e.apps.Scale(ctx, tx, opts)
if err != nil {
tx.Rollback()
return p, err
}
return p, tx.Commit().Error
}
// Streamlogs streams logs from an app.
func (e *Empire) StreamLogs(app *App, w io.Writer) error {
return e.LogsStreamer.StreamLogs(app, w)
}
// CertsAttach attaches an SSL certificate to the app.
func (e *Empire) CertsAttach(ctx context.Context, app *App, cert string) error {
tx := e.db.Begin()
if err := e.certs.CertsAttach(ctx, tx, app, cert); 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() bool {
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()
}
func newJSONMessageError(err error) jsonmessage.JSONMessage {
return jsonmessage.JSONMessage{
ErrorMessage: err.Error(),
Error: &jsonmessage.JSONError{
Message: err.Error(),
},
}
}
func nullLogger() log15.Logger {
l := log15.New()
h := log15.StreamHandler(ioutil.Discard, log15.LogfmtFormat())
l.SetHandler(h)
return l
}
// PullAndExtract returns a ProcfileExtractor that will pull the image using the
// docker client, then attempt to extract the Procfile from the WORKDIR, or
// fallback to the CMD directive in the Procfile.
func PullAndExtract(c *dockerutil.Client) ProcfileExtractor {
e := procfile.MultiExtractor(
procfile.NewFileExtractor(c.Client),
procfile.NewCMDExtractor(c.Client),
)
return ProcfileExtractor(func(ctx context.Context, img image.Image, w io.Writer) (procfile.Procfile, error) {
if err := c.PullImage(ctx, docker.PullImageOptions{
Registry: img.Registry,
Repository: img.Repository,
Tag: img.Tag,
OutputStream: w,
RawJSONStream: true,
}); err != nil {
return nil, err
}
return e.Extract(img)
})
}