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

Init registry #2

Merged
merged 27 commits into from
Mar 1, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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 OWNERS
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
approvers:
- YangruiEmma
- hanson
- Hanson
91 changes: 90 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,90 @@
# registry-consul
# registry-consul
GuangmingLuo marked this conversation as resolved.
Show resolved Hide resolved

## Docs

### Server

#### Basic Usage
```
import (
...
"github.com/cloudwego/kitex/pkg/rpcinfo"
"github.com/cloudwego/kitex/server"
consul "github.com/kitex-contrib/registry-consul"
consulapi "github.com/hashicorp/consul/api"
)

func main() {

r, err := consul.NewConsulRegister("127.0.0.1:8500")
if err != nil {
log.Fatal(err)
}

server := hello.NewServer(new(HelloImpl), server.WithRegistry(r), server.WithServerBasicInfo(&rpcinfo.EndpointBasicInfo{
ServiceName: "Hello",
GuangmingLuo marked this conversation as resolved.
Show resolved Hide resolved
}))
err = server.Run()
if err != nil {
log.Fatal(err)
}
}
```

#### Customize Service Check
registry has a default config for service check like
```
check.Timeout = "5s"
check.Interval = "5s"
check.DeregisterCriticalServiceAfter = "30s"
```

you can also use `CustomizeCheck` to modify your config
```
func main() {
...
r.CustomizeCheck(&consulapi.AgentServiceCheck{
Timeout: "1s",
Interval: "3s",
DeregisterCriticalServiceAfter: "10s",
})
}
```

#### Customize Registration
```
func main() {
...
r.CustomizeRegistration(&consulapi.AgentServiceRegistration{
Tags: []string{"dev"},
})
}
```

### Client

```
import (
...
"github.com/cloudwego/kitex/client"
consul "github.com/kitex-contrib/registry-consul"
...
)

func main() {
...
r, err := consul.NewConsulResolver("127.0.0.1:8500")
if err != nil {
log.Fatal(err)
}
client, err := echo.NewClient("hello", client.WithResolver(r))
GuangmingLuo marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
log.Fatal(err)
}
...
}
```

## Example

See Server and Client.
9 changes: 9 additions & 0 deletions client/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module client

go 1.16

require (
github.com/cloudwego/kitex v0.1.1
github.com/cloudwego/kitex-examples v0.0.0-20211103034154-ddf5b924924e
github.com/hanson/registry-consul v0.0.0-20211216173348-1845c5b668d0
)
322 changes: 322 additions & 0 deletions client/go.sum

Large diffs are not rendered by default.

44 changes: 44 additions & 0 deletions client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2021 CloudWeGo authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"context"
consul "github.com/kitex-contrib/registry-consul"
"log"
"time"

"github.com/cloudwego/kitex-examples/hello/kitex_gen/api"
"github.com/cloudwego/kitex-examples/hello/kitex_gen/api/hello"
"github.com/cloudwego/kitex/client"
)

func main() {
r, err := consul.NewConsulResolver("127.0.0.1:8500")
if err != nil {
log.Fatal(err)
}
client := hello.MustNewClient("Hello", client.WithResolver(r))
for {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
resp, err := client.Echo(ctx, &api.Request{Message: "Hello"})
cancel()
if err != nil {
log.Fatal(err)
}
log.Println(resp)
time.Sleep(time.Second)
}
}
116 changes: 116 additions & 0 deletions consul_registry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright 2021 CloudWeGo authors.
Hanson marked this conversation as resolved.
Show resolved Hide resolved
//
// Licensed under the Apache License, Version 2.0 (the "License");
GuangmingLuo marked this conversation as resolved.
Show resolved Hide resolved
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package consul

import (
"fmt"
"github.com/cloudwego/kitex/pkg/registry"
"github.com/hashicorp/consul/api"
)

type consulRegistry struct {
consulClient *api.Client
registration *api.AgentServiceRegistration
check *api.AgentServiceCheck
}

func NewConsulRegister(address string) (*consulRegistry, error) {
config := api.DefaultConfig()
config.Address = address
client, err := api.NewClient(config)
if err != nil {
return nil, err
}

return &consulRegistry{consulClient: client, check: defaultCheck()}, nil
}

