keys.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // Copyright 2015 CoreOS, Inc.
  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. "encoding/json"
  17. "fmt"
  18. "net/http"
  19. "net/url"
  20. "path"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  25. )
  26. const (
  27. ErrorCodeKeyNotFound = 100
  28. ErrorCodeTestFailed = 101
  29. ErrorCodeNotFile = 102
  30. ErrorCodeNotDir = 104
  31. ErrorCodeNodeExist = 105
  32. ErrorCodeRootROnly = 107
  33. ErrorCodeDirNotEmpty = 108
  34. ErrorCodePrevValueRequired = 201
  35. ErrorCodeTTLNaN = 202
  36. ErrorCodeIndexNaN = 203
  37. ErrorCodeInvalidField = 209
  38. ErrorCodeInvalidForm = 210
  39. ErrorCodeRaftInternal = 300
  40. ErrorCodeLeaderElect = 301
  41. ErrorCodeWatcherCleared = 400
  42. ErrorCodeEventIndexCleared = 401
  43. )
  44. type Error struct {
  45. Code int `json:"errorCode"`
  46. Message string `json:"message"`
  47. Cause string `json:"cause"`
  48. Index uint64 `json:"index"`
  49. }
  50. func (e Error) Error() string {
  51. return fmt.Sprintf("%v: %v (%v) [%v]", e.Code, e.Message, e.Cause, e.Index)
  52. }
  53. // PrevExistType is used to define an existence condition when setting
  54. // or deleting Nodes.
  55. type PrevExistType string
  56. const (
  57. PrevIgnore = PrevExistType("")
  58. PrevExist = PrevExistType("true")
  59. PrevNoExist = PrevExistType("false")
  60. )
  61. var (
  62. defaultV2KeysPrefix = "/v2/keys"
  63. )
  64. // NewKeysAPI builds a KeysAPI that interacts with etcd's key-value
  65. // API over HTTP.
  66. func NewKeysAPI(c Client) KeysAPI {
  67. return NewKeysAPIWithPrefix(c, defaultV2KeysPrefix)
  68. }
  69. // NewKeysAPIWithPrefix acts like NewKeysAPI, but allows the caller
  70. // to provide a custom base URL path. This should only be used in
  71. // very rare cases.
  72. func NewKeysAPIWithPrefix(c Client, p string) KeysAPI {
  73. return &httpKeysAPI{
  74. client: c,
  75. prefix: p,
  76. }
  77. }
  78. type KeysAPI interface {
  79. // Get retrieves a set of Nodes from etcd
  80. Get(ctx context.Context, key string, opts *GetOptions) (*Response, error)
  81. // Set assigns a new value to a Node identified by a given key. The caller
  82. // may define a set of conditions in the SetOptions.
  83. Set(ctx context.Context, key, value string, opts *SetOptions) (*Response, error)
  84. // Delete removes a Node identified by the given key, optionally destroying
  85. // all of its children as well. The caller may define a set of required
  86. // conditions in an DeleteOptions object.
  87. Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error)
  88. // Create is an alias for Set w/ PrevExist=false
  89. Create(ctx context.Context, key, value string) (*Response, error)
  90. // Update is an alias for Set w/ PrevExist=true
  91. Update(ctx context.Context, key, value string) (*Response, error)
  92. // Watcher builds a new Watcher targeted at a specific Node identified
  93. // by the given key. The Watcher may be configured at creation time
  94. // through a WatcherOptions object. The returned Watcher is designed
  95. // to emit events that happen to a Node, and optionally to its children.
  96. Watcher(key string, opts *WatcherOptions) Watcher
  97. }
  98. type WatcherOptions struct {
  99. // AfterIndex defines the index after-which the Watcher should
  100. // start emitting events. For example, if a value of 5 is
  101. // provided, the first event will have an index >= 6.
  102. //
  103. // Setting AfterIndex to 0 (default) means that the Watcher
  104. // should start watching for events starting at the current
  105. // index, whatever that may be.
  106. AfterIndex uint64
  107. // Recursive specifices whether or not the Watcher should emit
  108. // events that occur in children of the given keyspace. If set
  109. // to false (default), events will be limited to those that
  110. // occur for the exact key.
  111. Recursive bool
  112. }
  113. type SetOptions struct {
  114. // PrevValue specifies what the current value of the Node must
  115. // be in order for the Set operation to succeed.
  116. //
  117. // Leaving this field empty means that the caller wishes to
  118. // ignore the current value of the Node. This cannot be used
  119. // to compare the Node's current value to an empty string.
  120. PrevValue string
  121. // PrevIndex indicates what the current ModifiedIndex of the
  122. // Node must be in order for the Set operation to succeed.
  123. //
  124. // If PrevIndex is set to 0 (default), no comparison is made.
  125. PrevIndex uint64
  126. // PrevExist specifies whether the Node must currently exist
  127. // (PrevExist) or not (PrevNoExist). If the caller does not
  128. // care about existence, set PrevExist to PrevIgnore, or simply
  129. // leave it unset.
  130. PrevExist PrevExistType
  131. // TTL defines a period of time after-which the Node should
  132. // expire and no longer exist. Values <= 0 are ignored. Given
  133. // that the zero-value is ignored, TTL cannot be used to set
  134. // a TTL of 0.
  135. TTL time.Duration
  136. }
  137. type GetOptions struct {
  138. // Recursive defines whether or not all children of the Node
  139. // should be returned.
  140. Recursive bool
  141. // Sort instructs the server whether or not to sort the Nodes.
  142. // If true, the Nodes are sorted alphabetically by key in
  143. // ascending order (A to z). If false (default), the Nodes will
  144. // not be sorted and the ordering used should not be considered
  145. // predictable.
  146. Sort bool
  147. }
  148. type DeleteOptions struct {
  149. // PrevValue specifies what the current value of the Node must
  150. // be in order for the Delete operation to succeed.
  151. //
  152. // Leaving this field empty means that the caller wishes to
  153. // ignore the current value of the Node. This cannot be used
  154. // to compare the Node's current value to an empty string.
  155. PrevValue string
  156. // PrevIndex indicates what the current ModifiedIndex of the
  157. // Node must be in order for the Delete operation to succeed.
  158. //
  159. // If PrevIndex is set to 0 (default), no comparison is made.
  160. PrevIndex uint64
  161. // Recursive defines whether or not all children of the Node
  162. // should be deleted. If set to true, all children of the Node
  163. // identified by the given key will be deleted. If left unset
  164. // or explicitly set to false, only a single Node will be
  165. // deleted.
  166. Recursive bool
  167. }
  168. type Watcher interface {
  169. // Next blocks until an etcd event occurs, then returns a Response
  170. // represeting that event. The behavior of Next depends on the
  171. // WatcherOptions used to construct the Watcher. Next is designed to
  172. // be called repeatedly, each time blocking until a subsequent event
  173. // is available.
  174. //
  175. // If the provided context is cancelled, Next will return a non-nil
  176. // error. Any other failures encountered while waiting for the next
  177. // event (connection issues, deserialization failures, etc) will
  178. // also result in a non-nil error.
  179. Next(context.Context) (*Response, error)
  180. }
  181. type Response struct {
  182. // Action is the name of the operation that occurred. Possible values
  183. // include get, set, delete, update, create, compareAndSwap,
  184. // compareAndDelete and expire.
  185. Action string `json:"action"`
  186. // Node represents the state of the relevant etcd Node.
  187. Node *Node `json:"node"`
  188. // PrevNode represents the previous state of the Node. PrevNode is non-nil
  189. // only if the Node existed before the action occured and the action
  190. // caused a change to the Node.
  191. PrevNode *Node `json:"prevNode"`
  192. // Index holds the cluster-level index at the time the Response was generated.
  193. // This index is not tied to the Node(s) contained in this Response.
  194. Index uint64 `json:"-"`
  195. }
  196. type Node struct {
  197. // Key represents the unique location of this Node (e.g. "/foo/bar").
  198. Key string `json:"key"`
  199. // Dir reports whether node describes a directory.
  200. Dir bool `json:"dir,omitempty"`
  201. // Value is the current data stored on this Node. If this Node
  202. // is a directory, Value will be empty.
  203. Value string `json:"value"`
  204. // Nodes holds the children of this Node, only if this Node is a directory.
  205. // This slice of will be arbitrarily deep (children, grandchildren, great-
  206. // grandchildren, etc.) if a recursive Get or Watch request were made.
  207. Nodes []*Node `json:"nodes"`
  208. // CreatedIndex is the etcd index at-which this Node was created.
  209. CreatedIndex uint64 `json:"createdIndex"`
  210. // ModifiedIndex is the etcd index at-which this Node was last modified.
  211. ModifiedIndex uint64 `json:"modifiedIndex"`
  212. // Expiration is the server side expiration time of the key.
  213. Expiration *time.Time `json:"expiration,omitempty"`
  214. // TTL is the time to live of the key in second.
  215. TTL int64 `json:"ttl,omitempty"`
  216. }
  217. func (n *Node) String() string {
  218. return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d, TTL: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex, n.TTL)
  219. }
  220. type httpKeysAPI struct {
  221. client httpClient
  222. prefix string
  223. }
  224. func (k *httpKeysAPI) Set(ctx context.Context, key, val string, opts *SetOptions) (*Response, error) {
  225. act := &setAction{
  226. Prefix: k.prefix,
  227. Key: key,
  228. Value: val,
  229. }
  230. if opts != nil {
  231. act.PrevValue = opts.PrevValue
  232. act.PrevIndex = opts.PrevIndex
  233. act.PrevExist = opts.PrevExist
  234. act.TTL = opts.TTL
  235. }
  236. resp, body, err := k.client.Do(ctx, act)
  237. if err != nil {
  238. return nil, err
  239. }
  240. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  241. }
  242. func (k *httpKeysAPI) Create(ctx context.Context, key, val string) (*Response, error) {
  243. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevNoExist})
  244. }
  245. func (k *httpKeysAPI) Update(ctx context.Context, key, val string) (*Response, error) {
  246. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevExist})
  247. }
  248. func (k *httpKeysAPI) Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error) {
  249. act := &deleteAction{
  250. Prefix: k.prefix,
  251. Key: key,
  252. }
  253. if opts != nil {
  254. act.PrevValue = opts.PrevValue
  255. act.PrevIndex = opts.PrevIndex
  256. act.Recursive = opts.Recursive
  257. }
  258. resp, body, err := k.client.Do(ctx, act)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  263. }
  264. func (k *httpKeysAPI) Get(ctx context.Context, key string, opts *GetOptions) (*Response, error) {
  265. act := &getAction{
  266. Prefix: k.prefix,
  267. Key: key,
  268. }
  269. if opts != nil {
  270. act.Recursive = opts.Recursive
  271. act.Sorted = opts.Sort
  272. }
  273. resp, body, err := k.client.Do(ctx, act)
  274. if err != nil {
  275. return nil, err
  276. }
  277. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  278. }
  279. func (k *httpKeysAPI) Watcher(key string, opts *WatcherOptions) Watcher {
  280. act := waitAction{
  281. Prefix: k.prefix,
  282. Key: key,
  283. }
  284. if opts != nil {
  285. act.Recursive = opts.Recursive
  286. if opts.AfterIndex > 0 {
  287. act.WaitIndex = opts.AfterIndex + 1
  288. }
  289. }
  290. return &httpWatcher{
  291. client: k.client,
  292. nextWait: act,
  293. }
  294. }
  295. type httpWatcher struct {
  296. client httpClient
  297. nextWait waitAction
  298. }
  299. func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) {
  300. httpresp, body, err := hw.client.Do(ctx, &hw.nextWait)
  301. if err != nil {
  302. return nil, err
  303. }
  304. resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body)
  305. if err != nil {
  306. return nil, err
  307. }
  308. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  309. return resp, nil
  310. }
  311. // v2KeysURL forms a URL representing the location of a key.
  312. // The endpoint argument represents the base URL of an etcd
  313. // server. The prefix is the path needed to route from the
  314. // provided endpoint's path to the root of the keys API
  315. // (typically "/v2/keys").
  316. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  317. ep.Path = path.Join(ep.Path, prefix, key)
  318. return &ep
  319. }
  320. type getAction struct {
  321. Prefix string
  322. Key string
  323. Recursive bool
  324. Sorted bool
  325. }
  326. func (g *getAction) HTTPRequest(ep url.URL) *http.Request {
  327. u := v2KeysURL(ep, g.Prefix, g.Key)
  328. params := u.Query()
  329. params.Set("recursive", strconv.FormatBool(g.Recursive))
  330. params.Set("sorted", strconv.FormatBool(g.Sorted))
  331. u.RawQuery = params.Encode()
  332. req, _ := http.NewRequest("GET", u.String(), nil)
  333. return req
  334. }
  335. type waitAction struct {
  336. Prefix string
  337. Key string
  338. WaitIndex uint64
  339. Recursive bool
  340. }
  341. func (w *waitAction) HTTPRequest(ep url.URL) *http.Request {
  342. u := v2KeysURL(ep, w.Prefix, w.Key)
  343. params := u.Query()
  344. params.Set("wait", "true")
  345. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  346. params.Set("recursive", strconv.FormatBool(w.Recursive))
  347. u.RawQuery = params.Encode()
  348. req, _ := http.NewRequest("GET", u.String(), nil)
  349. return req
  350. }
  351. type setAction struct {
  352. Prefix string
  353. Key string
  354. Value string
  355. PrevValue string
  356. PrevIndex uint64
  357. PrevExist PrevExistType
  358. TTL time.Duration
  359. }
  360. func (a *setAction) HTTPRequest(ep url.URL) *http.Request {
  361. u := v2KeysURL(ep, a.Prefix, a.Key)
  362. params := u.Query()
  363. if a.PrevValue != "" {
  364. params.Set("prevValue", a.PrevValue)
  365. }
  366. if a.PrevIndex != 0 {
  367. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  368. }
  369. if a.PrevExist != PrevIgnore {
  370. params.Set("prevExist", string(a.PrevExist))
  371. }
  372. u.RawQuery = params.Encode()
  373. form := url.Values{}
  374. form.Add("value", a.Value)
  375. if a.TTL > 0 {
  376. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  377. }
  378. body := strings.NewReader(form.Encode())
  379. req, _ := http.NewRequest("PUT", u.String(), body)
  380. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  381. return req
  382. }
  383. type deleteAction struct {
  384. Prefix string
  385. Key string
  386. PrevValue string
  387. PrevIndex uint64
  388. Recursive bool
  389. }
  390. func (a *deleteAction) HTTPRequest(ep url.URL) *http.Request {
  391. u := v2KeysURL(ep, a.Prefix, a.Key)
  392. params := u.Query()
  393. if a.PrevValue != "" {
  394. params.Set("prevValue", a.PrevValue)
  395. }
  396. if a.PrevIndex != 0 {
  397. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  398. }
  399. if a.Recursive {
  400. params.Set("recursive", "true")
  401. }
  402. u.RawQuery = params.Encode()
  403. req, _ := http.NewRequest("DELETE", u.String(), nil)
  404. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  405. return req
  406. }
  407. func unmarshalHTTPResponse(code int, header http.Header, body []byte) (res *Response, err error) {
  408. switch code {
  409. case http.StatusOK, http.StatusCreated:
  410. res, err = unmarshalSuccessfulKeysResponse(header, body)
  411. default:
  412. err = unmarshalFailedKeysResponse(body)
  413. }
  414. return
  415. }
  416. func unmarshalSuccessfulKeysResponse(header http.Header, body []byte) (*Response, error) {
  417. var res Response
  418. err := json.Unmarshal(body, &res)
  419. if err != nil {
  420. return nil, err
  421. }
  422. if header.Get("X-Etcd-Index") != "" {
  423. res.Index, err = strconv.ParseUint(header.Get("X-Etcd-Index"), 10, 64)
  424. if err != nil {
  425. return nil, err
  426. }
  427. }
  428. return &res, nil
  429. }
  430. func unmarshalFailedKeysResponse(body []byte) error {
  431. var etcdErr Error
  432. if err := json.Unmarshal(body, &etcdErr); err != nil {
  433. return err
  434. }
  435. return etcdErr
  436. }