builder.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package dockerfile
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "strings"
  8. "github.com/Sirupsen/logrus"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/backend"
  11. "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/builder"
  13. "github.com/docker/docker/builder/dockerfile/command"
  14. "github.com/docker/docker/builder/dockerfile/parser"
  15. "github.com/docker/docker/builder/remotecontext"
  16. "github.com/docker/docker/pkg/streamformatter"
  17. "github.com/docker/docker/pkg/stringid"
  18. "github.com/pkg/errors"
  19. "golang.org/x/net/context"
  20. "golang.org/x/sync/syncmap"
  21. )
  22. var validCommitCommands = map[string]bool{
  23. "cmd": true,
  24. "entrypoint": true,
  25. "healthcheck": true,
  26. "env": true,
  27. "expose": true,
  28. "label": true,
  29. "onbuild": true,
  30. "user": true,
  31. "volume": true,
  32. "workdir": true,
  33. }
  34. var defaultLogConfig = container.LogConfig{Type: "none"}
  35. // BuildManager is shared across all Builder objects
  36. type BuildManager struct {
  37. backend builder.Backend
  38. pathCache pathCache // TODO: make this persistent
  39. }
  40. // NewBuildManager creates a BuildManager
  41. func NewBuildManager(b builder.Backend) *BuildManager {
  42. return &BuildManager{backend: b, pathCache: &syncmap.Map{}}
  43. }
  44. // Build starts a new build from a BuildConfig
  45. func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (*builder.Result, error) {
  46. if config.Options.Dockerfile == "" {
  47. config.Options.Dockerfile = builder.DefaultDockerfileName
  48. }
  49. source, dockerfile, err := remotecontext.Detect(config)
  50. if err != nil {
  51. return nil, err
  52. }
  53. if source != nil {
  54. defer func() {
  55. if err := source.Close(); err != nil {
  56. logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
  57. }
  58. }()
  59. }
  60. builderOptions := builderOptions{
  61. Options: config.Options,
  62. ProgressWriter: config.ProgressWriter,
  63. Backend: bm.backend,
  64. PathCache: bm.pathCache,
  65. }
  66. return newBuilder(ctx, builderOptions).build(source, dockerfile)
  67. }
  68. // builderOptions are the dependencies required by the builder
  69. type builderOptions struct {
  70. Options *types.ImageBuildOptions
  71. Backend builder.Backend
  72. ProgressWriter backend.ProgressWriter
  73. PathCache pathCache
  74. }
  75. // Builder is a Dockerfile builder
  76. // It implements the builder.Backend interface.
  77. type Builder struct {
  78. options *types.ImageBuildOptions
  79. Stdout io.Writer
  80. Stderr io.Writer
  81. Aux *streamformatter.AuxFormatter
  82. Output io.Writer
  83. docker builder.Backend
  84. source builder.Source
  85. clientCtx context.Context
  86. tmpContainers map[string]struct{}
  87. imageContexts *imageContexts // helper for storing contexts from builds
  88. disableCommit bool
  89. cacheBusted bool
  90. buildArgs *buildArgs
  91. imageCache builder.ImageCache
  92. }
  93. // newBuilder creates a new Dockerfile builder from an optional dockerfile and a Options.
  94. func newBuilder(clientCtx context.Context, options builderOptions) *Builder {
  95. config := options.Options
  96. if config == nil {
  97. config = new(types.ImageBuildOptions)
  98. }
  99. b := &Builder{
  100. clientCtx: clientCtx,
  101. options: config,
  102. Stdout: options.ProgressWriter.StdoutFormatter,
  103. Stderr: options.ProgressWriter.StderrFormatter,
  104. Aux: options.ProgressWriter.AuxFormatter,
  105. Output: options.ProgressWriter.Output,
  106. docker: options.Backend,
  107. tmpContainers: map[string]struct{}{},
  108. buildArgs: newBuildArgs(config.BuildArgs),
  109. }
  110. b.imageContexts = &imageContexts{b: b, cache: options.PathCache}
  111. return b
  112. }
  113. func (b *Builder) resetImageCache() {
  114. if icb, ok := b.docker.(builder.ImageCacheBuilder); ok {
  115. b.imageCache = icb.MakeImageCache(b.options.CacheFrom)
  116. }
  117. b.cacheBusted = false
  118. }
  119. // Build runs the Dockerfile builder by parsing the Dockerfile and executing
  120. // the instructions from the file.
  121. func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
  122. defer b.imageContexts.unmount()
  123. // TODO: Remove source field from Builder
  124. b.source = source
  125. addNodesForLabelOption(dockerfile.AST, b.options.Labels)
  126. if err := checkDispatchDockerfile(dockerfile.AST); err != nil {
  127. return nil, err
  128. }
  129. dispatchState, err := b.dispatchDockerfileWithCancellation(dockerfile)
  130. if err != nil {
  131. return nil, err
  132. }
  133. if b.options.Target != "" && !dispatchState.isCurrentStage(b.options.Target) {
  134. return nil, errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target)
  135. }
  136. b.warnOnUnusedBuildArgs()
  137. if dispatchState.imageID == "" {
  138. return nil, errors.New("No image was generated. Is your Dockerfile empty?")
  139. }
  140. return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
  141. }
  142. func emitImageID(aux *streamformatter.AuxFormatter, state *dispatchState) error {
  143. if aux == nil || state.imageID == "" {
  144. return nil
  145. }
  146. return aux.Emit(types.BuildResult{ID: state.imageID})
  147. }
  148. func (b *Builder) dispatchDockerfileWithCancellation(dockerfile *parser.Result) (*dispatchState, error) {
  149. shlex := NewShellLex(dockerfile.EscapeToken)
  150. state := newDispatchState()
  151. total := len(dockerfile.AST.Children)
  152. var err error
  153. for i, n := range dockerfile.AST.Children {
  154. select {
  155. case <-b.clientCtx.Done():
  156. logrus.Debug("Builder: build cancelled!")
  157. fmt.Fprint(b.Stdout, "Build cancelled")
  158. return nil, errors.New("Build cancelled")
  159. default:
  160. // Not cancelled yet, keep going...
  161. }
  162. // If this is a FROM and we have a previous image then
  163. // emit an aux message for that image since it is the
  164. // end of the previous stage
  165. if n.Value == command.From {
  166. if err := emitImageID(b.Aux, state); err != nil {
  167. return nil, err
  168. }
  169. }
  170. if n.Value == command.From && state.isCurrentStage(b.options.Target) {
  171. break
  172. }
  173. opts := dispatchOptions{
  174. state: state,
  175. stepMsg: formatStep(i, total),
  176. node: n,
  177. shlex: shlex,
  178. }
  179. if state, err = b.dispatch(opts); err != nil {
  180. if b.options.ForceRemove {
  181. b.clearTmp()
  182. }
  183. return nil, err
  184. }
  185. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(state.imageID))
  186. if b.options.Remove {
  187. b.clearTmp()
  188. }
  189. }
  190. // Emit a final aux message for the final image
  191. if err := emitImageID(b.Aux, state); err != nil {
  192. return nil, err
  193. }
  194. return state, nil
  195. }
  196. func addNodesForLabelOption(dockerfile *parser.Node, labels map[string]string) {
  197. if len(labels) == 0 {
  198. return
  199. }
  200. node := parser.NodeFromLabels(labels)
  201. dockerfile.Children = append(dockerfile.Children, node)
  202. }
  203. // check if there are any leftover build-args that were passed but not
  204. // consumed during build. Print a warning, if there are any.
  205. func (b *Builder) warnOnUnusedBuildArgs() {
  206. leftoverArgs := b.buildArgs.UnreferencedOptionArgs()
  207. if len(leftoverArgs) > 0 {
  208. fmt.Fprintf(b.Stderr, "[Warning] One or more build-args %v were not consumed\n", leftoverArgs)
  209. }
  210. }
  211. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  212. // It will:
  213. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  214. // - Do build by calling builder.dispatch() to call all entries' handling routines
  215. //
  216. // BuildFromConfig is used by the /commit endpoint, with the changes
  217. // coming from the query parameter of the same name.
  218. //
  219. // TODO: Remove?
  220. func BuildFromConfig(config *container.Config, changes []string) (*container.Config, error) {
  221. if len(changes) == 0 {
  222. return config, nil
  223. }
  224. b := newBuilder(context.Background(), builderOptions{})
  225. dockerfile, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
  226. if err != nil {
  227. return nil, err
  228. }
  229. // ensure that the commands are valid
  230. for _, n := range dockerfile.AST.Children {
  231. if !validCommitCommands[n.Value] {
  232. return nil, fmt.Errorf("%s is not a valid change command", n.Value)
  233. }
  234. }
  235. b.Stdout = ioutil.Discard
  236. b.Stderr = ioutil.Discard
  237. b.disableCommit = true
  238. if err := checkDispatchDockerfile(dockerfile.AST); err != nil {
  239. return nil, err
  240. }
  241. dispatchState := newDispatchState()
  242. dispatchState.runConfig = config
  243. return dispatchFromDockerfile(b, dockerfile, dispatchState)
  244. }
  245. func checkDispatchDockerfile(dockerfile *parser.Node) error {
  246. for _, n := range dockerfile.Children {
  247. if err := checkDispatch(n); err != nil {
  248. return errors.Wrapf(err, "Dockerfile parse error line %d", n.StartLine)
  249. }
  250. }
  251. return nil
  252. }
  253. func dispatchFromDockerfile(b *Builder, result *parser.Result, dispatchState *dispatchState) (*container.Config, error) {
  254. shlex := NewShellLex(result.EscapeToken)
  255. ast := result.AST
  256. total := len(ast.Children)
  257. for i, n := range ast.Children {
  258. opts := dispatchOptions{
  259. state: dispatchState,
  260. stepMsg: formatStep(i, total),
  261. node: n,
  262. shlex: shlex,
  263. }
  264. if _, err := b.dispatch(opts); err != nil {
  265. return nil, err
  266. }
  267. }
  268. return dispatchState.runConfig, nil
  269. }