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.
Open-IM-Server/pkg/discoveryregistry/dns.go

64 lines
1.6 KiB

2 years ago
package discoveryregistry
import (
"context"
"fmt"
"net"
"google.golang.org/grpc"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
type DnsDiscoveryRegistry struct {
opts []grpc.DialOption
namespace string
2 years ago
config *rest.Config
2 years ago
}
2 years ago
func NewDnsDiscoveryRegistry(namespace string, opts []grpc.DialOption) (*DnsDiscoveryRegistry, error) {
2 years ago
config, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
2 years ago
return &DnsDiscoveryRegistry{
config: config,
namespace: namespace,
opts: opts,
}, nil
}
func (d DnsDiscoveryRegistry) GetConns(serviceName string, opts ...grpc.DialOption) ([]*grpc.ClientConn, error) {
clientset, err := kubernetes.NewForConfig(d.config)
2 years ago
if err != nil {
return nil, err
}
endpoints, err := clientset.CoreV1().Endpoints(d.namespace).Get(context.TODO(), serviceName, metav1.GetOptions{})
if err != nil {
return nil, err
}
var conns []*grpc.ClientConn
for _, subset := range endpoints.Subsets {
for _, address := range subset.Addresses {
for _, port := range subset.Ports {
2 years ago
conn, err := grpc.Dial(net.JoinHostPort(address.IP, string(port.Port)), append(d.opts, opts...)...)
2 years ago
if err != nil {
return nil, err
}
conns = append(conns, conn)
}
}
}
return conns, nil
}
func (d DnsDiscoveryRegistry) GetConn(serviceName string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
2 years ago
return grpc.Dial(fmt.Sprintf("%s.%s.svc.cluster.local", serviceName, d.namespace), append(d.opts, opts...)...)
2 years ago
}
func (d *DnsDiscoveryRegistry) AddOption(opts ...grpc.DialOption) {
d.opts = append(d.opts, opts...)
}