builder.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package dockerfile
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "strings"
  10. "sync"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/builder"
  13. "github.com/docker/docker/builder/dockerfile/parser"
  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. 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. cancelled chan struct{}
  63. cancelOnce sync.Once
  64. allowedBuildArgs map[string]bool // list of build-time args that are allowed for expansion/substitution and passing to commands in 'run'.
  65. // TODO: remove once docker.Commit can receive a tag
  66. id string
  67. }
  68. // BuildManager implements builder.Backend and is shared across all Builder objects.
  69. type BuildManager struct {
  70. backend builder.Backend
  71. }
  72. // NewBuildManager creates a BuildManager.
  73. func NewBuildManager(b builder.Backend) (bm *BuildManager) {
  74. return &BuildManager{backend: b}
  75. }
  76. // NewBuilder creates a new Dockerfile builder from an optional dockerfile and a Config.
  77. // If dockerfile is nil, the Dockerfile specified by Config.DockerfileName,
  78. // will be read from the Context passed to Build().
  79. func NewBuilder(clientCtx context.Context, config *types.ImageBuildOptions, backend builder.Backend, context builder.Context, dockerfile io.ReadCloser) (b *Builder, err error) {
  80. if config == nil {
  81. config = new(types.ImageBuildOptions)
  82. }
  83. if config.BuildArgs == nil {
  84. config.BuildArgs = make(map[string]string)
  85. }
  86. b = &Builder{
  87. clientCtx: clientCtx,
  88. options: config,
  89. Stdout: os.Stdout,
  90. Stderr: os.Stderr,
  91. docker: backend,
  92. context: context,
  93. runConfig: new(container.Config),
  94. tmpContainers: map[string]struct{}{},
  95. cancelled: make(chan 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, clientGone <-chan bool) (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, clientGone)
  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, clientGone <-chan bool) (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. finished := make(chan struct{})
  177. defer close(finished)
  178. go func() {
  179. select {
  180. case <-finished:
  181. case <-clientGone:
  182. b.cancelOnce.Do(func() {
  183. close(b.cancelled)
  184. })
  185. }
  186. }()
  187. repoAndTags, err := sanitizeRepoAndTags(config.Tags)
  188. if err != nil {
  189. return "", err
  190. }
  191. var shortImgID string
  192. for i, n := range b.dockerfile.Children {
  193. select {
  194. case <-b.cancelled:
  195. logrus.Debug("Builder: build cancelled!")
  196. fmt.Fprintf(b.Stdout, "Build cancelled")
  197. return "", fmt.Errorf("Build cancelled")
  198. default:
  199. // Not cancelled yet, keep going...
  200. }
  201. if err := b.dispatch(i, n); err != nil {
  202. if b.options.ForceRemove {
  203. b.clearTmp()
  204. }
  205. return "", err
  206. }
  207. shortImgID = stringid.TruncateID(b.image)
  208. fmt.Fprintf(b.Stdout, " ---> %s\n", shortImgID)
  209. if b.options.Remove {
  210. b.clearTmp()
  211. }
  212. }
  213. // check if there are any leftover build-args that were passed but not
  214. // consumed during build. Return an error, if there are any.
  215. leftoverArgs := []string{}
  216. for arg := range b.options.BuildArgs {
  217. if !b.isBuildArgAllowed(arg) {
  218. leftoverArgs = append(leftoverArgs, arg)
  219. }
  220. }
  221. if len(leftoverArgs) > 0 {
  222. return "", fmt.Errorf("One or more build-args %v were not consumed, failing build.", leftoverArgs)
  223. }
  224. if b.image == "" {
  225. return "", fmt.Errorf("No image was generated. Is your Dockerfile empty?")
  226. }
  227. for _, rt := range repoAndTags {
  228. if err := b.docker.TagImage(rt, b.image); err != nil {
  229. return "", err
  230. }
  231. }
  232. fmt.Fprintf(b.Stdout, "Successfully built %s\n", shortImgID)
  233. return b.image, nil
  234. }
  235. // Cancel cancels an ongoing Dockerfile build.
  236. func (b *Builder) Cancel() {
  237. b.cancelOnce.Do(func() {
  238. close(b.cancelled)
  239. })
  240. }
  241. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  242. // It will:
  243. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  244. // - Do build by calling builder.dispatch() to call all entries' handling routines
  245. //
  246. // BuildFromConfig is used by the /commit endpoint, with the changes
  247. // coming from the query parameter of the same name.
  248. //
  249. // TODO: Remove?
  250. func BuildFromConfig(config *container.Config, changes []string) (*container.Config, error) {
  251. ast, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
  252. if err != nil {
  253. return nil, err
  254. }
  255. // ensure that the commands are valid
  256. for _, n := range ast.Children {
  257. if !validCommitCommands[n.Value] {
  258. return nil, fmt.Errorf("%s is not a valid change command", n.Value)
  259. }
  260. }
  261. b, err := NewBuilder(context.Background(), nil, nil, nil, nil)
  262. if err != nil {
  263. return nil, err
  264. }
  265. b.runConfig = config
  266. b.Stdout = ioutil.Discard
  267. b.Stderr = ioutil.Discard
  268. b.disableCommit = true
  269. for i, n := range ast.Children {
  270. if err := b.dispatch(i, n); err != nil {
  271. return nil, err
  272. }
  273. }
  274. return b.runConfig, nil
  275. }