builder.go 10 KB

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