build.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. package client
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "github.com/docker/docker/api"
  21. Cli "github.com/docker/docker/cli"
  22. "github.com/docker/docker/graph/tags"
  23. "github.com/docker/docker/opts"
  24. "github.com/docker/docker/pkg/archive"
  25. "github.com/docker/docker/pkg/fileutils"
  26. "github.com/docker/docker/pkg/httputils"
  27. "github.com/docker/docker/pkg/jsonmessage"
  28. flag "github.com/docker/docker/pkg/mflag"
  29. "github.com/docker/docker/pkg/parsers"
  30. "github.com/docker/docker/pkg/progressreader"
  31. "github.com/docker/docker/pkg/streamformatter"
  32. "github.com/docker/docker/pkg/symlink"
  33. "github.com/docker/docker/pkg/ulimit"
  34. "github.com/docker/docker/pkg/units"
  35. "github.com/docker/docker/pkg/urlutil"
  36. "github.com/docker/docker/registry"
  37. "github.com/docker/docker/utils"
  38. )
  39. const (
  40. tarHeaderSize = 512
  41. )
  42. // CmdBuild builds a new image from the source code at a given path.
  43. //
  44. // If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN.
  45. //
  46. // Usage: docker build [OPTIONS] PATH | URL | -
  47. func (cli *DockerCli) CmdBuild(args ...string) error {
  48. cmd := Cli.Subcmd("build", []string{"PATH | URL | -"}, "Build a new image from the source code at PATH", true)
  49. tag := cmd.String([]string{"t", "-tag"}, "", "Repository name (and optionally a tag) for the image")
  50. suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the verbose output generated by the containers")
  51. noCache := cmd.Bool([]string{"#no-cache", "-no-cache"}, false, "Do not use cache when building the image")
  52. rm := cmd.Bool([]string{"#rm", "-rm"}, true, "Remove intermediate containers after a successful build")
  53. forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers")
  54. pull := cmd.Bool([]string{"-pull"}, false, "Always attempt to pull a newer version of the image")
  55. dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')")
  56. flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit")
  57. flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap")
  58. flCPUShares := cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
  59. flCpuPeriod := cmd.Int64([]string{"-cpu-period"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) period")
  60. flCpuQuota := cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota")
  61. flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
  62. flCPUSetMems := cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
  63. flCgroupParent := cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
  64. ulimits := make(map[string]*ulimit.Ulimit)
  65. flUlimits := opts.NewUlimitOpt(&ulimits)
  66. cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
  67. cmd.Require(flag.Exact, 1)
  68. // For trusted pull on "FROM <image>" instruction.
  69. addTrustedFlags(cmd, true)
  70. cmd.ParseFlags(args, true)
  71. var (
  72. context io.ReadCloser
  73. isRemote bool
  74. err error
  75. )
  76. _, err = exec.LookPath("git")
  77. hasGit := err == nil
  78. specifiedContext := cmd.Arg(0)
  79. var (
  80. contextDir string
  81. tempDir string
  82. relDockerfile string
  83. )
  84. switch {
  85. case specifiedContext == "-":
  86. tempDir, relDockerfile, err = getContextFromReader(cli.in, *dockerfileName)
  87. case urlutil.IsGitURL(specifiedContext) && hasGit:
  88. tempDir, relDockerfile, err = getContextFromGitURL(specifiedContext, *dockerfileName)
  89. case urlutil.IsURL(specifiedContext):
  90. tempDir, relDockerfile, err = getContextFromURL(cli.out, specifiedContext, *dockerfileName)
  91. default:
  92. contextDir, relDockerfile, err = getContextFromLocalDir(specifiedContext, *dockerfileName)
  93. }
  94. if err != nil {
  95. return fmt.Errorf("unable to prepare context: %s", err)
  96. }
  97. if tempDir != "" {
  98. defer os.RemoveAll(tempDir)
  99. contextDir = tempDir
  100. }
  101. // Resolve the FROM lines in the Dockerfile to trusted digest references
  102. // using Notary. On a successful build, we must tag the resolved digests
  103. // to the original name specified in the Dockerfile.
  104. newDockerfile, resolvedTags, err := rewriteDockerfileFrom(filepath.Join(contextDir, relDockerfile), cli.trustedReference)
  105. if err != nil {
  106. return fmt.Errorf("unable to process Dockerfile: %v", err)
  107. }
  108. defer newDockerfile.Close()
  109. // And canonicalize dockerfile name to a platform-independent one
  110. relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile)
  111. if err != nil {
  112. return fmt.Errorf("cannot canonicalize dockerfile path %s: %v", relDockerfile, err)
  113. }
  114. var includes = []string{"."}
  115. excludes, err := utils.ReadDockerIgnore(path.Join(contextDir, ".dockerignore"))
  116. if err != nil {
  117. return err
  118. }
  119. if err := utils.ValidateContextDirectory(contextDir, excludes); err != nil {
  120. return fmt.Errorf("Error checking context: '%s'.", err)
  121. }
  122. // If .dockerignore mentions .dockerignore or the Dockerfile
  123. // then make sure we send both files over to the daemon
  124. // because Dockerfile is, obviously, needed no matter what, and
  125. // .dockerignore is needed to know if either one needs to be
  126. // removed. The deamon will remove them for us, if needed, after it
  127. // parses the Dockerfile. Ignore errors here, as they will have been
  128. // caught by ValidateContextDirectory above.
  129. keepThem1, _ := fileutils.Matches(".dockerignore", excludes)
  130. keepThem2, _ := fileutils.Matches(relDockerfile, excludes)
  131. if keepThem1 || keepThem2 {
  132. includes = append(includes, ".dockerignore", relDockerfile)
  133. }
  134. context, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
  135. Compression: archive.Uncompressed,
  136. ExcludePatterns: excludes,
  137. IncludeFiles: includes,
  138. })
  139. if err != nil {
  140. return err
  141. }
  142. // Wrap the tar archive to replace the Dockerfile entry with the rewritten
  143. // Dockerfile which uses trusted pulls.
  144. context = replaceDockerfileTarWrapper(context, newDockerfile, relDockerfile)
  145. // Setup an upload progress bar
  146. // FIXME: ProgressReader shouldn't be this annoying to use
  147. sf := streamformatter.NewStreamFormatter()
  148. var body io.Reader = progressreader.New(progressreader.Config{
  149. In: context,
  150. Out: cli.out,
  151. Formatter: sf,
  152. NewLines: true,
  153. ID: "",
  154. Action: "Sending build context to Docker daemon",
  155. })
  156. var memory int64
  157. if *flMemoryString != "" {
  158. parsedMemory, err := units.RAMInBytes(*flMemoryString)
  159. if err != nil {
  160. return err
  161. }
  162. memory = parsedMemory
  163. }
  164. var memorySwap int64
  165. if *flMemorySwap != "" {
  166. if *flMemorySwap == "-1" {
  167. memorySwap = -1
  168. } else {
  169. parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
  170. if err != nil {
  171. return err
  172. }
  173. memorySwap = parsedMemorySwap
  174. }
  175. }
  176. // Send the build context
  177. v := &url.Values{}
  178. //Check if the given image name can be resolved
  179. if *tag != "" {
  180. repository, tag := parsers.ParseRepositoryTag(*tag)
  181. if err := registry.ValidateRepositoryName(repository); err != nil {
  182. return err
  183. }
  184. if len(tag) > 0 {
  185. if err := tags.ValidateTagName(tag); err != nil {
  186. return err
  187. }
  188. }
  189. }
  190. v.Set("t", *tag)
  191. if *suppressOutput {
  192. v.Set("q", "1")
  193. }
  194. if isRemote {
  195. v.Set("remote", cmd.Arg(0))
  196. }
  197. if *noCache {
  198. v.Set("nocache", "1")
  199. }
  200. if *rm {
  201. v.Set("rm", "1")
  202. } else {
  203. v.Set("rm", "0")
  204. }
  205. if *forceRm {
  206. v.Set("forcerm", "1")
  207. }
  208. if *pull {
  209. v.Set("pull", "1")
  210. }
  211. v.Set("cpusetcpus", *flCPUSetCpus)
  212. v.Set("cpusetmems", *flCPUSetMems)
  213. v.Set("cpushares", strconv.FormatInt(*flCPUShares, 10))
  214. v.Set("cpuquota", strconv.FormatInt(*flCpuQuota, 10))
  215. v.Set("cpuperiod", strconv.FormatInt(*flCpuPeriod, 10))
  216. v.Set("memory", strconv.FormatInt(memory, 10))
  217. v.Set("memswap", strconv.FormatInt(memorySwap, 10))
  218. v.Set("cgroupparent", *flCgroupParent)
  219. v.Set("dockerfile", relDockerfile)
  220. ulimitsVar := flUlimits.GetList()
  221. ulimitsJson, err := json.Marshal(ulimitsVar)
  222. if err != nil {
  223. return err
  224. }
  225. v.Set("ulimits", string(ulimitsJson))
  226. headers := http.Header(make(map[string][]string))
  227. buf, err := json.Marshal(cli.configFile.AuthConfigs)
  228. if err != nil {
  229. return err
  230. }
  231. headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf))
  232. headers.Set("Content-Type", "application/tar")
  233. sopts := &streamOpts{
  234. rawTerminal: true,
  235. in: body,
  236. out: cli.out,
  237. headers: headers,
  238. }
  239. serverResp, err := cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), sopts)
  240. // Windows: show error message about modified file permissions.
  241. if runtime.GOOS == "windows" {
  242. h, err := httputils.ParseServerHeader(serverResp.header.Get("Server"))
  243. if err == nil {
  244. if h.OS != "windows" {
  245. fmt.Fprintln(cli.err, `SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.`)
  246. }
  247. }
  248. }
  249. if jerr, ok := err.(*jsonmessage.JSONError); ok {
  250. // If no error code is set, default to 1
  251. if jerr.Code == 0 {
  252. jerr.Code = 1
  253. }
  254. return Cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  255. }
  256. if err != nil {
  257. return err
  258. }
  259. // Since the build was successful, now we must tag any of the resolved
  260. // images from the above Dockerfile rewrite.
  261. for _, resolved := range resolvedTags {
  262. if err := cli.tagTrusted(resolved.repoInfo, resolved.digestRef, resolved.tagRef); err != nil {
  263. return err
  264. }
  265. }
  266. return nil
  267. }
  268. // getDockerfileRelPath uses the given context directory for a `docker build`
  269. // and returns the absolute path to the context directory, the relative path of
  270. // the dockerfile in that context directory, and a non-nil error on success.
  271. func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
  272. if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
  273. return "", "", fmt.Errorf("unable to get absolute context directory: %v", err)
  274. }
  275. // The context dir might be a symbolic link, so follow it to the actual
  276. // target directory.
  277. absContextDir, err = filepath.EvalSymlinks(absContextDir)
  278. if err != nil {
  279. return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err)
  280. }
  281. stat, err := os.Lstat(absContextDir)
  282. if err != nil {
  283. return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err)
  284. }
  285. if !stat.IsDir() {
  286. return "", "", fmt.Errorf("context must be a directory: %s", absContextDir)
  287. }
  288. absDockerfile := givenDockerfile
  289. if absDockerfile == "" {
  290. // No -f/--file was specified so use the default relative to the
  291. // context directory.
  292. absDockerfile = filepath.Join(absContextDir, api.DefaultDockerfileName)
  293. // Just to be nice ;-) look for 'dockerfile' too but only
  294. // use it if we found it, otherwise ignore this check
  295. if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
  296. altPath := filepath.Join(absContextDir, strings.ToLower(api.DefaultDockerfileName))
  297. if _, err = os.Lstat(altPath); err == nil {
  298. absDockerfile = altPath
  299. }
  300. }
  301. }
  302. // If not already an absolute path, the Dockerfile path should be joined to
  303. // the base directory.
  304. if !filepath.IsAbs(absDockerfile) {
  305. absDockerfile = filepath.Join(absContextDir, absDockerfile)
  306. }
  307. // Verify that 'filename' is within the build context
  308. absDockerfile, err = symlink.FollowSymlinkInScope(absDockerfile, absContextDir)
  309. if err != nil {
  310. return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
  311. }
  312. if _, err := os.Lstat(absDockerfile); err != nil {
  313. if os.IsNotExist(err) {
  314. return "", "", fmt.Errorf("Cannot locate Dockerfile: absDockerfile: %q", absDockerfile)
  315. }
  316. return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err)
  317. }
  318. if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
  319. return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err)
  320. }
  321. return absContextDir, relDockerfile, nil
  322. }
  323. // writeToFile copies from the given reader and writes it to a file with the
  324. // given filename.
  325. func writeToFile(r io.Reader, filename string) error {
  326. file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600))
  327. if err != nil {
  328. return fmt.Errorf("unable to create file: %v", err)
  329. }
  330. defer file.Close()
  331. if _, err := io.Copy(file, r); err != nil {
  332. return fmt.Errorf("unable to write file: %v", err)
  333. }
  334. return nil
  335. }
  336. // getContextFromReader will read the contents of the given reader as either a
  337. // Dockerfile or tar archive to be extracted to a temporary directory used as
  338. // the context directory. Returns the absolute path to the temporary context
  339. // directory, the relative path of the dockerfile in that context directory,
  340. // and a non-nil error on success.
  341. func getContextFromReader(r io.Reader, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  342. buf := bufio.NewReader(r)
  343. magic, err := buf.Peek(tarHeaderSize)
  344. if err != nil && err != io.EOF {
  345. return "", "", fmt.Errorf("failed to peek context header from STDIN: %v", err)
  346. }
  347. if absContextDir, err = ioutil.TempDir("", "docker-build-context-"); err != nil {
  348. return "", "", fmt.Errorf("unbale to create temporary context directory: %v", err)
  349. }
  350. defer func(d string) {
  351. if err != nil {
  352. os.RemoveAll(d)
  353. }
  354. }(absContextDir)
  355. if !archive.IsArchive(magic) { // Input should be read as a Dockerfile.
  356. // -f option has no meaning when we're reading it from stdin,
  357. // so just use our default Dockerfile name
  358. relDockerfile = api.DefaultDockerfileName
  359. return absContextDir, relDockerfile, writeToFile(buf, filepath.Join(absContextDir, relDockerfile))
  360. }
  361. if err := archive.Untar(buf, absContextDir, nil); err != nil {
  362. return "", "", fmt.Errorf("unable to extract stdin to temporary context direcotry: %v", err)
  363. }
  364. return getDockerfileRelPath(absContextDir, dockerfileName)
  365. }
  366. // getContextFromGitURL uses a Git URL as context for a `docker build`. The
  367. // git repo is cloned into a temporary directory used as the context directory.
  368. // Returns the absolute path to the temporary context directory, the relative
  369. // path of the dockerfile in that context directory, and a non-nil error on
  370. // success.
  371. func getContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  372. if absContextDir, err = utils.GitClone(gitURL); err != nil {
  373. return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err)
  374. }
  375. return getDockerfileRelPath(absContextDir, dockerfileName)
  376. }
  377. // getContextFromURL uses a remote URL as context for a `docker build`. The
  378. // remote resource is downloaded as either a Dockerfile or a context tar
  379. // archive and stored in a temporary directory used as the context directory.
  380. // Returns the absolute path to the temporary context directory, the relative
  381. // path of the dockerfile in that context directory, and a non-nil error on
  382. // success.
  383. func getContextFromURL(out io.Writer, remoteURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  384. response, err := httputils.Download(remoteURL)
  385. if err != nil {
  386. return "", "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err)
  387. }
  388. defer response.Body.Close()
  389. // Pass the response body through a progress reader.
  390. progReader := &progressreader.Config{
  391. In: response.Body,
  392. Out: out,
  393. Formatter: streamformatter.NewStreamFormatter(),
  394. Size: int(response.ContentLength),
  395. NewLines: true,
  396. ID: "",
  397. Action: fmt.Sprintf("Downloading build context from remote url: %s", remoteURL),
  398. }
  399. return getContextFromReader(progReader, dockerfileName)
  400. }
  401. // getContextFromLocalDir uses the given local directory as context for a
  402. // `docker build`. Returns the absolute path to the local context directory,
  403. // the relative path of the dockerfile in that context directory, and a non-nil
  404. // error on success.
  405. func getContextFromLocalDir(localDir, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  406. // When using a local context directory, when the Dockerfile is specified
  407. // with the `-f/--file` option then it is considered relative to the
  408. // current directory and not the context directory.
  409. if dockerfileName != "" {
  410. if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
  411. return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err)
  412. }
  413. }
  414. return getDockerfileRelPath(localDir, dockerfileName)
  415. }
  416. var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
  417. type trustedDockerfile struct {
  418. *os.File
  419. size int64
  420. }
  421. func (td *trustedDockerfile) Close() error {
  422. td.File.Close()
  423. return os.Remove(td.File.Name())
  424. }
  425. // resolvedTag records the repository, tag, and resolved digest reference
  426. // from a Dockerfile rewrite.
  427. type resolvedTag struct {
  428. repoInfo *registry.RepositoryInfo
  429. digestRef, tagRef registry.Reference
  430. }
  431. // rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
  432. // "FROM <image>" instructions to a digest reference. `translator` is a
  433. // function that takes a repository name and tag reference and returns a
  434. // trusted digest reference.
  435. func rewriteDockerfileFrom(dockerfileName string, translator func(string, registry.Reference) (registry.Reference, error)) (newDockerfile *trustedDockerfile, resolvedTags []*resolvedTag, err error) {
  436. dockerfile, err := os.Open(dockerfileName)
  437. if err != nil {
  438. return nil, nil, fmt.Errorf("unable to open Dockerfile: %v", err)
  439. }
  440. defer dockerfile.Close()
  441. scanner := bufio.NewScanner(dockerfile)
  442. // Make a tempfile to store the rewritten Dockerfile.
  443. tempFile, err := ioutil.TempFile("", "trusted-dockerfile-")
  444. if err != nil {
  445. return nil, nil, fmt.Errorf("unable to make temporary trusted Dockerfile: %v", err)
  446. }
  447. trustedFile := &trustedDockerfile{
  448. File: tempFile,
  449. }
  450. defer func() {
  451. if err != nil {
  452. // Close the tempfile if there was an error during Notary lookups.
  453. // Otherwise the caller should close it.
  454. trustedFile.Close()
  455. }
  456. }()
  457. // Scan the lines of the Dockerfile, looking for a "FROM" line.
  458. for scanner.Scan() {
  459. line := scanner.Text()
  460. matches := dockerfileFromLinePattern.FindStringSubmatch(line)
  461. if matches != nil && matches[1] != "scratch" {
  462. // Replace the line with a resolved "FROM repo@digest"
  463. repo, tag := parsers.ParseRepositoryTag(matches[1])
  464. if tag == "" {
  465. tag = tags.DEFAULTTAG
  466. }
  467. repoInfo, err := registry.ParseRepositoryInfo(repo)
  468. if err != nil {
  469. return nil, nil, fmt.Errorf("unable to parse repository info: %v", err)
  470. }
  471. ref := registry.ParseReference(tag)
  472. if !ref.HasDigest() && isTrusted() {
  473. trustedRef, err := translator(repo, ref)
  474. if err != nil {
  475. return nil, nil, err
  476. }
  477. line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.ImageName(repo)))
  478. resolvedTags = append(resolvedTags, &resolvedTag{
  479. repoInfo: repoInfo,
  480. digestRef: trustedRef,
  481. tagRef: ref,
  482. })
  483. }
  484. }
  485. n, err := fmt.Fprintln(tempFile, line)
  486. if err != nil {
  487. return nil, nil, err
  488. }
  489. trustedFile.size += int64(n)
  490. }
  491. tempFile.Seek(0, os.SEEK_SET)
  492. return trustedFile, resolvedTags, scanner.Err()
  493. }
  494. // replaceDockerfileTarWrapper wraps the given input tar archive stream and
  495. // replaces the entry with the given Dockerfile name with the contents of the
  496. // new Dockerfile. Returns a new tar archive stream with the replaced
  497. // Dockerfile.
  498. func replaceDockerfileTarWrapper(inputTarStream io.ReadCloser, newDockerfile *trustedDockerfile, dockerfileName string) io.ReadCloser {
  499. pipeReader, pipeWriter := io.Pipe()
  500. go func() {
  501. tarReader := tar.NewReader(inputTarStream)
  502. tarWriter := tar.NewWriter(pipeWriter)
  503. defer inputTarStream.Close()
  504. for {
  505. hdr, err := tarReader.Next()
  506. if err == io.EOF {
  507. // Signals end of archive.
  508. tarWriter.Close()
  509. pipeWriter.Close()
  510. return
  511. }
  512. if err != nil {
  513. pipeWriter.CloseWithError(err)
  514. return
  515. }
  516. var content io.Reader = tarReader
  517. if hdr.Name == dockerfileName {
  518. // This entry is the Dockerfile. Since the tar archive was
  519. // generated from a directory on the local filesystem, the
  520. // Dockerfile will only appear once in the archive.
  521. hdr.Size = newDockerfile.size
  522. content = newDockerfile
  523. }
  524. if err := tarWriter.WriteHeader(hdr); err != nil {
  525. pipeWriter.CloseWithError(err)
  526. return
  527. }
  528. if _, err := io.Copy(tarWriter, content); err != nil {
  529. pipeWriter.CloseWithError(err)
  530. return
  531. }
  532. }
  533. }()
  534. return pipeReader
  535. }