cli.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. package client
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "reflect"
  11. "strings"
  12. "text/template"
  13. "github.com/docker/docker/cliconfig"
  14. flag "github.com/docker/docker/pkg/mflag"
  15. "github.com/docker/docker/pkg/sockets"
  16. "github.com/docker/docker/pkg/term"
  17. )
  18. // DockerCli represents the docker command line client.
  19. // Instances of the client can be returned from NewDockerCli.
  20. type DockerCli struct {
  21. // proto holds the client protocol i.e. unix.
  22. proto string
  23. // addr holds the client address.
  24. addr string
  25. // basePath holds the path to prepend to the requests
  26. basePath string
  27. // configFile has the client configuration file
  28. configFile *cliconfig.ConfigFile
  29. // in holds the input stream and closer (io.ReadCloser) for the client.
  30. in io.ReadCloser
  31. // out holds the output stream (io.Writer) for the client.
  32. out io.Writer
  33. // err holds the error stream (io.Writer) for the client.
  34. err io.Writer
  35. // keyFile holds the key file as a string.
  36. keyFile string
  37. // tlsConfig holds the TLS configuration for the client, and will
  38. // set the scheme to https in NewDockerCli if present.
  39. tlsConfig *tls.Config
  40. // scheme holds the scheme of the client i.e. https.
  41. scheme string
  42. // inFd holds the file descriptor of the client's STDIN (if valid).
  43. inFd uintptr
  44. // outFd holds file descriptor of the client's STDOUT (if valid).
  45. outFd uintptr
  46. // isTerminalIn indicates whether the client's STDIN is a TTY
  47. isTerminalIn bool
  48. // isTerminalOut dindicates whether the client's STDOUT is a TTY
  49. isTerminalOut bool
  50. // transport holds the client transport instance.
  51. transport *http.Transport
  52. }
  53. var funcMap = template.FuncMap{
  54. "json": func(v interface{}) string {
  55. a, _ := json.Marshal(v)
  56. return string(a)
  57. },
  58. }
  59. func (cli *DockerCli) Out() io.Writer {
  60. return cli.out
  61. }
  62. func (cli *DockerCli) Err() io.Writer {
  63. return cli.err
  64. }
  65. func (cli *DockerCli) getMethod(args ...string) (func(...string) error, bool) {
  66. camelArgs := make([]string, len(args))
  67. for i, s := range args {
  68. if len(s) == 0 {
  69. return nil, false
  70. }
  71. camelArgs[i] = strings.ToUpper(s[:1]) + strings.ToLower(s[1:])
  72. }
  73. methodName := "Cmd" + strings.Join(camelArgs, "")
  74. method := reflect.ValueOf(cli).MethodByName(methodName)
  75. if !method.IsValid() {
  76. return nil, false
  77. }
  78. return method.Interface().(func(...string) error), true
  79. }
  80. // Cmd executes the specified command.
  81. func (cli *DockerCli) Cmd(args ...string) error {
  82. if len(args) > 1 {
  83. method, exists := cli.getMethod(args[:2]...)
  84. if exists {
  85. return method(args[2:]...)
  86. }
  87. }
  88. if len(args) > 0 {
  89. method, exists := cli.getMethod(args[0])
  90. if !exists {
  91. return fmt.Errorf("docker: '%s' is not a docker command.\nSee 'docker --help'.", args[0])
  92. }
  93. return method(args[1:]...)
  94. }
  95. return cli.CmdHelp()
  96. }
  97. // Subcmd is a subcommand of the main "docker" command.
  98. // A subcommand represents an action that can be performed
  99. // from the Docker command line client.
  100. //
  101. // Multiple subcommand synopses may be provided with one 'Usage' line being
  102. // printed for each in the following way:
  103. //
  104. // Usage: docker <subcmd-name> [OPTIONS] <synopsis 0>
  105. // docker <subcmd-name> [OPTIONS] <synopsis 1>
  106. // ...
  107. //
  108. // If no undeprecated flags are added to the returned FlagSet, "[OPTIONS]" will
  109. // not be included on the usage synopsis lines. If no synopses are given, only
  110. // one usage synopsis line will be printed with nothing following the
  111. // "[OPTIONS]" section
  112. //
  113. // To see all available subcommands, run "docker --help".
  114. func (cli *DockerCli) Subcmd(name string, synopses []string, description string, exitOnError bool) *flag.FlagSet {
  115. var errorHandling flag.ErrorHandling
  116. if exitOnError {
  117. errorHandling = flag.ExitOnError
  118. } else {
  119. errorHandling = flag.ContinueOnError
  120. }
  121. flags := flag.NewFlagSet(name, errorHandling)
  122. flags.Usage = func() {
  123. flags.ShortUsage()
  124. flags.PrintDefaults()
  125. }
  126. flags.ShortUsage = func() {
  127. options := ""
  128. if flags.FlagCountUndeprecated() > 0 {
  129. options = " [OPTIONS]"
  130. }
  131. if len(synopses) == 0 {
  132. synopses = []string{""}
  133. }
  134. // Allow for multiple command usage synopses.
  135. for i, synopsis := range synopses {
  136. lead := "\t"
  137. if i == 0 {
  138. // First line needs the word 'Usage'.
  139. lead = "Usage:\t"
  140. }
  141. if synopsis != "" {
  142. synopsis = " " + synopsis
  143. }
  144. fmt.Fprintf(flags.Out(), "\n%sdocker %s%s%s", lead, name, options, synopsis)
  145. }
  146. fmt.Fprintf(flags.Out(), "\n\n%s\n", description)
  147. }
  148. return flags
  149. }
  150. // CheckTtyInput checks if we are trying to attach to a container tty
  151. // from a non-tty client input stream, and if so, returns an error.
  152. func (cli *DockerCli) CheckTtyInput(attachStdin, ttyMode bool) error {
  153. // In order to attach to a container tty, input stream for the client must
  154. // be a tty itself: redirecting or piping the client standard input is
  155. // incompatible with `docker run -t`, `docker exec -t` or `docker attach`.
  156. if ttyMode && attachStdin && !cli.isTerminalIn {
  157. return errors.New("cannot enable tty mode on non tty input")
  158. }
  159. return nil
  160. }
  161. // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
  162. // The key file, protocol (i.e. unix) and address are passed in as strings, along with the tls.Config. If the tls.Config
  163. // is set the client scheme will be set to https.
  164. // The client will be given a 32-second timeout (see https://github.com/docker/docker/pull/8035).
  165. func NewDockerCli(in io.ReadCloser, out, err io.Writer, keyFile string, proto, addr string, tlsConfig *tls.Config) *DockerCli {
  166. var (
  167. inFd uintptr
  168. outFd uintptr
  169. isTerminalIn = false
  170. isTerminalOut = false
  171. scheme = "http"
  172. basePath = ""
  173. )
  174. if tlsConfig != nil {
  175. scheme = "https"
  176. }
  177. if in != nil {
  178. inFd, isTerminalIn = term.GetFdInfo(in)
  179. }
  180. if out != nil {
  181. outFd, isTerminalOut = term.GetFdInfo(out)
  182. }
  183. if err == nil {
  184. err = out
  185. }
  186. // The transport is created here for reuse during the client session.
  187. tr := &http.Transport{
  188. TLSClientConfig: tlsConfig,
  189. }
  190. sockets.ConfigureTCPTransport(tr, proto, addr)
  191. configFile, e := cliconfig.Load(cliconfig.ConfigDir())
  192. if e != nil {
  193. fmt.Fprintf(err, "WARNING: Error loading config file:%v\n", e)
  194. }
  195. if proto == "tcp" {
  196. // error is checked in pkg/parsers already
  197. parsed, _ := url.Parse("tcp://" + addr)
  198. addr = parsed.Host
  199. basePath = parsed.Path
  200. }
  201. return &DockerCli{
  202. proto: proto,
  203. addr: addr,
  204. basePath: basePath,
  205. configFile: configFile,
  206. in: in,
  207. out: out,
  208. err: err,
  209. keyFile: keyFile,
  210. inFd: inFd,
  211. outFd: outFd,
  212. isTerminalIn: isTerminalIn,
  213. isTerminalOut: isTerminalOut,
  214. tlsConfig: tlsConfig,
  215. scheme: scheme,
  216. transport: tr,
  217. }
  218. }