func defaultCheck() *api.AgentServiceCheck {
check := new(api.AgentServiceCheck)
check.Timeout = "5s"
check.Interval = "5s"
check.DeregisterCriticalServiceAfter = "30s"

return check
}

func NewConsulRegisterWithConfig(config *api.Config) (*consulRegistry, error) {
client, err := api.NewClient(config)
if err != nil {
return nil, err
}

return &consulRegistry{consulClient: client}, nil
}

func (c *consulRegistry) CustomizeRegistration(registration *api.AgentServiceRegistration) {
c.registration = registration
}

func (c *consulRegistry) CustomizeCheck(check *api.AgentServiceCheck) {
c.check = check
}

func (c *consulRegistry) Register(info *registry.Info) error {
if err := validateRegistryInfo(info); err != nil {
return err
}

if c.registration == nil {
c.registration = &api.AgentServiceRegistration{
Name: info.ServiceName,
Address: info.Addr.String(),
}
} else {
c.registration.Name = info.ServiceName
c.registration.Address = info.Addr.String()
}

if c.check != nil {
c.check.TCP = info.Addr.String()
Hanson marked this conversation as resolved.
Show resolved Hide resolved
c.registration.Check = c.check
}

c.registration.Meta = info.Tags

if c.registration.Meta == nil {
c.registration.Meta = make(map[string]string)
}

c.registration.Meta["network"] = info.Addr.Network()
if info.Weight <= 0 {
info.Weight = defaultWeight
}
c.registration.Weights = &api.AgentWeights{
Passing: info.Weight,
Warning: 1,
}

if err := c.consulClient.Agent().ServiceRegister(c.registration); err != nil {
Hanson marked this conversation as resolved.
Show resolved Hide resolved
return err
}

return nil
}

func validateRegistryInfo(info *registry.Info) error {
if info.ServiceName == "" {
return fmt.Errorf("missing service name in Register")
Hanson marked this conversation as resolved.
Show resolved Hide resolved
}
if info.Addr == nil {
return fmt.Errorf("missing addr in Register")
Hanson marked this conversation as resolved.
Show resolved Hide resolved
}
return nil
}
84 changes: 84 additions & 0 deletions consul_resolver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright 2021 CloudWeGo authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package consul
Hanson marked this conversation as resolved.
Show resolved Hide resolved

import (
"context"
"github.com/cloudwego/kitex/pkg/discovery"
"github.com/cloudwego/kitex/pkg/registry"
"github.com/cloudwego/kitex/pkg/rpcinfo"
"github.com/hashicorp/consul/api"
"log"
)

const (
defaultWeight = 10
)

type consulResolver struct {
consulClient *api.Client
}

func (c consulResolver) Target(ctx context.Context, target rpcinfo.EndpointInfo) (description string) {
return target.ServiceName()
}

func (c consulResolver) Resolve(ctx context.Context, desc string) (discovery.Result, error) {
var eps []discovery.Instance

services, err := c.consulClient.Agent().Services()
if err != nil {
log.Printf("err:%v", err)
return discovery.Result{}, err
}

for _, service := range services {
weight := service.Weights.Passing
if weight <= 0 {
Hanson marked this conversation as resolved.
Show resolved Hide resolved
weight = defaultWeight
}

eps = append(eps, discovery.NewInstance(service.Meta["network"], service.Address, weight, service.Meta))
}

return discovery.Result{
Cacheable: true,
CacheKey: desc,
Instances: eps,
}, nil
}

func (c consulResolver) Diff(cacheKey string, prev, next discovery.Result) (discovery.Change, bool) {
return discovery.DefaultDiff(cacheKey, prev, next)
}

func (c consulResolver) Name() string {
return "consul"
}

func (c *consulRegistry) Deregister(info *registry.Info) error {
return c.consulClient.Agent().ServiceDeregister(info.ServiceName)
Hanson marked this conversation as resolved.
Show resolved Hide resolved
}

func NewConsulResolver(address string) (discovery.Resolver, error) {
config := api.DefaultConfig()
config.Address = address
client, err := api.NewClient(config)
if err != nil {
return nil, err
}

return &consulResolver{consulClient: client}, nil
}
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module github.com/kitex-contrib/registry-consul

go 1.16

require (
github.com/cloudwego/kitex v0.1.1
github.com/hashicorp/consul/api v1.12.0
GuangmingLuo marked this conversation as resolved.
Show resolved Hide resolved
)
Loading