builder.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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/docker/builder"
  12. "github.com/docker/docker/builder/dockerfile/parser"
  13. "github.com/docker/docker/image"
  14. "github.com/docker/docker/pkg/stringid"
  15. "github.com/docker/docker/reference"
  16. "github.com/docker/engine-api/types"
  17. "github.com/docker/engine-api/types/container"
  18. "golang.org/x/net/context"
  19. )
  20. var validCommitCommands = map[string]bool{
  21. "cmd": true,
  22. "entrypoint": true,
  23. "env": true,
  24. "expose": true,
  25. "label": true,
  26. "onbuild": true,
  27. "user": true,
  28. "volume": true,
  29. "workdir": true,
  30. }
  31. // BuiltinAllowedBuildArgs is list of built-in allowed build args
  32. var BuiltinAllowedBuildArgs = map[string]bool{
  33. "HTTP_PROXY": true,
  34. "http_proxy": true,
  35. "HTTPS_PROXY": true,
  36. "https_proxy": true,
  37. "FTP_PROXY": true,
  38. "ftp_proxy": true,
  39. "NO_PROXY": true,
  40. "no_proxy": true,
  41. }
  42. // Builder is a Dockerfile builder
  43. // It implements the builder.Backend interface.
  44. type Builder struct {
  45. options *types.ImageBuildOptions
  46. Stdout io.Writer
  47. Stderr io.Writer
  48. Output io.Writer
  49. docker builder.Backend
  50. context builder.Context
  51. clientCtx context.Context
  52. cancel context.CancelFunc
  53. dockerfile *parser.Node
  54. runConfig *container.Config // runconfig for cmd, run, entrypoint etc.
  55. flags *BFlags
  56. tmpContainers map[string]struct{}
  57. image string // imageID
  58. noBaseImage bool
  59. maintainer string
  60. cmdSet bool
  61. disableCommit bool
  62. cacheBusted bool
  63. allowedBuildArgs map[string]bool // list of build-time args that are allowed for expansion/substitution and passing to commands in 'run'.
  64. // TODO: remove once docker.Commit can receive a tag
  65. id string
  66. }
  67. // BuildManager implements builder.Backend and is shared across all Builder objects.
  68. type BuildManager struct {
  69. backend builder.Backend
  70. }
  71. // NewBuildManager creates a BuildManager.
  72. func NewBuildManager(b builder.Backend) (bm *BuildManager) {
  73. return &BuildManager{backend: b}
  74. }
  75. // NewBuilder creates a new Dockerfile builder from an optional dockerfile and a Config.
  76. // If dockerfile is nil, the Dockerfile specified by Config.DockerfileName,
  77. // will be read from the Context passed to Build().
  78. func NewBuilder(clientCtx context.Context, config *types.ImageBuildOptions, backend builder.Backend, buildContext builder.Context, dockerfile io.ReadCloser) (b *Builder, err error) {
  79. if config == nil {
  80. config = new(types.ImageBuildOptions)
  81. }
  82. if config.BuildArgs == nil {
  83. config.BuildArgs = make(map[string]string)
  84. }
  85. ctx, cancel := context.WithCancel(clientCtx)
  86. b = &Builder{
  87. clientCtx: ctx,
  88. cancel: cancel,
  89. options: config,
  90. Stdout: os.Stdout,
  91. Stderr: os.Stderr,
  92. docker: backend,
  93. context: buildContext,
  94. runConfig: new(container.Config),
  95. tmpContainers: map[string]struct{}{},
  96. id: stringid.GenerateNonCryptoID(),
  97. allowedBuildArgs: make(map[string]bool),
  98. }
  99. if dockerfile != nil {
  100. b.dockerfile, err = parser.Parse(dockerfile)
  101. if err != nil {
  102. return nil, err
  103. }
  104. }
  105. return b, nil
  106. }
  107. // sanitizeRepoAndTags parses the raw "t" parameter received from the client
  108. // to a slice of repoAndTag.
  109. // It also validates each repoName and tag.
  110. func sanitizeRepoAndTags(names []string) ([]reference.Named, error) {
  111. var (
  112. repoAndTags []reference.Named
  113. // This map is used for deduplicating the "-t" parameter.
  114. uniqNames = make(map[string]struct{})
  115. )
  116. for _, repo := range names {
  117. if repo == "" {
  118. continue
  119. }
  120. ref, err := reference.ParseNamed(repo)
  121. if err != nil {
  122. return nil, err
  123. }
  124. ref = reference.WithDefaultTag(ref)
  125. if _, isCanonical := ref.(reference.Canonical); isCanonical {
  126. return nil, errors.New("build tag cannot contain a digest")
  127. }
  128. if _, isTagged := ref.(reference.NamedTagged); !isTagged {
  129. ref, err = reference.WithTag(ref, reference.DefaultTag)
  130. if err != nil {
  131. return nil, err
  132. }
  133. }
  134. nameWithTag := ref.String()
  135. if _, exists := uniqNames[nameWithTag]; !exists {
  136. uniqNames[nameWithTag] = struct{}{}
  137. repoAndTags = append(repoAndTags, ref)
  138. }
  139. }
  140. return repoAndTags, nil
  141. }
  142. // Build creates a NewBuilder, which builds the image.
  143. func (bm *BuildManager) Build(clientCtx context.Context, config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer) (string, error) {
  144. b, err := NewBuilder(clientCtx, config, bm.backend, context, nil)
  145. if err != nil {
  146. return "", err
  147. }
  148. img, err := b.build(config, context, stdout, stderr, out)
  149. return img, err
  150. }
  151. // build runs the Dockerfile builder from a context and a docker object that allows to make calls
  152. // to Docker.
  153. //
  154. // This will (barring errors):
  155. //
  156. // * read the dockerfile from context
  157. // * parse the dockerfile if not already parsed
  158. // * walk the AST and execute it by dispatching to handlers. If Remove
  159. // or ForceRemove is set, additional cleanup around containers happens after
  160. // processing.
  161. // * Tag image, if applicable.
  162. // * Print a happy message and return the image ID.
  163. //
  164. func (b *Builder) build(config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer) (string, error) {
  165. b.options = config
  166. b.context = context
  167. b.Stdout = stdout
  168. b.Stderr = stderr
  169. b.Output = out
  170. // If Dockerfile was not parsed yet, extract it from the Context
  171. if b.dockerfile == nil {
  172. if err := b.readDockerfile(); err != nil {
  173. return "", err
  174. }
  175. }
  176. repoAndTags, err := sanitizeRepoAndTags(config.Tags)
  177. if err != nil {
  178. return "", err
  179. }
  180. var shortImgID string
  181. for i, n := range b.dockerfile.Children {
  182. // we only want to add labels to the last layer
  183. if i == len(b.dockerfile.Children)-1 {
  184. b.addLabels()
  185. }
  186. select {
  187. case <-b.clientCtx.Done():
  188. logrus.Debug("Builder: build cancelled!")
  189. fmt.Fprintf(b.Stdout, "Build cancelled")
  190. return "", fmt.Errorf("Build cancelled")
  191. default:
  192. // Not cancelled yet, keep going...
  193. }
  194. if err := b.dispatch(i, n); err != nil {
  195. if b.options.ForceRemove {
  196. b.clearTmp()
  197. }
  198. return "", err
  199. }
  200. // Commit the layer when there are only one children in
  201. // the dockerfile, this is only the `FROM` tag, and
  202. // build labels. Otherwise, the new image won't be
  203. // labeled properly.
  204. // Commit here, so the ID of the final image is reported
  205. // properly.
  206. if len(b.dockerfile.Children) == 1 && len(b.options.Labels) > 0 {
  207. b.commit("", b.runConfig.Cmd, "")
  208. }
  209. shortImgID = stringid.TruncateID(b.image)
  210. fmt.Fprintf(b.Stdout, " ---> %s\n", shortImgID)
  211. if b.options.Remove {
  212. b.clearTmp()
  213. }
  214. }
  215. // check if there are any leftover build-args that were passed but not
  216. // consumed during build. Return an error, if there are any.
  217. leftoverArgs := []string{}
  218. for arg := range b.options.BuildArgs {
  219. if !b.isBuildArgAllowed(arg) {
  220. leftoverArgs = append(leftoverArgs, arg)
  221. }
  222. }
  223. if len(leftoverArgs) > 0 {
  224. return "", fmt.Errorf("One or more build-args %v were not consumed, failing build.", leftoverArgs)
  225. }
  226. if b.image == "" {
  227. return "", fmt.Errorf("No image was generated. Is your Dockerfile empty?")
  228. }
  229. imageID := image.ID(b.image)
  230. for _, rt := range repoAndTags {
  231. if err := b.docker.TagImageWithReference(imageID, rt); err != nil {
  232. return "", err
  233. }
  234. }
  235. fmt.Fprintf(b.Stdout, "Successfully built %s\n", shortImgID)
  236. return b.image, nil
  237. }
  238. // Cancel cancels an ongoing Dockerfile build.
  239. func (b *Builder) Cancel() {
  240. b.cancel()
  241. }
  242. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  243. // It will:
  244. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  245. // - Do build by calling builder.dispatch() to call all entries' handling routines
  246. //
  247. // BuildFromConfig is used by the /commit endpoint, with the changes
  248. // coming from the query parameter of the same name.
  249. //
  250. // TODO: Remove?
  251. func BuildFromConfig(config *container.Config, changes []string) (*container.Config, error) {
  252. ast, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
  253. if err != nil {
  254. return nil, err
  255. }
  256. // ensure that the commands are valid
  257. for _, n := range ast.Children {
  258. if !validCommitCommands[n.Value] {
  259. return nil, fmt.Errorf("%s is not a valid change command", n.Value)
  260. }
  261. }
  262. b, err := NewBuilder(context.Background(), nil, nil, nil, nil)
  263. if err != nil {
  264. return nil, err
  265. }
  266. b.runConfig = config
  267. b.Stdout = ioutil.Discard
  268. b.Stderr = ioutil.Discard
  269. b.disableCommit = true
  270. for i, n := range ast.Children {
  271. if err := b.dispatch(i, n); err != nil {
  272. return nil, err
  273. }
  274. }
  275. return b.runConfig, nil
  276. }