Skip to content

Commit

Permalink
code optimization
Browse files Browse the repository at this point in the history
code optimization
  • Loading branch information
werbenhu committed Apr 6, 2023
1 parent 48b4794 commit ef1be00
Show file tree
Hide file tree
Showing 10 changed files with 136 additions and 47 deletions.
16 changes: 4 additions & 12 deletions agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,6 @@ import (
"sync"
)

const (
TagGroup = "group"
TagService = "service"
TagReplicas = "replicas"

DefaultReplicas = "10000"
)

type Service struct {
Id string `json:"id"`
Group string `json:"group"`
Expand All @@ -32,7 +24,7 @@ type Agent struct {
Id string `json:"id"`
Addr string `json:"addr"`
Advertise string `json:"advertise"`
Members string `json:"-"`
Routers string `json:"-"`
Replicas string `json:"replicas"`
Service Service `json:"service"`
tags map[string]string
Expand All @@ -43,20 +35,20 @@ func newSimpleAgent(id string, addr string, advertise string) *Agent {
Id: id,
Addr: addr,
Advertise: advertise,
Members: "",
Routers: "",
Replicas: DefaultReplicas,
Service: Service{
Id: id,
},
}
}

func NewAgent(id string, addr string, advertise string, members string, group string, serviceAddr string) *Agent {
func NewAgent(id string, addr string, advertise string, routers string, group string, serviceAddr string) *Agent {
return &Agent{
Id: id,
Addr: addr,
Advertise: advertise,
Members: members,
Routers: routers,
Replicas: DefaultReplicas,
Service: Service{
Id: id,
Expand Down
56 changes: 54 additions & 2 deletions client/client.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,64 @@
package client

import (
"context"
"time"

"github.com/werbenhu/srouter"
"google.golang.org/grpc"
)

type Client struct {
Addr string
conn *grpc.ClientConn
rpc srouter.RouterClient
}

func (c *Client) Match() {
func New(router string) (*Client, error) {
client := &Client{Addr: router}
conn, err := grpc.Dial(client.Addr, grpc.WithInsecure())
if err != nil {
return nil, err
}

client.conn = conn
client.rpc = srouter.NewRouterClient(conn)
return client, nil
}

func (c *Client) Members() {
func (c *Client) Close() {
c.conn.Close()
}

func (c *Client) Match(group string, key string) (*srouter.Service, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

service, err := c.rpc.Match(ctx, &srouter.MatchRequest{
Group: group,
Key: key,
})
if err != nil {
return nil, err
}
return srouter.NewService(service.Id, service.Group, service.Addr), nil
}

func (c *Client) Members(group string) ([]*srouter.Service, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

services := make([]*srouter.Service, 0)

members, err := c.rpc.Members(ctx, &srouter.MembersRequest{
Group: group,
})
if err != nil {
return services, err
}
for _, member := range members.Services {
services = append(services, srouter.NewService(member.Id, member.Group, member.Addr))
}

return services, nil
}
4 changes: 2 additions & 2 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func main() {
id := flag.String("id", "node1", "")
addr := flag.String("addr", "172.16.3.3:7370", "")
advertise := flag.String("advertise", "172.16.3.3:7370", "")
members := flag.String("members", "", "")
routers := flag.String("routers", "", "")
service := flag.String("service", "", "")
port := flag.String("api-port", "8080", "")

Expand All @@ -31,7 +31,7 @@ func main() {
srouter.OptId(*id),
srouter.OptAddr(*addr),
srouter.OptAdvertise(*advertise),
srouter.OptMembers(*members),
srouter.OptRouters(*routers),
srouter.OptApiPort(*port),
srouter.OptService(*service),
})
Expand Down
23 changes: 23 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2023 werbenhu
// SPDX-FileContributor: werbenhu

package srouter

type err struct {
Msg string
Code int
}

func (e err) String() string {
return e.Msg
}

func (e err) Error() string {
return e.Msg
}

var (
ErrReplicasParam = err{Code: 10000, Msg: "agent replicas param error"}
ErrGroupNameEmpty = err{Code: 10001, Msg: "agent group name empty"}
)
29 changes: 29 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2023 werbenhu
// SPDX-FileContributor: werbenhu

package srouter

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestErrString(t *testing.T) {
c := err{
Msg: "test",
Code: 0x1,
}

require.Equal(t, "test", c.String())
}

func TestErrErrorr(t *testing.T) {
c := err{
Msg: "error",
Code: 0x1,
}

require.Equal(t, "error", error(c).Error())
}
7 changes: 3 additions & 4 deletions http.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package srouter

import (
"log"
"net"
"net/http"

Expand Down Expand Up @@ -50,7 +49,7 @@ func (h *Http) match(c *gin.Context) {
}

c.JSON(http.StatusOK, gin.H{
"code": 1,
"code": 0,
"msg": "success",
"data": gin.H{
"service": agent.Service,
Expand Down Expand Up @@ -79,7 +78,7 @@ func (h *Http) members(c *gin.Context) {
}

c.JSON(http.StatusOK, gin.H{
"code": 1,
"code": 0,
"msg": "success",
"data": gin.H{
"services": services,
Expand All @@ -97,7 +96,7 @@ func (h *Http) Start(port string) error {

h.listener, err = net.Listen("tcp", ":"+h.port)
if err != nil {
log.Fatalf("[ERROR] web listen to port:%s failed, err:%s", h.port, err.Error())
return err
}
return r.RunListener(h.listener)
}
Expand Down
8 changes: 4 additions & 4 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type Option struct {
Id string
Addr string
Advertise string
Members string
Routers string
ApiPort string
Service string
}
Expand Down Expand Up @@ -47,10 +47,10 @@ func OptAddr(addr string) IOption {
}
}

func OptMembers(members string) IOption {
func OptRouters(routers string) IOption {
return func(o *Option) {
if members != "" {
o.Members = members
if routers != "" {
o.Routers = routers
}
}
}
Expand Down
3 changes: 0 additions & 3 deletions rpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package srouter

import (
"context"
"log"
"net"

"github.com/werbenhu/chash"
Expand Down Expand Up @@ -43,7 +42,6 @@ func (s *RpcServer) Match(ctx context.Context, req *MatchRequest) (*MatchRespons
}

func (s *RpcServer) Members(ctx context.Context, req *MembersRequest) (*MembersResponse, error) {

group, err := chash.GetGroup(req.Group)
if err != nil {
return nil, err
Expand Down Expand Up @@ -74,7 +72,6 @@ func (s *RpcServer) Start(port string) error {
s.port = port
listener, err := net.Listen("tcp", ":"+s.port)
if err != nil {
log.Fatalf("[ERROR] rpc listen to port:%s failed, err:%s", s.port, err.Error())
return err
}

Expand Down
9 changes: 4 additions & 5 deletions serf.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ func (s *Serf) Start() error {
MinLevel: logutils.LogLevel("ERROR"),
Writer: io.MultiWriter(&lumberjack.Logger{
Filename: "./log/serf.log",
MaxSize: 10, // megabytes
MaxSize: 10,
MaxBackups: 3,
MaxAge: 28, //days
MaxAge: 28,
}, os.Stderr),
}

Expand All @@ -88,8 +88,8 @@ func (s *Serf) Start() error {

go s.Loop()
log.Printf("[INFO] serf discovery started, current agent addr:%s, advertise addr:%s\n", s.agent.Addr, s.agent.Advertise)
if len(s.agent.Members) > 0 {
members := strings.Split(s.agent.Members, ",")
if len(s.agent.Routers) > 0 {
members := strings.Split(s.agent.Routers, ",")
s.Join(members)
}
return nil
Expand Down Expand Up @@ -162,7 +162,6 @@ func (s *Serf) Loop() {
log.Printf("[ERROR] serf handle agent leave err:%s\n", err.Error())
}
}

}
}
}
Expand Down
28 changes: 13 additions & 15 deletions srouter.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package srouter

import (
"errors"
"log"
"strconv"

"github.com/werbenhu/chash"
)

const (
GroupName = "router-group"
TagGroup = "group"
TagService = "service"
TagReplicas = "replicas"

SRouterName = "srouter-group"
DefaultReplicas = "10000"
)

type SRouter struct {
Expand All @@ -30,12 +34,12 @@ func New(opts []IOption) *SRouter {
s.opt.Id,
s.opt.Addr,
s.opt.Advertise,
s.opt.Members,
GroupName,
s.opt.Routers,
SRouterName,
s.opt.Service,
))

s.api = NewHttp()
s.api = NewRpcServer()
s.serf.SetHandler(s)
return s
}
Expand Down Expand Up @@ -75,16 +79,13 @@ func (s *SRouter) OnAgentUpdate(agent *Agent) error {
}

func (s *SRouter) delete(agent *Agent) error {
log.Printf("[INFO] srouter delete agent, id:%s, addr:%s, group:%s, service:%s\n",
agent.Id, agent.Addr, agent.Service.Group, agent.Service.Addr)

if len(agent.Service.Group) == 0 {
return errors.New("srouter delete agent's group name can't be empty")
return ErrGroupNameEmpty
}

replicas, err := strconv.Atoi(agent.Replicas)
if err != nil {
return errors.New("srouter agent replicas param error")
return ErrReplicasParam
}

group, _ := chash.CreateGroup(agent.Service.Group, replicas)
Expand All @@ -95,16 +96,13 @@ func (s *SRouter) delete(agent *Agent) error {
}

func (s *SRouter) insert(agent *Agent) error {
log.Printf("[INFO] srouter insert agent, id:%s, addr:%s, group:%s, service:%s\n",
agent.Id, agent.Addr, agent.Service.Group, agent.Service.Addr)

if len(agent.Service.Group) == 0 {
return errors.New("srouter insert agent's group name can't be empty")
return ErrGroupNameEmpty
}

replicas, err := strconv.Atoi(agent.Replicas)
if err != nil {
return errors.New("srouter agent replicas param error")
return ErrReplicasParam
}

payload, err := agent.Marshal()
Expand Down

0 comments on commit ef1be00

Please sign in to comment.