Tizen_4.0 base
[platform/upstream/docker-engine.git] / builder / dockerfile / evaluator.go
1 // Package dockerfile is the evaluation step in the Dockerfile parse/evaluate pipeline.
2 //
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.
8 //
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.
11 //
12 // ONBUILD is a special case, which is covered in the onbuild() func in
13 // dispatchers.go.
14 //
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).
20 package dockerfile
21
22 import (
23         "bytes"
24         "fmt"
25         "runtime"
26         "strings"
27
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"
35 )
36
37 // Environment variable interpolation will happen on these statements only.
38 var replaceEnvAllowed = map[string]bool{
39         command.Env:        true,
40         command.Label:      true,
41         command.Add:        true,
42         command.Copy:       true,
43         command.Workdir:    true,
44         command.Expose:     true,
45         command.Volume:     true,
46         command.User:       true,
47         command.StopSignal: true,
48         command.Arg:        true,
49 }
50
51 // Certain commands are allowed to have their args split into more
52 // words after env var replacements. Meaning:
53 //   ENV foo="123 456"
54 //   EXPOSE $foo
55 // should result in the same thing as:
56 //   EXPOSE 123 456
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{
61         command.Expose: true,
62 }
63
64 type dispatchRequest struct {
65         builder    *Builder // TODO: replace this with a smaller interface
66         args       []string
67         attributes map[string]bool
68         flags      *BFlags
69         original   string
70         shlex      *ShellLex
71         state      *dispatchState
72         source     builder.Source
73 }
74
75 func newDispatchRequestFromOptions(options dispatchOptions, builder *Builder, args []string) dispatchRequest {
76         return dispatchRequest{
77                 builder:    builder,
78                 args:       args,
79                 attributes: options.node.Attributes,
80                 original:   options.node.Original,
81                 flags:      NewBFlagsWithArgs(options.node.Flags),
82                 shlex:      options.shlex,
83                 state:      options.state,
84                 source:     options.source,
85         }
86 }
87
88 type dispatcher func(dispatchRequest) error
89
90 var evaluateTable map[string]dispatcher
91
92 func init() {
93         evaluateTable = map[string]dispatcher{
94                 command.Add:         add,
95                 command.Arg:         arg,
96                 command.Cmd:         cmd,
97                 command.Copy:        dispatchCopy, // copy() is a go builtin
98                 command.Entrypoint:  entrypoint,
99                 command.Env:         env,
100                 command.Expose:      expose,
101                 command.From:        from,
102                 command.Healthcheck: healthcheck,
103                 command.Label:       label,
104                 command.Maintainer:  maintainer,
105                 command.Onbuild:     onbuild,
106                 command.Run:         run,
107                 command.Shell:       shell,
108                 command.StopSignal:  stopSignal,
109                 command.User:        user,
110                 command.Volume:      volume,
111                 command.Workdir:     workdir,
112         }
113 }
114
115 func formatStep(stepN int, stepTotal int) string {
116         return fmt.Sprintf("%d/%d", stepN+1, stepTotal)
117 }
118
119 // This method is the entrypoint to all statement handling routines.
120 //
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.
126 //
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
132 // features.
133 func (b *Builder) dispatch(options dispatchOptions) (*dispatchState, error) {
134         node := options.node
135         cmd := node.Value
136         upperCasedCmd := strings.ToUpper(cmd)
137
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()
142                 return nil, err
143         }
144
145         msg := bytes.NewBufferString(fmt.Sprintf("Step %s : %s%s",
146                 options.stepMsg, upperCasedCmd, formatFlags(node.Flags)))
147
148         args := []string{}
149         ast := node
150         if cmd == command.Onbuild {
151                 var err error
152                 ast, args, err = handleOnBuildNode(node, msg)
153                 if err != nil {
154                         return nil, err
155                 }
156         }
157
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)
162         if err != nil {
163                 buildsFailed.WithValues(metricsErrorProcessingCommandsError).Inc()
164                 return nil, err
165         }
166         args = append(args, words...)
167
168         fmt.Fprintln(b.Stdout, msg.String())
169
170         f, ok := evaluateTable[cmd]
171         if !ok {
172                 buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
173                 return nil, fmt.Errorf("unknown instruction: %s", upperCasedCmd)
174         }
175         options.state.updateRunConfig()
176         err = f(newDispatchRequestFromOptions(options, b, args))
177         return options.state, err
178 }
179
180 type dispatchOptions struct {
181         state   *dispatchState
182         stepMsg string
183         node    *parser.Node
184         shlex   *ShellLex
185         source  builder.Source
186 }
187
188 // dispatchState is a data object which is modified by dispatchers
189 type dispatchState struct {
190         runConfig  *container.Config
191         maintainer string
192         cmdSet     bool
193         imageID    string
194         baseImage  builder.Image
195         stageName  string
196 }
197
198 func newDispatchState() *dispatchState {
199         return &dispatchState{runConfig: &container.Config{}}
200 }
201
202 func (s *dispatchState) updateRunConfig() {
203         s.runConfig.Image = s.imageID
204 }
205
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() == "")
209 }
210
211 func (s *dispatchState) isCurrentStage(target string) bool {
212         if target == "" {
213                 return false
214         }
215         return strings.EqualFold(s.stageName, target)
216 }
217
218 func (s *dispatchState) beginStage(stageName string, image builder.Image) {
219         s.stageName = stageName
220         s.imageID = image.ImageID()
221
222         if image.RunConfig() != nil {
223                 s.runConfig = image.RunConfig()
224         } else {
225                 s.runConfig = &container.Config{}
226         }
227         s.baseImage = image
228         s.setDefaultPath()
229 }
230
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() {
237                 platform = "linux"
238         }
239         if system.DefaultPathEnv(platform) == "" {
240                 return
241         }
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))
245         }
246 }
247
248 func handleOnBuildNode(ast *parser.Node, msg *bytes.Buffer) (*parser.Node, []string, error) {
249         if ast.Next == nil {
250                 return nil, nil, errors.New("ONBUILD requires at least one argument")
251         }
252         ast = ast.Next.Children[0]
253         msg.WriteString(" " + ast.Value + formatFlags(ast.Flags))
254         return ast, []string{ast.Value}, nil
255 }
256
257 func formatFlags(flags []string) string {
258         if len(flags) > 0 {
259                 return " " + strings.Join(flags, " ")
260         }
261         return ""
262 }
263
264 func getDispatchArgsFromNode(ast *parser.Node, processFunc processWordFunc, msg *bytes.Buffer) ([]string, error) {
265         args := []string{}
266         for i := 0; ast.Next != nil; i++ {
267                 ast = ast.Next
268                 words, err := processFunc(ast.Value)
269                 if err != nil {
270                         return nil, err
271                 }
272                 args = append(args, words...)
273                 msg.WriteString(" " + ast.Value)
274         }
275         return args, nil
276 }
277
278 type processWordFunc func(string) ([]string, error)
279
280 func createProcessWordFunc(shlex *ShellLex, cmd string, envs []string) processWordFunc {
281         switch {
282         case !replaceEnvAllowed[cmd]:
283                 return func(word string) ([]string, error) {
284                         return []string{word}, nil
285                 }
286         case allowWordExpansion[cmd]:
287                 return func(word string) ([]string, error) {
288                         return shlex.ProcessWords(word, envs)
289                 }
290         default:
291                 return func(word string) ([]string, error) {
292                         word, err := shlex.ProcessWord(word, envs)
293                         return []string{word}, err
294                 }
295         }
296 }
297
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 {
304         cmd := ast.Value
305         upperCasedCmd := strings.ToUpper(cmd)
306
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 {
310                 return err
311         }
312
313         // The instruction itself is ONBUILD, we will make sure it follows with at
314         // least one argument
315         if upperCasedCmd == "ONBUILD" {
316                 if ast.Next == nil {
317                         buildsFailed.WithValues(metricsMissingOnbuildArgumentsError).Inc()
318                         return errors.New("ONBUILD requires at least one argument")
319                 }
320         }
321
322         if _, ok := evaluateTable[cmd]; ok {
323                 return nil
324         }
325         buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
326         return errors.Errorf("unknown instruction: %s", upperCasedCmd)
327 }