utils.go 9.5 KB

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