utils.go 9.3 KB

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