Skip to content

Commit 2058c6c

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 7d78a3c commit 2058c6c

File tree

12 files changed

+230
-22
lines changed

12 files changed

+230
-22
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.13/ -->
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"
@@ -114,7 +115,7 @@ func ListTargets(ctx context.Context, dt []byte) (*targets.List, error) {
114115
if err != nil {
115116
return nil, err
116117
}
117-
stages, _, err := instructions.Parse(dockerfile.AST)
118+
stages, _, err := instructions.Parse(dockerfile.AST, instructions.ParseOpts{})
118119
if err != nil {
119120
return nil, err
120121
}
@@ -186,7 +187,10 @@ func toDispatchState(ctx context.Context, dt []byte, opt ConvertOpt) (*dispatchS
186187

187188
proxyEnv := proxyEnvFromBuildArgs(opt.BuildArgs)
188189

189-
stages, metaArgs, err := instructions.Parse(dockerfile.AST)
190+
parseOpts := instructions.ParseOpts{
191+
InstructionHook: opt.InstructionHook,
192+
}
193+
stages, metaArgs, err := instructions.Parse(dockerfile.AST, parseOpts)
190194
if err != nil {
191195
return nil, err
192196
}
@@ -561,6 +565,7 @@ func toDispatchState(ctx context.Context, dt []byte, opt ConvertOpt) (*dispatchS
561565
cgroupParent: opt.CgroupParent,
562566
llbCaps: opt.LLBCaps,
563567
sourceMap: opt.SourceMap,
568+
instHook: opt.InstructionHook,
564569
}
565570

566571
if err = dispatchOnBuildTriggers(d, d.image.Config.OnBuild, opt); err != nil {
@@ -696,6 +701,7 @@ type dispatchOpt struct {
696701
cgroupParent string
697702
llbCaps *apicaps.CapSet
698703
sourceMap *llb.SourceMap
704+
instHook *types.InstructionHook
699705
}
700706

701707
func dispatch(d *dispatchState, cmd command, opt dispatchOpt) error {
@@ -903,6 +909,9 @@ type command struct {
903909
}
904910

905911
func dispatchOnBuildTriggers(d *dispatchState, triggers []string, opt dispatchOpt) error {
912+
parseOpts := instructions.ParseOpts{
913+
InstructionHook: opt.instHook,
914+
}
906915
for _, trigger := range triggers {
907916
ast, err := parser.Parse(strings.NewReader(trigger))
908917
if err != nil {
@@ -911,7 +920,7 @@ func dispatchOnBuildTriggers(d *dispatchState, triggers []string, opt dispatchOp
911920
if len(ast.AST.Children) != 1 {
912921
return errors.New("onbuild trigger should be a single expression")
913922
}
914-
ic, err := instructions.ParseCommand(ast.AST.Children[0])
923+
ic, err := instructions.ParseCommand(ast.AST.Children[0], parseOpts)
915924
if err != nil {
916925
return err
917926
}
@@ -1001,6 +1010,12 @@ func dispatchRun(d *dispatchState, c *instructions.RunCommand, proxy *llb.ProxyE
10011010
args = withShell(d.image, args)
10021011
}
10031012

1013+
argsForHistory := args
1014+
if dopt.instHook != nil && dopt.instHook.Run != nil {
1015+
args = append(dopt.instHook.Run.Entrypoint, args...)
1016+
// leave argsForHistory unmodified
1017+
}
1018+
10041019
env, err := d.state.Env(context.TODO())
10051020
if err != nil {
10061021
return err
@@ -1067,7 +1082,7 @@ func dispatchRun(d *dispatchState, c *instructions.RunCommand, proxy *llb.ProxyE
10671082
}
10681083

10691084
d.state = d.state.Run(opt...).Root()
1070-
return commitToHistory(&d.image, "RUN "+runCommandString(args, d.buildArgs, shell.BuildEnvs(env)), true, &d.state, d.epoch)
1085+
return commitToHistory(&d.image, "RUN "+runCommandString(argsForHistory, d.buildArgs, shell.BuildEnvs(env)), true, &d.state, d.epoch)
10711086
}
10721087

10731088
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
@@ -252,6 +252,7 @@ func TestIntegration(t *testing.T) {
252252
"amd64/bullseye-20230109-slim": "docker.io/amd64/debian:bullseye-20230109-slim@sha256:1acb06a0c31fb467eb8327ad361f1091ab265e0bf26d452dea45dcb0c0ea5e75",
253253
}),
254254
)...)
255+
integration.Run(t, instHookTests, opts...)
255256
}
256257

257258
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

@@ -337,7 +338,7 @@ type ShellDependantCmdLine struct {
337338
// RUN ["echo", "hi"] # echo hi
338339
type RunCommand struct {
339340
withNameAndCode
340-
withExternalData
341+
WithInstructionHook
341342
ShellDependantCmdLine
342343
FlagsUsed []string
343344
}
@@ -548,3 +549,21 @@ func (c *withExternalData) setExternalValue(k, v interface{}) {
548549
}
549550
c.m[k] = v
550551
}
552+
553+
type WithInstructionHook struct {
554+
withExternalData
555+
}
556+
557+
const instHookKey = "dockerfile/run/instruction-hook"
558+
559+
func (c *WithInstructionHook) GetInstructionHook() *types.InstructionHook {
560+
x := c.getExternalValue(instHookKey)
561+
if x == nil {
562+
return nil
563+
}
564+
return x.(*types.InstructionHook)
565+
}
566+
567+
func (c *WithInstructionHook) SetInstructionHook(h *types.InstructionHook) {
568+
c.setExternalValue(instHookKey, h)
569+
}

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: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,15 @@ import (
1616
"github.com/docker/docker/api/types/strslice"
1717
"github.com/moby/buildkit/frontend/dockerfile/command"
1818
"github.com/moby/buildkit/frontend/dockerfile/parser"
19+
"github.com/moby/buildkit/frontend/dockerui/types"
1920
"github.com/moby/buildkit/util/suggest"
2021
"github.com/pkg/errors"
2122
)
2223

24+
type ParseOpts struct {
25+
InstructionHook *types.InstructionHook
26+
}
27+
2328
type parseRequest struct {
2429
command string
2530
args []string
@@ -29,6 +34,7 @@ type parseRequest struct {
2934
original string
3035
location []parser.Range
3136
comments []string
37+
opts ParseOpts
3238
}
3339

3440
var parseRunPreHooks []func(*RunCommand, parseRequest) error
@@ -65,11 +71,12 @@ func newParseRequestFromNode(node *parser.Node) parseRequest {
6571
}
6672

6773
// ParseInstruction converts an AST to a typed instruction (either a command or a build stage beginning when encountering a `FROM` statement)
68-
func ParseInstruction(node *parser.Node) (v interface{}, err error) {
74+
func ParseInstruction(node *parser.Node, opts ParseOpts) (v interface{}, err error) {
6975
defer func() {
7076
err = parser.WithLocation(err, node.Location())
7177
}()
7278
req := newParseRequestFromNode(node)
79+
req.opts = opts
7380
switch strings.ToLower(node.Value) {
7481
case command.Env:
7582
return parseEnv(req)
@@ -112,8 +119,8 @@ func ParseInstruction(node *parser.Node) (v interface{}, err error) {
112119
}
113120

114121
// ParseCommand converts an AST to a typed Command
115-
func ParseCommand(node *parser.Node) (Command, error) {
116-
s, err := ParseInstruction(node)
122+
func ParseCommand(node *parser.Node, opts ParseOpts) (Command, error) {
123+
s, err := ParseInstruction(node, opts)
117124
if err != nil {
118125
return nil, err
119126
}
@@ -148,9 +155,9 @@ func (e *parseError) Unwrap() error {
148155

149156
// Parse a Dockerfile into a collection of buildable stages.
150157
// metaArgs is a collection of ARG instructions that occur before the first FROM.
151-
func Parse(ast *parser.Node) (stages []Stage, metaArgs []ArgCommand, err error) {
158+
func Parse(ast *parser.Node, opts ParseOpts) (stages []Stage, metaArgs []ArgCommand, err error) {
152159
for _, n := range ast.Children {
153-
cmd, err := ParseInstruction(n)
160+
cmd, err := ParseInstruction(n, opts)
154161
if err != nil {
155162
return nil, nil, &parseError{inner: err, node: n}
156163
}
@@ -444,6 +451,7 @@ func parseShellDependentCommand(req parseRequest, command string, emptyAsNil boo
444451

445452
func parseRun(req parseRequest) (*RunCommand, error) {
446453
cmd := &RunCommand{}
454+
cmd.SetInstructionHook(req.opts.InstructionHook)
447455

448456
for _, fn := range parseRunPreHooks {
449457
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)