forked from buildkite/agent
/
bootstrap.go
440 lines (406 loc) · 13.7 KB
/
bootstrap.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
package clicommand
import (
"context"
"os"
"os/signal"
"runtime"
"sync"
"syscall"
"github.com/buildkite/agent/v3/bootstrap"
"github.com/derekmarcotte/agent/v3/cliconfig"
"github.com/buildkite/agent/v3/experiments"
"github.com/buildkite/agent/v3/logger"
"github.com/urfave/cli"
)
var BootstrapHelpDescription = `Usage:
buildkite-agent bootstrap [arguments...]
Description:
The bootstrap command executes a buildkite job locally.
Generally the bootstrap command is run as a sub-process of the buildkite-agent to execute
a given job sent from buildkite.com, but you can also invoke the bootstrap manually.
Execution is broken down into phases. By default, the bootstrap runs a plugin phase which
sets up any plugins specified, then a checkout phase which pulls down your code and then a
command phase that executes the specified command in the created environment.
You can run only specific phases with the --phases flag.
The bootstrap is also responsible for executing hooks around the phases.
See https://buildkite.com/docs/agent/v3/hooks for more details.
Example:
$ eval $(curl -s -H "Authorization: Bearer xxx" \
"https://api.buildkite.com/v2/organizations/[org]/pipelines/[proj]/builds/[build]/jobs/[job]/env.txt" | sed 's/^/export /')
$ buildkite-agent bootstrap --build-path builds`
type BootstrapConfig struct {
Command string `cli:"command"`
JobID string `cli:"job" validate:"required"`
Repository string `cli:"repository" validate:"required"`
Commit string `cli:"commit" validate:"required"`
Branch string `cli:"branch" validate:"required"`
Tag string `cli:"tag"`
RefSpec string `cli:"refspec"`
Plugins string `cli:"plugins"`
PullRequest string `cli:"pullrequest"`
GitSubmodules bool `cli:"git-submodules"`
SSHKeyscan bool `cli:"ssh-keyscan"`
AgentName string `cli:"agent" validate:"required"`
OrganizationSlug string `cli:"organization" validate:"required"`
PipelineSlug string `cli:"pipeline" validate:"required"`
PipelineProvider string `cli:"pipeline-provider" validate:"required"`
AutomaticArtifactUploadPaths string `cli:"artifact-upload-paths"`
ArtifactUploadDestination string `cli:"artifact-upload-destination"`
CleanCheckout bool `cli:"clean-checkout"`
GitCloneFlags string `cli:"git-clone-flags"`
GitFetchFlags string `cli:"git-fetch-flags"`
GitCloneMirrorFlags string `cli:"git-clone-mirror-flags"`
GitCleanFlags string `cli:"git-clean-flags"`
GitMirrorsPath string `cli:"git-mirrors-path" normalize:"filepath"`
GitMirrorsLockTimeout int `cli:"git-mirrors-lock-timeout"`
BinPath string `cli:"bin-path" normalize:"filepath"`
BuildPath string `cli:"build-path" normalize:"filepath"`
HooksPath string `cli:"hooks-path" normalize:"filepath"`
PluginsPath string `cli:"plugins-path" normalize:"filepath"`
CommandEval bool `cli:"command-eval"`
PluginsEnabled bool `cli:"plugins-enabled"`
PluginValidation bool `cli:"plugin-validation"`
LocalHooksEnabled bool `cli:"local-hooks-enabled"`
PTY bool `cli:"pty"`
Debug bool `cli:"debug"`
Shell string `cli:"shell"`
Experiments []string `cli:"experiment" normalize:"list"`
Phases []string `cli:"phases" normalize:"list"`
Profile string `cli:"profile"`
RedactedVars []string `cli:"redacted-vars" normalize:"list"`
}
var BootstrapCommand = cli.Command{
Name: "bootstrap",
Usage: "Run a Buildkite job locally",
Description: BootstrapHelpDescription,
Flags: []cli.Flag{
cli.StringFlag{
Name: "command",
Value: "",
Usage: "The command to run",
EnvVar: "BUILDKITE_COMMAND",
},
cli.StringFlag{
Name: "job",
Value: "",
Usage: "The ID of the job being run",
EnvVar: "BUILDKITE_JOB_ID",
},
cli.StringFlag{
Name: "repository",
Value: "",
Usage: "The repository to clone and run the job from",
EnvVar: "BUILDKITE_REPO",
},
cli.StringFlag{
Name: "commit",
Value: "",
Usage: "The commit to checkout in the repository",
EnvVar: "BUILDKITE_COMMIT",
},
cli.StringFlag{
Name: "branch",
Value: "",
Usage: "The branch the commit is in",
EnvVar: "BUILDKITE_BRANCH",
},
cli.StringFlag{
Name: "tag",
Value: "",
Usage: "The tag the commit",
EnvVar: "BUILDKITE_TAG",
},
cli.StringFlag{
Name: "refspec",
Value: "",
Usage: "Optional refspec to override git fetch",
EnvVar: "BUILDKITE_REFSPEC",
},
cli.StringFlag{
Name: "plugins",
Value: "",
Usage: "The plugins for the job",
EnvVar: "BUILDKITE_PLUGINS",
},
cli.StringFlag{
Name: "pullrequest",
Value: "",
Usage: "The number/id of the pull request this commit belonged to",
EnvVar: "BUILDKITE_PULL_REQUEST",
},
cli.StringFlag{
Name: "agent",
Value: "",
Usage: "The name of the agent running the job",
EnvVar: "BUILDKITE_AGENT_NAME",
},
cli.StringFlag{
Name: "organization",
Value: "",
Usage: "The slug of the organization that the job is a part of",
EnvVar: "BUILDKITE_ORGANIZATION_SLUG",
},
cli.StringFlag{
Name: "pipeline",
Value: "",
Usage: "The slug of the pipeline that the job is a part of",
EnvVar: "BUILDKITE_PIPELINE_SLUG",
},
cli.StringFlag{
Name: "pipeline-provider",
Value: "",
Usage: "The id of the SCM provider that the repository is hosted on",
EnvVar: "BUILDKITE_PIPELINE_PROVIDER",
},
cli.StringFlag{
Name: "artifact-upload-paths",
Value: "",
Usage: "Paths to files to automatically upload at the end of a job",
EnvVar: "BUILDKITE_ARTIFACT_PATHS",
},
cli.StringFlag{
Name: "artifact-upload-destination",
Value: "",
Usage: "A custom location to upload artifact paths to (i.e. s3://my-custom-bucket)",
EnvVar: "BUILDKITE_ARTIFACT_UPLOAD_DESTINATION",
},
cli.BoolFlag{
Name: "clean-checkout",
Usage: "Whether or not the bootstrap should remove the existing repository before running the command",
EnvVar: "BUILDKITE_CLEAN_CHECKOUT",
},
cli.StringFlag{
Name: "git-clone-flags",
Value: "-v",
Usage: "Flags to pass to \"git clone\" command",
EnvVar: "BUILDKITE_GIT_CLONE_FLAGS",
},
cli.StringFlag{
Name: "git-clone-mirror-flags",
Value: "-v --mirror",
Usage: "Flags to pass to \"git clone\" command when mirroring",
EnvVar: "BUILDKITE_GIT_CLONE_MIRROR_FLAGS",
},
cli.StringFlag{
Name: "git-clean-flags",
Value: "-ffxdq",
Usage: "Flags to pass to \"git clean\" command",
EnvVar: "BUILDKITE_GIT_CLEAN_FLAGS",
},
cli.StringFlag{
Name: "git-fetch-flags",
Value: "",
Usage: "Flags to pass to \"git fetch\" command",
EnvVar: "BUILDKITE_GIT_FETCH_FLAGS",
},
cli.StringFlag{
Name: "git-mirrors-path",
Value: "",
Usage: "Path to where mirrors of git repositories are stored",
EnvVar: "BUILDKITE_GIT_MIRRORS_PATH",
},
cli.IntFlag{
Name: "git-mirrors-lock-timeout",
Value: 300,
Usage: "Seconds to lock a git mirror during clone, should exceed your longest checkout",
EnvVar: "BUILDKITE_GIT_MIRRORS_LOCK_TIMEOUT",
},
cli.StringFlag{
Name: "bin-path",
Value: "",
Usage: "Directory where the buildkite-agent binary lives",
EnvVar: "BUILDKITE_BIN_PATH",
},
cli.StringFlag{
Name: "build-path",
Value: "",
Usage: "Directory where builds will be created",
EnvVar: "BUILDKITE_BUILD_PATH",
},
cli.StringFlag{
Name: "hooks-path",
Value: "",
Usage: "Directory where the hook scripts are found",
EnvVar: "BUILDKITE_HOOKS_PATH",
},
cli.StringFlag{
Name: "plugins-path",
Value: "",
Usage: "Directory where the plugins are saved to",
EnvVar: "BUILDKITE_PLUGINS_PATH",
},
cli.BoolTFlag{
Name: "command-eval",
Usage: "Allow running of arbitary commands",
EnvVar: "BUILDKITE_COMMAND_EVAL",
},
cli.BoolTFlag{
Name: "plugins-enabled",
Usage: "Allow plugins to be run",
EnvVar: "BUILDKITE_PLUGINS_ENABLED",
},
cli.BoolFlag{
Name: "plugin-validation",
Usage: "Validate plugin configuration",
EnvVar: "BUILDKITE_PLUGIN_VALIDATION",
},
cli.BoolTFlag{
Name: "local-hooks-enabled",
Usage: "Allow local hooks to be run",
EnvVar: "BUILDKITE_LOCAL_HOOKS_ENABLED",
},
cli.BoolTFlag{
Name: "ssh-keyscan",
Usage: "Automatically run ssh-keyscan before checkout",
EnvVar: "BUILDKITE_SSH_KEYSCAN",
},
cli.BoolTFlag{
Name: "git-submodules",
Usage: "Enable git submodules",
EnvVar: "BUILDKITE_GIT_SUBMODULES",
},
cli.BoolTFlag{
Name: "pty",
Usage: "Run jobs within a pseudo terminal",
EnvVar: "BUILDKITE_PTY",
},
cli.StringFlag{
Name: "shell",
Usage: "The shell to use to interpret build commands",
EnvVar: "BUILDKITE_SHELL",
Value: DefaultShell(),
},
cli.StringSliceFlag{
Name: "phases",
Usage: "The specific phases to execute. The order they're defined is is irrelevant.",
EnvVar: "BUILDKITE_BOOTSTRAP_PHASES",
},
cli.StringSliceFlag{
Name: "redacted-vars",
Usage: "Pattern of environment variable names containing sensitive values",
EnvVar: "BUILDKITE_REDACTED_VARS",
},
DebugFlag,
ExperimentsFlag,
ProfileFlag,
},
Action: func(c *cli.Context) {
// The configuration will be loaded into this struct
cfg := BootstrapConfig{}
l := CreateLogger(&cfg)
// Load the configuration
if err := cliconfig.Load(c, l, &cfg); err != nil {
l.Fatal("%s", err)
}
// Enable experiments
for _, name := range cfg.Experiments {
experiments.Enable(name)
}
// Enable debug if set
if cfg.Debug {
l.SetLevel(logger.DEBUG)
}
// Handle profiling flag
done := HandleProfileFlag(l, cfg)
defer done()
// Turn of PTY support if we're on Windows
runInPty := cfg.PTY
if runtime.GOOS == "windows" {
runInPty = false
}
// Validate phases
for _, phase := range cfg.Phases {
switch phase {
case "plugin", "checkout", "command":
// Valid phase
default:
l.Fatal("Invalid phase %q", phase)
}
}
// Configure the bootstraper
bootstrap := bootstrap.New(bootstrap.Config{
Command: cfg.Command,
JobID: cfg.JobID,
Repository: cfg.Repository,
Commit: cfg.Commit,
Branch: cfg.Branch,
Tag: cfg.Tag,
RefSpec: cfg.RefSpec,
Plugins: cfg.Plugins,
GitSubmodules: cfg.GitSubmodules,
PullRequest: cfg.PullRequest,
GitCloneFlags: cfg.GitCloneFlags,
GitFetchFlags: cfg.GitFetchFlags,
GitCloneMirrorFlags: cfg.GitCloneMirrorFlags,
GitCleanFlags: cfg.GitCleanFlags,
AgentName: cfg.AgentName,
PipelineProvider: cfg.PipelineProvider,
PipelineSlug: cfg.PipelineSlug,
OrganizationSlug: cfg.OrganizationSlug,
AutomaticArtifactUploadPaths: cfg.AutomaticArtifactUploadPaths,
ArtifactUploadDestination: cfg.ArtifactUploadDestination,
CleanCheckout: cfg.CleanCheckout,
BuildPath: cfg.BuildPath,
GitMirrorsPath: cfg.GitMirrorsPath,
GitMirrorsLockTimeout: cfg.GitMirrorsLockTimeout,
BinPath: cfg.BinPath,
HooksPath: cfg.HooksPath,
PluginsPath: cfg.PluginsPath,
PluginValidation: cfg.PluginValidation,
Debug: cfg.Debug,
RunInPty: runInPty,
CommandEval: cfg.CommandEval,
PluginsEnabled: cfg.PluginsEnabled,
LocalHooksEnabled: cfg.LocalHooksEnabled,
SSHKeyscan: cfg.SSHKeyscan,
Shell: cfg.Shell,
Phases: cfg.Phases,
RedactedVars: cfg.RedactedVars,
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt,
syscall.SIGHUP,
syscall.SIGTERM,
syscall.SIGINT,
syscall.SIGQUIT)
defer signal.Stop(signals)
var (
cancelled bool
received os.Signal
signalMu sync.Mutex
)
// Listen for signals in the background and cancel the bootstrap
go func() {
sig := <-signals
signalMu.Lock()
defer signalMu.Unlock()
// Cancel the bootstrap
bootstrap.Cancel()
// Track the state and signal used
cancelled = true
received = sig
// Remove our signal handler so subsequent signals kill
signal.Stop(signals)
}()
// Run the bootstrap and get the exit code
exitCode := bootstrap.Run(ctx)
signalMu.Lock()
defer signalMu.Unlock()
// If cancelled and our child process returns a non-zero, we should terminate
// ourselves with the same signal so that our caller can detect and handle appropriately
if cancelled && runtime.GOOS != `windows` {
p, err := os.FindProcess(os.Getpid())
if err != nil {
l.Error("Failed to find current process: %v", err)
}
l.Debug("Terminating bootstrap after cancellation with %v", received)
err = p.Signal(received)
if err != nil {
l.Error("Failed to signal self: %v", err)
}
}
os.Exit(exitCode)
},
}