github.com/uppal0016/docker_new@v0.0.0-20240123060250-1c98be13ac2c/runconfig/opts/parse.go (about)

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