v2_client.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package etcd
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "strconv"
  12. "github.com/coreos/etcd/config"
  13. etcdErr "github.com/coreos/etcd/error"
  14. )
  15. // v2client 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. type v2client struct {
  22. http.Client
  23. }
  24. func newClient(tc *tls.Config) *v2client {
  25. tr := new(http.Transport)
  26. tr.TLSClientConfig = tc
  27. return &v2client{http.Client{Transport: tr}}
  28. }
  29. // CheckVersion returns true when the version check on the server returns 200.
  30. func (c *v2client) 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 *v2client) 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 *v2client) 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 *v2client) GetClusterConfig(url string) (*config.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(config.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 *v2client) AddMachine(url string, name string, info *context) *etcdErr.Error {
  81. b, _ := json.Marshal(info)
  82. url = url + "/v2/admin/machines/" + name
  83. log.Printf("Send Join Request to %s", url)
  84. resp, err := c.put(url, b)
  85. if err != nil {
  86. return clientError(err)
  87. }
  88. defer resp.Body.Close()
  89. if err := c.checkErrorResponse(resp); err != nil {
  90. return err
  91. }
  92. return nil
  93. }
  94. func (c *v2client) parseJSONResponse(resp *http.Response, val interface{}) *etcdErr.Error {
  95. defer resp.Body.Close()
  96. if err := c.checkErrorResponse(resp); err != nil {
  97. return err
  98. }
  99. if err := json.NewDecoder(resp.Body).Decode(val); err != nil {
  100. log.Printf("Error parsing join response: %v", err)
  101. return clientError(err)
  102. }
  103. return nil
  104. }
  105. func (c *v2client) checkErrorResponse(resp *http.Response) *etcdErr.Error {
  106. if resp.StatusCode != http.StatusOK {
  107. uerr := &etcdErr.Error{}
  108. if err := json.NewDecoder(resp.Body).Decode(uerr); err != nil {
  109. log.Printf("Error parsing response to etcd error: %v", err)
  110. return clientError(err)
  111. }
  112. return uerr
  113. }
  114. return nil
  115. }
  116. // put sends server side PUT request.
  117. // It always follows redirects instead of stopping according to RFC 2616.
  118. func (c *v2client) put(urlStr string, body []byte) (*http.Response, error) {
  119. return c.doAlwaysFollowingRedirects("PUT", urlStr, body)
  120. }
  121. func (c *v2client) doAlwaysFollowingRedirects(method string, urlStr string, body []byte) (resp *http.Response, err error) {
  122. var req *http.Request
  123. for redirect := 0; redirect < 10; redirect++ {
  124. req, err = http.NewRequest(method, urlStr, bytes.NewBuffer(body))
  125. if err != nil {
  126. return
  127. }
  128. if resp, err = c.Do(req); err != nil {
  129. if resp != nil {
  130. resp.Body.Close()
  131. }
  132. return
  133. }
  134. if resp.StatusCode == http.StatusMovedPermanently || resp.StatusCode == http.StatusTemporaryRedirect {
  135. resp.Body.Close()
  136. if urlStr = resp.Header.Get("Location"); urlStr == "" {
  137. err = errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
  138. return
  139. }
  140. continue
  141. }
  142. return
  143. }
  144. err = errors.New("stopped after 10 redirects")
  145. return
  146. }
  147. func clientError(err error) *etcdErr.Error {
  148. return etcdErr.NewError(etcdErr.EcodeClientInternal, err.Error(), 0)
  149. }