builder.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package dockerfile
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "strings"
  9. "github.com/Sirupsen/logrus"
  10. "github.com/docker/distribution/reference"
  11. apierrors "github.com/docker/docker/api/errors"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/api/types/backend"
  14. "github.com/docker/docker/api/types/container"
  15. "github.com/docker/docker/builder"
  16. "github.com/docker/docker/builder/dockerfile/command"
  17. "github.com/docker/docker/builder/dockerfile/parser"
  18. "github.com/docker/docker/builder/remotecontext"
  19. "github.com/docker/docker/image"
  20. "github.com/docker/docker/pkg/stringid"
  21. "github.com/pkg/errors"
  22. "golang.org/x/net/context"
  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. var defaultLogConfig = container.LogConfig{Type: "none"}
  37. // Builder is a Dockerfile builder
  38. // It implements the builder.Backend interface.
  39. type Builder struct {
  40. options *types.ImageBuildOptions
  41. Stdout io.Writer
  42. Stderr io.Writer
  43. Output io.Writer
  44. docker builder.Backend
  45. source builder.Source
  46. clientCtx context.Context
  47. runConfig *container.Config // runconfig for cmd, run, entrypoint etc.
  48. tmpContainers map[string]struct{}
  49. imageContexts *imageContexts // helper for storing contexts from builds
  50. disableCommit bool
  51. cacheBusted bool
  52. buildArgs *buildArgs
  53. imageCache builder.ImageCache
  54. // TODO: these move to DispatchState
  55. escapeToken rune
  56. maintainer string
  57. cmdSet bool
  58. noBaseImage bool // A flag to track the use of `scratch` as the base image
  59. image string // imageID
  60. from builder.Image
  61. }
  62. // BuildManager implements builder.Backend and is shared across all Builder objects.
  63. type BuildManager struct {
  64. backend builder.Backend
  65. pathCache *pathCache // TODO: make this persistent
  66. }
  67. // NewBuildManager creates a BuildManager.
  68. func NewBuildManager(b builder.Backend) (bm *BuildManager) {
  69. return &BuildManager{backend: b, pathCache: &pathCache{}}
  70. }
  71. // BuildFromContext builds a new image from a given context.
  72. func (bm *BuildManager) BuildFromContext(ctx context.Context, src io.ReadCloser, buildOptions *types.ImageBuildOptions, pg backend.ProgressWriter) (string, error) {
  73. if buildOptions.Squash && !bm.backend.HasExperimental() {
  74. return "", apierrors.NewBadRequestError(errors.New("squash is only supported with experimental mode"))
  75. }
  76. if buildOptions.Dockerfile == "" {
  77. buildOptions.Dockerfile = builder.DefaultDockerfileName
  78. }
  79. source, dockerfile, err := remotecontext.Detect(ctx, buildOptions.RemoteContext, buildOptions.Dockerfile, src, pg.ProgressReaderFunc)
  80. if err != nil {
  81. return "", err
  82. }
  83. if source != nil {
  84. defer func() {
  85. if err := source.Close(); err != nil {
  86. logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
  87. }
  88. }()
  89. }
  90. b, err := NewBuilder(ctx, buildOptions, bm.backend, source)
  91. if err != nil {
  92. return "", err
  93. }
  94. b.imageContexts.cache = bm.pathCache
  95. return b.build(dockerfile, pg.StdoutFormatter, pg.StderrFormatter, pg.Output)
  96. }
  97. // NewBuilder creates a new Dockerfile builder from an optional dockerfile and a Config.
  98. // If dockerfile is nil, the Dockerfile specified by Config.DockerfileName,
  99. // will be read from the Context passed to Build().
  100. func NewBuilder(clientCtx context.Context, config *types.ImageBuildOptions, backend builder.Backend, source builder.Source) (b *Builder, err error) {
  101. if config == nil {
  102. config = new(types.ImageBuildOptions)
  103. }
  104. b = &Builder{
  105. clientCtx: clientCtx,
  106. options: config,
  107. Stdout: os.Stdout,
  108. Stderr: os.Stderr,
  109. docker: backend,
  110. source: source,
  111. runConfig: new(container.Config),
  112. tmpContainers: map[string]struct{}{},
  113. buildArgs: newBuildArgs(config.BuildArgs),
  114. escapeToken: parser.DefaultEscapeToken,
  115. }
  116. b.imageContexts = &imageContexts{b: b}
  117. return b, nil
  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.noBaseImage = false
  124. b.cacheBusted = false
  125. }
  126. // sanitizeRepoAndTags parses the raw "t" parameter received from the client
  127. // to a slice of repoAndTag.
  128. // It also validates each repoName and tag.
  129. func sanitizeRepoAndTags(names []string) ([]reference.Named, error) {
  130. var (
  131. repoAndTags []reference.Named
  132. // This map is used for deduplicating the "-t" parameter.
  133. uniqNames = make(map[string]struct{})
  134. )
  135. for _, repo := range names {
  136. if repo == "" {
  137. continue
  138. }
  139. ref, err := reference.ParseNormalizedNamed(repo)
  140. if err != nil {
  141. return nil, err
  142. }
  143. if _, isCanonical := ref.(reference.Canonical); isCanonical {
  144. return nil, errors.New("build tag cannot contain a digest")
  145. }
  146. ref = reference.TagNameOnly(ref)
  147. nameWithTag := ref.String()
  148. if _, exists := uniqNames[nameWithTag]; !exists {
  149. uniqNames[nameWithTag] = struct{}{}
  150. repoAndTags = append(repoAndTags, ref)
  151. }
  152. }
  153. return repoAndTags, nil
  154. }
  155. // build runs the Dockerfile builder from a context and a docker object that allows to make calls
  156. // to Docker.
  157. func (b *Builder) build(dockerfile *parser.Result, stdout io.Writer, stderr io.Writer, out io.Writer) (string, error) {
  158. defer b.imageContexts.unmount()
  159. b.Stdout = stdout
  160. b.Stderr = stderr
  161. b.Output = out
  162. repoAndTags, err := sanitizeRepoAndTags(b.options.Tags)
  163. if err != nil {
  164. return "", err
  165. }
  166. addNodesForLabelOption(dockerfile.AST, b.options.Labels)
  167. if err := checkDispatchDockerfile(dockerfile.AST); err != nil {
  168. return "", err
  169. }
  170. imageID, err := b.dispatchDockerfileWithCancellation(dockerfile)
  171. if err != nil {
  172. return "", err
  173. }
  174. b.warnOnUnusedBuildArgs()
  175. if imageID == "" {
  176. return "", errors.New("No image was generated. Is your Dockerfile empty?")
  177. }
  178. if b.options.Squash {
  179. if imageID, err = b.squashBuild(imageID); err != nil {
  180. return "", err
  181. }
  182. }
  183. fmt.Fprintf(b.Stdout, "Successfully built %s\n", stringid.TruncateID(imageID))
  184. if err := b.tagImages(imageID, repoAndTags); err != nil {
  185. return "", err
  186. }
  187. return imageID, nil
  188. }
  189. func (b *Builder) dispatchDockerfileWithCancellation(dockerfile *parser.Result) (string, error) {
  190. // TODO: pass this to dispatchRequest instead
  191. b.escapeToken = dockerfile.EscapeToken
  192. total := len(dockerfile.AST.Children)
  193. var imageID string
  194. for i, n := range dockerfile.AST.Children {
  195. select {
  196. case <-b.clientCtx.Done():
  197. logrus.Debug("Builder: build cancelled!")
  198. fmt.Fprint(b.Stdout, "Build cancelled")
  199. return "", errors.New("Build cancelled")
  200. default:
  201. // Not cancelled yet, keep going...
  202. }
  203. if command.From == n.Value && b.imageContexts.isCurrentTarget(b.options.Target) {
  204. break
  205. }
  206. if err := b.dispatch(i, total, n); err != nil {
  207. if b.options.ForceRemove {
  208. b.clearTmp()
  209. }
  210. return "", err
  211. }
  212. // TODO: get this from dispatch
  213. imageID = b.image
  214. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(imageID))
  215. if b.options.Remove {
  216. b.clearTmp()
  217. }
  218. }
  219. if b.options.Target != "" && !b.imageContexts.isCurrentTarget(b.options.Target) {
  220. return "", errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target)
  221. }
  222. return imageID, nil
  223. }
  224. func (b *Builder) squashBuild(imageID string) (string, error) {
  225. var fromID string
  226. var err error
  227. if b.from != nil {
  228. fromID = b.from.ImageID()
  229. }
  230. imageID, err = b.docker.SquashImage(imageID, fromID)
  231. if err != nil {
  232. return "", errors.Wrap(err, "error squashing image")
  233. }
  234. return imageID, nil
  235. }
  236. func addNodesForLabelOption(dockerfile *parser.Node, labels map[string]string) {
  237. if len(labels) == 0 {
  238. return
  239. }
  240. node := parser.NodeFromLabels(labels)
  241. dockerfile.Children = append(dockerfile.Children, node)
  242. }
  243. // check if there are any leftover build-args that were passed but not
  244. // consumed during build. Print a warning, if there are any.
  245. func (b *Builder) warnOnUnusedBuildArgs() {
  246. leftoverArgs := b.buildArgs.UnreferencedOptionArgs()
  247. if len(leftoverArgs) > 0 {
  248. fmt.Fprintf(b.Stderr, "[Warning] One or more build-args %v were not consumed\n", leftoverArgs)
  249. }
  250. }
  251. func (b *Builder) tagImages(id string, repoAndTags []reference.Named) error {
  252. imageID := image.ID(id)
  253. for _, rt := range repoAndTags {
  254. if err := b.docker.TagImageWithReference(imageID, rt); err != nil {
  255. return err
  256. }
  257. fmt.Fprintf(b.Stdout, "Successfully tagged %s\n", reference.FamiliarString(rt))
  258. }
  259. return nil
  260. }
  261. // hasFromImage returns true if the builder has processed a `FROM <image>` line
  262. // TODO: move to DispatchState
  263. func (b *Builder) hasFromImage() bool {
  264. return b.image != "" || b.noBaseImage
  265. }
  266. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  267. // It will:
  268. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  269. // - Do build by calling builder.dispatch() to call all entries' handling routines
  270. //
  271. // BuildFromConfig is used by the /commit endpoint, with the changes
  272. // coming from the query parameter of the same name.
  273. //
  274. // TODO: Remove?
  275. func BuildFromConfig(config *container.Config, changes []string) (*container.Config, error) {
  276. b, err := NewBuilder(context.Background(), nil, nil, nil)
  277. if err != nil {
  278. return nil, err
  279. }
  280. result, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
  281. if err != nil {
  282. return nil, err
  283. }
  284. // ensure that the commands are valid
  285. for _, n := range result.AST.Children {
  286. if !validCommitCommands[n.Value] {
  287. return nil, fmt.Errorf("%s is not a valid change command", n.Value)
  288. }
  289. }
  290. b.runConfig = config
  291. b.Stdout = ioutil.Discard
  292. b.Stderr = ioutil.Discard
  293. b.disableCommit = true
  294. if err := checkDispatchDockerfile(result.AST); err != nil {
  295. return nil, err
  296. }
  297. if err := dispatchFromDockerfile(b, result); err != nil {
  298. return nil, err
  299. }
  300. return b.runConfig, nil
  301. }
  302. func checkDispatchDockerfile(dockerfile *parser.Node) error {
  303. for _, n := range dockerfile.Children {
  304. if err := checkDispatch(n); err != nil {
  305. return errors.Wrapf(err, "Dockerfile parse error line %d", n.StartLine)
  306. }
  307. }
  308. return nil
  309. }
  310. func dispatchFromDockerfile(b *Builder, result *parser.Result) error {
  311. // TODO: pass this to dispatchRequest instead
  312. b.escapeToken = result.EscapeToken
  313. ast := result.AST
  314. total := len(ast.Children)
  315. for i, n := range ast.Children {
  316. if err := b.dispatch(i, total, n); err != nil {
  317. return err
  318. }
  319. }
  320. return nil
  321. }