cli.go 6.0 KB

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