client.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // +build ignore
  2. package server
  3. import (
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "strconv"
  12. etcdErr "github.com/coreos/etcd/error"
  13. "github.com/coreos/etcd/log"
  14. )
  15. // Client sends various requests using HTTP API.
  16. // It is different from raft communication, and doesn't record anything in the log.
  17. // The argument url is required to contain scheme and host only, and
  18. // there is no trailing slash in it.
  19. // Public functions return "etcd/error".Error intentionally to figure out
  20. // etcd error code easily.
  21. // TODO(yichengq): It is similar to go-etcd. But it could have many efforts
  22. // to integrate the two. Leave it for further discussion.
  23. type Client struct {
  24. http.Client
  25. }
  26. func NewClient(transport http.RoundTripper) *Client {
  27. return &Client{http.Client{Transport: transport}}
  28. }
  29. // CheckVersion returns true when the version check on the server returns 200.
  30. func (c *Client) CheckVersion(url string, version int) (bool, *etcdErr.Error) {
  31. resp, err := c.Get(url + fmt.Sprintf("/version/%d/check", version))
  32. if err != nil {
  33. return false, clientError(err)
  34. }
  35. defer resp.Body.Close()
  36. return resp.StatusCode == 200, nil
  37. }
  38. // GetVersion fetches the peer version of a cluster.
  39. func (c *Client) GetVersion(url string) (int, *etcdErr.Error) {
  40. resp, err := c.Get(url + "/version")
  41. if err != nil {
  42. return 0, clientError(err)
  43. }
  44. defer resp.Body.Close()
  45. body, err := ioutil.ReadAll(resp.Body)
  46. if err != nil {
  47. return 0, clientError(err)
  48. }
  49. // Parse version number.
  50. version, err := strconv.Atoi(string(body))
  51. if err != nil {
  52. return 0, clientError(err)
  53. }
  54. return version, nil
  55. }
  56. func (c *Client) GetMachines(url string) ([]*machineMessage, *etcdErr.Error) {
  57. resp, err := c.Get(url + "/v2/admin/machines")
  58. if err != nil {
  59. return nil, clientError(err)
  60. }
  61. msgs := new([]*machineMessage)
  62. if uerr := c.parseJSONResponse(resp, msgs); uerr != nil {
  63. return nil, uerr
  64. }
  65. return *msgs, nil
  66. }
  67. func (c *Client) GetClusterConfig(url string) (*ClusterConfig, *etcdErr.Error) {
  68. resp, err := c.Get(url + "/v2/admin/config")
  69. if err != nil {
  70. return nil, clientError(err)
  71. }
  72. config := new(ClusterConfig)
  73. if uerr := c.parseJSONResponse(resp, config); uerr != nil {
  74. return nil, uerr
  75. }
  76. return config, nil
  77. }
  78. // AddMachine adds machine to the cluster.
  79. // The first return value is the commit index of join command.
  80. func (c *Client) AddMachine(url string, cmd *JoinCommand) (uint64, *etcdErr.Error) {
  81. b, _ := json.Marshal(cmd)
  82. url = url + "/join"
  83. log.Infof("Send Join Request to %s", url)
  84. resp, err := c.put(url, b)
  85. if err != nil {
  86. return 0, clientError(err)
  87. }
  88. defer resp.Body.Close()
  89. if err := c.checkErrorResponse(resp); err != nil {
  90. return 0, err
  91. }
  92. b, err = ioutil.ReadAll(resp.Body)
  93. if err != nil {
  94. return 0, clientError(err)
  95. }
  96. index, numRead := binary.Uvarint(b)
  97. if numRead < 0 {
  98. return 0, clientError(fmt.Errorf("buf too small, or value too large"))
  99. }
  100. return index, nil
  101. }
  102. func (c *Client) parseJSONResponse(resp *http.Response, val interface{}) *etcdErr.Error {
  103. defer resp.Body.Close()
  104. if err := c.checkErrorResponse(resp); err != nil {
  105. return err
  106. }
  107. if err := json.NewDecoder(resp.Body).Decode(val); err != nil {
  108. log.Debugf("Error parsing join response: %v", err)
  109. return clientError(err)
  110. }
  111. return nil
  112. }
  113. func (c *Client) checkErrorResponse(resp *http.Response) *etcdErr.Error {
  114. if resp.StatusCode != http.StatusOK {
  115. uerr := &etcdErr.Error{}
  116. if err := json.NewDecoder(resp.Body).Decode(uerr); err != nil {
  117. log.Debugf("Error parsing response to etcd error: %v", err)
  118. return clientError(err)
  119. }
  120. return uerr
  121. }
  122. return nil
  123. }
  124. // put sends server side PUT request.
  125. // It always follows redirects instead of stopping according to RFC 2616.
  126. func (c *Client) put(urlStr string, body []byte) (*http.Response, error) {
  127. return c.doAlwaysFollowingRedirects("PUT", urlStr, body)
  128. }
  129. func (c *Client) doAlwaysFollowingRedirects(method string, urlStr string, body []byte) (resp *http.Response, err error) {
  130. var req *http.Request
  131. for redirect := 0; redirect < 10; redirect++ {
  132. req, err = http.NewRequest(method, urlStr, bytes.NewBuffer(body))
  133. if err != nil {
  134. return
  135. }
  136. if resp, err = c.Do(req); err != nil {
  137. if resp != nil {
  138. resp.Body.Close()
  139. }
  140. return
  141. }
  142. if resp.StatusCode == http.StatusMovedPermanently || resp.StatusCode == http.StatusTemporaryRedirect {
  143. resp.Body.Close()
  144. if urlStr = resp.Header.Get("Location"); urlStr == "" {
  145. err = errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
  146. return
  147. }
  148. continue
  149. }
  150. return
  151. }
  152. err = errors.New("stopped after 10 redirects")
  153. return
  154. }
  155. func clientError(err error) *etcdErr.Error {
  156. return etcdErr.NewError(etcdErr.EcodeClientInternal, err.Error(), 0)
  157. }