github.com/kafkaliu/etcd@v0.1.2-0.20131007164923-44c16dd30d69/name_url_map.go (about)

     1  /*
     2  Copyright 2013 CoreOS Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package main
    18  
    19  import (
    20  	"net/url"
    21  	"path"
    22  )
    23  
    24  // we map node name to url
    25  type nodeInfo struct {
    26  	raftVersion string
    27  	raftURL     string
    28  	etcdURL     string
    29  }
    30  
    31  var namesMap = make(map[string]*nodeInfo)
    32  
    33  // nameToEtcdURL maps node name to its etcd http address
    34  func nameToEtcdURL(name string) (string, bool) {
    35  
    36  	if info, ok := namesMap[name]; ok {
    37  		// first try to read from the map
    38  		return info.etcdURL, true
    39  	}
    40  
    41  	// if fails, try to recover from etcd storage
    42  	return readURL(name, "etcd")
    43  
    44  }
    45  
    46  // nameToRaftURL maps node name to its raft http address
    47  func nameToRaftURL(name string) (string, bool) {
    48  	if info, ok := namesMap[name]; ok {
    49  		// first try to read from the map
    50  		return info.raftURL, true
    51  
    52  	}
    53  
    54  	// if fails, try to recover from etcd storage
    55  	return readURL(name, "raft")
    56  }
    57  
    58  // addNameToURL add a name that maps to raftURL and etcdURL
    59  func addNameToURL(name string, version string, raftURL string, etcdURL string) {
    60  	namesMap[name] = &nodeInfo{
    61  		raftVersion: raftVersion,
    62  		raftURL:     raftURL,
    63  		etcdURL:     etcdURL,
    64  	}
    65  }
    66  
    67  func readURL(nodeName string, urlName string) (string, bool) {
    68  	// if fails, try to recover from etcd storage
    69  	key := path.Join("/_etcd/machines", nodeName)
    70  
    71  	resps, err := etcdStore.RawGet(key)
    72  
    73  	if err != nil {
    74  		return "", false
    75  	}
    76  
    77  	m, err := url.ParseQuery(resps[0].Value)
    78  
    79  	if err != nil {
    80  		panic("Failed to parse machines entry")
    81  	}
    82  
    83  	url := m[urlName][0]
    84  
    85  	return url, true
    86  }