github.com/alpe/etcd@v0.1.2-0.20130915230056-09f31af88aeb/name_url_map.go (about)

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