a1522ec0 |
package builder |
22c46af4 |
|
3f5f6b03 |
// internals for handling commands. Covers many areas and a lot of
// non-contiguous functionality. Please read the comments.
|
d6c0bbc3 |
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/ioutil" |
2e482c86 |
"net/http" |
d6c0bbc3 |
"net/url"
"os"
"path/filepath" |
010e3e04 |
"runtime" |
d6c0bbc3 |
"sort"
"strings"
"syscall"
"time"
|
6f4d8470 |
"github.com/Sirupsen/logrus" |
1150c163 |
"github.com/docker/docker/builder/parser" |
02c7bbef |
"github.com/docker/docker/cliconfig" |
d6c0bbc3 |
"github.com/docker/docker/daemon" |
6e38a53f |
"github.com/docker/docker/graph" |
9001ea26 |
"github.com/docker/docker/image" |
30d5a42c |
"github.com/docker/docker/pkg/archive" |
1cb17f03 |
"github.com/docker/docker/pkg/chrootarchive" |
c30a55f1 |
"github.com/docker/docker/pkg/httputils" |
e662775f |
"github.com/docker/docker/pkg/ioutils" |
0cd6c05d |
"github.com/docker/docker/pkg/jsonmessage" |
d6c0bbc3 |
"github.com/docker/docker/pkg/parsers" |
12b278d3 |
"github.com/docker/docker/pkg/progressreader" |
b80fae73 |
"github.com/docker/docker/pkg/stringid" |
d6c0bbc3 |
"github.com/docker/docker/pkg/system"
"github.com/docker/docker/pkg/tarsum" |
5794b537 |
"github.com/docker/docker/pkg/urlutil" |
bb9da6ba |
"github.com/docker/docker/registry" |
e6ae89a4 |
"github.com/docker/docker/runconfig" |
d6c0bbc3 |
)
|
8c4a282a |
func (b *builder) readContext(context io.Reader) (err error) { |
22c46af4 |
tmpdirPath, err := ioutil.TempDir("", "docker-build")
if err != nil { |
13c08b89 |
return |
22c46af4 |
}
|
13c08b89 |
// Make sure we clean-up upon error. In the happy case the caller
// is expected to manage the clean-up
defer func() {
if err != nil {
if e := os.RemoveAll(tmpdirPath); e != nil {
logrus.Debugf("[BUILDER] failed to remove temporary context: %s", e)
}
}
}()
|
22c46af4 |
decompressedStream, err := archive.DecompressStream(context)
if err != nil { |
13c08b89 |
return |
22c46af4 |
}
|
0e10507a |
if b.context, err = tarsum.NewTarSum(decompressedStream, true, tarsum.Version1); err != nil { |
13c08b89 |
return |
747f89cd |
} |
1cb17f03 |
|
13c08b89 |
if err = chrootarchive.Untar(b.context, tmpdirPath, nil); err != nil {
return |
22c46af4 |
}
b.contextPath = tmpdirPath |
13c08b89 |
return |
22c46af4 |
}
|
8c4a282a |
func (b *builder) commit(id string, autoCmd *runconfig.Command, comment string) error { |
7f091eca |
if b.disableCommit {
return nil
} |
89367899 |
if b.image == "" && !b.noBaseImage { |
22c46af4 |
return fmt.Errorf("Please provide a source image with `from` prior to commit")
} |
1ae4c00a |
b.Config.Image = b.image |
22c46af4 |
if id == "" { |
1ae4c00a |
cmd := b.Config.Cmd |
010e3e04 |
if runtime.GOOS != "windows" {
b.Config.Cmd = runconfig.NewCommand("/bin/sh", "-c", "#(nop) "+comment)
} else {
b.Config.Cmd = runconfig.NewCommand("cmd", "/S /C", "REM (nop) "+comment)
} |
767df67e |
defer func(cmd *runconfig.Command) { b.Config.Cmd = cmd }(cmd) |
22c46af4 |
hit, err := b.probeCache()
if err != nil {
return err
}
if hit {
return nil
}
|
f17410da |
container, err := b.create() |
22c46af4 |
if err != nil {
return err
}
id = container.ID
if err := container.Mount(); err != nil {
return err
}
defer container.Unmount()
} |
d25a6537 |
container, err := b.Daemon.Get(id)
if err != nil {
return err |
22c46af4 |
}
// Note: Actually copy the struct |
1ae4c00a |
autoConfig := *b.Config |
22c46af4 |
autoConfig.Cmd = autoCmd |
ac107995 |
|
7046651b |
commitCfg := &daemon.ContainerCommitConfig{
Author: b.maintainer,
Pause: true,
Config: &autoConfig,
}
|
22c46af4 |
// Commit the container |
7046651b |
image, err := b.Daemon.Commit(container, commitCfg) |
22c46af4 |
if err != nil {
return err
} |
1b67c38f |
b.Daemon.Graph().Retain(b.id, image.ID)
b.activeImages = append(b.activeImages, image.ID) |
22c46af4 |
b.image = image.ID
return nil
}
|
05b8a1eb |
type copyInfo struct {
origPath string
destPath string |
acd40d50 |
hash string |
05b8a1eb |
decompress bool
tmpDir string
}
|
8c4a282a |
func (b *builder) runContextCommand(args []string, allowRemote bool, allowDecompression bool, cmdName string) error { |
22c46af4 |
if b.context == nil {
return fmt.Errorf("No context given. Impossible to use %s", cmdName)
}
|
05b8a1eb |
if len(args) < 2 {
return fmt.Errorf("Invalid %s format - at least two arguments required", cmdName)
}
|
2ceb1146 |
// Work in daemon-specific filepath semantics
dest := filepath.FromSlash(args[len(args)-1]) // last one is always the dest |
05b8a1eb |
|
acd40d50 |
copyInfos := []*copyInfo{} |
05b8a1eb |
b.Config.Image = b.image
defer func() {
for _, ci := range copyInfos {
if ci.tmpDir != "" {
os.RemoveAll(ci.tmpDir)
}
}
}()
// Loop through each src file and calculate the info we need to
// do the copy (e.g. hash value if cached). Don't actually do
// the copy until we've looked at all src files |
acd40d50 |
for _, orig := range args[0 : len(args)-1] { |
84453814 |
if err := calcCopyInfo(
b,
cmdName,
©Infos,
orig,
dest,
allowRemote,
allowDecompression, |
82daa438 |
true, |
84453814 |
); err != nil { |
05b8a1eb |
return err
} |
acd40d50 |
}
if len(copyInfos) == 0 {
return fmt.Errorf("No source files were specified")
} |
2ceb1146 |
if len(copyInfos) > 1 && !strings.HasSuffix(dest, string(os.PathSeparator)) { |
acd40d50 |
return fmt.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName)
} |
05b8a1eb |
|
acd40d50 |
// For backwards compat, if there's just one CI then use it as the
// cache look-up string, otherwise hash 'em all into one
var srcHash string
var origPaths string
if len(copyInfos) == 1 {
srcHash = copyInfos[0].hash
origPaths = copyInfos[0].origPath
} else {
var hashs []string
var origs []string
for _, ci := range copyInfos {
hashs = append(hashs, ci.hash)
origs = append(origs, ci.origPath) |
05b8a1eb |
} |
acd40d50 |
hasher := sha256.New()
hasher.Write([]byte(strings.Join(hashs, ",")))
srcHash = "multi:" + hex.EncodeToString(hasher.Sum(nil))
origPaths = strings.Join(origs, " ") |
05b8a1eb |
} |
22c46af4 |
|
1ae4c00a |
cmd := b.Config.Cmd |
010e3e04 |
if runtime.GOOS != "windows" {
b.Config.Cmd = runconfig.NewCommand("/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest))
} else {
b.Config.Cmd = runconfig.NewCommand("cmd", "/S /C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest))
} |
767df67e |
defer func(cmd *runconfig.Command) { b.Config.Cmd = cmd }(cmd) |
22c46af4 |
|
05b8a1eb |
hit, err := b.probeCache()
if err != nil {
return err
} |
1a5ea50a |
if hit { |
05b8a1eb |
return nil
}
|
1df87b95 |
container, _, err := b.Daemon.Create(b.Config, nil, "") |
05b8a1eb |
if err != nil {
return err
}
b.TmpContainers[container.ID] = struct{}{}
if err := container.Mount(); err != nil {
return err
}
defer container.Unmount()
|
52f4d09f |
if err := container.PrepareStorage(); err != nil {
return err
}
|
05b8a1eb |
for _, ci := range copyInfos {
if err := b.addContext(container, ci.origPath, ci.destPath, ci.decompress); err != nil {
return err
}
}
|
52f4d09f |
if err := container.CleanupStorage(); err != nil {
return err
}
|
acd40d50 |
if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)); err != nil { |
05b8a1eb |
return err
}
return nil
}
|
8c4a282a |
func calcCopyInfo(b *builder, cmdName string, cInfos *[]*copyInfo, origPath string, destPath string, allowRemote bool, allowDecompression bool, allowWildcards bool) error { |
acd40d50 |
|
2ceb1146 |
// Work in daemon-specific OS filepath semantics. However, we save
// the the origPath passed in here, as it might also be a URL which
// we need to check for in this function.
passedInOrigPath := origPath
origPath = filepath.FromSlash(origPath)
destPath = filepath.FromSlash(destPath)
if origPath != "" && origPath[0] == os.PathSeparator && len(origPath) > 1 { |
acd40d50 |
origPath = origPath[1:]
} |
2ceb1146 |
origPath = strings.TrimPrefix(origPath, "."+string(os.PathSeparator)) |
acd40d50 |
|
f21f9f85 |
// Twiddle the destPath when its a relative path - meaning, make it
// relative to the WORKINGDIR
if !filepath.IsAbs(destPath) { |
2ceb1146 |
hasSlash := strings.HasSuffix(destPath, string(os.PathSeparator))
destPath = filepath.Join(string(os.PathSeparator), filepath.FromSlash(b.Config.WorkingDir), destPath) |
f21f9f85 |
// Make sure we preserve any trailing slash
if hasSlash { |
2ceb1146 |
destPath += string(os.PathSeparator) |
f21f9f85 |
}
}
|
acd40d50 |
// In the remote/URL case, download it and gen its hashcode |
2ceb1146 |
if urlutil.IsURL(passedInOrigPath) {
// As it's a URL, we go back to processing on what was passed in
// to this function
origPath = passedInOrigPath
|
acd40d50 |
if !allowRemote {
return fmt.Errorf("Source can't be a URL for %s", cmdName)
} |
22c46af4 |
|
acd40d50 |
ci := copyInfo{}
ci.origPath = origPath
ci.hash = origPath // default to this but can change
ci.destPath = destPath
ci.decompress = false
*cInfos = append(*cInfos, &ci) |
05b8a1eb |
|
22c46af4 |
// Initiate the download |
c30a55f1 |
resp, err := httputils.Download(ci.origPath) |
22c46af4 |
if err != nil {
return err
}
// Create a tmp dir
tmpDirName, err := ioutil.TempDir(b.contextPath, "docker-remote")
if err != nil {
return err
} |
05b8a1eb |
ci.tmpDir = tmpDirName |
22c46af4 |
// Create a tmp file within our tmp dir |
010e3e04 |
tmpFileName := filepath.Join(tmpDirName, "tmp") |
22c46af4 |
tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return err
}
// Download and dump result to tmp file |
12b278d3 |
if _, err := io.Copy(tmpFile, progressreader.New(progressreader.Config{
In: resp.Body,
Out: b.OutOld,
Formatter: b.StreamFormatter,
Size: int(resp.ContentLength),
NewLines: true,
ID: "",
Action: "Downloading",
})); err != nil { |
22c46af4 |
tmpFile.Close()
return err
} |
4e40d09a |
fmt.Fprintf(b.OutStream, "\n") |
22c46af4 |
tmpFile.Close()
|
2e482c86 |
// Set the mtime to the Last-Modified header value if present
// Otherwise just remove atime and mtime
times := make([]syscall.Timespec, 2)
lastMod := resp.Header.Get("Last-Modified")
if lastMod != "" {
mTime, err := http.ParseTime(lastMod)
// If we can't parse it then just let it default to 'zero'
// otherwise use the parsed time value
if err == nil {
times[1] = syscall.NsecToTimespec(mTime.UnixNano())
}
}
if err := system.UtimesNano(tmpFileName, times); err != nil { |
22c46af4 |
return err
}
|
010e3e04 |
ci.origPath = filepath.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName)) |
22c46af4 |
// If the destination is a directory, figure out the filename. |
2ceb1146 |
if strings.HasSuffix(ci.destPath, string(os.PathSeparator)) { |
acd40d50 |
u, err := url.Parse(origPath) |
22c46af4 |
if err != nil {
return err
}
path := u.Path |
2ceb1146 |
if strings.HasSuffix(path, string(os.PathSeparator)) { |
22c46af4 |
path = path[:len(path)-1]
} |
2ceb1146 |
parts := strings.Split(path, string(os.PathSeparator)) |
22c46af4 |
filename := parts[len(parts)-1]
if filename == "" {
return fmt.Errorf("cannot determine filename from url: %s", u)
} |
05b8a1eb |
ci.destPath = ci.destPath + filename |
22c46af4 |
}
|
6f20b957 |
// Calc the checksum, even if we're using the cache
r, err := archive.Tar(tmpFileName, archive.Uncompressed)
if err != nil {
return err |
acd40d50 |
} |
0e10507a |
tarSum, err := tarsum.NewTarSum(r, true, tarsum.Version1) |
6f20b957 |
if err != nil {
return err
}
if _, err := io.Copy(ioutil.Discard, tarSum); err != nil {
return err
}
ci.hash = tarSum.Sum(nil)
r.Close() |
acd40d50 |
return nil
}
// Deal with wildcards |
8c4a282a |
if allowWildcards && containsWildcards(origPath) { |
acd40d50 |
for _, fileInfo := range b.context.GetSums() {
if fileInfo.Name() == "" {
continue |
22c46af4 |
} |
010e3e04 |
match, _ := filepath.Match(origPath, fileInfo.Name()) |
acd40d50 |
if !match {
continue |
22c46af4 |
} |
acd40d50 |
|
82daa438 |
// Note we set allowWildcards to false in case the name has
// a * in it
calcCopyInfo(b, cmdName, cInfos, fileInfo.Name(), destPath, allowRemote, allowDecompression, false) |
acd40d50 |
}
return nil
}
// Must be a dir or a file
if err := b.checkPathForAddition(origPath); err != nil {
return err
} |
010e3e04 |
fi, _ := os.Stat(filepath.Join(b.contextPath, origPath)) |
acd40d50 |
ci := copyInfo{}
ci.origPath = origPath
ci.hash = origPath
ci.destPath = destPath
ci.decompress = allowDecompression
*cInfos = append(*cInfos, &ci)
// Deal with the single file case
if !fi.IsDir() {
// This will match first file in sums of the archive
fis := b.context.GetSums().GetFile(ci.origPath)
if fis != nil {
ci.hash = "file:" + fis.Sum() |
22c46af4 |
} |
acd40d50 |
return nil
}
// Must be a dir
var subfiles []string |
010e3e04 |
absOrigPath := filepath.Join(b.contextPath, ci.origPath) |
22c46af4 |
|
acd40d50 |
// Add a trailing / to make sure we only pick up nested files under
// the dir and not sibling files of the dir that just happen to
// start with the same chars |
2ceb1146 |
if !strings.HasSuffix(absOrigPath, string(os.PathSeparator)) {
absOrigPath += string(os.PathSeparator) |
22c46af4 |
}
|
2ceb1146 |
// Need path w/o slash too to find matching dir w/o trailing slash |
acd40d50 |
absOrigPathNoSlash := absOrigPath[:len(absOrigPath)-1]
for _, fileInfo := range b.context.GetSums() { |
010e3e04 |
absFile := filepath.Join(b.contextPath, fileInfo.Name()) |
6d801a3c |
// Any file in the context that starts with the given path will be
// picked up and its hashcode used. However, we'll exclude the
// root dir itself. We do this for a coupel of reasons:
// 1 - ADD/COPY will not copy the dir itself, just its children
// so there's no reason to include it in the hash calc
// 2 - the metadata on the dir will change when any child file
// changes. This will lead to a miss in the cache check if that
// child file is in the .dockerignore list.
if strings.HasPrefix(absFile, absOrigPath) && absFile != absOrigPathNoSlash { |
acd40d50 |
subfiles = append(subfiles, fileInfo.Sum())
} |
22c46af4 |
} |
acd40d50 |
sort.Strings(subfiles)
hasher := sha256.New()
hasher.Write([]byte(strings.Join(subfiles, ",")))
ci.hash = "dir:" + hex.EncodeToString(hasher.Sum(nil))
|
22c46af4 |
return nil
} |
d6c0bbc3 |
|
8c4a282a |
func containsWildcards(name string) bool { |
acd40d50 |
for i := 0; i < len(name); i++ {
ch := name[i]
if ch == '\\' {
i++
} else if ch == '*' || ch == '?' || ch == '[' {
return true
}
}
return false
}
|
8c4a282a |
func (b *builder) pullImage(name string) (*image.Image, error) { |
d6c0bbc3 |
remote, tag := parsers.ParseRepositoryTag(name) |
6ba5d67a |
if tag == "" {
tag = "latest"
} |
6e38a53f |
|
02c7bbef |
pullRegistryAuth := &cliconfig.AuthConfig{}
if len(b.AuthConfigs) > 0 { |
d6c0bbc3 |
// The request came with a full auth config file, we prefer to use that |
03d3d79b |
repoInfo, err := b.Daemon.RegistryService.ResolveRepository(remote) |
d6c0bbc3 |
if err != nil {
return nil, err
} |
02c7bbef |
resolvedConfig := registry.ResolveAuthConfig(
&cliconfig.ConfigFile{AuthConfigs: b.AuthConfigs},
repoInfo.Index,
)
pullRegistryAuth = &resolvedConfig |
d6c0bbc3 |
} |
6e38a53f |
imagePullConfig := &graph.ImagePullConfig{
AuthConfig: pullRegistryAuth,
OutStream: ioutils.NopWriteCloser(b.OutOld),
}
|
a2f74aa4 |
if err := b.Daemon.Repositories().Pull(remote, tag, imagePullConfig); err != nil { |
d6c0bbc3 |
return nil, err
} |
6e38a53f |
|
2ef1dec7 |
image, err := b.Daemon.Repositories().LookupImage(name) |
d6c0bbc3 |
if err != nil {
return nil, err
}
return image, nil
}
|
8c4a282a |
func (b *builder) processImageFrom(img *image.Image) error { |
d6c0bbc3 |
b.image = img.ID |
cb51681a |
|
d6c0bbc3 |
if img.Config != nil { |
1ae4c00a |
b.Config = img.Config |
d6c0bbc3 |
} |
cb51681a |
|
3c177dc8 |
// The default path will be blank on Windows (set by HCS)
if len(b.Config.Env) == 0 && daemon.DefaultPathEnv != "" { |
1ae4c00a |
b.Config.Env = append(b.Config.Env, "PATH="+daemon.DefaultPathEnv) |
d6c0bbc3 |
} |
cb51681a |
|
d6c0bbc3 |
// Process ONBUILD triggers if they exist |
1ae4c00a |
if nTriggers := len(b.Config.OnBuild); nTriggers != 0 { |
2ef1dec7 |
fmt.Fprintf(b.ErrStream, "# Executing %d build triggers\n", nTriggers) |
d6c0bbc3 |
}
|
3941623f |
// Copy the ONBUILD triggers, and remove them from the config, since the config will be committed. |
1ae4c00a |
onBuildTriggers := b.Config.OnBuild
b.Config.OnBuild = []string{} |
d6c0bbc3 |
|
1150c163 |
// parse the ONBUILD triggers by invoking the parser |
8edacc67 |
for stepN, step := range onBuildTriggers { |
1150c163 |
ast, err := parser.Parse(strings.NewReader(step))
if err != nil {
return err |
d6c0bbc3 |
}
|
1150c163 |
for i, n := range ast.Children {
switch strings.ToUpper(n.Value) {
case "ONBUILD":
return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
case "MAINTAINER", "FROM":
return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", n.Value)
} |
d6c0bbc3 |
|
8edacc67 |
fmt.Fprintf(b.OutStream, "Trigger %d, %s\n", stepN, step) |
1150c163 |
if err := b.dispatch(i, n); err != nil { |
d6c0bbc3 |
return err
}
}
}
return nil
}
|
2ef1dec7 |
// probeCache checks to see if image-caching is enabled (`b.UtilizeCache`) |
1ae4c00a |
// and if so attempts to look up the current `b.image` and `b.Config` pair |
2ef1dec7 |
// in the current server `b.Daemon`. If an image is found, probeCache returns |
d6c0bbc3 |
// `(true, nil)`. If no image is found, it returns `(false, nil)`. If there
// is any error, it returns `(false, err)`. |
8c4a282a |
func (b *builder) probeCache() (bool, error) { |
2420c1f0 |
if !b.UtilizeCache || b.cacheBusted {
return false, nil
}
cache, err := b.Daemon.ImageGetCached(b.image, b.Config)
if err != nil {
return false, err
}
if cache == nil { |
6f4d8470 |
logrus.Debugf("[BUILDER] Cache miss") |
2420c1f0 |
b.cacheBusted = true
return false, nil |
d6c0bbc3 |
} |
2420c1f0 |
fmt.Fprintf(b.OutStream, " ---> Using cache\n") |
6f4d8470 |
logrus.Debugf("[BUILDER] Use cached version") |
2420c1f0 |
b.image = cache.ID |
1b67c38f |
b.Daemon.Graph().Retain(b.id, cache.ID)
b.activeImages = append(b.activeImages, cache.ID) |
2420c1f0 |
return true, nil |
d6c0bbc3 |
}
|
8c4a282a |
func (b *builder) create() (*daemon.Container, error) { |
89367899 |
if b.image == "" && !b.noBaseImage { |
d6c0bbc3 |
return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
} |
1ae4c00a |
b.Config.Image = b.image |
d6c0bbc3 |
|
e6ae89a4 |
hostConfig := &runconfig.HostConfig{ |
bb411939 |
CpuShares: b.cpuShares, |
dccb8b5c |
CpuPeriod: b.cpuPeriod, |
bb411939 |
CpuQuota: b.cpuQuota,
CpusetCpus: b.cpuSetCpus,
CpusetMems: b.cpuSetMems,
CgroupParent: b.cgroupParent,
Memory: b.memory,
MemorySwap: b.memorySwap, |
877dbbbd |
Ulimits: b.ulimits, |
e6ae89a4 |
}
|
f17410da |
config := *b.Config
|
d6c0bbc3 |
// Create the container |
e6ae89a4 |
c, warnings, err := b.Daemon.Create(b.Config, hostConfig, "") |
d6c0bbc3 |
if err != nil {
return nil, err
} |
f17410da |
for _, warning := range warnings {
fmt.Fprintf(b.OutStream, " ---> [Warning] %s\n", warning)
} |
2ef1dec7 |
|
1ae4c00a |
b.TmpContainers[c.ID] = struct{}{} |
b80fae73 |
fmt.Fprintf(b.OutStream, " ---> Running in %s\n", stringid.TruncateID(c.ID)) |
d6c0bbc3 |
|
767df67e |
if config.Cmd.Len() > 0 { |
39343b86 |
// override the entry point that may have been picked up from the base image |
767df67e |
s := config.Cmd.Slice()
c.Path = s[0]
c.Args = s[1:] |
39343b86 |
} else { |
767df67e |
config.Cmd = runconfig.NewCommand() |
39343b86 |
} |
d6c0bbc3 |
return c, nil
}
|
8c4a282a |
func (b *builder) run(c *daemon.Container) error { |
1095d5e5 |
var errCh chan error
if b.Verbose { |
c44f5132 |
errCh = c.Attach(nil, b.OutStream, b.ErrStream) |
1095d5e5 |
}
|
d6c0bbc3 |
//start the container
if err := c.Start(); err != nil {
return err
}
|
671c1220 |
finished := make(chan struct{})
defer close(finished)
go func() {
select {
case <-b.cancelled: |
6f4d8470 |
logrus.Debugln("Build cancelled, killing container:", c.ID) |
671c1220 |
c.Kill()
case <-finished:
}
}()
|
92c35358 |
if b.Verbose {
// Block on reading output from container, stop on err or chan closed
if err := <-errCh; err != nil {
return err
} |
d6c0bbc3 |
}
// Wait for it to finish |
e0339d4b |
if ret, _ := c.WaitStop(-1 * time.Second); ret != 0 { |
1c89c6ea |
return &jsonmessage.JSONError{ |
006c066b |
Message: fmt.Sprintf("The command '%s' returned a non-zero code: %d", b.Config.Cmd.ToString(), ret), |
d6c0bbc3 |
Code: ret,
}
}
return nil
}
|
8c4a282a |
func (b *builder) checkPathForAddition(orig string) error { |
010e3e04 |
origPath := filepath.Join(b.contextPath, orig) |
cb51681a |
origPath, err := filepath.EvalSymlinks(origPath)
if err != nil { |
d6c0bbc3 |
if os.IsNotExist(err) {
return fmt.Errorf("%s: no such file or directory", orig)
}
return err
} |
010e3e04 |
contextPath, err := filepath.EvalSymlinks(b.contextPath)
if err != nil {
return err
}
if !strings.HasPrefix(origPath, contextPath) { |
d6c0bbc3 |
return fmt.Errorf("Forbidden path outside the build context: %s (%s)", orig, origPath)
} |
cb51681a |
if _, err := os.Stat(origPath); err != nil { |
d6c0bbc3 |
if os.IsNotExist(err) {
return fmt.Errorf("%s: no such file or directory", orig)
}
return err
}
return nil
}
|
8c4a282a |
func (b *builder) addContext(container *daemon.Container, orig, dest string, decompress bool) error { |
d6c0bbc3 |
var (
err error
destExists = true |
010e3e04 |
origPath = filepath.Join(b.contextPath, orig) |
b7c3c0cb |
destPath string |
d6c0bbc3 |
)
|
2ceb1146 |
// Work in daemon-local OS specific file paths
dest = filepath.FromSlash(dest)
|
b7c3c0cb |
destPath, err = container.GetResourcePath(dest)
if err != nil {
return err |
d6c0bbc3 |
}
|
2ceb1146 |
// Preserve the trailing slash
if strings.HasSuffix(dest, string(os.PathSeparator)) || dest == "." {
destPath = destPath + string(os.PathSeparator) |
d6c0bbc3 |
}
destStat, err := os.Stat(destPath)
if err != nil {
if !os.IsNotExist(err) { |
2ceb1146 |
logrus.Errorf("Error performing os.Stat on %s. %s", destPath, err) |
d6c0bbc3 |
return err
}
destExists = false
}
fi, err := os.Stat(origPath)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("%s: no such file or directory", orig)
}
return err
}
if fi.IsDir() { |
916cba9c |
return copyAsDirectory(origPath, destPath, destExists) |
d6c0bbc3 |
}
// If we are adding a remote file (or we've been told not to decompress), do not try to untar it
if decompress {
// First try to unpack the source as an archive
// to support the untar feature we need to clean up the path a little bit
// because tar is very forgiving. First we need to strip off the archive's |
2ceb1146 |
// filename from the path but this is only added if it does not end in slash |
d6c0bbc3 |
tarDest := destPath |
2ceb1146 |
if strings.HasSuffix(tarDest, string(os.PathSeparator)) { |
d6c0bbc3 |
tarDest = filepath.Dir(destPath)
}
// try to successfully untar the orig |
1cb17f03 |
if err := chrootarchive.UntarPath(origPath, tarDest); err == nil { |
d6c0bbc3 |
return nil
} else if err != io.EOF { |
6f4d8470 |
logrus.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err) |
d6c0bbc3 |
}
}
|
010e3e04 |
if err := system.MkdirAll(filepath.Dir(destPath), 0755); err != nil { |
d6c0bbc3 |
return err
} |
1cb17f03 |
if err := chrootarchive.CopyWithTar(origPath, destPath); err != nil { |
d6c0bbc3 |
return err
}
resPath := destPath
if destExists && destStat.IsDir() { |
010e3e04 |
resPath = filepath.Join(destPath, filepath.Base(origPath)) |
d6c0bbc3 |
}
|
916cba9c |
return fixPermissions(origPath, resPath, 0, 0, destExists) |
d6c0bbc3 |
}
|
916cba9c |
func copyAsDirectory(source, destination string, destExisted bool) error { |
1cb17f03 |
if err := chrootarchive.CopyWithTar(source, destination); err != nil { |
d6c0bbc3 |
return err
} |
916cba9c |
return fixPermissions(source, destination, 0, 0, destExisted) |
d6c0bbc3 |
}
|
8c4a282a |
func (b *builder) clearTmp() { |
305f7350 |
for c := range b.TmpContainers { |
f8628ba8 |
rmConfig := &daemon.ContainerRmConfig{
ForceRemove: true,
RemoveVolume: true, |
d25a6537 |
} |
f8628ba8 |
if err := b.Daemon.ContainerRm(c, rmConfig); err != nil { |
b80fae73 |
fmt.Fprintf(b.OutStream, "Error removing intermediate container %s: %v\n", stringid.TruncateID(c), err) |
45407cf0 |
return |
d6c0bbc3 |
} |
45407cf0 |
delete(b.TmpContainers, c) |
b80fae73 |
fmt.Fprintf(b.OutStream, "Removing intermediate container %s\n", stringid.TruncateID(c)) |
d6c0bbc3 |
}
} |