builder.go 8.9 KB

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