builder.go 8.5 KB

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