-
Notifications
You must be signed in to change notification settings - Fork 790
/
historyArchiver.go
438 lines (396 loc) · 14.1 KB
/
historyArchiver.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright (c) 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.
// S3 History Archiver will archive workflow histories to amazon s3
package s3store
import (
"context"
"encoding/binary"
"errors"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/archiver"
"github.com/uber/cadence/common/backoff"
"github.com/uber/cadence/common/config"
"github.com/uber/cadence/common/log/tag"
"github.com/uber/cadence/common/metrics"
"github.com/uber/cadence/common/persistence"
"github.com/uber/cadence/common/types"
)
const (
// URIScheme is the scheme for the s3 implementation
URIScheme = "s3"
errEncodeHistory = "failed to encode history batches"
errWriteKey = "failed to write history to s3"
defaultBlobstoreTimeout = 60 * time.Second
targetHistoryBlobSize = 2 * 1024 * 1024 // 2MB
)
var (
errNoBucketSpecified = errors.New("no bucket specified")
errBucketNotExists = errors.New("requested bucket does not exist")
errEmptyAwsRegion = errors.New("empty aws region")
)
type (
historyArchiver struct {
container *archiver.HistoryBootstrapContainer
s3cli s3iface.S3API
// only set in test code
historyIterator archiver.HistoryIterator
}
getHistoryToken struct {
CloseFailoverVersion int64
BatchIdx int
}
uploadProgress struct {
BatchIdx int
IteratorState []byte
uploadedSize int64
historySize int64
}
)
// NewHistoryArchiver creates a new archiver.HistoryArchiver based on s3
func NewHistoryArchiver(
container *archiver.HistoryBootstrapContainer,
config *config.S3Archiver,
) (archiver.HistoryArchiver, error) {
return newHistoryArchiver(container, config, nil)
}
func newHistoryArchiver(
container *archiver.HistoryBootstrapContainer,
config *config.S3Archiver,
historyIterator archiver.HistoryIterator,
) (*historyArchiver, error) {
if len(config.Region) == 0 {
return nil, errEmptyAwsRegion
}
s3Config := &aws.Config{
Endpoint: config.Endpoint,
Region: aws.String(config.Region),
S3ForcePathStyle: aws.Bool(config.S3ForcePathStyle),
}
sess, err := session.NewSession(s3Config)
if err != nil {
return nil, err
}
return &historyArchiver{
container: container,
s3cli: s3.New(sess),
historyIterator: historyIterator,
}, nil
}
func (h *historyArchiver) Archive(
ctx context.Context,
URI archiver.URI,
request *archiver.ArchiveHistoryRequest,
opts ...archiver.ArchiveOption,
) (err error) {
scope := h.container.MetricsClient.Scope(metrics.HistoryArchiverScope, metrics.DomainTag(request.DomainName))
featureCatalog := archiver.GetFeatureCatalog(opts...)
sw := scope.StartTimer(metrics.CadenceLatency)
defer func() {
sw.Stop()
if err != nil {
if persistence.IsTransientError(err) || isRetryableError(err) {
scope.IncCounter(metrics.HistoryArchiverArchiveTransientErrorCount)
} else {
scope.IncCounter(metrics.HistoryArchiverArchiveNonRetryableErrorCount)
if featureCatalog.NonRetriableError != nil {
err = featureCatalog.NonRetriableError()
}
}
}
}()
logger := archiver.TagLoggerWithArchiveHistoryRequestAndURI(h.container.Logger, request, URI.String())
if err := softValidateURI(URI); err != nil {
logger.Error(archiver.ArchiveNonRetriableErrorMsg, tag.ArchivalArchiveFailReason(archiver.ErrReasonInvalidURI), tag.Error(err))
return err
}
if err := archiver.ValidateHistoryArchiveRequest(request); err != nil {
logger.Error(archiver.ArchiveNonRetriableErrorMsg, tag.ArchivalArchiveFailReason(archiver.ErrReasonInvalidArchiveRequest), tag.Error(err))
return err
}
var progress uploadProgress
historyIterator := h.historyIterator
if historyIterator == nil { // will only be set by testing code
historyIterator = loadHistoryIterator(ctx, request, h.container.HistoryV2Manager, featureCatalog, &progress)
}
for historyIterator.HasNext() {
historyBlob, err := getNextHistoryBlob(ctx, historyIterator)
if err != nil {
if common.IsEntityNotExistsError(err) {
// workflow history no longer exists, may due to duplicated archival signal
// this may happen even in the middle of iterating history as two archival signals
// can be processed concurrently.
logger.Info(archiver.ArchiveSkippedInfoMsg)
scope.IncCounter(metrics.HistoryArchiverDuplicateArchivalsCount)
return nil
}
logger := logger.WithTags(tag.ArchivalArchiveFailReason(archiver.ErrReasonReadHistory), tag.Error(err))
if persistence.IsTransientError(err) {
logger.Error(archiver.ArchiveTransientErrorMsg)
} else {
logger.Error(archiver.ArchiveNonRetriableErrorMsg)
}
return err
}
if archiver.IsHistoryMutated(request, historyBlob.Body, *historyBlob.Header.IsLast, logger) {
if !featureCatalog.ArchiveIncompleteHistory() {
return archiver.ErrHistoryMutated
}
}
encodedHistoryBlob, err := encode(historyBlob)
if err != nil {
logger.Error(archiver.ArchiveNonRetriableErrorMsg, tag.ArchivalArchiveFailReason(errEncodeHistory), tag.Error(err))
return err
}
key := constructHistoryKey(URI.Path(), request.DomainID, request.WorkflowID, request.RunID, request.CloseFailoverVersion, progress.BatchIdx)
exists, err := keyExists(ctx, h.s3cli, URI, key)
if err != nil {
logger := logger.WithTags(tag.ArchivalArchiveFailReason(errWriteKey), tag.Error(err))
if isRetryableError(err) {
logger.Error(archiver.ArchiveTransientErrorMsg)
} else {
logger.Error(archiver.ArchiveNonRetriableErrorMsg)
}
return err
}
blobSize := int64(binary.Size(encodedHistoryBlob))
if exists {
scope.IncCounter(metrics.HistoryArchiverBlobExistsCount)
} else {
if err := upload(ctx, h.s3cli, URI, key, encodedHistoryBlob); err != nil {
logger := logger.WithTags(tag.ArchivalArchiveFailReason(errWriteKey), tag.Error(err))
if isRetryableError(err) {
logger.Error(archiver.ArchiveTransientErrorMsg)
} else {
logger.Error(archiver.ArchiveNonRetriableErrorMsg)
}
return err
}
progress.uploadedSize += blobSize
scope.RecordTimer(metrics.HistoryArchiverBlobSize, time.Duration(blobSize))
}
progress.historySize += blobSize
progress.BatchIdx = progress.BatchIdx + 1
saveHistoryIteratorState(ctx, featureCatalog, historyIterator, &progress)
}
scope.RecordTimer(metrics.HistoryArchiverTotalUploadSize, time.Duration(progress.uploadedSize))
scope.RecordTimer(metrics.HistoryArchiverHistorySize, time.Duration(progress.historySize))
scope.IncCounter(metrics.HistoryArchiverArchiveSuccessCount)
return nil
}
func loadHistoryIterator(ctx context.Context, request *archiver.ArchiveHistoryRequest, historyManager persistence.HistoryManager, featureCatalog *archiver.ArchiveFeatureCatalog, progress *uploadProgress) (historyIterator archiver.HistoryIterator) {
if featureCatalog.ProgressManager != nil {
if featureCatalog.ProgressManager.HasProgress(ctx) {
err := featureCatalog.ProgressManager.LoadProgress(ctx, progress)
if err == nil {
historyIterator, err := archiver.NewHistoryIteratorFromState(ctx, request, historyManager, targetHistoryBlobSize, progress.IteratorState)
if err == nil {
return historyIterator
}
}
progress.IteratorState = nil
progress.BatchIdx = 0
progress.historySize = 0
progress.uploadedSize = 0
}
}
return archiver.NewHistoryIterator(ctx, request, historyManager, targetHistoryBlobSize)
}
func saveHistoryIteratorState(ctx context.Context, featureCatalog *archiver.ArchiveFeatureCatalog, historyIterator archiver.HistoryIterator, progress *uploadProgress) {
// Saving history state is a best effort operation. Ignore errors and continue
if featureCatalog.ProgressManager != nil {
state, err := historyIterator.GetState()
if err != nil {
return
}
progress.IteratorState = state
err = featureCatalog.ProgressManager.RecordProgress(ctx, progress)
if err != nil {
return
}
}
}
func (h *historyArchiver) Get(
ctx context.Context,
URI archiver.URI,
request *archiver.GetHistoryRequest,
) (*archiver.GetHistoryResponse, error) {
if err := softValidateURI(URI); err != nil {
return nil, &types.BadRequestError{Message: archiver.ErrInvalidURI.Error()}
}
if err := archiver.ValidateGetRequest(request); err != nil {
return nil, &types.BadRequestError{Message: archiver.ErrInvalidGetHistoryRequest.Error()}
}
var err error
var token *getHistoryToken
if request.NextPageToken != nil {
token, err = deserializeGetHistoryToken(request.NextPageToken)
if err != nil {
return nil, &types.BadRequestError{Message: archiver.ErrNextPageTokenCorrupted.Error()}
}
} else if request.CloseFailoverVersion != nil {
token = &getHistoryToken{
CloseFailoverVersion: *request.CloseFailoverVersion,
}
} else {
highestVersion, err := h.getHighestVersion(ctx, URI, request)
if err != nil {
return nil, &types.BadRequestError{Message: err.Error()}
}
token = &getHistoryToken{
CloseFailoverVersion: *highestVersion,
}
}
response := &archiver.GetHistoryResponse{}
numOfEvents := 0
isTruncated := false
for {
if numOfEvents >= request.PageSize {
isTruncated = true
break
}
key := constructHistoryKey(URI.Path(), request.DomainID, request.WorkflowID, request.RunID, token.CloseFailoverVersion, token.BatchIdx)
encodedRecord, err := download(ctx, h.s3cli, URI, key)
if err != nil {
if isRetryableError(err) {
return nil, &types.InternalServiceError{Message: err.Error()}
}
switch err.(type) {
case *types.BadRequestError, *types.InternalServiceError, *types.EntityNotExistsError:
return nil, err
default:
return nil, &types.InternalServiceError{Message: err.Error()}
}
}
historyBlob, err := decodeHistoryBlob(encodedRecord)
if err != nil {
return nil, &types.InternalServiceError{Message: err.Error()}
}
for _, batch := range historyBlob.Body {
response.HistoryBatches = append(response.HistoryBatches, batch)
numOfEvents += len(batch.Events)
}
if *historyBlob.Header.IsLast {
break
}
token.BatchIdx++
}
if isTruncated {
nextToken, err := serializeToken(token)
if err != nil {
return nil, &types.InternalServiceError{Message: err.Error()}
}
response.NextPageToken = nextToken
}
return response, nil
}
func (h *historyArchiver) ValidateURI(URI archiver.URI) error {
err := softValidateURI(URI)
if err != nil {
return err
}
return bucketExists(context.TODO(), h.s3cli, URI)
}
func getNextHistoryBlob(ctx context.Context, historyIterator archiver.HistoryIterator) (*archiver.HistoryBlob, error) {
historyBlob, err := historyIterator.Next()
op := func() error {
historyBlob, err = historyIterator.Next()
return err
}
throttleRetry := backoff.NewThrottleRetry(
backoff.WithRetryPolicy(common.CreatePersistenceRetryPolicy()),
backoff.WithRetryableError(persistence.IsTransientError),
)
for err != nil {
if contextExpired(ctx) {
return nil, archiver.ErrContextTimeout
}
if !persistence.IsTransientError(err) {
return nil, err
}
err = throttleRetry.Do(ctx, op)
}
return historyBlob, nil
}
// with XDC(global domain) concept, archival may write different history with the same RunID, with different failoverVersion.
// In that case, the history/runID with the highest failoverVersion wins.
// getHighestVersion look up all archived files to find the highest failoverVersion.
func (h *historyArchiver) getHighestVersion(ctx context.Context, URI archiver.URI, request *archiver.GetHistoryRequest) (*int64, error) {
ctx, cancel := ensureContextTimeout(ctx)
defer cancel()
var prefix = constructHistoryKeyPrefix(URI.Path(), request.DomainID, request.WorkflowID, request.RunID) + "/"
results, err := h.s3cli.ListObjectsV2WithContext(ctx, &s3.ListObjectsV2Input{
Bucket: aws.String(URI.Hostname()),
Prefix: aws.String(prefix),
Delimiter: aws.String("/"),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchBucket {
return nil, &types.BadRequestError{Message: errBucketNotExists.Error()}
}
return nil, err
}
var highestVersion *int64
for _, v := range results.CommonPrefixes {
var version int64
version, err = strconv.ParseInt(strings.Replace(strings.Replace(*v.Prefix, prefix, "", 1), "/", "", 1), 10, 64)
if err != nil {
continue
}
if highestVersion == nil || version > *highestVersion {
highestVersion = &version
}
}
if highestVersion == nil {
return nil, archiver.ErrHistoryNotExist
}
return highestVersion, nil
}
func isRetryableError(err error) bool {
if err == nil {
return false
}
if aerr, ok := err.(awserr.Error); ok {
return isStatusCodeRetryable(aerr) || request.IsErrorRetryable(aerr) || request.IsErrorThrottle(aerr)
}
return false
}
func isStatusCodeRetryable(err error) bool {
if aerr, ok := err.(awserr.Error); ok {
if rerr, ok := err.(awserr.RequestFailure); ok {
if rerr.StatusCode() == 429 {
return true
}
if rerr.StatusCode() >= 500 && rerr.StatusCode() != 501 {
return true
}
}
return isStatusCodeRetryable(aerr.OrigErr())
}
return false
}