You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/pkg/naming/etcd/etcd.go

325 lines
7.2 KiB

5 years ago
package etcd
import (
"context"
"encoding/json"
"errors"
"flag"
5 years ago
"fmt"
"os"
"strings"
5 years ago
"sync"
"sync/atomic"
5 years ago
"time"
5 years ago
"go.etcd.io/etcd/api/v3/mvccpb"
"go.etcd.io/etcd/client/v3"
"google.golang.org/grpc"
"github.com/go-kratos/kratos/pkg/log"
"github.com/go-kratos/kratos/pkg/naming"
5 years ago
)
5 years ago
var (
//etcdPrefix is a etcd globe key prefix
endpoints string
etcdPrefix string
5 years ago
//Time units is second
registerTTL = 90
defaultDialTimeout = 30
5 years ago
)
5 years ago
5 years ago
var (
_once sync.Once
_builder naming.Builder
5 years ago
//ErrDuplication is a register duplication err
5 years ago
ErrDuplication = errors.New("etcd: instance duplicate registration")
)
func init() {
addFlag(flag.CommandLine)
}
func addFlag(fs *flag.FlagSet) {
// env
fs.StringVar(&endpoints, "etcd.endpoints", os.Getenv("ETCD_ENDPOINTS"), "etcd.endpoints is etcd endpoints. value: 127.0.0.1:2379,127.0.0.2:2379 etc.")
fs.StringVar(&etcdPrefix, "etcd.prefix", defaultString("ETCD_PREFIX", "kratos_etcd"), "etcd globe key prefix or use ETCD_PREFIX env variable. value etcd_prefix etc.")
}
func defaultString(env, value string) string {
v := os.Getenv(env)
if v == "" {
return value
}
return v
}
5 years ago
// Builder return default etcd resolver builder.
func Builder(c *clientv3.Config) naming.Builder {
_once.Do(func() {
_builder, _ = New(c)
5 years ago
})
return _builder
}
5 years ago
5 years ago
// Build register resolver into default etcd.
5 years ago
func Build(c *clientv3.Config, id string) naming.Resolver {
5 years ago
return Builder(c).Build(id)
}
5 years ago
// EtcdBuilder is a etcd clientv3 EtcdBuilder
5 years ago
type EtcdBuilder struct {
5 years ago
cli *clientv3.Client
5 years ago
ctx context.Context
cancelFunc context.CancelFunc
5 years ago
mutex sync.RWMutex
apps map[string]*appInfo
registry map[string]struct{}
5 years ago
}
type appInfo struct {
resolver map[*Resolve]struct{}
5 years ago
ins atomic.Value
e *EtcdBuilder
once sync.Once
5 years ago
}
5 years ago
5 years ago
// Resolve etch resolver.
type Resolve struct {
id string
event chan struct{}
e *EtcdBuilder
opt *naming.BuildOptions
5 years ago
}
// New is new a etcdbuilder
func New(c *clientv3.Config) (e *EtcdBuilder, err error) {
if c == nil {
if endpoints == "" {
panic(fmt.Errorf("invalid etcd config endpoints:%+v", endpoints))
}
c = &clientv3.Config{
Endpoints: strings.Split(endpoints, ","),
DialTimeout: time.Second * time.Duration(defaultDialTimeout),
DialOptions: []grpc.DialOption{grpc.WithBlock()},
}
}
5 years ago
cli, err := clientv3.New(*c)
if err != nil {
return nil, err
5 years ago
}
ctx, cancel := context.WithCancel(context.Background())
e = &EtcdBuilder{
5 years ago
cli: cli,
5 years ago
ctx: ctx,
cancelFunc: cancel,
apps: map[string]*appInfo{},
registry: map[string]struct{}{},
}
return
}
// Build disovery resovler builder.
func (e *EtcdBuilder) Build(appid string, opts ...naming.BuildOpt) naming.Resolver {
5 years ago
r := &Resolve{
id: appid,
e: e,
event: make(chan struct{}, 1),
opt: new(naming.BuildOptions),
5 years ago
}
e.mutex.Lock()
app, ok := e.apps[appid]
if !ok {
app = &appInfo{
resolver: make(map[*Resolve]struct{}),
5 years ago
e: e,
5 years ago
}
e.apps[appid] = app
}
app.resolver[r] = struct{}{}
e.mutex.Unlock()
if ok {
select {
case r.event <- struct{}{}:
default:
}
}
5 years ago
app.once.Do(func() {
5 years ago
go app.watch(appid)
log.Info("etcd: AddWatch(%s) already watch(%v)", appid, ok)
})
return r
}
// Scheme return etcd's scheme
func (e *EtcdBuilder) Scheme() string {
return "etcd"
}
// Register is register instance
5 years ago
func (e *EtcdBuilder) Register(ctx context.Context, ins *naming.Instance) (cancelFunc context.CancelFunc, err error) {
e.mutex.Lock()
if _, ok := e.registry[ins.AppID]; ok {
err = ErrDuplication
} else {
e.registry[ins.AppID] = struct{}{}
}
e.mutex.Unlock()
if err != nil {
return
}
ctx, cancel := context.WithCancel(e.ctx)
if err = e.register(ctx, ins); err != nil {
e.mutex.Lock()
delete(e.registry, ins.AppID)
e.mutex.Unlock()
cancel()
return
}
ch := make(chan struct{}, 1)
cancelFunc = context.CancelFunc(func() {
cancel()
<-ch
})
go func() {
ticker := time.NewTicker(time.Duration(registerTTL/3) * time.Second)
5 years ago
defer ticker.Stop()
for {
select {
case <-ticker.C:
_ = e.register(ctx, ins)
case <-ctx.Done():
_ = e.unregister(ins)
ch <- struct{}{}
return
}
}
}()
return
}
5 years ago
5 years ago
//注册和续约公用一个操作
5 years ago
func (e *EtcdBuilder) register(ctx context.Context, ins *naming.Instance) (err error) {
prefix := e.keyPrefix(ins)
5 years ago
val, _ := json.Marshal(ins)
5 years ago
ttlResp, err := e.cli.Grant(context.TODO(), int64(registerTTL))
5 years ago
if err != nil {
log.Error("etcd: register client.Grant(%v) error(%v)", registerTTL, err)
5 years ago
return err
}
5 years ago
_, err = e.cli.Put(ctx, prefix, string(val), clientv3.WithLease(ttlResp.ID))
if err != nil {
5 years ago
log.Error("etcd: register client.Put(%v) appid(%s) hostname(%s) error(%v)",
5 years ago
prefix, ins.AppID, ins.Hostname, err)
5 years ago
return err
}
return nil
}
5 years ago
func (e *EtcdBuilder) unregister(ins *naming.Instance) (err error) {
prefix := e.keyPrefix(ins)
5 years ago
5 years ago
if _, err = e.cli.Delete(context.TODO(), prefix); err != nil {
5 years ago
log.Error("etcd: unregister client.Delete(%v) appid(%s) hostname(%s) error(%v)",
prefix, ins.AppID, ins.Hostname, err)
}
log.Info("etcd: unregister client.Delete(%v) appid(%s) hostname(%s) success",
prefix, ins.AppID, ins.Hostname)
return
}
func (e *EtcdBuilder) keyPrefix(ins *naming.Instance) string {
return fmt.Sprintf("/%s/%s/%s", etcdPrefix, ins.AppID, ins.Hostname)
5 years ago
}
5 years ago
5 years ago
// Close stop all running process including etcdfetch and register
func (e *EtcdBuilder) Close() error {
e.cancelFunc()
return nil
}
5 years ago
func (a *appInfo) watch(appID string) {
5 years ago
_ = a.fetchstore(appID)
prefix := fmt.Sprintf("/%s/%s/", etcdPrefix, appID)
5 years ago
rch := a.e.cli.Watch(a.e.ctx, prefix, clientv3.WithPrefix())
for wresp := range rch {
for _, ev := range wresp.Events {
5 years ago
if ev.Type == mvccpb.PUT || ev.Type == mvccpb.DELETE {
5 years ago
_ = a.fetchstore(appID)
}
}
}
}
5 years ago
func (a *appInfo) fetchstore(appID string) (err error) {
prefix := fmt.Sprintf("/%s/%s/", etcdPrefix, appID)
5 years ago
resp, err := a.e.cli.Get(a.e.ctx, prefix, clientv3.WithPrefix())
if err != nil {
5 years ago
log.Error("etcd: fetch client.Get(%s) error(%+v)", prefix, err)
return err
}
5 years ago
ins, err := a.paserIns(resp)
if err != nil {
5 years ago
return err
}
a.store(ins)
return nil
}
5 years ago
func (a *appInfo) store(ins *naming.InstancesInfo) {
a.ins.Store(ins)
a.e.mutex.RLock()
for rs := range a.resolver {
select {
case rs.event <- struct{}{}:
default:
5 years ago
}
5 years ago
}
a.e.mutex.RUnlock()
5 years ago
}
5 years ago
func (a *appInfo) paserIns(resp *clientv3.GetResponse) (ins *naming.InstancesInfo, err error) {
5 years ago
ins = &naming.InstancesInfo{
Instances: make(map[string][]*naming.Instance),
5 years ago
}
for _, ev := range resp.Kvs {
in := new(naming.Instance)
5 years ago
err := json.Unmarshal(ev.Value, in)
if err != nil {
return nil, err
5 years ago
}
5 years ago
ins.Instances[in.Zone] = append(ins.Instances[in.Zone], in)
5 years ago
}
5 years ago
return ins, nil
5 years ago
}
5 years ago
5 years ago
// Watch watch instance.
func (r *Resolve) Watch() <-chan struct{} {
return r.event
}
// Fetch fetch resolver instance.
func (r *Resolve) Fetch(ctx context.Context) (ins *naming.InstancesInfo, ok bool) {
r.e.mutex.RLock()
app, ok := r.e.apps[r.id]
r.e.mutex.RUnlock()
if ok {
ins, ok = app.ins.Load().(*naming.InstancesInfo)
return
}
return
}
// Close close resolver.
func (r *Resolve) Close() error {
r.e.mutex.Lock()
if app, ok := r.e.apps[r.id]; ok && len(app.resolver) != 0 {
delete(app.resolver, r)
}
r.e.mutex.Unlock()
return nil
}