utils.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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) encodeRegistryAuth(index *registry.IndexInfo) (string, error) {
  142. authConfig := registry.ResolveAuthConfig(cli.configFile, index)
  143. return authConfig.EncodeToBase64()
  144. }
  145. func (cli *DockerCli) registryAuthenticationPrivilegedFunc(index *registry.IndexInfo, cmdName string) lib.RequestPrivilegeFunc {
  146. return func() (string, error) {
  147. fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName)
  148. if err := cli.CmdLogin(index.GetAuthConfigKey()); err != nil {
  149. return "", err
  150. }
  151. return cli.encodeRegistryAuth(index)
  152. }
  153. }
  154. func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reader, out io.Writer, index *registry.IndexInfo, cmdName string) (io.ReadCloser, int, error) {
  155. // Resolve the Auth config relevant for this server
  156. authConfig := registry.ResolveAuthConfig(cli.configFile, index)
  157. body, statusCode, err := cli.cmdAttempt(authConfig, method, path, in, out)
  158. if statusCode == http.StatusUnauthorized {
  159. fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName)
  160. if err = cli.CmdLogin(index.GetAuthConfigKey()); err != nil {
  161. return nil, -1, err
  162. }
  163. authConfig = registry.ResolveAuthConfig(cli.configFile, index)
  164. return cli.cmdAttempt(authConfig, method, path, in, out)
  165. }
  166. return body, statusCode, err
  167. }
  168. func (cli *DockerCli) callWrapper(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
  169. sr, err := cli.call(method, path, data, headers)
  170. return sr.body, sr.header, sr.statusCode, err
  171. }
  172. func (cli *DockerCli) call(method, path string, data interface{}, headers map[string][]string) (*serverResponse, error) {
  173. params, err := cli.encodeData(data)
  174. if err != nil {
  175. sr := &serverResponse{
  176. body: nil,
  177. header: nil,
  178. statusCode: -1,
  179. }
  180. return sr, nil
  181. }
  182. if data != nil {
  183. if headers == nil {
  184. headers = make(map[string][]string)
  185. }
  186. headers["Content-Type"] = []string{"application/json"}
  187. }
  188. serverResp, err := cli.clientRequest(method, path, params, headers)
  189. return serverResp, err
  190. }
  191. type streamOpts struct {
  192. rawTerminal bool
  193. in io.Reader
  194. out io.Writer
  195. err io.Writer
  196. headers map[string][]string
  197. }
  198. func (cli *DockerCli) stream(method, path string, opts *streamOpts) (*serverResponse, error) {
  199. serverResp, err := cli.clientRequest(method, path, opts.in, opts.headers)
  200. if err != nil {
  201. return serverResp, err
  202. }
  203. return serverResp, cli.streamBody(serverResp.body, serverResp.header.Get("Content-Type"), opts.rawTerminal, opts.out, opts.err)
  204. }
  205. func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, rawTerminal bool, stdout, stderr io.Writer) error {
  206. defer body.Close()
  207. if api.MatchesContentType(contentType, "application/json") {
  208. return jsonmessage.DisplayJSONMessagesStream(body, stdout, cli.outFd, cli.isTerminalOut)
  209. }
  210. if stdout != nil || stderr != nil {
  211. // When TTY is ON, use regular copy
  212. var err error
  213. if rawTerminal {
  214. _, err = io.Copy(stdout, body)
  215. } else {
  216. _, err = stdcopy.StdCopy(stdout, stderr, body)
  217. }
  218. logrus.Debugf("[stream] End of stdout")
  219. return err
  220. }
  221. return nil
  222. }
  223. func (cli *DockerCli) resizeTty(id string, isExec bool) {
  224. height, width := cli.getTtySize()
  225. if height == 0 && width == 0 {
  226. return
  227. }
  228. v := url.Values{}
  229. v.Set("h", strconv.Itoa(height))
  230. v.Set("w", strconv.Itoa(width))
  231. path := ""
  232. if !isExec {
  233. path = "/containers/" + id + "/resize?"
  234. } else {
  235. path = "/exec/" + id + "/resize?"
  236. }
  237. if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, nil)); err != nil {
  238. logrus.Debugf("Error resize: %s", err)
  239. }
  240. }
  241. // getExitCode perform an inspect on the container. It returns
  242. // the running state and the exit code.
  243. func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
  244. c, err := cli.client.ContainerInspect(containerID)
  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 c.State.Running, c.State.ExitCode, nil
  253. }
  254. // getExecExitCode perform an inspect on the exec command. It returns
  255. // the running state and the exit code.
  256. func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
  257. resp, err := cli.client.ContainerExecInspect(execID)
  258. if err != nil {
  259. // If we can't connect, then the daemon probably died.
  260. if err != lib.ErrConnectionFailed {
  261. return false, -1, err
  262. }
  263. return false, -1, nil
  264. }
  265. return resp.Running, resp.ExitCode, nil
  266. }
  267. func (cli *DockerCli) monitorTtySize(id string, isExec bool) error {
  268. cli.resizeTty(id, isExec)
  269. if runtime.GOOS == "windows" {
  270. go func() {
  271. prevH, prevW := cli.getTtySize()
  272. for {
  273. time.Sleep(time.Millisecond * 250)
  274. h, w := cli.getTtySize()
  275. if prevW != w || prevH != h {
  276. cli.resizeTty(id, isExec)
  277. }
  278. prevH = h
  279. prevW = w
  280. }
  281. }()
  282. } else {
  283. sigchan := make(chan os.Signal, 1)
  284. gosignal.Notify(sigchan, signal.SIGWINCH)
  285. go func() {
  286. for range sigchan {
  287. cli.resizeTty(id, isExec)
  288. }
  289. }()
  290. }
  291. return nil
  292. }
  293. func (cli *DockerCli) getTtySize() (int, int) {
  294. if !cli.isTerminalOut {
  295. return 0, 0
  296. }
  297. ws, err := term.GetWinsize(cli.outFd)
  298. if err != nil {
  299. logrus.Debugf("Error getting size: %s", err)
  300. if ws == nil {
  301. return 0, 0
  302. }
  303. }
  304. return int(ws.Height), int(ws.Width)
  305. }
  306. func readBody(serverResp *serverResponse, err error) ([]byte, int, error) {
  307. if serverResp.body != nil {
  308. defer serverResp.body.Close()
  309. }
  310. if err != nil {
  311. return nil, serverResp.statusCode, err
  312. }
  313. body, err := ioutil.ReadAll(serverResp.body)
  314. if err != nil {
  315. return nil, -1, err
  316. }
  317. return body, serverResp.statusCode, nil
  318. }