utils.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package client
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. gosignal "os/signal"
  15. "strconv"
  16. "strings"
  17. "syscall"
  18. "time"
  19. "github.com/docker/docker/api"
  20. "github.com/docker/docker/dockerversion"
  21. "github.com/docker/docker/engine"
  22. "github.com/docker/docker/pkg/log"
  23. "github.com/docker/docker/pkg/stdcopy"
  24. "github.com/docker/docker/pkg/term"
  25. "github.com/docker/docker/registry"
  26. "github.com/docker/docker/utils"
  27. )
  28. var (
  29. ErrConnectionRefused = errors.New("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  30. )
  31. func (cli *DockerCli) HTTPClient() *http.Client {
  32. tr := &http.Transport{
  33. TLSClientConfig: cli.tlsConfig,
  34. Dial: func(network, addr string) (net.Conn, error) {
  35. // Why 32? See issue 8035
  36. return net.DialTimeout(cli.proto, cli.addr, 32*time.Second)
  37. },
  38. }
  39. return &http.Client{Transport: tr}
  40. }
  41. func (cli *DockerCli) encodeData(data interface{}) (*bytes.Buffer, error) {
  42. params := bytes.NewBuffer(nil)
  43. if data != nil {
  44. if env, ok := data.(engine.Env); ok {
  45. if err := env.Encode(params); err != nil {
  46. return nil, err
  47. }
  48. } else {
  49. buf, err := json.Marshal(data)
  50. if err != nil {
  51. return nil, err
  52. }
  53. if _, err := params.Write(buf); err != nil {
  54. return nil, err
  55. }
  56. }
  57. }
  58. return params, nil
  59. }
  60. func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo bool) (io.ReadCloser, int, error) {
  61. params, err := cli.encodeData(data)
  62. if err != nil {
  63. return nil, -1, err
  64. }
  65. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), params)
  66. if err != nil {
  67. return nil, -1, err
  68. }
  69. if passAuthInfo {
  70. cli.LoadConfigFile()
  71. // Resolve the Auth config relevant for this server
  72. authConfig := cli.configFile.ResolveAuthConfig(registry.IndexServerAddress())
  73. getHeaders := func(authConfig registry.AuthConfig) (map[string][]string, error) {
  74. buf, err := json.Marshal(authConfig)
  75. if err != nil {
  76. return nil, err
  77. }
  78. registryAuthHeader := []string{
  79. base64.URLEncoding.EncodeToString(buf),
  80. }
  81. return map[string][]string{"X-Registry-Auth": registryAuthHeader}, nil
  82. }
  83. if headers, err := getHeaders(authConfig); err == nil && headers != nil {
  84. for k, v := range headers {
  85. req.Header[k] = v
  86. }
  87. }
  88. }
  89. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  90. req.URL.Host = cli.addr
  91. req.URL.Scheme = cli.scheme
  92. if data != nil {
  93. req.Header.Set("Content-Type", "application/json")
  94. } else if method == "POST" {
  95. req.Header.Set("Content-Type", "plain/text")
  96. }
  97. resp, err := cli.HTTPClient().Do(req)
  98. if err != nil {
  99. if strings.Contains(err.Error(), "connection refused") {
  100. return nil, -1, ErrConnectionRefused
  101. }
  102. return nil, -1, err
  103. }
  104. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  105. body, err := ioutil.ReadAll(resp.Body)
  106. if err != nil {
  107. return nil, -1, err
  108. }
  109. if len(body) == 0 {
  110. return nil, resp.StatusCode, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(resp.StatusCode), req.URL)
  111. }
  112. return nil, resp.StatusCode, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body))
  113. }
  114. return resp.Body, resp.StatusCode, nil
  115. }
  116. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  117. return cli.streamHelper(method, path, true, in, out, nil, headers)
  118. }
  119. func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in io.Reader, stdout, stderr io.Writer, headers map[string][]string) error {
  120. if (method == "POST" || method == "PUT") && in == nil {
  121. in = bytes.NewReader([]byte{})
  122. }
  123. req, err := http.NewRequest(method, fmt.Sprintf("http://v%s%s", api.APIVERSION, path), in)
  124. if err != nil {
  125. return err
  126. }
  127. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  128. req.URL.Host = cli.addr
  129. req.URL.Scheme = cli.scheme
  130. if method == "POST" {
  131. req.Header.Set("Content-Type", "plain/text")
  132. }
  133. if headers != nil {
  134. for k, v := range headers {
  135. req.Header[k] = v
  136. }
  137. }
  138. resp, err := cli.HTTPClient().Do(req)
  139. if err != nil {
  140. if strings.Contains(err.Error(), "connection refused") {
  141. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  142. }
  143. return err
  144. }
  145. defer resp.Body.Close()
  146. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  147. body, err := ioutil.ReadAll(resp.Body)
  148. if err != nil {
  149. return err
  150. }
  151. if len(body) == 0 {
  152. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  153. }
  154. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  155. }
  156. if api.MatchesContentType(resp.Header.Get("Content-Type"), "application/json") || api.MatchesContentType(resp.Header.Get("Content-Type"), "application/x-json-stream") {
  157. return utils.DisplayJSONMessagesStream(resp.Body, stdout, cli.terminalFd, cli.isTerminal)
  158. }
  159. if stdout != nil || stderr != nil {
  160. // When TTY is ON, use regular copy
  161. if setRawTerminal {
  162. _, err = io.Copy(stdout, resp.Body)
  163. } else {
  164. _, err = stdcopy.StdCopy(stdout, stderr, resp.Body)
  165. }
  166. log.Debugf("[stream] End of stdout")
  167. return err
  168. }
  169. return nil
  170. }
  171. func (cli *DockerCli) resizeTty(id string, isExec bool) {
  172. height, width := cli.getTtySize()
  173. if height == 0 && width == 0 {
  174. return
  175. }
  176. v := url.Values{}
  177. v.Set("h", strconv.Itoa(height))
  178. v.Set("w", strconv.Itoa(width))
  179. path := ""
  180. if !isExec {
  181. path = "/containers/" + id + "/resize?"
  182. } else {
  183. path = "/exec/" + id + "/resize?"
  184. }
  185. if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, false)); err != nil {
  186. log.Debugf("Error resize: %s", err)
  187. }
  188. }
  189. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  190. stream, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil, false)
  191. if err != nil {
  192. return -1, err
  193. }
  194. var out engine.Env
  195. if err := out.Decode(stream); err != nil {
  196. return -1, err
  197. }
  198. return out.GetInt("StatusCode"), nil
  199. }
  200. // getExitCode perform an inspect on the container. It returns
  201. // the running state and the exit code.
  202. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  203. steam, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil, false)
  204. if err != nil {
  205. // If we can't connect, then the daemon probably died.
  206. if err != ErrConnectionRefused {
  207. return false, -1, err
  208. }
  209. return false, -1, nil
  210. }
  211. var result engine.Env
  212. if err := result.Decode(steam); err != nil {
  213. return false, -1, err
  214. }
  215. state := result.GetSubEnv("State")
  216. return state.GetBool("Running"), state.GetInt("ExitCode"), nil
  217. }
  218. func (cli *DockerCli) monitorTtySize(id string, isExec bool) error {
  219. cli.resizeTty(id, isExec)
  220. sigchan := make(chan os.Signal, 1)
  221. gosignal.Notify(sigchan, syscall.SIGWINCH)
  222. go func() {
  223. for _ = range sigchan {
  224. cli.resizeTty(id, isExec)
  225. }
  226. }()
  227. return nil
  228. }
  229. func (cli *DockerCli) getTtySize() (int, int) {
  230. if !cli.isTerminal {
  231. return 0, 0
  232. }
  233. ws, err := term.GetWinsize(cli.terminalFd)
  234. if err != nil {
  235. log.Debugf("Error getting size: %s", err)
  236. if ws == nil {
  237. return 0, 0
  238. }
  239. }
  240. return int(ws.Height), int(ws.Width)
  241. }
  242. func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
  243. if stream != nil {
  244. defer stream.Close()
  245. }
  246. if err != nil {
  247. return nil, statusCode, err
  248. }
  249. body, err := ioutil.ReadAll(stream)
  250. if err != nil {
  251. return nil, -1, err
  252. }
  253. return body, statusCode, nil
  254. }