forked from polarismesh/polaris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
335 lines (300 loc) · 12.7 KB
/
client.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**
* Tencent is pleased to support the open source community by making Polaris available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 config
import (
"context"
"encoding/base64"
"time"
apiconfig "github.com/polarismesh/specification/source/go/api/v1/config_manage"
apimodel "github.com/polarismesh/specification/source/go/api/v1/model"
"go.uber.org/zap"
"google.golang.org/protobuf/types/known/wrapperspb"
api "github.com/polarismesh/polaris/common/api/v1"
"github.com/polarismesh/polaris/common/model"
"github.com/polarismesh/polaris/common/rsa"
commontime "github.com/polarismesh/polaris/common/time"
"github.com/polarismesh/polaris/common/utils"
)
type (
CompareFunction func(clientInfo *apiconfig.ClientConfigFileInfo, file *model.ConfigFileRelease) bool
)
// GetConfigFileWithCache 从缓存中获取配置文件,如果客户端的版本号大于服务端,则服务端重新加载缓存
func (s *Server) GetConfigFileWithCache(ctx context.Context,
req *apiconfig.ClientConfigFileInfo) *apiconfig.ConfigClientResponse {
namespace := req.GetNamespace().GetValue()
group := req.GetGroup().GetValue()
fileName := req.GetFileName().GetValue()
req = formatClientRequest(ctx, req)
// 从缓存中获取灰度文件
var release *model.ConfigFileRelease
var match = false
if len(req.GetTags()) > 0 {
if release = s.fileCache.GetActiveGrayRelease(namespace, group, fileName); release != nil {
key := model.GetGrayConfigRealseKey(release.SimpleConfigFileRelease)
match = s.grayCache.HitGrayRule(key, model.ToTagMap(req.GetTags()))
}
}
if !match {
if release = s.fileCache.GetActiveRelease(namespace, group, fileName); release == nil {
return api.NewConfigClientResponse(apimodel.Code_NotFoundResource, req)
}
}
// 客户端版本号大于服务端版本号,服务端不返回变更
if req.GetVersion().GetValue() > release.Version {
log.Debug("[Config][Service] get config file to client", utils.RequestID(ctx),
zap.Uint64("client-version", req.GetVersion().GetValue()), zap.Uint64("server-version", release.Version))
return api.NewConfigClientResponse(apimodel.Code_DataNoChange, req)
}
configFile, err := toClientInfo(req, release)
if err != nil {
log.Error("[Config][Service] get config file to client", utils.RequestID(ctx), zap.Error(err))
return api.NewConfigClientResponseWithInfo(apimodel.Code_ExecuteException, err.Error())
}
return api.NewConfigClientResponse(apimodel.Code_ExecuteSuccess, configFile)
}
func formatClientRequest(ctx context.Context, client *apiconfig.ClientConfigFileInfo) *apiconfig.ClientConfigFileInfo {
if len(client.Tags) > 0 {
return client
}
client.Tags = []*apiconfig.ConfigFileTag{
{
Key: wrapperspb.String(model.ClientLabel_IP),
Value: wrapperspb.String(utils.ParseClientIP(ctx)),
},
}
return client
}
// LongPullWatchFile .
func (s *Server) LongPullWatchFile(ctx context.Context,
req *apiconfig.ClientWatchConfigFileRequest) (WatchCallback, error) {
watchFiles := req.GetWatchFiles()
tmpWatchCtx := BuildTimeoutWatchCtx(ctx, req, 0)("", s.watchCenter.MatchBetaReleaseFile)
for _, file := range watchFiles {
tmpWatchCtx.AppendInterest(file)
}
if quickResp := s.watchCenter.CheckQuickResponseClient(tmpWatchCtx); quickResp != nil {
_ = tmpWatchCtx.Close()
return func() *apiconfig.ConfigClientResponse {
return quickResp
}, nil
}
watchTimeOut := defaultLongPollingTimeout
if timeoutVal, ok := ctx.Value(utils.WatchTimeoutCtx{}).(time.Duration); ok {
watchTimeOut = timeoutVal
}
// 3. 监听配置变更,hold 请求 30s,30s 内如果有配置发布,则响应请求
clientId := utils.ParseClientAddress(ctx) + "@" + utils.NewUUID()[0:8]
watchCtx := s.WatchCenter().AddWatcher(clientId, watchFiles, BuildTimeoutWatchCtx(ctx, req, watchTimeOut))
return func() *apiconfig.ConfigClientResponse {
return (watchCtx.(*LongPollWatchContext)).GetNotifieResult()
}, nil
}
func BuildTimeoutWatchCtx(ctx context.Context, req *apiconfig.ClientWatchConfigFileRequest,
watchTimeOut time.Duration) WatchContextFactory {
labels := map[string]string{
model.ClientLabel_IP: utils.ParseClientIP(ctx),
}
if len(req.GetClientIp().GetValue()) != 0 {
labels[model.ClientLabel_IP] = req.GetClientIp().GetValue()
}
return func(clientId string, matcher BetaReleaseMatcher) WatchContext {
watchCtx := &LongPollWatchContext{
clientId: clientId,
labels: labels,
finishTime: time.Now().Add(watchTimeOut),
finishChan: make(chan *apiconfig.ConfigClientResponse, 1),
watchConfigFiles: map[string]*apiconfig.ClientConfigFileInfo{},
betaMatcher: matcher,
}
return watchCtx
}
}
// GetConfigFileNamesWithCache
func (s *Server) GetConfigFileNamesWithCache(ctx context.Context,
req *apiconfig.ConfigFileGroupRequest) *apiconfig.ConfigClientListResponse {
namespace := req.GetConfigFileGroup().GetNamespace().GetValue()
group := req.GetConfigFileGroup().GetName().GetValue()
releases, revision := s.fileCache.GetGroupActiveReleases(namespace, group)
if revision == "" {
return api.NewConfigClientListResponse(apimodel.Code_ExecuteSuccess)
}
if revision == req.GetRevision().GetValue() {
return api.NewConfigClientListResponse(apimodel.Code_DataNoChange)
}
ret := make([]*apiconfig.ClientConfigFileInfo, 0, len(releases))
for i := range releases {
ret = append(ret, &apiconfig.ClientConfigFileInfo{
Namespace: utils.NewStringValue(releases[i].Namespace),
Group: utils.NewStringValue(releases[i].Group),
FileName: utils.NewStringValue(releases[i].FileName),
Name: utils.NewStringValue(releases[i].Name),
Version: utils.NewUInt64Value(releases[i].Version),
ReleaseTime: utils.NewStringValue(commontime.Time2String(releases[i].ModifyTime)),
Tags: model.FromTagMap(releases[i].Metadata),
})
}
return &apiconfig.ConfigClientListResponse{
Code: utils.NewUInt32Value(uint32(apimodel.Code_ExecuteSuccess)),
Info: utils.NewStringValue(api.Code2Info(uint32(apimodel.Code_ExecuteSuccess))),
Revision: utils.NewStringValue(revision),
Namespace: namespace,
Group: group,
ConfigFileInfos: ret,
}
}
func (s *Server) GetConfigGroupsWithCache(ctx context.Context, req *apiconfig.ClientConfigFileInfo) *apiconfig.ConfigDiscoverResponse {
namespace := req.GetNamespace().GetValue()
out := api.NewConfigDiscoverResponse(apimodel.Code_ExecuteSuccess)
groups, revision := s.groupCache.ListGroups(namespace)
if revision == "" {
out = api.NewConfigDiscoverResponse(apimodel.Code_ExecuteSuccess)
out.Type = apiconfig.ConfigDiscoverResponse_CONFIG_FILE_GROUPS
return out
}
if revision == req.GetMd5().GetValue() {
out = api.NewConfigDiscoverResponse(apimodel.Code_DataNoChange)
out.Type = apiconfig.ConfigDiscoverResponse_CONFIG_FILE_GROUPS
return out
}
ret := make([]*apiconfig.ConfigFileGroup, 0, len(groups))
for i := range groups {
item := groups[i]
ret = append(ret, &apiconfig.ConfigFileGroup{
Namespace: wrapperspb.String(item.Namespace),
Name: wrapperspb.String(item.Name),
})
}
out.Type = apiconfig.ConfigDiscoverResponse_CONFIG_FILE_GROUPS
out.ConfigFile = &apiconfig.ClientConfigFileInfo{Namespace: wrapperspb.String(namespace)}
out.Revision = revision
out.ConfigFileGroups = ret
return out
}
func CompareByVersion(clientInfo *apiconfig.ClientConfigFileInfo, file *model.ConfigFileRelease) bool {
return clientInfo.GetVersion().GetValue() < file.Version
}
// only for unit test
func (s *Server) checkClientConfigFile(ctx context.Context, files []*apiconfig.ClientConfigFileInfo,
compartor CompareFunction) (*apiconfig.ConfigClientResponse, bool) {
if len(files) == 0 {
return api.NewConfigClientResponse(apimodel.Code_InvalidWatchConfigFileFormat, nil), false
}
for _, configFile := range files {
namespace := configFile.GetNamespace().GetValue()
group := configFile.GetGroup().GetValue()
fileName := configFile.GetFileName().GetValue()
if namespace == "" || group == "" || fileName == "" {
return api.NewConfigClientResponseWithInfo(apimodel.Code_BadRequest,
"namespace & group & fileName can not be empty"), false
}
// 从缓存中获取最新的配置文件信息
release := s.fileCache.GetActiveRelease(namespace, group, fileName)
if release != nil && compartor(configFile, release) {
ret := &apiconfig.ClientConfigFileInfo{
Namespace: utils.NewStringValue(namespace),
Group: utils.NewStringValue(group),
FileName: utils.NewStringValue(fileName),
Version: utils.NewUInt64Value(release.Version),
Md5: utils.NewStringValue(release.Md5),
}
return api.NewConfigClientResponse(apimodel.Code_ExecuteSuccess, ret), false
}
}
return api.NewConfigClientResponse(apimodel.Code_DataNoChange, nil), true
}
func toClientInfo(client *apiconfig.ClientConfigFileInfo,
release *model.ConfigFileRelease) (*apiconfig.ClientConfigFileInfo, error) {
namespace := client.GetNamespace().GetValue()
group := client.GetGroup().GetValue()
fileName := client.GetFileName().GetValue()
publicKey := client.GetPublicKey().GetValue()
copyMetadata := func() map[string]string {
ret := map[string]string{}
for k, v := range release.Metadata {
ret[k] = v
}
delete(ret, model.MetaKeyConfigFileDataKey)
return ret
}()
configFile := &apiconfig.ClientConfigFileInfo{
Namespace: utils.NewStringValue(namespace),
Group: utils.NewStringValue(group),
FileName: utils.NewStringValue(fileName),
Content: utils.NewStringValue(release.Content),
Version: utils.NewUInt64Value(release.Version),
Md5: utils.NewStringValue(release.Md5),
Encrypted: utils.NewBoolValue(release.IsEncrypted()),
Tags: model.FromTagMap(copyMetadata),
}
dataKey := release.GetEncryptDataKey()
encryptAlgo := release.GetEncryptAlgo()
if dataKey != "" && encryptAlgo != "" {
dataKeyBytes, err := base64.StdEncoding.DecodeString(dataKey)
if err != nil {
log.Error("[Config][Service] decode data key error.", zap.String("dataKey", dataKey), zap.Error(err))
return nil, err
}
if publicKey != "" {
cipherDataKey, err := rsa.EncryptToBase64(dataKeyBytes, publicKey)
if err != nil {
log.Error("[Config][Service] rsa encrypt data key error.",
zap.String("dataKey", dataKey), zap.Error(err))
} else {
dataKey = cipherDataKey
}
}
configFile.Tags = append(configFile.Tags,
&apiconfig.ConfigFileTag{
Key: utils.NewStringValue(model.MetaKeyConfigFileDataKey),
Value: utils.NewStringValue(dataKey),
},
)
}
return configFile, nil
}
// UpsertAndReleaseConfigFile 创建/更新配置文件并发布
func (s *Server) UpsertAndReleaseConfigFileFromClient(ctx context.Context,
req *apiconfig.ConfigFilePublishInfo) *apiconfig.ConfigResponse {
return s.UpsertAndReleaseConfigFile(ctx, req)
}
// DeleteConfigFileFromClient 调用config_file的方法更新配置文件
func (s *Server) DeleteConfigFileFromClient(ctx context.Context, req *apiconfig.ConfigFile) *apiconfig.ConfigResponse {
return s.DeleteConfigFile(ctx, req)
}
// CreateConfigFileFromClient 调用config_file接口获取配置文件
func (s *Server) CreateConfigFileFromClient(ctx context.Context,
client *apiconfig.ConfigFile) *apiconfig.ConfigClientResponse {
configResponse := s.CreateConfigFile(ctx, client)
return api.NewConfigClientResponseFromConfigResponse(configResponse)
}
// UpdateConfigFileFromClient 调用config_file接口更新配置文件
func (s *Server) UpdateConfigFileFromClient(ctx context.Context,
client *apiconfig.ConfigFile) *apiconfig.ConfigClientResponse {
configResponse := s.UpdateConfigFile(ctx, client)
return api.NewConfigClientResponseFromConfigResponse(configResponse)
}
// PublishConfigFileFromClient 调用config_file_release接口发布配置文件
func (s *Server) PublishConfigFileFromClient(ctx context.Context,
client *apiconfig.ConfigFileRelease) *apiconfig.ConfigClientResponse {
configResponse := s.PublishConfigFile(ctx, client)
return api.NewConfigClientResponseFromConfigResponse(configResponse)
}
// CasUpsertAndReleaseConfigFileFromClient 创建/更新配置文件并发布
func (s *Server) CasUpsertAndReleaseConfigFileFromClient(ctx context.Context,
req *apiconfig.ConfigFilePublishInfo) *apiconfig.ConfigResponse {
return s.CasUpsertAndReleaseConfigFile(ctx, req)
}