builder.go 10 KB

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