Ejemplo n.º 1
0
// ENTRYPOINT /usr/sbin/nginx
//
// Set the entrypoint (which defaults to sh -c on linux, or cmd /S /C on Windows) to
// /usr/sbin/nginx. Will accept the CMD as the arguments to /usr/sbin/nginx.
//
// Handles command processing similar to CMD and RUN, only b.runConfig.Entrypoint
// is initialized at NewBuilder time instead of through argument parsing.
//
func entrypoint(b *Builder, args []string, attributes map[string]bool, original string) error {
	if err := b.flags.Parse(); err != nil {
		return err
	}

	parsed := handleJSONArgs(args, attributes)

	switch {
	case attributes["json"]:
		// ENTRYPOINT ["echo", "hi"]
		b.runConfig.Entrypoint = stringutils.NewStrSlice(parsed...)
	case len(parsed) == 0:
		// ENTRYPOINT []
		b.runConfig.Entrypoint = nil
	default:
		// ENTRYPOINT echo hi
		if runtime.GOOS != "windows" {
			b.runConfig.Entrypoint = stringutils.NewStrSlice("/bin/sh", "-c", parsed[0])
		} else {
			b.runConfig.Entrypoint = stringutils.NewStrSlice("cmd", "/S", "/C", parsed[0])
		}
	}

	// when setting the entrypoint if a CMD was not explicitly set then
	// set the command to nil
	if !b.cmdSet {
		b.runConfig.Cmd = nil
	}

	if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.runConfig.Entrypoint)); err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 2
