peers.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. Copyright 2012 Google Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // peers.go defines how processes find and communicate with their peers.
  14. package groupcache
  15. import (
  16. pb "github.com/golang/groupcache/groupcachepb"
  17. )
  18. // Context is an opaque value passed through calls to the
  19. // ProtoGetter. It may be nil if your ProtoGetter implementation does
  20. // not require a context.
  21. type Context interface{}
  22. // ProtoGetter is the interface that must be implemented by a peer.
  23. type ProtoGetter interface {
  24. Get(context Context, in *pb.GetRequest, out *pb.GetResponse) error
  25. }
  26. // PeerPicker is the interface that must be implemented to locate
  27. // the peer that owns a specific key.
  28. type PeerPicker interface {
  29. // PickPeer returns the peer that owns the specific key
  30. // and true to indicate that a remote peer was nominated.
  31. // It returns nil, false if the key owner is the current peer.
  32. PickPeer(key string) (peer ProtoGetter, ok bool)
  33. }
  34. // NoPeers is an implementation of PeerPicker that never finds a peer.
  35. type NoPeers struct{}
  36. func (NoPeers) PickPeer(key string) (peer ProtoGetter, ok bool) { return }
  37. var (
  38. portPicker func() PeerPicker
  39. )
  40. // RegisterPeerPicker registers the peer initialization function.
  41. // It is called once, when the first group is created.
  42. func RegisterPeerPicker(fn func() PeerPicker) {
  43. if portPicker != nil {
  44. panic("RegisterPeerPicker called more than once")
  45. }
  46. portPicker = fn
  47. }
  48. func getPeers() PeerPicker {
  49. if portPicker == nil {
  50. return NoPeers{}
  51. }
  52. pk := portPicker()
  53. if pk == nil {
  54. pk = NoPeers{}
  55. }
  56. return pk
  57. }