builder.go 8.1 KB

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