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