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.7 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
clientset *kubernetes.Clientset
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
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
2 years ago
return &DnsDiscoveryRegistry{
2 years ago
clientset: clientset,
2 years ago
namespace: namespace,
opts: opts,
}, nil
}
2 years ago
func (d DnsDiscoveryRegistry) GetConns(ctx context.Context, serviceName string, opts ...grpc.DialOption) ([]*grpc.ClientConn, error) {
endpoints, err := d.clientset.CoreV1().Endpoints(d.namespace).Get(context.TODO(), serviceName, metav1.GetOptions{})
2 years ago
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.DialContext(ctx, 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
}
2 years ago
func (d DnsDiscoveryRegistry) GetConn(ctx context.Context, serviceName string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
return grpc.DialContext(ctx, 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...)
}