members.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package client
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/json"
  19. "fmt"
  20. "net/http"
  21. "net/url"
  22. "path"
  23. "go.etcd.io/etcd/pkg/types"
  24. )
  25. var (
  26. defaultV2MembersPrefix = "/v2/members"
  27. defaultLeaderSuffix = "/leader"
  28. )
  29. type Member struct {
  30. // ID is the unique identifier of this Member.
  31. ID string `json:"id"`
  32. // Name is a human-readable, non-unique identifier of this Member.
  33. Name string `json:"name"`
  34. // PeerURLs represents the HTTP(S) endpoints this Member uses to
  35. // participate in etcd's consensus protocol.
  36. PeerURLs []string `json:"peerURLs"`
  37. // ClientURLs represents the HTTP(S) endpoints on which this Member
  38. // serves its client-facing APIs.
  39. ClientURLs []string `json:"clientURLs"`
  40. }
  41. type memberCollection []Member
  42. func (c *memberCollection) UnmarshalJSON(data []byte) error {
  43. d := struct {
  44. Members []Member
  45. }{}
  46. if err := json.Unmarshal(data, &d); err != nil {
  47. return err
  48. }
  49. if d.Members == nil {
  50. *c = make([]Member, 0)
  51. return nil
  52. }
  53. *c = d.Members
  54. return nil
  55. }
  56. type memberCreateOrUpdateRequest struct {
  57. PeerURLs types.URLs
  58. }
  59. func (m *memberCreateOrUpdateRequest) MarshalJSON() ([]byte, error) {
  60. s := struct {
  61. PeerURLs []string `json:"peerURLs"`
  62. }{
  63. PeerURLs: make([]string, len(m.PeerURLs)),
  64. }
  65. for i, u := range m.PeerURLs {
  66. s.PeerURLs[i] = u.String()
  67. }
  68. return json.Marshal(&s)
  69. }
  70. // NewMembersAPI constructs a new MembersAPI that uses HTTP to
  71. // interact with etcd's membership API.
  72. func NewMembersAPI(c Client) MembersAPI {
  73. return &httpMembersAPI{
  74. client: c,
  75. }
  76. }
  77. type MembersAPI interface {
  78. // List enumerates the current cluster membership.
  79. List(ctx context.Context) ([]Member, error)
  80. // Add instructs etcd to accept a new Member into the cluster.
  81. Add(ctx context.Context, peerURL string) (*Member, error)
  82. // Remove demotes an existing Member out of the cluster.
  83. Remove(ctx context.Context, mID string) error
  84. // Update instructs etcd to update an existing Member in the cluster.
  85. Update(ctx context.Context, mID string, peerURLs []string) error
  86. // Leader gets current leader of the cluster
  87. Leader(ctx context.Context) (*Member, error)
  88. }
  89. type httpMembersAPI struct {
  90. client httpClient
  91. }
  92. func (m *httpMembersAPI) List(ctx context.Context) ([]Member, error) {
  93. req := &membersAPIActionList{}
  94. resp, body, err := m.client.Do(ctx, req)
  95. if err != nil {
  96. return nil, err
  97. }
  98. if err := assertStatusCode(resp.StatusCode, http.StatusOK); err != nil {
  99. return nil, err
  100. }
  101. var mCollection memberCollection
  102. if err := json.Unmarshal(body, &mCollection); err != nil {
  103. return nil, err
  104. }
  105. return []Member(mCollection), nil
  106. }
  107. func (m *httpMembersAPI) Add(ctx context.Context, peerURL string) (*Member, error) {
  108. urls, err := types.NewURLs([]string{peerURL})
  109. if err != nil {
  110. return nil, err
  111. }
  112. req := &membersAPIActionAdd{peerURLs: urls}
  113. resp, body, err := m.client.Do(ctx, req)
  114. if err != nil {
  115. return nil, err
  116. }
  117. if err := assertStatusCode(resp.StatusCode, http.StatusCreated, http.StatusConflict); err != nil {
  118. return nil, err
  119. }
  120. if resp.StatusCode != http.StatusCreated {
  121. var merr membersError
  122. if err := json.Unmarshal(body, &merr); err != nil {
  123. return nil, err
  124. }
  125. return nil, merr
  126. }
  127. var memb Member
  128. if err := json.Unmarshal(body, &memb); err != nil {
  129. return nil, err
  130. }
  131. return &memb, nil
  132. }
  133. func (m *httpMembersAPI) Update(ctx context.Context, memberID string, peerURLs []string) error {
  134. urls, err := types.NewURLs(peerURLs)
  135. if err != nil {
  136. return err
  137. }
  138. req := &membersAPIActionUpdate{peerURLs: urls, memberID: memberID}
  139. resp, body, err := m.client.Do(ctx, req)
  140. if err != nil {
  141. return err
  142. }
  143. if err := assertStatusCode(resp.StatusCode, http.StatusNoContent, http.StatusNotFound, http.StatusConflict); err != nil {
  144. return err
  145. }
  146. if resp.StatusCode != http.StatusNoContent {
  147. var merr membersError
  148. if err := json.Unmarshal(body, &merr); err != nil {
  149. return err
  150. }
  151. return merr
  152. }
  153. return nil
  154. }
  155. func (m *httpMembersAPI) Remove(ctx context.Context, memberID string) error {
  156. req := &membersAPIActionRemove{memberID: memberID}
  157. resp, _, err := m.client.Do(ctx, req)
  158. if err != nil {
  159. return err
  160. }
  161. return assertStatusCode(resp.StatusCode, http.StatusNoContent, http.StatusGone)
  162. }
  163. func (m *httpMembersAPI) Leader(ctx context.Context) (*Member, error) {
  164. req := &membersAPIActionLeader{}
  165. resp, body, err := m.client.Do(ctx, req)
  166. if err != nil {
  167. return nil, err
  168. }
  169. if err := assertStatusCode(resp.StatusCode, http.StatusOK); err != nil {
  170. return nil, err
  171. }
  172. var leader Member
  173. if err := json.Unmarshal(body, &leader); err != nil {
  174. return nil, err
  175. }
  176. return &leader, nil
  177. }
  178. type membersAPIActionList struct{}
  179. func (l *membersAPIActionList) HTTPRequest(ep url.URL) *http.Request {
  180. u := v2MembersURL(ep)
  181. req, _ := http.NewRequest("GET", u.String(), nil)
  182. return req
  183. }
  184. type membersAPIActionRemove struct {
  185. memberID string
  186. }
  187. func (d *membersAPIActionRemove) HTTPRequest(ep url.URL) *http.Request {
  188. u := v2MembersURL(ep)
  189. u.Path = path.Join(u.Path, d.memberID)
  190. req, _ := http.NewRequest("DELETE", u.String(), nil)
  191. return req
  192. }
  193. type membersAPIActionAdd struct {
  194. peerURLs types.URLs
  195. }
  196. func (a *membersAPIActionAdd) HTTPRequest(ep url.URL) *http.Request {
  197. u := v2MembersURL(ep)
  198. m := memberCreateOrUpdateRequest{PeerURLs: a.peerURLs}
  199. b, _ := json.Marshal(&m)
  200. req, _ := http.NewRequest("POST", u.String(), bytes.NewReader(b))
  201. req.Header.Set("Content-Type", "application/json")
  202. return req
  203. }
  204. type membersAPIActionUpdate struct {
  205. memberID string
  206. peerURLs types.URLs
  207. }
  208. func (a *membersAPIActionUpdate) HTTPRequest(ep url.URL) *http.Request {
  209. u := v2MembersURL(ep)
  210. m := memberCreateOrUpdateRequest{PeerURLs: a.peerURLs}
  211. u.Path = path.Join(u.Path, a.memberID)
  212. b, _ := json.Marshal(&m)
  213. req, _ := http.NewRequest("PUT", u.String(), bytes.NewReader(b))
  214. req.Header.Set("Content-Type", "application/json")
  215. return req
  216. }
  217. func assertStatusCode(got int, want ...int) (err error) {
  218. for _, w := range want {
  219. if w == got {
  220. return nil
  221. }
  222. }
  223. return fmt.Errorf("unexpected status code %d", got)
  224. }
  225. type membersAPIActionLeader struct{}
  226. func (l *membersAPIActionLeader) HTTPRequest(ep url.URL) *http.Request {
  227. u := v2MembersURL(ep)
  228. u.Path = path.Join(u.Path, defaultLeaderSuffix)
  229. req, _ := http.NewRequest("GET", u.String(), nil)
  230. return req
  231. }
  232. // v2MembersURL add the necessary path to the provided endpoint
  233. // to route requests to the default v2 members API.
  234. func v2MembersURL(ep url.URL) *url.URL {
  235. ep.Path = path.Join(ep.Path, defaultV2MembersPrefix)
  236. return &ep
  237. }
  238. type membersError struct {
  239. Message string `json:"message"`
  240. Code int `json:"-"`
  241. }
  242. func (e membersError) Error() string {
  243. return e.Message
  244. }