name_url_map.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "net/url"
  4. "path"
  5. )
  6. // we map node name to url
  7. type nodeInfo struct {
  8. raftURL string
  9. etcdURL string
  10. }
  11. var namesMap = make(map[string]*nodeInfo)
  12. // nameToEtcdURL maps node name to its etcd http address
  13. func nameToEtcdURL(name string) (string, bool) {
  14. if info, ok := namesMap[name]; ok {
  15. // first try to read from the map
  16. return info.etcdURL, true
  17. }
  18. // if fails, try to recover from etcd storage
  19. return readURL(name, "etcd")
  20. }
  21. // nameToRaftURL maps node name to its raft http address
  22. func nameToRaftURL(name string) (string, bool) {
  23. if info, ok := namesMap[name]; ok {
  24. // first try to read from the map
  25. return info.raftURL, true
  26. }
  27. // if fails, try to recover from etcd storage
  28. return readURL(name, "raft")
  29. }
  30. // addNameToURL add a name that maps to raftURL and etcdURL
  31. func addNameToURL(name string, raftURL string, etcdURL string) {
  32. namesMap[name] = &nodeInfo{
  33. raftURL: raftURL,
  34. etcdURL: etcdURL,
  35. }
  36. }
  37. func readURL(nodeName string, urlName string) (string, bool) {
  38. // if fails, try to recover from etcd storage
  39. key := path.Join("/_etcd/machines", nodeName)
  40. resps, err := etcdStore.RawGet(key)
  41. if err != nil {
  42. return "", false
  43. }
  44. m, err := url.ParseQuery(resps[0].Value)
  45. if err != nil {
  46. panic("Failed to parse machines entry")
  47. }
  48. url := m[urlName][0]
  49. return url, true
  50. }