forked from buildkite/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent_worker.go
313 lines (256 loc) · 7.99 KB
/
agent_worker.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
package agent
import (
"fmt"
"strings"
"sync"
"time"
"github.com/buildkite/agent/api"
"github.com/buildkite/agent/logger"
"github.com/buildkite/agent/proctitle"
"github.com/buildkite/agent/retry"
)
type AgentWorker struct {
// The API Client used when this agent is communicating with the API
APIClient *api.Client
// The endpoint that should be used when communicating with the API
Endpoint string
// The registred agent API record
Agent *api.Agent
// The configuration of the agent from the CLI
AgentConfiguration *AgentConfiguration
// Whether or not the agent is running
running bool
// Used by the Start call to control the looping of the pings
ticker *time.Ticker
// Stop controls
stop chan struct{}
stopping bool
stopMutex sync.Mutex
// When this worker runs a job, we'll store an instance of the
// JobRunner here
jobRunner *JobRunner
}
// Creates the agent worker and initializes it's API Client
func (a AgentWorker) Create() AgentWorker {
var endpoint string
if a.Agent.Endpoint != "" {
endpoint = a.Agent.Endpoint
} else {
endpoint = a.Endpoint
}
a.APIClient = APIClient{Endpoint: endpoint, Token: a.Agent.AccessToken}.Create()
return a
}
// Starts the agent worker
func (a *AgentWorker) Start() error {
// Mark the agent as running
a.running = true
// Create the intervals we'll be using
pingInterval := time.Second * time.Duration(a.Agent.PingInterval)
heartbeatInterval := time.Second * time.Duration(a.Agent.HearbeatInterval)
// Setup and start the heartbeater
go func() {
// Keep the heartbeat running as long as the agent is
for a.running {
err := a.Heartbeat()
if err != nil {
logger.Error("Failed to heartbeat %s. Will try again in %s", err, heartbeatInterval)
}
time.Sleep(heartbeatInterval)
}
}()
// Create the ticker and stop channels
a.ticker = time.NewTicker(pingInterval)
a.stop = make(chan struct{})
// Continue this loop until the the ticker is stopped, and we received
// a message on the stop channel.
for {
a.Ping()
select {
case <-a.ticker.C:
continue
case <-a.stop:
a.ticker.Stop()
return nil
}
}
// Mark the agent as not running anymore
a.running = false
return nil
}
// Stops the agent from accepting new work and cancels any current work it's
// running
func (a *AgentWorker) Stop(graceful bool) {
// Only allow one stop to run at a time (because we're playing with
// channels)
a.stopMutex.Lock()
defer a.stopMutex.Unlock()
if graceful {
if a.stopping {
logger.Warn("Agent is already gracefully stopping...")
} else {
// If we have a job, tell the user that we'll wait for
// it to finish before disconnecting
if a.jobRunner != nil {
logger.Info("Gracefully stopping agent. Waiting for current job to finish before disconnecting...")
} else {
logger.Info("Gracefully stopping agent. Since there is no job running, the agent will disconnect immediately")
}
}
} else {
// If there's a job running, kill it, then disconnect
if a.jobRunner != nil {
logger.Info("Forcefully stopping agent. The current job will be canceled before disconnecting...")
// Kill the current job. Doesn't do anything if the job
// is already being killed, so it's safe to call
// multiple times.
a.jobRunner.Kill()
} else {
logger.Info("Forcefully stopping agent. Since there is no job running, the agent will disconnect immediately")
}
}
// We don't need to do the below operations again since we've already
// done them before
if a.stopping {
return
}
// Update the proc title
a.UpdateProcTitle("stopping")
// If we have a ticker, stop it, and send a signal to the stop channel,
// which will cause the agent worker to stop looping immediatly.
if a.ticker != nil {
close(a.stop)
}
// Mark the agent as stopping
a.stopping = true
}
// Connects the agent to the Buildkite Agent API, retrying up to 30 times if it
// fails.
func (a *AgentWorker) Connect() error {
// Update the proc title
a.UpdateProcTitle("connecting")
return retry.Do(func(s *retry.Stats) error {
_, err := a.APIClient.Agents.Connect()
if err != nil {
logger.Warn("%s (%s)", err, s)
}
return err
}, &retry.Config{Maximum: 10, Interval: 5 * time.Second})
}
// Performs a heatbeat
func (a *AgentWorker) Heartbeat() error {
var beat *api.Heartbeat
var err error
// Retry the heartbeat a few times
err = retry.Do(func(s *retry.Stats) error {
beat, _, err = a.APIClient.Heartbeats.Beat()
if err != nil {
logger.Warn("%s (%s)", err, s)
}
return err
}, &retry.Config{Maximum: 5, Interval: 5 * time.Second})
if err != nil {
return err
}
logger.Debug("Heartbeat sent at %s and received at %s", beat.SentAt, beat.ReceivedAt)
return nil
}
// Performs a ping, which returns what action the agent should take next.
func (a *AgentWorker) Ping() {
// Update the proc title
a.UpdateProcTitle("pinging")
ping, _, err := a.APIClient.Pings.Get()
if err != nil {
// If a ping fails, we don't really care, because it'll
// ping again after the interval.
logger.Warn("Failed to ping: %s", err)
return
}
// Should we switch endpoints?
if ping.Endpoint != "" && ping.Endpoint != a.Agent.Endpoint {
// Before switching to the new one, do a ping test to make sure it's
// valid. If it is, switch and carry on, otherwise ignore the switch
// for now.
newAPIClient := APIClient{Endpoint: ping.Endpoint, Token: a.Agent.AccessToken}.Create()
newPing, _, err := newAPIClient.Pings.Get()
if err != nil {
logger.Warn("Failed to ping the new endpoint %s - ignoring switch for now (%s)", ping.Endpoint, err)
} else {
// Replace the APIClient and process the new ping
a.APIClient = newAPIClient
a.Agent.Endpoint = ping.Endpoint
ping = newPing
}
}
// Is there a message that should be shown in the logs?
if ping.Message != "" {
logger.Info(ping.Message)
}
// Should the agent disconnect?
if ping.Action == "disconnect" {
a.Stop(false)
return
}
// If we don't have a job, there's nothing to do!
if ping.Job == nil {
// Update the proc title
a.UpdateProcTitle("idle")
return
}
// Update the proc title
a.UpdateProcTitle(fmt.Sprintf("job %s", strings.Split(ping.Job.ID, "-")[0]))
logger.Info("Assigned job %s. Accepting...", ping.Job.ID)
// Accept the job. We'll retry on connection related issues, but if
// Buildkite returns a 422 or 500 for example, we'll just bail out,
// re-ping, and try the whole process again.
var accepted *api.Job
retry.Do(func(s *retry.Stats) error {
accepted, _, err = a.APIClient.Jobs.Accept(ping.Job)
if err != nil {
if api.IsRetryableError(err) {
logger.Warn("%s (%s)", err, s)
} else {
logger.Warn("Buildkite rejected the call to accept the job (%s)", err)
s.Break()
}
}
return err
}, &retry.Config{Maximum: 30, Interval: 5 * time.Second})
// If `accepted` is nil, then the job was never accepted
if accepted == nil {
logger.Error("Failed to accept job")
return
}
// Now that the job has been accepted, we can start it.
a.jobRunner, err = JobRunner{
Endpoint: accepted.Endpoint,
Agent: a.Agent,
AgentConfiguration: a.AgentConfiguration,
Job: accepted,
}.Create()
// Was there an error creating the job runner?
if err != nil {
logger.Error("Failed to initialize job: %s", err)
return
}
// Start running the job
if err = a.jobRunner.Run(); err != nil {
logger.Error("Failed to run job: %s", err)
}
// No more job, no more runner.
a.jobRunner = nil
}
// Disconnects the agent from the Buildkite Agent API, doesn't bother retrying
// because we want to disconnect as fast as possible.
func (a *AgentWorker) Disconnect() error {
// Update the proc title
a.UpdateProcTitle("disconnecting")
_, err := a.APIClient.Agents.Disconnect()
if err != nil {
logger.Warn("There was an error sending the disconnect API call to Buildkite. If this agent still appears online, you may have to manually stop it (%s)", err)
}
return err
}
func (a *AgentWorker) UpdateProcTitle(action string) {
proctitle.Replace(fmt.Sprintf("buildkite-agent v%s [%s]", Version(), action))
}