builder.go 8.5 KB

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