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