builder.go 10 KB

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