consul_catalog.go 3.8 KB
Newer Older
E
eoLinker API Management 已提交
1 2 3 4
package consul

import (
	"context"
黄孟柱 已提交
5 6
	log "github.com/eolinker/goku-api-gateway/goku-log"
	"github.com/eolinker/goku-api-gateway/goku-service/common"
E
eoLinker API Management 已提交
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
	"github.com/hashicorp/consul/api"
	"time"
)

type ConsulDiscovery struct {
	//Config *api.Config

	orgConfig string

	callback func([]*common.Service)
	client   *api.Client
	services []*common.Service

	instanceFactory *common.InstanceFactory
	cancel          context.CancelFunc
}

func (d *ConsulDiscovery) SetConfig(config string) error {
	if d.orgConfig == config {
		return nil
	}
	d.orgConfig = config
	c := api.DefaultConfig()
	c.Address = config
	//d.Config = c
	client, err := api.NewClient(c)
	if err != nil {
		return err
	}
	d.client = client

	return nil

}

func (d *ConsulDiscovery) Driver() string {
	return DriverName
}

func (d *ConsulDiscovery) SetCallback(callback func(services []*common.Service)) {
	d.callback = callback
}

func (d *ConsulDiscovery) GetServers() ([]*common.Service, error) {
	return d.services, nil
}

func (d *ConsulDiscovery) Close() error {
	if d.cancel != nil {
		d.cancel()
	}
	return nil
}

func (d *ConsulDiscovery) Open() error {

	d.ScheduleAtFixedRate(time.Second * 5)
	return nil
}

//address: [hostName:port]
func NewConsulDiscovery(address string) *ConsulDiscovery {
	config := api.DefaultConfig()
	config.Address = address

	client, err := api.NewClient(config)
	if err != nil {
		log.Error(err)
		return nil
	}

	cd := &ConsulDiscovery{
		callback:        nil,
		client:          client,
		services:        nil,
		orgConfig:       address,
		instanceFactory: common.NewInstanceFactory(),
	}

	return cd
}

func (d *ConsulDiscovery) GetServicesInTime() (map[string][]string, map[string][]*api.ServiceEntry, error) {

	q := &api.QueryOptions{}
	services, _, err := d.client.Catalog().Services(q)
	if err != nil {
		return nil, nil, err
	}

	catalogServices := make(map[string][]*api.ServiceEntry)

	for serviceName := range services {
Y
Your Name 已提交
100
		cs, _, err := d.client.Health().Service(serviceName, "", true, q)
E
eoLinker API Management 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
		if err != nil {
			log.Info(err.Error())
			continue
		}
		catalogServices[serviceName] = cs

	}

	return services, catalogServices, nil

}

func (d *ConsulDiscovery) ScheduleAtFixedRate(second time.Duration) {
	if d.cancel != nil {
		d.cancel()
		d.cancel = nil
	}
	d.run()
	ctx, cancel := context.WithCancel(context.Background())
	d.cancel = cancel
	go d.runTask(second, ctx)
}

func (d *ConsulDiscovery) runTask(second time.Duration, ctx context.Context) {
	timer := time.NewTicker(second)
	defer timer.Stop()
	for {
		select {
		case <-ctx.Done():
			{
				return
			}
		case <-timer.C:
			go d.run()
		}
	}
}
func (d *ConsulDiscovery) run() {
	services, catalogServices, err := d.GetServicesInTime()
	if err == nil || services != nil || catalogServices != nil {
		d.execCallbacks(services, catalogServices)
	} else {
		log.Info(err.Error())
	}
}

func (d *ConsulDiscovery) execCallbacks(services map[string][]string, catalogServices map[string][]*api.ServiceEntry) {
	if services == nil {
		log.Info("consul services is empty")
		return
	}
	if d.callback == nil {
		return
	}

	serviceList := make([]*common.Service, 0, len(catalogServices))
	for appName, catalogInstances := range catalogServices {

		size := len(catalogInstances)
Y
Your Name 已提交
160
		if size == 0 {
E
eoLinker API Management 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
			continue
		}
		hosts := make([]*common.Instance, size)
		for i, instance := range catalogInstances {
			//h.hostChangedCallback(appName, newHostInstanceByEureka(appName, &instance))
			hosts[i] = d.instanceFactory.General(instance.Node.Address, instance.Service.Port, 1)

		}

		s := common.NewService(appName, hosts)
		serviceList = append(serviceList, s)
	}
	d.services = serviceList
	d.callback(serviceList)

}

func (d *ConsulDiscovery) Health() (bool, string) {
	leader, err := d.client.Status().Leader()
	if err != nil || leader == "" {
		return false, err.Error()
	}

	ok, desc := true, "ok"

	return ok, desc

}