build.go 21 KB

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