utils.go 9.2 KB

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