utils.go 9.3 KB

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