github.com/guilhermebr/docker@v1.4.2-0.20150428121140-67da055cebca/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/ulimit"
    14  	"github.com/docker/docker/pkg/units"
    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  		flLabels  = opts.NewListOpts(opts.ValidateEnv)
    34  		flDevices = opts.NewListOpts(opts.ValidatePath)
    35  
    36  		ulimits   = make(map[string]*ulimit.Ulimit)
    37  		flUlimits = opts.NewUlimitOpt(ulimits)
    38  
    39  		flPublish     = opts.NewListOpts(nil)
    40  		flExpose      = opts.NewListOpts(nil)
    41  		flDns         = opts.NewListOpts(opts.ValidateIPAddress)
    42  		flDnsSearch   = opts.NewListOpts(opts.ValidateDnsSearch)
    43  		flExtraHosts  = opts.NewListOpts(opts.ValidateExtraHost)
    44  		flVolumesFrom = opts.NewListOpts(nil)
    45  		flLxcOpts     = opts.NewListOpts(nil)
    46  		flEnvFile     = opts.NewListOpts(nil)
    47  		flCapAdd      = opts.NewListOpts(nil)
    48  		flCapDrop     = opts.NewListOpts(nil)
    49  		flSecurityOpt = opts.NewListOpts(nil)
    50  		flLabelsFile  = opts.NewListOpts(nil)
    51  
    52  		flNetwork         = cmd.Bool([]string{"#n", "#-networking"}, true, "Enable networking for this container")
    53  		flPrivileged      = cmd.Bool([]string{"#privileged", "-privileged"}, false, "Give extended privileges to this container")
    54  		flPidMode         = cmd.String([]string{"-pid"}, "", "PID namespace to use")
    55  		flPublishAll      = cmd.Bool([]string{"P", "-publish-all"}, false, "Publish all exposed ports to random ports")
    56  		flStdin           = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached")
    57  		flTty             = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY")
    58  		flContainerIDFile = cmd.String([]string{"#cidfile", "-cidfile"}, "", "Write the container ID to the file")
    59  		flEntrypoint      = cmd.String([]string{"#entrypoint", "-entrypoint"}, "", "Overwrite the default ENTRYPOINT of the image")
    60  		flHostname        = cmd.String([]string{"h", "-hostname"}, "", "Container host name")
    61  		flMemoryString    = cmd.String([]string{"m", "-memory"}, "", "Memory limit")
    62  		flMemorySwap      = cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap")
    63  		flUser            = cmd.String([]string{"u", "-user"}, "", "Username or UID (format: <name|uid>[:<group|gid>])")
    64  		flWorkingDir      = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container")
    65  		flCpuShares       = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
    66  		flCpusetCpus      = cmd.String([]string{"#-cpuset", "-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
    67  		flCpusetMems      = cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
    68  		flCpuQuota        = cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota")
    69  		flNetMode         = cmd.String([]string{"-net"}, "bridge", "Set the Network mode for the container")
    70  		flMacAddress      = cmd.String([]string{"-mac-address"}, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)")
    71  		flIpcMode         = cmd.String([]string{"-ipc"}, "", "IPC namespace to use")
    72  		flRestartPolicy   = cmd.String([]string{"-restart"}, "no", "Restart policy to apply when a container exits")
    73  		flReadonlyRootfs  = cmd.Bool([]string{"-read-only"}, false, "Mount the container's root filesystem as read only")
    74  		flLoggingDriver   = cmd.String([]string{"-log-driver"}, "", "Logging driver for container")
    75  		flCgroupParent    = cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
    76  	)
    77  
    78  	cmd.Var(&flAttach, []string{"a", "-attach"}, "Attach to STDIN, STDOUT or STDERR")
    79  	cmd.Var(&flVolumes, []string{"v", "-volume"}, "Bind mount a volume")
    80  	cmd.Var(&flLinks, []string{"#link", "-link"}, "Add link to another container")
    81  	cmd.Var(&flDevices, []string{"-device"}, "Add a host device to the container")
    82  	cmd.Var(&flLabels, []string{"l", "-label"}, "Set meta data on a container")
    83  	cmd.Var(&flLabelsFile, []string{"-label-file"}, "Read in a line delimited file of labels")
    84  	cmd.Var(&flEnv, []string{"e", "-env"}, "Set environment variables")
    85  	cmd.Var(&flEnvFile, []string{"-env-file"}, "Read in a file of environment variables")
    86  	cmd.Var(&flPublish, []string{"p", "-publish"}, "Publish a container's port(s) to the host")
    87  	cmd.Var(&flExpose, []string{"#expose", "-expose"}, "Expose a port or a range of ports")
    88  	cmd.Var(&flDns, []string{"#dns", "-dns"}, "Set custom DNS servers")
    89  	cmd.Var(&flDnsSearch, []string{"-dns-search"}, "Set custom DNS search domains")
    90  	cmd.Var(&flExtraHosts, []string{"-add-host"}, "Add a custom host-to-IP mapping (host:ip)")
    91  	cmd.Var(&flVolumesFrom, []string{"#volumes-from", "-volumes-from"}, "Mount volumes from the specified container(s)")
    92  	cmd.Var(&flLxcOpts, []string{"#lxc-conf", "-lxc-conf"}, "Add custom lxc options")
    93  	cmd.Var(&flCapAdd, []string{"-cap-add"}, "Add Linux capabilities")
    94  	cmd.Var(&flCapDrop, []string{"-cap-drop"}, "Drop Linux capabilities")
    95  	cmd.Var(&flSecurityOpt, []string{"-security-opt"}, "Security Options")
    96  	cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
    97  
    98  	cmd.Require(flag.Min, 1)
    99  
   100  	if err := cmd.ParseFlags(args, true); err != nil {
   101  		return nil, nil, cmd, err
   102  	}
   103  
   104  	// Validate input params
   105  	if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
   106  		return nil, nil, cmd, ErrInvalidWorkingDirectory
   107  	}
   108  
   109  	// Validate the input mac address
   110  	if *flMacAddress != "" {
   111  		if _, err := opts.ValidateMACAddress(*flMacAddress); err != nil {
   112  			return nil, nil, cmd, fmt.Errorf("%s is not a valid mac address", *flMacAddress)
   113  		}
   114  	}
   115  	var (
   116  		attachStdin  = flAttach.Get("stdin")
   117  		attachStdout = flAttach.Get("stdout")
   118  		attachStderr = flAttach.Get("stderr")
   119  	)
   120  
   121  	if *flNetMode != "bridge" && *flNetMode != "none" && *flHostname != "" {
   122  		return nil, nil, cmd, ErrConflictNetworkHostname
   123  	}
   124  
   125  	if *flNetMode == "host" && flLinks.Len() > 0 {
   126  		return nil, nil, cmd, ErrConflictHostNetworkAndLinks
   127  	}
   128  
   129  	if strings.HasPrefix(*flNetMode, "container") && flLinks.Len() > 0 {
   130  		return nil, nil, cmd, ErrConflictContainerNetworkAndLinks
   131  	}
   132  
   133  	if *flNetMode == "host" && flDns.Len() > 0 {
   134  		return nil, nil, cmd, ErrConflictHostNetworkAndDns
   135  	}
   136  
   137  	if strings.HasPrefix(*flNetMode, "container") && flDns.Len() > 0 {
   138  		return nil, nil, cmd, ErrConflictContainerNetworkAndDns
   139  	}
   140  
   141  	// If neither -d or -a are set, attach to everything by default
   142  	if flAttach.Len() == 0 {
   143  		attachStdout = true
   144  		attachStderr = true
   145  		if *flStdin {
   146  			attachStdin = true
   147  		}
   148  	}
   149  
   150  	var flMemory int64
   151  	if *flMemoryString != "" {
   152  		parsedMemory, err := units.RAMInBytes(*flMemoryString)
   153  		if err != nil {
   154  			return nil, nil, cmd, err
   155  		}
   156  		flMemory = parsedMemory
   157  	}
   158  
   159  	var MemorySwap int64
   160  	if *flMemorySwap != "" {
   161  		if *flMemorySwap == "-1" {
   162  			MemorySwap = -1
   163  		} else {
   164  			parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
   165  			if err != nil {
   166  				return nil, nil, cmd, err
   167  			}
   168  			MemorySwap = parsedMemorySwap
   169  		}
   170  	}
   171  
   172  	var binds []string
   173  	// add any bind targets to the list of container volumes
   174  	for bind := range flVolumes.GetMap() {
   175  		if arr := strings.Split(bind, ":"); len(arr) > 1 {
   176  			if arr[1] == "/" {
   177  				return nil, nil, cmd, fmt.Errorf("Invalid bind mount: destination can't be '/'")
   178  			}
   179  			// after creating the bind mount we want to delete it from the flVolumes values because
   180  			// we do not want bind mounts being committed to image configs
   181  			binds = append(binds, bind)
   182  			flVolumes.Delete(bind)
   183  		} else if bind == "/" {
   184  			return nil, nil, cmd, fmt.Errorf("Invalid volume: path can't be '/'")
   185  		}
   186  	}
   187  
   188  	var (
   189  		parsedArgs = cmd.Args()
   190  		runCmd     *Command
   191  		entrypoint *Entrypoint
   192  		image      = cmd.Arg(0)
   193  	)
   194  	if len(parsedArgs) > 1 {
   195  		runCmd = NewCommand(parsedArgs[1:]...)
   196  	}
   197  	if *flEntrypoint != "" {
   198  		entrypoint = NewEntrypoint(*flEntrypoint)
   199  	}
   200  
   201  	lc, err := parseKeyValueOpts(flLxcOpts)
   202  	if err != nil {
   203  		return nil, nil, cmd, err
   204  	}
   205  	lxcConf := NewLxcConfig(lc)
   206  
   207  	var (
   208  		domainname string
   209  		hostname   = *flHostname
   210  		parts      = strings.SplitN(hostname, ".", 2)
   211  	)
   212  	if len(parts) > 1 {
   213  		hostname = parts[0]
   214  		domainname = parts[1]
   215  	}
   216  
   217  	ports, portBindings, err := nat.ParsePortSpecs(flPublish.GetAll())
   218  	if err != nil {
   219  		return nil, nil, cmd, err
   220  	}
   221  
   222  	// Merge in exposed ports to the map of published ports
   223  	for _, e := range flExpose.GetAll() {
   224  		if strings.Contains(e, ":") {
   225  			return nil, nil, cmd, fmt.Errorf("Invalid port format for --expose: %s", e)
   226  		}
   227  		//support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
   228  		proto, port := nat.SplitProtoPort(e)
   229  		//parse the start and end port and create a sequence of ports to expose
   230  		//if expose a port, the start and end port are the same
   231  		start, end, err := parsers.ParsePortRange(port)
   232  		if err != nil {
   233  			return nil, nil, cmd, fmt.Errorf("Invalid range format for --expose: %s, error: %s", e, err)
   234  		}
   235  		for i := start; i <= end; i++ {
   236  			p := nat.NewPort(proto, strconv.FormatUint(i, 10))
   237  			if _, exists := ports[p]; !exists {
   238  				ports[p] = struct{}{}
   239  			}
   240  		}
   241  	}
   242  
   243  	// parse device mappings
   244  	deviceMappings := []DeviceMapping{}
   245  	for _, device := range flDevices.GetAll() {
   246  		deviceMapping, err := ParseDevice(device)
   247  		if err != nil {
   248  			return nil, nil, cmd, err
   249  		}
   250  		deviceMappings = append(deviceMappings, deviceMapping)
   251  	}
   252  
   253  	// collect all the environment variables for the container
   254  	envVariables, err := readKVStrings(flEnvFile.GetAll(), flEnv.GetAll())
   255  	if err != nil {
   256  		return nil, nil, cmd, err
   257  	}
   258  
   259  	// collect all the labels for the container
   260  	labels, err := readKVStrings(flLabelsFile.GetAll(), flLabels.GetAll())
   261  	if err != nil {
   262  		return nil, nil, cmd, err
   263  	}
   264  
   265  	ipcMode := IpcMode(*flIpcMode)
   266  	if !ipcMode.Valid() {
   267  		return nil, nil, cmd, fmt.Errorf("--ipc: invalid IPC mode")
   268  	}
   269  
   270  	pidMode := PidMode(*flPidMode)
   271  	if !pidMode.Valid() {
   272  		return nil, nil, cmd, fmt.Errorf("--pid: invalid PID mode")
   273  	}
   274  
   275  	netMode, err := parseNetMode(*flNetMode)
   276  	if err != nil {
   277  		return nil, nil, cmd, fmt.Errorf("--net: invalid net mode: %v", err)
   278  	}
   279  
   280  	restartPolicy, err := ParseRestartPolicy(*flRestartPolicy)
   281  	if err != nil {
   282  		return nil, nil, cmd, err
   283  	}
   284  
   285  	config := &Config{
   286  		Hostname:        hostname,
   287  		Domainname:      domainname,
   288  		PortSpecs:       nil, // Deprecated
   289  		ExposedPorts:    ports,
   290  		User:            *flUser,
   291  		Tty:             *flTty,
   292  		NetworkDisabled: !*flNetwork,
   293  		OpenStdin:       *flStdin,
   294  		AttachStdin:     attachStdin,
   295  		AttachStdout:    attachStdout,
   296  		AttachStderr:    attachStderr,
   297  		Env:             envVariables,
   298  		Cmd:             runCmd,
   299  		Image:           image,
   300  		Volumes:         flVolumes.GetMap(),
   301  		MacAddress:      *flMacAddress,
   302  		Entrypoint:      entrypoint,
   303  		WorkingDir:      *flWorkingDir,
   304  		Labels:          convertKVStringsToMap(labels),
   305  	}
   306  
   307  	hostConfig := &HostConfig{
   308  		Binds:           binds,
   309  		ContainerIDFile: *flContainerIDFile,
   310  		LxcConf:         lxcConf,
   311  		Memory:          flMemory,
   312  		MemorySwap:      MemorySwap,
   313  		CpuShares:       *flCpuShares,
   314  		CpusetCpus:      *flCpusetCpus,
   315  		CpusetMems:      *flCpusetMems,
   316  		CpuQuota:        *flCpuQuota,
   317  		Privileged:      *flPrivileged,
   318  		PortBindings:    portBindings,
   319  		Links:           flLinks.GetAll(),
   320  		PublishAllPorts: *flPublishAll,
   321  		Dns:             flDns.GetAll(),
   322  		DnsSearch:       flDnsSearch.GetAll(),
   323  		ExtraHosts:      flExtraHosts.GetAll(),
   324  		VolumesFrom:     flVolumesFrom.GetAll(),
   325  		NetworkMode:     netMode,
   326  		IpcMode:         ipcMode,
   327  		PidMode:         pidMode,
   328  		Devices:         deviceMappings,
   329  		CapAdd:          flCapAdd.GetAll(),
   330  		CapDrop:         flCapDrop.GetAll(),
   331  		RestartPolicy:   restartPolicy,
   332  		SecurityOpt:     flSecurityOpt.GetAll(),
   333  		ReadonlyRootfs:  *flReadonlyRootfs,
   334  		Ulimits:         flUlimits.GetList(),
   335  		LogConfig:       LogConfig{Type: *flLoggingDriver},
   336  		CgroupParent:    *flCgroupParent,
   337  	}
   338  
   339  	// When allocating stdin in attached mode, close stdin at client disconnect
   340  	if config.OpenStdin && config.AttachStdin {
   341  		config.StdinOnce = true
   342  	}
   343  	return config, hostConfig, cmd, nil
   344  }
   345  
   346  // reads a file of line terminated key=value pairs and override that with override parameter
   347  func readKVStrings(files []string, override []string) ([]string, error) {
   348  	envVariables := []string{}
   349  	for _, ef := range files {
   350  		parsedVars, err := opts.ParseEnvFile(ef)
   351  		if err != nil {
   352  			return nil, err
   353  		}
   354  		envVariables = append(envVariables, parsedVars...)
   355  	}
   356  	// parse the '-e' and '--env' after, to allow override
   357  	envVariables = append(envVariables, override...)
   358  
   359  	return envVariables, nil
   360  }
   361  
   362  // converts ["key=value"] to {"key":"value"}
   363  func convertKVStringsToMap(values []string) map[string]string {
   364  	result := make(map[string]string, len(values))
   365  	for _, value := range values {
   366  		kv := strings.SplitN(value, "=", 2)
   367  		if len(kv) == 1 {
   368  			result[kv[0]] = ""
   369  		} else {
   370  			result[kv[0]] = kv[1]
   371  		}
   372  	}
   373  
   374  	return result
   375  }
   376  
   377  // ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect
   378  func ParseRestartPolicy(policy string) (RestartPolicy, error) {
   379  	p := RestartPolicy{}
   380  
   381  	if policy == "" {
   382  		return p, nil
   383  	}
   384  
   385  	var (
   386  		parts = strings.Split(policy, ":")
   387  		name  = parts[0]
   388  	)
   389  
   390  	p.Name = name
   391  	switch name {
   392  	case "always":
   393  		if len(parts) == 2 {
   394  			return p, fmt.Errorf("maximum restart count not valid with restart policy of \"always\"")
   395  		}
   396  	case "no":
   397  		// do nothing
   398  	case "on-failure":
   399  		if len(parts) == 2 {
   400  			count, err := strconv.Atoi(parts[1])
   401  			if err != nil {
   402  				return p, err
   403  			}
   404  
   405  			p.MaximumRetryCount = count
   406  		}
   407  	default:
   408  		return p, fmt.Errorf("invalid restart policy %s", name)
   409  	}
   410  
   411  	return p, nil
   412  }
   413  
   414  // options will come in the format of name.key=value or name.option
   415  func parseDriverOpts(opts opts.ListOpts) (map[string][]string, error) {
   416  	out := make(map[string][]string, len(opts.GetAll()))
   417  	for _, o := range opts.GetAll() {
   418  		parts := strings.SplitN(o, ".", 2)
   419  		if len(parts) < 2 {
   420  			return nil, fmt.Errorf("invalid opt format %s", o)
   421  		} else if strings.TrimSpace(parts[0]) == "" {
   422  			return nil, fmt.Errorf("key cannot be empty %s", o)
   423  		}
   424  		values, exists := out[parts[0]]
   425  		if !exists {
   426  			values = []string{}
   427  		}
   428  		out[parts[0]] = append(values, parts[1])
   429  	}
   430  	return out, nil
   431  }
   432  
   433  func parseKeyValueOpts(opts opts.ListOpts) ([]KeyValuePair, error) {
   434  	out := make([]KeyValuePair, opts.Len())
   435  	for i, o := range opts.GetAll() {
   436  		k, v, err := parsers.ParseKeyValueOpt(o)
   437  		if err != nil {
   438  			return nil, err
   439  		}
   440  		out[i] = KeyValuePair{Key: k, Value: v}
   441  	}
   442  	return out, nil
   443  }
   444  
   445  func parseNetMode(netMode string) (NetworkMode, error) {
   446  	parts := strings.Split(netMode, ":")
   447  	switch mode := parts[0]; mode {
   448  	case "bridge", "none", "host":
   449  	case "container":
   450  		if len(parts) < 2 || parts[1] == "" {
   451  			return "", fmt.Errorf("invalid container format container:<name|id>")
   452  		}
   453  	default:
   454  		return "", fmt.Errorf("invalid --net: %s", netMode)
   455  	}
   456  	return NetworkMode(netMode), nil
   457  }
   458  
   459  func ParseDevice(device string) (DeviceMapping, error) {
   460  	src := ""
   461  	dst := ""
   462  	permissions := "rwm"
   463  	arr := strings.Split(device, ":")
   464  	switch len(arr) {
   465  	case 3:
   466  		permissions = arr[2]
   467  		fallthrough
   468  	case 2:
   469  		dst = arr[1]
   470  		fallthrough
   471  	case 1:
   472  		src = arr[0]
   473  	default:
   474  		return DeviceMapping{}, fmt.Errorf("Invalid device specification: %s", device)
   475  	}
   476  
   477  	if dst == "" {
   478  		dst = src
   479  	}
   480  
   481  	deviceMapping := DeviceMapping{
   482  		PathOnHost:        src,
   483  		PathInContainer:   dst,
   484  		CgroupPermissions: permissions,
   485  	}
   486  	return deviceMapping, nil
   487  }