builder.go 8.7 KB

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