Skip to content

Commit e2c4e45

Browse files
committed
Fix bug with naocs
1 parent 2393f09 commit e2c4e45

File tree

11 files changed

+108
-74
lines changed

11 files changed

+108
-74
lines changed

internal/config/serverNameExample.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ func Show(hiddenFields ...string) string {
1919

2020
func Get() *Config {
2121
if config == nil {
22-
panic("config is nil")
22+
panic("config is nil, please call config.Init() first")
2323
}
2424
return config
2525
}

internal/server/grpc.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ func (s *grpcServer) secureServerOption() grpc.ServerOption {
124124
if err != nil {
125125
panic(err)
126126
}
127-
logger.Info("rpc security type: sever-side certification")
127+
logger.Info("grpc security type: sever-side certification")
128128
return grpc.Creds(credentials)
129129

130130
case "two-way": // both client and server side certification
@@ -136,11 +136,11 @@ func (s *grpcServer) secureServerOption() grpc.ServerOption {
136136
if err != nil {
137137
panic(err)
138138
}
139-
logger.Info("rpc security type: both client-side and server-side certification")
139+
logger.Info("grpc security type: both client-side and server-side certification")
140140
return grpc.Creds(credentials)
141141
}
142142

143-
logger.Info("rpc security type: insecure")
143+
logger.Info("grpc security type: insecure")
144144
return nil
145145
}
146146

internal/service/service_test.go

Lines changed: 52 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package service
22

33
import (
44
"context"
5+
"strconv"
56
"testing"
67
"time"
78

@@ -30,7 +31,7 @@ func TestRegisterAllService(t *testing.T) {
3031
})
3132
}
3233

