builder.go 10 KB

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