utils.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package client
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/base64"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net"
  12. "net/http"
  13. "net/http/httputil"
  14. "net/url"
  15. "os"
  16. gosignal "os/signal"
  17. "regexp"
  18. goruntime "runtime"
  19. "strconv"
  20. "strings"
  21. "syscall"
  22. "github.com/dotcloud/docker/api"
  23. "github.com/dotcloud/docker/dockerversion"
  24. "github.com/dotcloud/docker/engine"
  25. "github.com/dotcloud/docker/pkg/term"
  26. "github.com/dotcloud/docker/registry"
  27. "github.com/dotcloud/docker/utils"
  28. )
  29. var (
  30. ErrConnectionRefused = errors.New("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  31. )
  32. func (cli *DockerCli) HTTPClient() *http.Client {
  33. tr := &http.Transport{
  34. Dial: func(network, addr string) (net.Conn, error) {
  35. return net.Dial(cli.proto, cli.addr)
  36. },
  37. }
  38. if cli.proto != "unix" {
  39. tr.TLSClientConfig = cli.tlsConfig
  40. }
  41. return &http.Client{Transport: tr}
  42. }
  43. func (cli *DockerCli) dial() (net.Conn, error) {
  44. if cli.tlsConfig != nil && cli.proto != "unix" {
  45. return tls.Dial(cli.proto, cli.addr, cli.tlsConfig)
  46. }
  47. return net.Dial(cli.proto, cli.addr)
  48. }
  49. func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo bool) (io.ReadCloser, int, error) {
  50. params := bytes.NewBuffer(nil)
  51. if data != nil {
  52. if env, ok := data.(engine.Env); ok {
  53. if err := env.Encode(params); err != nil {
  54. return nil, -1, err
  55. }
  56. } else {
  57. buf, err := json.Marshal(data)
  58. if err != nil {
  59. return nil, -1, err
  60. }
  61. if _, err := params.Write(buf); err != nil {
  62. return nil, -1, err
  63. }
  64. }
  65. }
  66. // fixme: refactor client to support redirect
  67. re := regexp.MustCompile("/+")
  68. path = re.ReplaceAllString(path, "/")
  69. req, err := http.NewRequest(method, fmt.Sprintf("http://v%s%s", api.APIVERSION, path), params)
  70. if err != nil {
  71. return nil, -1, err
  72. }
  73. if passAuthInfo {
  74. cli.LoadConfigFile()
  75. // Resolve the Auth config relevant for this server
  76. authConfig := cli.configFile.ResolveAuthConfig(registry.IndexServerAddress())
  77. getHeaders := func(authConfig registry.AuthConfig) (map[string][]string, error) {
  78. buf, err := json.Marshal(authConfig)
  79. if err != nil {
  80. return nil, err
  81. }
  82. registryAuthHeader := []string{
  83. base64.URLEncoding.EncodeToString(buf),
  84. }
  85. return map[string][]string{"X-Registry-Auth": registryAuthHeader}, nil
  86. }
  87. if headers, err := getHeaders(authConfig); err == nil && headers != nil {
  88. for k, v := range headers {
  89. req.Header[k] = v
  90. }
  91. }
  92. }
  93. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  94. req.Host = cli.addr
  95. if data != nil {
  96. req.Header.Set("Content-Type", "application/json")
  97. } else if method == "POST" {
  98. req.Header.Set("Content-Type", "plain/text")
  99. }
  100. resp, err := cli.HTTPClient().Do(req)
  101. if err != nil {
  102. if strings.Contains(err.Error(), "connection refused") {
  103. return nil, -1, ErrConnectionRefused
  104. }
  105. return nil, -1, err
  106. }
  107. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  108. body, err := ioutil.ReadAll(resp.Body)
  109. if err != nil {
  110. return nil, -1, err
  111. }
  112. if len(body) == 0 {
  113. return nil, resp.StatusCode, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(resp.StatusCode), req.URL)
  114. }
  115. return nil, resp.StatusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  116. }
  117. return resp.Body, resp.StatusCode, nil
  118. }
  119. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  120. return cli.streamHelper(method, path, true, in, out, nil, headers)
  121. }
  122. func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in io.Reader, stdout, stderr io.Writer, headers map[string][]string) error {
  123. if (method == "POST" || method == "PUT") && in == nil {
  124. in = bytes.NewReader([]byte{})
  125. }
  126. // fixme: refactor client to support redirect
  127. re := regexp.MustCompile("/+")
  128. path = re.ReplaceAllString(path, "/")
  129. req, err := http.NewRequest(method, fmt.Sprintf("http://v%s%s", api.APIVERSION, path), in)
  130. if err != nil {
  131. return err
  132. }
  133. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  134. req.Host = cli.addr
  135. if method == "POST" {
  136. req.Header.Set("Content-Type", "plain/text")
  137. }
  138. if headers != nil {
  139. for k, v := range headers {
  140. req.Header[k] = v
  141. }
  142. }
  143. resp, err := cli.HTTPClient().Do(req)
  144. if err != nil {
  145. if strings.Contains(err.Error(), "connection refused") {
  146. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  147. }
  148. return err
  149. }
  150. defer resp.Body.Close()
  151. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  152. body, err := ioutil.ReadAll(resp.Body)
  153. if err != nil {
  154. return err
  155. }
  156. if len(body) == 0 {
  157. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  158. }
  159. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  160. }
  161. if api.MatchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  162. return utils.DisplayJSONMessagesStream(resp.Body, stdout, cli.terminalFd, cli.isTerminal)
  163. }
  164. if stdout != nil || stderr != nil {
  165. // When TTY is ON, use regular copy
  166. if setRawTerminal {
  167. _, err = io.Copy(stdout, resp.Body)
  168. } else {
  169. _, err = utils.StdCopy(stdout, stderr, resp.Body)
  170. }
  171. utils.Debugf("[stream] End of stdout")
  172. return err
  173. }
  174. return nil
  175. }
  176. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
  177. defer func() {
  178. if started != nil {
  179. close(started)
  180. }
  181. }()
  182. // fixme: refactor client to support redirect
  183. re := regexp.MustCompile("/+")
  184. path = re.ReplaceAllString(path, "/")
  185. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), nil)
  186. if err != nil {
  187. return err
  188. }
  189. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  190. req.Header.Set("Content-Type", "plain/text")
  191. req.Host = cli.addr
  192. dial, err := cli.dial()
  193. if err != nil {
  194. if strings.Contains(err.Error(), "connection refused") {
  195. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  196. }
  197. return err
  198. }
  199. clientconn := httputil.NewClientConn(dial, nil)
  200. defer clientconn.Close()
  201. // Server hijacks the connection, error 'connection closed' expected
  202. clientconn.Do(req)
  203. rwc, br := clientconn.Hijack()
  204. defer rwc.Close()
  205. if started != nil {
  206. started <- rwc
  207. }
  208. var receiveStdout chan error
  209. var oldState *term.State
  210. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  211. oldState, err = term.SetRawTerminal(cli.terminalFd)
  212. if err != nil {
  213. return err
  214. }
  215. defer term.RestoreTerminal(cli.terminalFd, oldState)
  216. }
  217. if stdout != nil || stderr != nil {
  218. receiveStdout = utils.Go(func() (err error) {
  219. defer func() {
  220. if in != nil {
  221. if setRawTerminal && cli.isTerminal {
  222. term.RestoreTerminal(cli.terminalFd, oldState)
  223. }
  224. // For some reason this Close call blocks on darwin..
  225. // As the client exists right after, simply discard the close
  226. // until we find a better solution.
  227. if goruntime.GOOS != "darwin" {
  228. in.Close()
  229. }
  230. }
  231. }()
  232. // When TTY is ON, use regular copy
  233. if setRawTerminal {
  234. _, err = io.Copy(stdout, br)
  235. } else {
  236. _, err = utils.StdCopy(stdout, stderr, br)
  237. }
  238. utils.Debugf("[hijack] End of stdout")
  239. return err
  240. })
  241. }
  242. sendStdin := utils.Go(func() error {
  243. if in != nil {
  244. io.Copy(rwc, in)
  245. utils.Debugf("[hijack] End of stdin")
  246. }
  247. if tcpc, ok := rwc.(*net.TCPConn); ok {
  248. if err := tcpc.CloseWrite(); err != nil {
  249. utils.Debugf("Couldn't send EOF: %s\n", err)
  250. }
  251. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  252. if err := unixc.CloseWrite(); err != nil {
  253. utils.Debugf("Couldn't send EOF: %s\n", err)
  254. }
  255. }
  256. // Discard errors due to pipe interruption
  257. return nil
  258. })
  259. if stdout != nil || stderr != nil {
  260. if err := <-receiveStdout; err != nil {
  261. utils.Debugf("Error receiveStdout: %s", err)
  262. return err
  263. }
  264. }
  265. if !cli.isTerminal {
  266. if err := <-sendStdin; err != nil {
  267. utils.Debugf("Error sendStdin: %s", err)
  268. return err
  269. }
  270. }
  271. return nil
  272. }
  273. func (cli *DockerCli) resizeTty(id string) {
  274. height, width := cli.getTtySize()
  275. if height == 0 && width == 0 {
  276. return
  277. }
  278. v := url.Values{}
  279. v.Set("h", strconv.Itoa(height))
  280. v.Set("w", strconv.Itoa(width))
  281. if _, _, err := readBody(cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil, false)); err != nil {
  282. utils.Debugf("Error resize: %s", err)
  283. }
  284. }
  285. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  286. stream, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil, false)
  287. if err != nil {
  288. return -1, err
  289. }
  290. var out engine.Env
  291. if err := out.Decode(stream); err != nil {
  292. return -1, err
  293. }
  294. return out.GetInt("StatusCode"), nil
  295. }
  296. // getExitCode perform an inspect on the container. It returns
  297. // the running state and the exit code.
  298. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  299. body, _, err := readBody(cli.call("GET", "/containers/"+containerId+"/json", nil, false))
  300. if err != nil {
  301. // If we can't connect, then the daemon probably died.
  302. if err != ErrConnectionRefused {
  303. return false, -1, err
  304. }
  305. return false, -1, nil
  306. }
  307. c := &api.Container{}
  308. if err := json.Unmarshal(body, c); err != nil {
  309. return false, -1, err
  310. }
  311. return c.State.Running, c.State.ExitCode, nil
  312. }
  313. func (cli *DockerCli) monitorTtySize(id string) error {
  314. cli.resizeTty(id)
  315. sigchan := make(chan os.Signal, 1)
  316. gosignal.Notify(sigchan, syscall.SIGWINCH)
  317. go func() {
  318. for _ = range sigchan {
  319. cli.resizeTty(id)
  320. }
  321. }()
  322. return nil
  323. }
  324. func (cli *DockerCli) getTtySize() (int, int) {
  325. if !cli.isTerminal {
  326. return 0, 0
  327. }
  328. ws, err := term.GetWinsize(cli.terminalFd)
  329. if err != nil {
  330. utils.Debugf("Error getting size: %s", err)
  331. if ws == nil {
  332. return 0, 0
  333. }
  334. }
  335. return int(ws.Height), int(ws.Width)
  336. }
  337. func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
  338. if stream != nil {
  339. defer stream.Close()
  340. }
  341. if err != nil {
  342. return nil, statusCode, err
  343. }
  344. body, err := ioutil.ReadAll(stream)
  345. if err != nil {
  346. return nil, -1, err
  347. }
  348. return body, statusCode, nil
  349. }