utils.go 10 KB

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