github.com/goern/docker@v1.9.0-rc1/api/client/build.go (about)

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