Skip to content

Commit ae1a002

Browse files
committed
dockerfile: implement hooks for RUN instructions
Close issue 4576 - - - e.g., ```bash buildctl build \ --frontend dockerfile.v0 \ --opt hook="$(cat hook.json)" ``` with `hook.json` as follows: ```json { "RUN": { "entrypoint": ["/dev/.dfhook/entrypoint"], "mounts": [ {"from": "example.com/hook", "target": "/dev/.dfhook"}, {"type": "secret", "source": "something", "target": "/etc/something"} ] } } ``` This will let the frontend treat `RUN foo` as: ```dockerfile RUN \ --mount=from=example.com/hook,target=/dev/.dfhook \ --mount=type=secret,source=something,target=/etc/something \ /dev/.dfhook/entrypoint foo ``` `docker history` will still show this as `RUN foo`. Signed-off-by: Akihiro Suda <[email protected]>
1 parent 6babc32 commit ae1a002

File tree

12 files changed

+232
-24
lines changed

12 files changed

+232
-24
lines changed

docs/reference/buildctl.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,45 @@ $ buildctl build --frontend dockerfile.v0 --local context=. --local dockerfile=.
181181
$ buildctl build --frontend dockerfile.v0 --local context=. --local dockerfile=. --oci-layout foo2=/home/dir/oci --opt context:alpine=oci-layout://foo2@sha256:bd04a5b26dec16579cd1d7322e949c5905c4742269663fcbc84dcb2e9f4592fb
182182
```
183183

184+
##### Instruction hooks
185+
<!-- TODO: s/master/v0.14/ -->
186+
In the master branch, the Dockerfile frontend also supports "instruction hooks".
187+
188+
e.g.,
189+
190+
```bash
191+
buildctl build \
192+
--frontend dockerfile.v0 \
193+
--opt hook="$(cat hook.json)"
194+
```
195+
with `hook.json` as follows:
196+
```json
197+
{
198+
"RUN": {
199+
"entrypoint": ["/dev/.dfhook/entrypoint"],
200+
"mounts": [
201+
{"from": "example.com/hook", "target": "/dev/.dfhook"},
202+
{"type": "secret", "source": "something", "target": "/etc/something"}
203+
]
204+
}
205+
}
206+
```
207+
208+
This will let the frontend treat `RUN foo` as:
209+
```dockerfile
210+
RUN \
211+
--mount=from=example.com/hook,target=/dev/.dfhook \
212+
--mount=type=secret,source=something,target=/etc/something \
213+
/dev/.dfhook/entrypoint foo
214+
```
215+
216+
`docker history` will still show this as `RUN foo`.
217+
218+
<!--
219+
TODO: add example hook images to show concrete use-cases
220+
https://github.com/moby/buildkit/issues/4576
221+
-->
222+
184223
#### gateway-specific options
185224

186225
The `gateway.v0` frontend passes all of its `--opt` options on to the OCI image that is called to convert the

frontend/dockerfile/dockerfile2llb/convert.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"github.com/moby/buildkit/frontend/dockerfile/parser"
2727
"github.com/moby/buildkit/frontend/dockerfile/shell"
2828
"github.com/moby/buildkit/frontend/dockerui"
29+
"github.com/moby/buildkit/frontend/dockerui/types"
2930
"github.com/moby/buildkit/frontend/subrequests/outline"
3031
"github.com/moby/buildkit/frontend/subrequests/targets"
3132
"github.com/moby/buildkit/identity"
@@ -116,7 +117,7 @@ func ListTargets(ctx context.Context, dt []byte) (*targets.List, error) {
116117
return nil, err
117118
}
118119

119-
stages, _, err := instructions.Parse(dockerfile.AST, nil)
120+
stages, _, err := instructions.Parse(dockerfile.AST, nil, instructions.ParseOpts{})
120121
if err != nil {
121122
return nil, err
122123
}
@@ -199,7 +200,10 @@ func toDispatchState(ctx context.Context, dt []byte, opt ConvertOpt) (*dispatchS
199200

200201
proxyEnv := proxyEnvFromBuildArgs(opt.BuildArgs)
201202

202-
stages, metaArgs, err := instructions.Parse(dockerfile.AST, opt.Warn)
203+
parseOpts := instructions.ParseOpts{
204+
InstructionHook: opt.InstructionHook,
205+
}
206+
stages, metaArgs, err := instructions.Parse(dockerfile.AST, opt.Warn, parseOpts)
203207
if err != nil {
204208
return nil, err
205209
}
@@ -578,6 +582,7 @@ func toDispatchState(ctx context.Context, dt []byte, opt ConvertOpt) (*dispatchS
578582
cgroupParent: opt.CgroupParent,
579583
llbCaps: opt.LLBCaps,
580584
sourceMap: opt.SourceMap,
585+
instHook: opt.InstructionHook,
581586
}
582587

583588
if err = dispatchOnBuildTriggers(d, d.image.Config.OnBuild, opt); err != nil {
@@ -713,6 +718,7 @@ type dispatchOpt struct {
713718
cgroupParent string
714719
llbCaps *apicaps.CapSet
715720
sourceMap *llb.SourceMap
721+
instHook *types.InstructionHook
716722
}
717723

718724
func dispatch(d *dispatchState, cmd command, opt dispatchOpt) error {
@@ -923,6 +929,9 @@ type command struct {
923929
}
924930

925931
func dispatchOnBuildTriggers(d *dispatchState, triggers []string, opt dispatchOpt) error {
932+
parseOpts := instructions.ParseOpts{
933+
InstructionHook: opt.instHook,
934+
}
926935
for _, trigger := range triggers {
927936
ast, err := parser.Parse(strings.NewReader(trigger))
928937
if err != nil {
@@ -931,7 +940,7 @@ func dispatchOnBuildTriggers(d *dispatchState, triggers []string, opt dispatchOp
931940
if len(ast.AST.Children) != 1 {
932941
return errors.New("onbuild trigger should be a single expression")
933942
}
934-
ic, err := instructions.ParseCommand(ast.AST.Children[0])
943+
ic, err := instructions.ParseCommand(ast.AST.Children[0], parseOpts)
935944
if err != nil {
936945
return err
937946
}
@@ -1021,6 +1030,12 @@ func dispatchRun(d *dispatchState, c *instructions.RunCommand, proxy *llb.ProxyE
10211030
args = withShell(d.image, args)
10221031
}
10231032

1033+
argsForHistory := args
1034+
if dopt.instHook != nil && dopt.instHook.Run != nil {
1035+
args = append(dopt.instHook.Run.Entrypoint, args...)
1036+
// leave argsForHistory unmodified
1037+
}
1038+
10241039
env, err := d.state.Env(context.TODO())
10251040
if err != nil {
10261041
return err
@@ -1087,7 +1102,7 @@ func dispatchRun(d *dispatchState, c *instructions.RunCommand, proxy *llb.ProxyE
10871102
}
10881103

10891104
d.state = d.state.Run(opt...).Root()
1090-
return commitToHistory(&d.image, "RUN "+runCommandString(args, d.buildArgs, shell.BuildEnvs(env)), true, &d.state, d.epoch)
1105+
return commitToHistory(&d.image, "RUN "+runCommandString(argsForHistory, d.buildArgs, shell.BuildEnvs(env)), true, &d.state, d.epoch)
10911106
}
10921107

10931108
func dispatchWorkdir(d *dispatchState, c *instructions.WorkdirCommand, commit bool, opt *dispatchOpt) error {
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package dockerfile
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"strings"
7+
"testing"
8+
9+
"github.com/containerd/continuity/fs/fstest"
10+
"github.com/moby/buildkit/client"
11+
"github.com/moby/buildkit/frontend/dockerui"
12+
"github.com/moby/buildkit/util/testutil/integration"
13+
"github.com/stretchr/testify/require"
14+
"github.com/tonistiigi/fsutil"
15+
)
16+
17+
var instHookTests = integration.TestFuncs(
18+
testInstructionHook,
19+
)
20+
21+
func testInstructionHook(t *testing.T, sb integration.Sandbox) {
22+
integration.SkipOnPlatform(t, "windows")
23+
f := getFrontend(t, sb)
24+
25+
dockerfile := []byte(`
26+
FROM busybox AS base
27+
RUN echo "$FOO" >/foo
28+
29+
FROM scratch
30+
COPY --from=base /foo /foo
31+
`)
32+
33+
dir := integration.Tmpdir(
34+
t,
35+
fstest.CreateFile("Dockerfile", dockerfile, 0600),
36+
)
37+
destDir := t.TempDir()
38+
39+
c, err := client.New(sb.Context(), sb.Address())
40+
require.NoError(t, err)
41+
defer c.Close()
42+
43+
build := func(attrs map[string]string) string {
44+
_, err = f.Solve(sb.Context(), c, client.SolveOpt{
45+
FrontendAttrs: attrs,
46+
Exports: []client.ExportEntry{
47+
{
48+
Type: client.ExporterLocal,
49+
OutputDir: destDir,
50+
},
51+
},
52+
LocalMounts: map[string]fsutil.FS{
53+
dockerui.DefaultLocalNameDockerfile: dir,
54+
dockerui.DefaultLocalNameContext: dir,
55+
},
56+
}, nil)
57+
require.NoError(t, err)
58+
p := filepath.Join(destDir, "foo")
59+
b, err := os.ReadFile(p)
60+
require.NoError(t, err)
61+
return strings.TrimSpace(string(b))
62+
}
63+
64+
require.Equal(t, "", build(nil))
65+
66+
const hook = `
67+
{
68+
"RUN": {
69+
"entrypoint": ["/dev/.dfhook/bin/busybox", "env", "FOO=BAR"],
70+
"mounts": [
71+
{"from": "busybox:uclibc", "target": "/dev/.dfhook"}
72+
]
73+
}
74+
}`
75+
require.Equal(t, "BAR", build(map[string]string{"hook": hook}))
76+
}

frontend/dockerfile/dockerfile_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ func TestIntegration(t *testing.T) {
257257
"amd64/bullseye-20230109-slim": "docker.io/amd64/debian:bullseye-20230109-slim@sha256:1acb06a0c31fb467eb8327ad361f1091ab265e0bf26d452dea45dcb0c0ea5e75",
258258
}),
259259
)...)
260+
integration.Run(t, instHookTests, opts...)
260261
}
261262

262263
func testDefaultEnvWithArgs(t *testing.T, sb integration.Sandbox) {

frontend/dockerfile/instructions/commands.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"github.com/docker/docker/api/types/container"
77
"github.com/docker/docker/api/types/strslice"
88
"github.com/moby/buildkit/frontend/dockerfile/parser"
9+
"github.com/moby/buildkit/frontend/dockerui/types"
910
"github.com/pkg/errors"
1011
)
1112

@@ -339,7 +340,7 @@ type ShellDependantCmdLine struct {
339340
// RUN ["echo", "hi"] # echo hi
340341
type RunCommand struct {
341342
withNameAndCode
342-
withExternalData
343+
WithInstructionHook
343344
ShellDependantCmdLine
344345
FlagsUsed []string
345346
}
@@ -550,3 +551,21 @@ func (c *withExternalData) setExternalValue(k, v interface{}) {
550551
}
551552
c.m[k] = v
552553
}
554+
555+
type WithInstructionHook struct {
556+
withExternalData
557+
}
558+
559+
const instHookKey = "dockerfile/run/instruction-hook"
560+
561+
func (c *WithInstructionHook) GetInstructionHook() *types.InstructionHook {
562+
x := c.getExternalValue(instHookKey)
563+
if x == nil {
564+
return nil
565+
}
566+
return x.(*types.InstructionHook)
567+
}
568+
569+
func (c *WithInstructionHook) SetInstructionHook(h *types.InstructionHook) {
570+
c.setExternalValue(instHookKey, h)
571+
}

frontend/dockerfile/instructions/commands_runmount.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,15 @@ func setMountState(cmd *RunCommand, expander SingleWordExpander) error {
8686
return errors.Errorf("no mount state")
8787
}
8888
var mounts []*Mount
89+
if hook := cmd.GetInstructionHook(); hook != nil && hook.Run != nil {
90+
for _, m := range hook.Run.Mounts {
91+
m := m
92+
if err := validateMount(&m, false); err != nil {
93+
return err
94+
}
95+
mounts = append(mounts, &m)
96+
}
97+
}
8998
for _, str := range st.flag.StringValues {
9099
m, err := parseMount(str, expander)
91100
if err != nil {

frontend/dockerfile/instructions/parse.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,17 @@ import (
1717
"github.com/moby/buildkit/frontend/dockerfile/command"
1818
"github.com/moby/buildkit/frontend/dockerfile/linter"
1919
"github.com/moby/buildkit/frontend/dockerfile/parser"
20+
"github.com/moby/buildkit/frontend/dockerui/types"
2021
"github.com/moby/buildkit/util/suggest"
2122
"github.com/pkg/errors"
2223
)
2324

2425
var excludePatternsEnabled = false
2526

27+
type ParseOpts struct {
28+
InstructionHook *types.InstructionHook
29+
}
30+
2631
type parseRequest struct {
2732
command string
2833
args []string
@@ -32,6 +37,7 @@ type parseRequest struct {
3237
original string
3338
location []parser.Range
3439
comments []string
40+
opts ParseOpts
3541
}
3642

3743
var parseRunPreHooks []func(*RunCommand, parseRequest) error
@@ -67,16 +73,17 @@ func newParseRequestFromNode(node *parser.Node) parseRequest {
6773
}
6874
}
6975

70-
func ParseInstruction(node *parser.Node) (v interface{}, err error) {
71-
return ParseInstructionWithLinter(node, nil)
76+
func ParseInstruction(node *parser.Node, opts ParseOpts) (v interface{}, err error) {
77+
return ParseInstructionWithLinter(node, nil, opts)
7278
}
7379

7480
// ParseInstruction converts an AST to a typed instruction (either a command or a build stage beginning when encountering a `FROM` statement)
75-
func ParseInstructionWithLinter(node *parser.Node, lintWarn linter.LintWarnFunc) (v interface{}, err error) {
81+
func ParseInstructionWithLinter(node *parser.Node, lintWarn linter.LintWarnFunc, opts ParseOpts) (v interface{}, err error) {
7682
defer func() {
7783
err = parser.WithLocation(err, node.Location())
7884
}()
7985
req := newParseRequestFromNode(node)
86+
req.opts = opts
8087
switch strings.ToLower(node.Value) {
8188
case command.Env:
8289
return parseEnv(req)
@@ -127,8 +134,8 @@ func ParseInstructionWithLinter(node *parser.Node, lintWarn linter.LintWarnFunc)
127134
}
128135

129136
// ParseCommand converts an AST to a typed Command
130-
func ParseCommand(node *parser.Node) (Command, error) {
131-
s, err := ParseInstruction(node)
137+
func ParseCommand(node *parser.Node, opts ParseOpts) (Command, error) {
138+
s, err := ParseInstruction(node, opts)
132139
if err != nil {
133140
return nil, err
134141
}
@@ -163,9 +170,9 @@ func (e *parseError) Unwrap() error {
163170

164171
// Parse a Dockerfile into a collection of buildable stages.
165172
// metaArgs is a collection of ARG instructions that occur before the first FROM.
166-
func Parse(ast *parser.Node, lint linter.LintWarnFunc) (stages []Stage, metaArgs []ArgCommand, err error) {
173+
func Parse(ast *parser.Node, lint linter.LintWarnFunc, opts ParseOpts) (stages []Stage, metaArgs []ArgCommand, err error) {
167174
for _, n := range ast.Children {
168-
cmd, err := ParseInstructionWithLinter(n, lint)
175+
cmd, err := ParseInstructionWithLinter(n, lint, opts)
169176
if err != nil {
170177
return nil, nil, &parseError{inner: err, node: n}
171178
}
@@ -488,6 +495,7 @@ func parseShellDependentCommand(req parseRequest, command string, emptyAsNil boo
488495

489496
func parseRun(req parseRequest) (*RunCommand, error) {
490497
cmd := &RunCommand{}
498+
cmd.SetInstructionHook(req.opts.InstructionHook)
491499

492500
for _, fn := range parseRunPreHooks {
493501
if err := fn(cmd, req); err != nil {

frontend/dockerfile/instructions/parse_heredoc_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func TestErrorCasesHeredoc(t *testing.T) {
2929
t.Fatalf("Error when parsing Dockerfile: %s", err)
3030
}
3131
n := ast.AST.Children[0]
32-
_, err = ParseInstruction(n)
32+
_, err = ParseInstruction(n, ParseOpts{})
3333
require.Error(t, err)
3434
require.Contains(t, err.Error(), c.expectedError)
3535
}
@@ -167,7 +167,7 @@ EOF`,
167167
require.NoError(t, err)
168168

169169
n := ast.AST.Children[0]
170-
comm, err := ParseInstruction(n)
170+
comm, err := ParseInstruction(n, ParseOpts{})
171171
require.NoError(t, err)
172172

173173
sd := comm.(*CopyCommand).SourcesAndDest
@@ -249,7 +249,7 @@ EOF`,
249249
require.NoError(t, err)
250250

251251
n := ast.AST.Children[0]
252-
comm, err := ParseInstruction(n)
252+
comm, err := ParseInstruction(n, ParseOpts{})
253253
require.NoError(t, err)
254254
require.Equal(t, c.shell, comm.(*RunCommand).PrependShell)
255255
require.Equal(t, c.command, comm.(*RunCommand).CmdLine)

0 commit comments

Comments
 (0)