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

feat: support Consul as ServiceRegistry #666

Merged
merged 50 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
66d0cb7
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 27, 2024
fe5182e
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 27, 2024
1bfb1d4
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 27, 2024
3120753
Merge branch 'mosn:main' into main
lyt122 Jun 27, 2024
7bf2834
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 27, 2024
d0dc175
Merge branch 'main' of github.com:lyt122/htnn
lyt122 Jun 27, 2024
17ed368
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 30, 2024
99bf29d
format go
lyt122 Jun 30, 2024
57329f4
Merge branch 'mosn:main' into main
lyt122 Jul 3, 2024
6eb6b03
refactor codes
lyt122 Jul 6, 2024
5c99c69
refactor codes
lyt122 Jul 6, 2024
846ff5b
refactor codes
lyt122 Jul 6, 2024
f330ec6
refactor codes
lyt122 Jul 6, 2024
29822b8
add test codes
lyt122 Jul 7, 2024
a7bf59d
add test codes
lyt122 Jul 7, 2024
6719586
add test codes
lyt122 Jul 7, 2024
daf2c24
add test codes
lyt122 Jul 7, 2024
7120888
add test codes
lyt122 Jul 7, 2024
c2ffc2e
fix: avoid data race
lyt122 Jul 8, 2024
46d90e6
refactor codes
lyt122 Jul 9, 2024
2b01940
fix golangci-lint error
lyt122 Jul 9, 2024
c1522d2
add test codes
lyt122 Jul 9, 2024
c7cdd4a
Merge branch 'mosn:main' into main
lyt122 Jul 9, 2024
4c686e2
refactor codes
lyt122 Jul 10, 2024
cc84ebd
refactor codes
lyt122 Jul 10, 2024
5e32bea
fix: avoid data race
lyt122 Jul 10, 2024
930b568
fix: avoid data race
lyt122 Jul 10, 2024
1eaa4e7
refactor codes
lyt122 Jul 10, 2024
e34511d
Merge branch 'main' of github.com:lyt122/htnn
lyt122 Jul 10, 2024
7a1551f
refactor codes
lyt122 Jul 11, 2024
bbefd66
refactor codes
lyt122 Jul 12, 2024
f239cf5
refactor codes
lyt122 Jul 12, 2024
75d00da
refactor codes
lyt122 Jul 12, 2024
b9d7d06
refactor: watch the dir of file
lyt122 Jul 14, 2024
0b03da5
refactor codes
lyt122 Jul 14, 2024
8ca375a
use file's abspath
lyt122 Jul 15, 2024
363dd1d
refactor codes
lyt122 Jul 15, 2024
b81b325
refactor codes
lyt122 Jul 15, 2024
c879870
refactor codes
lyt122 Jul 16, 2024
ac85bd9
refactor codes
lyt122 Jul 16, 2024
43abae4
Merge branch 'mosn:main' into main
lyt122 Jul 17, 2024
ca0f2f0
Merge branch 'mosn:main' into main
lyt122 Jul 25, 2024
b57534e
Merge branch 'main' of github.com:lyt122/htnn
lyt122 Aug 1, 2024
ca62248
feat: refresh consul services
lyt122 Aug 1, 2024
817d903
Remove redundant code
lyt122 Aug 1, 2024
d759bff
refactor codes to avoid test failed
lyt122 Aug 1, 2024
2b2fc28
add more tests
lyt122 Aug 2, 2024
f0d005c
refactor codes
lyt122 Aug 6, 2024
d7de52d
add more tests
lyt122 Aug 6, 2024
49c5909
write test codes in one style
lyt122 Aug 7, 2024
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
115 changes: 86 additions & 29 deletions controller/registries/consul/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,6 @@
})
}

const (
defaultToken = ""
)

type Consul struct {
consul.RegistryType
logger log.RegistryLogger
Expand All @@ -70,11 +66,7 @@

DataCenter string
NameSpace string
}

type consulService struct {
DataCenter string
ServiceName string
Token string
}

func (reg *Consul) NewClient(config *consul.Config) (*Client, error) {
Expand All @@ -85,7 +77,7 @@
clientConfig := consulapi.DefaultConfig()
clientConfig.Address = uri.Host
clientConfig.Scheme = uri.Scheme
clientConfig.Token = defaultToken
clientConfig.Token = config.Token
clientConfig.Datacenter = config.DataCenter

client, err := consulapi.NewClient(clientConfig)
Expand All @@ -97,9 +89,16 @@
consulClient: client,
consulCatalog: client.Catalog(),
DataCenter: config.DataCenter,
NameSpace: config.Namespace,
Token: config.Token,
}, nil
}

type consulService struct {
Tag string
ServiceName string
}

func (reg *Consul) Start(c registrytype.RegistryConfig) error {
config := c.(*consul.Config)

Expand All @@ -108,11 +107,13 @@
return err
}

