utils.go 7.5 KB

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