github.com/mheon/docker@v0.11.2-0.20150922122814-44f47903a831/runconfig/parse.go (about)

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