cli.go 6.4 KB

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