utils.go 9.3 KB

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