parse.go 13 KB

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