utils.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. "runtime"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/Sirupsen/logrus"
  19. "github.com/docker/docker/api"
  20. "github.com/docker/docker/autogen/dockerversion"
  21. "github.com/docker/docker/engine"
  22. "github.com/docker/docker/pkg/jsonmessage"
  23. "github.com/docker/docker/pkg/signal"
  24. "github.com/docker/docker/pkg/stdcopy"
  25. "github.com/docker/docker/pkg/term"
  26. "github.com/docker/docker/registry"
  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. return &http.Client{Transport: cli.transport}
  33. }
  34. func (cli *DockerCli) encodeData(data interface{}) (*bytes.Buffer, error) {
  35. params := bytes.NewBuffer(nil)
  36. if data != nil {
  37. if env, ok := data.(engine.Env); ok {
  38. if err := env.Encode(params); err != nil {
  39. return nil, err
  40. }
  41. } else {
  42. buf, err := json.Marshal(data)
  43. if err != nil {
  44. return nil, err
  45. }
  46. if _, err := params.Write(buf); err != nil {
  47. return nil, err
  48. }
  49. }
  50. }
  51. return params, nil
  52. }
  53. func (cli *DockerCli) clientRequest(method, path string, in io.Reader, headers map[string][]string) (io.ReadCloser, string, int, error) {
  54. expectedPayload := (method == "POST" || method == "PUT")
  55. if expectedPayload && in == nil {
  56. in = bytes.NewReader([]byte{})
  57. }
  58. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), in)
  59. if err != nil {
  60. return nil, "", -1, err
  61. }
  62. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  63. req.URL.Host = cli.addr
  64. req.URL.Scheme = cli.scheme
  65. if headers != nil {
  66. for k, v := range headers {
  67. req.Header[k] = v
  68. }
  69. }
  70. if expectedPayload && req.Header.Get("Content-Type") == "" {
  71. req.Header.Set("Content-Type", "text/plain")
  72. }
  73. resp, err := cli.HTTPClient().Do(req)
  74. statusCode := -1
  75. if resp != nil {
  76. statusCode = resp.StatusCode
  77. }
  78. if err != nil {
  79. if strings.Contains(err.Error(), "connection refused") {
  80. return nil, "", statusCode, ErrConnectionRefused
  81. }
  82. if cli.tlsConfig == nil {
  83. return nil, "", statusCode, fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err)
  84. }
  85. return nil, "", statusCode, fmt.Errorf("An error occurred trying to connect: %v", err)
  86. }
  87. if statusCode < 200 || statusCode >= 400 {
  88. body, err := ioutil.ReadAll(resp.Body)
  89. if err != nil {
  90. return nil, "", statusCode, err
  91. }
  92. if len(body) == 0 {
  93. return nil, "", statusCode, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(statusCode), req.URL)
  94. }
  95. return nil, "", statusCode, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body))
  96. }
  97. return resp.Body, resp.Header.Get("Content-Type"), statusCode, nil
  98. }
  99. func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reader, out io.Writer, index *registry.IndexInfo, cmdName string) (io.ReadCloser, int, error) {
  100. cmdAttempt := func(authConfig registry.AuthConfig) (io.ReadCloser, int, error) {
  101. buf, err := json.Marshal(authConfig)
  102. if err != nil {
  103. return nil, -1, err
  104. }
  105. registryAuthHeader := []string{
  106. base64.URLEncoding.EncodeToString(buf),
  107. }
  108. // begin the request
  109. body, contentType, statusCode, err := cli.clientRequest(method, path, in, map[string][]string{
  110. "X-Registry-Auth": registryAuthHeader,
  111. })
  112. if err == nil && out != nil {
  113. // If we are streaming output, complete the stream since
  114. // errors may not appear until later.
  115. err = cli.streamBody(body, contentType, true, out, nil)
  116. }
  117. if err != nil {
  118. // Since errors in a stream appear after status 200 has been written,
  119. // we may need to change the status code.
  120. if strings.Contains(err.Error(), "Authentication is required") ||
  121. strings.Contains(err.Error(), "Status 401") ||
  122. strings.Contains(err.Error(), "status code 401") {
  123. statusCode = http.StatusUnauthorized
  124. }
  125. }
  126. return body, statusCode, err
  127. }
  128. // Resolve the Auth config relevant for this server
  129. authConfig := cli.configFile.ResolveAuthConfig(index)
  130. body, statusCode, err := cmdAttempt(authConfig)
  131. if statusCode == http.StatusUnauthorized {
  132. fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName)
  133. if err = cli.CmdLogin(index.GetAuthConfigKey()); err != nil {
  134. return nil, -1, err
  135. }
  136. authConfig = cli.configFile.ResolveAuthConfig(index)
  137. return cmdAttempt(authConfig)
  138. }
  139. return body, statusCode, err
  140. }
  141. func (cli *DockerCli) call(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, int, error) {
  142. params, err := cli.encodeData(data)
  143. if err != nil {
  144. return nil, -1, err
  145. }
  146. if data != nil {
  147. if headers == nil {
  148. headers = make(map[string][]string)
  149. }
  150. headers["Content-Type"] = []string{"application/json"}
  151. }
  152. body, _, statusCode, err := cli.clientRequest(method, path, params, headers)
  153. return body, statusCode, err
  154. }
  155. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  156. return cli.streamHelper(method, path, true, in, out, nil, headers)
  157. }
  158. func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in io.Reader, stdout, stderr io.Writer, headers map[string][]string) error {
  159. body, contentType, _, err := cli.clientRequest(method, path, in, headers)
  160. if err != nil {
  161. return err
  162. }
  163. return cli.streamBody(body, contentType, setRawTerminal, stdout, stderr)
  164. }
  165. func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, setRawTerminal bool, stdout, stderr io.Writer) error {
  166. defer body.Close()
  167. if api.MatchesContentType(contentType, "application/json") {
  168. return jsonmessage.DisplayJSONMessagesStream(body, stdout, cli.outFd, cli.isTerminalOut)
  169. }
  170. if stdout != nil || stderr != nil {
  171. // When TTY is ON, use regular copy
  172. var err error
  173. if setRawTerminal {
  174. _, err = io.Copy(stdout, body)
  175. } else {
  176. _, err = stdcopy.StdCopy(stdout, stderr, body)
  177. }
  178. logrus.Debugf("[stream] End of stdout")
  179. return err
  180. }
  181. return nil
  182. }
  183. func (cli *DockerCli) resizeTty(id string, isExec bool) {
  184. height, width := cli.getTtySize()
  185. if height == 0 && width == 0 {
  186. return
  187. }
  188. v := url.Values{}
  189. v.Set("h", strconv.Itoa(height))
  190. v.Set("w", strconv.Itoa(width))
  191. path := ""
  192. if !isExec {
  193. path = "/containers/" + id + "/resize?"
  194. } else {
  195. path = "/exec/" + id + "/resize?"
  196. }
  197. if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, nil)); err != nil {
  198. logrus.Debugf("Error resize: %s", err)
  199. }
  200. }
  201. func waitForExit(cli *DockerCli, containerID string) (int, error) {
  202. stream, _, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, nil)
  203. if err != nil {
  204. return -1, err
  205. }
  206. var out engine.Env
  207. if err := out.Decode(stream); err != nil {
  208. return -1, err
  209. }
  210. return out.GetInt("StatusCode"), nil
  211. }
  212. // getExitCode perform an inspect on the container. It returns
  213. // the running state and the exit code.
  214. func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
  215. stream, _, err := cli.call("GET", "/containers/"+containerID+"/json", nil, nil)
  216. if err != nil {
  217. // If we can't connect, then the daemon probably died.
  218. if err != ErrConnectionRefused {
  219. return false, -1, err
  220. }
  221. return false, -1, nil
  222. }
  223. var result engine.Env
  224. if err := result.Decode(stream); err != nil {
  225. return false, -1, err
  226. }
  227. state := result.GetSubEnv("State")
  228. return state.GetBool("Running"), state.GetInt("ExitCode"), nil
  229. }
  230. // getExecExitCode perform an inspect on the exec command. It returns
  231. // the running state and the exit code.
  232. func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
  233. stream, _, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil)
  234. if err != nil {
  235. // If we can't connect, then the daemon probably died.
  236. if err != ErrConnectionRefused {
  237. return false, -1, err
  238. }
  239. return false, -1, nil
  240. }
  241. var result engine.Env
  242. if err := result.Decode(stream); err != nil {
  243. return false, -1, err
  244. }
  245. return result.GetBool("Running"), result.GetInt("ExitCode"), nil
  246. }
  247. func (cli *DockerCli) monitorTtySize(id string, isExec bool) error {
  248. cli.resizeTty(id, isExec)
  249. if runtime.GOOS == "windows" {
  250. go func() {
  251. prevH, prevW := cli.getTtySize()
  252. for {
  253. time.Sleep(time.Millisecond * 250)
  254. h, w := cli.getTtySize()
  255. if prevW != w || prevH != h {
  256. cli.resizeTty(id, isExec)
  257. }
  258. prevH = h
  259. prevW = w
  260. }
  261. }()
  262. } else {
  263. sigchan := make(chan os.Signal, 1)
  264. gosignal.Notify(sigchan, signal.SIGWINCH)
  265. go func() {
  266. for _ = range sigchan {
  267. cli.resizeTty(id, isExec)
  268. }
  269. }()
  270. }
  271. return nil
  272. }
  273. func (cli *DockerCli) getTtySize() (int, int) {
  274. if !cli.isTerminalOut {
  275. return 0, 0
  276. }
  277. ws, err := term.GetWinsize(cli.outFd)
  278. if err != nil {
  279. logrus.Debugf("Error getting size: %s", err)
  280. if ws == nil {
  281. return 0, 0
  282. }
  283. }
  284. return int(ws.Height), int(ws.Width)
  285. }
  286. func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
  287. if stream != nil {
  288. defer stream.Close()
  289. }
  290. if err != nil {
  291. return nil, statusCode, err
  292. }
  293. body, err := ioutil.ReadAll(stream)
  294. if err != nil {
  295. return nil, -1, err
  296. }
  297. return body, statusCode, nil
  298. }