builder.go 10 KB

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