0
func (b *Builder) commit(id string, autoCmd *stringutils.StrSlice, comment string) error {
	if b.disableCommit {
		return nil
	}
	if b.image == "" && !b.noBaseImage {
		return fmt.Errorf("Please provide a source image with `from` prior to commit")
	}
	b.runConfig.Image = b.image
	if id == "" {
		cmd := b.runConfig.Cmd
		if runtime.GOOS != "windows" {
			b.runConfig.Cmd = stringutils.NewStrSlice("/bin/sh", "-c", "#(nop) "+comment)
		} else {
			b.runConfig.Cmd = stringutils.NewStrSlice("cmd", "/S /C", "REM (nop) "+comment)
		}
		defer func(cmd *stringutils.StrSlice) { b.runConfig.Cmd = cmd }(cmd)

		if hit, err := b.probeCache(); err != nil {
			return err
		} else if hit {
			return nil
		}

		container, err := b.create()
		if err != nil {
			return err
		}
		id = container.ID

		if err := container.Mount(); err != nil {
			return err
		}
		defer container.Unmount()
	}

	container, err := b.docker.Container(id)
	if err != nil {
		return err
	}

	// Note: Actually copy the struct
	autoConfig := *b.runConfig
	autoConfig.Cmd = autoCmd

	commitCfg := &daemon.ContainerCommitConfig{
		Author: b.maintainer,
		Pause:  true,
		Config: &autoConfig,
	}

	// Commit the container
	image, err := b.docker.Commit(container, commitCfg)
	if err != nil {
		return err
	}
	b.docker.Retain(b.id, image.ID)
	b.activeImages = append(b.activeImages, image.ID)
	b.image = image.ID
	return nil
}
Ejemplo n.º 3
0
// ContainerExecCreate sets up an exec in a running container.
func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, error) {
	container, err := d.getActiveContainer(config.Container)
	if err != nil {
		return "", err
	}

	cmd := stringutils.NewStrSlice(config.Cmd...)
	entrypoint, args := d.getEntrypointAndArgs(stringutils.NewStrSlice(), cmd)

	processConfig := &execdriver.ProcessConfig{
		CommonProcessConfig: execdriver.CommonProcessConfig{
			Tty:        config.Tty,
			Entrypoint: entrypoint,
			Arguments:  args,
		},
	}
	setPlatformSpecificExecProcessConfig(config, container, processConfig)

	execConfig := exec.NewConfig()
	execConfig.OpenStdin = config.AttachStdin
	execConfig.OpenStdout = config.AttachStdout
	execConfig.OpenStderr = config.AttachStderr
	execConfig.ProcessConfig = processConfig
	execConfig.ContainerID = container.ID

	d.registerExecCommand(container, execConfig)

	d.LogContainerEvent(container, "exec_create: "+execConfig.ProcessConfig.Entrypoint+" "+strings.Join(execConfig.ProcessConfig.Arguments, " "))

	return execConfig.ID, nil
}
Ejemplo n.º 4
0
func (cli Docker) SendCmdCreate(name, image string, entrypoint, cmds []string, userConfig interface{}) ([]byte, int, error) {
	config := &runconfig.Config{
		Image: image,
		Cmd:   stringutils.NewStrSlice(cmds...),
	}

	if len(entrypoint) != 0 {
		config.Entrypoint = stringutils.NewStrSlice(entrypoint...)
	}

	if userConfig != nil {
		config = userConfig.(*runconfig.Config)
	}
	hostConfig := &runconfig.HostConfig{}
	containerResp, err := cli.daemon.ContainerCreate(&daemon.ContainerCreateConfig{
		Name:            name,
		Config:          config,
		HostConfig:      hostConfig,
		AdjustCPUShares: false,
	})
	if err != nil {
		return nil, 500, err
	}
	return []byte(containerResp.ID), 200, nil
}
Ejemplo n.º 5
0
func TestDecodeContainerConfig(t *testing.T) {
	fixtures := []struct {
		file       string
		entrypoint *stringutils.StrSlice
	}{
		{"fixtures/container_config_1_14.json", stringutils.NewStrSlice()},
		{"fixtures/container_config_1_17.json", stringutils.NewStrSlice("bash")},
		{"fixtures/container_config_1_19.json", stringutils.NewStrSlice("bash")},
	}

	for _, f := range fixtures {
		b, err := ioutil.ReadFile(f.file)
		if err != nil {
			t.Fatal(err)
		}

		c, h, err := DecodeContainerConfig(bytes.NewReader(b))
		if err != nil {
			t.Fatal(fmt.Errorf("Error parsing %s: %v", f, err))
		}

		if c.Image != "ubuntu" {
			t.Fatalf("Expected ubuntu image, found %s\n", c.Image)
		}

		if c.Entrypoint.Len() != f.entrypoint.Len() {
			t.Fatalf("Expected %v, found %v\n", f.entrypoint, c.Entrypoint)
		}

		if h.Memory != 1000 {
			t.Fatalf("Expected memory to be 1000, found %d\n", h.Memory)
		}
	}
}
Ejemplo n.º 6
0
Archivo: exec.go Proyecto: m1911/hyper
// ContainerExecCreate sets up an exec in a running container.
func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, error) {
	container, err := d.getActiveContainer(config.Container)
	if err != nil {
		return "", err
	}

	cmd := stringutils.NewStrSlice(config.Cmd...)
	entrypoint, args := d.getEntrypointAndArgs(stringutils.NewStrSlice(), cmd)

	processConfig := &execdriver.ProcessConfig{
		CommonProcessConfig: execdriver.CommonProcessConfig{
			Tty:        config.Tty,
			Entrypoint: entrypoint,
			Arguments:  args,
		},
	}
	setPlatformSpecificExecProcessConfig(config, container, processConfig)

	ExecConfig := &ExecConfig{
		ID:            stringid.GenerateNonCryptoID(),
		OpenStdin:     config.AttachStdin,
		OpenStdout:    config.AttachStdout,
		OpenStderr:    config.AttachStderr,
		streamConfig:  streamConfig{},
		ProcessConfig: processConfig,
		Container:     container,
		Running:       false,
		waitStart:     make(chan struct{}),
	}

	d.registerExecCommand(ExecConfig)

	return ExecConfig.ID, nil
}
Ejemplo n.º 7
0
// CMD foo
//
// Set the default command to run in the container (which may be empty).
// Argument handling is the same as RUN.
//
func cmd(b *Builder, args []string, attributes map[string]bool, original string) error {
	if err := b.flags.Parse(); err != nil {
		return err
	}

	cmdSlice := handleJSONArgs(args, attributes)

	if !attributes["json"] {
		if runtime.GOOS != "windows" {
			cmdSlice = append([]string{"/bin/sh", "-c"}, cmdSlice...)
		} else {
			cmdSlice = append([]string{"cmd", "/S", "/C"}, cmdSlice...)
		}
	}

	b.runConfig.Cmd = stringutils.NewStrSlice(cmdSlice...)

	if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
		return err
	}

	if len(args) != 0 {
		b.cmdSet = true
	}

	return nil
}
Ejemplo n.º 8
0
// ContainerExecCreate sets up an exec in a running container.
func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, error) {
	// Not all drivers support Exec (LXC for example)
	if err := checkExecSupport(d.execDriver.Name()); err != nil {
		return "", err
	}

	container, err := d.getActiveContainer(config.Container)
	if err != nil {
		return "", err
	}

	cmd := stringutils.NewStrSlice(config.Cmd...)
	entrypoint, args := d.getEntrypointAndArgs(stringutils.NewStrSlice(), cmd)

	user := config.User
	if len(user) == 0 {
		user = container.Config.User
	}

	processConfig := &execdriver.ProcessConfig{
		Tty:        config.Tty,
		Entrypoint: entrypoint,
		Arguments:  args,
		User:       user,
		Privileged: config.Privileged,
	}

	ExecConfig := &ExecConfig{
		ID:            stringid.GenerateNonCryptoID(),
		OpenStdin:     config.AttachStdin,
		OpenStdout:    config.AttachStdout,
		OpenStderr:    config.AttachStderr,
		streamConfig:  streamConfig{},
		ProcessConfig: processConfig,
		Container:     container,
		Running:       false,
		waitStart:     make(chan struct{}),
	}

	d.registerExecCommand(ExecConfig)

	container.logEvent("exec_create: " + ExecConfig.ProcessConfig.Entrypoint + " " + strings.Join(ExecConfig.ProcessConfig.Arguments, " "))

	return ExecConfig.ID, nil
}
Ejemplo n.º 9
0
func TestDecodeContainerConfig(t *testing.T) {

	var (
		fixtures []f
		image    string
	)

	if runtime.GOOS != "windows" {
		image = "ubuntu"
		fixtures = []f{
			{"fixtures/unix/container_config_1_14.json", stringutils.NewStrSlice()},
			{"fixtures/unix/container_config_1_17.json", stringutils.NewStrSlice("bash")},
			{"fixtures/unix/container_config_1_19.json", stringutils.NewStrSlice("bash")},
		}
	} else {
		image = "windows"
		fixtures = []f{
			{"fixtures/windows/container_config_1_19.json", stringutils.NewStrSlice("cmd")},
		}
	}

	for _, f := range fixtures {
		b, err := ioutil.ReadFile(f.file)
		if err != nil {
			t.Fatal(err)
		}

		c, h, err := DecodeContainerConfig(bytes.NewReader(b))
		if err != nil {
			t.Fatal(fmt.Errorf("Error parsing %s: %v", f, err))
		}

		if c.Image != image {
			t.Fatalf("Expected %s image, found %s\n", image, c.Image)
		}

		if c.Entrypoint.Len() != f.entrypoint.Len() {
			t.Fatalf("Expected %v, found %v\n", f.entrypoint, c.Entrypoint)
		}

		if h != nil && h.Memory != 1000 {
			t.Fatalf("Expected memory to be 1000, found %d\n", h.Memory)
		}
	}
}
Ejemplo n.º 10
0
func (b *builder) create() (*daemon.Container, error) {
	if b.image == "" && !b.noBaseImage {
		return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
	}
	b.Config.Image = b.image

	hostConfig := &runconfig.HostConfig{
		CPUShares:    b.cpuShares,
		CPUPeriod:    b.cpuPeriod,
		CPUQuota:     b.cpuQuota,
		CpusetCpus:   b.cpuSetCpus,
		CpusetMems:   b.cpuSetMems,
		CgroupParent: b.cgroupParent,
		Memory:       b.memory,
		MemorySwap:   b.memorySwap,
		Ulimits:      b.ulimits,
	}

	config := *b.Config

	// Create the container
	ccr, err := b.Daemon.ContainerCreate("", b.Config, hostConfig, true)
	if err != nil {
		return nil, err
	}
	for _, warning := range ccr.Warnings {
		fmt.Fprintf(b.OutStream, " ---> [Warning] %s\n", warning)
	}
	c, err := b.Daemon.Get(ccr.ID)
	if err != nil {
		return nil, err
	}

	b.TmpContainers[c.ID] = struct{}{}
	fmt.Fprintf(b.OutStream, " ---> Running in %s\n", stringid.TruncateID(c.ID))

	if config.Cmd.Len() > 0 {
		// override the entry point that may have been picked up from the base image
		s := config.Cmd.Slice()
		c.Path = s[0]
		c.Args = s[1:]
	} else {
		config.Cmd = stringutils.NewStrSlice()
	}

	return c, nil
}
Ejemplo n.º 11
0
// Parse parses the specified args for the specified command and generates a Config,
// a HostConfig and returns them with the specified command.
// If the specified args are not valid, it will return an error.
func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSet, error) {
	var (
		// FIXME: use utils.ListOpts for attach and volumes?
		flAttach            = opts.NewListOpts(opts.ValidateAttach)
		flVolumes           = opts.NewListOpts(nil)
		flBlkioWeightDevice = opts.NewWeightdeviceOpt(opts.ValidateWeightDevice)
		flLinks             = opts.NewListOpts(opts.ValidateLink)
		flEnv               = opts.NewListOpts(opts.ValidateEnv)
		flLabels            = opts.NewListOpts(opts.ValidateEnv)
		flDevices           = opts.NewListOpts(opts.ValidateDevice)

		flUlimits = opts.NewUlimitOpt(nil)

		flPublish           = opts.NewListOpts(nil)
		flExpose            = opts.NewListOpts(nil)
		flDNS               = opts.NewListOpts(opts.ValidateIPAddress)
		flDNSSearch         = opts.NewListOpts(opts.ValidateDNSSearch)
		flDNSOptions        = opts.NewListOpts(nil)
		flExtraHosts        = opts.NewListOpts(opts.ValidateExtraHost)
		flVolumesFrom       = opts.NewListOpts(nil)
		flEnvFile           = opts.NewListOpts(nil)
		flCapAdd            = opts.NewListOpts(nil)
		flCapDrop           = opts.NewListOpts(nil)
		flGroupAdd          = opts.NewListOpts(nil)
		flSecurityOpt       = opts.NewListOpts(nil)
		flLabelsFile        = opts.NewListOpts(nil)
		flLoggingOpts       = opts.NewListOpts(nil)
		flPrivileged        = cmd.Bool([]string{"-privileged"}, false, "Give extended privileges to this container")
		flPidMode           = cmd.String([]string{"-pid"}, "", "PID namespace to use")
		flUTSMode           = cmd.String([]string{"-uts"}, "", "UTS namespace to use")
		flPublishAll        = cmd.Bool([]string{"P", "-publish-all"}, false, "Publish all exposed ports to random ports")
		flStdin             = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached")
		flTty               = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY")
		flOomKillDisable    = cmd.Bool([]string{"-oom-kill-disable"}, false, "Disable OOM Killer")
		flContainerIDFile   = cmd.String([]string{"-cidfile"}, "", "Write the container ID to the file")
		flEntrypoint        = cmd.String([]string{"-entrypoint"}, "", "Overwrite the default ENTRYPOINT of the image")
		flHostname          = cmd.String([]string{"h", "-hostname"}, "", "Container host name")
		flMemoryString      = cmd.String([]string{"m", "-memory"}, "", "Memory limit")
		flMemoryReservation = cmd.String([]string{"-memory-reservation"}, "", "Memory soft limit")
		flMemorySwap        = cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap")
		flKernelMemory      = cmd.String([]string{"-kernel-memory"}, "", "Kernel memory limit")
		flUser              = cmd.String([]string{"u", "-user"}, "", "Username or UID (format: <name|uid>[:<group|gid>])")
		flWorkingDir        = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container")
		flCPUShares         = cmd.Int64([]string{"#c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
		flCPUPeriod         = cmd.Int64([]string{"-cpu-period"}, 0, "Limit CPU CFS (Completely Fair Scheduler) period")
		flCPUQuota          = cmd.Int64([]string{"-cpu-quota"}, 0, "Limit CPU CFS (Completely Fair Scheduler) quota")
		flCpusetCpus        = cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
		flCpusetMems        = cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
		flBlkioWeight       = cmd.Uint16([]string{"-blkio-weight"}, 0, "Block IO (relative weight), between 10 and 1000")
		flSwappiness        = cmd.Int64([]string{"-memory-swappiness"}, -1, "Tuning container memory swappiness (0 to 100)")
		flNetMode           = cmd.String([]string{"-net"}, "default", "Set the Network for the container")
		flMacAddress        = cmd.String([]string{"-mac-address"}, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)")
		flIpcMode           = cmd.String([]string{"-ipc"}, "", "IPC namespace to use")
		flRestartPolicy     = cmd.String([]string{"-restart"}, "no", "Restart policy to apply when a container exits")
		flReadonlyRootfs    = cmd.Bool([]string{"-read-only"}, false, "Mount the container's root filesystem as read only")
		flLoggingDriver     = cmd.String([]string{"-log-driver"}, "", "Logging driver for container")
		flCgroupParent      = cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
		flVolumeDriver      = cmd.String([]string{"-volume-driver"}, "", "Optional volume driver for the container")
		flStopSignal        = cmd.String([]string{"-stop-signal"}, signal.DefaultStopSignal, fmt.Sprintf("Signal to stop a container, %v by default", signal.DefaultStopSignal))
		flIsolation         = cmd.String([]string{"-isolation"}, "", "Container isolation level")
		flShmSize           = cmd.String([]string{"-shm-size"}, "", "Size of /dev/shm, default value is 64MB")
	)

	cmd.Var(&flAttach, []string{"a", "-attach"}, "Attach to STDIN, STDOUT or STDERR")
	cmd.Var(&flBlkioWeightDevice, []string{"-blkio-weight-device"}, "Block IO weight (relative device weight)")
	cmd.Var(&flVolumes, []string{"v", "-volume"}, "Bind mount a volume")
	cmd.Var(&flLinks, []string{"-link"}, "Add link to another container")
	cmd.Var(&flDevices, []string{"-device"}, "Add a host device to the container")
	cmd.Var(&flLabels, []string{"l", "-label"}, "Set meta data on a container")
	cmd.Var(&flLabelsFile, []string{"-label-file"}, "Read in a line delimited file of labels")
	cmd.Var(&flEnv, []string{"e", "-env"}, "Set environment variables")
	cmd.Var(&flEnvFile, []string{"-env-file"}, "Read in a file of environment variables")
	cmd.Var(&flPublish, []string{"p", "-publish"}, "Publish a container's port(s) to the host")
	cmd.Var(&flExpose, []string{"-expose"}, "Expose a port or a range of ports")
	cmd.Var(&flDNS, []string{"-dns"}, "Set custom DNS servers")
	cmd.Var(&flDNSSearch, []string{"-dns-search"}, "Set custom DNS search domains")
	cmd.Var(&flDNSOptions, []string{"-dns-opt"}, "Set DNS options")
	cmd.Var(&flExtraHosts, []string{"-add-host"}, "Add a custom host-to-IP mapping (host:ip)")
	cmd.Var(&flVolumesFrom, []string{"-volumes-from"}, "Mount volumes from the specified container(s)")
	cmd.Var(&flCapAdd, []string{"-cap-add"}, "Add Linux capabilities")
	cmd.Var(&flCapDrop, []string{"-cap-drop"}, "Drop Linux capabilities")
	cmd.Var(&flGroupAdd, []string{"-group-add"}, "Add additional groups to join")
	cmd.Var(&flSecurityOpt, []string{"-security-opt"}, "Security Options")
	cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
	cmd.Var(&flLoggingOpts, []string{"-log-opt"}, "Log driver options")

	cmd.Require(flag.Min, 1)

	if err := cmd.ParseFlags(args, true); err != nil {
		return nil, nil, cmd, err
	}

	var (
		attachStdin  = flAttach.Get("stdin")
		attachStdout = flAttach.Get("stdout")
		attachStderr = flAttach.Get("stderr")
	)

	// Validate the input mac address
	if *flMacAddress != "" {
		if _, err := opts.ValidateMACAddress(*flMacAddress); err != nil {
			return nil, nil, cmd, fmt.Errorf("%s is not a valid mac address", *flMacAddress)
		}
	}
	if *flStdin {
		attachStdin = true
	}
	// If -a is not set attach to the output stdio
	if flAttach.Len() == 0 {
		attachStdout = true
		attachStderr = true
	}

	var err error

	var flMemory int64
	if *flMemoryString != "" {
		flMemory, err = units.RAMInBytes(*flMemoryString)
		if err != nil {
			return nil, nil, cmd, err
		}
	}

	var MemoryReservation int64
	if *flMemoryReservation != "" {
		MemoryReservation, err = units.RAMInBytes(*flMemoryReservation)
		if err != nil {
			return nil, nil, cmd, err
		}
	}

	var memorySwap int64
	if *flMemorySwap != "" {
		if *flMemorySwap == "-1" {
			memorySwap = -1
		} else {
			memorySwap, err = units.RAMInBytes(*flMemorySwap)
			if err != nil {
				return nil, nil, cmd, err
			}
		}
	}

	var KernelMemory int64
	if *flKernelMemory != "" {
		KernelMemory, err = units.RAMInBytes(*flKernelMemory)
		if err != nil {
			return nil, nil, cmd, err
		}
	}

	swappiness := *flSwappiness
	if swappiness != -1 && (swappiness < 0 || swappiness > 100) {
		return nil, nil, cmd, fmt.Errorf("Invalid value: %d. Valid memory swappiness range is 0-100", swappiness)
	}

	var parsedShm *int64
	if *flShmSize != "" {
		shmSize, err := units.RAMInBytes(*flShmSize)
		if err != nil {
			return nil, nil, cmd, err
		}
		parsedShm = &shmSize
	}

	var binds []string
	// add any bind targets to the list of container volumes
	for bind := range flVolumes.GetMap() {
		if arr := volume.SplitN(bind, 2); len(arr) > 1 {
			// after creating the bind mount we want to delete it from the flVolumes values because
			// we do not want bind mounts being committed to image configs
			binds = append(binds, bind)
			flVolumes.Delete(bind)
		}
	}

	var (
		parsedArgs = cmd.Args()
		runCmd     *stringutils.StrSlice
		entrypoint *stringutils.StrSlice
		image      = cmd.Arg(0)
	)
	if len(parsedArgs) > 1 {
		runCmd = stringutils.NewStrSlice(parsedArgs[1:]...)
	}
	if *flEntrypoint != "" {
		entrypoint = stringutils.NewStrSlice(*flEntrypoint)
	}

	var (
		domainname string
		hostname   = *flHostname
		parts      = strings.SplitN(hostname, ".", 2)
	)
	if len(parts) > 1 {
		hostname = parts[0]
		domainname = parts[1]
	}

	ports, portBindings, err := nat.ParsePortSpecs(flPublish.GetAll())
	if err != nil {
		return nil, nil, cmd, err
	}

	// Merge in exposed ports to the map of published ports
	for _, e := range flExpose.GetAll() {
		if strings.Contains(e, ":") {
			return nil, nil, cmd, fmt.Errorf("Invalid port format for --expose: %s", e)
		}
		//support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
		proto, port := nat.SplitProtoPort(e)
		//parse the start and end port and create a sequence of ports to expose
		//if expose a port, the start and end port are the same
		start, end, err := parsers.ParsePortRange(port)
		if err != nil {
			return nil, nil, cmd, fmt.Errorf("Invalid range format for --expose: %s, error: %s", e, err)
		}
		for i := start; i <= end; i++ {
			p, err := nat.NewPort(proto, strconv.FormatUint(i, 10))
			if err != nil {
				return nil, nil, cmd, err
			}
			if _, exists := ports[p]; !exists {
				ports[p] = struct{}{}
			}
		}
	}

	// parse device mappings
	deviceMappings := []DeviceMapping{}
	for _, device := range flDevices.GetAll() {
		deviceMapping, err := ParseDevice(device)
		if err != nil {
			return nil, nil, cmd, err
		}
		deviceMappings = append(deviceMappings, deviceMapping)
	}

	// collect all the environment variables for the container
	envVariables, err := readKVStrings(flEnvFile.GetAll(), flEnv.GetAll())
	if err != nil {
		return nil, nil, cmd, err
	}

	// collect all the labels for the container
	labels, err := readKVStrings(flLabelsFile.GetAll(), flLabels.GetAll())
	if err != nil {
		return nil, nil, cmd, err
	}

	ipcMode := IpcMode(*flIpcMode)
	if !ipcMode.Valid() {
		return nil, nil, cmd, fmt.Errorf("--ipc: invalid IPC mode")
	}

	pidMode := PidMode(*flPidMode)
	if !pidMode.Valid() {
		return nil, nil, cmd, fmt.Errorf("--pid: invalid PID mode")
	}

	utsMode := UTSMode(*flUTSMode)
	if !utsMode.Valid() {
		return nil, nil, cmd, fmt.Errorf("--uts: invalid UTS mode")
	}

	restartPolicy, err := ParseRestartPolicy(*flRestartPolicy)
	if err != nil {
		return nil, nil, cmd, err
	}

	loggingOpts, err := parseLoggingOpts(*flLoggingDriver, flLoggingOpts.GetAll())
	if err != nil {
		return nil, nil, cmd, err
	}

	resources := Resources{
		CgroupParent:      *flCgroupParent,
		Memory:            flMemory,
		MemoryReservation: MemoryReservation,
		MemorySwap:        memorySwap,
		MemorySwappiness:  flSwappiness,
		KernelMemory:      KernelMemory,
		CPUShares:         *flCPUShares,
		CPUPeriod:         *flCPUPeriod,
		CpusetCpus:        *flCpusetCpus,
		CpusetMems:        *flCpusetMems,
		CPUQuota:          *flCPUQuota,
		BlkioWeight:       *flBlkioWeight,
		BlkioWeightDevice: flBlkioWeightDevice.GetList(),
		Ulimits:           flUlimits.GetList(),
		Devices:           deviceMappings,
	}

	config := &Config{
		Hostname:     hostname,
		Domainname:   domainname,
		ExposedPorts: ports,
		User:         *flUser,
		Tty:          *flTty,
		// TODO: deprecated, it comes from -n, --networking
		// it's still needed internally to set the network to disabled
		// if e.g. bridge is none in daemon opts, and in inspect
		NetworkDisabled: false,
		OpenStdin:       *flStdin,
		AttachStdin:     attachStdin,
		AttachStdout:    attachStdout,
		AttachStderr:    attachStderr,
		Env:             envVariables,
		Cmd:             runCmd,
		Image:           image,
		Volumes:         flVolumes.GetMap(),
		MacAddress:      *flMacAddress,
		Entrypoint:      entrypoint,
		WorkingDir:      *flWorkingDir,
		Labels:          ConvertKVStringsToMap(labels),
		StopSignal:      *flStopSignal,
	}

	hostConfig := &HostConfig{
		Binds:           binds,
		ContainerIDFile: *flContainerIDFile,
		OomKillDisable:  *flOomKillDisable,
		Privileged:      *flPrivileged,
		PortBindings:    portBindings,
		Links:           flLinks.GetAll(),
		PublishAllPorts: *flPublishAll,
		// Make sure the dns fields are never nil.
		// New containers don't ever have those fields nil,
		// but pre created containers can still have those nil values.
		// See https://github.com/docker/docker/pull/17779
		// for a more detailed explanation on why we don't want that.
		DNS:            flDNS.GetAllOrEmpty(),
		DNSSearch:      flDNSSearch.GetAllOrEmpty(),
		DNSOptions:     flDNSOptions.GetAllOrEmpty(),
		ExtraHosts:     flExtraHosts.GetAll(),
		VolumesFrom:    flVolumesFrom.GetAll(),
		NetworkMode:    NetworkMode(*flNetMode),
		IpcMode:        ipcMode,
		PidMode:        pidMode,
		UTSMode:        utsMode,
		CapAdd:         stringutils.NewStrSlice(flCapAdd.GetAll()...),
		CapDrop:        stringutils.NewStrSlice(flCapDrop.GetAll()...),
		GroupAdd:       flGroupAdd.GetAll(),
		RestartPolicy:  restartPolicy,
		SecurityOpt:    flSecurityOpt.GetAll(),
		ReadonlyRootfs: *flReadonlyRootfs,
		LogConfig:      LogConfig{Type: *flLoggingDriver, Config: loggingOpts},
		VolumeDriver:   *flVolumeDriver,
		Isolation:      IsolationLevel(*flIsolation),
		ShmSize:        parsedShm,
		Resources:      resources,
	}

	// When allocating stdin in attached mode, close stdin at client disconnect
	if config.OpenStdin && config.AttachStdin {
		config.StdinOnce = true
	}
	return config, hostConfig, cmd, nil
}
Ejemplo n.º 12
0
func (b *builder) runContextCommand(args []string, allowRemote bool, allowDecompression bool, cmdName string) error {
	if b.context == nil {
		return fmt.Errorf("No context given. Impossible to use %s", cmdName)
	}

	if len(args) < 2 {
		return fmt.Errorf("Invalid %s format - at least two arguments required", cmdName)
	}

	// Work in daemon-specific filepath semantics
	dest := filepath.FromSlash(args[len(args)-1]) // last one is always the dest

	copyInfos := []*copyInfo{}

	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
	for _, orig := range args[0 : len(args)-1] {
		if err := calcCopyInfo(
			b,
			cmdName,
			&copyInfos,
			orig,
			dest,
			allowRemote,
			allowDecompression,
			true,
		); err != nil {
			return err
		}
	}

	if len(copyInfos) == 0 {
		return fmt.Errorf("No source files were specified")
	}
	if len(copyInfos) > 1 && !strings.HasSuffix(dest, string(os.PathSeparator)) {
		return fmt.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName)
	}

	// 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)
		}
		hasher := sha256.New()
		hasher.Write([]byte(strings.Join(hashs, ",")))
		srcHash = "multi:" + hex.EncodeToString(hasher.Sum(nil))
		origPaths = strings.Join(origs, " ")
	}

	cmd := b.Config.Cmd
	if runtime.GOOS != "windows" {
		b.Config.Cmd = stringutils.NewStrSlice("/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest))
	} else {
		b.Config.Cmd = stringutils.NewStrSlice("cmd", "/S /C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest))
	}
	defer func(cmd *stringutils.StrSlice) { b.Config.Cmd = cmd }(cmd)

	hit, err := b.probeCache()
	if err != nil {
		return err
	}

	if hit {
		return nil
	}

	container, _, err := b.Daemon.ContainerCreate("", b.Config, nil, true)
	if err != nil {
		return err
	}
	b.TmpContainers[container.ID] = struct{}{}

	if err := container.Mount(); err != nil {
		return err
	}
	defer container.Unmount()

	for _, ci := range copyInfos {
		if err := b.addContext(container, ci.origPath, ci.destPath, ci.decompress); err != nil {
			return err
		}
	}

	if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 13
0
func (b *Builder) runContextCommand(args []string, allowRemote bool, allowLocalDecompression bool, cmdName string) error {
	if b.context == nil {
		return fmt.Errorf("No context given. Impossible to use %s", cmdName)
	}

	if len(args) < 2 {
		return fmt.Errorf("Invalid %s format - at least two arguments required", cmdName)
	}

	// Work in daemon-specific filepath semantics
	dest := filepath.FromSlash(args[len(args)-1]) // last one is always the dest

	b.runConfig.Image = b.image

	var infos []copyInfo

	// 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
	var err error
	for _, orig := range args[0 : len(args)-1] {
		var fi builder.FileInfo
		decompress := allowLocalDecompression
		if urlutil.IsURL(orig) {
			if !allowRemote {
				return fmt.Errorf("Source can't be a URL for %s", cmdName)
			}
			fi, err = b.download(orig)
			if err != nil {
				return err
			}
			defer os.RemoveAll(filepath.Dir(fi.Path()))
			decompress = false
			infos = append(infos, copyInfo{fi, decompress})
			continue
		}
		// not a URL
		subInfos, err := b.calcCopyInfo(cmdName, orig, allowLocalDecompression, true)
		if err != nil {
			return err
		}

		infos = append(infos, subInfos...)
	}

	if len(infos) == 0 {
		return fmt.Errorf("No source files were specified")
	}
	if len(infos) > 1 && !strings.HasSuffix(dest, string(os.PathSeparator)) {
		return fmt.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName)
	}

	// For backwards compat, if there's just one info then use it as the
	// cache look-up string, otherwise hash 'em all into one
	var srcHash string
	var origPaths string

	if len(infos) == 1 {
		fi := infos[0].FileInfo
		origPaths = fi.Name()
		if hfi, ok := fi.(builder.Hashed); ok {
			srcHash = hfi.Hash()
		}
	} else {
		var hashs []string
		var origs []string
		for _, info := range infos {
			fi := info.FileInfo
			origs = append(origs, fi.Name())
			if hfi, ok := fi.(builder.Hashed); ok {
				hashs = append(hashs, hfi.Hash())
			}
		}
		hasher := sha256.New()
		hasher.Write([]byte(strings.Join(hashs, ",")))
		srcHash = "multi:" + hex.EncodeToString(hasher.Sum(nil))
		origPaths = strings.Join(origs, " ")
	}

	cmd := b.runConfig.Cmd
	if runtime.GOOS != "windows" {
		b.runConfig.Cmd = stringutils.NewStrSlice("/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest))
	} else {
		b.runConfig.Cmd = stringutils.NewStrSlice("cmd", "/S", "/C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest))
	}
	defer func(cmd *stringutils.StrSlice) { b.runConfig.Cmd = cmd }(cmd)

	if hit, err := b.probeCache(); err != nil {
		return err
	} else if hit {
		return nil
	}

	// Create the Pod
	podId := fmt.Sprintf("buildpod-%s", utils.RandStr(10, "alpha"))
	tempSrcDir := fmt.Sprintf("/var/run/hyper/temp/%s/", podId)
	if err := os.MkdirAll(tempSrcDir, 0755); err != nil {
		glog.Errorf(err.Error())
		return err
	}
	if _, err := os.Stat(tempSrcDir); err != nil {
		glog.Errorf(err.Error())
		return err
	}
	shellDir := fmt.Sprintf("/var/run/hyper/shell/%s/", podId)
	if err := os.MkdirAll(shellDir, 0755); err != nil {
		glog.Errorf(err.Error())
		return err
	}
	copyshell, err1 := os.Create(shellDir + "/exec-copy.sh")
	if err1 != nil {
		glog.Errorf(err1.Error())
		return err1
	}
	fmt.Fprintf(copyshell, "#!/bin/sh\n")

	podString, err := MakeCopyPod(podId, b.image, b.runConfig.WorkingDir, tempSrcDir, dest, shellDir)
	if err != nil {
		return err
	}
	err = b.Hyperdaemon.CreatePod(podId, podString, false)
	if err != nil {
		return err
	}
	// Get the container
	var (
		containerId string = ""
		container   *daemon.Container
	)

	ps, ok := b.Hyperdaemon.PodList.GetStatus(podId)
	if !ok {
		return fmt.Errorf("Cannot find pod %s", podId)
	}
	for _, i := range ps.Containers {
		containerId = i.Id
	}
	container, err = b.Daemon.Get(containerId)
	if err != nil {
		glog.Error(err.Error())
		return err
	}

	/*
		container, _, err := b.docker.Create(b.runConfig, nil)
		if err != nil {
			return err
		}
		defer b.docker.Unmount(container)
	*/
	b.tmpPods[podId] = struct{}{}
	b.tmpContainers[container.ID] = struct{}{}

	comment := fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)

	// Twiddle the destination when its a relative path - meaning, make it
	// relative to the WORKINGDIR
	if !system.IsAbs(dest) {
		hasSlash := strings.HasSuffix(dest, string(os.PathSeparator))
		dest = filepath.Join(string(os.PathSeparator), filepath.FromSlash(b.runConfig.WorkingDir), dest)

		// Make sure we preserve any trailing slash
		if hasSlash {
			dest += string(os.PathSeparator)
		}
	}

	for _, info := range infos {
		if err := b.docker.Copy(container, tempSrcDir, info.FileInfo, info.decompress); err != nil {
			return err
		}
		if strings.HasSuffix(dest, string(os.PathSeparator)) == true {
			fmt.Fprintf(copyshell, fmt.Sprintf("cp /tmp/src/%s %s\n", info.FileInfo.Name(), filepath.Join(dest, info.FileInfo.Name())))
		} else {
			fmt.Fprintf(copyshell, fmt.Sprintf("cp /tmp/src/%s %s\n", info.FileInfo.Name(), dest))
		}
	}

	fmt.Fprintf(copyshell, "umount /tmp/src/\n")
	fmt.Fprintf(copyshell, "umount /tmp/shell/\n")
	fmt.Fprintf(copyshell, "rm -rf /tmp/shell/\n")
	fmt.Fprintf(copyshell, "rm -rf /tmp/src/\n")
	copyshell.Close()
	// start or replace pod
	vm, ok := b.Hyperdaemon.VmList[b.Name]
	if !ok {
		glog.Warningf("can not find VM(%s)", b.Name)

		bo := &hypervisor.BootConfig{
			CPU:    1,
			Memory: 512,
			Kernel: b.Hyperdaemon.Kernel,
			Initrd: b.Hyperdaemon.Initrd,
			Bios:   b.Hyperdaemon.Bios,
			Cbfs:   b.Hyperdaemon.Cbfs,
			Vbox:   b.Hyperdaemon.VboxImage,
		}

		vm = b.Hyperdaemon.NewVm(b.Name, 1, 512, false, types.VM_KEEP_AFTER_FINISH)

		err = vm.Launch(bo)
		if err != nil {
			return err
		}

		b.Hyperdaemon.AddVm(vm)
	}
	if vm.Status == types.S_VM_IDLE {
		code, cause, err := b.Hyperdaemon.StartPod(podId, "", b.Name, nil, false, false, types.VM_KEEP_AFTER_FINISH, []*hypervisor.TtyIO{})
		if err != nil {
			glog.Errorf("Code is %d, Cause is %s, %s", code, cause, err.Error())
			b.Hyperdaemon.KillVm(b.Name)
			return err
		}
		vm = b.Hyperdaemon.VmList[b.Name]
		// wait for cmd finish
		Status, err := vm.GetResponseChan()
		if err != nil {
			glog.Error(err.Error())
			return err
		}
		defer vm.ReleaseResponseChan(Status)

		var vmResponse *types.VmResponse
		for {
			vmResponse = <-Status
			if vmResponse.VmId == b.Name {
				if vmResponse.Code == types.E_POD_FINISHED {
					glog.Infof("Got E_POD_FINISHED code response")
					break
				}
			}
		}

		pod, ok := b.Hyperdaemon.PodList.Get(podId)
		if !ok {
			return fmt.Errorf("Cannot find pod %s", podId)
		}
		pod.SetVM(b.Name, vm)

		// release pod from VM
		glog.Warningf("start stop pod")
		code, cause, err = b.Hyperdaemon.StopPod(podId, "no")
		if err != nil {
			glog.Errorf("Code is %d, Cause is %s, %s", code, cause, err.Error())
			b.Hyperdaemon.KillVm(b.Name)
			return err
		}
		glog.Warningf("stop pod finish")
	} else {
		glog.Errorf("Vm is not IDLE")
		return fmt.Errorf("Vm is not IDLE")
	}

	if err := b.commit(container.ID, cmd, comment); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 14
0
func (b *Builder) runContextCommand(args []string, allowRemote bool, allowLocalDecompression bool, cmdName string) error {
	if b.context == nil {
		return fmt.Errorf("No context given. Impossible to use %s", cmdName)
	}

	if len(args) < 2 {
		return fmt.Errorf("Invalid %s format - at least two arguments required", cmdName)
	}

	// Work in daemon-specific filepath semantics
	dest := filepath.FromSlash(args[len(args)-1]) // last one is always the dest

	b.runConfig.Image = b.image

	var infos []copyInfo

	// 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
	var err error
	for _, orig := range args[0 : len(args)-1] {
		var fi builder.FileInfo
		decompress := allowLocalDecompression
		if urlutil.IsURL(orig) {
			if !allowRemote {
				return fmt.Errorf("Source can't be a URL for %s", cmdName)
			}
			fi, err = b.download(orig)
			if err != nil {
				return err
			}
			defer os.RemoveAll(filepath.Dir(fi.Path()))
			decompress = false
			infos = append(infos, copyInfo{fi, decompress})
			continue
		}
		// not a URL
		subInfos, err := b.calcCopyInfo(cmdName, orig, allowLocalDecompression, true)
		if err != nil {
			return err
		}

		infos = append(infos, subInfos...)
	}

	if len(infos) == 0 {
		return fmt.Errorf("No source files were specified")
	}
	if len(infos) > 1 && !strings.HasSuffix(dest, string(os.PathSeparator)) {
		return fmt.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName)
	}

	// For backwards compat, if there's just one info then use it as the
	// cache look-up string, otherwise hash 'em all into one
	var srcHash string
	var origPaths string

	if len(infos) == 1 {
		fi := infos[0].FileInfo
		origPaths = fi.Name()
		if hfi, ok := fi.(builder.Hashed); ok {
			srcHash = hfi.Hash()
		}
	} else {
		var hashs []string
		var origs []string
		for _, info := range infos {
			fi := info.FileInfo
			origs = append(origs, fi.Name())
			if hfi, ok := fi.(builder.Hashed); ok {
				hashs = append(hashs, hfi.Hash())
			}
		}
		hasher := sha256.New()
		hasher.Write([]byte(strings.Join(hashs, ",")))
		srcHash = "multi:" + hex.EncodeToString(hasher.Sum(nil))
		origPaths = strings.Join(origs, " ")
	}

	cmd := b.runConfig.Cmd
	if runtime.GOOS != "windows" {
		b.runConfig.Cmd = stringutils.NewStrSlice("/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest))
	} else {
		b.runConfig.Cmd = stringutils.NewStrSlice("cmd", "/S /C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest))
	}
	defer func(cmd *stringutils.StrSlice) { b.runConfig.Cmd = cmd }(cmd)

	if hit, err := b.probeCache(); err != nil {
		return err
	} else if hit {
		return nil
	}

	container, _, err := b.docker.Create(b.runConfig, nil)
	if err != nil {
		return err
	}
	defer container.Unmount()
	b.tmpContainers[container.ID] = struct{}{}

	comment := fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)

	// Twiddle the destination when its a relative path - meaning, make it
	// relative to the WORKINGDIR
	if !system.IsAbs(dest) {
		hasSlash := strings.HasSuffix(dest, string(os.PathSeparator))
		dest = filepath.Join(string(os.PathSeparator), filepath.FromSlash(b.runConfig.WorkingDir), dest)

		// Make sure we preserve any trailing slash
		if hasSlash {
			dest += string(os.PathSeparator)
		}
	}

	for _, info := range infos {
		if err := b.docker.Copy(container, dest, info.FileInfo, info.decompress); err != nil {
			return err
		}
	}

	if err := b.commit(container.ID, cmd, comment); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 15
0
// RUN some command yo
//
// run a command and commit the image. Args are automatically prepended with
// 'sh -c' under linux or 'cmd /S /C' under Windows, in the event there is
// only one argument. The difference in processing:
//
// RUN echo hi          # sh -c echo hi       (Linux)
// RUN echo hi          # cmd /S /C echo hi   (Windows)
// RUN [ "echo", "hi" ] # echo hi
//
func run(b *Builder, args []string, attributes map[string]bool, original string) error {
	if b.image == "" && !b.noBaseImage {
		return derr.ErrorCodeMissingFrom
	}

	if err := b.flags.Parse(); err != nil {
		return err
	}

	args = handleJSONArgs(args, attributes)

	if !attributes["json"] {
		if runtime.GOOS != "windows" {
			args = append([]string{"/bin/sh", "-c"}, args...)
		} else {
			args = append([]string{"cmd", "/S", "/C"}, args...)
		}
	}

	runCmd := flag.NewFlagSet("run", flag.ContinueOnError)
	runCmd.SetOutput(ioutil.Discard)
	runCmd.Usage = nil

	config, _, _, err := runconfig.Parse(runCmd, append([]string{b.image}, args...))
	if err != nil {
		return err
	}

	// stash the cmd
	cmd := b.runConfig.Cmd
	runconfig.Merge(b.runConfig, config)
	// stash the config environment
	env := b.runConfig.Env

	defer func(cmd *stringutils.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
	defer func(env []string) { b.runConfig.Env = env }(env)

	// derive the net build-time environment for this run. We let config
	// environment override the build time environment.
	// This means that we take the b.buildArgs list of env vars and remove
	// any of those variables that are defined as part of the container. In other
	// words, anything in b.Config.Env. What's left is the list of build-time env
	// vars that we need to add to each RUN command - note the list could be empty.
	//
	// We don't persist the build time environment with container's config
	// environment, but just sort and prepend it to the command string at time
	// of commit.
	// This helps with tracing back the image's actual environment at the time
	// of RUN, without leaking it to the final image. It also aids cache
	// lookup for same image built with same build time environment.
	cmdBuildEnv := []string{}
	configEnv := runconfig.ConvertKVStringsToMap(b.runConfig.Env)
	for key, val := range b.BuildArgs {
		if !b.isBuildArgAllowed(key) {
			// skip build-args that are not in allowed list, meaning they have
			// not been defined by an "ARG" Dockerfile command yet.
			// This is an error condition but only if there is no "ARG" in the entire
			// Dockerfile, so we'll generate any necessary errors after we parsed
			// the entire file (see 'leftoverArgs' processing in evaluator.go )
			continue
		}
		if _, ok := configEnv[key]; !ok {
			cmdBuildEnv = append(cmdBuildEnv, fmt.Sprintf("%s=%s", key, val))
		}
	}

	// derive the command to use for probeCache() and to commit in this container.
	// Note that we only do this if there are any build-time env vars.  Also, we
	// use the special argument "|#" at the start of the args array. This will
	// avoid conflicts with any RUN command since commands can not
	// start with | (vertical bar). The "#" (number of build envs) is there to
	// help ensure proper cache matches. We don't want a RUN command
	// that starts with "foo=abc" to be considered part of a build-time env var.
	saveCmd := config.Cmd
	if len(cmdBuildEnv) > 0 {
		sort.Strings(cmdBuildEnv)
		tmpEnv := append([]string{fmt.Sprintf("|%d", len(cmdBuildEnv))}, cmdBuildEnv...)
		saveCmd = stringutils.NewStrSlice(append(tmpEnv, saveCmd.Slice()...)...)
	}

	b.runConfig.Cmd = saveCmd
	hit, err := b.probeCache()
	if err != nil {
		return err
	}
	if hit {
		return nil
	}

	// set Cmd manually, this is special case only for Dockerfiles
	b.runConfig.Cmd = config.Cmd
	// set build-time environment for 'run'.
	b.runConfig.Env = append(b.runConfig.Env, cmdBuildEnv...)
	// set config as already being escaped, this prevents double escaping on windows
	b.runConfig.ArgsEscaped = true

	logrus.Debugf("[BUILDER] Command to be executed: %v", b.runConfig.Cmd)

	c, err := b.create()
	if err != nil {
		return err
	}

	// Ensure that we keep the container mounted until the commit
	// to avoid unmounting and then mounting directly again
	b.docker.Mount(c)
	defer b.docker.Unmount(c)

	err = b.run(c)
	if err != nil {
		return err
	}

	// revert to original config environment and set the command string to
	// have the build-time env vars in it (if any) so that future cache look-ups
	// properly match it.
	b.runConfig.Env = env
	b.runConfig.Cmd = saveCmd
	if err := b.commit(c.ID, cmd, "run"); err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 16
0
func TestCompare(t *testing.T) {
	ports1 := make(nat.PortSet)
	ports1[newPortNoError("tcp", "1111")] = struct{}{}
	ports1[newPortNoError("tcp", "2222")] = struct{}{}
	ports2 := make(nat.PortSet)
	ports2[newPortNoError("tcp", "3333")] = struct{}{}
	ports2[newPortNoError("tcp", "4444")] = struct{}{}
	ports3 := make(nat.PortSet)
	ports3[newPortNoError("tcp", "1111")] = struct{}{}
	ports3[newPortNoError("tcp", "2222")] = struct{}{}
	ports3[newPortNoError("tcp", "5555")] = struct{}{}
	volumes1 := make(map[string]struct{})
	volumes1["/test1"] = struct{}{}
	volumes2 := make(map[string]struct{})
	volumes2["/test2"] = struct{}{}
	volumes3 := make(map[string]struct{})
	volumes3["/test1"] = struct{}{}
	volumes3["/test3"] = struct{}{}
	envs1 := []string{"ENV1=value1", "ENV2=value2"}
	envs2 := []string{"ENV1=value1", "ENV3=value3"}
	entrypoint1 := stringutils.NewStrSlice("/bin/sh", "-c")
	entrypoint2 := stringutils.NewStrSlice("/bin/sh", "-d")
	entrypoint3 := stringutils.NewStrSlice("/bin/sh", "-c", "echo")
	cmd1 := stringutils.NewStrSlice("/bin/sh", "-c")
	cmd2 := stringutils.NewStrSlice("/bin/sh", "-d")
	cmd3 := stringutils.NewStrSlice("/bin/sh", "-c", "echo")
	labels1 := map[string]string{"LABEL1": "value1", "LABEL2": "value2"}
	labels2 := map[string]string{"LABEL1": "value1", "LABEL2": "value3"}
	labels3 := map[string]string{"LABEL1": "value1", "LABEL2": "value2", "LABEL3": "value3"}

	sameConfigs := map[*Config]*Config{
		// Empty config
		&Config{}: {},
		// Does not compare hostname, domainname & image
		&Config{
			Hostname:   "host1",
			Domainname: "domain1",
			Image:      "image1",
			User:       "******",
		}: {
			Hostname:   "host2",
			Domainname: "domain2",
			Image:      "image2",
			User:       "******",
		},
		// only OpenStdin
		&Config{OpenStdin: false}: {OpenStdin: false},
		// only env
		&Config{Env: envs1}: {Env: envs1},
		// only cmd
		&Config{Cmd: cmd1}: {Cmd: cmd1},
		// only labels
		&Config{Labels: labels1}: {Labels: labels1},
		// only exposedPorts
		&Config{ExposedPorts: ports1}: {ExposedPorts: ports1},
		// only entrypoints
		&Config{Entrypoint: entrypoint1}: {Entrypoint: entrypoint1},
		// only volumes
		&Config{Volumes: volumes1}: {Volumes: volumes1},
	}
	differentConfigs := map[*Config]*Config{
		nil: nil,
		&Config{
			Hostname:   "host1",
			Domainname: "domain1",
			Image:      "image1",
			User:       "******",
		}: {
			Hostname:   "host1",
			Domainname: "domain1",
			Image:      "image1",
			User:       "******",
		},
		// only OpenStdin
		&Config{OpenStdin: false}: {OpenStdin: true},
		&Config{OpenStdin: true}:  {OpenStdin: false},
		// only env
		&Config{Env: envs1}: {Env: envs2},
		// only cmd
		&Config{Cmd: cmd1}: {Cmd: cmd2},
		// not the same number of parts
		&Config{Cmd: cmd1}: {Cmd: cmd3},
		// only labels
		&Config{Labels: labels1}: {Labels: labels2},
		// not the same number of labels
		&Config{Labels: labels1}: {Labels: labels3},
		// only exposedPorts
		&Config{ExposedPorts: ports1}: {ExposedPorts: ports2},
		// not the same number of ports
		&Config{ExposedPorts: ports1}: {ExposedPorts: ports3},
		// only entrypoints
		&Config{Entrypoint: entrypoint1}: {Entrypoint: entrypoint2},
		// not the same number of parts
		&Config{Entrypoint: entrypoint1}: {Entrypoint: entrypoint3},
		// only volumes
		&Config{Volumes: volumes1}: {Volumes: volumes2},
		// not the same number of labels
		&Config{Volumes: volumes1}: {Volumes: volumes3},
	}
	for config1, config2 := range sameConfigs {
		if !Compare(config1, config2) {
			t.Fatalf("Compare should be true for [%v] and [%v]", config1, config2)
		}
	}
	for config1, config2 := range differentConfigs {
		if Compare(config1, config2) {
			t.Fatalf("Compare should be false for [%v] and [%v]", config1, config2)
		}
	}
}