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