v2_client.go 4.9 KB

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