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