cli.go 6.3 KB

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