srv.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "fmt"
  17. "net"
  18. "net/url"
  19. )
  20. var (
  21. // indirection for testing
  22. lookupSRV = net.LookupSRV
  23. )
  24. type srvDiscover struct{}
  25. // NewSRVDiscover constructs a new Dicoverer that uses the stdlib to lookup SRV records.
  26. func NewSRVDiscover() Discoverer {
  27. return &srvDiscover{}
  28. }
  29. // Discover looks up the etcd servers for the domain.
  30. func (d *srvDiscover) Discover(domain string) ([]string, error) {
  31. var urls []*url.URL
  32. updateURLs := func(service, scheme string) error {
  33. _, addrs, err := lookupSRV(service, "tcp", domain)
  34. if err != nil {
  35. return err
  36. }
  37. for _, srv := range addrs {
  38. urls = append(urls, &url.URL{
  39. Scheme: scheme,
  40. Host: net.JoinHostPort(srv.Target, fmt.Sprintf("%d", srv.Port)),
  41. })
  42. }
  43. return nil
  44. }
  45. errHTTPS := updateURLs("etcd-server-ssl", "https")
  46. errHTTP := updateURLs("etcd-server", "http")
  47. if errHTTPS != nil && errHTTP != nil {
  48. return nil, fmt.Errorf("dns lookup errors: %s and %s", errHTTPS, errHTTP)
  49. }
  50. endpoints := make([]string, len(urls))
  51. for i := range urls {
  52. endpoints[i] = urls[i].String()
  53. }
  54. return endpoints, nil
  55. }