parse.go 13 KB

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