2015-12-21 20:05:55 -05:00
package opts
2014-02-11 23:04:39 -05:00
import (
2016-01-04 12:59:26 -05:00
"bytes"
"encoding/json"
2014-02-11 23:04:39 -05:00
"fmt"
2016-01-04 12:59:26 -05:00
"io/ioutil"
2015-12-15 21:36:35 -05:00
"path"
2014-08-04 19:14:43 -04:00
"strconv"
2014-04-30 18:46:56 -04:00
"strings"
2016-05-31 19:49:32 -04:00
"time"
2014-04-30 18:46:56 -04:00
2014-07-24 18:19:50 -04:00
"github.com/docker/docker/opts"
2015-12-01 13:39:34 -05:00
"github.com/docker/docker/pkg/mount"
2015-08-04 16:51:48 -04:00
"github.com/docker/docker/pkg/signal"
2016-01-04 19:05:26 -05:00
"github.com/docker/engine-api/types/container"
2016-01-07 19:18:34 -05:00
networktypes "github.com/docker/engine-api/types/network"
2016-01-04 19:05:26 -05:00
"github.com/docker/engine-api/types/strslice"
2015-12-18 12:58:48 -05:00
"github.com/docker/go-connections/nat"
2016-05-31 19:49:32 -04:00
units "github.com/docker/go-units"
"github.com/spf13/pflag"
2014-02-11 23:04:39 -05:00
)
2016-05-31 19:49:32 -04:00
// ContainerOptions is a data object with all the options for creating a container
// TODO: remove fl prefix
type ContainerOptions struct {
flAttach opts . ListOpts
flVolumes opts . ListOpts
flTmpfs opts . ListOpts
flBlkioWeightDevice WeightdeviceOpt
flDeviceReadBps ThrottledeviceOpt
flDeviceWriteBps ThrottledeviceOpt
flLinks opts . ListOpts
flAliases opts . ListOpts
2016-06-09 18:10:59 -04:00
flLinkLocalIPs opts . ListOpts
2016-05-31 19:49:32 -04:00
flDeviceReadIOps ThrottledeviceOpt
flDeviceWriteIOps ThrottledeviceOpt
flEnv opts . ListOpts
flLabels opts . ListOpts
flDevices opts . ListOpts
flUlimits * UlimitOpt
flSysctls * opts . MapOpts
flPublish opts . ListOpts
flExpose opts . ListOpts
flDNS opts . ListOpts
flDNSSearch opts . ListOpts
flDNSOptions opts . ListOpts
flExtraHosts opts . ListOpts
flVolumesFrom opts . ListOpts
flEnvFile opts . ListOpts
flCapAdd opts . ListOpts
flCapDrop opts . ListOpts
flGroupAdd opts . ListOpts
flSecurityOpt opts . ListOpts
flStorageOpt opts . ListOpts
flLabelsFile opts . ListOpts
flLoggingOpts opts . ListOpts
2016-06-06 18:25:04 -04:00
flPrivileged bool
flPidMode string
flUTSMode string
flUsernsMode string
flPublishAll bool
flStdin bool
flTty bool
flOomKillDisable bool
flOomScoreAdj int
flContainerIDFile string
flEntrypoint string
flHostname string
flMemoryString string
flMemoryReservation string
flMemorySwap string
flKernelMemory string
flUser string
flWorkingDir string
flCPUShares int64
flCPUPercent int64
flCPUPeriod int64
flCPUQuota int64
flCpusetCpus string
flCpusetMems string
flBlkioWeight uint16
flIOMaxBandwidth string
flIOMaxIOps uint64
flSwappiness int64
flNetMode string
flMacAddress string
flIPv4Address string
flIPv6Address string
flIpcMode string
flPidsLimit int64
flRestartPolicy string
flReadonlyRootfs bool
flLoggingDriver string
flCgroupParent string
flVolumeDriver string
flStopSignal string
flIsolation string
flShmSize string
flNoHealthcheck bool
flHealthCmd string
flHealthInterval time . Duration
flHealthTimeout time . Duration
flHealthRetries int
flRuntime string
2016-05-31 19:49:32 -04:00
Image string
Args [ ] string
}
// AddFlags adds all command line flags that will be used by Parse to the FlagSet
func AddFlags ( flags * pflag . FlagSet ) * ContainerOptions {
copts := & ContainerOptions {
2016-06-06 18:25:04 -04:00
flAliases : opts . NewListOpts ( nil ) ,
2016-05-31 19:49:32 -04:00
flAttach : opts . NewListOpts ( ValidateAttach ) ,
flBlkioWeightDevice : NewWeightdeviceOpt ( ValidateWeightDevice ) ,
2016-06-06 18:25:04 -04:00
flCapAdd : opts . NewListOpts ( nil ) ,
flCapDrop : opts . NewListOpts ( nil ) ,
flDNS : opts . NewListOpts ( opts . ValidateIPAddress ) ,
flDNSOptions : opts . NewListOpts ( nil ) ,
flDNSSearch : opts . NewListOpts ( opts . ValidateDNSSearch ) ,
2016-05-31 19:49:32 -04:00
flDeviceReadBps : NewThrottledeviceOpt ( ValidateThrottleBpsDevice ) ,
flDeviceReadIOps : NewThrottledeviceOpt ( ValidateThrottleIOpsDevice ) ,
2016-06-06 18:25:04 -04:00
flDeviceWriteBps : NewThrottledeviceOpt ( ValidateThrottleBpsDevice ) ,
2016-05-31 19:49:32 -04:00
flDeviceWriteIOps : NewThrottledeviceOpt ( ValidateThrottleIOpsDevice ) ,
2016-06-06 18:25:04 -04:00
flDevices : opts . NewListOpts ( ValidateDevice ) ,
2016-05-31 19:49:32 -04:00
flEnv : opts . NewListOpts ( ValidateEnv ) ,
2016-06-06 18:25:04 -04:00
flEnvFile : opts . NewListOpts ( nil ) ,
flExpose : opts . NewListOpts ( nil ) ,
flExtraHosts : opts . NewListOpts ( ValidateExtraHost ) ,
flGroupAdd : opts . NewListOpts ( nil ) ,
2016-05-31 19:49:32 -04:00
flLabels : opts . NewListOpts ( ValidateEnv ) ,
2016-06-06 18:25:04 -04:00
flLabelsFile : opts . NewListOpts ( nil ) ,
flLinkLocalIPs : opts . NewListOpts ( nil ) ,
flLinks : opts . NewListOpts ( ValidateLink ) ,
flLoggingOpts : opts . NewListOpts ( nil ) ,
flPublish : opts . NewListOpts ( nil ) ,
flSecurityOpt : opts . NewListOpts ( nil ) ,
flStorageOpt : opts . NewListOpts ( nil ) ,
flSysctls : opts . NewMapOpts ( nil , opts . ValidateSysctl ) ,
flTmpfs : opts . NewListOpts ( nil ) ,
flUlimits : NewUlimitOpt ( nil ) ,
flVolumes : opts . NewListOpts ( nil ) ,
flVolumesFrom : opts . NewListOpts ( nil ) ,
2016-05-31 19:49:32 -04:00
}
2016-06-06 18:25:04 -04:00
// General purpose flags
2016-05-31 19:49:32 -04:00
flags . VarP ( & copts . flAttach , "attach" , "a" , "Attach to STDIN, STDOUT or STDERR" )
flags . Var ( & copts . flDevices , "device" , "Add a host device to the container" )
flags . VarP ( & copts . flEnv , "env" , "e" , "Set environment variables" )
flags . Var ( & copts . flEnvFile , "env-file" , "Read in a file of environment variables" )
2016-06-06 18:25:04 -04:00
flags . StringVar ( & copts . flEntrypoint , "entrypoint" , "" , "Overwrite the default ENTRYPOINT of the image" )
flags . Var ( & copts . flGroupAdd , "group-add" , "Add additional groups to join" )
flags . StringVarP ( & copts . flHostname , "hostname" , "h" , "" , "Container host name" )
flags . BoolVarP ( & copts . flStdin , "interactive" , "i" , false , "Keep STDIN open even if not attached" )
flags . VarP ( & copts . flLabels , "label" , "l" , "Set meta data on a container" )
flags . Var ( & copts . flLabelsFile , "label-file" , "Read in a line delimited file of labels" )
flags . BoolVar ( & copts . flReadonlyRootfs , "read-only" , false , "Mount the container's root filesystem as read only" )
flags . StringVar ( & copts . flRestartPolicy , "restart" , "no" , "Restart policy to apply when a container exits" )
flags . StringVar ( & copts . flStopSignal , "stop-signal" , signal . DefaultStopSignal , fmt . Sprintf ( "Signal to stop a container, %v by default" , signal . DefaultStopSignal ) )
flags . Var ( copts . flSysctls , "sysctl" , "Sysctl options" )
flags . BoolVarP ( & copts . flTty , "tty" , "t" , false , "Allocate a pseudo-TTY" )
flags . Var ( copts . flUlimits , "ulimit" , "Ulimit options" )
flags . StringVarP ( & copts . flUser , "user" , "u" , "" , "Username or UID (format: <name|uid>[:<group|gid>])" )
flags . StringVarP ( & copts . flWorkingDir , "workdir" , "w" , "" , "Working directory inside the container" )
// Security
2016-05-31 19:49:32 -04:00
flags . Var ( & copts . flCapAdd , "cap-add" , "Add Linux capabilities" )
flags . Var ( & copts . flCapDrop , "cap-drop" , "Drop Linux capabilities" )
2016-06-06 18:25:04 -04:00
flags . BoolVar ( & copts . flPrivileged , "privileged" , false , "Give extended privileges to this container" )
2016-05-31 19:49:32 -04:00
flags . Var ( & copts . flSecurityOpt , "security-opt" , "Security Options" )
2016-06-06 18:25:04 -04:00
flags . StringVar ( & copts . flUsernsMode , "userns" , "" , "User namespace to use" )
// Network and port publishing flag
flags . Var ( & copts . flExtraHosts , "add-host" , "Add a custom host-to-IP mapping (host:ip)" )
flags . Var ( & copts . flDNS , "dns" , "Set custom DNS servers" )
flags . Var ( & copts . flDNSOptions , "dns-opt" , "Set DNS options" )
flags . Var ( & copts . flDNSSearch , "dns-search" , "Set custom DNS search domains" )
flags . Var ( & copts . flExpose , "expose" , "Expose a port or a range of ports" )
flags . StringVar ( & copts . flIPv4Address , "ip" , "" , "Container IPv4 address (e.g. 172.30.100.104)" )
flags . StringVar ( & copts . flIPv6Address , "ip6" , "" , "Container IPv6 address (e.g. 2001:db8::33)" )
flags . Var ( & copts . flLinks , "link" , "Add link to another container" )
flags . Var ( & copts . flLinkLocalIPs , "link-local-ip" , "Container IPv4/IPv6 link-local addresses" )
flags . StringVar ( & copts . flMacAddress , "mac-address" , "" , "Container MAC address (e.g. 92:d0:c6:0a:29:33)" )
flags . VarP ( & copts . flPublish , "publish" , "p" , "Publish a container's port(s) to the host" )
flags . BoolVarP ( & copts . flPublishAll , "publish-all" , "P" , false , "Publish all exposed ports to random ports" )
2016-06-06 19:33:00 -04:00
// We allow for both "--net" and "--network", although the latter is the recommended way.
flags . StringVar ( & copts . flNetMode , "net" , "default" , "Connect a container to a network" )
flags . StringVar ( & copts . flNetMode , "network" , "default" , "Connect a container to a network" )
flags . MarkHidden ( "net" )
// We allow for both "--net-alias" and "--network-alias", although the latter is the recommended way.
flags . Var ( & copts . flAliases , "net-alias" , "Add network-scoped alias for the container" )
flags . Var ( & copts . flAliases , "network-alias" , "Add network-scoped alias for the container" )
flags . MarkHidden ( "net-alias" )
2016-06-06 18:25:04 -04:00
// Logging and storage
2016-07-15 19:52:59 -04:00
flags . StringVar ( & copts . flLoggingDriver , "log-driver" , "" , "Logging driver for the container" )
2016-06-06 18:25:04 -04:00
flags . StringVar ( & copts . flVolumeDriver , "volume-driver" , "" , "Optional volume driver for the container" )
2016-05-31 19:49:32 -04:00
flags . Var ( & copts . flLoggingOpts , "log-opt" , "Log driver options" )
2016-07-15 19:52:59 -04:00
flags . Var ( & copts . flStorageOpt , "storage-opt" , "Storage driver options for the container" )
2016-06-06 18:25:04 -04:00
flags . Var ( & copts . flTmpfs , "tmpfs" , "Mount a tmpfs directory" )
flags . Var ( & copts . flVolumesFrom , "volumes-from" , "Mount volumes from the specified container(s)" )
flags . VarP ( & copts . flVolumes , "volume" , "v" , "Bind mount a volume" )
2016-05-31 19:49:32 -04:00
2016-06-06 18:25:04 -04:00
// Health-checking
flags . StringVar ( & copts . flHealthCmd , "health-cmd" , "" , "Command to run to check health" )
flags . DurationVar ( & copts . flHealthInterval , "health-interval" , 0 , "Time between running the check" )
flags . IntVar ( & copts . flHealthRetries , "health-retries" , 0 , "Consecutive failures needed to report unhealthy" )
flags . DurationVar ( & copts . flHealthTimeout , "health-timeout" , 0 , "Maximum time to allow one check to run" )
flags . BoolVar ( & copts . flNoHealthcheck , "no-healthcheck" , false , "Disable any container-specified HEALTHCHECK" )
// Resource management
flags . Uint16Var ( & copts . flBlkioWeight , "blkio-weight" , 0 , "Block IO (relative weight), between 10 and 1000" )
flags . Var ( & copts . flBlkioWeightDevice , "blkio-weight-device" , "Block IO weight (relative device weight)" )
flags . StringVar ( & copts . flContainerIDFile , "cidfile" , "" , "Write the container ID to the file" )
flags . StringVar ( & copts . flCpusetCpus , "cpuset-cpus" , "" , "CPUs in which to allow execution (0-3, 0,1)" )
flags . StringVar ( & copts . flCpusetMems , "cpuset-mems" , "" , "MEMs in which to allow execution (0-3, 0,1)" )
flags . Int64Var ( & copts . flCPUPercent , "cpu-percent" , 0 , "CPU percent (Windows only)" )
flags . Int64Var ( & copts . flCPUPeriod , "cpu-period" , 0 , "Limit CPU CFS (Completely Fair Scheduler) period" )
flags . Int64Var ( & copts . flCPUQuota , "cpu-quota" , 0 , "Limit CPU CFS (Completely Fair Scheduler) quota" )
flags . Int64VarP ( & copts . flCPUShares , "cpu-shares" , "c" , 0 , "CPU shares (relative weight)" )
flags . Var ( & copts . flDeviceReadBps , "device-read-bps" , "Limit read rate (bytes per second) from a device" )
flags . Var ( & copts . flDeviceReadIOps , "device-read-iops" , "Limit read rate (IO per second) from a device" )
flags . Var ( & copts . flDeviceWriteBps , "device-write-bps" , "Limit write rate (bytes per second) to a device" )
flags . Var ( & copts . flDeviceWriteIOps , "device-write-iops" , "Limit write rate (IO per second) to a device" )
flags . StringVar ( & copts . flIOMaxBandwidth , "io-maxbandwidth" , "" , "Maximum IO bandwidth limit for the system drive (Windows only)" )
flags . Uint64Var ( & copts . flIOMaxIOps , "io-maxiops" , 0 , "Maximum IOps limit for the system drive (Windows only)" )
flags . StringVar ( & copts . flKernelMemory , "kernel-memory" , "" , "Kernel memory limit" )
flags . StringVarP ( & copts . flMemoryString , "memory" , "m" , "" , "Memory limit" )
flags . StringVar ( & copts . flMemoryReservation , "memory-reservation" , "" , "Memory soft limit" )
flags . StringVar ( & copts . flMemorySwap , "memory-swap" , "" , "Swap limit equal to memory plus swap: '-1' to enable unlimited swap" )
flags . Int64Var ( & copts . flSwappiness , "memory-swappiness" , - 1 , "Tune container memory swappiness (0 to 100)" )
flags . BoolVar ( & copts . flOomKillDisable , "oom-kill-disable" , false , "Disable OOM Killer" )
flags . IntVar ( & copts . flOomScoreAdj , "oom-score-adj" , 0 , "Tune host's OOM preferences (-1000 to 1000)" )
flags . Int64Var ( & copts . flPidsLimit , "pids-limit" , 0 , "Tune container pids limit (set -1 for unlimited)" )
// Low-level execution (cgroups, namespaces, ...)
flags . StringVar ( & copts . flCgroupParent , "cgroup-parent" , "" , "Optional parent cgroup for the container" )
flags . StringVar ( & copts . flIpcMode , "ipc" , "" , "IPC namespace to use" )
flags . StringVar ( & copts . flIsolation , "isolation" , "" , "Container isolation technology" )
flags . StringVar ( & copts . flPidMode , "pid" , "" , "PID namespace to use" )
flags . StringVar ( & copts . flShmSize , "shm-size" , "" , "Size of /dev/shm, default value is 64MB" )
flags . StringVar ( & copts . flUTSMode , "uts" , "" , "UTS namespace to use" )
flags . StringVar ( & copts . flRuntime , "runtime" , "" , "Runtime to use for this container" )
2016-05-31 19:49:32 -04:00
return copts
}
// Parse parses the args for the specified command and generates a Config,
2015-07-25 05:11:45 -04:00
// a HostConfig and returns them with the specified command.
// If the specified args are not valid, it will return an error.
2016-05-31 19:49:32 -04:00
func Parse ( flags * pflag . FlagSet , copts * ContainerOptions ) ( * container . Config , * container . HostConfig , * networktypes . NetworkingConfig , error ) {
2014-03-10 09:11:23 -04:00
var (
2016-05-31 19:49:32 -04:00
attachStdin = copts . flAttach . Get ( "stdin" )
attachStdout = copts . flAttach . Get ( "stdout" )
attachStderr = copts . flAttach . Get ( "stderr" )
2014-03-10 09:11:23 -04:00
)
2014-02-11 23:04:39 -05:00
2015-05-05 07:27:07 -04:00
// Validate the input mac address
2016-06-06 18:25:04 -04:00
if copts . flMacAddress != "" {
if _ , err := ValidateMACAddress ( copts . flMacAddress ) ; err != nil {
return nil , nil , nil , fmt . Errorf ( "%s is not a valid mac address" , copts . flMacAddress )
2015-05-05 07:27:07 -04:00
}
2014-07-30 10:51:28 -04:00
}
2016-06-06 18:25:04 -04:00
if copts . flStdin {
2015-07-06 18:24:23 -04:00
attachStdin = true
}
2016-04-05 08:53:04 -04:00
// If -a is not set, attach to stdout and stderr
2016-05-31 19:49:32 -04:00
if copts . flAttach . Len ( ) == 0 {
2014-03-10 09:11:23 -04:00
attachStdout = true
attachStderr = true
2014-02-11 23:04:39 -05:00
}
2015-09-14 08:30:11 -04:00
var err error
2014-02-11 23:04:39 -05:00
var flMemory int64
2016-06-06 18:25:04 -04:00
if copts . flMemoryString != "" {
flMemory , err = units . RAMInBytes ( copts . flMemoryString )
2014-02-11 23:04:39 -05:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2014-02-11 23:04:39 -05:00
}
}
2015-09-23 02:02:45 -04:00
var MemoryReservation int64
2016-06-06 18:25:04 -04:00
if copts . flMemoryReservation != "" {
MemoryReservation , err = units . RAMInBytes ( copts . flMemoryReservation )
2015-09-23 02:02:45 -04:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2015-09-23 02:02:45 -04:00
}
}
2015-08-06 07:55:56 -04:00
var memorySwap int64
2016-06-06 18:25:04 -04:00
if copts . flMemorySwap != "" {
if copts . flMemorySwap == "-1" {
2015-08-06 07:55:56 -04:00
memorySwap = - 1
2015-02-08 21:36:49 -05:00
} else {
2016-06-06 18:25:04 -04:00
memorySwap , err = units . RAMInBytes ( copts . flMemorySwap )
2015-02-08 21:36:49 -05:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2015-02-08 21:36:49 -05:00
}
2014-12-10 19:53:43 -05:00
}
}
2015-08-19 11:56:55 -04:00
var KernelMemory int64
2016-06-06 18:25:04 -04:00
if copts . flKernelMemory != "" {
KernelMemory , err = units . RAMInBytes ( copts . flKernelMemory )
2015-08-19 11:56:55 -04:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2015-08-19 11:56:55 -04:00
}
}
2016-06-06 18:25:04 -04:00
swappiness := copts . flSwappiness
2015-07-20 04:10:10 -04:00
if swappiness != - 1 && ( swappiness < 0 || swappiness > 100 ) {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , fmt . Errorf ( "invalid value: %d. Valid memory swappiness range is 0-100" , swappiness )
2015-07-12 03:46:33 -04:00
}
2015-12-29 15:49:17 -05:00
var shmSize int64
2016-06-06 18:25:04 -04:00
if copts . flShmSize != "" {
shmSize , err = units . RAMInBytes ( copts . flShmSize )
2015-09-09 02:30:56 -04:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2015-09-09 02:30:56 -04:00
}
}
2016-02-24 20:51:46 -05:00
// TODO FIXME units.RAMInBytes should have a uint64 version
var maxIOBandwidth int64
2016-06-06 18:25:04 -04:00
if copts . flIOMaxBandwidth != "" {
maxIOBandwidth , err = units . RAMInBytes ( copts . flIOMaxBandwidth )
2016-02-24 20:51:46 -05:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2016-02-24 20:51:46 -05:00
}
if maxIOBandwidth < 0 {
2016-06-06 18:25:04 -04:00
return nil , nil , nil , fmt . Errorf ( "invalid value: %s. Maximum IO Bandwidth must be positive" , copts . flIOMaxBandwidth )
2016-02-24 20:51:46 -05:00
}
}
2014-02-11 23:04:39 -05:00
var binds [ ] string
// add any bind targets to the list of container volumes
2016-05-31 19:49:32 -04:00
for bind := range copts . flVolumes . GetMap ( ) {
2015-12-22 19:52:27 -05:00
if arr := volumeSplitN ( bind , 2 ) ; len ( arr ) > 1 {
2016-05-31 19:49:32 -04:00
// after creating the bind mount we want to delete it from the copts.flVolumes values because
2014-05-19 18:18:37 -04:00
// we do not want bind mounts being committed to image configs
2014-02-11 23:04:39 -05:00
binds = append ( binds , bind )
2016-05-31 19:49:32 -04:00
copts . flVolumes . Delete ( bind )
2014-02-11 23:04:39 -05:00
}
}
2015-12-13 11:00:39 -05:00
// Can't evaluate options passed into --tmpfs until we actually mount
2015-12-01 13:39:34 -05:00
tmpfs := make ( map [ string ] string )
2016-05-31 19:49:32 -04:00
for _ , t := range copts . flTmpfs . GetAll ( ) {
2015-12-01 13:39:34 -05:00
if arr := strings . SplitN ( t , ":" , 2 ) ; len ( arr ) > 1 {
if _ , _ , err := mount . ParseTmpfsOptions ( arr [ 1 ] ) ; err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2015-12-01 13:39:34 -05:00
}
tmpfs [ arr [ 0 ] ] = arr [ 1 ]
} else {
tmpfs [ arr [ 0 ] ] = ""
}
}
2014-02-11 23:04:39 -05:00
var (
2016-02-29 06:28:37 -05:00
runCmd strslice . StrSlice
entrypoint strslice . StrSlice
2014-02-11 23:04:39 -05:00
)
2016-05-31 19:49:32 -04:00
if len ( copts . Args ) > 0 {
runCmd = strslice . StrSlice ( copts . Args )
2014-02-11 23:04:39 -05:00
}
2016-06-06 18:25:04 -04:00
if copts . flEntrypoint != "" {
entrypoint = strslice . StrSlice { copts . flEntrypoint }
2014-02-11 23:04:39 -05:00
}
2016-05-31 19:49:32 -04:00
ports , portBindings , err := nat . ParsePortSpecs ( copts . flPublish . GetAll ( ) )
2014-02-11 23:04:39 -05:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2014-02-11 23:04:39 -05:00
}
// Merge in exposed ports to the map of published ports
2016-05-31 19:49:32 -04:00
for _ , e := range copts . flExpose . GetAll ( ) {
2014-02-11 23:04:39 -05:00
if strings . Contains ( e , ":" ) {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , fmt . Errorf ( "invalid port format for --expose: %s" , e )
2014-02-11 23:04:39 -05:00
}
2014-09-16 21:08:30 -04:00
//support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
2015-02-17 10:12:02 -05:00
proto , port := nat . SplitProtoPort ( e )
//parse the start and end port and create a sequence of ports to expose
//if expose a port, the start and end port are the same
2015-12-22 19:02:47 -05:00
start , end , err := nat . ParsePortRange ( port )
2015-02-17 10:12:02 -05:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , fmt . Errorf ( "invalid range format for --expose: %s, error: %s" , e , err )
2015-02-17 10:12:02 -05:00
}
for i := start ; i <= end ; i ++ {
2015-07-15 23:45:48 -04:00
p , err := nat . NewPort ( proto , strconv . FormatUint ( i , 10 ) )
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2015-07-15 23:45:48 -04:00
}
2014-09-16 21:08:30 -04:00
if _ , exists := ports [ p ] ; ! exists {
ports [ p ] = struct { } { }
}
2014-02-11 23:04:39 -05:00
}
}
2014-05-31 00:00:47 -04:00
// parse device mappings
2015-12-18 13:36:17 -05:00
deviceMappings := [ ] container . DeviceMapping { }
2016-05-31 19:49:32 -04:00
for _ , device := range copts . flDevices . GetAll ( ) {
2015-07-29 05:08:30 -04:00
deviceMapping , err := ParseDevice ( device )
2014-05-31 00:00:47 -04:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2014-05-31 00:00:47 -04:00
}
deviceMappings = append ( deviceMappings , deviceMapping )
}
2014-02-16 19:24:22 -05:00
// collect all the environment variables for the container
2016-05-31 19:49:32 -04:00
envVariables , err := readKVStrings ( copts . flEnvFile . GetAll ( ) , copts . flEnv . GetAll ( ) )
2015-01-06 19:04:10 -05:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2015-01-06 19:04:10 -05:00
}
// collect all the labels for the container
2016-05-31 19:49:32 -04:00
labels , err := readKVStrings ( copts . flLabelsFile . GetAll ( ) , copts . flLabels . GetAll ( ) )
2015-01-06 19:04:10 -05:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2014-02-16 19:24:22 -05:00
}
2016-06-06 18:25:04 -04:00
ipcMode := container . IpcMode ( copts . flIpcMode )
2014-11-10 16:14:17 -05:00
if ! ipcMode . Valid ( ) {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , fmt . Errorf ( "--ipc: invalid IPC mode" )
2014-11-25 15:10:53 -05:00
}
2016-06-06 18:25:04 -04:00
pidMode := container . PidMode ( copts . flPidMode )
2014-11-25 15:10:53 -05:00
if ! pidMode . Valid ( ) {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , fmt . Errorf ( "--pid: invalid PID mode" )
2014-11-10 16:14:17 -05:00
}
2016-06-06 18:25:04 -04:00
utsMode := container . UTSMode ( copts . flUTSMode )
2015-05-05 18:32:36 -04:00
if ! utsMode . Valid ( ) {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , fmt . Errorf ( "--uts: invalid UTS mode" )
2015-05-05 18:32:36 -04:00
}
2016-06-06 18:25:04 -04:00
usernsMode := container . UsernsMode ( copts . flUsernsMode )
2016-02-08 09:23:24 -05:00
if ! usernsMode . Valid ( ) {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , fmt . Errorf ( "--userns: invalid USER mode" )
2016-02-08 09:23:24 -05:00
}
2016-06-06 18:25:04 -04:00
restartPolicy , err := ParseRestartPolicy ( copts . flRestartPolicy )
2014-08-04 19:14:43 -04:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2014-08-04 19:14:43 -04:00
}
2016-06-06 18:25:04 -04:00
loggingOpts , err := parseLoggingOpts ( copts . flLoggingDriver , copts . flLoggingOpts . GetAll ( ) )
2015-05-04 17:39:48 -04:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2015-05-04 17:39:48 -04:00
}
2016-05-31 19:49:32 -04:00
securityOpts , err := parseSecurityOpts ( copts . flSecurityOpt . GetAll ( ) )
2016-01-04 12:59:26 -05:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2016-01-04 12:59:26 -05:00
}
2016-05-31 19:49:32 -04:00
storageOpts , err := parseStorageOpts ( copts . flStorageOpt . GetAll ( ) )
2016-03-20 00:42:58 -04:00
if err != nil {
2016-05-31 19:49:32 -04:00
return nil , nil , nil , err
2016-03-20 00:42:58 -04:00
}
2016-04-18 05:48:13 -04:00
// Healthcheck
var healthConfig * container . HealthConfig
2016-06-06 18:25:04 -04:00
haveHealthSettings := copts . flHealthCmd != "" ||
copts . flHealthInterval != 0 ||
copts . flHealthTimeout != 0 ||
copts . flHealthRetries != 0
if copts . flNoHealthcheck {
2016-04-18 05:48:13 -04:00
if haveHealthSettings {
2016-06-01 01:19:13 -04:00
return nil , nil , nil , fmt . Errorf ( "--no-healthcheck conflicts with --health-* options" )
2016-04-18 05:48:13 -04:00
}
test := strslice . StrSlice { "NONE" }
healthConfig = & container . HealthConfig { Test : test }
} else if haveHealthSettings {
var probe strslice . StrSlice
2016-06-06 18:25:04 -04:00
if copts . flHealthCmd != "" {
args := [ ] string { "CMD-SHELL" , copts . flHealthCmd }
2016-04-18 05:48:13 -04:00
probe = strslice . StrSlice ( args )
}
2016-06-06 18:25:04 -04:00
if copts . flHealthInterval < 0 {
2016-06-01 01:19:13 -04:00
return nil , nil , nil , fmt . Errorf ( "--health-interval cannot be negative" )
2016-04-18 05:48:13 -04:00
}
2016-06-06 18:25:04 -04:00
if copts . flHealthTimeout < 0 {
2016-06-01 01:19:13 -04:00
return nil , nil , nil , fmt . Errorf ( "--health-timeout cannot be negative" )
2016-04-18 05:48:13 -04:00
}
healthConfig = & container . HealthConfig {
Test : probe ,
2016-06-06 18:25:04 -04:00
Interval : copts . flHealthInterval ,
Timeout : copts . flHealthTimeout ,
Retries : copts . flHealthRetries ,
2016-04-18 05:48:13 -04:00
}
}
2015-12-18 13:36:17 -05:00
resources := container . Resources {
2016-06-06 18:25:04 -04:00
CgroupParent : copts . flCgroupParent ,
2015-07-08 07:06:48 -04:00
Memory : flMemory ,
MemoryReservation : MemoryReservation ,
MemorySwap : memorySwap ,
2016-06-06 18:25:04 -04:00
MemorySwappiness : & copts . flSwappiness ,
2015-07-08 07:06:48 -04:00
KernelMemory : KernelMemory ,
2016-06-06 18:25:04 -04:00
OomKillDisable : & copts . flOomKillDisable ,
CPUPercent : copts . flCPUPercent ,
CPUShares : copts . flCPUShares ,
CPUPeriod : copts . flCPUPeriod ,
CpusetCpus : copts . flCpusetCpus ,
CpusetMems : copts . flCpusetMems ,
CPUQuota : copts . flCPUQuota ,
PidsLimit : copts . flPidsLimit ,
BlkioWeight : copts . flBlkioWeight ,
2016-05-31 19:49:32 -04:00
BlkioWeightDevice : copts . flBlkioWeightDevice . GetList ( ) ,
BlkioDeviceReadBps : copts . flDeviceReadBps . GetList ( ) ,
BlkioDeviceWriteBps : copts . flDeviceWriteBps . GetList ( ) ,
BlkioDeviceReadIOps : copts . flDeviceReadIOps . GetList ( ) ,
BlkioDeviceWriteIOps : copts . flDeviceWriteIOps . GetList ( ) ,
2016-06-06 18:25:04 -04:00
IOMaximumIOps : copts . flIOMaxIOps ,
2016-02-24 20:51:46 -05:00
IOMaximumBandwidth : uint64 ( maxIOBandwidth ) ,
2016-05-31 19:49:32 -04:00
Ulimits : copts . flUlimits . GetList ( ) ,
2015-07-08 07:06:48 -04:00
Devices : deviceMappings ,
2015-11-18 14:03:08 -05:00
}
2015-12-18 13:36:17 -05:00
config := & container . Config {
2016-06-06 18:25:04 -04:00
Hostname : copts . flHostname ,
2015-11-09 09:37:24 -05:00
ExposedPorts : ports ,
2016-06-06 18:25:04 -04:00
User : copts . flUser ,
Tty : copts . flTty ,
2015-11-09 09:37:24 -05:00
// TODO: deprecated, it comes from -n, --networking
// it's still needed internally to set the network to disabled
// if e.g. bridge is none in daemon opts, and in inspect
NetworkDisabled : false ,
2016-06-06 18:25:04 -04:00
OpenStdin : copts . flStdin ,
2014-03-10 09:11:23 -04:00
AttachStdin : attachStdin ,
AttachStdout : attachStdout ,
AttachStderr : attachStderr ,
2014-02-16 19:24:22 -05:00
Env : envVariables ,
2014-02-11 23:04:39 -05:00
Cmd : runCmd ,
2016-05-31 19:49:32 -04:00
Image : copts . Image ,
Volumes : copts . flVolumes . GetMap ( ) ,
2016-06-06 18:25:04 -04:00
MacAddress : copts . flMacAddress ,
2014-02-11 23:04:39 -05:00
Entrypoint : entrypoint ,
2016-06-06 18:25:04 -04:00
WorkingDir : copts . flWorkingDir ,
2014-11-14 13:59:14 -05:00
Labels : ConvertKVStringsToMap ( labels ) ,
2016-04-18 05:48:13 -04:00
Healthcheck : healthConfig ,
2016-02-12 17:56:40 -05:00
}
2016-05-31 19:49:32 -04:00
if flags . Changed ( "stop-signal" ) {
2016-06-06 18:25:04 -04:00
config . StopSignal = copts . flStopSignal
2014-02-11 23:04:39 -05:00
}
2015-12-18 13:36:17 -05:00
hostConfig := & container . HostConfig {
2015-11-18 14:03:08 -05:00
Binds : binds ,
2016-06-06 18:25:04 -04:00
ContainerIDFile : copts . flContainerIDFile ,
OomScoreAdj : copts . flOomScoreAdj ,
Privileged : copts . flPrivileged ,
2015-11-18 14:03:08 -05:00
PortBindings : portBindings ,
2016-05-31 19:49:32 -04:00
Links : copts . flLinks . GetAll ( ) ,
2016-06-06 18:25:04 -04:00
PublishAllPorts : copts . flPublishAll ,
2015-11-06 17:22:48 -05:00
// Make sure the dns fields are never nil.
// New containers don't ever have those fields nil,
// but pre created containers can still have those nil values.
// See https://github.com/docker/docker/pull/17779
// for a more detailed explanation on why we don't want that.
2016-05-31 19:49:32 -04:00
DNS : copts . flDNS . GetAllOrEmpty ( ) ,
DNSSearch : copts . flDNSSearch . GetAllOrEmpty ( ) ,
DNSOptions : copts . flDNSOptions . GetAllOrEmpty ( ) ,
ExtraHosts : copts . flExtraHosts . GetAll ( ) ,
VolumesFrom : copts . flVolumesFrom . GetAll ( ) ,
2016-06-06 18:25:04 -04:00
NetworkMode : container . NetworkMode ( copts . flNetMode ) ,
2015-11-06 17:22:48 -05:00
IpcMode : ipcMode ,
PidMode : pidMode ,
UTSMode : utsMode ,
2016-02-08 09:23:24 -05:00
UsernsMode : usernsMode ,
2016-05-31 19:49:32 -04:00
CapAdd : strslice . StrSlice ( copts . flCapAdd . GetAll ( ) ) ,
CapDrop : strslice . StrSlice ( copts . flCapDrop . GetAll ( ) ) ,
GroupAdd : copts . flGroupAdd . GetAll ( ) ,
2015-11-06 17:22:48 -05:00
RestartPolicy : restartPolicy ,
2016-01-04 12:59:26 -05:00
SecurityOpt : securityOpts ,
2016-03-20 00:42:58 -04:00
StorageOpt : storageOpts ,
2016-06-06 18:25:04 -04:00
ReadonlyRootfs : copts . flReadonlyRootfs ,
LogConfig : container . LogConfig { Type : copts . flLoggingDriver , Config : loggingOpts } ,
VolumeDriver : copts . flVolumeDriver ,
Isolation : container . Isolation ( copts . flIsolation ) ,
2015-12-29 15:49:17 -05:00
ShmSize : shmSize ,
2015-11-18 14:03:08 -05:00
Resources : resources ,
2015-12-01 13:39:34 -05:00
Tmpfs : tmpfs ,
2016-05-31 19:49:32 -04:00
Sysctls : copts . flSysctls . GetAll ( ) ,
2016-06-06 18:25:04 -04:00
Runtime : copts . flRuntime ,
2014-02-11 23:04:39 -05:00
}
// When allocating stdin in attached mode, close stdin at client disconnect
if config . OpenStdin && config . AttachStdin {
config . StdinOnce = true
}
2016-01-07 19:18:34 -05:00
2016-01-05 14:20:47 -05:00
networkingConfig := & networktypes . NetworkingConfig {
EndpointsConfig : make ( map [ string ] * networktypes . EndpointSettings ) ,
}
2016-06-06 18:25:04 -04:00
if copts . flIPv4Address != "" || copts . flIPv6Address != "" || copts . flLinkLocalIPs . Len ( ) > 0 {
2016-06-09 18:10:59 -04:00
epConfig := & networktypes . EndpointSettings { }
networkingConfig . EndpointsConfig [ string ( hostConfig . NetworkMode ) ] = epConfig
epConfig . IPAMConfig = & networktypes . EndpointIPAMConfig {
2016-06-06 18:25:04 -04:00
IPv4Address : copts . flIPv4Address ,
IPv6Address : copts . flIPv6Address ,
2016-06-09 18:10:59 -04:00
}
if copts . flLinkLocalIPs . Len ( ) > 0 {
epConfig . IPAMConfig . LinkLocalIPs = make ( [ ] string , copts . flLinkLocalIPs . Len ( ) )
copy ( epConfig . IPAMConfig . LinkLocalIPs , copts . flLinkLocalIPs . GetAll ( ) )
2016-01-07 19:18:34 -05:00
}
}
2016-01-05 14:20:47 -05:00
if hostConfig . NetworkMode . IsUserDefined ( ) && len ( hostConfig . Links ) > 0 {
epConfig := networkingConfig . EndpointsConfig [ string ( hostConfig . NetworkMode ) ]
if epConfig == nil {
epConfig = & networktypes . EndpointSettings { }
}
epConfig . Links = make ( [ ] string , len ( hostConfig . Links ) )
copy ( epConfig . Links , hostConfig . Links )
networkingConfig . EndpointsConfig [ string ( hostConfig . NetworkMode ) ] = epConfig
}
2016-05-31 19:49:32 -04:00
if copts . flAliases . Len ( ) > 0 {
2016-01-08 08:45:56 -05:00
epConfig := networkingConfig . EndpointsConfig [ string ( hostConfig . NetworkMode ) ]
if epConfig == nil {
epConfig = & networktypes . EndpointSettings { }
}
2016-05-31 19:49:32 -04:00
epConfig . Aliases = make ( [ ] string , copts . flAliases . Len ( ) )
copy ( epConfig . Aliases , copts . flAliases . GetAll ( ) )
2016-01-08 08:45:56 -05:00
networkingConfig . EndpointsConfig [ string ( hostConfig . NetworkMode ) ] = epConfig
}
2016-05-31 19:49:32 -04:00
return config , hostConfig , networkingConfig , nil
2014-02-11 23:04:39 -05:00
}
2016-04-05 08:53:04 -04:00
// reads a file of line terminated key=value pairs, and overrides any keys
// present in the file with additional pairs specified in the override parameter
2015-01-06 19:04:10 -05:00
func readKVStrings ( files [ ] string , override [ ] string ) ( [ ] string , error ) {
envVariables := [ ] string { }
for _ , ef := range files {
2015-12-29 11:28:21 -05:00
parsedVars , err := ParseEnvFile ( ef )
2015-01-06 19:04:10 -05:00
if err != nil {
return nil , err
}
envVariables = append ( envVariables , parsedVars ... )
}
// parse the '-e' and '--env' after, to allow override
envVariables = append ( envVariables , override ... )
return envVariables , nil
}
2014-11-14 13:59:14 -05:00
// ConvertKVStringsToMap converts ["key=value"] to {"key":"value"}
func ConvertKVStringsToMap ( values [ ] string ) map [ string ] string {
2015-01-06 19:04:10 -05:00
result := make ( map [ string ] string , len ( values ) )
for _ , value := range values {
kv := strings . SplitN ( value , "=" , 2 )
if len ( kv ) == 1 {
result [ kv [ 0 ] ] = ""
} else {
result [ kv [ 0 ] ] = kv [ 1 ]
}
}
return result
}
2015-05-04 17:39:48 -04:00
func parseLoggingOpts ( loggingDriver string , loggingOpts [ ] string ) ( map [ string ] string , error ) {
2014-11-14 13:59:14 -05:00
loggingOptsMap := ConvertKVStringsToMap ( loggingOpts )
2015-05-04 17:39:48 -04:00
if loggingDriver == "none" && len ( loggingOpts ) > 0 {
2016-02-18 03:26:47 -05:00
return map [ string ] string { } , fmt . Errorf ( "invalid logging opts for driver %s" , loggingDriver )
2015-05-04 17:39:48 -04:00
}
return loggingOptsMap , nil
}
2016-01-04 12:59:26 -05:00
// takes a local seccomp daemon, reads the file contents for sending to the daemon
func parseSecurityOpts ( securityOpts [ ] string ) ( [ ] string , error ) {
for key , opt := range securityOpts {
2016-03-15 18:34:29 -04:00
con := strings . SplitN ( opt , "=" , 2 )
2016-02-22 00:31:21 -05:00
if len ( con ) == 1 && con [ 0 ] != "no-new-privileges" {
2016-03-15 18:34:29 -04:00
if strings . Index ( opt , ":" ) != - 1 {
con = strings . SplitN ( opt , ":" , 2 )
} else {
return securityOpts , fmt . Errorf ( "Invalid --security-opt: %q" , opt )
}
2016-01-04 12:59:26 -05:00
}
if con [ 0 ] == "seccomp" && con [ 1 ] != "unconfined" {
f , err := ioutil . ReadFile ( con [ 1 ] )
if err != nil {
2016-02-18 03:26:47 -05:00
return securityOpts , fmt . Errorf ( "opening seccomp profile (%s) failed: %v" , con [ 1 ] , err )
2016-01-04 12:59:26 -05:00
}
b := bytes . NewBuffer ( nil )
if err := json . Compact ( b , f ) ; err != nil {
2016-02-18 03:26:47 -05:00
return securityOpts , fmt . Errorf ( "compacting json for seccomp profile (%s) failed: %v" , con [ 1 ] , err )
2016-01-04 12:59:26 -05:00
}
2016-03-15 18:34:29 -04:00
securityOpts [ key ] = fmt . Sprintf ( "seccomp=%s" , b . Bytes ( ) )
2016-01-04 12:59:26 -05:00
}
}
return securityOpts , nil
}
2016-04-05 08:53:04 -04:00
// parses storage options per container into a map
2016-03-20 00:42:58 -04:00
func parseStorageOpts ( storageOpts [ ] string ) ( map [ string ] string , error ) {
m := make ( map [ string ] string )
for _ , option := range storageOpts {
if strings . Contains ( option , "=" ) {
opt := strings . SplitN ( option , "=" , 2 )
m [ opt [ 0 ] ] = opt [ 1 ]
} else {
return nil , fmt . Errorf ( "Invalid storage option." )
}
}
return m , nil
}
2015-04-24 15:23:54 -04:00
// ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect
2015-12-18 13:36:17 -05:00
func ParseRestartPolicy ( policy string ) ( container . RestartPolicy , error ) {
p := container . RestartPolicy { }
2014-08-04 19:14:43 -04:00
if policy == "" {
return p , nil
}
var (
parts = strings . Split ( policy , ":" )
name = parts [ 0 ]
)
2015-01-08 04:15:55 -05:00
p . Name = name
2014-08-04 19:14:43 -04:00
switch name {
2015-08-05 17:09:08 -04:00
case "always" , "unless-stopped" :
2015-07-03 05:33:33 -04:00
if len ( parts ) > 1 {
2015-08-05 17:09:08 -04:00
return p , fmt . Errorf ( "maximum restart count not valid with restart policy of \"%s\"" , name )
2014-08-04 21:20:53 -04:00
}
case "no" :
// do nothing
case "on-failure" :
2015-07-03 05:33:33 -04:00
if len ( parts ) > 2 {
return p , fmt . Errorf ( "restart count format is not valid, usage: 'on-failure:N' or 'on-failure'" )
}
2014-08-04 19:14:43 -04:00
if len ( parts ) == 2 {
count , err := strconv . Atoi ( parts [ 1 ] )
if err != nil {
return p , err
}
p . MaximumRetryCount = count
}
default :
return p , fmt . Errorf ( "invalid restart policy %s" , name )
}
return p , nil
}
2015-12-18 13:36:17 -05:00
// ParseDevice parses a device mapping string to a container.DeviceMapping struct
func ParseDevice ( device string ) ( container . DeviceMapping , error ) {
2014-05-31 00:00:47 -04:00
src := ""
dst := ""
permissions := "rwm"
arr := strings . Split ( device , ":" )
switch len ( arr ) {
case 3 :
permissions = arr [ 2 ]
fallthrough
case 2 :
2015-12-15 21:36:35 -05:00
if ValidDeviceMode ( arr [ 1 ] ) {
2015-08-24 05:57:12 -04:00
permissions = arr [ 1 ]
} else {
dst = arr [ 1 ]
}
2014-05-31 00:00:47 -04:00
fallthrough
case 1 :
src = arr [ 0 ]
default :
2016-02-18 03:26:47 -05:00
return container . DeviceMapping { } , fmt . Errorf ( "invalid device specification: %s" , device )
2014-05-31 00:00:47 -04:00
}
if dst == "" {
dst = src
}
2015-12-18 13:36:17 -05:00
deviceMapping := container . DeviceMapping {
2014-05-31 00:00:47 -04:00
PathOnHost : src ,
PathInContainer : dst ,
CgroupPermissions : permissions ,
}
return deviceMapping , nil
}
2015-12-15 21:36:35 -05:00
// ParseLink parses and validates the specified string as a link format (name:alias)
func ParseLink ( val string ) ( string , string , error ) {
if val == "" {
return "" , "" , fmt . Errorf ( "empty string specified for links" )
}
arr := strings . Split ( val , ":" )
if len ( arr ) > 2 {
return "" , "" , fmt . Errorf ( "bad format for links: %s" , val )
}
if len ( arr ) == 1 {
return val , val , nil
}
2016-04-05 08:53:04 -04:00
// This is kept because we can actually get a HostConfig with links
2015-12-15 21:36:35 -05:00
// from an already created container and the format is not `foo:bar`
// but `/foo:/c1/bar`
if strings . HasPrefix ( arr [ 0 ] , "/" ) {
_ , alias := path . Split ( arr [ 1 ] )
return arr [ 0 ] [ 1 : ] , alias , nil
}
return arr [ 0 ] , arr [ 1 ] , nil
}
// ValidateLink validates that the specified string has a valid link format (containerName:alias).
func ValidateLink ( val string ) ( string , error ) {
if _ , _ , err := ParseLink ( val ) ; err != nil {
return val , err
}
return val , nil
}
// ValidDeviceMode checks if the mode for device is valid or not.
// Valid mode is a composition of r (read), w (write), and m (mknod).
func ValidDeviceMode ( mode string ) bool {
var legalDeviceMode = map [ rune ] bool {
'r' : true ,
'w' : true ,
'm' : true ,
}
if mode == "" {
return false
}
for _ , c := range mode {
if ! legalDeviceMode [ c ] {
return false
}
legalDeviceMode [ c ] = false
}
return true
}
// ValidateDevice validates a path for devices
// It will make sure 'val' is in the form:
// [host-dir:]container-path[:mode]
// It also validates the device mode.
func ValidateDevice ( val string ) ( string , error ) {
return validatePath ( val , ValidDeviceMode )
}
func validatePath ( val string , validator func ( string ) bool ) ( string , error ) {
var containerPath string
var mode string
if strings . Count ( val , ":" ) > 2 {
return val , fmt . Errorf ( "bad format for path: %s" , val )
}
split := strings . SplitN ( val , ":" , 3 )
if split [ 0 ] == "" {
return val , fmt . Errorf ( "bad format for path: %s" , val )
}
switch len ( split ) {
case 1 :
containerPath = split [ 0 ]
val = path . Clean ( containerPath )
case 2 :
if isValid := validator ( split [ 1 ] ) ; isValid {
containerPath = split [ 0 ]
mode = split [ 1 ]
val = fmt . Sprintf ( "%s:%s" , path . Clean ( containerPath ) , mode )
} else {
containerPath = split [ 1 ]
val = fmt . Sprintf ( "%s:%s" , split [ 0 ] , path . Clean ( containerPath ) )
}
case 3 :
containerPath = split [ 1 ]
mode = split [ 2 ]
if isValid := validator ( split [ 2 ] ) ; ! isValid {
return val , fmt . Errorf ( "bad mode specified: %s" , mode )
}
val = fmt . Sprintf ( "%s:%s:%s" , split [ 0 ] , containerPath , mode )
}
if ! path . IsAbs ( containerPath ) {
return val , fmt . Errorf ( "%s is not an absolute path" , containerPath )
}
return val , nil
}
2015-12-22 19:52:27 -05:00
2016-01-24 12:02:21 -05:00
// volumeSplitN splits raw into a maximum of n parts, separated by a separator colon.
2016-03-10 20:06:53 -05:00
// A separator colon is the last `:` character in the regex `[:\\]?[a-zA-Z]:` (note `\\` is `\` escaped).
// In Windows driver letter appears in two situations:
// a. `^[a-zA-Z]:` (A colon followed by `^[a-zA-Z]:` is OK as colon is the separator in volume option)
// b. A string in the format like `\\?\C:\Windows\...` (UNC).
// Therefore, a driver letter can only follow either a `:` or `\\`
// This allows to correctly split strings such as `C:\foo:D:\:rw` or `/tmp/q:/foo`.
2015-12-22 19:52:27 -05:00
func volumeSplitN ( raw string , n int ) [ ] string {
var array [ ] string
if len ( raw ) == 0 || raw [ 0 ] == ':' {
// invalid
return nil
}
// numberOfParts counts the number of parts separated by a separator colon
numberOfParts := 0
// left represents the left-most cursor in raw, updated at every `:` character considered as a separator.
left := 0
// right represents the right-most cursor in raw incremented with the loop. Note this
// starts at index 1 as index 0 is already handle above as a special case.
for right := 1 ; right < len ( raw ) ; right ++ {
// stop parsing if reached maximum number of parts
if n >= 0 && numberOfParts >= n {
break
}
if raw [ right ] != ':' {
continue
}
potentialDriveLetter := raw [ right - 1 ]
if ( potentialDriveLetter >= 'A' && potentialDriveLetter <= 'Z' ) || ( potentialDriveLetter >= 'a' && potentialDriveLetter <= 'z' ) {
if right > 1 {
beforePotentialDriveLetter := raw [ right - 2 ]
2016-03-10 20:06:53 -05:00
// Only `:` or `\\` are checked (`/` could fall into the case of `/tmp/q:/foo`)
if beforePotentialDriveLetter != ':' && beforePotentialDriveLetter != '\\' {
2015-12-22 19:52:27 -05:00
// e.g. `C:` is not preceded by any delimiter, therefore it was not a drive letter but a path ending with `C:`.
array = append ( array , raw [ left : right ] )
left = right + 1
numberOfParts ++
}
// else, `C:` is considered as a drive letter and not as a delimiter, so we continue parsing.
}
// if right == 1, then `C:` is the beginning of the raw string, therefore `:` is again not considered a delimiter and we continue parsing.
} else {
// if `:` is not preceded by a potential drive letter, then consider it as a delimiter.
array = append ( array , raw [ left : right ] )
left = right + 1
numberOfParts ++
}
}
// need to take care of the last part
if left < len ( raw ) {
if n >= 0 && numberOfParts >= n {
// if the maximum number of parts is reached, just append the rest to the last part
// left-1 is at the last `:` that needs to be included since not considered a separator.
array [ n - 1 ] += raw [ left - 1 : ]
} else {
array = append ( array , raw [ left : ] )
}
}
return array
}