33-
// The default is to connect to the local grpc service, if you want to connect to a remote grpc service,
34+
// The default is to connect to the local grpc server, if you want to connect to a remote grpc server,
3435
// pass in the parameter grpcClient.
3536
func getRPCClientConnForTest(grpcClient ...config.GrpcClient) *grpc.ClientConn {
3637
err := config.Init(configs.Path("serverNameExample.yml"))
@@ -40,21 +41,22 @@ func getRPCClientConnForTest(grpcClient ...config.GrpcClient) *grpc.ClientConn {
4041
var grpcClientCfg config.GrpcClient
4142

4243
if len(grpcClient) == 0 {
44+
// default config from configuration file serverNameExample.yml
4345
grpcClientCfg = config.GrpcClient{
44-
Host: "127.0.0.1",
46+
Host: config.Get().App.Host,
4547
Port: config.Get().Grpc.Port,
46-
47-
Name: "",
48-
EnableLoadBalance: false,
49-
RegistryDiscoveryType: "",
50-
ClientSecure: config.ClientSecure{},
51-
ClientToken: config.ClientToken{},
48+
// If RegistryDiscoveryType is not empty, service discovery is used, and Host and Port values are invalid
49+
RegistryDiscoveryType: config.Get().App.RegistryDiscoveryType, // supports consul, etcd and nacos
50+
Name: config.Get().App.Name,
51+
}
52+
if grpcClientCfg.RegistryDiscoveryType != "" {
53+
grpcClientCfg.EnableLoadBalance = true
5254
}
5355
} else {
56+
// custom config
5457
grpcClientCfg = grpcClient[0]
5558
}
5659

57-
endpoint := grpcClientCfg.Host + ":" + utils.IntToStr(grpcClientCfg.Port)
5860
var cliOptions []grpccli.Option
5961

6062
// load balance
@@ -83,66 +85,58 @@ func getRPCClientConnForTest(grpcClient ...config.GrpcClient) *grpc.ClientConn {
8385
grpccli.WithEnableLog(logger.Get()),
8486
)
8587

86-
isUseDiscover := false
87-
if config.Get().App.RegistryDiscoveryType != "" {
88-
var iDiscovery registry.Discovery
89-
endpoint = "discovery:///" + config.Get().App.Name // Connecting to grpc services by service name
90-
91-
// Use consul service discovery, note that the host field in the configuration file serverNameExample.yml
92-
// needs to be filled with the local ip, not 127.0.0.1, to do the health check
93-
if config.Get().App.RegistryDiscoveryType == "consul" {
94-
cli, err := consulcli.Init(config.Get().Consul.Addr, consulcli.WithWaitTime(time.Second*2))
95-
if err != nil {
96-
panic(err)
97-
}
98-
iDiscovery = consul.New(cli)
99-
isUseDiscover = true
100-
}
88+
var (
89+
endpoint string
90+
isUseDiscover bool
91+
iDiscovery registry.Discovery
92+
)
10193

102-
// Use etcd service discovery, use the command etcdctl get / --prefix to see if the service is registered before testing,
103-
// note: the IDE using a proxy may cause the connection to the etcd service to fail
104-
if config.Get().App.RegistryDiscoveryType == "etcd" {
105-
cli, err := etcdcli.Init(config.Get().Etcd.Addrs, etcdcli.WithDialTimeout(time.Second*2))
106-
if err != nil {
107-
panic(err)
108-
}
109-
iDiscovery = etcd.New(cli)
110-
isUseDiscover = true
94+
switch grpcClientCfg.RegistryDiscoveryType {
95+
case "consul":
96+
endpoint = "discovery:///" + grpcClientCfg.Name // Connecting to grpc services by service name
97+
cli, err := consulcli.Init(config.Get().Consul.Addr, consulcli.WithWaitTime(time.Second*2))
98+
if err != nil {
99+
panic(err)
111100
}
112-
113-
// Use nacos service discovery
114-
if config.Get().App.RegistryDiscoveryType == "nacos" {
115-
// example: endpoint = "discovery:///serverName.scheme"
116-
endpoint = "discovery:///" + config.Get().App.Name + ".grpc"
117-
cli, err := nacoscli.NewNamingClient(
118-
config.Get().NacosRd.IPAddr,
119-
config.Get().NacosRd.Port,
120-
config.Get().NacosRd.NamespaceID)
121-
if err != nil {
122-
panic(err)
123-
}
124-
iDiscovery = nacos.New(cli)
125-
isUseDiscover = true
101+
iDiscovery = consul.New(cli)
102+
isUseDiscover = true
103+
104+
case "etcd":
105+
endpoint = "discovery:///" + grpcClientCfg.Name // Connecting to grpc services by service name
106+
cli, err := etcdcli.Init(config.Get().Etcd.Addrs, etcdcli.WithDialTimeout(time.Second*2))
107+
if err != nil {
108+
panic(err)
126109
}
110+
iDiscovery = etcd.New(cli)
111+
isUseDiscover = true
112+
case "nacos":
113+
// example: endpoint = "discovery:///serverName.scheme"
114+
endpoint = "discovery:///" + grpcClientCfg.Name + ".grpc"
115+
cli, err := nacoscli.NewNamingClient(
116+
config.Get().NacosRd.IPAddr,
117+
config.Get().NacosRd.Port,
118+
config.Get().NacosRd.NamespaceID)
119+
if err != nil {
120+
panic(err)
121+
}
122+
iDiscovery = nacos.New(cli)
123+
isUseDiscover = true
127124

128-
cliOptions = append(cliOptions, grpccli.WithDiscovery(iDiscovery))
125+
default:
126+
endpoint = grpcClientCfg.Host + ":" + strconv.Itoa(grpcClientCfg.Port)
127+
iDiscovery = nil
128+
isUseDiscover = false
129129
}
130130

131-
if config.Get().App.EnableTrace {
132-
cliOptions = append(cliOptions, grpccli.WithEnableTrace())
133-
}
134-
if config.Get().App.EnableCircuitBreaker {
135-
cliOptions = append(cliOptions, grpccli.WithEnableCircuitBreaker())
136-
}
137-
if config.Get().App.EnableMetrics {
138-
cliOptions = append(cliOptions, grpccli.WithEnableMetrics())
131+
if iDiscovery != nil {
132+
cliOptions = append(cliOptions, grpccli.WithDiscovery(iDiscovery))
139133
}
140134

141135
msg := "dialing grpc server"
142136
if isUseDiscover {
143-
msg += " with discovery from " + config.Get().App.RegistryDiscoveryType
137+
msg += " with discovery from " + grpcClientCfg.RegistryDiscoveryType
144138
}
145-
logger.Info(msg, logger.String("name", config.Get().App.Name), logger.String("endpoint", endpoint))
139+
logger.Info(msg, logger.String("name", grpcClientCfg.Name), logger.String("endpoint", endpoint))
146140

147141
conn, err := grpccli.Dial(context.Background(), endpoint, cliOptions...)
148142
if err != nil {

pkg/consulcli/consulcli_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ func TestInit(t *testing.T) {
1313
WithScheme("http"),
1414
WithWaitTime(time.Second*2),
1515
WithDatacenter(""),
16+
WithToken("your-token"),
1617
)
1718
t.Log(err, cli)
1819

pkg/consulcli/option.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ type options struct {
1313
scheme string
1414
waitTime time.Duration
1515
datacenter string
16+
token string
1617

1718
// if you set this parameter, all fields above are invalid
1819
config *api.Config
@@ -52,6 +53,13 @@ func WithDatacenter(datacenter string) Option {
5253
}
5354
}
5455

56+
// WithToken set token
57+
func WithToken(token string) Option {
58+
return func(o *options) {
59+
o.token = token
60+
}
61+
}
62+
5563
// WithConfig set consul config
5664
func WithConfig(c *api.Config) Option {
5765
return func(o *options) {

pkg/grpc/grpccli/dail.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
"google.golang.org/grpc/credentials/insecure"
1616
)
1717

18-
// Dial to rpc server
18+
// Dial to grpc server
1919
func Dial(ctx context.Context, endpoint string, opts ...Option) (*grpc.ClientConn, error) {
2020
o := defaultOptions()
2121
o.apply(opts...)

pkg/nacoscli/nacos.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import (
1919
type Params struct {
2020
IPAddr string // server address
2121
Port uint64 // port
22-
Scheme string // http or https
22+
Scheme string // http or grpc
2323
ContextPath string // path
2424
// if you set this parameter, the above fields(IPAddr, Port, Scheme, ContextPath) are invalid
2525
serverConfigs []constant.ServerConfig
@@ -70,6 +70,8 @@ func setParams(params *Params, opts ...Option) {
7070
NotLoadCacheAtStart: true,
7171
LogDir: os.TempDir() + "/nacos/log",
7272
CacheDir: os.TempDir() + "/nacos/cache",
73+
Username: o.username,
74+
Password: o.password,
7375
}
7476
}
7577

@@ -86,7 +88,7 @@ func setParams(params *Params, opts ...Option) {
8688
}
8789
}
8890

89-
// Init get configuration from nacos and parse to struct
91+
// Init get configuration from nacos and parse to struct, use for configuration centre
9092
func Init(obj interface{}, params *Params, opts ...Option) error {
9193
err := params.valid()
9294
if err != nil {

pkg/nacoscli/nacos_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ func TestParse(t *testing.T) {
5757
err := Init(conf, params,
5858
WithClientConfig(clientConfig),
5959
WithServerConfigs(serverConfigs),
60+
WithAuth("foo", "bar"),
6061
)
6162
t.Log(err, conf)
6263
})

pkg/nacoscli/option.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import (
55
)
66

77
type options struct {
8+
username string
9+
password string
10+
11+
// if set the clientConfig, the above fields(username, password) are invalid
812
clientConfig *constant.ClientConfig
913
serverConfigs []constant.ServerConfig
1014
}
@@ -25,6 +29,14 @@ func (o *options) apply(opts ...Option) {
2529
}
2630
}
2731

32+
// WithAuth set authentication
33+
func WithAuth(username string, password string) Option {
34+
return func(o *options) {
35+
o.username = username
36+
o.password = password
37+
}
38+
}
39+
2840
// WithClientConfig set nacos client config
2941
func WithClientConfig(clientConfig *constant.ClientConfig) Option {
3042
return func(o *options) {

pkg/servicerd/registry/nacos/registry.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ func (r *Registry) Register(_ context.Context, si *registry.ServiceInstance) err
116116
var rmd map[string]string
117117
if si.Metadata == nil {
118118
rmd = map[string]string{
119+
"id": si.ID,
119120
"kind": u.Scheme,
120121
"version": si.Version,
121122
}
@@ -124,6 +125,7 @@ func (r *Registry) Register(_ context.Context, si *registry.ServiceInstance) err
124125
for k, v := range si.Metadata {
125126
rmd[k] = v
126127
}
128+
rmd["id"] = si.ID
127129
rmd["kind"] = u.Scheme
128130
rmd["version"] = si.Version
129131
}
@@ -140,7 +142,7 @@ func (r *Registry) Register(_ context.Context, si *registry.ServiceInstance) err
140142
GroupName: r.opts.group,
141143
})
142144
if e != nil {
143-
return fmt.Errorf("RegisterInstance err %v,%v", e, endpoint)
145+
return fmt.Errorf("RegisterInstance err %v, id = %s", e, si.ID)
144146
}
145147
}
146148
return nil
@@ -193,11 +195,18 @@ func (r *Registry) GetService(_ context.Context, serviceName string) ([]*registr
193195
items := make([]*registry.ServiceInstance, 0, len(res))
194196
for _, in := range res {
195197
kind := r.opts.kind
196-
if k, ok := in.Metadata["kind"]; ok {
197-
kind = k
198+
id := in.InstanceId
199+
if in.Metadata != nil {
200+
if k, ok := in.Metadata["kind"]; ok {
201+
kind = k
202+
}
203+
if v, ok := in.Metadata["id"]; ok {
204+
id = v
205+
delete(in.Metadata, "id")
206+
}
198207
}
199208
items = append(items, &registry.ServiceInstance{
200-
ID: in.InstanceId,
209+
ID: id,
201210
Name: in.ServiceName,
202211
Version: in.Metadata["version"],
203212
Metadata: in.Metadata,

0 commit comments

Comments
 (0)