parse.go 16 KB

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