Skip to content

Commit

Permalink
support nacos (#27)
Browse files Browse the repository at this point in the history
* support nacos

* reorgnize nacos configuration

* modify the nacos configure name

* add example configure file
  • Loading branch information
giskook authored and scf0220 committed Nov 26, 2023
1 parent e1effdc commit 5693c64
Show file tree
Hide file tree
Showing 7 changed files with 193 additions and 2 deletions.
5 changes: 5 additions & 0 deletions config/environments/local/local.node.config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ EnableL2SuggestedGasPricePolling = true
[RPC.WebSockets]
Enabled = true
Port = 8546
[RCP.Nacos]
URLs = ""
NamespaceId = "public"
ApplicationName = ""
ExternalListenAddr = "127.0.0.1:8123"

[Synchronizer]
SyncInterval = "1s"
Expand Down
5 changes: 5 additions & 0 deletions config/environments/mainnet/node.config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ EnableL2SuggestedGasPricePolling = false
[RPC.WebSockets]
Enabled = true
Port = 8546
[RCP.Nacos]
URLs = ""
NamespaceId = "public"
ApplicationName = ""
ExternalListenAddr = "127.0.0.1:8123"

[Synchronizer]
SyncInterval = "2s"
Expand Down
5 changes: 5 additions & 0 deletions config/environments/testnet/node.config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ EnableL2SuggestedGasPricePolling = false
[RPC.WebSockets]
Enabled = true
Port = 8546
[RCP.Nacos]
URLs = ""
NamespaceId = "public"
ApplicationName = ""
ExternalListenAddr = "127.0.0.1:8123"

[Synchronizer]
SyncInterval = "2s"
Expand Down
17 changes: 17 additions & 0 deletions jsonrpc/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ type Config struct {
EnableHttpLog bool `mapstructure:"EnableHttpLog"`
// EnablePendingTransactionFilter enables pending transaction filter that can support query L2 pending transaction
EnablePendingTransactionFilter bool `mapstructure:"EnablePendingTransactionFilter"`

// Nacos configuration
Nacos NacosConfig `mspstructure:"Nacos"`
}

// WebSocketsConfig has parameters to config the rpc websocket support
Expand All @@ -80,3 +83,17 @@ type WebSocketsConfig struct {
// ReadLimit defines the maximum size of a message read from the client (in bytes)
ReadLimit int64 `mapstructure:"ReadLimit"`
}

type NacosConfig struct {
// URLs nacos server urls for discovery service of rest api, url is separated by ","
URLs string `mapstructure:"URLs"`

// NamespaceId nacos namepace id for discovery service of rest api
NamespaceId string `mapstructure:"NamespaceId"`

// ApplicationName rest application name in nacos
ApplicationName string `mapstructure:"ApplicationName"`

// ExternalListenAddr Set the rest-server external ip and port, when it is launched by Docker
ExternalListenAddr string `mapstructure:"ExternalListenAddr"`
}
94 changes: 94 additions & 0 deletions jsonrpc/nacos/start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package nacos

import (
"fmt"
"net"
"strconv"
"strings"
"time"

"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/vo"

"github.com/0xPolygonHermez/zkevm-node/log"
)

// StartNacosClient start nacos client and register rest service in nacos
func StartNacosClient(urls string, namespace string, name string, externalAddr string) {
ip, port, err := ResolveIPAndPort(externalAddr)
if err != nil {
log.Error(fmt.Sprintf("failed to resolve %s error: %s", externalAddr, err.Error()))
return
}

serverConfigs, err := getServerConfigs(urls)
if err != nil {
log.Error(fmt.Sprintf("failed to resolve nacos server url %s: %s", urls, err.Error()))
return
}
client, err := clients.CreateNamingClient(map[string]interface{}{
"serverConfigs": serverConfigs,
"clientConfig": constant.ClientConfig{
TimeoutMs: 5000,
ListenInterval: 10000,
NotLoadCacheAtStart: true,
NamespaceId: namespace,
LogDir: "/dev/null",
LogLevel: "error",
},
})
if err != nil {
log.Error(fmt.Sprintf("failed to create nacos client. error: %s", err.Error()))
return
}

_, err = client.RegisterInstance(vo.RegisterInstanceParam{
Ip: ip,
Port: uint64(port),
ServiceName: name,
Weight: 10,
ClusterName: "DEFAULT",
Enable: true,
Healthy: true,
Ephemeral: true,
Metadata: map[string]string{
"preserved.register.source": "GO",
"app_registry_tag": strconv.FormatInt(time.Now().Unix(), 10),
},
})
if err != nil {
log.Error(fmt.Sprintf("failed to register instance in nacos server. error: %s", err.Error()))
return
}
log.Info("register application instance in nacos successfully")
}

func ResolveIPAndPort(addr string) (string, int, error) {
laddr := strings.Split(addr, ":")
ip := laddr[0]
if ip == "127.0.0.1" {
return GetLocalIP(), 26659, nil
}
port, err := strconv.Atoi(laddr[1])
if err != nil {
return "", 0, err
}
return ip, port, nil
}

// GetLocalIP get local ip
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
55 changes: 55 additions & 0 deletions jsonrpc/nacos/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package nacos

import (
"fmt"
"strconv"
"strings"

"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/model"
"github.com/nacos-group/nacos-sdk-go/vo"
)

func GetOneInstance(urls string, nameSpace string, param vo.SelectOneHealthInstanceParam) (instance *model.Instance, err error) {
serverConfigs, err := getServerConfigs(urls)
if err != nil {
return nil, fmt.Errorf("failed to resolve nacos server url %s: %s", urls, err.Error())
}

namingClient, err := clients.CreateNamingClient(map[string]interface{}{
"serverConfigs": serverConfigs,
"clientConfig": constant.ClientConfig{
NamespaceId: nameSpace,
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "/dev/null",
},
})
if err != nil {
return nil, fmt.Errorf("failed to create nacos client when getting one service. error: %s", err.Error())
}

instance, err = namingClient.SelectOneHealthyInstance(param)
if err != nil {
return nil, fmt.Errorf("failed to get %s service in [%s, %s]. error: %s", param, urls, nameSpace, err.Error())
}
return instance, nil
}

func getServerConfigs(urls string) ([]constant.ServerConfig, error) {
// nolint
var configs []constant.ServerConfig
for _, url := range strings.Split(urls, ",") {
laddr := strings.Split(url, ":")
serverPort, err := strconv.Atoi(laddr[1])
if err != nil {
return nil, err
}
configs = append(configs, constant.ServerConfig{
IpAddr: laddr[0],
Port: uint64(serverPort),
})
}
return configs, nil
}
14 changes: 12 additions & 2 deletions jsonrpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ import (
"syscall"
"time"

"github.com/didip/tollbooth/v6"
"github.com/gorilla/websocket"

"github.com/0xPolygonHermez/zkevm-node/jsonrpc/metrics"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/nacos"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/types"
"github.com/0xPolygonHermez/zkevm-node/log"
"github.com/didip/tollbooth/v6"
"github.com/gorilla/websocket"
)

const (
Expand Down Expand Up @@ -101,6 +103,7 @@ func NewServer(
// Start initializes the JSON RPC server to listen for request
func (s *Server) Start() error {
metrics.Register()
s.registerNacos()

if s.config.WebSockets.Enabled {
go s.startWS()
Expand Down Expand Up @@ -532,3 +535,10 @@ func (s *Server) combinedLog(r *http.Request, start time.Time, httpStatus, dataL
r.UserAgent(),
)
}

func (s *Server) registerNacos() {
// start nacos client for registering restful service
if s.config.Nacos.URLs != "" {
nacos.StartNacosClient(s.config.Nacos.URLs, s.config.Nacos.NamespaceId, s.config.Nacos.ApplicationName, s.config.Nacos.ExternalListenAddr)
}
}

0 comments on commit 5693c64

Please sign in to comment.