utils.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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("http://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.Host = cli.addr
  80. if data != nil {
  81. req.Header.Set("Content-Type", "application/json")
  82. } else if method == "POST" {
  83. req.Header.Set("Content-Type", "plain/text")
  84. }
  85. resp, err := cli.HTTPClient().Do(req)
  86. if err != nil {
  87. if strings.Contains(err.Error(), "connection refused") {
  88. return nil, -1, ErrConnectionRefused
  89. }
  90. return nil, -1, err
  91. }
  92. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  93. body, err := ioutil.ReadAll(resp.Body)
  94. if err != nil {
  95. return nil, -1, err
  96. }
  97. if len(body) == 0 {
  98. 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)
  99. }
  100. return nil, resp.StatusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  101. }
  102. return resp.Body, resp.StatusCode, nil
  103. }
  104. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  105. return cli.streamHelper(method, path, true, in, out, nil, headers)
  106. }
  107. func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in io.Reader, stdout, stderr io.Writer, headers map[string][]string) error {
  108. if (method == "POST" || method == "PUT") && in == nil {
  109. in = bytes.NewReader([]byte{})
  110. }
  111. req, err := http.NewRequest(method, fmt.Sprintf("http://v%s%s", api.APIVERSION, path), in)
  112. if err != nil {
  113. return err
  114. }
  115. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  116. req.Host = cli.addr
  117. if method == "POST" {
  118. req.Header.Set("Content-Type", "plain/text")
  119. }
  120. if headers != nil {
  121. for k, v := range headers {
  122. req.Header[k] = v
  123. }
  124. }
  125. resp, err := cli.HTTPClient().Do(req)
  126. if err != nil {
  127. if strings.Contains(err.Error(), "connection refused") {
  128. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  129. }
  130. return err
  131. }
  132. defer resp.Body.Close()
  133. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  134. body, err := ioutil.ReadAll(resp.Body)
  135. if err != nil {
  136. return err
  137. }
  138. if len(body) == 0 {
  139. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  140. }
  141. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  142. }
  143. if api.MatchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  144. return utils.DisplayJSONMessagesStream(resp.Body, stdout, cli.terminalFd, cli.isTerminal)
  145. }
  146. if stdout != nil || stderr != nil {
  147. // When TTY is ON, use regular copy
  148. if setRawTerminal {
  149. _, err = io.Copy(stdout, resp.Body)
  150. } else {
  151. _, err = utils.StdCopy(stdout, stderr, resp.Body)
  152. }
  153. utils.Debugf("[stream] End of stdout")
  154. return err
  155. }
  156. return nil
  157. }
  158. func (cli *DockerCli) resizeTty(id string) {
  159. height, width := cli.getTtySize()
  160. if height == 0 && width == 0 {
  161. return
  162. }
  163. v := url.Values{}
  164. v.Set("h", strconv.Itoa(height))
  165. v.Set("w", strconv.Itoa(width))
  166. if _, _, err := readBody(cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil, false)); err != nil {
  167. utils.Debugf("Error resize: %s", err)
  168. }
  169. }
  170. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  171. stream, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil, false)
  172. if err != nil {
  173. return -1, err
  174. }
  175. var out engine.Env
  176. if err := out.Decode(stream); err != nil {
  177. return -1, err
  178. }
  179. return out.GetInt("StatusCode"), nil
  180. }
  181. // getExitCode perform an inspect on the container. It returns
  182. // the running state and the exit code.
  183. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  184. body, _, err := readBody(cli.call("GET", "/containers/"+containerId+"/json", nil, false))
  185. if err != nil {
  186. // If we can't connect, then the daemon probably died.
  187. if err != ErrConnectionRefused {
  188. return false, -1, err
  189. }
  190. return false, -1, nil
  191. }
  192. c := &api.Container{}
  193. if err := json.Unmarshal(body, c); err != nil {
  194. return false, -1, err
  195. }
  196. return c.State.Running, c.State.ExitCode, nil
  197. }
  198. func (cli *DockerCli) monitorTtySize(id string) error {
  199. cli.resizeTty(id)
  200. sigchan := make(chan os.Signal, 1)
  201. gosignal.Notify(sigchan, syscall.SIGWINCH)
  202. go func() {
  203. for _ = range sigchan {
  204. cli.resizeTty(id)
  205. }
  206. }()
  207. return nil
  208. }
  209. func (cli *DockerCli) getTtySize() (int, int) {
  210. if !cli.isTerminal {
  211. return 0, 0
  212. }
  213. ws, err := term.GetWinsize(cli.terminalFd)
  214. if err != nil {
  215. utils.Debugf("Error getting size: %s", err)
  216. if ws == nil {
  217. return 0, 0
  218. }
  219. }
  220. return int(ws.Height), int(ws.Width)
  221. }
  222. func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
  223. if stream != nil {
  224. defer stream.Close()
  225. }
  226. if err != nil {
  227. return nil, statusCode, err
  228. }
  229. body, err := ioutil.ReadAll(stream)
  230. if err != nil {
  231. return nil, -1, err
  232. }
  233. return body, statusCode, nil
  234. }