watch.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 v3rpc
  15. import (
  16. "io"
  17. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  18. "github.com/coreos/etcd/storage"
  19. "github.com/coreos/etcd/storage/storagepb"
  20. )
  21. type watchServer struct {
  22. watchable storage.Watchable
  23. }
  24. func NewWatchServer(w storage.Watchable) pb.WatchServer {
  25. return &watchServer{w}
  26. }
  27. func (ws *watchServer) Watch(stream pb.Watch_WatchServer) error {
  28. closec := make(chan struct{})
  29. defer close(closec)
  30. watcher := ws.watchable.NewWatcher()
  31. defer watcher.Close()
  32. go sendLoop(stream, watcher, closec)
  33. for {
  34. req, err := stream.Recv()
  35. if err == io.EOF {
  36. return nil
  37. }
  38. if err != nil {
  39. return err
  40. }
  41. switch {
  42. case req.CreateRequest != nil:
  43. creq := req.CreateRequest
  44. var prefix bool
  45. toWatch := creq.Key
  46. if len(creq.Key) == 0 {
  47. toWatch = creq.Prefix
  48. prefix = true
  49. }
  50. watcher.Watch(toWatch, prefix, creq.StartRevision)
  51. default:
  52. // TODO: support cancellation
  53. panic("not implemented")
  54. }
  55. }
  56. }
  57. func sendLoop(stream pb.Watch_WatchServer, watcher storage.Watcher, closec chan struct{}) {
  58. for {
  59. select {
  60. case evs, ok := <-watcher.Chan():
  61. if !ok {
  62. return
  63. }
  64. // TODO: evs is []storagepb.Event type
  65. // either return []*storagepb.Event from storage package
  66. // or define protocol buffer with []storagepb.Event.
  67. events := make([]*storagepb.Event, len(evs))
  68. for i := range evs {
  69. events[i] = &evs[i]
  70. }
  71. err := stream.Send(&pb.WatchResponse{Events: events})
  72. storage.ReportEventReceived()
  73. if err != nil {
  74. return
  75. }
  76. case <-closec:
  77. // drain the chan to clean up pending events
  78. for {
  79. _, ok := <-watcher.Chan()
  80. if !ok {
  81. return
  82. }
  83. storage.ReportEventReceived()
  84. }
  85. }
  86. }
  87. }