-
Notifications
You must be signed in to change notification settings - Fork 86
/
processor.go
294 lines (253 loc) · 8.28 KB
/
processor.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
package worker
import (
"time"
gocontext "context"
"github.com/mitchellh/multistep"
"github.com/pborman/uuid"
"github.com/sirupsen/logrus"
"github.com/travis-ci/worker/backend"
"github.com/travis-ci/worker/config"
"github.com/travis-ci/worker/context"
"go.opencensus.io/trace"
)
// A Processor gets jobs off the job queue and coordinates running it with other
// components.
type Processor struct {
ID string
hostname string
config *config.Config
ctx gocontext.Context
buildJobsChan <-chan Job
provider backend.Provider
generator BuildScriptGenerator
persister BuildTracePersister
logWriterFactory LogWriterFactory
cancellationBroadcaster *CancellationBroadcaster
graceful chan struct{}
terminate gocontext.CancelFunc
shutdownAt time.Time
// ProcessedCount contains the number of jobs that has been processed
// by this Processor. This value should not be modified outside of the
// Processor.
ProcessedCount int
// CurrentStatus contains the current status of the processor, and can
// be one of "new", "waiting", "processing" or "done".
CurrentStatus string
// LastJobID contains the ID of the last job the processor processed.
LastJobID uint64
}
type ProcessorConfig struct {
Config *config.Config
}
// NewProcessor creates a new processor that will run the build jobs on the
// given channel using the given provider and getting build scripts from the
// generator.
func NewProcessor(ctx gocontext.Context, hostname string, queue JobQueue,
logWriterFactory LogWriterFactory, provider backend.Provider, generator BuildScriptGenerator, persister BuildTracePersister, cancellationBroadcaster *CancellationBroadcaster,
config ProcessorConfig) (*Processor, error) {
processorID, _ := context.ProcessorFromContext(ctx)
ctx, cancel := gocontext.WithCancel(ctx)
buildJobsChan, err := queue.Jobs(ctx)
if err != nil {
context.LoggerFromContext(ctx).WithField("err", err).Error("couldn't create jobs channel")
cancel()
return nil, err
}
return &Processor{
ID: processorID,
hostname: hostname,
config: config.Config,
ctx: ctx,
buildJobsChan: buildJobsChan,
provider: provider,
generator: generator,
persister: persister,
cancellationBroadcaster: cancellationBroadcaster,
logWriterFactory: logWriterFactory,
graceful: make(chan struct{}),
terminate: cancel,
CurrentStatus: "new",
}, nil
}
// Run starts the processor. This method will not return until the processor is
// terminated, either by calling the GracefulShutdown or Terminate methods, or
// if the build jobs channel is closed.
func (p *Processor) Run() {
logger := context.LoggerFromContext(p.ctx).WithField("self", "processor")
logger.Info("starting processor")
defer logger.Info("processor done")
defer func() { p.CurrentStatus = "done" }()
for {
select {
case <-p.ctx.Done():
logger.Info("processor is done, terminating")
return
case <-p.graceful:
logger.WithField("shutdown_duration_s", time.Since(p.shutdownAt).Seconds()).Info("processor is done, terminating")
p.terminate()
return
default:
}
select {
case <-p.ctx.Done():
logger.Info("processor is done, terminating")
return
case <-p.graceful:
logger.WithField("shutdown_duration_s", time.Since(p.shutdownAt).Seconds()).Info("processor is done, terminating")
p.terminate()
return
case buildJob, ok := <-p.buildJobsChan:
if !ok {
p.terminate()
return
}
buildJob.StartAttributes().ProgressType = p.config.ProgressType
jobID := buildJob.Payload().Job.ID
hardTimeout := p.config.HardTimeout
if buildJob.Payload().Timeouts.HardLimit != 0 {
hardTimeout = time.Duration(buildJob.Payload().Timeouts.HardLimit) * time.Second
}
logger.WithFields(logrus.Fields{
"hard_timeout": hardTimeout,
"job_id": jobID,
}).Debug("setting hard timeout")
buildJob.StartAttributes().HardTimeout = hardTimeout
ctx := context.FromJobID(context.FromRepository(p.ctx, buildJob.Payload().Repository.Slug), buildJob.Payload().Job.ID)
if buildJob.Payload().UUID != "" {
ctx = context.FromUUID(ctx, buildJob.Payload().UUID)
} else {
ctx = context.FromUUID(ctx, uuid.NewRandom().String())
}
logger.WithFields(logrus.Fields{
"job_id": jobID,
"status": "processing",
}).Debug("updating processor status and last id")
p.LastJobID = jobID
p.CurrentStatus = "processing"
p.process(ctx, buildJob)
logger.WithFields(logrus.Fields{
"job_id": jobID,
"status": "waiting",
}).Debug("updating processor status")
p.CurrentStatus = "waiting"
case <-time.After(10 * time.Second):
logger.Debug("timeout waiting for job, shutdown, or context done")
}
}
}
// GracefulShutdown tells the processor to finish the job it is currently
// processing, but not pick up any new jobs. This method will return
// immediately, the processor is done when Run() returns.
func (p *Processor) GracefulShutdown() {
logger := context.LoggerFromContext(p.ctx).WithField("self", "processor")
defer func() {
err := recover()
if err != nil {
logger.WithField("err", err).Error("recovered from panic")
}
}()
logger.Info("processor initiating graceful shutdown")
p.shutdownAt = time.Now()
tryClose(p.graceful)
}
// Terminate tells the processor to stop working on the current job as soon as
// possible.
func (p *Processor) Terminate() {
p.terminate()
}
func (p *Processor) process(ctx gocontext.Context, buildJob Job) {
ctx = buildJob.SetupContext(ctx)
ctx = context.WithTimings(ctx)
ctx, span := trace.StartSpan(ctx, "ProcessorRun")
defer span.End()
span.AddAttributes(
trace.StringAttribute("app", "worker"),
trace.Int64Attribute("job_id", int64(buildJob.Payload().Job.ID)),
trace.StringAttribute("repo", buildJob.Payload().Repository.Slug),
trace.StringAttribute("infra", p.config.ProviderName),
trace.StringAttribute("site", p.config.TravisSite),
)
state := new(multistep.BasicStateBag)
state.Put("hostname", p.ID)
state.Put("buildJob", buildJob)
state.Put("logWriterFactory", p.logWriterFactory)
state.Put("ctx", ctx)
state.Put("processedAt", time.Now().UTC())
state.Put("infra", p.config.Infra)
logger := context.LoggerFromContext(ctx).WithFields(logrus.Fields{
"job_id": buildJob.Payload().Job.ID,
"self": "processor",
})
logTimeout := p.config.LogTimeout
if buildJob.Payload().Timeouts.LogSilence != 0 {
logTimeout = time.Duration(buildJob.Payload().Timeouts.LogSilence) * time.Second
}
steps := []multistep.Step{
&stepSubscribeCancellation{
cancellationBroadcaster: p.cancellationBroadcaster,
},
&stepTransformBuildJSON{
payloadFilterExecutable: p.config.PayloadFilterExecutable,
},
&stepGenerateScript{
generator: p.generator,
},
&stepSendReceived{},
&stepSleep{duration: p.config.InitialSleep},
&stepCheckCancellation{},
&stepOpenLogWriter{
maxLogLength: p.config.MaxLogLength,
defaultLogTimeout: p.config.LogTimeout,
},
&stepCheckCancellation{},
&stepStartInstance{
provider: p.provider,
startTimeout: p.config.StartupTimeout,
},
&stepCheckCancellation{},
&stepUploadScript{
uploadTimeout: p.config.ScriptUploadTimeout,
},
&stepCheckCancellation{},
&stepUpdateState{},
&stepWriteWorkerInfo{},
&stepCheckCancellation{},
&stepRunScript{
logTimeout: logTimeout,
hardTimeout: buildJob.StartAttributes().HardTimeout,
skipShutdownOnLogTimeout: p.config.SkipShutdownOnLogTimeout,
},
&stepDownloadTrace{
persister: p.persister,
},
}
runner := &multistep.BasicRunner{Steps: steps}
logger.Info("starting job")
runner.Run(state)
fields := context.LoggerTimingsFromContext(ctx)
instance, ok := state.Get("instance").(backend.Instance)
if ok {
fields["instance_id"] = instance.ID()
fields["image_name"] = instance.ImageName()
}
err, ok := state.Get("err").(error)
if ok {
fields["err"] = err
}
if buildJob.FinishState() != "" {
fields["state"] = buildJob.FinishState()
}
if buildJob.Requeued() {
fields["requeued"] = 1
}
logger.WithFields(fields).Info("finished job")
p.ProcessedCount++
}
func (p *Processor) processorInfo() processorInfo {
return processorInfo{
ID: p.ID,
Processed: p.ProcessedCount,
Status: p.CurrentStatus,
LastJobID: p.LastJobID,
}
}