-
Notifications
You must be signed in to change notification settings - Fork 787
/
client.go
376 lines (321 loc) · 12.3 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// The MIT License (MIT)
// Copyright (c) 2017-2020 Uber Technologies Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package elasticsearch
import (
"context"
"encoding/json"
"fmt"
"io"
"math"
"strconv"
"time"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/elasticsearch/bulk"
"github.com/uber/cadence/common/elasticsearch/client"
"github.com/uber/cadence/common/elasticsearch/query"
"github.com/uber/cadence/common/log"
"github.com/uber/cadence/common/log/tag"
p "github.com/uber/cadence/common/persistence"
"github.com/uber/cadence/common/types"
"github.com/uber/cadence/common/types/mapper/thrift"
)
var _ GenericClient = (*ESClient)(nil)
type ESClient struct {
Client client.Client
Logger log.Logger
}
func (c *ESClient) RunBulkProcessor(ctx context.Context, p *bulk.BulkProcessorParameters) (bulk.GenericBulkProcessor, error) {
return c.Client.RunBulkProcessor(ctx, p)
}
func (c *ESClient) CreateIndex(ctx context.Context, index string) error {
return c.Client.CreateIndex(ctx, index)
}
func (c *ESClient) IsNotFoundError(err error) bool {
return c.Client.IsNotFoundError(err)
}
func (c *ESClient) Search(ctx context.Context, request *SearchRequest) (*SearchResponse, error) {
token, err := GetNextPageToken(request.ListRequest.NextPageToken)
if err != nil {
return nil, err
}
searchResult, err := c.getSearchResult(
ctx,
request.Index,
request.ListRequest,
request.MatchQuery,
request.IsOpen,
token,
)
if err != nil {
return nil, err
}
return c.getListWorkflowExecutionsResponse(searchResult, token, request.ListRequest.PageSize, request.MaxResultWindow, request.Filter)
}
func (c *ESClient) SearchByQuery(ctx context.Context, request *SearchByQueryRequest) (*SearchResponse, error) {
token, err := GetNextPageToken(request.NextPageToken)
if err != nil {
return nil, err
}
searchResult, err := c.Client.Search(ctx, request.Index, request.Query)
if err != nil {
return nil, err
}
return c.getListWorkflowExecutionsResponse(searchResult, token, request.PageSize, request.MaxResultWindow, request.Filter)
}
func (c *ESClient) SearchRaw(ctx context.Context, index, query string) (*RawResponse, error) {
response, err := c.Client.Search(ctx, index, query)
if err != nil {
return nil, err
}
result := RawResponse{
TookInMillis: response.TookInMillis,
Hits: SearchHits{
TotalHits: response.TotalHits,
Hits: c.esHitsToExecutions(response.Hits, nil /* no filter */),
},
Aggregations: response.Aggregations,
}
return &result, nil
}
func (c *ESClient) esHitsToExecutions(eshits *client.SearchHits, filter IsRecordValidFilter) []*p.InternalVisibilityWorkflowExecutionInfo {
var hits = make([]*p.InternalVisibilityWorkflowExecutionInfo, 0)
if eshits != nil && len(eshits.Hits) > 0 {
for _, hit := range eshits.Hits {
workflowExecutionInfo := c.convertSearchResultToVisibilityRecord(hit)
if filter == nil || filter(workflowExecutionInfo) {
hits = append(hits, workflowExecutionInfo)
}
}
}
return hits
}
func (c *ESClient) ScanByQuery(ctx context.Context, request *ScanByQueryRequest) (*SearchResponse, error) {
var err error
token, err := GetNextPageToken(request.NextPageToken)
if err != nil {
return nil, err
}
searchResult, err := c.Client.Scroll(ctx, request.Index, request.Query, token.ScrollID)
isLastPage := false
if err == io.EOF { // no more result
isLastPage = true
if err := c.Client.ClearScroll(ctx, searchResult.ScrollID); err != nil {
c.Logger.Warn("scroll clear failed", tag.Error(err))
}
} else if err != nil {
return nil, &types.InternalServiceError{
Message: fmt.Sprintf("ScanByQuery failed. Error: %v", err),
}
}
response := &p.InternalListWorkflowExecutionsResponse{}
if searchResult == nil {
return response, nil
}
response.Executions = c.esHitsToExecutions(searchResult.Hits, nil /* no filter */)
if len(searchResult.Hits.Hits) == request.PageSize && !isLastPage {
nextPageToken, err := SerializePageToken(&ElasticVisibilityPageToken{ScrollID: searchResult.ScrollID})
if err != nil {
return nil, err
}
response.NextPageToken = make([]byte, len(nextPageToken))
copy(response.NextPageToken, nextPageToken)
}
return response, nil
}
func (c *ESClient) SearchForOneClosedExecution(ctx context.Context, index string, request *SearchForOneClosedExecutionRequest) (*SearchForOneClosedExecutionResponse, error) {
matchDomainQuery := query.NewMatchQuery(DomainID, request.DomainUUID)
existClosedStatusQuery := query.NewExistsQuery(CloseStatus)
matchWorkflowIDQuery := query.NewMatchQuery(WorkflowID, request.Execution.GetWorkflowID())
boolQuery := query.NewBoolQuery().Must(matchDomainQuery).Must(existClosedStatusQuery).Must(matchWorkflowIDQuery)
rid := request.Execution.GetRunID()
if rid != "" {
matchRunIDQuery := query.NewMatchQuery(RunID, rid)
boolQuery = boolQuery.Must(matchRunIDQuery)
}
qb := query.NewBuilder()
body, err := qb.Query(boolQuery).String()
if err != nil {
return nil, fmt.Errorf("getting body from query builder: %w", err)
}
searchResult, err := c.Client.Search(ctx, index, body)
if err != nil {
return nil, &types.InternalServiceError{
Message: fmt.Sprintf("SearchForOneClosedExecution failed. Error: %v", err),
}
}
response := &p.InternalGetClosedWorkflowExecutionResponse{}
actualHits := searchResult.Hits.Hits
if len(actualHits) == 0 {
return response, nil
}
response.Execution = c.convertSearchResultToVisibilityRecord(actualHits[0])
return response, nil
}
func (c *ESClient) CountByQuery(ctx context.Context, index, query string) (int64, error) {
return c.Client.Count(ctx, index, query)
}
func (c *ESClient) PutMapping(ctx context.Context, index, root, key, valueType string) error {
mapping := buildPutMappingBody(root, key, valueType)
body, err := json.Marshal(mapping)
if err != nil {
return err
}
return c.Client.PutMapping(ctx, index, string(body))
}
func (c *ESClient) getListWorkflowExecutionsResponse(
searchHits *client.Response,
token *ElasticVisibilityPageToken,
pageSize int,
maxResultWindow int,
isRecordValid func(rec *p.InternalVisibilityWorkflowExecutionInfo) bool,
) (*p.InternalListWorkflowExecutionsResponse, error) {
response := &p.InternalListWorkflowExecutionsResponse{}
numOfActualHits := len(searchHits.Hits.Hits)
response.Executions = make([]*p.InternalVisibilityWorkflowExecutionInfo, 0)
for i := 0; i < numOfActualHits; i++ {
workflowExecutionInfo := c.convertSearchResultToVisibilityRecord(searchHits.Hits.Hits[i])
if isRecordValid == nil || isRecordValid(workflowExecutionInfo) {
// for old APIs like ListOpenWorkflowExecutions, we added 1 ms to range query to overcome ES limitation
// (see getSearchResult function), but manually dropped records beyond request range here.
response.Executions = append(response.Executions, workflowExecutionInfo)
}
}
if numOfActualHits == pageSize { // this means the response is not the last page
var nextPageToken []byte
var err error
// ES Search API support pagination using From and PageSize, but has limit that From+PageSize cannot exceed a threshold
// to retrieve deeper pages, use ES SearchAfter
if searchHits.TotalHits <= int64(maxResultWindow-pageSize) { // use ES Search From+Size
nextPageToken, err = SerializePageToken(&ElasticVisibilityPageToken{From: token.From + numOfActualHits})
} else { // use ES Search After
var sortVal interface{}
sortVal = searchHits.Sort[0]
tieBreaker := searchHits.Sort[1].(string)
nextPageToken, err = SerializePageToken(&ElasticVisibilityPageToken{SortValue: sortVal, TieBreaker: tieBreaker})
}
if err != nil {
return nil, err
}
response.NextPageToken = make([]byte, len(nextPageToken))
copy(response.NextPageToken, nextPageToken)
}
return response, nil
}
func (c *ESClient) convertSearchResultToVisibilityRecord(hit *client.SearchHit) *p.InternalVisibilityWorkflowExecutionInfo {
var source *VisibilityRecord
err := json.Unmarshal(hit.Source, &source)
if err != nil { // log and skip error
return nil
}
record := &p.InternalVisibilityWorkflowExecutionInfo{
DomainID: source.DomainID,
WorkflowType: source.WorkflowType,
WorkflowID: source.WorkflowID,
RunID: source.RunID,
TypeName: source.WorkflowType,
StartTime: time.Unix(0, source.StartTime),
ExecutionTime: time.Unix(0, source.ExecutionTime),
Memo: p.NewDataBlob(source.Memo, common.EncodingType(source.Encoding)),
TaskList: source.TaskList,
IsCron: source.IsCron,
NumClusters: source.NumClusters,
SearchAttributes: source.Attr,
}
if source.UpdateTime != 0 {
record.UpdateTime = time.Unix(0, source.UpdateTime)
}
if source.CloseTime != 0 {
record.CloseTime = time.Unix(0, source.CloseTime)
record.Status = thrift.ToWorkflowExecutionCloseStatus(&source.CloseStatus)
record.HistoryLength = source.HistoryLength
}
return record
}
func (c *ESClient) getSearchResult(
ctx context.Context,
index string,
request *p.InternalListWorkflowExecutionsRequest,
matchQuery *query.MatchQuery,
isOpen bool,
token *ElasticVisibilityPageToken,
) (*client.Response, error) {
// always match domain id
boolQuery := query.NewBoolQuery().Must(query.NewMatchQuery(DomainID, request.DomainUUID))
if matchQuery != nil {
boolQuery = boolQuery.Must(matchQuery)
}
// ElasticSearch v6 is unable to precisely compare time, have to manually add resolution 1ms to time range.
// Also has to use string instead of int64 to avoid data conversion issue,
// 9223372036854775807 to 9223372036854776000 (long overflow)
if request.LatestTime.UnixNano() > math.MaxInt64-oneMicroSecondInNano { // prevent latestTime overflow
request.LatestTime = time.Unix(0, math.MaxInt64-oneMicroSecondInNano)
}
if request.EarliestTime.UnixNano() < math.MinInt64+oneMicroSecondInNano { // prevent earliestTime overflow
request.EarliestTime = time.Unix(0, math.MinInt64+oneMicroSecondInNano)
}
var rangeQueryField string
existClosedStatusQuery := query.NewExistsQuery(CloseStatus)
if isOpen {
rangeQueryField = StartTime
boolQuery = boolQuery.MustNot(existClosedStatusQuery)
} else {
boolQuery = boolQuery.Must(existClosedStatusQuery)
rangeQueryField = CloseTime
}
earliestTimeStr := strconv.FormatInt(request.EarliestTime.UnixNano()-oneMicroSecondInNano, 10)
latestTimeStr := strconv.FormatInt(request.LatestTime.UnixNano()+oneMicroSecondInNano, 10)
rangeQuery := query.NewRangeQuery(rangeQueryField).Gte(earliestTimeStr).Lte(latestTimeStr)
boolQuery = boolQuery.Filter(rangeQuery)
qb := query.NewBuilder()
qb.Query(boolQuery).From(token.From).Size(request.PageSize)
qb.Sortby(
query.NewFieldSort(rangeQueryField).Desc(),
query.NewFieldSort(RunID).Desc(),
)
if ShouldSearchAfter(token) {
qb.SearchAfter(token.SortValue, token.TieBreaker)
}
body, err := qb.String()
if err != nil {
return nil, fmt.Errorf("getting body from query builder: %w", err)
}
return c.Client.Search(ctx, index, body)
}
func buildPutMappingBody(root, key, valueType string) map[string]interface{} {
body := make(map[string]interface{})
if len(root) != 0 {
body["properties"] = map[string]interface{}{
root: map[string]interface{}{
"properties": map[string]interface{}{
key: map[string]interface{}{
"type": valueType,
},
},
},
}
} else {
body["properties"] = map[string]interface{}{
key: map[string]interface{}{
"type": valueType,
},
}
}
return body
}