This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
resolver.go
187 lines (166 loc) · 5.42 KB
/
resolver.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
/*
* 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 polaris
import (
"context"
"fmt"
"strings"
"github.com/cloudwego/kitex/pkg/discovery"
"github.com/cloudwego/kitex/pkg/rpcinfo"
"github.com/polarismesh/polaris-go/api"
"github.com/polarismesh/polaris-go/pkg/log"
"github.com/polarismesh/polaris-go/pkg/model"
)
const (
defaultWeight = 10
polarisDefaultNamespace = "default"
)
// Resolver is extension interface of Kitex discovery.Resolver.
type Resolver interface {
discovery.Resolver
Watcher(ctx context.Context, desc string) (discovery.Change, error)
}
// polarisResolver is a resolver using polaris.
type polarisResolver struct {
provider api.ProviderAPI
consumer api.ConsumerAPI
}
// NewPolarisResolver creates a polaris based resolver.
func NewPolarisResolver(configFile ...string) (Resolver, error) {
sdkCtx, err := GetPolarisConfig(configFile...)
if err != nil {
return nil, err
}
newInstance := &polarisResolver{
consumer: api.NewConsumerAPIByContext(sdkCtx),
provider: api.NewProviderAPIByContext(sdkCtx),
}
return newInstance, nil
}
// Target implements the Resolver interface.
func (polaris *polarisResolver) Target(ctx context.Context, target rpcinfo.EndpointInfo) (description string) {
// serviceName identification is generated by namespace and serviceName to identify serviceName
var serviceIdentification strings.Builder
namespace, ok := target.Tag("namespace")
if ok {
serviceIdentification.WriteString(namespace)
} else {
serviceIdentification.WriteString(polarisDefaultNamespace)
}
serviceIdentification.WriteString(":")
serviceIdentification.WriteString(target.ServiceName())
return serviceIdentification.String()
}
// Watcher return registered service changes.
func (polaris *polarisResolver) Watcher(ctx context.Context, desc string) (discovery.Change, error) {
var (
eps []discovery.Instance
add []discovery.Instance
update []discovery.Instance
remove []discovery.Instance
)
namespace, serviceName := SplitDescription(desc)
key := model.ServiceKey{
Namespace: namespace,
Service: serviceName,
}
watchReq := api.WatchServiceRequest{}
watchReq.Key = key
watchRsp, err := polaris.consumer.WatchService(&watchReq)
if nil != err {
log.GetBaseLogger().Fatalf("fail to WatchService, err is %v", err)
}
instances := watchRsp.GetAllInstancesResp.Instances
if nil != instances {
for _, instance := range instances {
log.GetBaseLogger().Infof("instance getOneInstance is %s:%d", instance.GetHost(), instance.GetPort())
eps = append(eps, ChangePolarisInstanceToKitex(instance))
}
}
result := discovery.Result{
Cacheable: true,
CacheKey: desc,
Instances: eps,
}
Change := discovery.Change{}
select {
case <-ctx.Done():
log.GetBaseLogger().Infof("[Polaris resolver] Watch has been finished")
return Change, nil
case event := <-watchRsp.EventChannel:
eType := event.GetSubScribeEventType()
if eType == api.EventInstance {
insEvent := event.(*model.InstanceEvent)
if insEvent.AddEvent != nil {
for _, instance := range insEvent.AddEvent.Instances {
add = append(add, ChangePolarisInstanceToKitex(instance))
}
}
if insEvent.UpdateEvent != nil {
for i := range insEvent.UpdateEvent.UpdateList {
update = append(update, ChangePolarisInstanceToKitex(insEvent.UpdateEvent.UpdateList[i].After))
}
}
if insEvent.DeleteEvent != nil {
for _, instance := range insEvent.DeleteEvent.Instances {
remove = append(remove, ChangePolarisInstanceToKitex(instance))
}
}
Change = discovery.Change{
Result: result,
Added: add,
Updated: update,
Removed: remove,
}
}
return Change, nil
}
}
// Resolve implements the Resolver interface.
func (polaris *polarisResolver) Resolve(ctx context.Context, desc string) (discovery.Result, error) {
var eps []discovery.Instance
namespace, serviceName := SplitDescription(desc)
getInstances := &api.GetInstancesRequest{}
getInstances.Namespace = namespace
getInstances.Service = serviceName
InstanceResp, err := polaris.consumer.GetInstances(getInstances)
if nil != err {
log.GetBaseLogger().Fatalf("fail to getOneInstance, err is %v", err)
}
instances := InstanceResp.GetInstances()
if nil != instances {
for _, instance := range instances {
log.GetBaseLogger().Infof("instance getOneInstance is %s:%d", instance.GetHost(), instance.GetPort())
eps = append(eps, ChangePolarisInstanceToKitex(instance))
}
}
if len(eps) == 0 {
return discovery.Result{}, fmt.Errorf("no instance remains for %s", desc)
}
return discovery.Result{
Cacheable: true,
CacheKey: desc,
Instances: eps,
}, nil
}
// Diff implements the Resolver interface.
func (polaris *polarisResolver) Diff(cacheKey string, prev, next discovery.Result) (discovery.Change, bool) {
return discovery.DefaultDiff(cacheKey, prev, next)
}
// Name implements the Resolver interface.
func (polaris *polarisResolver) Name() string {
return "Polaris"
}