utils.go 6.7 KB

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