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