services, err := reg.fetchAllServices(client)
reg.client = client

services, err := reg.fetchAllServices(reg.client)

if err != nil {
return fmt.Errorf("fetch all services error: %v", err)
return err
}
reg.client = client

reg.watchingServices = services

Expand All @@ -122,22 +123,29 @@
}
go func() {
reg.logger.Infof("start refreshing services")
ticker := time.NewTicker(dur)
//q := consulapi.QueryOptions{
// WaitTime: dur,
//}
defer ticker.Stop()
q := &consulapi.QueryOptions{
WaitTime: dur,
Namespace: config.Namespace,
Datacenter: config.DataCenter,
Token: config.Token,
}
for {

select {
case <-ticker.C:
err := reg.refresh()
if err != nil {
reg.logger.Errorf("failed to refresh services, err: %v", err)
}
case <-reg.done:
reg.logger.Infof("stop refreshing services")
return
default:

Check warning on line 138 in controller/registries/consul/config.go

View check run for this annotation

Codecov / codecov/patch

controller/registries/consul/config.go#L138

Added line #L138 was not covered by tests
}
services, meta, err := reg.client.consulCatalog.Services(q)
if err != nil {
reg.logger.Errorf("failed to get services, err: %v", err)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a sleep and skip this turn would be better? So we can retry after some time.

time.Sleep(dur)
continue

Check warning on line 144 in controller/registries/consul/config.go

View check run for this annotation

Codecov / codecov/patch

controller/registries/consul/config.go#L140-L144

Added lines #L140 - L144 were not covered by tests
}
reg.refresh(services)

Check warning on line 146 in controller/registries/consul/config.go

View check run for this annotation

Codecov / codecov/patch

controller/registries/consul/config.go#L146

Added line #L146 was not covered by tests

q.WaitIndex = meta.LastIndex

Check warning on line 148 in controller/registries/consul/config.go

View check run for this annotation

Codecov / codecov/patch

controller/registries/consul/config.go#L148

Added line #L148 was not covered by tests
}
}()

Expand All @@ -160,13 +168,28 @@
return nil
}

func (reg *Consul) refresh() error {
return nil
}

func (reg *Consul) fetchAllServices(client *Client) (map[consulService]bool, error) {
fmt.Println(client)
return nil, nil
q := &consulapi.QueryOptions{}
q.Datacenter = client.DataCenter
q.Namespace = client.NameSpace
q.Token = client.Token
services, _, err := client.consulCatalog.Services(q)

if err != nil {
reg.logger.Errorf("failed to get service, err: %v", err)
return nil, err
}
serviceMap := make(map[consulService]bool)
for serviceName, tags := range services {
for _, tag := range tags {
service := consulService{
Tag: tag,
ServiceName: serviceName,
}
serviceMap[service] = true
}
}
return serviceMap, nil
}

func (reg *Consul) subscribe(serviceName string) error {
Expand All @@ -178,3 +201,37 @@
fmt.Println(serviceName)
return nil
}

func (reg *Consul) refresh(services map[string][]string) {
serviceMap := make(map[consulService]bool)
for serviceName, tags := range services {
for _, tag := range tags {
service := consulService{
Tag: tag,
ServiceName: serviceName,
}
serviceMap[service] = true
if _, ok := reg.watchingServices[service]; !ok {
err := reg.subscribe(serviceName)
if err != nil {
reg.logger.Errorf("failed to subscribe service, err: %v, service: %v", err, serviceName)
delete(serviceMap, service)

Check warning on line 218 in controller/registries/consul/config.go

View check run for this annotation

Codecov / codecov/patch

controller/registries/consul/config.go#L217-L218

Added lines #L217 - L218 were not covered by tests
}
}
}
}

prevFetchServices := reg.watchingServices
reg.watchingServices = serviceMap

for key := range prevFetchServices {
if _, ok := serviceMap[key]; !ok {
err := reg.unsubscribe(key.ServiceName)
if err != nil {
reg.logger.Errorf("failed to unsubscribe service, err: %v, service: %v", err, key)

Check warning on line 231 in controller/registries/consul/config.go

View check run for this annotation

Codecov / codecov/patch

controller/registries/consul/config.go#L231

Added line #L231 was not covered by tests
}
reg.softDeletedServices[key] = true
}
}

}
142 changes: 131 additions & 11 deletions controller/registries/consul/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@
package consul

