utils.go 7.0 KB

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