agent.go 1.71 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
package consul

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"math/rand"
	"strconv"
)

func GetAgentInfo(client *api.Client) (string, string) {
	info, err := client.Agent().Self()
	if err != nil {
		fmt.Printf("%v\n", err)
		return "", ""
	}
	if info == nil {
		fmt.Println("Fail to get consul info.")
		return "", ""
	}
	ip := ""

	inter := info["DebugConfig"]["AdvertiseAddrLAN"]
	switch inter.(type) {
	case string:
		ip = inter.(string)
		break
	}

	nodeName := ""
	inter = info["Config"]["NodeName"]
	switch inter.(type) {
	case string:
		nodeName = inter.(string)
		break
	}
	return ip, nodeName
}

func SelectService(cataLog *api.Catalog, serviceName string, nodeName string) (string, error) {
	services, _, err := cataLog.Service(serviceName, "", nil)
	if err != nil {
		return "", err
	}
	if len(services) == 0 {
		fmt.Println("userCenter not found in catalog.")
		return "", nil
	}

	var count int32 = 0
	addr := ""
	for _, s := range services {
		fmt.Printf("service info: %v\n", s)
		if s.ServiceWeights.Passing == 1 {
			count++
			if s.Node == nodeName {
				addr = s.ServiceAddress + ":" + strconv.Itoa(s.ServicePort)
				break
			} else {
				if rand.Int31n(count) == 0 {
					addr = s.ServiceAddress + ":" + strconv.Itoa(s.ServicePort)
				}
			}
		}
	}
	return addr, nil
}

func GetServices(cataLog *api.Catalog, serviceName string) ([]string, error) {
	addrs := make([]string, 0)

	services, _, err := cataLog.Service(serviceName, "", nil)
	if err == nil {
		for _, s := range services {
			fmt.Printf("service info: %s, %s, %s:%d", s.ID, s.Node, s.ServiceAddress, s.ServicePort)
			if s.ServiceWeights.Passing == 1 {
				addrs = append(addrs, s.ServiceAddress+":"+strconv.Itoa(s.ServicePort))
			}
		}
	}
	return addrs, nil
}