github.com/ncdc/docker@v0.10.1-0.20160129113957-6c6729ef5b74/runconfig/opts/parse.go (about)

     1  package opts
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"path"
     9  	"strconv"
    10  	"strings"
    11  
    12  	"github.com/docker/docker/opts"
    13  	flag "github.com/docker/docker/pkg/mflag"
    14  	"github.com/docker/docker/pkg/mount"
    15  	"github.com/docker/docker/pkg/signal"
    16  	"github.com/docker/engine-api/types/container"
    17  	networktypes "github.com/docker/engine-api/types/network"
    18  	"github.com/docker/engine-api/types/strslice"
    19  	"github.com/docker/go-connections/nat"
    20  	"github.com/docker/go-units"
    21  )
    22  
    23  // Parse parses the specified args for the specified command and generates a Config,
    24  // a HostConfig and returns them with the specified command.
    25  // If the specified args are not valid, it will return an error.
    26  func Parse(cmd *flag.FlagSet, args []string) (*container.Config, *container.HostConfig, *networktypes.NetworkingConfig, *flag.FlagSet, error) {
    27  	var (
    28  		// FIXME: use utils.ListOpts for attach and volumes?
    29  		flAttach            = opts.NewListOpts(ValidateAttach)
    30  		flVolumes           = opts.NewListOpts(nil)
    31  		flTmpfs             = opts.NewListOpts(nil)
    32  		flBlkioWeightDevice = NewWeightdeviceOpt(ValidateWeightDevice)
    33  		flDeviceReadBps     = NewThrottledeviceOpt(ValidateThrottleBpsDevice)
    34  		flDeviceWriteBps    = NewThrottledeviceOpt(ValidateThrottleBpsDevice)
    35  		flLinks             = opts.NewListOpts(ValidateLink)
    36  		flAliases           = opts.NewListOpts(nil)
    37  		flDeviceReadIOps    = NewThrottledeviceOpt(ValidateThrottleIOpsDevice)
    38  		flDeviceWriteIOps   = NewThrottledeviceOpt(ValidateThrottleIOpsDevice)
    39  		flEnv               = opts.NewListOpts(ValidateEnv)
    40  		flLabels            = opts.NewListOpts(ValidateEnv)
    41  		flDevices           = opts.NewListOpts(ValidateDevice)
    42  
    43  		flUlimits = NewUlimitOpt(nil)
    44  
    45  		flPublish           = opts.NewListOpts(nil)
    46  		flExpose            = opts.NewListOpts(nil)
    47  		flDNS               = opts.NewListOpts(opts.ValidateIPAddress)
    48  		flDNSSearch         = opts.NewListOpts(opts.ValidateDNSSearch)
    49  		flDNSOptions        = opts.NewListOpts(nil)
    50  		flExtraHosts        = opts.NewListOpts(ValidateExtraHost)
    51  		flVolumesFrom       = opts.NewListOpts(nil)
    52  		flEnvFile           = opts.NewListOpts(nil)
    53  		flCapAdd            = opts.NewListOpts(nil)
    54  		flCapDrop           = opts.NewListOpts(nil)
    55  		flGroupAdd          = opts.NewListOpts(nil)
    56  		flSecurityOpt       = opts.NewListOpts(nil)
    57  		flLabelsFile        = opts.NewListOpts(nil)
    58  		flLoggingOpts       = opts.NewListOpts(nil)
    59  		flPrivileged        = cmd.Bool([]string{"-privileged"}, false, "Give extended privileges to this container")
    60  		flPidMode           = cmd.String([]string{"-pid"}, "", "PID namespace to use")
    61  		flUTSMode           = cmd.String([]string{"-uts"}, "", "UTS namespace to use")
    62  		flPublishAll        = cmd.Bool([]string{"P", "-publish-all"}, false, "Publish all exposed ports to random ports")
    63  		flStdin             = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached")
    64  		flTty               = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY")
    65  		flOomKillDisable    = cmd.Bool([]string{"-oom-kill-disable"}, false, "Disable OOM Killer")
    66  		flOomScoreAdj       = cmd.Int([]string{"-oom-score-adj"}, 0, "Tune host's OOM preferences (-1000 to 1000)")
    67  		flContainerIDFile   = cmd.String([]string{"-cidfile"}, "", "Write the container ID to the file")
    68  		flEntrypoint        = cmd.String([]string{"-entrypoint"}, "", "Overwrite the default ENTRYPOINT of the image")
    69  		flHostname          = cmd.String([]string{"h", "-hostname"}, "", "Container host name")
    70  		flMemoryString      = cmd.String([]string{"m", "-memory"}, "", "Memory limit")
    71  		flMemoryReservation = cmd.String([]string{"-memory-reservation"}, "", "Memory soft limit")
    72  		flMemorySwap        = cmd.String([]string{"-memory-swap"}, "", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap")
    73  		flKernelMemory      = cmd.String([]string{"-kernel-memory"}, "", "Kernel memory limit")
    74  		flUser              = cmd.String([]string{"u", "-user"}, "", "Username or UID (format: <name|uid>[:<group|gid>])")
    75  		flWorkingDir        = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container")
    76  		flCPUShares         = cmd.Int64([]string{"#c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
    77  		flCPUPeriod         = cmd.Int64([]string{"-cpu-period"}, 0, "Limit CPU CFS (Completely Fair Scheduler) period")
    78  		flCPUQuota          = cmd.Int64([]string{"-cpu-quota"}, 0, "Limit CPU CFS (Completely Fair Scheduler) quota")
    79  		flCpusetCpus        = cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
    80  		flCpusetMems        = cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
    81  		flBlkioWeight       = cmd.Uint16([]string{"-blkio-weight"}, 0, "Block IO (relative weight), between 10 and 1000")
    82  		flSwappiness        = cmd.Int64([]string{"-memory-swappiness"}, -1, "Tune container memory swappiness (0 to 100)")
    83  		flNetMode           = cmd.String([]string{"-net"}, "default", "Connect a container to a network")
    84  		flMacAddress        = cmd.String([]string{"-mac-address"}, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)")
    85  		flIPv4Address       = cmd.String([]string{"-ip"}, "", "Container IPv4 address (e.g. 172.30.100.104)")
    86  		flIPv6Address       = cmd.String([]string{"-ip6"}, "", "Container IPv6 address (e.g. 2001:db8::33)")
    87  		flIpcMode           = cmd.String([]string{"-ipc"}, "", "IPC namespace to use")
    88  		flRestartPolicy     = cmd.String([]string{"-restart"}, "no", "Restart policy to apply when a container exits")
    89  		flReadonlyRootfs    = cmd.Bool([]string{"-read-only"}, false, "Mount the container's root filesystem as read only")
    90  		flLoggingDriver     = cmd.String([]string{"-log-driver"}, "", "Logging driver for container")
    91  		flCgroupParent      = cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
    92  		flVolumeDriver      = cmd.String([]string{"-volume-driver"}, "", "Optional volume driver for the container")
    93  		flStopSignal        = cmd.String([]string{"-stop-signal"}, signal.DefaultStopSignal, fmt.Sprintf("Signal to stop a container, %v by default", signal.DefaultStopSignal))
    94  		flIsolation         = cmd.String([]string{"-isolation"}, "", "Container isolation level")
    95  		flShmSize           = cmd.String([]string{"-shm-size"}, "", "Size of /dev/shm, default value is 64MB")
    96  	)
    97  
    98  	cmd.Var(&flAttach, []string{"a", "-attach"}, "Attach to STDIN, STDOUT or STDERR")
    99  	cmd.Var(&flBlkioWeightDevice, []string{"-blkio-weight-device"}, "Block IO weight (relative device weight)")
   100  	cmd.Var(&flDeviceReadBps, []string{"-device-read-bps"}, "Limit read rate (bytes per second) from a device")
   101  	cmd.Var(&flDeviceWriteBps, []string{"-device-write-bps"}, "Limit write rate (bytes per second) to a device")
   102  	cmd.Var(&flDeviceReadIOps, []string{"-device-read-iops"}, "Limit read rate (IO per second) from a device")
   103  	cmd.Var(&flDeviceWriteIOps, []string{"-device-write-iops"}, "Limit write rate (IO per second) to a device")
   104  	cmd.Var(&flVolumes, []string{"v", "-volume"}, "Bind mount a volume")
   105  	cmd.Var(&flTmpfs, []string{"-tmpfs"}, "Mount a tmpfs directory")
   106  	cmd.Var(&flLinks, []string{"-link"}, "Add link to another container")
   107  	cmd.Var(&flAliases, []string{"-net-alias"}, "Add network-scoped alias for the container")
   108  	cmd.Var(&flDevices, []string{"-device"}, "Add a host device to the container")
   109  	cmd.Var(&flLabels, []string{"l", "-label"}, "Set meta data on a container")
   110  	cmd.Var(&flLabelsFile, []string{"-label-file"}, "Read in a line delimited file of labels")
   111  	cmd.Var(&flEnv, []string{"e", "-env"}, "Set environment variables")
   112  	cmd.Var(&flEnvFile, []string{"-env-file"}, "Read in a file of environment variables")
   113  	cmd.Var(&flPublish, []string{"p", "-publish"}, "Publish a container's port(s) to the host")
   114  	cmd.Var(&flExpose, []string{"-expose"}, "Expose a port or a range of ports")
   115  	cmd.Var(&flDNS, []string{"-dns"}, "Set custom DNS servers")
   116  	cmd.Var(&flDNSSearch, []string{"-dns-search"}, "Set custom DNS search domains")
   117  	cmd.Var(&flDNSOptions, []string{"-dns-opt"}, "Set DNS options")
   118  	cmd.Var(&flExtraHosts, []string{"-add-host"}, "Add a custom host-to-IP mapping (host:ip)")
   119  	cmd.Var(&flVolumesFrom, []string{"-volumes-from"}, "Mount volumes from the specified container(s)")
   120  	cmd.Var(&flCapAdd, []string{"-cap-add"}, "Add Linux capabilities")
   121  	cmd.Var(&flCapDrop, []string{"-cap-drop"}, "Drop Linux capabilities")
   122  	cmd.Var(&flGroupAdd, []string{"-group-add"}, "Add additional groups to join")
   123  	cmd.Var(&flSecurityOpt, []string{"-security-opt"}, "Security Options")
   124  	cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
   125  	cmd.Var(&flLoggingOpts, []string{"-log-opt"}, "Log driver options")
   126  
   127  	cmd.Require(flag.Min, 1)
   128  
   129  	if err := cmd.ParseFlags(args, true); err != nil {
   130  		return nil, nil, nil, cmd, err
   131  	}
   132  
   133  	var (
   134  		attachStdin  = flAttach.Get("stdin")
   135  		attachStdout = flAttach.Get("stdout")
   136  		attachStderr = flAttach.Get("stderr")
   137  	)
   138  
   139  	// Validate the input mac address
   140  	if *flMacAddress != "" {
   141  		if _, err := ValidateMACAddress(*flMacAddress); err != nil {
   142  			return nil, nil, nil, cmd, fmt.Errorf("%s is not a valid mac address", *flMacAddress)
   143  		}
   144  	}
   145  	if *flStdin {
   146  		attachStdin = true
   147  	}
   148  	// If -a is not set attach to the output stdio
   149  	if flAttach.Len() == 0 {
   150  		attachStdout = true
   151  		attachStderr = true
   152  	}
   153  
   154  	var err error
   155  
   156  	var flMemory int64
   157  	if *flMemoryString != "" {
   158  		flMemory, err = units.RAMInBytes(*flMemoryString)
   159  		if err != nil {
   160  			return nil, nil, nil, cmd, err
   161  		}
   162  	}
   163  
   164  	var MemoryReservation int64
   165  	if *flMemoryReservation != "" {
   166  		MemoryReservation, err = units.RAMInBytes(*flMemoryReservation)
   167  		if err != nil {
   168  			return nil, nil, nil, cmd, err
   169  		}
   170  	}
   171  
   172  	var memorySwap int64
   173  	if *flMemorySwap != "" {
   174  		if *flMemorySwap == "-1" {
   175  			memorySwap = -1
   176  		} else {
   177  			memorySwap, err = units.RAMInBytes(*flMemorySwap)
   178  			if err != nil {
   179  				return nil, nil, nil, cmd, err
   180  			}
   181  		}
   182  	}
   183  
   184  	var KernelMemory int64
   185  	if *flKernelMemory != "" {
   186  		KernelMemory, err = units.RAMInBytes(*flKernelMemory)
   187  		if err != nil {
   188  			return nil, nil, nil, cmd, err
   189  		}
   190  	}
   191  
   192  	swappiness := *flSwappiness
   193  	if swappiness != -1 && (swappiness < 0 || swappiness > 100) {
   194  		return nil, nil, nil, cmd, fmt.Errorf("Invalid value: %d. Valid memory swappiness range is 0-100", swappiness)
   195  	}
   196  
   197  	var shmSize int64
   198  	if *flShmSize != "" {
   199  		shmSize, err = units.RAMInBytes(*flShmSize)
   200  		if err != nil {
   201  			return nil, nil, nil, cmd, err
   202  		}
   203  	}
   204  
   205  	var binds []string
   206  	// add any bind targets to the list of container volumes
   207  	for bind := range flVolumes.GetMap() {
   208  		if arr := volumeSplitN(bind, 2); len(arr) > 1 {
   209  			// after creating the bind mount we want to delete it from the flVolumes values because
   210  			// we do not want bind mounts being committed to image configs
   211  			binds = append(binds, bind)
   212  			flVolumes.Delete(bind)
   213  		}
   214  	}
   215  
   216  	// Can't evaluate options passed into --tmpfs until we actually mount
   217  	tmpfs := make(map[string]string)
   218  	for _, t := range flTmpfs.GetAll() {
   219  		if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
   220  			if _, _, err := mount.ParseTmpfsOptions(arr[1]); err != nil {
   221  				return nil, nil, nil, cmd, err
   222  			}
   223  			tmpfs[arr[0]] = arr[1]
   224  		} else {
   225  			tmpfs[arr[0]] = ""
   226  		}
   227  	}
   228  
   229  	var (
   230  		parsedArgs = cmd.Args()
   231  		runCmd     *strslice.StrSlice
   232  		entrypoint *strslice.StrSlice
   233  		image      = cmd.Arg(0)
   234  	)
   235  	if len(parsedArgs) > 1 {
   236  		runCmd = strslice.New(parsedArgs[1:]...)
   237  	}
   238  	if *flEntrypoint != "" {
   239  		entrypoint = strslice.New(*flEntrypoint)
   240  	}
   241  
   242  	var (
   243  		domainname string
   244  		hostname   = *flHostname
   245  		parts      = strings.SplitN(hostname, ".", 2)
   246  	)
   247  	if len(parts) > 1 {
   248  		hostname = parts[0]
   249  		domainname = parts[1]
   250  	}
   251  
   252  	ports, portBindings, err := nat.ParsePortSpecs(flPublish.GetAll())
   253  	if err != nil {
   254  		return nil, nil, nil, cmd, err
   255  	}
   256  
   257  	// Merge in exposed ports to the map of published ports
   258  	for _, e := range flExpose.GetAll() {
   259  		if strings.Contains(e, ":") {
   260  			return nil, nil, nil, cmd, fmt.Errorf("Invalid port format for --expose: %s", e)
   261  		}
   262  		//support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
   263  		proto, port := nat.SplitProtoPort(e)
   264  		//parse the start and end port and create a sequence of ports to expose
   265  		//if expose a port, the start and end port are the same
   266  		start, end, err := nat.ParsePortRange(port)
   267  		if err != nil {
   268  			return nil, nil, nil, cmd, fmt.Errorf("Invalid range format for --expose: %s, error: %s", e, err)
   269  		}
   270  		for i := start; i <= end; i++ {
   271  			p, err := nat.NewPort(proto, strconv.FormatUint(i, 10))
   272  			if err != nil {
   273  				return nil, nil, nil, cmd, err
   274  			}
   275  			if _, exists := ports[p]; !exists {
   276  				ports[p] = struct{}{}
   277  			}
   278  		}
   279  	}
   280  
   281  	// parse device mappings
   282  	deviceMappings := []container.DeviceMapping{}
   283  	for _, device := range flDevices.GetAll() {
   284  		deviceMapping, err := ParseDevice(device)
   285  		if err != nil {
   286  			return nil, nil, nil, cmd, err
   287  		}
   288  		deviceMappings = append(deviceMappings, deviceMapping)
   289  	}
   290  
   291  	// collect all the environment variables for the container
   292  	envVariables, err := readKVStrings(flEnvFile.GetAll(), flEnv.GetAll())
   293  	if err != nil {
   294  		return nil, nil, nil, cmd, err
   295  	}
   296  
   297  	// collect all the labels for the container
   298  	labels, err := readKVStrings(flLabelsFile.GetAll(), flLabels.GetAll())
   299  	if err != nil {
   300  		return nil, nil, nil, cmd, err
   301  	}
   302  
   303  	ipcMode := container.IpcMode(*flIpcMode)
   304  	if !ipcMode.Valid() {
   305  		return nil, nil, nil, cmd, fmt.Errorf("--ipc: invalid IPC mode")
   306  	}
   307  
   308  	pidMode := container.PidMode(*flPidMode)
   309  	if !pidMode.Valid() {
   310  		return nil, nil, nil, cmd, fmt.Errorf("--pid: invalid PID mode")
   311  	}
   312  
   313  	utsMode := container.UTSMode(*flUTSMode)
   314  	if !utsMode.Valid() {
   315  		return nil, nil, nil, cmd, fmt.Errorf("--uts: invalid UTS mode")
   316  	}
   317  
   318  	restartPolicy, err := ParseRestartPolicy(*flRestartPolicy)
   319  	if err != nil {
   320  		return nil, nil, nil, cmd, err
   321  	}
   322  
   323  	loggingOpts, err := parseLoggingOpts(*flLoggingDriver, flLoggingOpts.GetAll())
   324  	if err != nil {
   325  		return nil, nil, nil, cmd, err
   326  	}
   327  
   328  	securityOpts, err := parseSecurityOpts(flSecurityOpt.GetAll())
   329  	if err != nil {
   330  		return nil, nil, nil, cmd, err
   331  	}
   332  
   333  	resources := container.Resources{
   334  		CgroupParent:         *flCgroupParent,
   335  		Memory:               flMemory,
   336  		MemoryReservation:    MemoryReservation,
   337  		MemorySwap:           memorySwap,
   338  		MemorySwappiness:     flSwappiness,
   339  		KernelMemory:         KernelMemory,
   340  		OomKillDisable:       flOomKillDisable,
   341  		CPUShares:            *flCPUShares,
   342  		CPUPeriod:            *flCPUPeriod,
   343  		CpusetCpus:           *flCpusetCpus,
   344  		CpusetMems:           *flCpusetMems,
   345  		CPUQuota:             *flCPUQuota,
   346  		BlkioWeight:          *flBlkioWeight,
   347  		BlkioWeightDevice:    flBlkioWeightDevice.GetList(),
   348  		BlkioDeviceReadBps:   flDeviceReadBps.GetList(),
   349  		BlkioDeviceWriteBps:  flDeviceWriteBps.GetList(),
   350  		BlkioDeviceReadIOps:  flDeviceReadIOps.GetList(),
   351  		BlkioDeviceWriteIOps: flDeviceWriteIOps.GetList(),
   352  		Ulimits:              flUlimits.GetList(),
   353  		Devices:              deviceMappings,
   354  	}
   355  
   356  	config := &container.Config{
   357  		Hostname:     hostname,
   358  		Domainname:   domainname,
   359  		ExposedPorts: ports,
   360  		User:         *flUser,
   361  		Tty:          *flTty,
   362  		// TODO: deprecated, it comes from -n, --networking
   363  		// it's still needed internally to set the network to disabled
   364  		// if e.g. bridge is none in daemon opts, and in inspect
   365  		NetworkDisabled: false,
   366  		OpenStdin:       *flStdin,
   367  		AttachStdin:     attachStdin,
   368  		AttachStdout:    attachStdout,
   369  		AttachStderr:    attachStderr,
   370  		Env:             envVariables,
   371  		Cmd:             runCmd,
   372  		Image:           image,
   373  		Volumes:         flVolumes.GetMap(),
   374  		MacAddress:      *flMacAddress,
   375  		Entrypoint:      entrypoint,
   376  		WorkingDir:      *flWorkingDir,
   377  		Labels:          ConvertKVStringsToMap(labels),
   378  		StopSignal:      *flStopSignal,
   379  	}
   380  
   381  	hostConfig := &container.HostConfig{
   382  		Binds:           binds,
   383  		ContainerIDFile: *flContainerIDFile,
   384  		OomScoreAdj:     *flOomScoreAdj,
   385  		Privileged:      *flPrivileged,
   386  		PortBindings:    portBindings,
   387  		Links:           flLinks.GetAll(),
   388  		PublishAllPorts: *flPublishAll,
   389  		// Make sure the dns fields are never nil.
   390  		// New containers don't ever have those fields nil,
   391  		// but pre created containers can still have those nil values.
   392  		// See https://github.com/docker/docker/pull/17779
   393  		// for a more detailed explanation on why we don't want that.
   394  		DNS:            flDNS.GetAllOrEmpty(),
   395  		DNSSearch:      flDNSSearch.GetAllOrEmpty(),
   396  		DNSOptions:     flDNSOptions.GetAllOrEmpty(),
   397  		ExtraHosts:     flExtraHosts.GetAll(),
   398  		VolumesFrom:    flVolumesFrom.GetAll(),
   399  		NetworkMode:    container.NetworkMode(*flNetMode),
   400  		IpcMode:        ipcMode,
   401  		PidMode:        pidMode,
   402  		UTSMode:        utsMode,
   403  		CapAdd:         strslice.New(flCapAdd.GetAll()...),
   404  		CapDrop:        strslice.New(flCapDrop.GetAll()...),
   405  		GroupAdd:       flGroupAdd.GetAll(),
   406  		RestartPolicy:  restartPolicy,
   407  		SecurityOpt:    securityOpts,
   408  		ReadonlyRootfs: *flReadonlyRootfs,
   409  		LogConfig:      container.LogConfig{Type: *flLoggingDriver, Config: loggingOpts},
   410  		VolumeDriver:   *flVolumeDriver,
   411  		Isolation:      container.IsolationLevel(*flIsolation),
   412  		ShmSize:        shmSize,
   413  		Resources:      resources,
   414  		Tmpfs:          tmpfs,
   415  	}
   416  
   417  	// When allocating stdin in attached mode, close stdin at client disconnect
   418  	if config.OpenStdin && config.AttachStdin {
   419  		config.StdinOnce = true
   420  	}
   421  
   422  	networkingConfig := &networktypes.NetworkingConfig{
   423  		EndpointsConfig: make(map[string]*networktypes.EndpointSettings),
   424  	}
   425  
   426  	if *flIPv4Address != "" || *flIPv6Address != "" {
   427  		networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = &networktypes.EndpointSettings{
   428  			IPAMConfig: &networktypes.EndpointIPAMConfig{
   429  				IPv4Address: *flIPv4Address,
   430  				IPv6Address: *flIPv6Address,
   431  			},
   432  		}
   433  	}
   434  
   435  	if hostConfig.NetworkMode.IsUserDefined() && len(hostConfig.Links) > 0 {
   436  		epConfig := networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)]
   437  		if epConfig == nil {
   438  			epConfig = &networktypes.EndpointSettings{}
   439  		}
   440  		epConfig.Links = make([]string, len(hostConfig.Links))
   441  		copy(epConfig.Links, hostConfig.Links)
   442  		networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = epConfig
   443  	}
   444  
   445  	if flAliases.Len() > 0 {
   446  		epConfig := networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)]
   447  		if epConfig == nil {
   448  			epConfig = &networktypes.EndpointSettings{}
   449  		}
   450  		epConfig.Aliases = make([]string, flAliases.Len())
   451  		copy(epConfig.Aliases, flAliases.GetAll())
   452  		networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = epConfig
   453  	}
   454  
   455  	return config, hostConfig, networkingConfig, cmd, nil
   456  }
   457  
   458  // reads a file of line terminated key=value pairs and override that with override parameter
   459  func readKVStrings(files []string, override []string) ([]string, error) {
   460  	envVariables := []string{}
   461  	for _, ef := range files {
   462  		parsedVars, err := ParseEnvFile(ef)
   463  		if err != nil {
   464  			return nil, err
   465  		}
   466  		envVariables = append(envVariables, parsedVars...)
   467  	}
   468  	// parse the '-e' and '--env' after, to allow override
   469  	envVariables = append(envVariables, override...)
   470  
   471  	return envVariables, nil
   472  }
   473  
   474  // ConvertKVStringsToMap converts ["key=value"] to {"key":"value"}
   475  func ConvertKVStringsToMap(values []string) map[string]string {
   476  	result := make(map[string]string, len(values))
   477  	for _, value := range values {
   478  		kv := strings.SplitN(value, "=", 2)
   479  		if len(kv) == 1 {
   480  			result[kv[0]] = ""
   481  		} else {
   482  			result[kv[0]] = kv[1]
   483  		}
   484  	}
   485  
   486  	return result
   487  }
   488  
   489  func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) {
   490  	loggingOptsMap := ConvertKVStringsToMap(loggingOpts)
   491  	if loggingDriver == "none" && len(loggingOpts) > 0 {
   492  		return map[string]string{}, fmt.Errorf("Invalid logging opts for driver %s", loggingDriver)
   493  	}
   494  	return loggingOptsMap, nil
   495  }
   496  
   497  // takes a local seccomp daemon, reads the file contents for sending to the daemon
   498  func parseSecurityOpts(securityOpts []string) ([]string, error) {
   499  	for key, opt := range securityOpts {
   500  		con := strings.SplitN(opt, ":", 2)
   501  		if len(con) == 1 {
   502  			return securityOpts, fmt.Errorf("Invalid --security-opt: %q", opt)
   503  		}
   504  		if con[0] == "seccomp" && con[1] != "unconfined" {
   505  			f, err := ioutil.ReadFile(con[1])
   506  			if err != nil {
   507  				return securityOpts, fmt.Errorf("Opening seccomp profile (%s) failed: %v", con[1], err)
   508  			}
   509  			b := bytes.NewBuffer(nil)
   510  			if err := json.Compact(b, f); err != nil {
   511  				return securityOpts, fmt.Errorf("Compacting json for seccomp profile (%s) failed: %v", con[1], err)
   512  			}
   513  			securityOpts[key] = fmt.Sprintf("seccomp:%s", b.Bytes())
   514  		}
   515  	}
   516  
   517  	return securityOpts, nil
   518  }
   519  
   520  // ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect
   521  func ParseRestartPolicy(policy string) (container.RestartPolicy, error) {
   522  	p := container.RestartPolicy{}
   523  
   524  	if policy == "" {
   525  		return p, nil
   526  	}
   527  
   528  	var (
   529  		parts = strings.Split(policy, ":")
   530  		name  = parts[0]
   531  	)
   532  
   533  	p.Name = name
   534  	switch name {
   535  	case "always", "unless-stopped":
   536  		if len(parts) > 1 {
   537  			return p, fmt.Errorf("maximum restart count not valid with restart policy of \"%s\"", name)
   538  		}
   539  	case "no":
   540  		// do nothing
   541  	case "on-failure":
   542  		if len(parts) > 2 {
   543  			return p, fmt.Errorf("restart count format is not valid, usage: 'on-failure:N' or 'on-failure'")
   544  		}
   545  		if len(parts) == 2 {
   546  			count, err := strconv.Atoi(parts[1])
   547  			if err != nil {
   548  				return p, err
   549  			}
   550  
   551  			p.MaximumRetryCount = count
   552  		}
   553  	default:
   554  		return p, fmt.Errorf("invalid restart policy %s", name)
   555  	}
   556  
   557  	return p, nil
   558  }
   559  
   560  // ParseDevice parses a device mapping string to a container.DeviceMapping struct
   561  func ParseDevice(device string) (container.DeviceMapping, error) {
   562  	src := ""
   563  	dst := ""
   564  	permissions := "rwm"
   565  	arr := strings.Split(device, ":")
   566  	switch len(arr) {
   567  	case 3:
   568  		permissions = arr[2]
   569  		fallthrough
   570  	case 2:
   571  		if ValidDeviceMode(arr[1]) {
   572  			permissions = arr[1]
   573  		} else {
   574  			dst = arr[1]
   575  		}
   576  		fallthrough
   577  	case 1:
   578  		src = arr[0]
   579  	default:
   580  		return container.DeviceMapping{}, fmt.Errorf("Invalid device specification: %s", device)
   581  	}
   582  
   583  	if dst == "" {
   584  		dst = src
   585  	}
   586  
   587  	deviceMapping := container.DeviceMapping{
   588  		PathOnHost:        src,
   589  		PathInContainer:   dst,
   590  		CgroupPermissions: permissions,
   591  	}
   592  	return deviceMapping, nil
   593  }
   594  
   595  // ParseLink parses and validates the specified string as a link format (name:alias)
   596  func ParseLink(val string) (string, string, error) {
   597  	if val == "" {
   598  		return "", "", fmt.Errorf("empty string specified for links")
   599  	}
   600  	arr := strings.Split(val, ":")
   601  	if len(arr) > 2 {
   602  		return "", "", fmt.Errorf("bad format for links: %s", val)
   603  	}
   604  	if len(arr) == 1 {
   605  		return val, val, nil
   606  	}
   607  	// This is kept because we can actually get an HostConfig with links
   608  	// from an already created container and the format is not `foo:bar`
   609  	// but `/foo:/c1/bar`
   610  	if strings.HasPrefix(arr[0], "/") {
   611  		_, alias := path.Split(arr[1])
   612  		return arr[0][1:], alias, nil
   613  	}
   614  	return arr[0], arr[1], nil
   615  }
   616  
   617  // ValidateLink validates that the specified string has a valid link format (containerName:alias).
   618  func ValidateLink(val string) (string, error) {
   619  	if _, _, err := ParseLink(val); err != nil {
   620  		return val, err
   621  	}
   622  	return val, nil
   623  }
   624  
   625  // ValidDeviceMode checks if the mode for device is valid or not.
   626  // Valid mode is a composition of r (read), w (write), and m (mknod).
   627  func ValidDeviceMode(mode string) bool {
   628  	var legalDeviceMode = map[rune]bool{
   629  		'r': true,
   630  		'w': true,
   631  		'm': true,
   632  	}
   633  	if mode == "" {
   634  		return false
   635  	}
   636  	for _, c := range mode {
   637  		if !legalDeviceMode[c] {
   638  			return false
   639  		}
   640  		legalDeviceMode[c] = false
   641  	}
   642  	return true
   643  }
   644  
   645  // ValidateDevice validates a path for devices
   646  // It will make sure 'val' is in the form:
   647  //    [host-dir:]container-path[:mode]
   648  // It also validates the device mode.
   649  func ValidateDevice(val string) (string, error) {
   650  	return validatePath(val, ValidDeviceMode)
   651  }
   652  
   653  func validatePath(val string, validator func(string) bool) (string, error) {
   654  	var containerPath string
   655  	var mode string
   656  
   657  	if strings.Count(val, ":") > 2 {
   658  		return val, fmt.Errorf("bad format for path: %s", val)
   659  	}
   660  
   661  	split := strings.SplitN(val, ":", 3)
   662  	if split[0] == "" {
   663  		return val, fmt.Errorf("bad format for path: %s", val)
   664  	}
   665  	switch len(split) {
   666  	case 1:
   667  		containerPath = split[0]
   668  		val = path.Clean(containerPath)
   669  	case 2:
   670  		if isValid := validator(split[1]); isValid {
   671  			containerPath = split[0]
   672  			mode = split[1]
   673  			val = fmt.Sprintf("%s:%s", path.Clean(containerPath), mode)
   674  		} else {
   675  			containerPath = split[1]
   676  			val = fmt.Sprintf("%s:%s", split[0], path.Clean(containerPath))
   677  		}
   678  	case 3:
   679  		containerPath = split[1]
   680  		mode = split[2]
   681  		if isValid := validator(split[2]); !isValid {
   682  			return val, fmt.Errorf("bad mode specified: %s", mode)
   683  		}
   684  		val = fmt.Sprintf("%s:%s:%s", split[0], containerPath, mode)
   685  	}
   686  
   687  	if !path.IsAbs(containerPath) {
   688  		return val, fmt.Errorf("%s is not an absolute path", containerPath)
   689  	}
   690  	return val, nil
   691  }
   692  
   693  // SplitN splits raw into a maximum of n parts, separated by a separator colon.
   694  // A separator colon is the last `:` character in the regex `[/:\\]?[a-zA-Z]:` (note `\\` is `\` escaped).
   695  // This allows to correctly split strings such as `C:\foo:D:\:rw`.
   696  func volumeSplitN(raw string, n int) []string {
   697  	var array []string
   698  	if len(raw) == 0 || raw[0] == ':' {
   699  		// invalid
   700  		return nil
   701  	}
   702  	// numberOfParts counts the number of parts separated by a separator colon
   703  	numberOfParts := 0
   704  	// left represents the left-most cursor in raw, updated at every `:` character considered as a separator.
   705  	left := 0
   706  	// right represents the right-most cursor in raw incremented with the loop. Note this
   707  	// starts at index 1 as index 0 is already handle above as a special case.
   708  	for right := 1; right < len(raw); right++ {
   709  		// stop parsing if reached maximum number of parts
   710  		if n >= 0 && numberOfParts >= n {
   711  			break
   712  		}
   713  		if raw[right] != ':' {
   714  			continue
   715  		}
   716  		potentialDriveLetter := raw[right-1]
   717  		if (potentialDriveLetter >= 'A' && potentialDriveLetter <= 'Z') || (potentialDriveLetter >= 'a' && potentialDriveLetter <= 'z') {
   718  			if right > 1 {
   719  				beforePotentialDriveLetter := raw[right-2]
   720  				if beforePotentialDriveLetter != ':' && beforePotentialDriveLetter != '/' && beforePotentialDriveLetter != '\\' {
   721  					// e.g. `C:` is not preceded by any delimiter, therefore it was not a drive letter but a path ending with `C:`.
   722  					array = append(array, raw[left:right])
   723  					left = right + 1
   724  					numberOfParts++
   725  				}
   726  				// else, `C:` is considered as a drive letter and not as a delimiter, so we continue parsing.
   727  			}
   728  			// if right == 1, then `C:` is the beginning of the raw string, therefore `:` is again not considered a delimiter and we continue parsing.
   729  		} else {
   730  			// if `:` is not preceded by a potential drive letter, then consider it as a delimiter.
   731  			array = append(array, raw[left:right])
   732  			left = right + 1
   733  			numberOfParts++
   734  		}
   735  	}
   736  	// need to take care of the last part
   737  	if left < len(raw) {
   738  		if n >= 0 && numberOfParts >= n {
   739  			// if the maximum number of parts is reached, just append the rest to the last part
   740  			// left-1 is at the last `:` that needs to be included since not considered a separator.
   741  			array[n-1] += raw[left-1:]
   742  		} else {
   743  			array = append(array, raw[left:])
   744  		}
   745  	}
   746  	return array
   747  }