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