v2_client.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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.readJSONResponse(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.readJSONResponse(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. if err := c.readErrorResponse(resp); err != nil {
  89. return err
  90. }
  91. return nil
  92. }
  93. func (c *v2client) readJSONResponse(resp *http.Response, val interface{}) *etcdErr.Error {
  94. if err := c.readErrorResponse(resp); err != nil {
  95. return err
  96. }
  97. defer resp.Body.Close()
  98. defer ioutil.ReadAll(resp.Body)
  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) readErrorResponse(resp *http.Response) *etcdErr.Error {
  106. if resp.StatusCode == http.StatusOK {
  107. return nil
  108. }
  109. defer resp.Body.Close()
  110. defer ioutil.ReadAll(resp.Body)
  111. uerr := &etcdErr.Error{}
  112. if err := json.NewDecoder(resp.Body).Decode(uerr); err != nil {
  113. log.Printf("Error parsing response to etcd error: %v", err)
  114. return clientError(err)
  115. }
  116. return uerr
  117. }
  118. // put sends server side PUT request.
  119. // It always follows redirects instead of stopping according to RFC 2616.
  120. func (c *v2client) put(urlStr string, body []byte) (*http.Response, error) {
  121. return c.doAlwaysFollowingRedirects("PUT", urlStr, body)
  122. }
  123. func (c *v2client) doAlwaysFollowingRedirects(method string, urlStr string, body []byte) (resp *http.Response, err error) {
  124. var req *http.Request
  125. for redirect := 0; redirect < 10; redirect++ {
  126. req, err = http.NewRequest(method, urlStr, bytes.NewBuffer(body))
  127. if err != nil {
  128. return
  129. }
  130. if resp, err = c.Do(req); err != nil {
  131. if resp != nil {
  132. resp.Body.Close()
  133. }
  134. return
  135. }
  136. if resp.StatusCode == http.StatusMovedPermanently || resp.StatusCode == http.StatusTemporaryRedirect {
  137. resp.Body.Close()
  138. if urlStr = resp.Header.Get("Location"); urlStr == "" {
  139. err = errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
  140. return
  141. }
  142. continue
  143. }
  144. return
  145. }
  146. err = errors.New("stopped after 10 redirects")
  147. return
  148. }
  149. func clientError(err error) *etcdErr.Error {
  150. return etcdErr.NewError(etcdErr.EcodeClientInternal, err.Error(), 0)
  151. }