utils.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. if (method == "POST" || method == "PUT") && in == nil {
  125. in = bytes.NewReader([]byte{})
  126. }
  127. // fixme: refactor client to support redirect
  128. re := regexp.MustCompile("/+")
  129. path = re.ReplaceAllString(path, "/")
  130. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), in)
  131. if err != nil {
  132. return err
  133. }
  134. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  135. req.Host = cli.addr
  136. if method == "POST" {
  137. req.Header.Set("Content-Type", "plain/text")
  138. }
  139. if headers != nil {
  140. for k, v := range headers {
  141. req.Header[k] = v
  142. }
  143. }
  144. dial, err := cli.dial()
  145. if err != nil {
  146. if strings.Contains(err.Error(), "connection refused") {
  147. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  148. }
  149. return err
  150. }
  151. clientconn := httputil.NewClientConn(dial, nil)
  152. resp, err := clientconn.Do(req)
  153. defer clientconn.Close()
  154. if err != nil {
  155. if strings.Contains(err.Error(), "connection refused") {
  156. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  157. }
  158. return err
  159. }
  160. defer resp.Body.Close()
  161. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  162. body, err := ioutil.ReadAll(resp.Body)
  163. if err != nil {
  164. return err
  165. }
  166. if len(body) == 0 {
  167. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  168. }
  169. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  170. }
  171. if api.MatchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  172. return utils.DisplayJSONMessagesStream(resp.Body, out, cli.terminalFd, cli.isTerminal)
  173. }
  174. if _, err := io.Copy(out, resp.Body); err != nil {
  175. return err
  176. }
  177. return nil
  178. }
  179. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
  180. defer func() {
  181. if started != nil {
  182. close(started)
  183. }
  184. }()
  185. // fixme: refactor client to support redirect
  186. re := regexp.MustCompile("/+")
  187. path = re.ReplaceAllString(path, "/")
  188. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), nil)
  189. if err != nil {
  190. return err
  191. }
  192. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  193. req.Header.Set("Content-Type", "plain/text")
  194. req.Host = cli.addr
  195. dial, err := cli.dial()
  196. if err != nil {
  197. if strings.Contains(err.Error(), "connection refused") {
  198. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  199. }
  200. return err
  201. }
  202. clientconn := httputil.NewClientConn(dial, nil)
  203. defer clientconn.Close()
  204. // Server hijacks the connection, error 'connection closed' expected
  205. clientconn.Do(req)
  206. rwc, br := clientconn.Hijack()
  207. defer rwc.Close()
  208. if started != nil {
  209. started <- rwc
  210. }
  211. var receiveStdout chan error
  212. var oldState *term.State
  213. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  214. oldState, err = term.SetRawTerminal(cli.terminalFd)
  215. if err != nil {
  216. return err
  217. }
  218. defer term.RestoreTerminal(cli.terminalFd, oldState)
  219. }
  220. if stdout != nil || stderr != nil {
  221. receiveStdout = utils.Go(func() (err error) {
  222. defer func() {
  223. if in != nil {
  224. if setRawTerminal && cli.isTerminal {
  225. term.RestoreTerminal(cli.terminalFd, oldState)
  226. }
  227. // For some reason this Close call blocks on darwin..
  228. // As the client exists right after, simply discard the close
  229. // until we find a better solution.
  230. if goruntime.GOOS != "darwin" {
  231. in.Close()
  232. }
  233. }
  234. }()
  235. // When TTY is ON, use regular copy
  236. if setRawTerminal {
  237. _, err = io.Copy(stdout, br)
  238. } else {
  239. _, err = utils.StdCopy(stdout, stderr, br)
  240. }
  241. utils.Debugf("[hijack] End of stdout")
  242. return err
  243. })
  244. }
  245. sendStdin := utils.Go(func() error {
  246. if in != nil {
  247. io.Copy(rwc, in)
  248. utils.Debugf("[hijack] End of stdin")
  249. }
  250. if tcpc, ok := rwc.(*net.TCPConn); ok {
  251. if err := tcpc.CloseWrite(); err != nil {
  252. utils.Errorf("Couldn't send EOF: %s\n", err)
  253. }
  254. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  255. if err := unixc.CloseWrite(); err != nil {
  256. utils.Errorf("Couldn't send EOF: %s\n", err)
  257. }
  258. }
  259. // Discard errors due to pipe interruption
  260. return nil
  261. })
  262. if stdout != nil || stderr != nil {
  263. if err := <-receiveStdout; err != nil {
  264. utils.Errorf("Error receiveStdout: %s", err)
  265. return err
  266. }
  267. }
  268. if !cli.isTerminal {
  269. if err := <-sendStdin; err != nil {
  270. utils.Errorf("Error sendStdin: %s", err)
  271. return err
  272. }
  273. }
  274. return nil
  275. }
  276. func (cli *DockerCli) resizeTty(id string) {
  277. height, width := cli.getTtySize()
  278. if height == 0 && width == 0 {
  279. return
  280. }
  281. v := url.Values{}
  282. v.Set("h", strconv.Itoa(height))
  283. v.Set("w", strconv.Itoa(width))
  284. if _, _, err := readBody(cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil, false)); err != nil {
  285. utils.Errorf("Error resize: %s", err)
  286. }
  287. }
  288. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  289. stream, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil, false)
  290. if err != nil {
  291. return -1, err
  292. }
  293. var out engine.Env
  294. if err := out.Decode(stream); err != nil {
  295. return -1, err
  296. }
  297. return out.GetInt("StatusCode"), nil
  298. }
  299. // getExitCode perform an inspect on the container. It returns
  300. // the running state and the exit code.
  301. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  302. body, _, err := readBody(cli.call("GET", "/containers/"+containerId+"/json", nil, false))
  303. if err != nil {
  304. // If we can't connect, then the daemon probably died.
  305. if err != ErrConnectionRefused {
  306. return false, -1, err
  307. }
  308. return false, -1, nil
  309. }
  310. c := &api.Container{}
  311. if err := json.Unmarshal(body, c); err != nil {
  312. return false, -1, err
  313. }
  314. return c.State.Running, c.State.ExitCode, nil
  315. }
  316. func (cli *DockerCli) monitorTtySize(id string) error {
  317. cli.resizeTty(id)
  318. sigchan := make(chan os.Signal, 1)
  319. gosignal.Notify(sigchan, syscall.SIGWINCH)
  320. go func() {
  321. for _ = range sigchan {
  322. cli.resizeTty(id)
  323. }
  324. }()
  325. return nil
  326. }
  327. func (cli *DockerCli) getTtySize() (int, int) {
  328. if !cli.isTerminal {
  329. return 0, 0
  330. }
  331. ws, err := term.GetWinsize(cli.terminalFd)
  332. if err != nil {
  333. utils.Errorf("Error getting size: %s", err)
  334. if ws == nil {
  335. return 0, 0
  336. }
  337. }
  338. return int(ws.Height), int(ws.Width)
  339. }
  340. func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
  341. if stream != nil {
  342. defer stream.Close()
  343. }
  344. if err != nil {
  345. return nil, statusCode, err
  346. }
  347. body, err := ioutil.ReadAll(stream)
  348. if err != nil {
  349. return nil, -1, err
  350. }
  351. return body, statusCode, nil
  352. }