parse.go 11 KB

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