micro/client/selector/dns/dns.go

125 lines
2.2 KiB
Go
Raw Normal View History

2019-01-07 10:41:26 +03:00
// Package dns provides a dns SRV selector
package dns
import (
2019-07-08 10:01:42 +03:00
"fmt"
2019-01-07 10:41:26 +03:00
"net"
2019-01-07 12:34:07 +03:00
"strconv"
2019-01-07 10:41:26 +03:00
"github.com/micro/go-micro/v2/client/selector"
"github.com/micro/go-micro/v2/registry"
2019-01-07 10:41:26 +03:00
)
type dnsSelector struct {
options selector.Options
domain string
}
var (
DefaultDomain = "local"
)
func (d *dnsSelector) Init(opts ...selector.Option) error {
for _, o := range opts {
o(&d.options)
}
return nil
}
func (d *dnsSelector) Options() selector.Options {
return d.options
}
func (d *dnsSelector) Select(service string, opts ...selector.SelectOption) (selector.Next, error) {
2019-01-07 12:34:07 +03:00
var srv []*net.SRV
// check if its host:port
host, port, err := net.SplitHostPort(service)
// not host:port
2019-01-07 10:41:26 +03:00
if err != nil {
2019-01-07 12:34:07 +03:00
// lookup the SRV record
_, srvs, err := net.LookupSRV(service, "tcp", d.domain)
if err != nil {
return nil, err
}
// set SRV records
srv = srvs
// got host:port
} else {
p, _ := strconv.Atoi(port)
// lookup the A record
ips, err := net.LookupHost(host)
if err != nil {
return nil, err
}
// create SRV records
for _, ip := range ips {
srv = append(srv, &net.SRV{
Target: ip,
Port: uint16(p),
})
}
2019-01-07 10:41:26 +03:00
}
nodes := make([]*registry.Node, 0, len(srv))
2019-01-07 10:41:26 +03:00
for _, node := range srv {
nodes = append(nodes, &registry.Node{
Id: node.Target,
2019-07-08 10:01:42 +03:00
Address: fmt.Sprintf("%s:%d", node.Target, node.Port),
2019-01-07 10:41:26 +03:00
})
}
services := []*registry.Service{
{
2019-01-07 10:41:26 +03:00
Name: service,
Nodes: nodes,
},
}
sopts := selector.SelectOptions{
Strategy: d.options.Strategy,
}
for _, opt := range opts {
opt(&sopts)
}
// apply the filters
for _, filter := range sopts.Filters {
services = filter(services)
}
// if there's nothing left, return
if len(services) == 0 {
return nil, selector.ErrNoneAvailable
}
return sopts.Strategy(services), nil
}
func (d *dnsSelector) Mark(service string, node *registry.Node, err error) {}
2019-01-07 10:41:26 +03:00
func (d *dnsSelector) Reset(service string) {}
2019-01-07 10:41:26 +03:00
func (d *dnsSelector) Close() error {
return nil
}
func (d *dnsSelector) String() string {
return "dns"
}
func NewSelector(opts ...selector.Option) selector.Selector {
options := selector.Options{
Strategy: selector.Random,
}
for _, o := range opts {
o(&options)
}
return &dnsSelector{options: options, domain: DefaultDomain}
}