Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP]refactor: softly connect to cwgo-pkg #115

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/pr-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ jobs:
with:
version: latest
working-directory: ${{ matrix.workdir }}
args: -E gofumpt --timeout 10m
args: -E gofumpt --out-format=colored-line-number --timeout 10m
skip-pkg-cache: true
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.18
go-version: 1.21

- uses: actions/cache@v3
with:
Expand Down
53 changes: 49 additions & 4 deletions consul/go.mod
Original file line number Diff line number Diff line change
@@ -1,9 +1,54 @@
module github.com/hertz-contrib/registry/consul

go 1.16
go 1.21

require (
github.com/cloudwego/hertz v0.6.0
github.com/hashicorp/consul/api v1.15.0
github.com/stretchr/testify v1.8.2
github.com/cloudwego-contrib/cwgo-pkg/registry/consul v0.0.0-00010101000000-000000000000
github.com/cloudwego/hertz v0.9.2
github.com/hashicorp/consul/api v1.26.1
github.com/stretchr/testify v1.9.0
)

require (
github.com/armon/go-metrics v0.4.1 // indirect
github.com/bytedance/go-tagexpr/v2 v2.9.2 // indirect
github.com/bytedance/gopkg v0.1.1 // indirect
github.com/bytedance/sonic v1.12.2 // indirect
github.com/bytedance/sonic/loader v0.2.0 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/cloudwego/netpoll v0.6.4 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fatih/color v1.16.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-hclog v1.5.0 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/hashicorp/serf v0.10.1 // indirect
github.com/henrylee2cn/ameda v1.4.10 // indirect
github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/nyaruka/phonenumbers v1.0.55 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/tidwall/gjson v1.17.3 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
golang.org/x/arch v0.2.0 // indirect
golang.org/x/exp v0.0.0-20240112132812-db7319d0e0e3 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.19.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

replace github.com/cloudwego-contrib/cwgo-pkg/registry/consul => github.com/smx-Morgan/cwgo-pkg/registry/consul v0.0.0-20241016000926-d56ef7e0f578
2,278 changes: 2,220 additions & 58 deletions consul/go.sum

Large diffs are not rendered by default.

122 changes: 5 additions & 117 deletions consul/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,133 +15,21 @@
package consul

import (
"errors"
"fmt"
"net"

"github.com/cloudwego-contrib/cwgo-pkg/registry/consul/consulhertz"
cwOption "github.com/cloudwego-contrib/cwgo-pkg/registry/consul/options"
"github.com/cloudwego/hertz/pkg/app/server/registry"
"github.com/hashicorp/consul/api"
)

const (
DefaultCheckInterval = "5s"
DefaultCheckTimeout = "5s"
DefaultCheckDeregisterCriticalServiceAfter = "1m"
)

var (
ErrNilInfo = errors.New("info is nil")
ErrMissingServiceName = errors.New("missing service name in consul register")
ErrMissingAddr = errors.New("missing addr in consul register")
)

type consulRegistry struct {
consulClient *api.Client
opts options
}

var _ registry.Registry = (*consulRegistry)(nil)

type options struct {
check *api.AgentServiceCheck
}

// Option is the option of Consul.
type Option func(o *options)
type Option = cwOption.Option

// WithCheck is consul registry option to set AgentServiceCheck.
func WithCheck(check *api.AgentServiceCheck) Option {
return func(o *options) { o.check = check }
return cwOption.WithCheck(check)
}

// NewConsulRegister create a new registry using consul.
func NewConsulRegister(consulClient *api.Client, opts ...Option) registry.Registry {
op := options{
check: defaultCheck(),
}

for _, opt := range opts {
opt(&op)
}

return &consulRegistry{consulClient: consulClient, opts: op}
}

// Register register a service to consul.
func (c *consulRegistry) Register(info *registry.Info) error {
if err := validateRegistryInfo(info); err != nil {
return fmt.Errorf("validating registry info failed, err: %w", err)
}

host, port, err := parseAddr(info.Addr)
if err != nil {
return fmt.Errorf("parsing addr failed, err: %w", err)
}

svcID, err := getServiceId(info)
if err != nil {
return fmt.Errorf("getting service id failed, err: %w", err)
}

tags, err := convTagMapToSlice(info.Tags)
if err != nil {
return err
}

svcInfo := &api.AgentServiceRegistration{
ID: svcID,
Name: info.ServiceName,
Address: host,
Port: port,
Tags: tags,
Weights: &api.AgentWeights{
Passing: info.Weight,
Warning: info.Weight,
},
Check: c.opts.check,
}
if c.opts.check != nil {
c.opts.check.TCP = net.JoinHostPort(host, fmt.Sprintf("%d", port))
svcInfo.Check = c.opts.check
}

return c.consulClient.Agent().ServiceRegister(svcInfo)
}

// Deregister deregister a service from consul.
func (c *consulRegistry) Deregister(info *registry.Info) error {
err := validateRegistryInfo(info)
if err != nil {
return fmt.Errorf("validating registry info failed, err: %w", err)
}

svcID, err := getServiceId(info)
if err != nil {
return err
}

return c.consulClient.Agent().ServiceDeregister(svcID)
}

func defaultCheck() *api.AgentServiceCheck {
check := new(api.AgentServiceCheck)
check.Timeout = DefaultCheckTimeout
check.Interval = DefaultCheckInterval
check.DeregisterCriticalServiceAfter = DefaultCheckDeregisterCriticalServiceAfter

return check
}

func validateRegistryInfo(info *registry.Info) error {
if info == nil {
return ErrNilInfo
}
if info.ServiceName == "" {
return ErrMissingServiceName
}
if info.Addr == nil {
return ErrMissingAddr
}

return nil
return consulhertz.NewConsulRegister(consulClient, opts...)
}
54 changes: 2 additions & 52 deletions consul/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,62 +15,12 @@
package consul

import (
"context"
"fmt"
"net"

"github.com/cloudwego-contrib/cwgo-pkg/registry/consul/consulhertz"
"github.com/cloudwego/hertz/pkg/app/client/discovery"
"github.com/hashicorp/consul/api"
)

const (
defaultNetwork = "tcp"
)

type consulResolver struct {
consulClient *api.Client
}

var _ discovery.Resolver = (*consulResolver)(nil)

// NewConsulResolver create a service resolver using consul.
func NewConsulResolver(consulClient *api.Client) discovery.Resolver {
return &consulResolver{consulClient: consulClient}
}

// Target return a description for the given target that is suitable for being a key for cache.
func (c *consulResolver) Target(_ context.Context, target *discovery.TargetInfo) (description string) {
return target.Host
}

// Name returns the name of the resolver.
func (c *consulResolver) Name() string {
return "consul"
}

// Resolve a service info by desc.
func (c *consulResolver) Resolve(_ context.Context, desc string) (discovery.Result, error) {
var eps []discovery.Instance
agentServiceList, _, err := c.consulClient.Health().Service(desc, "", true, nil)
if err != nil {
return discovery.Result{}, err
}
for _, i := range agentServiceList {
svc := i.Service
if svc == nil || svc.Address == "" {
continue
}
tags := splitTags(svc.Tags)
eps = append(eps, discovery.NewInstance(
defaultNetwork,
net.JoinHostPort(svc.Address, fmt.Sprintf("%d", svc.Port)),
svc.Weights.Passing,
tags,
))
}

return discovery.Result{
CacheKey: desc,
Instances: eps,
}, nil
return consulhertz.NewConsulResolver(consulClient)
}
111 changes: 0 additions & 111 deletions consul/utils.go

This file was deleted.

Loading
Loading