Skip to content

Commit eff4fb7

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 3683f87 commit eff4fb7

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.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
@@ -25,6 +25,7 @@ import (
2525
"github.com/moby/buildkit/frontend/dockerfile/parser"
2626
"github.com/moby/buildkit/frontend/dockerfile/shell"
2727
"github.com/moby/buildkit/frontend/dockerui"
28+
"github.com/moby/buildkit/frontend/dockerui/types"
2829
"github.com/moby/buildkit/frontend/subrequests/outline"
2930
"github.com/moby/buildkit/frontend/subrequests/targets"
3031
"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
}
@@ -565,6 +569,7 @@ func toDispatchState(ctx context.Context, dt []byte, opt ConvertOpt) (*dispatchS
565569
cgroupParent: opt.CgroupParent,
566570
llbCaps: opt.LLBCaps,
567571
sourceMap: opt.SourceMap,
572+
instHook: opt.InstructionHook,
568573
}
569574

570575
if err = dispatchOnBuildTriggers(d, d.image.Config.OnBuild, opt); err != nil {
@@ -700,6 +705,7 @@ type dispatchOpt struct {
700705
cgroupParent string
701706
llbCaps *apicaps.CapSet
702707
sourceMap *llb.SourceMap
708+
instHook *types.InstructionHook
703709
}
704710

705711
func dispatch(d *dispatchState, cmd command, opt dispatchOpt) error {
@@ -910,6 +916,9 @@ type command struct {
910916
}
911917

912918
func dispatchOnBuildTriggers(d *dispatchState, triggers []string, opt dispatchOpt) error {
919+
parseOpts := instructions.ParseOpts{
920+
InstructionHook: opt.instHook,
921+
}
913922
for _, trigger := range triggers {
914923
ast, err := parser.Parse(strings.NewReader(trigger))
915924
if err != nil {
@@ -918,7 +927,7 @@ func dispatchOnBuildTriggers(d *dispatchState, triggers []string, opt dispatchOp
918927
if len(ast.AST.Children) != 1 {
919928
return errors.New("onbuild trigger should be a single expression")
920929
}
921-
ic, err := instructions.ParseCommand(ast.AST.Children[0])
930+
ic, err := instructions.ParseCommand(ast.AST.Children[0], parseOpts)
922931
if err != nil {
923932
return err
924933
}
@@ -1008,6 +1017,12 @@ func dispatchRun(d *dispatchState, c *instructions.RunCommand, proxy *llb.ProxyE
10081017
args = withShell(d.image, args)
10091018
}
10101019

1020+
argsForHistory := args
1021+
if dopt.instHook != nil && dopt.instHook.Run != nil {
1022+
args = append(dopt.instHook.Run.Entrypoint, args...)
1023+
// leave argsForHistory unmodified
1024+
}
1025+
10111026
env, err := d.state.Env(context.TODO())
10121027
if err != nil {
10131028
return err
@@ -1074,7 +1089,7 @@ func dispatchRun(d *dispatchState, c *instructions.RunCommand, proxy *llb.ProxyE
10741089
}
10751090

10761091
d.state = d.state.Run(opt...).Root()
1077-
return commitToHistory(&d.image, "RUN "+runCommandString(args, d.buildArgs, shell.BuildEnvs(env)), true, &d.state, d.epoch)
1092+
return commitToHistory(&d.image, "RUN "+runCommandString(argsForHistory, d.buildArgs, shell.BuildEnvs(env)), true, &d.state, d.epoch)
10781093
}
10791094

10801095
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
@@ -254,6 +254,7 @@ func TestIntegration(t *testing.T) {
254254
"amd64/bullseye-20230109-slim": "docker.io/amd64/debian:bullseye-20230109-slim@sha256:1acb06a0c31fb467eb8327ad361f1091ab265e0bf26d452dea45dcb0c0ea5e75",
255255
}),
256256
)...)
257+
integration.Run(t, instHookTests, opts...)
257258
}
258259

259260
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: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,17 @@ 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

2324
var excludePatternsEnabled = false
2425

26+
type ParseOpts struct {
27+
InstructionHook *types.InstructionHook
28+
}
29+
2530
type parseRequest struct {
2631
command string
2732
args []string
@@ -31,6 +36,7 @@ type parseRequest struct {
3136
original string
3237
location []parser.Range
3338
comments []string
39+
opts ParseOpts
3440
}
3541

3642
var parseRunPreHooks []func(*RunCommand, parseRequest) error
@@ -67,11 +73,12 @@ func newParseRequestFromNode(node *parser.Node) parseRequest {
6773
}
6874

6975
// ParseInstruction converts an AST to a typed instruction (either a command or a build stage beginning when encountering a `FROM` statement)
70-
func ParseInstruction(node *parser.Node) (v interface{}, err error) {
76+
func ParseInstruction(node *parser.Node, opts ParseOpts) (v interface{}, err error) {
7177
defer func() {
7278
err = parser.WithLocation(err, node.Location())
7379
}()
7480
req := newParseRequestFromNode(node)
81+
req.opts = opts
7582
switch strings.ToLower(node.Value) {
7683
case command.Env:
7784
return parseEnv(req)
@@ -114,8 +121,8 @@ func ParseInstruction(node *parser.Node) (v interface{}, err error) {
114121
}
115122

116123
// ParseCommand converts an AST to a typed Command
117-
func ParseCommand(node *parser.Node) (Command, error) {
118-
s, err := ParseInstruction(node)
124+
func ParseCommand(node *parser.Node, opts ParseOpts) (Command, error) {
125+
s, err := ParseInstruction(node, opts)
119126
if err != nil {
120127
return nil, err
121128
}
@@ -150,9 +157,9 @@ func (e *parseError) Unwrap() error {
150157

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

476483
func parseRun(req parseRequest) (*RunCommand, error) {
477484
cmd := &RunCommand{}
485+
cmd.SetInstructionHook(req.opts.InstructionHook)
478486

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