github.com/jmtd/docker@v1.5.0/runconfig/parse.go (about)

     1  package runconfig
     2  
     3  import (
     4  	"fmt"
     5  	"path"
     6  	"strconv"
     7  	"strings"
     8  
     9  	"github.com/docker/docker/nat"
    10  	"github.com/docker/docker/opts"
    11  	flag "github.com/docker/docker/pkg/mflag"
    12  	"github.com/docker/docker/pkg/parsers"
    13  	"github.com/docker/docker/pkg/units"
    14  	"github.com/docker/docker/utils"
    15  )
    16  
    17  var (
    18  	ErrInvalidWorkingDirectory          = fmt.Errorf("The working directory is invalid. It needs to be an absolute path.")
    19  	ErrConflictContainerNetworkAndLinks = fmt.Errorf("Conflicting options: --net=container can't be used with links. This would result in undefined behavior.")
    20  	ErrConflictContainerNetworkAndDns   = fmt.Errorf("Conflicting options: --net=container can't be used with --dns. This configuration is invalid.")
    21  	ErrConflictNetworkHostname          = fmt.Errorf("Conflicting options: -h and the network mode (--net)")
    22  	ErrConflictHostNetworkAndDns        = fmt.Errorf("Conflicting options: --net=host can't be used with --dns. This configuration is invalid.")
    23  	ErrConflictHostNetworkAndLinks      = fmt.Errorf("Conflicting options: --net=host can't be used with links. This would result in undefined behavior.")
    24  )
    25  
    26  func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSet, error) {
    27  	var (
    28  		// FIXME: use utils.ListOpts for attach and volumes?
    29  		flAttach  = opts.NewListOpts(opts.ValidateAttach)
    30  		flVolumes = opts.NewListOpts(opts.ValidatePath)
    31  		flLinks   = opts.NewListOpts(opts.ValidateLink)
    32  		flEnv     = opts.NewListOpts(opts.ValidateEnv)
    33  		flDevices = opts.NewListOpts(opts.ValidatePath)
    34  
    35  		flPublish     = opts.NewListOpts(nil)
    36  		flExpose      = opts.NewListOpts(nil)
    37  		flDns         = opts.NewListOpts(opts.ValidateIPAddress)
    38  		flDnsSearch   = opts.NewListOpts(opts.ValidateDnsSearch)
    39  		flExtraHosts  = opts.NewListOpts(opts.ValidateExtraHost)
    40  		flVolumesFrom = opts.NewListOpts(nil)
    41  		flLxcOpts     = opts.NewListOpts(nil)
    42  		flEnvFile     = opts.NewListOpts(nil)
    43  		flCapAdd      = opts.NewListOpts(nil)
    44  		flCapDrop     = opts.NewListOpts(nil)
    45  		flSecurityOpt = opts.NewListOpts(nil)
    46  
    47  		flNetwork         = cmd.Bool([]string{"#n", "#-networking"}, true, "Enable networking for this container")
    48  		flPrivileged      = cmd.Bool([]string{"#privileged", "-privileged"}, false, "Give extended privileges to this container")
    49  		flPidMode         = cmd.String([]string{"-pid"}, "", "Default is to create a private PID namespace for the container\n'host': use the host PID namespace inside the container.  Note: the host mode gives the container full access to processes on the system and is therefore considered insecure.")
    50  		flPublishAll      = cmd.Bool([]string{"P", "-publish-all"}, false, "Publish all exposed ports to random ports on the host interfaces")
    51  		flStdin           = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached")
    52  		flTty             = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY")
    53  		flContainerIDFile = cmd.String([]string{"#cidfile", "-cidfile"}, "", "Write the container ID to the file")
    54  		flEntrypoint      = cmd.String([]string{"#entrypoint", "-entrypoint"}, "", "Overwrite the default ENTRYPOINT of the image")
    55  		flHostname        = cmd.String([]string{"h", "-hostname"}, "", "Container host name")
    56  		flMemoryString    = cmd.String([]string{"m", "-memory"}, "", "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)")
    57  		flMemorySwap      = cmd.String([]string{"-memory-swap"}, "", "Total memory usage (memory + swap), set '-1' to disable swap (format: <number><optional unit>, where unit = b, k, m or g)")
    58  		flUser            = cmd.String([]string{"u", "-user"}, "", "Username or UID")
    59  		flWorkingDir      = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container")
    60  		flCpuShares       = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
    61  		flCpuset          = cmd.String([]string{"-cpuset"}, "", "CPUs in which to allow execution (0-3, 0,1)")
    62  		flNetMode         = cmd.String([]string{"-net"}, "bridge", "Set the Network mode for the container\n'bridge': creates a new network stack for the container on the docker bridge\n'none': no networking for this container\n'container:<name|id>': reuses another container network stack\n'host': use the host network stack inside the container.  Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.")
    63  		flMacAddress      = cmd.String([]string{"-mac-address"}, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)")
    64  		flIpcMode         = cmd.String([]string{"-ipc"}, "", "Default is to create a private IPC namespace (POSIX SysV IPC) for the container\n'container:<name|id>': reuses another container shared memory, semaphores and message queues\n'host': use the host shared memory,semaphores and message queues inside the container.  Note: the host mode gives the container full access to local shared memory and is therefore considered insecure.")
    65  		flRestartPolicy   = cmd.String([]string{"-restart"}, "", "Restart policy to apply when a container exits (no, on-failure[:max-retry], always)")
    66  		flReadonlyRootfs  = cmd.Bool([]string{"-read-only"}, false, "Mount the container's root filesystem as read only")
    67  	)
    68  
    69  	cmd.Var(&flAttach, []string{"a", "-attach"}, "Attach to STDIN, STDOUT or STDERR.")
    70  	cmd.Var(&flVolumes, []string{"v", "-volume"}, "Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)")
    71  	cmd.Var(&flLinks, []string{"#link", "-link"}, "Add link to another container in the form of <name|id>:alias")
    72  	cmd.Var(&flDevices, []string{"-device"}, "Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)")
    73  
    74  	cmd.Var(&flEnv, []string{"e", "-env"}, "Set environment variables")
    75  	cmd.Var(&flEnvFile, []string{"-env-file"}, "Read in a line delimited file of environment variables")
    76  
    77  	cmd.Var(&flPublish, []string{"p", "-publish"}, fmt.Sprintf("Publish a container's port to the host\nformat: %s\n(use 'docker port' to see the actual mapping)", nat.PortSpecTemplateFormat))
    78  	cmd.Var(&flExpose, []string{"#expose", "-expose"}, "Expose a port or a range of ports (e.g. --expose=3300-3310) from the container without publishing it to your host")
    79  	cmd.Var(&flDns, []string{"#dns", "-dns"}, "Set custom DNS servers")
    80  	cmd.Var(&flDnsSearch, []string{"-dns-search"}, "Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain)")
    81  	cmd.Var(&flExtraHosts, []string{"-add-host"}, "Add a custom host-to-IP mapping (host:ip)")
    82  	cmd.Var(&flVolumesFrom, []string{"#volumes-from", "-volumes-from"}, "Mount volumes from the specified container(s)")
    83  	cmd.Var(&flLxcOpts, []string{"#lxc-conf", "-lxc-conf"}, "(lxc exec-driver only) Add custom lxc options --lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"")
    84  
    85  	cmd.Var(&flCapAdd, []string{"-cap-add"}, "Add Linux capabilities")
    86  	cmd.Var(&flCapDrop, []string{"-cap-drop"}, "Drop Linux capabilities")
    87  	cmd.Var(&flSecurityOpt, []string{"-security-opt"}, "Security Options")
    88  
    89  	cmd.Require(flag.Min, 1)
    90  
    91  	if err := utils.ParseFlags(cmd, args, true); err != nil {
    92  		return nil, nil, cmd, err
    93  	}
    94  
    95  	// Validate input params
    96  	if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
    97  		return nil, nil, cmd, ErrInvalidWorkingDirectory
    98  	}
    99  
   100  	var (
   101  		attachStdin  = flAttach.Get("stdin")
   102  		attachStdout = flAttach.Get("stdout")
   103  		attachStderr = flAttach.Get("stderr")
   104  	)
   105  
   106  	if *flNetMode != "bridge" && *flNetMode != "none" && *flHostname != "" {
   107  		return nil, nil, cmd, ErrConflictNetworkHostname
   108  	}
   109  
   110  	if *flNetMode == "host" && flLinks.Len() > 0 {
   111  		return nil, nil, cmd, ErrConflictHostNetworkAndLinks
   112  	}
   113  
   114  	if *flNetMode == "container" && flLinks.Len() > 0 {
   115  		return nil, nil, cmd, ErrConflictContainerNetworkAndLinks
   116  	}
   117  
   118  	if *flNetMode == "host" && flDns.Len() > 0 {
   119  		return nil, nil, cmd, ErrConflictHostNetworkAndDns
   120  	}
   121  
   122  	if *flNetMode == "container" && flDns.Len() > 0 {
   123  		return nil, nil, cmd, ErrConflictContainerNetworkAndDns
   124  	}
   125  
   126  	// If neither -d or -a are set, attach to everything by default
   127  	if flAttach.Len() == 0 {
   128  		attachStdout = true
   129  		attachStderr = true
   130  		if *flStdin {
   131  			attachStdin = true
   132  		}
   133  	}
   134  
   135  	var flMemory int64
   136  	if *flMemoryString != "" {
   137  		parsedMemory, err := units.RAMInBytes(*flMemoryString)
   138  		if err != nil {
   139  			return nil, nil, cmd, err
   140  		}
   141  		flMemory = parsedMemory
   142  	}
   143  
   144  	var MemorySwap int64
   145  	if *flMemorySwap != "" {
   146  		parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
   147  		if err != nil {
   148  			return nil, nil, cmd, err
   149  		}
   150  		MemorySwap = parsedMemorySwap
   151  	}
   152  
   153  	var binds []string
   154  	// add any bind targets to the list of container volumes
   155  	for bind := range flVolumes.GetMap() {
   156  		if arr := strings.Split(bind, ":"); len(arr) > 1 {
   157  			if arr[1] == "/" {
   158  				return nil, nil, cmd, fmt.Errorf("Invalid bind mount: destination can't be '/'")
   159  			}
   160  			// after creating the bind mount we want to delete it from the flVolumes values because
   161  			// we do not want bind mounts being committed to image configs
   162  			binds = append(binds, bind)
   163  			flVolumes.Delete(bind)
   164  		} else if bind == "/" {
   165  			return nil, nil, cmd, fmt.Errorf("Invalid volume: path can't be '/'")
   166  		}
   167  	}
   168  
   169  	var (
   170  		parsedArgs = cmd.Args()
   171  		runCmd     []string
   172  		entrypoint []string
   173  		image      = cmd.Arg(0)
   174  	)
   175  	if len(parsedArgs) > 1 {
   176  		runCmd = parsedArgs[1:]
   177  	}
   178  	if *flEntrypoint != "" {
   179  		entrypoint = []string{*flEntrypoint}
   180  	}
   181  
   182  	lxcConf, err := parseKeyValueOpts(flLxcOpts)
   183  	if err != nil {
   184  		return nil, nil, cmd, err
   185  	}
   186  
   187  	var (
   188  		domainname string
   189  		hostname   = *flHostname
   190  		parts      = strings.SplitN(hostname, ".", 2)
   191  	)
   192  	if len(parts) > 1 {
   193  		hostname = parts[0]
   194  		domainname = parts[1]
   195  	}
   196  
   197  	ports, portBindings, err := nat.ParsePortSpecs(flPublish.GetAll())
   198  	if err != nil {
   199  		return nil, nil, cmd, err
   200  	}
   201  
   202  	// Merge in exposed ports to the map of published ports
   203  	for _, e := range flExpose.GetAll() {
   204  		if strings.Contains(e, ":") {
   205  			return nil, nil, cmd, fmt.Errorf("Invalid port format for --expose: %s", e)
   206  		}
   207  		//support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
   208  		if strings.Contains(e, "-") {
   209  			proto, port := nat.SplitProtoPort(e)
   210  			//parse the start and end port and create a sequence of ports to expose
   211  			start, end, err := parsers.ParsePortRange(port)
   212  			if err != nil {
   213  				return nil, nil, cmd, fmt.Errorf("Invalid range format for --expose: %s, error: %s", e, err)
   214  			}
   215  			for i := start; i <= end; i++ {
   216  				p := nat.NewPort(proto, strconv.FormatUint(i, 10))
   217  				if _, exists := ports[p]; !exists {
   218  					ports[p] = struct{}{}
   219  				}
   220  			}
   221  		} else {
   222  			p := nat.NewPort(nat.SplitProtoPort(e))
   223  			if _, exists := ports[p]; !exists {
   224  				ports[p] = struct{}{}
   225  			}
   226  		}
   227  	}
   228  
   229  	// parse device mappings
   230  	deviceMappings := []DeviceMapping{}
   231  	for _, device := range flDevices.GetAll() {
   232  		deviceMapping, err := ParseDevice(device)
   233  		if err != nil {
   234  			return nil, nil, cmd, err
   235  		}
   236  		deviceMappings = append(deviceMappings, deviceMapping)
   237  	}
   238  
   239  	// collect all the environment variables for the container
   240  	envVariables := []string{}
   241  	for _, ef := range flEnvFile.GetAll() {
   242  		parsedVars, err := opts.ParseEnvFile(ef)
   243  		if err != nil {
   244  			return nil, nil, cmd, err
   245  		}
   246  		envVariables = append(envVariables, parsedVars...)
   247  	}
   248  	// parse the '-e' and '--env' after, to allow override
   249  	envVariables = append(envVariables, flEnv.GetAll()...)
   250  
   251  	ipcMode := IpcMode(*flIpcMode)
   252  	if !ipcMode.Valid() {
   253  		return nil, nil, cmd, fmt.Errorf("--ipc: invalid IPC mode")
   254  	}
   255  
   256  	pidMode := PidMode(*flPidMode)
   257  	if !pidMode.Valid() {
   258  		return nil, nil, cmd, fmt.Errorf("--pid: invalid PID mode")
   259  	}
   260  
   261  	netMode, err := parseNetMode(*flNetMode)
   262  	if err != nil {
   263  		return nil, nil, cmd, fmt.Errorf("--net: invalid net mode: %v", err)
   264  	}
   265  
   266  	restartPolicy, err := parseRestartPolicy(*flRestartPolicy)
   267  	if err != nil {
   268  		return nil, nil, cmd, err
   269  	}
   270  
   271  	config := &Config{
   272  		Hostname:        hostname,
   273  		Domainname:      domainname,
   274  		PortSpecs:       nil, // Deprecated
   275  		ExposedPorts:    ports,
   276  		User:            *flUser,
   277  		Tty:             *flTty,
   278  		NetworkDisabled: !*flNetwork,
   279  		OpenStdin:       *flStdin,
   280  		Memory:          flMemory,
   281  		MemorySwap:      MemorySwap,
   282  		CpuShares:       *flCpuShares,
   283  		Cpuset:          *flCpuset,
   284  		AttachStdin:     attachStdin,
   285  		AttachStdout:    attachStdout,
   286  		AttachStderr:    attachStderr,
   287  		Env:             envVariables,
   288  		Cmd:             runCmd,
   289  		Image:           image,
   290  		Volumes:         flVolumes.GetMap(),
   291  		MacAddress:      *flMacAddress,
   292  		Entrypoint:      entrypoint,
   293  		WorkingDir:      *flWorkingDir,
   294  	}
   295  
   296  	hostConfig := &HostConfig{
   297  		Binds:           binds,
   298  		ContainerIDFile: *flContainerIDFile,
   299  		LxcConf:         lxcConf,
   300  		Privileged:      *flPrivileged,
   301  		PortBindings:    portBindings,
   302  		Links:           flLinks.GetAll(),
   303  		PublishAllPorts: *flPublishAll,
   304  		Dns:             flDns.GetAll(),
   305  		DnsSearch:       flDnsSearch.GetAll(),
   306  		ExtraHosts:      flExtraHosts.GetAll(),
   307  		VolumesFrom:     flVolumesFrom.GetAll(),
   308  		NetworkMode:     netMode,
   309  		IpcMode:         ipcMode,
   310  		PidMode:         pidMode,
   311  		Devices:         deviceMappings,
   312  		CapAdd:          flCapAdd.GetAll(),
   313  		CapDrop:         flCapDrop.GetAll(),
   314  		RestartPolicy:   restartPolicy,
   315  		SecurityOpt:     flSecurityOpt.GetAll(),
   316  		ReadonlyRootfs:  *flReadonlyRootfs,
   317  	}
   318  
   319  	// When allocating stdin in attached mode, close stdin at client disconnect
   320  	if config.OpenStdin && config.AttachStdin {
   321  		config.StdinOnce = true
   322  	}
   323  	return config, hostConfig, cmd, nil
   324  }
   325  
   326  // parseRestartPolicy returns the parsed policy or an error indicating what is incorrect
   327  func parseRestartPolicy(policy string) (RestartPolicy, error) {
   328  	p := RestartPolicy{}
   329  
   330  	if policy == "" {
   331  		return p, nil
   332  	}
   333  
   334  	var (
   335  		parts = strings.Split(policy, ":")
   336  		name  = parts[0]
   337  	)
   338  
   339  	p.Name = name
   340  	switch name {
   341  	case "always":
   342  		if len(parts) == 2 {
   343  			return p, fmt.Errorf("maximum restart count not valid with restart policy of \"always\"")
   344  		}
   345  	case "no":
   346  		// do nothing
   347  	case "on-failure":
   348  		if len(parts) == 2 {
   349  			count, err := strconv.Atoi(parts[1])
   350  			if err != nil {
   351  				return p, err
   352  			}
   353  
   354  			p.MaximumRetryCount = count
   355  		}
   356  	default:
   357  		return p, fmt.Errorf("invalid restart policy %s", name)
   358  	}
   359  
   360  	return p, nil
   361  }
   362  
   363  // options will come in the format of name.key=value or name.option
   364  func parseDriverOpts(opts opts.ListOpts) (map[string][]string, error) {
   365  	out := make(map[string][]string, len(opts.GetAll()))
   366  	for _, o := range opts.GetAll() {
   367  		parts := strings.SplitN(o, ".", 2)
   368  		if len(parts) < 2 {
   369  			return nil, fmt.Errorf("invalid opt format %s", o)
   370  		} else if strings.TrimSpace(parts[0]) == "" {
   371  			return nil, fmt.Errorf("key cannot be empty %s", o)
   372  		}
   373  		values, exists := out[parts[0]]
   374  		if !exists {
   375  			values = []string{}
   376  		}
   377  		out[parts[0]] = append(values, parts[1])
   378  	}
   379  	return out, nil
   380  }
   381  
   382  func parseKeyValueOpts(opts opts.ListOpts) ([]utils.KeyValuePair, error) {
   383  	out := make([]utils.KeyValuePair, opts.Len())
   384  	for i, o := range opts.GetAll() {
   385  		k, v, err := parsers.ParseKeyValueOpt(o)
   386  		if err != nil {
   387  			return nil, err
   388  		}
   389  		out[i] = utils.KeyValuePair{Key: k, Value: v}
   390  	}
   391  	return out, nil
   392  }
   393  
   394  func parseNetMode(netMode string) (NetworkMode, error) {
   395  	parts := strings.Split(netMode, ":")
   396  	switch mode := parts[0]; mode {
   397  	case "bridge", "none", "host":
   398  	case "container":
   399  		if len(parts) < 2 || parts[1] == "" {
   400  			return "", fmt.Errorf("invalid container format container:<name|id>")
   401  		}
   402  	default:
   403  		return "", fmt.Errorf("invalid --net: %s", netMode)
   404  	}
   405  	return NetworkMode(netMode), nil
   406  }
   407  
   408  func ParseDevice(device string) (DeviceMapping, error) {
   409  	src := ""
   410  	dst := ""
   411  	permissions := "rwm"
   412  	arr := strings.Split(device, ":")
   413  	switch len(arr) {
   414  	case 3:
   415  		permissions = arr[2]
   416  		fallthrough
   417  	case 2:
   418  		dst = arr[1]
   419  		fallthrough
   420  	case 1:
   421  		src = arr[0]
   422  	default:
   423  		return DeviceMapping{}, fmt.Errorf("Invalid device specification: %s", device)
   424  	}
   425  
   426  	if dst == "" {
   427  		dst = src
   428  	}
   429  
   430  	deviceMapping := DeviceMapping{
   431  		PathOnHost:        src,
   432  		PathInContainer:   dst,
   433  		CgroupPermissions: permissions,
   434  	}
   435  	return deviceMapping, nil
   436  }