github.com/ncdc/docker@v0.10.1-0.20160129113957-6c6729ef5b74/api/client/build.go (about)

     1  package client
     2  
     3  import (
     4  	"archive/tar"
     5  	"bufio"
     6  	"bytes"
     7  	"fmt"
     8  	"io"
     9  	"io/ioutil"
    10  	"os"
    11  	"os/exec"
    12  	"path/filepath"
    13  	"regexp"
    14  	"runtime"
    15  	"strings"
    16  
    17  	"github.com/docker/docker/api"
    18  	"github.com/docker/docker/builder/dockerignore"
    19  	Cli "github.com/docker/docker/cli"
    20  	"github.com/docker/docker/opts"
    21  	"github.com/docker/docker/pkg/archive"
    22  	"github.com/docker/docker/pkg/fileutils"
    23  	"github.com/docker/docker/pkg/gitutils"
    24  	"github.com/docker/docker/pkg/httputils"
    25  	"github.com/docker/docker/pkg/ioutils"
    26  	"github.com/docker/docker/pkg/jsonmessage"
    27  	flag "github.com/docker/docker/pkg/mflag"
    28  	"github.com/docker/docker/pkg/progress"
    29  	"github.com/docker/docker/pkg/streamformatter"
    30  	"github.com/docker/docker/pkg/urlutil"
    31  	"github.com/docker/docker/reference"
    32  	runconfigopts "github.com/docker/docker/runconfig/opts"
    33  	"github.com/docker/engine-api/types"
    34  	"github.com/docker/engine-api/types/container"
    35  	"github.com/docker/go-units"
    36  )
    37  
    38  type translatorFunc func(reference.NamedTagged) (reference.Canonical, error)
    39  
    40  // CmdBuild builds a new image from the source code at a given path.
    41  //
    42  // If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN.
    43  //
    44  // Usage: docker build [OPTIONS] PATH | URL | -
    45  func (cli *DockerCli) CmdBuild(args ...string) error {
    46  	cmd := Cli.Subcmd("build", []string{"PATH | URL | -"}, Cli.DockerCommands["build"].Description, true)
    47  	flTags := opts.NewListOpts(validateTag)
    48  	cmd.Var(&flTags, []string{"t", "-tag"}, "Name and optionally a tag in the 'name:tag' format")
    49  	suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the build output and print image ID on success")
    50  	noCache := cmd.Bool([]string{"-no-cache"}, false, "Do not use cache when building the image")
    51  	rm := cmd.Bool([]string{"-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"}, "", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap")
    57  	flShmSize := cmd.String([]string{"-shm-size"}, "", "Size of /dev/shm, default value is 64MB")
    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  	flBuildArg := opts.NewListOpts(runconfigopts.ValidateEnv)
    65  	cmd.Var(&flBuildArg, []string{"-build-arg"}, "Set build-time variables")
    66  	isolation := cmd.String([]string{"-isolation"}, "", "Container isolation level")
    67  
    68  	ulimits := make(map[string]*units.Ulimit)
    69  	flUlimits := runconfigopts.NewUlimitOpt(&ulimits)
    70  	cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
    71  
    72  	cmd.Require(flag.Exact, 1)
    73  
    74  	// For trusted pull on "FROM <image>" instruction.
    75  	addTrustedFlags(cmd, true)
    76  
    77  	cmd.ParseFlags(args, true)
    78  
    79  	var (
    80  		context io.ReadCloser
    81  		err     error
    82  	)
    83  
    84  	specifiedContext := cmd.Arg(0)
    85  
    86  	var (
    87  		contextDir    string
    88  		tempDir       string
    89  		relDockerfile string
    90  		progBuff      io.Writer
    91  		buildBuff     io.Writer
    92  	)
    93  
    94  	progBuff = cli.out
    95  	buildBuff = cli.out
    96  	if *suppressOutput {
    97  		progBuff = bytes.NewBuffer(nil)
    98  		buildBuff = bytes.NewBuffer(nil)
    99  	}
   100  
   101  	switch {
   102  	case specifiedContext == "-":
   103  		context, relDockerfile, err = getContextFromReader(cli.in, *dockerfileName)
   104  	case urlutil.IsGitURL(specifiedContext):
   105  		tempDir, relDockerfile, err = getContextFromGitURL(specifiedContext, *dockerfileName)
   106  	case urlutil.IsURL(specifiedContext):
   107  		context, relDockerfile, err = getContextFromURL(progBuff, specifiedContext, *dockerfileName)
   108  	default:
   109  		contextDir, relDockerfile, err = getContextFromLocalDir(specifiedContext, *dockerfileName)
   110  	}
   111  
   112  	if err != nil {
   113  		if *suppressOutput && urlutil.IsURL(specifiedContext) {
   114  			fmt.Fprintln(cli.err, progBuff)
   115  		}
   116  		return fmt.Errorf("unable to prepare context: %s", err)
   117  	}
   118  
   119  	if tempDir != "" {
   120  		defer os.RemoveAll(tempDir)
   121  		contextDir = tempDir
   122  	}
   123  
   124  	if context == nil {
   125  		// And canonicalize dockerfile name to a platform-independent one
   126  		relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile)
   127  		if err != nil {
   128  			return fmt.Errorf("cannot canonicalize dockerfile path %s: %v", relDockerfile, err)
   129  		}
   130  
   131  		f, err := os.Open(filepath.Join(contextDir, ".dockerignore"))
   132  		if err != nil && !os.IsNotExist(err) {
   133  			return err
   134  		}
   135  
   136  		var excludes []string
   137  		if err == nil {
   138  			excludes, err = dockerignore.ReadAll(f)
   139  			if err != nil {
   140  				return err
   141  			}
   142  		}
   143  
   144  		if err := validateContextDirectory(contextDir, excludes); err != nil {
   145  			return fmt.Errorf("Error checking context: '%s'.", err)
   146  		}
   147  
   148  		// If .dockerignore mentions .dockerignore or the Dockerfile
   149  		// then make sure we send both files over to the daemon
   150  		// because Dockerfile is, obviously, needed no matter what, and
   151  		// .dockerignore is needed to know if either one needs to be
   152  		// removed. The daemon will remove them for us, if needed, after it
   153  		// parses the Dockerfile. Ignore errors here, as they will have been
   154  		// caught by validateContextDirectory above.
   155  		var includes = []string{"."}
   156  		keepThem1, _ := fileutils.Matches(".dockerignore", excludes)
   157  		keepThem2, _ := fileutils.Matches(relDockerfile, excludes)
   158  		if keepThem1 || keepThem2 {
   159  			includes = append(includes, ".dockerignore", relDockerfile)
   160  		}
   161  
   162  		context, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
   163  			Compression:     archive.Uncompressed,
   164  			ExcludePatterns: excludes,
   165  			IncludeFiles:    includes,
   166  		})
   167  		if err != nil {
   168  			return err
   169  		}
   170  	}
   171  
   172  	var resolvedTags []*resolvedTag
   173  	if isTrusted() {
   174  		// Wrap the tar archive to replace the Dockerfile entry with the rewritten
   175  		// Dockerfile which uses trusted pulls.
   176  		context = replaceDockerfileTarWrapper(context, relDockerfile, cli.trustedReference, &resolvedTags)
   177  	}
   178  
   179  	// Setup an upload progress bar
   180  	progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(progBuff, true)
   181  
   182  	var body io.Reader = progress.NewProgressReader(context, progressOutput, 0, "", "Sending build context to Docker daemon")
   183  
   184  	var memory int64
   185  	if *flMemoryString != "" {
   186  		parsedMemory, err := units.RAMInBytes(*flMemoryString)
   187  		if err != nil {
   188  			return err
   189  		}
   190  		memory = parsedMemory
   191  	}
   192  
   193  	var memorySwap int64
   194  	if *flMemorySwap != "" {
   195  		if *flMemorySwap == "-1" {
   196  			memorySwap = -1
   197  		} else {
   198  			parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
   199  			if err != nil {
   200  				return err
   201  			}
   202  			memorySwap = parsedMemorySwap
   203  		}
   204  	}
   205  
   206  	var shmSize int64
   207  	if *flShmSize != "" {
   208  		shmSize, err = units.RAMInBytes(*flShmSize)
   209  		if err != nil {
   210  			return err
   211  		}
   212  	}
   213  
   214  	options := types.ImageBuildOptions{
   215  		Context:        body,
   216  		Memory:         memory,
   217  		MemorySwap:     memorySwap,
   218  		Tags:           flTags.GetAll(),
   219  		SuppressOutput: *suppressOutput,
   220  		NoCache:        *noCache,
   221  		Remove:         *rm,
   222  		ForceRemove:    *forceRm,
   223  		PullParent:     *pull,
   224  		IsolationLevel: container.IsolationLevel(*isolation),
   225  		CPUSetCPUs:     *flCPUSetCpus,
   226  		CPUSetMems:     *flCPUSetMems,
   227  		CPUShares:      *flCPUShares,
   228  		CPUQuota:       *flCPUQuota,
   229  		CPUPeriod:      *flCPUPeriod,
   230  		CgroupParent:   *flCgroupParent,
   231  		Dockerfile:     relDockerfile,
   232  		ShmSize:        shmSize,
   233  		Ulimits:        flUlimits.GetList(),
   234  		BuildArgs:      runconfigopts.ConvertKVStringsToMap(flBuildArg.GetAll()),
   235  		AuthConfigs:    cli.configFile.AuthConfigs,
   236  	}
   237  
   238  	response, err := cli.client.ImageBuild(options)
   239  	if err != nil {
   240  		return err
   241  	}
   242  
   243  	err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, cli.outFd, cli.isTerminalOut, nil)
   244  	if err != nil {
   245  		if jerr, ok := err.(*jsonmessage.JSONError); ok {
   246  			// If no error code is set, default to 1
   247  			if jerr.Code == 0 {
   248  				jerr.Code = 1
   249  			}
   250  			if *suppressOutput {
   251  				fmt.Fprintf(cli.err, "%s%s", progBuff, buildBuff)
   252  			}
   253  			return Cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
   254  		}
   255  	}
   256  
   257  	// Windows: show error message about modified file permissions if the
   258  	// daemon isn't running Windows.
   259  	if response.OSType != "windows" && runtime.GOOS == "windows" {
   260  		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.`)
   261  	}
   262  
   263  	// Everything worked so if -q was provided the output from the daemon
   264  	// should be just the image ID and we'll print that to stdout.
   265  	if *suppressOutput {
   266  		fmt.Fprintf(cli.out, "%s", buildBuff)
   267  	}
   268  
   269  	if isTrusted() {
   270  		// Since the build was successful, now we must tag any of the resolved
   271  		// images from the above Dockerfile rewrite.
   272  		for _, resolved := range resolvedTags {
   273  			if err := cli.tagTrusted(resolved.digestRef, resolved.tagRef); err != nil {
   274  				return err
   275  			}
   276  		}
   277  	}
   278  
   279  	return nil
   280  }
   281  
   282  // validateContextDirectory checks if all the contents of the directory
   283  // can be read and returns an error if some files can't be read
   284  // symlinks which point to non-existing files don't trigger an error
   285  func validateContextDirectory(srcPath string, excludes []string) error {
   286  	contextRoot, err := getContextRoot(srcPath)
   287  	if err != nil {
   288  		return err
   289  	}
   290  	return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
   291  		// skip this directory/file if it's not in the path, it won't get added to the context
   292  		if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil {
   293  			return err
   294  		} else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
   295  			return err
   296  		} else if skip {
   297  			if f.IsDir() {
   298  				return filepath.SkipDir
   299  			}
   300  			return nil
   301  		}
   302  
   303  		if err != nil {
   304  			if os.IsPermission(err) {
   305  				return fmt.Errorf("can't stat '%s'", filePath)
   306  			}
   307  			if os.IsNotExist(err) {
   308  				return nil
   309  			}
   310  			return err
   311  		}
   312  
   313  		// skip checking if symlinks point to non-existing files, such symlinks can be useful
   314  		// also skip named pipes, because they hanging on open
   315  		if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
   316  			return nil
   317  		}
   318  
   319  		if !f.IsDir() {
   320  			currentFile, err := os.Open(filePath)
   321  			if err != nil && os.IsPermission(err) {
   322  				return fmt.Errorf("no permission to read from '%s'", filePath)
   323  			}
   324  			currentFile.Close()
   325  		}
   326  		return nil
   327  	})
   328  }
   329  
   330  // validateTag checks if the given image name can be resolved.
   331  func validateTag(rawRepo string) (string, error) {
   332  	_, err := reference.ParseNamed(rawRepo)
   333  	if err != nil {
   334  		return "", err
   335  	}
   336  
   337  	return rawRepo, nil
   338  }
   339  
   340  // isUNC returns true if the path is UNC (one starting \\). It always returns
   341  // false on Linux.
   342  func isUNC(path string) bool {
   343  	return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`)
   344  }
   345  
   346  // getDockerfileRelPath uses the given context directory for a `docker build`
   347  // and returns the absolute path to the context directory, the relative path of
   348  // the dockerfile in that context directory, and a non-nil error on success.
   349  func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
   350  	if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
   351  		return "", "", fmt.Errorf("unable to get absolute context directory: %v", err)
   352  	}
   353  
   354  	// The context dir might be a symbolic link, so follow it to the actual
   355  	// target directory.
   356  	//
   357  	// FIXME. We use isUNC (always false on non-Windows platforms) to workaround
   358  	// an issue in golang. On Windows, EvalSymLinks does not work on UNC file
   359  	// paths (those starting with \\). This hack means that when using links
   360  	// on UNC paths, they will not be followed.
   361  	if !isUNC(absContextDir) {
   362  		absContextDir, err = filepath.EvalSymlinks(absContextDir)
   363  		if err != nil {
   364  			return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err)
   365  		}
   366  	}
   367  
   368  	stat, err := os.Lstat(absContextDir)
   369  	if err != nil {
   370  		return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err)
   371  	}
   372  
   373  	if !stat.IsDir() {
   374  		return "", "", fmt.Errorf("context must be a directory: %s", absContextDir)
   375  	}
   376  
   377  	absDockerfile := givenDockerfile
   378  	if absDockerfile == "" {
   379  		// No -f/--file was specified so use the default relative to the
   380  		// context directory.
   381  		absDockerfile = filepath.Join(absContextDir, api.DefaultDockerfileName)
   382  
   383  		// Just to be nice ;-) look for 'dockerfile' too but only
   384  		// use it if we found it, otherwise ignore this check
   385  		if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
   386  			altPath := filepath.Join(absContextDir, strings.ToLower(api.DefaultDockerfileName))
   387  			if _, err = os.Lstat(altPath); err == nil {
   388  				absDockerfile = altPath
   389  			}
   390  		}
   391  	}
   392  
   393  	// If not already an absolute path, the Dockerfile path should be joined to
   394  	// the base directory.
   395  	if !filepath.IsAbs(absDockerfile) {
   396  		absDockerfile = filepath.Join(absContextDir, absDockerfile)
   397  	}
   398  
   399  	// Evaluate symlinks in the path to the Dockerfile too.
   400  	//
   401  	// FIXME. We use isUNC (always false on non-Windows platforms) to workaround
   402  	// an issue in golang. On Windows, EvalSymLinks does not work on UNC file
   403  	// paths (those starting with \\). This hack means that when using links
   404  	// on UNC paths, they will not be followed.
   405  	if !isUNC(absDockerfile) {
   406  		absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
   407  		if err != nil {
   408  			return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
   409  		}
   410  	}
   411  
   412  	if _, err := os.Lstat(absDockerfile); err != nil {
   413  		if os.IsNotExist(err) {
   414  			return "", "", fmt.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
   415  		}
   416  		return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err)
   417  	}
   418  
   419  	if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
   420  		return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err)
   421  	}
   422  
   423  	if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
   424  		return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
   425  	}
   426  
   427  	return absContextDir, relDockerfile, nil
   428  }
   429  
   430  // writeToFile copies from the given reader and writes it to a file with the
   431  // given filename.
   432  func writeToFile(r io.Reader, filename string) error {
   433  	file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600))
   434  	if err != nil {
   435  		return fmt.Errorf("unable to create file: %v", err)
   436  	}
   437  	defer file.Close()
   438  
   439  	if _, err := io.Copy(file, r); err != nil {
   440  		return fmt.Errorf("unable to write file: %v", err)
   441  	}
   442  
   443  	return nil
   444  }
   445  
   446  // getContextFromReader will read the contents of the given reader as either a
   447  // Dockerfile or tar archive. Returns a tar archive used as a context and a
   448  // path to the Dockerfile inside the tar.
   449  func getContextFromReader(r io.ReadCloser, dockerfileName string) (out io.ReadCloser, relDockerfile string, err error) {
   450  	buf := bufio.NewReader(r)
   451  
   452  	magic, err := buf.Peek(archive.HeaderSize)
   453  	if err != nil && err != io.EOF {
   454  		return nil, "", fmt.Errorf("failed to peek context header from STDIN: %v", err)
   455  	}
   456  
   457  	if archive.IsArchive(magic) {
   458  		return ioutils.NewReadCloserWrapper(buf, func() error { return r.Close() }), dockerfileName, nil
   459  	}
   460  
   461  	// Input should be read as a Dockerfile.
   462  	tmpDir, err := ioutil.TempDir("", "docker-build-context-")
   463  	if err != nil {
   464  		return nil, "", fmt.Errorf("unbale to create temporary context directory: %v", err)
   465  	}
   466  
   467  	f, err := os.Create(filepath.Join(tmpDir, api.DefaultDockerfileName))
   468  	if err != nil {
   469  		return nil, "", err
   470  	}
   471  	_, err = io.Copy(f, buf)
   472  	if err != nil {
   473  		f.Close()
   474  		return nil, "", err
   475  	}
   476  
   477  	if err := f.Close(); err != nil {
   478  		return nil, "", err
   479  	}
   480  	if err := r.Close(); err != nil {
   481  		return nil, "", err
   482  	}
   483  
   484  	tar, err := archive.Tar(tmpDir, archive.Uncompressed)
   485  	if err != nil {
   486  		return nil, "", err
   487  	}
   488  
   489  	return ioutils.NewReadCloserWrapper(tar, func() error {
   490  		err := tar.Close()
   491  		os.RemoveAll(tmpDir)
   492  		return err
   493  	}), api.DefaultDockerfileName, nil
   494  
   495  }
   496  
   497  // getContextFromGitURL uses a Git URL as context for a `docker build`. The
   498  // git repo is cloned into a temporary directory used as the context directory.
   499  // Returns the absolute path to the temporary context directory, the relative
   500  // path of the dockerfile in that context directory, and a non-nil error on
   501  // success.
   502  func getContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
   503  	if _, err := exec.LookPath("git"); err != nil {
   504  		return "", "", fmt.Errorf("unable to find 'git': %v", err)
   505  	}
   506  	if absContextDir, err = gitutils.Clone(gitURL); err != nil {
   507  		return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err)
   508  	}
   509  
   510  	return getDockerfileRelPath(absContextDir, dockerfileName)
   511  }
   512  
   513  // getContextFromURL uses a remote URL as context for a `docker build`. The
   514  // remote resource is downloaded as either a Dockerfile or a tar archive.
   515  // Returns the tar archive used for the context and a path of the
   516  // dockerfile inside the tar.
   517  func getContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) {
   518  	response, err := httputils.Download(remoteURL)
   519  	if err != nil {
   520  		return nil, "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err)
   521  	}
   522  	progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(out, true)
   523  
   524  	// Pass the response body through a progress reader.
   525  	progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL))
   526  
   527  	return getContextFromReader(ioutils.NewReadCloserWrapper(progReader, func() error { return response.Body.Close() }), dockerfileName)
   528  }
   529  
   530  // getContextFromLocalDir uses the given local directory as context for a
   531  // `docker build`. Returns the absolute path to the local context directory,
   532  // the relative path of the dockerfile in that context directory, and a non-nil
   533  // error on success.
   534  func getContextFromLocalDir(localDir, dockerfileName string) (absContextDir, relDockerfile string, err error) {
   535  	// When using a local context directory, when the Dockerfile is specified
   536  	// with the `-f/--file` option then it is considered relative to the
   537  	// current directory and not the context directory.
   538  	if dockerfileName != "" {
   539  		if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
   540  			return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err)
   541  		}
   542  	}
   543  
   544  	return getDockerfileRelPath(localDir, dockerfileName)
   545  }
   546  
   547  var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
   548  
   549  // resolvedTag records the repository, tag, and resolved digest reference
   550  // from a Dockerfile rewrite.
   551  type resolvedTag struct {
   552  	digestRef reference.Canonical
   553  	tagRef    reference.NamedTagged
   554  }
   555  
   556  // rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
   557  // "FROM <image>" instructions to a digest reference. `translator` is a
   558  // function that takes a repository name and tag reference and returns a
   559  // trusted digest reference.
   560  func rewriteDockerfileFrom(dockerfile io.Reader, translator translatorFunc) (newDockerfile []byte, resolvedTags []*resolvedTag, err error) {
   561  	scanner := bufio.NewScanner(dockerfile)
   562  	buf := bytes.NewBuffer(nil)
   563  
   564  	// Scan the lines of the Dockerfile, looking for a "FROM" line.
   565  	for scanner.Scan() {
   566  		line := scanner.Text()
   567  
   568  		matches := dockerfileFromLinePattern.FindStringSubmatch(line)
   569  		if matches != nil && matches[1] != api.NoBaseImageSpecifier {
   570  			// Replace the line with a resolved "FROM repo@digest"
   571  			ref, err := reference.ParseNamed(matches[1])
   572  			if err != nil {
   573  				return nil, nil, err
   574  			}
   575  			ref = reference.WithDefaultTag(ref)
   576  			if ref, ok := ref.(reference.NamedTagged); ok && isTrusted() {
   577  				trustedRef, err := translator(ref)
   578  				if err != nil {
   579  					return nil, nil, err
   580  				}
   581  
   582  				line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.String()))
   583  				resolvedTags = append(resolvedTags, &resolvedTag{
   584  					digestRef: trustedRef,
   585  					tagRef:    ref,
   586  				})
   587  			}
   588  		}
   589  
   590  		_, err := fmt.Fprintln(buf, line)
   591  		if err != nil {
   592  			return nil, nil, err
   593  		}
   594  	}
   595  
   596  	return buf.Bytes(), resolvedTags, scanner.Err()
   597  }
   598  
   599  // replaceDockerfileTarWrapper wraps the given input tar archive stream and
   600  // replaces the entry with the given Dockerfile name with the contents of the
   601  // new Dockerfile. Returns a new tar archive stream with the replaced
   602  // Dockerfile.
   603  func replaceDockerfileTarWrapper(inputTarStream io.ReadCloser, dockerfileName string, translator translatorFunc, resolvedTags *[]*resolvedTag) io.ReadCloser {
   604  	pipeReader, pipeWriter := io.Pipe()
   605  	go func() {
   606  		tarReader := tar.NewReader(inputTarStream)
   607  		tarWriter := tar.NewWriter(pipeWriter)
   608  
   609  		defer inputTarStream.Close()
   610  
   611  		for {
   612  			hdr, err := tarReader.Next()
   613  			if err == io.EOF {
   614  				// Signals end of archive.
   615  				tarWriter.Close()
   616  				pipeWriter.Close()
   617  				return
   618  			}
   619  			if err != nil {
   620  				pipeWriter.CloseWithError(err)
   621  				return
   622  			}
   623  
   624  			var content io.Reader = tarReader
   625  			if hdr.Name == dockerfileName {
   626  				// This entry is the Dockerfile. Since the tar archive was
   627  				// generated from a directory on the local filesystem, the
   628  				// Dockerfile will only appear once in the archive.
   629  				var newDockerfile []byte
   630  				newDockerfile, *resolvedTags, err = rewriteDockerfileFrom(content, translator)
   631  				if err != nil {
   632  					pipeWriter.CloseWithError(err)
   633  					return
   634  				}
   635  				hdr.Size = int64(len(newDockerfile))
   636  				content = bytes.NewBuffer(newDockerfile)
   637  			}
   638  
   639  			if err := tarWriter.WriteHeader(hdr); err != nil {
   640  				pipeWriter.CloseWithError(err)
   641  				return
   642  			}
   643  
   644  			if _, err := io.Copy(tarWriter, content); err != nil {
   645  				pipeWriter.CloseWithError(err)
   646  				return
   647  			}
   648  		}
   649  	}()
   650  
   651  	return pipeReader
   652  }