priority_queue.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2016 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 recipe
  15. import (
  16. "fmt"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  18. v3 "github.com/coreos/etcd/clientv3"
  19. "github.com/coreos/etcd/storage/storagepb"
  20. )
  21. // PriorityQueue implements a multi-reader, multi-writer distributed queue.
  22. type PriorityQueue struct {
  23. client *v3.Client
  24. kv v3.KV
  25. ctx context.Context
  26. key string
  27. }
  28. // NewPriorityQueue creates an etcd priority queue.
  29. func NewPriorityQueue(client *v3.Client, key string) *PriorityQueue {
  30. return &PriorityQueue{client, v3.NewKV(client), context.TODO(), key + "/"}
  31. }
  32. // Enqueue puts a value into a queue with a given priority.
  33. func (q *PriorityQueue) Enqueue(val string, pr uint16) error {
  34. prefix := fmt.Sprintf("%s%05d", q.key, pr)
  35. _, err := NewSequentialKV(q.kv, prefix, val)
  36. return err
  37. }
  38. // Dequeue returns Enqueue()'d items in FIFO order. If the
  39. // queue is empty, Dequeue blocks until items are available.
  40. func (q *PriorityQueue) Dequeue() (string, error) {
  41. // TODO: fewer round trips by fetching more than one key
  42. resp, err := q.kv.Get(q.ctx, q.key, withFirstKey()...)
  43. if err != nil {
  44. return "", err
  45. }
  46. kv, err := claimFirstKey(q.kv, resp.Kvs)
  47. if err != nil {
  48. return "", err
  49. } else if kv != nil {
  50. return string(kv.Value), nil
  51. } else if resp.More {
  52. // missed some items, retry to read in more
  53. return q.Dequeue()
  54. }
  55. // nothing to dequeue; wait on items
  56. ev, err := WaitPrefixEvents(
  57. q.client,
  58. q.key,
  59. resp.Header.Revision,
  60. []storagepb.Event_EventType{storagepb.PUT})
  61. if err != nil {
  62. return "", err
  63. }
  64. ok, err := deleteRevKey(q.kv, string(ev.Kv.Key), ev.Kv.ModRevision)
  65. if err != nil {
  66. return "", err
  67. } else if !ok {
  68. return q.Dequeue()
  69. }
  70. return string(ev.Kv.Value), err
  71. }