cli.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. package client
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "path/filepath"
  11. "reflect"
  12. "strings"
  13. "text/template"
  14. "github.com/docker/docker/cliconfig"
  15. "github.com/docker/docker/pkg/homedir"
  16. flag "github.com/docker/docker/pkg/mflag"
  17. "github.com/docker/docker/pkg/term"
  18. "github.com/docker/docker/utils"
  19. )
  20. // DockerCli represents the docker command line client.
  21. // Instances of the client can be returned from NewDockerCli.
  22. type DockerCli struct {
  23. // proto holds the client protocol i.e. unix.
  24. proto string
  25. // addr holds the client address.
  26. addr 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. See '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. // To see all available subcommands, run "docker --help".
  102. func (cli *DockerCli) Subcmd(name, signature, description string, exitOnError bool) *flag.FlagSet {
  103. var errorHandling flag.ErrorHandling
  104. if exitOnError {
  105. errorHandling = flag.ExitOnError
  106. } else {
  107. errorHandling = flag.ContinueOnError
  108. }
  109. flags := flag.NewFlagSet(name, errorHandling)
  110. flags.Usage = func() {
  111. options := ""
  112. if signature != "" {
  113. signature = " " + signature
  114. }
  115. if flags.FlagCountUndeprecated() > 0 {
  116. options = " [OPTIONS]"
  117. }
  118. fmt.Fprintf(cli.out, "\nUsage: docker %s%s%s\n\n%s\n\n", name, options, signature, description)
  119. flags.SetOutput(cli.out)
  120. flags.PrintDefaults()
  121. os.Exit(0)
  122. }
  123. return flags
  124. }
  125. // CheckTtyInput checks if we are trying to attach to a container tty
  126. // from a non-tty client input stream, and if so, returns an error.
  127. func (cli *DockerCli) CheckTtyInput(attachStdin, ttyMode bool) error {
  128. // In order to attach to a container tty, input stream for the client must
  129. // be a tty itself: redirecting or piping the client standard input is
  130. // incompatible with `docker run -t`, `docker exec -t` or `docker attach`.
  131. if ttyMode && attachStdin && !cli.isTerminalIn {
  132. return errors.New("cannot enable tty mode on non tty input")
  133. }
  134. return nil
  135. }
  136. // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
  137. // The key file, protocol (i.e. unix) and address are passed in as strings, along with the tls.Config. If the tls.Config
  138. // is set the client scheme will be set to https.
  139. // The client will be given a 32-second timeout (see https://github.com/docker/docker/pull/8035).
  140. func NewDockerCli(in io.ReadCloser, out, err io.Writer, keyFile string, proto, addr string, tlsConfig *tls.Config) *DockerCli {
  141. var (
  142. inFd uintptr
  143. outFd uintptr
  144. isTerminalIn = false
  145. isTerminalOut = false
  146. scheme = "http"
  147. )
  148. if tlsConfig != nil {
  149. scheme = "https"
  150. }
  151. if in != nil {
  152. inFd, isTerminalIn = term.GetFdInfo(in)
  153. }
  154. if out != nil {
  155. outFd, isTerminalOut = term.GetFdInfo(out)
  156. }
  157. if err == nil {
  158. err = out
  159. }
  160. // The transport is created here for reuse during the client session.
  161. tr := &http.Transport{
  162. TLSClientConfig: tlsConfig,
  163. }
  164. utils.ConfigureTCPTransport(tr, proto, addr)
  165. configFile, e := cliconfig.Load(filepath.Join(homedir.Get(), ".docker"))
  166. if e != nil {
  167. fmt.Fprintf(err, "WARNING: Error loading config file:%v\n", e)
  168. }
  169. return &DockerCli{
  170. proto: proto,
  171. addr: addr,
  172. configFile: configFile,
  173. in: in,
  174. out: out,
  175. err: err,
  176. keyFile: keyFile,
  177. inFd: inFd,
  178. outFd: outFd,
  179. isTerminalIn: isTerminalIn,
  180. isTerminalOut: isTerminalOut,
  181. tlsConfig: tlsConfig,
  182. scheme: scheme,
  183. transport: tr,
  184. }
  185. }