github.com/hustcat/docker@v1.3.3-0.20160314103604-901c67a8eeab/runconfig/opts/parse.go (about) 1 package opts 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io/ioutil" 8 "path" 9 "strconv" 10 "strings" 11 12 "github.com/docker/docker/opts" 13 flag "github.com/docker/docker/pkg/mflag" 14 "github.com/docker/docker/pkg/mount" 15 "github.com/docker/docker/pkg/signal" 16 "github.com/docker/engine-api/types/container" 17 networktypes "github.com/docker/engine-api/types/network" 18 "github.com/docker/engine-api/types/strslice" 19 "github.com/docker/go-connections/nat" 20 "github.com/docker/go-units" 21 ) 22 23 // Parse parses the specified args for the specified command and generates a Config, 24 // a HostConfig and returns them with the specified command. 25 // If the specified args are not valid, it will return an error. 26 func Parse(cmd *flag.FlagSet, args []string) (*container.Config, *container.HostConfig, *networktypes.NetworkingConfig, *flag.FlagSet, error) { 27 var ( 28 // FIXME: use utils.ListOpts for attach and volumes? 29 flAttach = opts.NewListOpts(ValidateAttach) 30 flVolumes = opts.NewListOpts(nil) 31 flTmpfs = opts.NewListOpts(nil) 32 flBlkioWeightDevice = NewWeightdeviceOpt(ValidateWeightDevice) 33 flDeviceReadBps = NewThrottledeviceOpt(ValidateThrottleBpsDevice) 34 flDeviceWriteBps = NewThrottledeviceOpt(ValidateThrottleBpsDevice) 35 flLinks = opts.NewListOpts(ValidateLink) 36 flAliases = opts.NewListOpts(nil) 37 flDeviceReadIOps = NewThrottledeviceOpt(ValidateThrottleIOpsDevice) 38 flDeviceWriteIOps = NewThrottledeviceOpt(ValidateThrottleIOpsDevice) 39 flEnv = opts.NewListOpts(ValidateEnv) 40 flLabels = opts.NewListOpts(ValidateEnv) 41 flDevices = opts.NewListOpts(ValidateDevice) 42 43 flUlimits = NewUlimitOpt(nil) 44 45 flPublish = opts.NewListOpts(nil) 46 flExpose = opts.NewListOpts(nil) 47 flDNS = opts.NewListOpts(opts.ValidateIPAddress) 48 flDNSSearch = opts.NewListOpts(opts.ValidateDNSSearch) 49 flDNSOptions = opts.NewListOpts(nil) 50 flExtraHosts = opts.NewListOpts(ValidateExtraHost) 51 flVolumesFrom = opts.NewListOpts(nil) 52 flEnvFile = opts.NewListOpts(nil) 53 flCapAdd = opts.NewListOpts(nil) 54 flCapDrop = opts.NewListOpts(nil) 55 flGroupAdd = opts.NewListOpts(nil) 56 flSecurityOpt = opts.NewListOpts(nil) 57 flLabelsFile = opts.NewListOpts(nil) 58 flLoggingOpts = opts.NewListOpts(nil) 59 flPrivileged = cmd.Bool([]string{"-privileged"}, false, "Give extended privileges to this container") 60 flPidMode = cmd.String([]string{"-pid"}, "", "PID namespace to use") 61 flUTSMode = cmd.String([]string{"-uts"}, "", "UTS namespace to use") 62 flPublishAll = cmd.Bool([]string{"P", "-publish-all"}, false, "Publish all exposed ports to random ports") 63 flStdin = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached") 64 flTty = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY") 65 flOomKillDisable = cmd.Bool([]string{"-oom-kill-disable"}, false, "Disable OOM Killer") 66 flOomScoreAdj = cmd.Int([]string{"-oom-score-adj"}, 0, "Tune host's OOM preferences (-1000 to 1000)") 67 flContainerIDFile = cmd.String([]string{"-cidfile"}, "", "Write the container ID to the file") 68 flEntrypoint = cmd.String([]string{"-entrypoint"}, "", "Overwrite the default ENTRYPOINT of the image") 69 flHostname = cmd.String([]string{"h", "-hostname"}, "", "Container host name") 70 flMemoryString = cmd.String([]string{"m", "-memory"}, "", "Memory limit") 71 flMemoryReservation = cmd.String([]string{"-memory-reservation"}, "", "Memory soft limit") 72 flMemorySwap = cmd.String([]string{"-memory-swap"}, "", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap") 73 flKernelMemory = cmd.String([]string{"-kernel-memory"}, "", "Kernel memory limit") 74 flUser = cmd.String([]string{"u", "-user"}, "", "Username or UID (format: <name|uid>[:<group|gid>])") 75 flWorkingDir = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container") 76 flCPUShares = cmd.Int64([]string{"#c", "-cpu-shares"}, 0, "CPU shares (relative weight)") 77 flCPUPeriod = cmd.Int64([]string{"-cpu-period"}, 0, "Limit CPU CFS (Completely Fair Scheduler) period") 78 flCPUQuota = cmd.Int64([]string{"-cpu-quota"}, 0, "Limit CPU CFS (Completely Fair Scheduler) quota") 79 flCpusetCpus = cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)") 80 flCpusetMems = cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)") 81 flBlkioWeight = cmd.Uint16([]string{"-blkio-weight"}, 0, "Block IO (relative weight), between 10 and 1000") 82 flSwappiness = cmd.Int64([]string{"-memory-swappiness"}, -1, "Tune container memory swappiness (0 to 100)") 83 flNetMode = cmd.String([]string{"-net"}, "default", "Connect a container to a network") 84 flMacAddress = cmd.String([]string{"-mac-address"}, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)") 85 flIPv4Address = cmd.String([]string{"-ip"}, "", "Container IPv4 address (e.g. 172.30.100.104)") 86 flIPv6Address = cmd.String([]string{"-ip6"}, "", "Container IPv6 address (e.g. 2001:db8::33)") 87 flIpcMode = cmd.String([]string{"-ipc"}, "", "IPC namespace to use") 88 flPidsLimit = cmd.Int64([]string{"-pids-limit"}, 0, "Tune container pids limit (set -1 for unlimited)") 89 flRestartPolicy = cmd.String([]string{"-restart"}, "no", "Restart policy to apply when a container exits") 90 flReadonlyRootfs = cmd.Bool([]string{"-read-only"}, false, "Mount the container's root filesystem as read only") 91 flLoggingDriver = cmd.String([]string{"-log-driver"}, "", "Logging driver for container") 92 flCgroupParent = cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container") 93 flVolumeDriver = cmd.String([]string{"-volume-driver"}, "", "Optional volume driver for the container") 94 flStopSignal = cmd.String([]string{"-stop-signal"}, signal.DefaultStopSignal, fmt.Sprintf("Signal to stop a container, %v by default", signal.DefaultStopSignal)) 95 flIsolation = cmd.String([]string{"-isolation"}, "", "Container isolation technology") 96 flShmSize = cmd.String([]string{"-shm-size"}, "", "Size of /dev/shm, default value is 64MB") 97 ) 98 99 cmd.Var(&flAttach, []string{"a", "-attach"}, "Attach to STDIN, STDOUT or STDERR") 100 cmd.Var(&flBlkioWeightDevice, []string{"-blkio-weight-device"}, "Block IO weight (relative device weight)") 101 cmd.Var(&flDeviceReadBps, []string{"-device-read-bps"}, "Limit read rate (bytes per second) from a device") 102 cmd.Var(&flDeviceWriteBps, []string{"-device-write-bps"}, "Limit write rate (bytes per second) to a device") 103 cmd.Var(&flDeviceReadIOps, []string{"-device-read-iops"}, "Limit read rate (IO per second) from a device") 104 cmd.Var(&flDeviceWriteIOps, []string{"-device-write-iops"}, "Limit write rate (IO per second) to a device") 105 cmd.Var(&flVolumes, []string{"v", "-volume"}, "Bind mount a volume") 106 cmd.Var(&flTmpfs, []string{"-tmpfs"}, "Mount a tmpfs directory") 107 cmd.Var(&flLinks, []string{"-link"}, "Add link to another container") 108 cmd.Var(&flAliases, []string{"-net-alias"}, "Add network-scoped alias for the container") 109 cmd.Var(&flDevices, []string{"-device"}, "Add a host device to the container") 110 cmd.Var(&flLabels, []string{"l", "-label"}, "Set meta data on a container") 111 cmd.Var(&flLabelsFile, []string{"-label-file"}, "Read in a line delimited file of labels") 112 cmd.Var(&flEnv, []string{"e", "-env"}, "Set environment variables") 113 cmd.Var(&flEnvFile, []string{"-env-file"}, "Read in a file of environment variables") 114 cmd.Var(&flPublish, []string{"p", "-publish"}, "Publish a container's port(s) to the host") 115 cmd.Var(&flExpose, []string{"-expose"}, "Expose a port or a range of ports") 116 cmd.Var(&flDNS, []string{"-dns"}, "Set custom DNS servers") 117 cmd.Var(&flDNSSearch, []string{"-dns-search"}, "Set custom DNS search domains") 118 cmd.Var(&flDNSOptions, []string{"-dns-opt"}, "Set DNS options") 119 cmd.Var(&flExtraHosts, []string{"-add-host"}, "Add a custom host-to-IP mapping (host:ip)") 120 cmd.Var(&flVolumesFrom, []string{"-volumes-from"}, "Mount volumes from the specified container(s)") 121 cmd.Var(&flCapAdd, []string{"-cap-add"}, "Add Linux capabilities") 122 cmd.Var(&flCapDrop, []string{"-cap-drop"}, "Drop Linux capabilities") 123 cmd.Var(&flGroupAdd, []string{"-group-add"}, "Add additional groups to join") 124 cmd.Var(&flSecurityOpt, []string{"-security-opt"}, "Security Options") 125 cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options") 126 cmd.Var(&flLoggingOpts, []string{"-log-opt"}, "Log driver options") 127 128 cmd.Require(flag.Min, 1) 129 130 if err := cmd.ParseFlags(args, true); err != nil { 131 return nil, nil, nil, cmd, err 132 } 133 134 var ( 135 attachStdin = flAttach.Get("stdin") 136 attachStdout = flAttach.Get("stdout") 137 attachStderr = flAttach.Get("stderr") 138 ) 139 140 // Validate the input mac address 141 if *flMacAddress != "" { 142 if _, err := ValidateMACAddress(*flMacAddress); err != nil { 143 return nil, nil, nil, cmd, fmt.Errorf("%s is not a valid mac address", *flMacAddress) 144 } 145 } 146 if *flStdin { 147 attachStdin = true 148 } 149 // If -a is not set attach to the output stdio 150 if flAttach.Len() == 0 { 151 attachStdout = true 152 attachStderr = true 153 } 154 155 var err error 156 157 var flMemory int64 158 if *flMemoryString != "" { 159 flMemory, err = units.RAMInBytes(*flMemoryString) 160 if err != nil { 161 return nil, nil, nil, cmd, err 162 } 163 } 164 165 var MemoryReservation int64 166 if *flMemoryReservation != "" { 167 MemoryReservation, err = units.RAMInBytes(*flMemoryReservation) 168 if err != nil { 169 return nil, nil, nil, cmd, err 170 } 171 } 172 173 var memorySwap int64 174 if *flMemorySwap != "" { 175 if *flMemorySwap == "-1" { 176 memorySwap = -1 177 } else { 178 memorySwap, err = units.RAMInBytes(*flMemorySwap) 179 if err != nil { 180 return nil, nil, nil, cmd, err 181 } 182 } 183 } 184 185 var KernelMemory int64 186 if *flKernelMemory != "" { 187 KernelMemory, err = units.RAMInBytes(*flKernelMemory) 188 if err != nil { 189 return nil, nil, nil, cmd, err 190 } 191 } 192 193 swappiness := *flSwappiness 194 if swappiness != -1 && (swappiness < 0 || swappiness > 100) { 195 return nil, nil, nil, cmd, fmt.Errorf("invalid value: %d. Valid memory swappiness range is 0-100", swappiness) 196 } 197 198 var shmSize int64 199 if *flShmSize != "" { 200 shmSize, err = units.RAMInBytes(*flShmSize) 201 if err != nil { 202 return nil, nil, nil, cmd, err 203 } 204 } 205 206 var binds []string 207 // add any bind targets to the list of container volumes 208 for bind := range flVolumes.GetMap() { 209 if arr := volumeSplitN(bind, 2); len(arr) > 1 { 210 // after creating the bind mount we want to delete it from the flVolumes values because 211 // we do not want bind mounts being committed to image configs 212 binds = append(binds, bind) 213 flVolumes.Delete(bind) 214 } 215 } 216 217 // Can't evaluate options passed into --tmpfs until we actually mount 218 tmpfs := make(map[string]string) 219 for _, t := range flTmpfs.GetAll() { 220 if arr := strings.SplitN(t, ":", 2); len(arr) > 1 { 221 if _, _, err := mount.ParseTmpfsOptions(arr[1]); err != nil { 222 return nil, nil, nil, cmd, err 223 } 224 tmpfs[arr[0]] = arr[1] 225 } else { 226 tmpfs[arr[0]] = "" 227 } 228 } 229 230 var ( 231 parsedArgs = cmd.Args() 232 runCmd strslice.StrSlice 233 entrypoint strslice.StrSlice 234 image = cmd.Arg(0) 235 ) 236 if len(parsedArgs) > 1 { 237 runCmd = strslice.StrSlice(parsedArgs[1:]) 238 } 239 if *flEntrypoint != "" { 240 entrypoint = strslice.StrSlice{*flEntrypoint} 241 } 242 243 var ( 244 domainname string 245 hostname = *flHostname 246 parts = strings.SplitN(hostname, ".", 2) 247 ) 248 if len(parts) > 1 { 249 hostname = parts[0] 250 domainname = parts[1] 251 } 252 253 ports, portBindings, err := nat.ParsePortSpecs(flPublish.GetAll()) 254 if err != nil { 255 return nil, nil, nil, cmd, err 256 } 257 258 // Merge in exposed ports to the map of published ports 259 for _, e := range flExpose.GetAll() { 260 if strings.Contains(e, ":") { 261 return nil, nil, nil, cmd, fmt.Errorf("invalid port format for --expose: %s", e) 262 } 263 //support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>] 264 proto, port := nat.SplitProtoPort(e) 265 //parse the start and end port and create a sequence of ports to expose 266 //if expose a port, the start and end port are the same 267 start, end, err := nat.ParsePortRange(port) 268 if err != nil { 269 return nil, nil, nil, cmd, fmt.Errorf("invalid range format for --expose: %s, error: %s", e, err) 270 } 271 for i := start; i <= end; i++ { 272 p, err := nat.NewPort(proto, strconv.FormatUint(i, 10)) 273 if err != nil { 274 return nil, nil, nil, cmd, err 275 } 276 if _, exists := ports[p]; !exists { 277 ports[p] = struct{}{} 278 } 279 } 280 } 281 282 // parse device mappings 283 deviceMappings := []container.DeviceMapping{} 284 for _, device := range flDevices.GetAll() { 285 deviceMapping, err := ParseDevice(device) 286 if err != nil { 287 return nil, nil, nil, cmd, err 288 } 289 deviceMappings = append(deviceMappings, deviceMapping) 290 } 291 292 // collect all the environment variables for the container 293 envVariables, err := readKVStrings(flEnvFile.GetAll(), flEnv.GetAll()) 294 if err != nil { 295 return nil, nil, nil, cmd, err 296 } 297 298 // collect all the labels for the container 299 labels, err := readKVStrings(flLabelsFile.GetAll(), flLabels.GetAll()) 300 if err != nil { 301 return nil, nil, nil, cmd, err 302 } 303 304 ipcMode := container.IpcMode(*flIpcMode) 305 if !ipcMode.Valid() { 306 return nil, nil, nil, cmd, fmt.Errorf("--ipc: invalid IPC mode") 307 } 308 309 pidMode := container.PidMode(*flPidMode) 310 if !pidMode.Valid() { 311 return nil, nil, nil, cmd, fmt.Errorf("--pid: invalid PID mode") 312 } 313 314 utsMode := container.UTSMode(*flUTSMode) 315 if !utsMode.Valid() { 316 return nil, nil, nil, cmd, fmt.Errorf("--uts: invalid UTS mode") 317 } 318 319 restartPolicy, err := ParseRestartPolicy(*flRestartPolicy) 320 if err != nil { 321 return nil, nil, nil, cmd, err 322 } 323 324 loggingOpts, err := parseLoggingOpts(*flLoggingDriver, flLoggingOpts.GetAll()) 325 if err != nil { 326 return nil, nil, nil, cmd, err 327 } 328 329 securityOpts, err := parseSecurityOpts(flSecurityOpt.GetAll()) 330 if err != nil { 331 return nil, nil, nil, cmd, err 332 } 333 334 resources := container.Resources{ 335 CgroupParent: *flCgroupParent, 336 Memory: flMemory, 337 MemoryReservation: MemoryReservation, 338 MemorySwap: memorySwap, 339 MemorySwappiness: flSwappiness, 340 KernelMemory: KernelMemory, 341 OomKillDisable: flOomKillDisable, 342 CPUShares: *flCPUShares, 343 CPUPeriod: *flCPUPeriod, 344 CpusetCpus: *flCpusetCpus, 345 CpusetMems: *flCpusetMems, 346 CPUQuota: *flCPUQuota, 347 PidsLimit: *flPidsLimit, 348 BlkioWeight: *flBlkioWeight, 349 BlkioWeightDevice: flBlkioWeightDevice.GetList(), 350 BlkioDeviceReadBps: flDeviceReadBps.GetList(), 351 BlkioDeviceWriteBps: flDeviceWriteBps.GetList(), 352 BlkioDeviceReadIOps: flDeviceReadIOps.GetList(), 353 BlkioDeviceWriteIOps: flDeviceWriteIOps.GetList(), 354 Ulimits: flUlimits.GetList(), 355 Devices: deviceMappings, 356 } 357 358 config := &container.Config{ 359 Hostname: hostname, 360 Domainname: domainname, 361 ExposedPorts: ports, 362 User: *flUser, 363 Tty: *flTty, 364 // TODO: deprecated, it comes from -n, --networking 365 // it's still needed internally to set the network to disabled 366 // if e.g. bridge is none in daemon opts, and in inspect 367 NetworkDisabled: false, 368 OpenStdin: *flStdin, 369 AttachStdin: attachStdin, 370 AttachStdout: attachStdout, 371 AttachStderr: attachStderr, 372 Env: envVariables, 373 Cmd: runCmd, 374 Image: image, 375 Volumes: flVolumes.GetMap(), 376 MacAddress: *flMacAddress, 377 Entrypoint: entrypoint, 378 WorkingDir: *flWorkingDir, 379 Labels: ConvertKVStringsToMap(labels), 380 } 381 if cmd.IsSet("-stop-signal") { 382 config.StopSignal = *flStopSignal 383 } 384 385 hostConfig := &container.HostConfig{ 386 Binds: binds, 387 ContainerIDFile: *flContainerIDFile, 388 OomScoreAdj: *flOomScoreAdj, 389 Privileged: *flPrivileged, 390 PortBindings: portBindings, 391 Links: flLinks.GetAll(), 392 PublishAllPorts: *flPublishAll, 393 // Make sure the dns fields are never nil. 394 // New containers don't ever have those fields nil, 395 // but pre created containers can still have those nil values. 396 // See https://github.com/docker/docker/pull/17779 397 // for a more detailed explanation on why we don't want that. 398 DNS: flDNS.GetAllOrEmpty(), 399 DNSSearch: flDNSSearch.GetAllOrEmpty(), 400 DNSOptions: flDNSOptions.GetAllOrEmpty(), 401 ExtraHosts: flExtraHosts.GetAll(), 402 VolumesFrom: flVolumesFrom.GetAll(), 403 NetworkMode: container.NetworkMode(*flNetMode), 404 IpcMode: ipcMode, 405 PidMode: pidMode, 406 UTSMode: utsMode, 407 CapAdd: strslice.StrSlice(flCapAdd.GetAll()), 408 CapDrop: strslice.StrSlice(flCapDrop.GetAll()), 409 GroupAdd: flGroupAdd.GetAll(), 410 RestartPolicy: restartPolicy, 411 SecurityOpt: securityOpts, 412 ReadonlyRootfs: *flReadonlyRootfs, 413 LogConfig: container.LogConfig{Type: *flLoggingDriver, Config: loggingOpts}, 414 VolumeDriver: *flVolumeDriver, 415 Isolation: container.Isolation(*flIsolation), 416 ShmSize: shmSize, 417 Resources: resources, 418 Tmpfs: tmpfs, 419 } 420 421 // When allocating stdin in attached mode, close stdin at client disconnect 422 if config.OpenStdin && config.AttachStdin { 423 config.StdinOnce = true 424 } 425 426 networkingConfig := &networktypes.NetworkingConfig{ 427 EndpointsConfig: make(map[string]*networktypes.EndpointSettings), 428 } 429 430 if *flIPv4Address != "" || *flIPv6Address != "" { 431 networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = &networktypes.EndpointSettings{ 432 IPAMConfig: &networktypes.EndpointIPAMConfig{ 433 IPv4Address: *flIPv4Address, 434 IPv6Address: *flIPv6Address, 435 }, 436 } 437 } 438 439 if hostConfig.NetworkMode.IsUserDefined() && len(hostConfig.Links) > 0 { 440 epConfig := networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] 441 if epConfig == nil { 442 epConfig = &networktypes.EndpointSettings{} 443 } 444 epConfig.Links = make([]string, len(hostConfig.Links)) 445 copy(epConfig.Links, hostConfig.Links) 446 networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = epConfig 447 } 448 449 if flAliases.Len() > 0 { 450 epConfig := networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] 451 if epConfig == nil { 452 epConfig = &networktypes.EndpointSettings{} 453 } 454 epConfig.Aliases = make([]string, flAliases.Len()) 455 copy(epConfig.Aliases, flAliases.GetAll()) 456 networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = epConfig 457 } 458 459 return config, hostConfig, networkingConfig, cmd, nil 460 } 461 462 // reads a file of line terminated key=value pairs and override that with override parameter 463 func readKVStrings(files []string, override []string) ([]string, error) { 464 envVariables := []string{} 465 for _, ef := range files { 466 parsedVars, err := ParseEnvFile(ef) 467 if err != nil { 468 return nil, err 469 } 470 envVariables = append(envVariables, parsedVars...) 471 } 472 // parse the '-e' and '--env' after, to allow override 473 envVariables = append(envVariables, override...) 474 475 return envVariables, nil 476 } 477 478 // ConvertKVStringsToMap converts ["key=value"] to {"key":"value"} 479 func ConvertKVStringsToMap(values []string) map[string]string { 480 result := make(map[string]string, len(values)) 481 for _, value := range values { 482 kv := strings.SplitN(value, "=", 2) 483 if len(kv) == 1 { 484 result[kv[0]] = "" 485 } else { 486 result[kv[0]] = kv[1] 487 } 488 } 489 490 return result 491 } 492 493 func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) { 494 loggingOptsMap := ConvertKVStringsToMap(loggingOpts) 495 if loggingDriver == "none" && len(loggingOpts) > 0 { 496 return map[string]string{}, fmt.Errorf("invalid logging opts for driver %s", loggingDriver) 497 } 498 return loggingOptsMap, nil 499 } 500 501 // takes a local seccomp daemon, reads the file contents for sending to the daemon 502 func parseSecurityOpts(securityOpts []string) ([]string, error) { 503 for key, opt := range securityOpts { 504 con := strings.SplitN(opt, ":", 2) 505 if len(con) == 1 && con[0] != "no-new-privileges" { 506 return securityOpts, fmt.Errorf("Invalid --security-opt: %q", opt) 507 } 508 if con[0] == "seccomp" && con[1] != "unconfined" { 509 f, err := ioutil.ReadFile(con[1]) 510 if err != nil { 511 return securityOpts, fmt.Errorf("opening seccomp profile (%s) failed: %v", con[1], err) 512 } 513 b := bytes.NewBuffer(nil) 514 if err := json.Compact(b, f); err != nil { 515 return securityOpts, fmt.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err) 516 } 517 securityOpts[key] = fmt.Sprintf("seccomp:%s", b.Bytes()) 518 } 519 } 520 521 return securityOpts, nil 522 } 523 524 // ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect 525 func ParseRestartPolicy(policy string) (container.RestartPolicy, error) { 526 p := container.RestartPolicy{} 527 528 if policy == "" { 529 return p, nil 530 } 531 532 var ( 533 parts = strings.Split(policy, ":") 534 name = parts[0] 535 ) 536 537 p.Name = name 538 switch name { 539 case "always", "unless-stopped": 540 if len(parts) > 1 { 541 return p, fmt.Errorf("maximum restart count not valid with restart policy of \"%s\"", name) 542 } 543 case "no": 544 // do nothing 545 case "on-failure": 546 if len(parts) > 2 { 547 return p, fmt.Errorf("restart count format is not valid, usage: 'on-failure:N' or 'on-failure'") 548 } 549 if len(parts) == 2 { 550 count, err := strconv.Atoi(parts[1]) 551 if err != nil { 552 return p, err 553 } 554 555 p.MaximumRetryCount = count 556 } 557 default: 558 return p, fmt.Errorf("invalid restart policy %s", name) 559 } 560 561 return p, nil 562 } 563 564 // ParseDevice parses a device mapping string to a container.DeviceMapping struct 565 func ParseDevice(device string) (container.DeviceMapping, error) { 566 src := "" 567 dst := "" 568 permissions := "rwm" 569 arr := strings.Split(device, ":") 570 switch len(arr) { 571 case 3: 572 permissions = arr[2] 573 fallthrough 574 case 2: 575 if ValidDeviceMode(arr[1]) { 576 permissions = arr[1] 577 } else { 578 dst = arr[1] 579 } 580 fallthrough 581 case 1: 582 src = arr[0] 583 default: 584 return container.DeviceMapping{}, fmt.Errorf("invalid device specification: %s", device) 585 } 586 587 if dst == "" { 588 dst = src 589 } 590 591 deviceMapping := container.DeviceMapping{ 592 PathOnHost: src, 593 PathInContainer: dst, 594 CgroupPermissions: permissions, 595 } 596 return deviceMapping, nil 597 } 598 599 // ParseLink parses and validates the specified string as a link format (name:alias) 600 func ParseLink(val string) (string, string, error) { 601 if val == "" { 602 return "", "", fmt.Errorf("empty string specified for links") 603 } 604 arr := strings.Split(val, ":") 605 if len(arr) > 2 { 606 return "", "", fmt.Errorf("bad format for links: %s", val) 607 } 608 if len(arr) == 1 { 609 return val, val, nil 610 } 611 // This is kept because we can actually get an HostConfig with links 612 // from an already created container and the format is not `foo:bar` 613 // but `/foo:/c1/bar` 614 if strings.HasPrefix(arr[0], "/") { 615 _, alias := path.Split(arr[1]) 616 return arr[0][1:], alias, nil 617 } 618 return arr[0], arr[1], nil 619 } 620 621 // ValidateLink validates that the specified string has a valid link format (containerName:alias). 622 func ValidateLink(val string) (string, error) { 623 if _, _, err := ParseLink(val); err != nil { 624 return val, err 625 } 626 return val, nil 627 } 628 629 // ValidDeviceMode checks if the mode for device is valid or not. 630 // Valid mode is a composition of r (read), w (write), and m (mknod). 631 func ValidDeviceMode(mode string) bool { 632 var legalDeviceMode = map[rune]bool{ 633 'r': true, 634 'w': true, 635 'm': true, 636 } 637 if mode == "" { 638 return false 639 } 640 for _, c := range mode { 641 if !legalDeviceMode[c] { 642 return false 643 } 644 legalDeviceMode[c] = false 645 } 646 return true 647 } 648 649 // ValidateDevice validates a path for devices 650 // It will make sure 'val' is in the form: 651 // [host-dir:]container-path[:mode] 652 // It also validates the device mode. 653 func ValidateDevice(val string) (string, error) { 654 return validatePath(val, ValidDeviceMode) 655 } 656 657 func validatePath(val string, validator func(string) bool) (string, error) { 658 var containerPath string 659 var mode string 660 661 if strings.Count(val, ":") > 2 { 662 return val, fmt.Errorf("bad format for path: %s", val) 663 } 664 665 split := strings.SplitN(val, ":", 3) 666 if split[0] == "" { 667 return val, fmt.Errorf("bad format for path: %s", val) 668 } 669 switch len(split) { 670 case 1: 671 containerPath = split[0] 672 val = path.Clean(containerPath) 673 case 2: 674 if isValid := validator(split[1]); isValid { 675 containerPath = split[0] 676 mode = split[1] 677 val = fmt.Sprintf("%s:%s", path.Clean(containerPath), mode) 678 } else { 679 containerPath = split[1] 680 val = fmt.Sprintf("%s:%s", split[0], path.Clean(containerPath)) 681 } 682 case 3: 683 containerPath = split[1] 684 mode = split[2] 685 if isValid := validator(split[2]); !isValid { 686 return val, fmt.Errorf("bad mode specified: %s", mode) 687 } 688 val = fmt.Sprintf("%s:%s:%s", split[0], containerPath, mode) 689 } 690 691 if !path.IsAbs(containerPath) { 692 return val, fmt.Errorf("%s is not an absolute path", containerPath) 693 } 694 return val, nil 695 } 696 697 // volumeSplitN splits raw into a maximum of n parts, separated by a separator colon. 698 // A separator colon is the last `:` character in the regex `[/:\\]?[a-zA-Z]:` (note `\\` is `\` escaped). 699 // This allows to correctly split strings such as `C:\foo:D:\:rw`. 700 func volumeSplitN(raw string, n int) []string { 701 var array []string 702 if len(raw) == 0 || raw[0] == ':' { 703 // invalid 704 return nil 705 } 706 // numberOfParts counts the number of parts separated by a separator colon 707 numberOfParts := 0 708 // left represents the left-most cursor in raw, updated at every `:` character considered as a separator. 709 left := 0 710 // right represents the right-most cursor in raw incremented with the loop. Note this 711 // starts at index 1 as index 0 is already handle above as a special case. 712 for right := 1; right < len(raw); right++ { 713 // stop parsing if reached maximum number of parts 714 if n >= 0 && numberOfParts >= n { 715 break 716 } 717 if raw[right] != ':' { 718 continue 719 } 720 potentialDriveLetter := raw[right-1] 721 if (potentialDriveLetter >= 'A' && potentialDriveLetter <= 'Z') || (potentialDriveLetter >= 'a' && potentialDriveLetter <= 'z') { 722 if right > 1 { 723 beforePotentialDriveLetter := raw[right-2] 724 if beforePotentialDriveLetter != ':' && beforePotentialDriveLetter != '/' && beforePotentialDriveLetter != '\\' { 725 // e.g. `C:` is not preceded by any delimiter, therefore it was not a drive letter but a path ending with `C:`. 726 array = append(array, raw[left:right]) 727 left = right + 1 728 numberOfParts++ 729 } 730 // else, `C:` is considered as a drive letter and not as a delimiter, so we continue parsing. 731 } 732 // if right == 1, then `C:` is the beginning of the raw string, therefore `:` is again not considered a delimiter and we continue parsing. 733 } else { 734 // if `:` is not preceded by a potential drive letter, then consider it as a delimiter. 735 array = append(array, raw[left:right]) 736 left = right + 1 737 numberOfParts++ 738 } 739 } 740 // need to take care of the last part 741 if left < len(raw) { 742 if n >= 0 && numberOfParts >= n { 743 // if the maximum number of parts is reached, just append the rest to the last part 744 // left-1 is at the last `:` that needs to be included since not considered a separator. 745 array[n-1] += raw[left-1:] 746 } else { 747 array = append(array, raw[left:]) 748 } 749 } 750 return array 751 }