-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdriver.go
193 lines (172 loc) · 4.43 KB
/
driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package driver
import (
"encoding/base64"
"encoding/json"
"fmt"
"net"
"net/url"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/dtm-labs/dtmdriver"
"github.com/polarismesh/polaris-go/api"
"github.com/polarismesh/polaris-go/pkg/model"
_ "github.com/polarismesh/grpc-go-polaris"
)
const (
Name = "dtm-driver-polaris"
)
var (
provider api.ProviderAPI
consumer api.ConsumerAPI
PolarisTtl = 5 * time.Second // 心跳周期
)
type (
polarisDriver struct{}
dialOptions struct {
Namespace string `json:"Namespace"`
}
)
func (p *polarisDriver) GetName() string {
return Name
}
// RegisterGrpcResolver grpc-go-polaris的init已完成注册
func (p *polarisDriver) RegisterAddrResolver() {}
func firstIp() net.IP {
ias, _ := net.InterfaceAddrs()
for _, address := range ias {
if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
return ipNet.IP
}
}
return nil
}
// RegisterGrpcService 向北极星注册dtm server服务
// target polaris://ip:port/service?namespace=[Test,Pre-release,Production]
func (p *polarisDriver) RegisterService(target, token string) error {
var err error
// 主要考虑是dtmsvr的初始化,如果使用其他driver,polaris的consumer和provider不都应该初始化
if provider == nil {
config := GetPolarisConfiguration(GetPolarisConf())
provider, err = api.NewProviderAPIByConfig(config)
if err != nil {
return err
}
}
//// token为空不注册,用于托管服务的场景
//if token == "" {
// return nil
//}
u, err := url.Parse(target)
if err != nil {
return err
}
// namespace
ns := u.Query().Get("namespace")
if ns == "" {
return fmt.Errorf("namespace not found %s", target)
}
// service
if len(u.Path) <= 1 {
return fmt.Errorf("service not found %s", target)
}
service := u.Path[1:]
ip := net.ParseIP(u.Hostname())
if ip == nil || ip.IsUnspecified() {
ip = firstIp()
}
if ip == nil {
return fmt.Errorf("ip not found %s", target)
}
port, err := strconv.Atoi(u.Port())
if err != nil {
return fmt.Errorf("parse port failed %s, target :%s", err.Error(), target)
}
request := &api.InstanceRegisterRequest{}
{
request.Namespace = ns
request.Service = service
request.ServiceToken = token
request.Host = ip.String()
request.Port = port
request.SetTTL(int(PolarisTtl))
}
rsp, err := provider.Register(request)
if rsp == nil || err != nil {
return fmt.Errorf("register instance failed, err: %w", err)
}
hbReq := &api.InstanceHeartbeatRequest{
InstanceHeartbeatRequest: model.InstanceHeartbeatRequest{
Namespace: ns,
Service: service,
Host: ip.String(),
Port: port,
ServiceToken: token,
InstanceID: rsp.InstanceID,
},
}
// 心跳上报&关闭的反注册
go func() {
if err = provider.Heartbeat(hbReq); nil != err {
fmt.Println("polaris heartbeat error", err)
}
quit := make(chan os.Signal)
signal.Notify(
quit,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGQUIT,
syscall.SIGTERM,
)
ticker := time.NewTicker(PolarisTtl)
for {
select {
case <-ticker.C:
if err = provider.Heartbeat(hbReq); nil != err {
fmt.Println("polaris heartbeat error", err)
}
case <-quit:
provider.Deregister(&api.InstanceDeRegisterRequest{
InstanceDeRegisterRequest: model.InstanceDeRegisterRequest{
Namespace: ns,
Service: service,
Host: ip.String(),
Port: port,
ServiceToken: token,
InstanceID: rsp.InstanceID,
},
})
ticker.Stop()
provider.Destroy()
}
}
}()
return nil
}
// ParseServerMethod 面向github.com/polarismesh/grpc-go-polaris解析
// uri polaris://service/package.service/method?namespace=Test
func (p *polarisDriver) ParseServerMethod(uri string) (server string, method string, err error) {
if !strings.Contains(uri, "//") { // 处理无scheme的情况,如果您没有直连,可以不处理
sep := strings.IndexByte(uri, '/')
if sep == -1 {
return "", "", fmt.Errorf("bad url: '%s'. no '/' found", uri)
}
return uri[:sep], uri[sep:], nil
}
u, err := url.Parse(uri)
if err != nil {
return "", "", fmt.Errorf("parse url failed, err: %w", err)
}
opts := &dialOptions{}
opts.Namespace = u.Query().Get("namespace")
jsonStr, _ := json.Marshal(opts)
server = u.Scheme + "://" + u.Host + "/?options=" + base64.URLEncoding.EncodeToString(jsonStr)
method = u.Path
return
}
func init() {
dtmdriver.Register(&polarisDriver{})
}