utils.go 9.8 KB

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