server_discovery.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package pb
  2. import (
  3. "github.com/seaweedfs/seaweedfs/weed/glog"
  4. "reflect"
  5. )
  6. // ServerDiscovery encodes a way to find at least 1 instance of a service,
  7. // and provides utility functions to refresh the instance list
  8. type ServerDiscovery struct {
  9. list []ServerAddress
  10. srvRecord *ServerSrvAddress
  11. }
  12. func NewServiceDiscoveryFromMap(m map[string]ServerAddress) (sd *ServerDiscovery) {
  13. sd = &ServerDiscovery{}
  14. for _, s := range m {
  15. sd.list = append(sd.list, s)
  16. }
  17. return sd
  18. }
  19. // RefreshBySrvIfAvailable performs a DNS SRV lookup and updates list with the results
  20. // of the lookup
  21. func (sd *ServerDiscovery) RefreshBySrvIfAvailable() {
  22. if sd.srvRecord == nil {
  23. return
  24. }
  25. newList, err := sd.srvRecord.LookUp()
  26. if err != nil {
  27. glog.V(0).Infof("failed to lookup SRV for %s: %v", *sd.srvRecord, err)
  28. }
  29. if newList == nil || len(newList) == 0 {
  30. glog.V(0).Infof("looked up SRV for %s, but found no well-formed names", *sd.srvRecord)
  31. return
  32. }
  33. if !reflect.DeepEqual(sd.list, newList) {
  34. sd.list = newList
  35. }
  36. }
  37. // GetInstances returns a copy of the latest known list of addresses
  38. // call RefreshBySrvIfAvailable prior to this in order to get a more up-to-date view
  39. func (sd *ServerDiscovery) GetInstances() (addresses []ServerAddress) {
  40. for _, a := range sd.list {
  41. addresses = append(addresses, a)
  42. }
  43. return addresses
  44. }
  45. func (sd *ServerDiscovery) GetInstancesAsStrings() (addresses []string) {
  46. for _, i := range sd.list {
  47. addresses = append(addresses, string(i))
  48. }
  49. return addresses
  50. }
  51. func (sd *ServerDiscovery) GetInstancesAsMap() (addresses map[string]ServerAddress) {
  52. addresses = make(map[string]ServerAddress)
  53. for _, i := range sd.list {
  54. addresses[string(i)] = i
  55. }
  56. return addresses
  57. }