name_url_map.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Copyright 2013 CoreOS 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. package main
  14. import (
  15. "net/url"
  16. "path"
  17. )
  18. // we map node name to url
  19. type nodeInfo struct {
  20. raftVersion string
  21. raftURL string
  22. etcdURL string
  23. }
  24. var namesMap = make(map[string]*nodeInfo)
  25. // nameToEtcdURL maps node name to its etcd http address
  26. func nameToEtcdURL(name string) (string, bool) {
  27. if info, ok := namesMap[name]; ok {
  28. // first try to read from the map
  29. return info.etcdURL, true
  30. }
  31. // if fails, try to recover from etcd storage
  32. return readURL(name, "etcd")
  33. }
  34. // nameToRaftURL maps node name to its raft http address
  35. func nameToRaftURL(name string) (string, bool) {
  36. if info, ok := namesMap[name]; ok {
  37. // first try to read from the map
  38. return info.raftURL, true
  39. }
  40. // if fails, try to recover from etcd storage
  41. return readURL(name, "raft")
  42. }
  43. // addNameToURL add a name that maps to raftURL and etcdURL
  44. func addNameToURL(name string, version string, raftURL string, etcdURL string) {
  45. namesMap[name] = &nodeInfo{
  46. raftVersion: raftVersion,
  47. raftURL: raftURL,
  48. etcdURL: etcdURL,
  49. }
  50. }
  51. func readURL(nodeName string, urlName string) (string, bool) {
  52. // if fails, try to recover from etcd storage
  53. key := path.Join("/_etcd/machines", nodeName)
  54. resps, err := etcdStore.RawGet(key)
  55. if err != nil {
  56. return "", false
  57. }
  58. m, err := url.ParseQuery(resps[0].Value)
  59. if err != nil {
  60. panic("Failed to parse machines entry")
  61. }
  62. url := m[urlName][0]
  63. return url, true
  64. }