builder.go 11 KB

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