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

327 lines
7.2 KiB

6 years ago
package etcd
import (
"context"
"encoding/json"
"errors"
"flag"
6 years ago
"fmt"
"os"
"strings"
6 years ago
"sync"
"sync/atomic"
6 years ago
"time"
6 years ago
"github.com/bilibili/kratos/pkg/log"
"github.com/bilibili/kratos/pkg/naming"
"go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/mvcc/mvccpb"
"google.golang.org/grpc"
6 years ago
)
6 years ago
var (
//etcdPrefix is a etcd globe key prefix
endpoints string
etcdPrefix string
6 years ago
//Time units is second
registerTTL = 90
defaultDialTimeout = 30
6 years ago
)
6 years ago
6 years ago
var (
_once sync.Once
_builder naming.Builder
6 years ago
//ErrDuplication is a register duplication err
6 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
}
6 years ago
// Builder return default etcd resolver builder.
func Builder(c *clientv3.Config) naming.Builder {
_once.Do(func() {
_builder, _ = New(c)
6 years ago
})
return _builder
}
6 years ago
6 years ago
// Build register resolver into default etcd.
6 years ago
func Build(c *clientv3.Config, id string) naming.Resolver {
6 years ago
return Builder(c).Build(id)
}
6 years ago
// EtcdBuilder is a etcd clientv3 EtcdBuilder
6 years ago
type EtcdBuilder struct {
6 years ago
cli *clientv3.Client
6 years ago
ctx context.Context
cancelFunc context.CancelFunc
6 years ago
mutex sync.RWMutex
apps map[string]*appInfo
registry map[string]struct{}
6 years ago
}
type appInfo struct {
resolver map[*Resolve]struct{}
6 years ago
ins atomic.Value
e *EtcdBuilder
once sync.Once
6 years ago
}
6 years ago
6 years ago
// Resolve etch resolver.
type Resolve struct {
id string
event chan struct{}
e *EtcdBuilder
opt *naming.BuildOptions
6 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()},
}
}
6 years ago
cli, err := clientv3.New(*c)
if err != nil {
return nil, err
6 years ago
}
ctx, cancel := context.WithCancel(context.Background())
e = &EtcdBuilder{
6 years ago
cli: cli,
6 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 {
6 years ago
r := &Resolve{
id: appid,
e: e,
event: make(chan struct{}, 1),
opt: new(naming.BuildOptions),
6 years ago
}
e.mutex.Lock()
app, ok := e.apps[appid]
if !ok {
app = &appInfo{
resolver: make(map[*Resolve]struct{}),
6 years ago
e: e,
6 years ago
}
e.apps[appid] = app
}
app.resolver[r] = struct{}{}
e.mutex.Unlock()
if ok {
select {
case r.event <- struct{}{}:
default:
}
}
6 years ago
app.once.Do(func() {
6 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
6 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)
6 years ago
defer ticker.Stop()
for {
select {
case <-ticker.C:
_ = e.register(ctx, ins)
case <-ctx.Done():
_ = e.unregister(ins)
ch <- struct{}{}
return
}
}
}()
return
}
6 years ago
6 years ago
//注册和续约公用一个操作
6 years ago
func (e *EtcdBuilder) register(ctx context.Context, ins *naming.Instance) (err error) {
prefix := e.keyPrefix(ins)
6 years ago
val, _ := json.Marshal(ins)
6 years ago
ttlResp, err := e.cli.Grant(context.TODO(), int64(registerTTL))
6 years ago
if err != nil {
log.Error("etcd: register client.Grant(%v) error(%v)", registerTTL, err)
6 years ago
return err
}
6 years ago
_, err = e.cli.Put(ctx, prefix, string(val), clientv3.WithLease(ttlResp.ID))
if err != nil {
6 years ago
log.Error("etcd: register client.Put(%v) appid(%s) hostname(%s) error(%v)",
6 years ago
prefix, ins.AppID, ins.Hostname, err)
6 years ago
return err
}
return nil
}
6 years ago
func (e *EtcdBuilder) unregister(ins *naming.Instance) (err error) {
prefix := e.keyPrefix(ins)
6 years ago
6 years ago
if _, err = e.cli.Delete(context.TODO(), prefix); err != nil {
6 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)
6 years ago
}
6 years ago
6 years ago
// Close stop all running process including etcdfetch and register
func (e *EtcdBuilder) Close() error {
e.cancelFunc()
return nil
}
6 years ago
func (a *appInfo) watch(appID string) {
6 years ago
_ = a.fetchstore(appID)
prefix := fmt.Sprintf("/%s/%s/", etcdPrefix, appID)
6 years ago
rch := a.e.cli.Watch(a.e.ctx, prefix, clientv3.WithPrefix())
for wresp := range rch {
for _, ev := range wresp.Events {
6 years ago
if ev.Type == mvccpb.PUT || ev.Type == mvccpb.DELETE {
6 years ago
_ = a.fetchstore(appID)
}
}
}
}
6 years ago
func (a *appInfo) fetchstore(appID string) (err error) {
prefix := fmt.Sprintf("/%s/%s/", etcdPrefix, appID)
6 years ago
resp, err := a.e.cli.Get(a.e.ctx, prefix, clientv3.WithPrefix())
if err != nil {
6 years ago
log.Error("etcd: fetch client.Get(%s) error(%+v)", prefix, err)
return err
}
6 years ago
ins, err := a.paserIns(resp)
if err != nil {
6 years ago
return err
}
a.store(ins)
return nil
}
6 years ago
func (a *appInfo) store(ins *naming.InstancesInfo) {
6 years ago
6 years ago
a.ins.Store(ins)
a.e.mutex.RLock()
for rs := range a.resolver {
select {
case rs.event <- struct{}{}:
default:
6 years ago
}
6 years ago
}
a.e.mutex.RUnlock()
6 years ago
}
6 years ago
func (a *appInfo) paserIns(resp *clientv3.GetResponse) (ins *naming.InstancesInfo, err error) {
6 years ago
ins = &naming.InstancesInfo{
6 years ago
Instances: make(map[string][]*naming.Instance, 0),
6 years ago
}
for _, ev := range resp.Kvs {
in := new(naming.Instance)
6 years ago
err := json.Unmarshal(ev.Value, in)
if err != nil {
return nil, err
6 years ago
}
6 years ago
ins.Instances[in.Zone] = append(ins.Instances[in.Zone], in)
6 years ago
}
6 years ago
return ins, nil
6 years ago
}
6 years ago
6 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
}