builder.go 11 KB

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