builder.go 8.8 KB

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