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/transport/grpc/resolver/discovery/resolver.go

88 lines
1.9 KiB

4 years ago
package discovery
import (
"context"
"encoding/json"
"errors"
4 years ago
"time"
"github.com/go-kratos/kratos/v2/internal/endpoint"
4 years ago
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/registry"
"google.golang.org/grpc/attributes"
"google.golang.org/grpc/resolver"
)
type discoveryResolver struct {
w registry.Watcher
cc resolver.ClientConn
log *log.Helper
ctx context.Context
cancel context.CancelFunc
insecure bool
4 years ago
}
func (r *discoveryResolver) watch() {
for {
select {
case <-r.ctx.Done():
return
default:
}
4 years ago
ins, err := r.w.Next()
if err != nil {
if errors.Is(err, context.Canceled) {
return
}
r.log.Errorf("[resolver] Failed to watch discovery endpoint: %v", err)
4 years ago
time.Sleep(time.Second)
continue
}
r.update(ins)
}
}
func (r *discoveryResolver) update(ins []*registry.ServiceInstance) {
var addrs []resolver.Address
for _, in := range ins {
endpoint, err := endpoint.ParseEndpoint(in.Endpoints, "grpc", !r.insecure)
4 years ago
if err != nil {
r.log.Errorf("[resolver] Failed to parse discovery endpoint: %v", err)
4 years ago
continue
}
if endpoint == "" {
continue
}
4 years ago
addr := resolver.Address{
ServerName: in.Name,
Attributes: parseAttributes(in.Metadata),
Addr: endpoint,
}
addrs = append(addrs, addr)
}
if len(addrs) == 0 {
r.log.Warnf("[resolver] Zero endpoint found,refused to write, instances: %v", ins)
return
}
4 years ago
r.cc.UpdateState(resolver.State{Addresses: addrs})
b, _ := json.Marshal(ins)
r.log.Infof("[resolver] update instances: %s", b)
4 years ago
}
func (r *discoveryResolver) Close() {
r.cancel()
r.w.Stop()
4 years ago
}
func (r *discoveryResolver) ResolveNow(options resolver.ResolveNowOptions) {}
func parseAttributes(md map[string]string) *attributes.Attributes {
pairs := make([]interface{}, 0, len(md))
4 years ago
for k, v := range md {
pairs = append(pairs, k, v)
}
return attributes.New(pairs...)
4 years ago
}