github.com/codemac/docker@v1.2.1-0.20150518222241-6a18412d5b9c/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 cmd.Require(flag.Min, 1) 104 105 if err := cmd.ParseFlags(args, true); err != nil { 106 return nil, nil, cmd, err 107 } 108 109 var ( 110 attachStdin = flAttach.Get("stdin") 111 attachStdout = flAttach.Get("stdout") 112 attachStderr = flAttach.Get("stderr") 113 ) 114 115 netMode, err := parseNetMode(*flNetMode) 116 if err != nil { 117 return nil, nil, cmd, fmt.Errorf("--net: invalid net mode: %v", err) 118 } 119 120 if (netMode.IsHost() || netMode.IsContainer()) && *flHostname != "" { 121 return nil, nil, cmd, ErrConflictNetworkHostname 122 } 123 124 if netMode.IsHost() && flLinks.Len() > 0 { 125 return nil, nil, cmd, ErrConflictHostNetworkAndLinks 126 } 127 128 if netMode.IsContainer() && flLinks.Len() > 0 { 129 return nil, nil, cmd, ErrConflictContainerNetworkAndLinks 130 } 131 132 if (netMode.IsHost() || netMode.IsContainer()) && flDns.Len() > 0 { 133 return nil, nil, cmd, ErrConflictNetworkAndDns 134 } 135 136 if (netMode.IsContainer() || netMode.IsHost()) && flExtraHosts.Len() > 0 { 137 return nil, nil, cmd, ErrConflictNetworkHosts 138 } 139 140 if (netMode.IsContainer() || netMode.IsHost()) && *flMacAddress != "" { 141 return nil, nil, cmd, ErrConflictContainerNetworkAndMac 142 } 143 144 // Validate the input mac address 145 if *flMacAddress != "" { 146 if _, err := opts.ValidateMACAddress(*flMacAddress); err != nil { 147 return nil, nil, cmd, fmt.Errorf("%s is not a valid mac address", *flMacAddress) 148 } 149 } 150 151 // If neither -d or -a are set, attach to everything by default 152 if flAttach.Len() == 0 { 153 attachStdout = true 154 attachStderr = true 155 if *flStdin { 156 attachStdin = true 157 } 158 } 159 160 var flMemory int64 161 if *flMemoryString != "" { 162 parsedMemory, err := units.RAMInBytes(*flMemoryString) 163 if err != nil { 164 return nil, nil, cmd, err 165 } 166 flMemory = parsedMemory 167 } 168 169 var MemorySwap int64 170 if *flMemorySwap != "" { 171 if *flMemorySwap == "-1" { 172 MemorySwap = -1 173 } else { 174 parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap) 175 if err != nil { 176 return nil, nil, cmd, err 177 } 178 MemorySwap = parsedMemorySwap 179 } 180 } 181 182 var binds []string 183 // add any bind targets to the list of container volumes 184 for bind := range flVolumes.GetMap() { 185 if arr := strings.Split(bind, ":"); len(arr) > 1 { 186 if arr[1] == "/" { 187 return nil, nil, cmd, fmt.Errorf("Invalid bind mount: destination can't be '/'") 188 } 189 // after creating the bind mount we want to delete it from the flVolumes values because 190 // we do not want bind mounts being committed to image configs 191 binds = append(binds, bind) 192 flVolumes.Delete(bind) 193 } else if bind == "/" { 194 return nil, nil, cmd, fmt.Errorf("Invalid volume: path can't be '/'") 195 } 196 } 197 198 var ( 199 parsedArgs = cmd.Args() 200 runCmd *Command 201 entrypoint *Entrypoint 202 image = cmd.Arg(0) 203 ) 204 if len(parsedArgs) > 1 { 205 runCmd = NewCommand(parsedArgs[1:]...) 206 } 207 if *flEntrypoint != "" { 208 entrypoint = NewEntrypoint(*flEntrypoint) 209 } 210 211 lc, err := parseKeyValueOpts(flLxcOpts) 212 if err != nil { 213 return nil, nil, cmd, err 214 } 215 lxcConf := NewLxcConfig(lc) 216 217 var ( 218 domainname string 219 hostname = *flHostname 220 parts = strings.SplitN(hostname, ".", 2) 221 ) 222 if len(parts) > 1 { 223 hostname = parts[0] 224 domainname = parts[1] 225 } 226 227 ports, portBindings, err := nat.ParsePortSpecs(flPublish.GetAll()) 228 if err != nil { 229 return nil, nil, cmd, err 230 } 231 232 // Merge in exposed ports to the map of published ports 233 for _, e := range flExpose.GetAll() { 234 if strings.Contains(e, ":") { 235 return nil, nil, cmd, fmt.Errorf("Invalid port format for --expose: %s", e) 236 } 237 //support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>] 238 proto, port := nat.SplitProtoPort(e) 239 //parse the start and end port and create a sequence of ports to expose 240 //if expose a port, the start and end port are the same 241 start, end, err := parsers.ParsePortRange(port) 242 if err != nil { 243 return nil, nil, cmd, fmt.Errorf("Invalid range format for --expose: %s, error: %s", e, err) 244 } 245 for i := start; i <= end; i++ { 246 p := nat.NewPort(proto, strconv.FormatUint(i, 10)) 247 if _, exists := ports[p]; !exists { 248 ports[p] = struct{}{} 249 } 250 } 251 } 252 253 // parse device mappings 254 deviceMappings := []DeviceMapping{} 255 for _, device := range flDevices.GetAll() { 256 deviceMapping, err := ParseDevice(device) 257 if err != nil { 258 return nil, nil, cmd, err 259 } 260 deviceMappings = append(deviceMappings, deviceMapping) 261 } 262 263 // collect all the environment variables for the container 264 envVariables, err := readKVStrings(flEnvFile.GetAll(), flEnv.GetAll()) 265 if err != nil { 266 return nil, nil, cmd, err 267 } 268 269 // collect all the labels for the container 270 labels, err := readKVStrings(flLabelsFile.GetAll(), flLabels.GetAll()) 271 if err != nil { 272 return nil, nil, cmd, err 273 } 274 275 ipcMode := IpcMode(*flIpcMode) 276 if !ipcMode.Valid() { 277 return nil, nil, cmd, fmt.Errorf("--ipc: invalid IPC mode") 278 } 279 280 pidMode := PidMode(*flPidMode) 281 if !pidMode.Valid() { 282 return nil, nil, cmd, fmt.Errorf("--pid: invalid PID mode") 283 } 284 285 utsMode := UTSMode(*flUTSMode) 286 if !utsMode.Valid() { 287 return nil, nil, cmd, fmt.Errorf("--uts: invalid UTS mode") 288 } 289 290 restartPolicy, err := ParseRestartPolicy(*flRestartPolicy) 291 if err != nil { 292 return nil, nil, cmd, err 293 } 294 295 loggingOpts, err := parseLoggingOpts(*flLoggingDriver, flLoggingOpts.GetAll()) 296 if err != nil { 297 return nil, nil, cmd, err 298 } 299 300 config := &Config{ 301 Hostname: hostname, 302 Domainname: domainname, 303 PortSpecs: nil, // Deprecated 304 ExposedPorts: ports, 305 User: *flUser, 306 Tty: *flTty, 307 NetworkDisabled: !*flNetwork, 308 OpenStdin: *flStdin, 309 AttachStdin: attachStdin, 310 AttachStdout: attachStdout, 311 AttachStderr: attachStderr, 312 Env: envVariables, 313 Cmd: runCmd, 314 Image: image, 315 Volumes: flVolumes.GetMap(), 316 MacAddress: *flMacAddress, 317 Entrypoint: entrypoint, 318 WorkingDir: *flWorkingDir, 319 Labels: convertKVStringsToMap(labels), 320 } 321 322 hostConfig := &HostConfig{ 323 Binds: binds, 324 ContainerIDFile: *flContainerIDFile, 325 LxcConf: lxcConf, 326 Memory: flMemory, 327 MemorySwap: MemorySwap, 328 CpuShares: *flCpuShares, 329 CpuPeriod: *flCpuPeriod, 330 CpusetCpus: *flCpusetCpus, 331 CpusetMems: *flCpusetMems, 332 CpuQuota: *flCpuQuota, 333 BlkioWeight: *flBlkioWeight, 334 OomKillDisable: *flOomKillDisable, 335 Privileged: *flPrivileged, 336 PortBindings: portBindings, 337 Links: flLinks.GetAll(), 338 PublishAllPorts: *flPublishAll, 339 Dns: flDns.GetAll(), 340 DnsSearch: flDnsSearch.GetAll(), 341 ExtraHosts: flExtraHosts.GetAll(), 342 VolumesFrom: flVolumesFrom.GetAll(), 343 NetworkMode: netMode, 344 IpcMode: ipcMode, 345 PidMode: pidMode, 346 UTSMode: utsMode, 347 Devices: deviceMappings, 348 CapAdd: flCapAdd.GetAll(), 349 CapDrop: flCapDrop.GetAll(), 350 RestartPolicy: restartPolicy, 351 SecurityOpt: flSecurityOpt.GetAll(), 352 ReadonlyRootfs: *flReadonlyRootfs, 353 Ulimits: flUlimits.GetList(), 354 LogConfig: LogConfig{Type: *flLoggingDriver, Config: loggingOpts}, 355 CgroupParent: *flCgroupParent, 356 } 357 358 // When allocating stdin in attached mode, close stdin at client disconnect 359 if config.OpenStdin && config.AttachStdin { 360 config.StdinOnce = true 361 } 362 return config, hostConfig, cmd, nil 363 } 364 365 // reads a file of line terminated key=value pairs and override that with override parameter 366 func readKVStrings(files []string, override []string) ([]string, error) { 367 envVariables := []string{} 368 for _, ef := range files { 369 parsedVars, err := opts.ParseEnvFile(ef) 370 if err != nil { 371 return nil, err 372 } 373 envVariables = append(envVariables, parsedVars...) 374 } 375 // parse the '-e' and '--env' after, to allow override 376 envVariables = append(envVariables, override...) 377 378 return envVariables, nil 379 } 380 381 // converts ["key=value"] to {"key":"value"} 382 func convertKVStringsToMap(values []string) map[string]string { 383 result := make(map[string]string, len(values)) 384 for _, value := range values { 385 kv := strings.SplitN(value, "=", 2) 386 if len(kv) == 1 { 387 result[kv[0]] = "" 388 } else { 389 result[kv[0]] = kv[1] 390 } 391 } 392 393 return result 394 } 395 396 func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) { 397 loggingOptsMap := convertKVStringsToMap(loggingOpts) 398 if loggingDriver == "none" && len(loggingOpts) > 0 { 399 return map[string]string{}, fmt.Errorf("Invalid logging opts for driver %s", loggingDriver) 400 } 401 //TODO - validation step 402 return loggingOptsMap, nil 403 } 404 405 // ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect 406 func ParseRestartPolicy(policy string) (RestartPolicy, error) { 407 p := RestartPolicy{} 408 409 if policy == "" { 410 return p, nil 411 } 412 413 var ( 414 parts = strings.Split(policy, ":") 415 name = parts[0] 416 ) 417 418 p.Name = name 419 switch name { 420 case "always": 421 if len(parts) == 2 { 422 return p, fmt.Errorf("maximum restart count not valid with restart policy of \"always\"") 423 } 424 case "no": 425 // do nothing 426 case "on-failure": 427 if len(parts) == 2 { 428 count, err := strconv.Atoi(parts[1]) 429 if err != nil { 430 return p, err 431 } 432 433 p.MaximumRetryCount = count 434 } 435 default: 436 return p, fmt.Errorf("invalid restart policy %s", name) 437 } 438 439 return p, nil 440 } 441 442 // options will come in the format of name.key=value or name.option 443 func parseDriverOpts(opts opts.ListOpts) (map[string][]string, error) { 444 out := make(map[string][]string, len(opts.GetAll())) 445 for _, o := range opts.GetAll() { 446 parts := strings.SplitN(o, ".", 2) 447 if len(parts) < 2 { 448 return nil, fmt.Errorf("invalid opt format %s", o) 449 } else if strings.TrimSpace(parts[0]) == "" { 450 return nil, fmt.Errorf("key cannot be empty %s", o) 451 } 452 values, exists := out[parts[0]] 453 if !exists { 454 values = []string{} 455 } 456 out[parts[0]] = append(values, parts[1]) 457 } 458 return out, nil 459 } 460 461 func parseKeyValueOpts(opts opts.ListOpts) ([]KeyValuePair, error) { 462 out := make([]KeyValuePair, opts.Len()) 463 for i, o := range opts.GetAll() { 464 k, v, err := parsers.ParseKeyValueOpt(o) 465 if err != nil { 466 return nil, err 467 } 468 out[i] = KeyValuePair{Key: k, Value: v} 469 } 470 return out, nil 471 } 472 473 func parseNetMode(netMode string) (NetworkMode, error) { 474 parts := strings.Split(netMode, ":") 475 switch mode := parts[0]; mode { 476 case "bridge", "none", "host": 477 case "container": 478 if len(parts) < 2 || parts[1] == "" { 479 return "", fmt.Errorf("invalid container format container:<name|id>") 480 } 481 default: 482 return "", fmt.Errorf("invalid --net: %s", netMode) 483 } 484 return NetworkMode(netMode), nil 485 } 486 487 func ParseDevice(device string) (DeviceMapping, error) { 488 src := "" 489 dst := "" 490 permissions := "rwm" 491 arr := strings.Split(device, ":") 492 switch len(arr) { 493 case 3: 494 permissions = arr[2] 495 fallthrough 496 case 2: 497 dst = arr[1] 498 fallthrough 499 case 1: 500 src = arr[0] 501 default: 502 return DeviceMapping{}, fmt.Errorf("Invalid device specification: %s", device) 503 } 504 505 if dst == "" { 506 dst = src 507 } 508 509 deviceMapping := DeviceMapping{ 510 PathOnHost: src, 511 PathInContainer: dst, 512 CgroupPermissions: permissions, 513 } 514 return deviceMapping, nil 515 }