import (
"errors"
"reflect"
"testing"

"github.com/agiledragon/gomonkey/v2"
"github.com/hashicorp/consul/api"
"github.com/stretchr/testify/assert"

"mosn.io/htnn/controller/pkg/registry/log"
Expand Down Expand Up @@ -50,28 +54,42 @@ func TestStart(t *testing.T) {
logger: log.NewLogger(&log.RegistryLoggerOptions{
Name: "test",
}),
softDeletedServices: map[consulService]bool{},
done: make(chan struct{}),
watchingServices: map[consulService]bool{},
}
config := &consul.Config{
ServerUrl: "http://127.0.0.1:8500",
done: make(chan struct{}),
}

patches := gomonkey.ApplyPrivateMethod(reflect.TypeOf(reg), "fetchAllServices", func(_ *Consul, client *Client) (map[consulService]bool, error) {
return map[consulService]bool{
{ServiceName: "service1", Tag: "tag1"}: true,
{ServiceName: "service2", Tag: "tag2"}: true,
}, nil
})
config := &consul.Config{}
err := reg.Start(config)
assert.NoError(t, err)

assert.Nil(t, err)
err = reg.subscribe("123")
assert.Nil(t, err)

err = reg.unsubscribe("123")
assert.Nil(t, err)

err = reg.refresh()
assert.Nil(t, err)

err = reg.Stop()
assert.Nil(t, err)

patches.Reset()

config = &consul.Config{}

reg = &Consul{
logger: log.NewLogger(&log.RegistryLoggerOptions{
Name: "test",
}),
done: make(chan struct{}),
}

err = reg.Start(config)
assert.Error(t, err)

close(reg.done)
}

func TestReload(t *testing.T) {
Expand All @@ -83,3 +101,105 @@ func TestReload(t *testing.T) {
err := reg.Reload(config)
assert.NoError(t, err)
}

func TestRefresh(t *testing.T) {
reg := &Consul{
logger: log.NewLogger(&log.RegistryLoggerOptions{
Name: "test",
}),
softDeletedServices: map[consulService]bool{},
done: make(chan struct{}),
watchingServices: map[consulService]bool{},
}

config := &consul.Config{
ServerUrl: "http://127.0.0.1:8500",
}
client, _ := reg.NewClient(config)
reg.client = client
services := map[string][]string{
"service1": {"dc1", "dc2"},
"service2": {"dc1"},
}

reg.refresh(services)

assert.Len(t, reg.watchingServices, 3)
assert.Contains(t, reg.watchingServices, consulService{ServiceName: "service1", Tag: "dc1"})
assert.Contains(t, reg.watchingServices, consulService{ServiceName: "service1", Tag: "dc2"})
assert.Contains(t, reg.watchingServices, consulService{ServiceName: "service2", Tag: "dc1"})
assert.Empty(t, reg.softDeletedServices)

reg = &Consul{
logger: log.NewLogger(&log.RegistryLoggerOptions{
Name: "test",
}),
softDeletedServices: map[consulService]bool{},
watchingServices: map[consulService]bool{
{ServiceName: "service1", Tag: "dc1"}: true,
},
}

services = map[string][]string{}

reg.refresh(services)

assert.Len(t, reg.watchingServices, 0)
assert.Len(t, reg.softDeletedServices, 1)

}

func TestFetchAllServices(t *testing.T) {
t.Run("Test fetchAllServices method", func(t *testing.T) {
reg := &Consul{
logger: log.NewLogger(&log.RegistryLoggerOptions{
Name: "test",
}),
}
client := &Client{
consulCatalog: &api.Catalog{},
DataCenter: "dc1",
NameSpace: "ns1",
Token: "token",
}

patches := gomonkey.ApplyMethod(reflect.TypeOf(client.consulCatalog), "Services", func(_ *api.Catalog, q *api.QueryOptions) (map[string][]string, *api.QueryMeta, error) {
return map[string][]string{
"service1": {"tag1", "tag2"},
"service2": {"tag3"},
}, nil, nil
})
defer patches.Reset()

services, err := reg.fetchAllServices(client)
assert.NoError(t, err)
assert.NotNil(t, services)
assert.True(t, services[consulService{ServiceName: "service1", Tag: "tag1"}])
assert.True(t, services[consulService{ServiceName: "service1", Tag: "tag2"}])
assert.True(t, services[consulService{ServiceName: "service2", Tag: "tag3"}])
})

t.Run("Test fetchAllServices method with error", func(t *testing.T) {
reg := &Consul{
logger: log.NewLogger(&log.RegistryLoggerOptions{
Name: "test",
}),
}
client := &Client{
consulCatalog: &api.Catalog{},
DataCenter: "dc1",
NameSpace: "ns1",
Token: "token",
}

patches := gomonkey.ApplyMethod(reflect.TypeOf(client.consulCatalog), "Services", func(_ *api.Catalog, q *api.QueryOptions) (map[string][]string, *api.QueryMeta, error) {
return nil, nil, errors.New("mock error")
})
defer patches.Reset()

services, err := reg.fetchAllServices(client)
assert.Error(t, err)
assert.Equal(t, "mock error", err.Error())
assert.Nil(t, services)
})
}
Loading
Loading