utils.go 9.5 KB

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