builder.go 11 KB

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