builder.go 8.5 KB

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