1 // Package dockerfile is the evaluation step in the Dockerfile parse/evaluate pipeline.
3 // It incorporates a dispatch table based on the parser.Node values (see the
4 // parser package for more information) that are yielded from the parser itself.
5 // Calling newBuilder with the BuildOpts struct can be used to customize the
6 // experience for execution purposes only. Parsing is controlled in the parser
7 // package, and this division of responsibility should be respected.
9 // Please see the jump table targets for the actual invocations, most of which
10 // will call out to the functions in internals.go to deal with their tasks.
12 // ONBUILD is a special case, which is covered in the onbuild() func in
15 // The evaluator uses the concept of "steps", which are usually each processable
16 // line in the Dockerfile. Each step is numbered and certain actions are taken
17 // before and after each step, such as creating an image ID and removing temporary
18 // containers and images. Note that ONBUILD creates a kinda-sorta "sub run" which
19 // includes its own set of steps (usually only one of them).
28 "github.com/docker/docker/api/types/container"
29 "github.com/docker/docker/builder"
30 "github.com/docker/docker/builder/dockerfile/command"
31 "github.com/docker/docker/builder/dockerfile/parser"
32 "github.com/docker/docker/pkg/system"
33 "github.com/docker/docker/runconfig/opts"
34 "github.com/pkg/errors"
37 // Environment variable interpolation will happen on these statements only.
38 var replaceEnvAllowed = map[string]bool{
43 command.Workdir: true,
47 command.StopSignal: true,
51 // Certain commands are allowed to have their args split into more
52 // words after env var replacements. Meaning:
55 // should result in the same thing as:
57 // and not treat "123 456" as a single word.
58 // Note that: EXPOSE "$foo" and EXPOSE $foo are not the same thing.
59 // Quotes will cause it to still be treated as single word.
60 var allowWordExpansion = map[string]bool{
64 type dispatchRequest struct {
65 builder *Builder // TODO: replace this with a smaller interface
67 attributes map[string]bool
75 func newDispatchRequestFromOptions(options dispatchOptions, builder *Builder, args []string) dispatchRequest {
76 return dispatchRequest{
79 attributes: options.node.Attributes,
80 original: options.node.Original,
81 flags: NewBFlagsWithArgs(options.node.Flags),
84 source: options.source,
88 type dispatcher func(dispatchRequest) error
90 var evaluateTable map[string]dispatcher
93 evaluateTable = map[string]dispatcher{
97 command.Copy: dispatchCopy, // copy() is a go builtin
98 command.Entrypoint: entrypoint,
100 command.Expose: expose,
102 command.Healthcheck: healthcheck,
103 command.Label: label,
104 command.Maintainer: maintainer,
105 command.Onbuild: onbuild,
107 command.Shell: shell,
108 command.StopSignal: stopSignal,
110 command.Volume: volume,
111 command.Workdir: workdir,
115 func formatStep(stepN int, stepTotal int) string {
116 return fmt.Sprintf("%d/%d", stepN+1, stepTotal)
119 // This method is the entrypoint to all statement handling routines.
121 // Almost all nodes will have this structure:
122 // Child[Node, Node, Node] where Child is from parser.Node.Children and each
123 // node comes from parser.Node.Next. This forms a "line" with a statement and
124 // arguments and we process them in this normalized form by hitting
125 // evaluateTable with the leaf nodes of the command and the Builder object.
127 // ONBUILD is a special case; in this case the parser will emit:
128 // Child[Node, Child[Node, Node...]] where the first node is the literal
129 // "onbuild" and the child entrypoint is the command of the ONBUILD statement,
130 // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to
131 // deal with that, at least until it becomes more of a general concern with new
133 func (b *Builder) dispatch(options dispatchOptions) (*dispatchState, error) {
136 upperCasedCmd := strings.ToUpper(cmd)
138 // To ensure the user is given a decent error message if the platform
139 // on which the daemon is running does not support a builder command.
140 if err := platformSupports(strings.ToLower(cmd)); err != nil {
141 buildsFailed.WithValues(metricsCommandNotSupportedError).Inc()
145 msg := bytes.NewBufferString(fmt.Sprintf("Step %s : %s%s",
146 options.stepMsg, upperCasedCmd, formatFlags(node.Flags)))
150 if cmd == command.Onbuild {
152 ast, args, err = handleOnBuildNode(node, msg)
158 runConfigEnv := options.state.runConfig.Env
159 envs := append(runConfigEnv, b.buildArgs.FilterAllowed(runConfigEnv)...)
160 processFunc := createProcessWordFunc(options.shlex, cmd, envs)
161 words, err := getDispatchArgsFromNode(ast, processFunc, msg)
163 buildsFailed.WithValues(metricsErrorProcessingCommandsError).Inc()
166 args = append(args, words...)
168 fmt.Fprintln(b.Stdout, msg.String())
170 f, ok := evaluateTable[cmd]
172 buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
173 return nil, fmt.Errorf("unknown instruction: %s", upperCasedCmd)
175 options.state.updateRunConfig()
176 err = f(newDispatchRequestFromOptions(options, b, args))
177 return options.state, err
180 type dispatchOptions struct {
185 source builder.Source
188 // dispatchState is a data object which is modified by dispatchers
189 type dispatchState struct {
190 runConfig *container.Config
194 baseImage builder.Image
198 func newDispatchState() *dispatchState {
199 return &dispatchState{runConfig: &container.Config{}}
202 func (s *dispatchState) updateRunConfig() {
203 s.runConfig.Image = s.imageID
206 // hasFromImage returns true if the builder has processed a `FROM <image>` line
207 func (s *dispatchState) hasFromImage() bool {
208 return s.imageID != "" || (s.baseImage != nil && s.baseImage.ImageID() == "")
211 func (s *dispatchState) isCurrentStage(target string) bool {
215 return strings.EqualFold(s.stageName, target)
218 func (s *dispatchState) beginStage(stageName string, image builder.Image) {
219 s.stageName = stageName
220 s.imageID = image.ImageID()
222 if image.RunConfig() != nil {
223 s.runConfig = image.RunConfig()
225 s.runConfig = &container.Config{}
231 // Add the default PATH to runConfig.ENV if one exists for the platform and there
232 // is no PATH set. Note that Windows containers on Windows won't have one as it's set by HCS
233 func (s *dispatchState) setDefaultPath() {
234 // TODO @jhowardmsft LCOW Support - This will need revisiting later
235 platform := runtime.GOOS
236 if system.LCOWSupported() {
239 if system.DefaultPathEnv(platform) == "" {
242 envMap := opts.ConvertKVStringsToMap(s.runConfig.Env)
243 if _, ok := envMap["PATH"]; !ok {
244 s.runConfig.Env = append(s.runConfig.Env, "PATH="+system.DefaultPathEnv(platform))
248 func handleOnBuildNode(ast *parser.Node, msg *bytes.Buffer) (*parser.Node, []string, error) {
250 return nil, nil, errors.New("ONBUILD requires at least one argument")
252 ast = ast.Next.Children[0]
253 msg.WriteString(" " + ast.Value + formatFlags(ast.Flags))
254 return ast, []string{ast.Value}, nil
257 func formatFlags(flags []string) string {
259 return " " + strings.Join(flags, " ")
264 func getDispatchArgsFromNode(ast *parser.Node, processFunc processWordFunc, msg *bytes.Buffer) ([]string, error) {
266 for i := 0; ast.Next != nil; i++ {
268 words, err := processFunc(ast.Value)
272 args = append(args, words...)
273 msg.WriteString(" " + ast.Value)
278 type processWordFunc func(string) ([]string, error)
280 func createProcessWordFunc(shlex *ShellLex, cmd string, envs []string) processWordFunc {
282 case !replaceEnvAllowed[cmd]:
283 return func(word string) ([]string, error) {
284 return []string{word}, nil
286 case allowWordExpansion[cmd]:
287 return func(word string) ([]string, error) {
288 return shlex.ProcessWords(word, envs)
291 return func(word string) ([]string, error) {
292 word, err := shlex.ProcessWord(word, envs)
293 return []string{word}, err
298 // checkDispatch does a simple check for syntax errors of the Dockerfile.
299 // Because some of the instructions can only be validated through runtime,
300 // arg, env, etc., this syntax check will not be complete and could not replace
301 // the runtime check. Instead, this function is only a helper that allows
302 // user to find out the obvious error in Dockerfile earlier on.
303 func checkDispatch(ast *parser.Node) error {
305 upperCasedCmd := strings.ToUpper(cmd)
307 // To ensure the user is given a decent error message if the platform
308 // on which the daemon is running does not support a builder command.
309 if err := platformSupports(strings.ToLower(cmd)); err != nil {
313 // The instruction itself is ONBUILD, we will make sure it follows with at
314 // least one argument
315 if upperCasedCmd == "ONBUILD" {
317 buildsFailed.WithValues(metricsMissingOnbuildArgumentsError).Inc()
318 return errors.New("ONBUILD requires at least one argument")
322 if _, ok := evaluateTable[cmd]; ok {
325 buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
326 return errors.Errorf("unknown instruction: %s", upperCasedCmd)