v2_client.go 4.6 KB

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