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