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