utils.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. package client
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "os"
  12. gosignal "os/signal"
  13. "runtime"
  14. "strings"
  15. "time"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/docker/api"
  18. "github.com/docker/docker/api/client/lib"
  19. "github.com/docker/docker/api/types"
  20. "github.com/docker/docker/cliconfig"
  21. "github.com/docker/docker/dockerversion"
  22. "github.com/docker/docker/pkg/jsonmessage"
  23. "github.com/docker/docker/pkg/signal"
  24. "github.com/docker/docker/pkg/stdcopy"
  25. "github.com/docker/docker/pkg/term"
  26. "github.com/docker/docker/registry"
  27. "github.com/docker/docker/utils"
  28. )
  29. var (
  30. errConnectionFailed = errors.New("Cannot connect to the Docker daemon. Is the docker daemon running on this host?")
  31. )
  32. type serverResponse struct {
  33. body io.ReadCloser
  34. header http.Header
  35. statusCode int
  36. }
  37. // HTTPClient creates a new HTTP client with the cli's client transport instance.
  38. func (cli *DockerCli) HTTPClient() *http.Client {
  39. return &http.Client{Transport: cli.transport}
  40. }
  41. func (cli *DockerCli) encodeData(data interface{}) (*bytes.Buffer, error) {
  42. params := bytes.NewBuffer(nil)
  43. if data != nil {
  44. if err := json.NewEncoder(params).Encode(data); err != nil {
  45. return nil, err
  46. }
  47. }
  48. return params, nil
  49. }
  50. func (cli *DockerCli) clientRequest(method, path string, in io.Reader, headers map[string][]string) (*serverResponse, error) {
  51. serverResp := &serverResponse{
  52. body: nil,
  53. statusCode: -1,
  54. }
  55. expectedPayload := (method == "POST" || method == "PUT")
  56. if expectedPayload && in == nil {
  57. in = bytes.NewReader([]byte{})
  58. }
  59. req, err := http.NewRequest(method, fmt.Sprintf("%s/v%s%s", cli.basePath, api.Version, path), in)
  60. if err != nil {
  61. return serverResp, err
  62. }
  63. // Add CLI Config's HTTP Headers BEFORE we set the Docker headers
  64. // then the user can't change OUR headers
  65. for k, v := range cli.configFile.HTTPHeaders {
  66. req.Header.Set(k, v)
  67. }
  68. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.Version+" ("+runtime.GOOS+")")
  69. req.URL.Host = cli.addr
  70. req.URL.Scheme = cli.scheme
  71. if headers != nil {
  72. for k, v := range headers {
  73. req.Header[k] = v
  74. }
  75. }
  76. if expectedPayload && req.Header.Get("Content-Type") == "" {
  77. req.Header.Set("Content-Type", "text/plain")
  78. }
  79. resp, err := cli.HTTPClient().Do(req)
  80. if resp != nil {
  81. serverResp.statusCode = resp.StatusCode
  82. }
  83. if err != nil {
  84. if utils.IsTimeout(err) || strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") {
  85. return serverResp, errConnectionFailed
  86. }
  87. if cli.tlsConfig == nil && strings.Contains(err.Error(), "malformed HTTP response") {
  88. return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err)
  89. }
  90. if cli.tlsConfig != nil && strings.Contains(err.Error(), "remote error: bad certificate") {
  91. return serverResp, fmt.Errorf("The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings: %v", err)
  92. }
  93. return serverResp, fmt.Errorf("An error occurred trying to connect: %v", err)
  94. }
  95. if serverResp.statusCode < 200 || serverResp.statusCode >= 400 {
  96. body, err := ioutil.ReadAll(resp.Body)
  97. if err != nil {
  98. return serverResp, err
  99. }
  100. if len(body) == 0 {
  101. return serverResp, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), req.URL)
  102. }
  103. return serverResp, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body))
  104. }
  105. serverResp.body = resp.Body
  106. serverResp.header = resp.Header
  107. return serverResp, nil
  108. }
  109. // cmdAttempt builds the corresponding registry Auth Header from the given
  110. // authConfig. It returns the servers body, status, error response
  111. func (cli *DockerCli) cmdAttempt(authConfig cliconfig.AuthConfig, method, path string, in io.Reader, out io.Writer) (io.ReadCloser, int, error) {
  112. buf, err := json.Marshal(authConfig)
  113. if err != nil {
  114. return nil, -1, err
  115. }
  116. registryAuthHeader := []string{
  117. base64.URLEncoding.EncodeToString(buf),
  118. }
  119. // begin the request
  120. serverResp, err := cli.clientRequest(method, path, in, map[string][]string{
  121. "X-Registry-Auth": registryAuthHeader,
  122. })
  123. if err == nil && out != nil {
  124. // If we are streaming output, complete the stream since
  125. // errors may not appear until later.
  126. err = cli.streamBody(serverResp.body, serverResp.header.Get("Content-Type"), true, out, nil)
  127. }
  128. if err != nil {
  129. // Since errors in a stream appear after status 200 has been written,
  130. // we may need to change the status code.
  131. if strings.Contains(err.Error(), "Authentication is required") ||
  132. strings.Contains(err.Error(), "Status 401") ||
  133. strings.Contains(err.Error(), "401 Unauthorized") ||
  134. strings.Contains(err.Error(), "status code 401") {
  135. serverResp.statusCode = http.StatusUnauthorized
  136. }
  137. }
  138. return serverResp.body, serverResp.statusCode, err
  139. }
  140. func (cli *DockerCli) encodeRegistryAuth(index *registry.IndexInfo) (string, error) {
  141. authConfig := registry.ResolveAuthConfig(cli.configFile, index)
  142. return authConfig.EncodeToBase64()
  143. }
  144. func (cli *DockerCli) registryAuthenticationPrivilegedFunc(index *registry.IndexInfo, cmdName string) lib.RequestPrivilegeFunc {
  145. return func() (string, error) {
  146. fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName)
  147. if err := cli.CmdLogin(index.GetAuthConfigKey()); err != nil {
  148. return "", err
  149. }
  150. return cli.encodeRegistryAuth(index)
  151. }
  152. }
  153. func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reader, out io.Writer, index *registry.IndexInfo, cmdName string) (io.ReadCloser, int, error) {
  154. // Resolve the Auth config relevant for this server
  155. authConfig := registry.ResolveAuthConfig(cli.configFile, index)
  156. body, statusCode, err := cli.cmdAttempt(authConfig, method, path, in, out)
  157. if statusCode == http.StatusUnauthorized {
  158. fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName)
  159. if err = cli.CmdLogin(index.GetAuthConfigKey()); err != nil {
  160. return nil, -1, err
  161. }
  162. authConfig = registry.ResolveAuthConfig(cli.configFile, index)
  163. return cli.cmdAttempt(authConfig, method, path, in, out)
  164. }
  165. return body, statusCode, err
  166. }
  167. func (cli *DockerCli) callWrapper(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
  168. sr, err := cli.call(method, path, data, headers)
  169. return sr.body, sr.header, sr.statusCode, err
  170. }
  171. func (cli *DockerCli) call(method, path string, data interface{}, headers map[string][]string) (*serverResponse, error) {
  172. params, err := cli.encodeData(data)
  173. if err != nil {
  174. sr := &serverResponse{
  175. body: nil,
  176. header: nil,
  177. statusCode: -1,
  178. }
  179. return sr, nil
  180. }
  181. if data != nil {
  182. if headers == nil {
  183. headers = make(map[string][]string)
  184. }
  185. headers["Content-Type"] = []string{"application/json"}
  186. }
  187. serverResp, err := cli.clientRequest(method, path, params, headers)
  188. return serverResp, err
  189. }
  190. type streamOpts struct {
  191. rawTerminal bool
  192. in io.Reader
  193. out io.Writer
  194. err io.Writer
  195. headers map[string][]string
  196. }
  197. func (cli *DockerCli) stream(method, path string, opts *streamOpts) (*serverResponse, error) {
  198. serverResp, err := cli.clientRequest(method, path, opts.in, opts.headers)
  199. if err != nil {
  200. return serverResp, err
  201. }
  202. return serverResp, cli.streamBody(serverResp.body, serverResp.header.Get("Content-Type"), opts.rawTerminal, opts.out, opts.err)
  203. }
  204. func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, rawTerminal bool, stdout, stderr io.Writer) error {
  205. defer body.Close()
  206. if api.MatchesContentType(contentType, "application/json") {
  207. return jsonmessage.DisplayJSONMessagesStream(body, stdout, cli.outFd, cli.isTerminalOut)
  208. }
  209. if stdout != nil || stderr != nil {
  210. // When TTY is ON, use regular copy
  211. var err error
  212. if rawTerminal {
  213. _, err = io.Copy(stdout, body)
  214. } else {
  215. _, err = stdcopy.StdCopy(stdout, stderr, body)
  216. }
  217. logrus.Debugf("[stream] End of stdout")
  218. return err
  219. }
  220. return nil
  221. }
  222. func (cli *DockerCli) resizeTty(id string, isExec bool) {
  223. height, width := cli.getTtySize()
  224. if height == 0 && width == 0 {
  225. return
  226. }
  227. options := types.ResizeOptions{
  228. ID: id,
  229. Height: height,
  230. Width: width,
  231. }
  232. var err error
  233. if !isExec {
  234. err = cli.client.ContainerExecResize(options)
  235. } else {
  236. err = cli.client.ContainerResize(options)
  237. }
  238. if err != nil {
  239. logrus.Debugf("Error resize: %s", err)
  240. }
  241. }
  242. // getExitCode perform an inspect on the container. It returns
  243. // the running state and the exit code.
  244. func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
  245. c, err := cli.client.ContainerInspect(containerID)
  246. if err != nil {
  247. // If we can't connect, then the daemon probably died.
  248. if err != lib.ErrConnectionFailed {
  249. return false, -1, err
  250. }
  251. return false, -1, nil
  252. }
  253. return c.State.Running, c.State.ExitCode, nil
  254. }
  255. // getExecExitCode perform an inspect on the exec command. It returns
  256. // the running state and the exit code.
  257. func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
  258. resp, err := cli.client.ContainerExecInspect(execID)
  259. if err != nil {
  260. // If we can't connect, then the daemon probably died.
  261. if err != lib.ErrConnectionFailed {
  262. return false, -1, err
  263. }
  264. return false, -1, nil
  265. }
  266. return resp.Running, resp.ExitCode, nil
  267. }
  268. func (cli *DockerCli) monitorTtySize(id string, isExec bool) error {
  269. cli.resizeTty(id, isExec)
  270. if runtime.GOOS == "windows" {
  271. go func() {
  272. prevH, prevW := cli.getTtySize()
  273. for {
  274. time.Sleep(time.Millisecond * 250)
  275. h, w := cli.getTtySize()
  276. if prevW != w || prevH != h {
  277. cli.resizeTty(id, isExec)
  278. }
  279. prevH = h
  280. prevW = w
  281. }
  282. }()
  283. } else {
  284. sigchan := make(chan os.Signal, 1)
  285. gosignal.Notify(sigchan, signal.SIGWINCH)
  286. go func() {
  287. for range sigchan {
  288. cli.resizeTty(id, isExec)
  289. }
  290. }()
  291. }
  292. return nil
  293. }
  294. func (cli *DockerCli) getTtySize() (int, int) {
  295. if !cli.isTerminalOut {
  296. return 0, 0
  297. }
  298. ws, err := term.GetWinsize(cli.outFd)
  299. if err != nil {
  300. logrus.Debugf("Error getting size: %s", err)
  301. if ws == nil {
  302. return 0, 0
  303. }
  304. }
  305. return int(ws.Height), int(ws.Width)
  306. }
  307. func readBody(serverResp *serverResponse, err error) ([]byte, int, error) {
  308. if serverResp.body != nil {
  309. defer serverResp.body.Close()
  310. }
  311. if err != nil {
  312. return nil, serverResp.statusCode, err
  313. }
  314. body, err := ioutil.ReadAll(serverResp.body)
  315. if err != nil {
  316. return nil, -1, err
  317. }
  318. return body, serverResp.statusCode, nil
  319. }