builder.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. // 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{
  42. backend: b,
  43. pathCache: &syncmap.Map{},
  44. }
  45. }
  46. // Build starts a new build from a BuildConfig
  47. func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (*builder.Result, error) {
  48. buildsTriggered.Inc()
  49. if config.Options.Dockerfile == "" {
  50. config.Options.Dockerfile = builder.DefaultDockerfileName
  51. }
  52. source, dockerfile, err := remotecontext.Detect(config)
  53. if err != nil {
  54. return nil, err
  55. }
  56. if source != nil {
  57. defer func() {
  58. if err := source.Close(); err != nil {
  59. logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
  60. }
  61. }()
  62. }
  63. builderOptions := builderOptions{
  64. Options: config.Options,
  65. ProgressWriter: config.ProgressWriter,
  66. Backend: bm.backend,
  67. PathCache: bm.pathCache,
  68. }
  69. return newBuilder(ctx, builderOptions).build(source, dockerfile)
  70. }
  71. // builderOptions are the dependencies required by the builder
  72. type builderOptions struct {
  73. Options *types.ImageBuildOptions
  74. Backend builder.Backend
  75. ProgressWriter backend.ProgressWriter
  76. PathCache pathCache
  77. }
  78. // Builder is a Dockerfile builder
  79. // It implements the builder.Backend interface.
  80. type Builder struct {
  81. options *types.ImageBuildOptions
  82. Stdout io.Writer
  83. Stderr io.Writer
  84. Aux *streamformatter.AuxFormatter
  85. Output io.Writer
  86. docker builder.Backend
  87. clientCtx context.Context
  88. buildStages *buildStages
  89. disableCommit bool
  90. buildArgs *buildArgs
  91. imageSources *imageSources
  92. pathCache pathCache
  93. containerManager *containerManager
  94. imageProber ImageProber
  95. }
  96. // newBuilder creates a new Dockerfile builder from an optional dockerfile and a Options.
  97. func newBuilder(clientCtx context.Context, options builderOptions) *Builder {
  98. config := options.Options
  99. if config == nil {
  100. config = new(types.ImageBuildOptions)
  101. }
  102. b := &Builder{
  103. clientCtx: clientCtx,
  104. options: config,
  105. Stdout: options.ProgressWriter.StdoutFormatter,
  106. Stderr: options.ProgressWriter.StderrFormatter,
  107. Aux: options.ProgressWriter.AuxFormatter,
  108. Output: options.ProgressWriter.Output,
  109. docker: options.Backend,
  110. buildArgs: newBuildArgs(config.BuildArgs),
  111. buildStages: newBuildStages(),
  112. imageSources: newImageSources(clientCtx, options),
  113. pathCache: options.PathCache,
  114. imageProber: newImageProber(options.Backend, config.CacheFrom, config.NoCache),
  115. containerManager: newContainerManager(options.Backend),
  116. }
  117. return b
  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.imageSources.Unmount()
  123. addNodesForLabelOption(dockerfile.AST, b.options.Labels)
  124. if err := checkDispatchDockerfile(dockerfile.AST); err != nil {
  125. buildsFailed.WithValues(metricsDockerfileSyntaxError).Inc()
  126. return nil, err
  127. }
  128. dispatchState, err := b.dispatchDockerfileWithCancellation(dockerfile, source)
  129. if err != nil {
  130. return nil, err
  131. }
  132. if b.options.Target != "" && !dispatchState.isCurrentStage(b.options.Target) {
  133. buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc()
  134. return nil, errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target)
  135. }
  136. b.buildArgs.WarnOnUnusedBuildArgs(b.Stderr)
  137. if dispatchState.imageID == "" {
  138. buildsFailed.WithValues(metricsDockerfileEmptyError).Inc()
  139. return nil, errors.New("No image was generated. Is your Dockerfile empty?")
  140. }
  141. return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
  142. }
  143. func emitImageID(aux *streamformatter.AuxFormatter, state *dispatchState) error {
  144. if aux == nil || state.imageID == "" {
  145. return nil
  146. }
  147. return aux.Emit(types.BuildResult{ID: state.imageID})
  148. }
  149. func (b *Builder) dispatchDockerfileWithCancellation(dockerfile *parser.Result, source builder.Source) (*dispatchState, error) {
  150. shlex := NewShellLex(dockerfile.EscapeToken)
  151. state := newDispatchState()
  152. total := len(dockerfile.AST.Children)
  153. var err error
  154. for i, n := range dockerfile.AST.Children {
  155. select {
  156. case <-b.clientCtx.Done():
  157. logrus.Debug("Builder: build cancelled!")
  158. fmt.Fprint(b.Stdout, "Build cancelled")
  159. buildsFailed.WithValues(metricsBuildCanceled).Inc()
  160. return nil, errors.New("Build cancelled")
  161. default:
  162. // Not cancelled yet, keep going...
  163. }
  164. // If this is a FROM and we have a previous image then
  165. // emit an aux message for that image since it is the
  166. // end of the previous stage
  167. if n.Value == command.From {
  168. if err := emitImageID(b.Aux, state); err != nil {
  169. return nil, err
  170. }
  171. }
  172. if n.Value == command.From && state.isCurrentStage(b.options.Target) {
  173. break
  174. }
  175. opts := dispatchOptions{
  176. state: state,
  177. stepMsg: formatStep(i, total),
  178. node: n,
  179. shlex: shlex,
  180. source: source,
  181. }
  182. if state, err = b.dispatch(opts); err != nil {
  183. if b.options.ForceRemove {
  184. b.containerManager.RemoveAll(b.Stdout)
  185. }
  186. return nil, err
  187. }
  188. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(state.imageID))
  189. if b.options.Remove {
  190. b.containerManager.RemoveAll(b.Stdout)
  191. }
  192. }
  193. // Emit a final aux message for the final image
  194. if err := emitImageID(b.Aux, state); err != nil {
  195. return nil, err
  196. }
  197. return state, nil
  198. }
  199. func addNodesForLabelOption(dockerfile *parser.Node, labels map[string]string) {
  200. if len(labels) == 0 {
  201. return
  202. }
  203. node := parser.NodeFromLabels(labels)
  204. dockerfile.Children = append(dockerfile.Children, node)
  205. }
  206. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  207. // It will:
  208. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  209. // - Do build by calling builder.dispatch() to call all entries' handling routines
  210. //
  211. // BuildFromConfig is used by the /commit endpoint, with the changes
  212. // coming from the query parameter of the same name.
  213. //
  214. // TODO: Remove?
  215. func BuildFromConfig(config *container.Config, changes []string) (*container.Config, error) {
  216. if len(changes) == 0 {
  217. return config, nil
  218. }
  219. b := newBuilder(context.Background(), builderOptions{
  220. Options: &types.ImageBuildOptions{NoCache: true},
  221. })
  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. }