discovery.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package discovery
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "math/rand"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "strings"
  12. "sync"
  13. "time"
  14. "go-common/library/log"
  15. "go-common/library/naming"
  16. "go-common/library/stat/prom"
  17. "go-common/app/service/main/bns/agent/backend"
  18. )
  19. func init() {
  20. backend.Registry("discovery", New)
  21. }
  22. const (
  23. // NodeStatusUP Ready to receive register
  24. NodeStatusUP NodeStatus = iota
  25. // NodeStatusLost lost with each other
  26. NodeStatusLost
  27. defaultCacheExpireIn int64 = 10
  28. )
  29. // NodeStatus Status of instance
  30. type NodeStatus int
  31. // ServerNode backend servier node status
  32. type ServerNode struct {
  33. Addr string `json:"addr"`
  34. Zone string `json:"zone"`
  35. Status NodeStatus `json:"status"`
  36. }
  37. // InstanceList discovery instance list
  38. type InstanceList struct {
  39. Instances []naming.Instance `json:"instances"`
  40. LatestTimestamp int64 `json:"latest_timestamp"`
  41. }
  42. // InstanceMetadata discovery instance metadata
  43. type InstanceMetadata struct {
  44. Provider interface{} `json:"provider"`
  45. }
  46. type discoveryResp struct {
  47. Code int64 `json:"code"`
  48. Message string `json:"message"`
  49. }
  50. type discoveryFetchResp struct {
  51. discoveryResp `json:",inline"`
  52. Data *InstanceList `json:"data"`
  53. }
  54. type discoveryNodeResp struct {
  55. discoveryResp `json:",inline"`
  56. Data []ServerNode `json:"data"`
  57. }
  58. var urlParse = url.Parse
  59. // New discovery backend
  60. func New(config map[string]interface{}) (backend.Backend, error) {
  61. if config == nil {
  62. return nil, fmt.Errorf("discovery require url, secret, appkey")
  63. }
  64. var url, secret, appKey string
  65. var ok bool
  66. discoveryURL := os.Getenv("DISCOVERY_URL")
  67. if url, ok = config["url"].(string); !ok && discoveryURL == "" {
  68. return nil, fmt.Errorf("discovery require `url`")
  69. }
  70. // use env DISCOVERY_URL overwrite config
  71. if discoveryURL != "" {
  72. url = discoveryURL
  73. }
  74. if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
  75. url = "http://" + url
  76. }
  77. refreshInterval := time.Minute
  78. if second, ok := config["refresh_interval"].(int); ok {
  79. refreshInterval = time.Duration(second) * time.Second
  80. }
  81. cacheExpireIn := defaultCacheExpireIn
  82. if second, ok := config["cacheExpireIn"].(int); ok {
  83. cacheExpireIn = int64(second)
  84. }
  85. u, err := urlParse(url)
  86. if err != nil {
  87. return nil, err
  88. }
  89. dis := &discovery{
  90. client: http.DefaultClient,
  91. scheme: u.Scheme,
  92. host: u.Host,
  93. discoveryHosts: []string{u.Host},
  94. secret: secret,
  95. appKey: appKey,
  96. refreshTick: time.NewTicker(refreshInterval),
  97. cacheMap: make(map[string]*cacheNode),
  98. cacheExpireIn: cacheExpireIn,
  99. }
  100. go dis.daemon()
  101. return dis, nil
  102. }
  103. type cacheNode struct {
  104. expired int64
  105. data []*backend.Instance
  106. }
  107. func (c *cacheNode) IsExpired() bool {
  108. return time.Now().Unix() > c.expired
  109. }
  110. func newCacheNode(data []*backend.Instance, expireIn int64) *cacheNode {
  111. return &cacheNode{expired: time.Now().Unix() + expireIn, data: data}
  112. }
  113. type discovery struct {
  114. client *http.Client
  115. secret string
  116. appKey string
  117. host string
  118. scheme string
  119. discoveryHosts []string
  120. rmx sync.RWMutex
  121. cachermx sync.RWMutex
  122. cacheMap map[string]*cacheNode
  123. cacheExpireIn int64
  124. refreshTick *time.Ticker
  125. }
  126. var _ backend.Backend = &discovery{}
  127. func (d *discovery) Ping(ctx context.Context) error {
  128. _, err := d.Nodes(ctx)
  129. return err
  130. }
  131. func (d *discovery) Close(ctx context.Context) error {
  132. d.refreshTick.Stop()
  133. return nil
  134. }
  135. func (d *discovery) daemon() {
  136. for range d.refreshTick.C {
  137. log.V(10).Info("refresh discovery nodes ...")
  138. nodes, err := d.Nodes(context.Background())
  139. if err != nil {
  140. log.Error("refresh discovery nodes error %s", err)
  141. continue
  142. }
  143. hosts := make([]string, 0, len(nodes))
  144. for i := range nodes {
  145. if nodes[i].Status == NodeStatusUP {
  146. hosts = append(hosts, nodes[i].Addr)
  147. }
  148. }
  149. d.rmx.Lock()
  150. d.discoveryHosts = hosts
  151. d.rmx.Unlock()
  152. log.V(10).Info("new discovery nodes list %v", hosts)
  153. }
  154. }
  155. func (d *discovery) Nodes(ctx context.Context) ([]ServerNode, error) {
  156. req, err := http.NewRequest(http.MethodGet, "/discovery/nodes", nil)
  157. if err != nil {
  158. return nil, err
  159. }
  160. resp, err := d.do(req)
  161. if err != nil {
  162. return nil, err
  163. }
  164. defer resp.Body.Close()
  165. nodesResp := &discoveryNodeResp{}
  166. if err := json.NewDecoder(resp.Body).Decode(nodesResp); err != nil {
  167. return nil, err
  168. }
  169. if nodesResp.Code < 0 || nodesResp.Data == nil || len(nodesResp.Data) == 0 {
  170. return nil, fmt.Errorf("no data found, err: %s", nodesResp.Message)
  171. }
  172. log.V(10).Info("responsed data: %v", nodesResp.Data)
  173. return nodesResp.Data, nil
  174. }
  175. func (d *discovery) do(req *http.Request) (resp *http.Response, err error) {
  176. req.URL.Scheme = d.scheme
  177. req.Host = d.host
  178. req.URL.Scheme = d.scheme
  179. req.Host = d.host
  180. d.rmx.RLock()
  181. hosts := d.discoveryHosts
  182. d.rmx.RUnlock()
  183. for _, host := range shuffle(hosts) {
  184. req.URL.Host = host
  185. resp, err = d.client.Do(req)
  186. log.V(5).Info("request discovery.. request: %s", req.URL)
  187. if err == nil {
  188. return
  189. }
  190. log.Error("request discovery %s err %s, try next", host, err)
  191. }
  192. return
  193. }
  194. // Query appid
  195. func (d *discovery) Query(ctx context.Context, target backend.Target, sel backend.Selector, md backend.Metadata) ([]*backend.Instance, error) {
  196. // TODO: parallel query
  197. key := target.Name + sel.String()
  198. if data, ok := d.fromCache(key); ok {
  199. prom.CacheHit.Incr("bns:discovery_mem_cache_hit")
  200. return data, nil
  201. }
  202. prom.CacheMiss.Incr("bns:discovery_mem_cache_miss")
  203. instanceList, err := d.fetch(ctx, target.Name, sel, md)
  204. if err != nil {
  205. return nil, err
  206. }
  207. data := copyInstance(instanceList)
  208. if len(data) != 0 {
  209. d.setCache(key, data)
  210. }
  211. return data, nil
  212. }
  213. func (d *discovery) fromCache(key string) ([]*backend.Instance, bool) {
  214. d.cachermx.RLock()
  215. defer d.cachermx.RUnlock()
  216. node, ok := d.cacheMap[key]
  217. if !ok || node.IsExpired() {
  218. return nil, false
  219. }
  220. return node.data, true
  221. }
  222. func (d *discovery) setCache(key string, data []*backend.Instance) {
  223. d.cachermx.Lock()
  224. defer d.cachermx.Unlock()
  225. d.cacheMap[key] = newCacheNode(data, d.cacheExpireIn)
  226. }
  227. func (d *discovery) fetch(ctx context.Context, discoveryID string, sel backend.Selector, md backend.Metadata) (*InstanceList, error) {
  228. params := url.Values{}
  229. params.Add("appid", discoveryID)
  230. params.Add("env", sel.Env)
  231. params.Add("region", sel.Region)
  232. params.Add("hostname", md.ClientHost)
  233. params.Add("zone", sel.Zone)
  234. params.Add("status", "1")
  235. if md.LatestTimestamps != "" {
  236. params.Add("latest_timestamp", md.LatestTimestamps)
  237. } else {
  238. params.Add("latest_timestamp", "0")
  239. }
  240. payload := params.Encode()
  241. req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/discovery/fetch?%s", payload), nil)
  242. if err != nil {
  243. return nil, err
  244. }
  245. resp, err := d.do(req)
  246. if err != nil {
  247. return nil, err
  248. }
  249. defer resp.Body.Close()
  250. fetchResp := &discoveryFetchResp{}
  251. if err := json.NewDecoder(resp.Body).Decode(fetchResp); err != nil {
  252. return nil, err
  253. }
  254. if fetchResp.Code < 0 || fetchResp.Data == nil || fetchResp.Data.Instances == nil || len(fetchResp.Data.Instances) == 0 {
  255. return nil, fmt.Errorf("no data found, err: %s", fetchResp.Message)
  256. }
  257. log.V(10).Info("fetchResponsed data: %v", fetchResp.Data)
  258. return fetchResp.Data, nil
  259. }
  260. func shuffle(hosts []string) []string {
  261. for i := 0; i < len(hosts); i++ {
  262. j := rand.Intn(len(hosts) - i)
  263. hosts[i], hosts[i+j] = hosts[i+j], hosts[i]
  264. }
  265. return hosts
  266. }
  267. func copyInstance(il *InstanceList) (inss []*backend.Instance) {
  268. copyloop:
  269. for _, in := range il.Instances {
  270. out := &backend.Instance{
  271. DiscoveryID: in.AppID,
  272. Env: in.Env,
  273. Hostname: in.Hostname,
  274. Zone: in.Zone,
  275. }
  276. for _, addr := range in.Addrs {
  277. ip, err := ipFromURI(addr)
  278. if err == nil {
  279. out.IPAddr = ip
  280. inss = append(inss, out)
  281. continue copyloop
  282. }
  283. log.Error("extract ip from addr %s error: %s", addr, err)
  284. }
  285. log.Error("can't found any ip for discoveryID: %s", in.AppID)
  286. }
  287. return
  288. }
  289. // extract ip from uri
  290. func ipFromURI(uri string) (net.IP, error) {
  291. var hostport string
  292. if u, err := url.Parse(uri); err != nil {
  293. hostport = uri
  294. } else {
  295. hostport = u.Host
  296. }
  297. if strings.ContainsRune(hostport, ':') {
  298. host, _, err := net.SplitHostPort(hostport)
  299. if err != nil {
  300. return net.IPv4zero, err
  301. }
  302. return net.ParseIP(host), nil
  303. }
  304. return net.ParseIP(hostport), nil
  305. }