micro/registry/mdns_registry.go

733 lines
14 KiB
Go
Raw Normal View History

2019-01-15 19:50:37 +03:00
// Package mdns is a multicast dns registry
package registry
import (
2020-04-10 19:19:26 +03:00
"bytes"
"compress/zlib"
2019-02-01 16:41:11 +03:00
"context"
2020-04-10 19:19:26 +03:00
"encoding/hex"
"encoding/json"
2019-07-08 10:01:42 +03:00
"fmt"
2020-04-10 19:19:26 +03:00
"io/ioutil"
2019-01-15 19:50:37 +03:00
"net"
2019-07-08 10:01:42 +03:00
"strconv"
2019-01-15 19:50:37 +03:00
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/v2/logger"
2020-04-11 15:02:53 +03:00
"github.com/micro/go-micro/v2/util/mdns"
2019-01-15 19:50:37 +03:00
)
const (
// every service is written to the global domain so * domain queries work, e.g.
// calling mdns.List(registry.ListDomain("*")) will list the services across all
// domains
globalDomain = "global"
2019-09-09 15:11:25 +03:00
)
2019-01-15 19:50:37 +03:00
type mdnsTxt struct {
Service string
Version string
Endpoints []*Endpoint
Metadata map[string]string
}
type mdnsEntry struct {
id string
node *mdns.Server
}
// services are a key/value map, with the service name as a key and the value being a
// slice of mdns entries, representing the nodes with a single _services entry to be
// used for listing
type services map[string][]*mdnsEntry
2019-01-15 19:50:37 +03:00
type mdnsRegistry struct {
opts Options
// the top level domains, these can be overriden using options
defaultDomain string
globalDomain string
2019-01-15 19:50:37 +03:00
sync.Mutex
domains map[string]services
mtx sync.RWMutex
// watchers
watchers map[string]*mdnsWatcher
// listener
listener chan *mdns.ServiceEntry
2019-01-15 19:50:37 +03:00
}
2020-04-12 13:01:09 +03:00
type mdnsWatcher struct {
id string
wo WatchOptions
ch chan *mdns.ServiceEntry
exit chan struct{}
// the mdns domain
domain string
// the registry
registry *mdnsRegistry
}
2020-04-10 19:19:26 +03:00
func encode(txt *mdnsTxt) ([]string, error) {
b, err := json.Marshal(txt)
if err != nil {
return nil, err
}
var buf bytes.Buffer
defer buf.Reset()
w := zlib.NewWriter(&buf)
if _, err := w.Write(b); err != nil {
return nil, err
}
w.Close()
encoded := hex.EncodeToString(buf.Bytes())
// individual txt limit
if len(encoded) <= 255 {
return []string{encoded}, nil
}
// split encoded string
var record []string
for len(encoded) > 255 {
record = append(record, encoded[:255])
encoded = encoded[255:]
}
record = append(record, encoded)
return record, nil
}
func decode(record []string) (*mdnsTxt, error) {
encoded := strings.Join(record, "")
hr, err := hex.DecodeString(encoded)
if err != nil {
return nil, err
}
br := bytes.NewReader(hr)
zr, err := zlib.NewReader(br)
if err != nil {
return nil, err
}
rbuf, err := ioutil.ReadAll(zr)
if err != nil {
return nil, err
}
var txt *mdnsTxt
if err := json.Unmarshal(rbuf, &txt); err != nil {
return nil, err
}
return txt, nil
}
2019-01-15 19:50:37 +03:00
func newRegistry(opts ...Option) Registry {
options := Options{
2019-09-09 15:11:25 +03:00
Context: context.Background(),
2019-11-30 04:16:32 +03:00
Timeout: time.Millisecond * 100,
2019-01-15 19:50:37 +03:00
}
2019-09-09 15:11:25 +03:00
for _, o := range opts {
o(&options)
}
// set the domain
defaultDomain := DefaultDomain
2019-09-09 15:11:25 +03:00
d, ok := options.Context.Value("mdns.domain").(string)
if ok {
defaultDomain = d
2019-09-09 15:11:25 +03:00
}
2019-01-15 19:50:37 +03:00
return &mdnsRegistry{
defaultDomain: defaultDomain,
globalDomain: globalDomain,
opts: options,
domains: make(map[string]services),
watchers: make(map[string]*mdnsWatcher),
2019-01-15 19:50:37 +03:00
}
}
func (m *mdnsRegistry) Init(opts ...Option) error {
for _, o := range opts {
o(&m.opts)
}
return nil
}
func (m *mdnsRegistry) Options() Options {
return m.opts
}
// createServiceMDNSEntry will create a new wildcard mdns entry for the service in the
// given domain. This wildcard mdns entry is used when listing services.
func createServiceMDNSEntry(name, domain string) (*mdnsEntry, error) {
ip := net.ParseIP("0.0.0.0")
s, err := mdns.NewMDNSService(name, "_services", domain+".", "", 9999, []net.IP{ip}, nil)
if err != nil {
return nil, err
}
srv, err := mdns.NewServer(&mdns.Config{Zone: &mdns.DNSSDService{MDNSService: s}})
if err != nil {
return nil, err
}
return &mdnsEntry{id: "*", node: srv}, nil
}
2019-01-15 19:50:37 +03:00
func (m *mdnsRegistry) Register(service *Service, opts ...RegisterOption) error {
m.Lock()
// parse the options
var options RegisterOptions
for _, o := range opts {
o(&options)
}
if len(options.Domain) == 0 {
options.Domain = m.defaultDomain
}
2019-01-15 19:50:37 +03:00
// create the domain in the memory store if it doesn't yet exist
if _, ok := m.domains[options.Domain]; !ok {
m.domains[options.Domain] = make(services)
}
// create the wildcard entry used for list queries in this domain
entries, ok := m.domains[options.Domain][service.Name]
if !ok {
entry, err := createServiceMDNSEntry(service.Name, options.Domain)
2019-01-15 19:50:37 +03:00
if err != nil {
m.Unlock()
2019-01-15 19:50:37 +03:00
return err
}
entries = append(entries, entry)
2019-01-15 19:50:37 +03:00
}
var gerr error
for _, node := range service.Nodes {
var seen bool
for _, entry := range entries {
if node.Id == entry.id {
seen = true
break
}
}
// this node has already been registered, continue
if seen {
2019-01-15 19:50:37 +03:00
continue
}
txt, err := encode(&mdnsTxt{
Service: service.Name,
Version: service.Version,
Endpoints: service.Endpoints,
Metadata: node.Metadata,
})
if err != nil {
gerr = err
continue
}
2019-07-08 10:01:42 +03:00
host, pt, err := net.SplitHostPort(node.Address)
if err != nil {
gerr = err
continue
}
port, _ := strconv.Atoi(pt)
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
logger.Debugf("[mdns] registry create new service with ip: %s for: %s", net.ParseIP(host).String(), host)
}
2019-01-15 19:50:37 +03:00
// we got here, new node
s, err := mdns.NewMDNSService(
node.Id,
service.Name,
options.Domain+".",
2019-01-15 19:50:37 +03:00
"",
2019-07-08 10:01:42 +03:00
port,
[]net.IP{net.ParseIP(host)},
2019-01-15 19:50:37 +03:00
txt,
)
if err != nil {
gerr = err
continue
}
srv, err := mdns.NewServer(&mdns.Config{Zone: s})
if err != nil {
gerr = err
continue
}
entries = append(entries, &mdnsEntry{id: node.Id, node: srv})
2019-01-15 19:50:37 +03:00
}
// save the mdns entry
m.domains[options.Domain][service.Name] = entries
m.Unlock()
// register in the global Domain so it can be queried as one
if options.Domain != m.globalDomain {
srv := *service
srv.Nodes = nil
for _, n := range service.Nodes {
node := n
// set the original domain in node metadata
if node.Metadata == nil {
node.Metadata = map[string]string{"domain": options.Domain}
} else {
node.Metadata["domain"] = options.Domain
}
srv.Nodes = append(srv.Nodes, node)
}
if err := m.Register(service, append(opts, RegisterDomain(m.globalDomain))...); err != nil {
gerr = err
}
}
2019-01-15 19:50:37 +03:00
return gerr
}
2020-04-14 14:32:59 +03:00
func (m *mdnsRegistry) Deregister(service *Service, opts ...DeregisterOption) error {
// parse the options
var options DeregisterOptions
for _, o := range opts {
o(&options)
}
if len(options.Domain) == 0 {
options.Domain = m.defaultDomain
}
// register in the global Domain
var err error
if options.Domain != m.globalDomain {
defer func() {
err = m.Deregister(service, append(opts, DeregisterDomain(m.globalDomain))...)
}()
}
// we want to unlock before we call deregister on the global domain, so it's important this unlock
// is applied after the defer m.Deregister is called above
2019-01-15 19:50:37 +03:00
m.Lock()
defer m.Unlock()
// the service wasn't registered, we can safely exist
if _, ok := m.domains[options.Domain]; !ok {
return err
}
2019-01-15 19:50:37 +03:00
// loop existing entries, check if any match, shutdown those that do
var newEntries []*mdnsEntry
for _, entry := range m.domains[options.Domain][service.Name] {
2019-01-15 19:50:37 +03:00
var remove bool
for _, node := range service.Nodes {
if node.Id == entry.id {
entry.node.Shutdown()
remove = true
break
}
}
// keep it?
if !remove {
newEntries = append(newEntries, entry)
}
}
// we have more than one entry remaining, we can exit
if len(newEntries) > 1 {
m.domains[options.Domain][service.Name] = newEntries
return err
}
// our remaining entry is not a wildcard, we can exit
if len(newEntries) == 1 && newEntries[0].id != "*" {
m.domains[options.Domain][service.Name] = newEntries
return err
}
2019-01-15 19:50:37 +03:00
// last entry is the wildcard for list queries. Remove it.
newEntries[0].node.Shutdown()
delete(m.domains[options.Domain], service.Name)
// check to see if we can delete the domain entry
if len(m.domains[options.Domain]) == 0 {
delete(m.domains, options.Domain)
2019-01-15 19:50:37 +03:00
}
return err
2019-01-15 19:50:37 +03:00
}
2020-04-14 14:32:59 +03:00
func (m *mdnsRegistry) GetService(service string, opts ...GetOption) ([]*Service, error) {
// parse the options
var options GetOptions
for _, o := range opts {
o(&options)
}
if len(options.Domain) == 0 {
options.Domain = m.defaultDomain
}
if options.Domain == WildcardDomain {
options.Domain = m.globalDomain
}
2019-01-15 19:50:37 +03:00
serviceMap := make(map[string]*Service)
2019-02-01 16:41:11 +03:00
entries := make(chan *mdns.ServiceEntry, 10)
done := make(chan bool)
p := mdns.DefaultParams(service)
// set context with timeout
2019-12-03 10:25:58 +03:00
var cancel context.CancelFunc
p.Context, cancel = context.WithTimeout(context.Background(), m.opts.Timeout)
defer cancel()
2019-02-01 16:41:11 +03:00
// set entries channel
p.Entries = entries
2019-09-09 15:11:25 +03:00
// set the domain
p.Domain = options.Domain
2019-01-15 19:50:37 +03:00
go func() {
for {
select {
2019-02-01 16:41:11 +03:00
case e := <-entries:
2019-01-15 19:50:37 +03:00
// list record so skip
if e.Name == "_services" {
2019-09-09 15:11:25 +03:00
continue
}
2019-01-15 19:50:37 +03:00
if e.TTL == 0 {
continue
}
txt, err := decode(e.InfoFields)
if err != nil {
continue
}
if txt.Service != service {
continue
}
s, ok := serviceMap[txt.Version]
if !ok {
s = &Service{
Name: txt.Service,
Version: txt.Version,
Endpoints: txt.Endpoints,
}
}
addr := ""
// prefer ipv4 addrs
if len(e.AddrV4) > 0 {
addr = e.AddrV4.String()
// else use ipv6
} else if len(e.AddrV6) > 0 {
addr = "[" + e.AddrV6.String() + "]"
} else {
if logger.V(logger.InfoLevel, logger.DefaultLogger) {
logger.Infof("[mdns]: invalid endpoint received: %v", e)
}
continue
}
2019-01-15 19:50:37 +03:00
s.Nodes = append(s.Nodes, &Node{
Id: strings.TrimSuffix(e.Name, "."+p.Service+"."+p.Domain+"."),
Address: fmt.Sprintf("%s:%d", addr, e.Port),
2019-01-15 19:50:37 +03:00
Metadata: txt.Metadata,
})
serviceMap[txt.Version] = s
2019-02-01 16:41:11 +03:00
case <-p.Context.Done():
close(done)
2019-01-15 19:50:37 +03:00
return
}
}
}()
2019-02-01 16:41:11 +03:00
// execute the query
2019-01-15 19:50:37 +03:00
if err := mdns.Query(p); err != nil {
return nil, err
}
2019-02-01 16:41:11 +03:00
// wait for completion
<-done
2019-01-15 19:50:37 +03:00
// create list and return
2019-11-11 03:03:51 +03:00
services := make([]*Service, 0, len(serviceMap))
2019-01-15 19:50:37 +03:00
for _, service := range serviceMap {
services = append(services, service)
}
return services, nil
}
2020-04-14 14:32:59 +03:00
func (m *mdnsRegistry) ListServices(opts ...ListOption) ([]*Service, error) {
// parse the options
var options ListOptions
for _, o := range opts {
o(&options)
}
if len(options.Domain) == 0 {
options.Domain = m.defaultDomain
}
if options.Domain == WildcardDomain {
options.Domain = m.globalDomain
}
2019-02-01 16:41:11 +03:00
serviceMap := make(map[string]bool)
entries := make(chan *mdns.ServiceEntry, 10)
done := make(chan bool)
2019-01-15 19:50:37 +03:00
2019-02-01 16:41:11 +03:00
p := mdns.DefaultParams("_services")
// set context with timeout
2019-12-03 10:25:58 +03:00
var cancel context.CancelFunc
p.Context, cancel = context.WithTimeout(context.Background(), m.opts.Timeout)
defer cancel()
2019-02-01 16:41:11 +03:00
// set entries channel
p.Entries = entries
2019-09-09 15:11:25 +03:00
// set domain
p.Domain = options.Domain
2019-01-15 19:50:37 +03:00
var services []*Service
go func() {
for {
select {
2019-02-01 16:41:11 +03:00
case e := <-entries:
2019-01-15 19:50:37 +03:00
if e.TTL == 0 {
continue
}
2019-09-09 15:11:25 +03:00
if !strings.HasSuffix(e.Name, p.Domain+".") {
continue
}
2019-01-15 19:50:37 +03:00
name := strings.TrimSuffix(e.Name, "."+p.Service+"."+p.Domain+".")
if !serviceMap[name] {
serviceMap[name] = true
services = append(services, &Service{Name: name})
}
2019-02-01 16:41:11 +03:00
case <-p.Context.Done():
close(done)
2019-01-15 19:50:37 +03:00
return
}
}
}()
2019-02-01 16:41:11 +03:00
// execute query
2019-01-15 19:50:37 +03:00
if err := mdns.Query(p); err != nil {
return nil, err
}
2019-02-01 16:41:11 +03:00
// wait till done
<-done
2019-01-15 19:50:37 +03:00
return services, nil
}
func (m *mdnsRegistry) Watch(opts ...WatchOption) (Watcher, error) {
var wo WatchOptions
for _, o := range opts {
o(&wo)
}
if len(wo.Domain) == 0 {
wo.Domain = m.defaultDomain
}
if wo.Domain == WildcardDomain {
wo.Domain = m.globalDomain
}
2019-01-15 19:50:37 +03:00
md := &mdnsWatcher{
id: uuid.New().String(),
wo: wo,
ch: make(chan *mdns.ServiceEntry, 32),
exit: make(chan struct{}),
domain: wo.Domain,
registry: m,
}
m.mtx.Lock()
defer m.mtx.Unlock()
// save the watcher
m.watchers[md.id] = md
// check of the listener exists
if m.listener != nil {
return md, nil
2019-01-15 19:50:37 +03:00
}
// start the listener
2019-01-15 19:50:37 +03:00
go func() {
// go to infinity
for {
m.mtx.Lock()
// just return if there are no watchers
if len(m.watchers) == 0 {
m.listener = nil
m.mtx.Unlock()
return
}
// check existing listener
if m.listener != nil {
m.mtx.Unlock()
return
}
// reset the listener
exit := make(chan struct{})
ch := make(chan *mdns.ServiceEntry, 32)
m.listener = ch
m.mtx.Unlock()
// send messages to the watchers
go func() {
send := func(w *mdnsWatcher, e *mdns.ServiceEntry) {
select {
case w.ch <- e:
default:
}
}
for {
select {
case <-exit:
return
case e, ok := <-ch:
if !ok {
return
}
m.mtx.RLock()
// send service entry to all watchers
for _, w := range m.watchers {
send(w, e)
}
m.mtx.RUnlock()
}
}
}()
// start listening, blocking call
mdns.Listen(ch, exit)
// mdns.Listen has unblocked
// kill the saved listener
m.mtx.Lock()
m.listener = nil
close(ch)
m.mtx.Unlock()
2019-01-15 19:50:37 +03:00
}
}()
return md, nil
}
func (m *mdnsRegistry) String() string {
return "mdns"
}
2020-04-12 13:01:09 +03:00
func (m *mdnsWatcher) Next() (*Result, error) {
for {
select {
case e := <-m.ch:
txt, err := decode(e.InfoFields)
if err != nil {
continue
}
if len(txt.Service) == 0 || len(txt.Version) == 0 {
continue
}
// Filter watch options
// wo.Service: Only keep services we care about
if len(m.wo.Service) > 0 && txt.Service != m.wo.Service {
continue
}
var action string
if e.TTL == 0 {
action = "delete"
} else {
action = "create"
}
service := &Service{
Name: txt.Service,
Version: txt.Version,
Endpoints: txt.Endpoints,
}
// skip anything without the domain we care about
suffix := fmt.Sprintf(".%s.%s.", service.Name, m.domain)
if !strings.HasSuffix(e.Name, suffix) {
continue
}
var addr string
if len(e.AddrV4) > 0 {
addr = e.AddrV4.String()
} else if len(e.AddrV6) > 0 {
addr = "[" + e.AddrV6.String() + "]"
} else {
addr = e.Addr.String()
}
2020-04-12 13:01:09 +03:00
service.Nodes = append(service.Nodes, &Node{
Id: strings.TrimSuffix(e.Name, suffix),
Address: fmt.Sprintf("%s:%d", addr, e.Port),
2020-04-12 13:01:09 +03:00
Metadata: txt.Metadata,
})
return &Result{
Action: action,
Service: service,
}, nil
case <-m.exit:
return nil, ErrWatcherStopped
}
}
}
func (m *mdnsWatcher) Stop() {
select {
case <-m.exit:
return
default:
close(m.exit)
// remove self from the registry
m.registry.mtx.Lock()
delete(m.registry.watchers, m.id)
m.registry.mtx.Unlock()
}
}
2019-01-15 19:50:37 +03:00
// NewRegistry returns a new default registry which is mdns
func NewRegistry(opts ...Option) Registry {
return newRegistry(opts...)
}