2019-01-15 18:50:37 +02:00
|
|
|
package registry
|
2016-05-01 20:31:03 +02:00
|
|
|
|
|
|
|
import (
|
2019-07-08 09:01:42 +02:00
|
|
|
"fmt"
|
2016-05-01 20:31:03 +02:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/micro/mdns"
|
|
|
|
)
|
|
|
|
|
|
|
|
type mdnsWatcher struct {
|
2019-01-15 18:50:37 +02:00
|
|
|
wo WatchOptions
|
2016-05-01 20:31:03 +02:00
|
|
|
ch chan *mdns.ServiceEntry
|
|
|
|
exit chan struct{}
|
2019-09-09 14:11:25 +02:00
|
|
|
// the mdns domain
|
|
|
|
domain string
|
2016-05-01 20:31:03 +02:00
|
|
|
}
|
|
|
|
|
2019-01-15 18:50:37 +02:00
|
|
|
func (m *mdnsWatcher) Next() (*Result, error) {
|
2016-05-01 20:31:03 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2018-02-19 19:12:37 +02:00
|
|
|
// Filter watch options
|
|
|
|
// wo.Service: Only keep services we care about
|
|
|
|
if len(m.wo.Service) > 0 && txt.Service != m.wo.Service {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2016-05-01 20:31:03 +02:00
|
|
|
var action string
|
|
|
|
|
|
|
|
if e.TTL == 0 {
|
|
|
|
action = "delete"
|
|
|
|
} else {
|
|
|
|
action = "create"
|
|
|
|
}
|
|
|
|
|
2019-01-15 18:50:37 +02:00
|
|
|
service := &Service{
|
2016-05-01 20:31:03 +02:00
|
|
|
Name: txt.Service,
|
|
|
|
Version: txt.Version,
|
|
|
|
Endpoints: txt.Endpoints,
|
|
|
|
}
|
|
|
|
|
2019-09-09 14:11:25 +02:00
|
|
|
// skip anything without the domain we care about
|
|
|
|
suffix := fmt.Sprintf(".%s.%s.", service.Name, m.domain)
|
|
|
|
if !strings.HasSuffix(e.Name, suffix) {
|
2016-05-01 20:31:03 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-01-15 18:50:37 +02:00
|
|
|
service.Nodes = append(service.Nodes, &Node{
|
2019-09-09 14:11:25 +02:00
|
|
|
Id: strings.TrimSuffix(e.Name, suffix),
|
2019-07-08 09:01:42 +02:00
|
|
|
Address: fmt.Sprintf("%s:%d", e.AddrV4.String(), e.Port),
|
2016-05-01 20:31:03 +02:00
|
|
|
Metadata: txt.Metadata,
|
|
|
|
})
|
|
|
|
|
2019-01-15 18:50:37 +02:00
|
|
|
return &Result{
|
2016-05-01 20:31:03 +02:00
|
|
|
Action: action,
|
|
|
|
Service: service,
|
|
|
|
}, nil
|
|
|
|
case <-m.exit:
|
2019-07-01 16:43:50 +02:00
|
|
|
return nil, ErrWatcherStopped
|
2016-05-01 20:31:03 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *mdnsWatcher) Stop() {
|
|
|
|
select {
|
|
|
|
case <-m.exit:
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
close(m.exit)
|
|
|
|
}
|
|
|
|
}
|