utils.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. "strconv"
  15. "strings"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/docker/api"
  18. "github.com/docker/docker/autogen/dockerversion"
  19. "github.com/docker/docker/engine"
  20. "github.com/docker/docker/pkg/jsonmessage"
  21. "github.com/docker/docker/pkg/signal"
  22. "github.com/docker/docker/pkg/stdcopy"
  23. "github.com/docker/docker/pkg/term"
  24. "github.com/docker/docker/registry"
  25. )
  26. var (
  27. ErrConnectionRefused = errors.New("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  28. )
  29. func (cli *DockerCli) HTTPClient() *http.Client {
  30. return &http.Client{Transport: cli.transport}
  31. }
  32. func (cli *DockerCli) encodeData(data interface{}) (*bytes.Buffer, error) {
  33. params := bytes.NewBuffer(nil)
  34. if data != nil {
  35. if env, ok := data.(engine.Env); ok {
  36. if err := env.Encode(params); err != nil {
  37. return nil, err
  38. }
  39. } else {
  40. buf, err := json.Marshal(data)
  41. if err != nil {
  42. return nil, err
  43. }
  44. if _, err := params.Write(buf); err != nil {
  45. return nil, err
  46. }
  47. }
  48. }
  49. return params, nil
  50. }
  51. func (cli *DockerCli) clientRequest(method, path string, in io.Reader, headers map[string][]string) (io.ReadCloser, string, int, error) {
  52. expectedPayload := (method == "POST" || method == "PUT")
  53. if expectedPayload && in == nil {
  54. in = bytes.NewReader([]byte{})
  55. }
  56. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), in)
  57. if err != nil {
  58. return nil, "", -1, err
  59. }
  60. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  61. req.URL.Host = cli.addr
  62. req.URL.Scheme = cli.scheme
  63. if headers != nil {
  64. for k, v := range headers {
  65. req.Header[k] = v
  66. }
  67. }
  68. if expectedPayload && req.Header.Get("Content-Type") == "" {
  69. req.Header.Set("Content-Type", "text/plain")
  70. }
  71. resp, err := cli.HTTPClient().Do(req)
  72. statusCode := -1
  73. if resp != nil {
  74. statusCode = resp.StatusCode
  75. }
  76. if err != nil {
  77. if strings.Contains(err.Error(), "connection refused") {
  78. return nil, "", statusCode, ErrConnectionRefused
  79. }
  80. if cli.tlsConfig == nil {
  81. return nil, "", statusCode, fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err)
  82. }
  83. return nil, "", statusCode, fmt.Errorf("An error occurred trying to connect: %v", err)
  84. }
  85. if statusCode < 200 || statusCode >= 400 {
  86. body, err := ioutil.ReadAll(resp.Body)
  87. if err != nil {
  88. return nil, "", statusCode, err
  89. }
  90. if len(body) == 0 {
  91. return 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)
  92. }
  93. return nil, "", statusCode, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body))
  94. }
  95. return resp.Body, resp.Header.Get("Content-Type"), statusCode, nil
  96. }
  97. func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reader, out io.Writer, index *registry.IndexInfo, cmdName string) (io.ReadCloser, int, error) {
  98. cmdAttempt := func(authConfig registry.AuthConfig) (io.ReadCloser, int, error) {
  99. buf, err := json.Marshal(authConfig)
  100. if err != nil {
  101. return nil, -1, err
  102. }
  103. registryAuthHeader := []string{
  104. base64.URLEncoding.EncodeToString(buf),
  105. }
  106. // begin the request
  107. body, contentType, statusCode, err := cli.clientRequest(method, path, in, map[string][]string{
  108. "X-Registry-Auth": registryAuthHeader,
  109. })
  110. if err == nil && out != nil {
  111. // If we are streaming output, complete the stream since
  112. // errors may not appear until later.
  113. err = cli.streamBody(body, contentType, true, out, nil)
  114. }
  115. if err != nil {
  116. // Since errors in a stream appear after status 200 has been written,
  117. // we may need to change the status code.
  118. if strings.Contains(err.Error(), "Authentication is required") ||
  119. strings.Contains(err.Error(), "Status 401") ||
  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 := cli.configFile.ResolveAuthConfig(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 = cli.configFile.ResolveAuthConfig(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, int, error) {
  140. params, err := cli.encodeData(data)
  141. if err != nil {
  142. return 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, _, statusCode, err := cli.clientRequest(method, path, params, headers)
  151. return body, statusCode, err
  152. }
  153. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  154. return cli.streamHelper(method, path, true, in, out, nil, headers)
  155. }
  156. func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in io.Reader, stdout, stderr io.Writer, headers map[string][]string) error {
  157. body, contentType, _, err := cli.clientRequest(method, path, in, headers)
  158. if err != nil {
  159. return err
  160. }
  161. return cli.streamBody(body, contentType, setRawTerminal, stdout, stderr)
  162. }
  163. func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, setRawTerminal bool, stdout, stderr io.Writer) error {
  164. defer body.Close()
  165. if api.MatchesContentType(contentType, "application/json") {
  166. return jsonmessage.DisplayJSONMessagesStream(body, stdout, cli.outFd, cli.isTerminalOut)
  167. }
  168. if stdout != nil || stderr != nil {
  169. // When TTY is ON, use regular copy
  170. var err error
  171. if setRawTerminal {
  172. _, err = io.Copy(stdout, body)
  173. } else {
  174. _, err = stdcopy.StdCopy(stdout, stderr, body)
  175. }
  176. logrus.Debugf("[stream] End of stdout")
  177. return err
  178. }
  179. return nil
  180. }
  181. func (cli *DockerCli) resizeTty(id string, isExec bool) {
  182. height, width := cli.getTtySize()
  183. if height == 0 && width == 0 {
  184. return
  185. }
  186. v := url.Values{}
  187. v.Set("h", strconv.Itoa(height))
  188. v.Set("w", strconv.Itoa(width))
  189. path := ""
  190. if !isExec {
  191. path = "/containers/" + id + "/resize?"
  192. } else {
  193. path = "/exec/" + id + "/resize?"
  194. }
  195. if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, nil)); err != nil {
  196. logrus.Debugf("Error resize: %s", err)
  197. }
  198. }
  199. func waitForExit(cli *DockerCli, containerID string) (int, error) {
  200. stream, _, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, nil)
  201. if err != nil {
  202. return -1, err
  203. }
  204. var out engine.Env
  205. if err := out.Decode(stream); err != nil {
  206. return -1, err
  207. }
  208. return out.GetInt("StatusCode"), nil
  209. }
  210. // getExitCode perform an inspect on the container. It returns
  211. // the running state and the exit code.
  212. func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
  213. stream, _, err := cli.call("GET", "/containers/"+containerID+"/json", nil, nil)
  214. if err != nil {
  215. // If we can't connect, then the daemon probably died.
  216. if err != ErrConnectionRefused {
  217. return false, -1, err
  218. }
  219. return false, -1, nil
  220. }
  221. var result engine.Env
  222. if err := result.Decode(stream); err != nil {
  223. return false, -1, err
  224. }
  225. state := result.GetSubEnv("State")
  226. return state.GetBool("Running"), state.GetInt("ExitCode"), nil
  227. }
  228. // getExecExitCode perform an inspect on the exec command. It returns
  229. // the running state and the exit code.
  230. func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
  231. stream, _, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil)
  232. if err != nil {
  233. // If we can't connect, then the daemon probably died.
  234. if err != ErrConnectionRefused {
  235. return false, -1, err
  236. }
  237. return false, -1, nil
  238. }
  239. var result engine.Env
  240. if err := result.Decode(stream); err != nil {
  241. return false, -1, err
  242. }
  243. return result.GetBool("Running"), result.GetInt("ExitCode"), nil
  244. }
  245. func (cli *DockerCli) monitorTtySize(id string, isExec bool) error {
  246. cli.resizeTty(id, isExec)
  247. sigchan := make(chan os.Signal, 1)
  248. gosignal.Notify(sigchan, signal.SIGWINCH)
  249. go func() {
  250. for _ = range sigchan {
  251. cli.resizeTty(id, isExec)
  252. }
  253. }()
  254. return nil
  255. }
  256. func (cli *DockerCli) getTtySize() (int, int) {
  257. if !cli.isTerminalOut {
  258. return 0, 0
  259. }
  260. ws, err := term.GetWinsize(cli.outFd)
  261. if err != nil {
  262. logrus.Debugf("Error getting size: %s", err)
  263. if ws == nil {
  264. return 0, 0
  265. }
  266. }
  267. return int(ws.Height), int(ws.Width)
  268. }
  269. func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
  270. if stream != nil {
  271. defer stream.Close()
  272. }
  273. if err != nil {
  274. return nil, statusCode, err
  275. }
  276. body, err := ioutil.ReadAll(stream)
  277. if err != nil {
  278. return nil, -1, err
  279. }
  280. return body, statusCode, nil
  281. }