-
Notifications
You must be signed in to change notification settings - Fork 170
/
common.go
301 lines (249 loc) · 6.29 KB
/
common.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
package core
import (
"crypto/rand"
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/armon/circbuf"
docker "github.com/fsouza/go-dockerclient"
)
var (
// ErrSkippedExecution pass this error to `Execution.Stop` if you wish to mark
// it as skipped.
ErrSkippedExecution = errors.New("skipped execution")
ErrUnexpected = errors.New("error unexpected, docker has returned exit code -1, maybe wrong user?")
ErrMaxTimeRunning = errors.New("the job has exceed the maximum allowed time running.")
ErrLocalImageNotFound = errors.New("couldn't find image on the host")
)
const (
// maximum size of a stdout/stderr stream to be kept in memory and optional stored/sent via mail
maxStreamSize = 10 * 1024 * 1024
logPrefix = "[Job %q (%s)] %s"
)
type Job interface {
GetName() string
GetSchedule() string
GetCommand() string
Middlewares() []Middleware
Use(...Middleware)
Run(*Context) error
Running() int32
NotifyStart()
NotifyStop()
}
type Context struct {
Scheduler *Scheduler
Logger Logger
Job Job
Execution *Execution
current int
executed bool
middlewares []Middleware
}
func NewContext(s *Scheduler, j Job, e *Execution) *Context {
return &Context{
Scheduler: s,
Logger: s.Logger,
Job: j,
Execution: e,
middlewares: j.Middlewares(),
}
}
func (c *Context) Start() {
c.Execution.Start()
c.Job.NotifyStart()
}
func (c *Context) Next() error {
if err := c.doNext(); err != nil || c.executed {
c.Stop(err)
}
return nil
}
func (c *Context) doNext() error {
for {
m, end := c.getNext()
if end {
break
}
if !c.Execution.IsRunning && !m.ContinueOnStop() {
continue
}
return m.Run(c)
}
if !c.Execution.IsRunning {
return nil
}
c.executed = true
return c.Job.Run(c)
}
func (c *Context) getNext() (Middleware, bool) {
if c.current >= len(c.middlewares) {
return nil, true
}
c.current++
return c.middlewares[c.current-1], false
}
func (c *Context) Stop(err error) {
if !c.Execution.IsRunning {
return
}
c.Execution.Stop(err)
c.Job.NotifyStop()
}
func (c *Context) Log(msg string) {
args := []interface{}{c.Job.GetName(), c.Execution.ID, msg}
switch {
case c.Execution.Failed:
c.Logger.Errorf(logPrefix, args...)
case c.Execution.Skipped:
c.Logger.Warningf(logPrefix, args...)
default:
c.Logger.Noticef(logPrefix, args...)
}
}
func (c *Context) Warn(msg string) {
args := []interface{}{c.Job.GetName(), c.Execution.ID, msg}
c.Logger.Warningf(logPrefix, args...)
}
// Execution contains all the information relative to a Job execution.
type Execution struct {
ID string
Date time.Time
Duration time.Duration
IsRunning bool
Failed bool
Skipped bool
Error error
OutputStream, ErrorStream *circbuf.Buffer `json:"-"`
}
// NewExecution returns a new Execution, with a random ID
func NewExecution() *Execution {
bufOut, _ := circbuf.NewBuffer(maxStreamSize)
bufErr, _ := circbuf.NewBuffer(maxStreamSize)
return &Execution{
ID: randomID(),
OutputStream: bufOut,
ErrorStream: bufErr,
}
}
// Start start the exection, initialize the running flags and the start date.
func (e *Execution) Start() {
e.IsRunning = true
e.Date = time.Now()
}
// Stop stops the executions, if a ErrSkippedExecution is given the exection
// is mark as skipped, if any other error is given the exection is mark as
// failed. Also mark the exection as IsRunning false and save the duration time
func (e *Execution) Stop(err error) {
e.IsRunning = false
e.Duration = time.Since(e.Date)
if err != nil && err != ErrSkippedExecution {
e.Error = err
e.Failed = true
} else if err == ErrSkippedExecution {
e.Skipped = true
}
}
// Middleware can wrap any job execution, allowing to execution code before
// or/and after of each `Job.Run`
type Middleware interface {
// Run is called instead of the original `Job.Run`, you MUST call to `ctx.Run`
// inside of the middleware `Run` function otherwise you will broken the
// Job workflow.
Run(*Context) error
// ContinueOnStop, If return true the Run function will be called even if
// the execution is stopped
ContinueOnStop() bool
}
type middlewareContainer struct {
m map[string]Middleware
order []string
}
func (c *middlewareContainer) Use(ms ...Middleware) {
if c.m == nil {
c.m = make(map[string]Middleware, 0)
}
for _, m := range ms {
if m == nil {
continue
}
t := reflect.TypeOf(m).String()
if _, ok := c.m[t]; ok {
continue
}
c.order = append(c.order, t)
c.m[t] = m
}
}
func (c *middlewareContainer) Middlewares() []Middleware {
var ms []Middleware
for _, t := range c.order {
ms = append(ms, c.m[t])
}
return ms
}
type Logger interface {
Criticalf(format string, args ...interface{})
Debugf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Noticef(format string, args ...interface{})
Warningf(format string, args ...interface{})
}
func randomID() string {
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return fmt.Sprintf("%x", b)
}
func buildFindLocalImageOptions(image string) docker.ListImagesOptions {
return docker.ListImagesOptions{
Filters: map[string][]string{
"reference": []string{image},
},
}
}
func buildPullOptions(image string) (docker.PullImageOptions, docker.AuthConfiguration) {
repository, tag := docker.ParseRepositoryTag(image)
registry := parseRegistry(repository)
if tag == "" {
tag = "latest"
}
return docker.PullImageOptions{
Repository: repository,
Registry: registry,
Tag: tag,
}, buildAuthConfiguration(registry)
}
func parseRegistry(repository string) string {
parts := strings.Split(repository, "/")
if len(parts) < 2 {
return ""
}
if strings.ContainsAny(parts[0], ".:") || len(parts) > 2 {
return parts[0]
}
return ""
}
func buildAuthConfiguration(registry string) docker.AuthConfiguration {
var auth docker.AuthConfiguration
if dockercfg == nil {
return auth
}
if v, ok := dockercfg.Configs[registry]; ok {
return v
}
// try to fetch configs from docker hub default registry urls
// see example here: https://www.projectatomic.io/blog/2016/03/docker-credentials-store/
if registry == "" {
if v, ok := dockercfg.Configs["https://index.docker.io/v2/"]; ok {
return v
}
if v, ok := dockercfg.Configs["https://index.docker.io/v1/"]; ok {
return v
}
}
return auth
}