/
context_impl.go
2238 lines (1940 loc) · 69.9 KB
/
context_impl.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// 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.
package shard
import (
"context"
"errors"
"fmt"
"math"
"sync"
"sync/atomic"
"time"
"github.com/pborman/uuid"
commonpb "go.temporal.io/api/common/v1"
"go.temporal.io/api/enums/v1"
"go.temporal.io/api/serviceerror"
"golang.org/x/exp/maps"
"golang.org/x/sync/semaphore"
"google.golang.org/protobuf/types/known/timestamppb"
"go.temporal.io/server/api/adminservice/v1"
clockspb "go.temporal.io/server/api/clock/v1"
enumsspb "go.temporal.io/server/api/enums/v1"
"go.temporal.io/server/api/historyservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
"go.temporal.io/server/client"
"go.temporal.io/server/common"
"go.temporal.io/server/common/archiver"
"go.temporal.io/server/common/backoff"
cclock "go.temporal.io/server/common/clock"
"go.temporal.io/server/common/cluster"
"go.temporal.io/server/common/config"
"go.temporal.io/server/common/convert"
"go.temporal.io/server/common/debug"
"go.temporal.io/server/common/definition"
"go.temporal.io/server/common/dynamicconfig"
"go.temporal.io/server/common/future"
"go.temporal.io/server/common/headers"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/membership"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/persistence/serialization"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/common/rpc"
"go.temporal.io/server/common/searchattribute"
"go.temporal.io/server/common/util"
"go.temporal.io/server/service/history/configs"
"go.temporal.io/server/service/history/consts"
"go.temporal.io/server/service/history/events"
"go.temporal.io/server/service/history/tasks"
"go.temporal.io/server/service/history/vclock"
)
const (
// See transition for overview of state transitions.
// These are the possible values of ContextImpl.state:
contextStateInitialized contextState = iota
contextStateAcquiring
contextStateAcquired
contextStateStopping
contextStateStopped
)
const (
shardIOTimeout = 5 * time.Second * debug.TimeoutMultiplier
pendingMaxReplicationTaskID = math.MaxInt64
)
var (
shardContextSequenceID int64 = 0
)
type (
contextState int32
ContextImpl struct {
// These fields are constant:
shardID int32
owner string
stringRepr string
executionManager persistence.ExecutionManager
metricsHandler metrics.Handler
eventsCache events.Cache
closeCallback CloseCallback
config *configs.Config
contextTaggedLogger log.Logger
throttledLogger log.Logger
engineFactory EngineFactory
engineFuture *future.FutureImpl[Engine]
persistenceShardManager persistence.ShardManager
clientBean client.Bean
historyClient historyservice.HistoryServiceClient
payloadSerializer serialization.Serializer
timeSource cclock.TimeSource
namespaceRegistry namespace.Registry
saProvider searchattribute.Provider
saMapperProvider searchattribute.MapperProvider
clusterMetadata cluster.Metadata
archivalMetadata archiver.ArchivalMetadata
hostInfoProvider membership.HostInfoProvider
taskCategoryRegistry tasks.TaskCategoryRegistry
// Context that lives for the lifetime of the shard context
lifecycleCtx context.Context
lifecycleCancel context.CancelFunc
// ioSemaphore is used to control the concurrency of shard I/O requests.
// Despite its name, this semaphore is only applied to persistence requests that
// could cause potentially contention/conflict with each other.
// For cassandra, this basically means requests that use LWT.
// It's ok to use semaphore by its own or lock rwLock within the semaphore.
// But DO NOT try to acquire ioSemaphore while holding rwLock, as it may cause deadlock.
ioSemaphore *semaphore.Weighted
// state is protected by stateLock
stateLock sync.Mutex
state contextState
stopReason stopReason
// All following fields are protected by rwLock, and only valid if state >= Acquiring:
rwLock sync.RWMutex
lastUpdated time.Time
shardInfo *persistencespb.ShardInfo
// All methods of the taskKeyManager, except the completionFn returned by
// setAndTrackTaskKeys, must be invoked within rwLock.
// NOTE: The completionFn must be invoked outside rwLock because when
// renewing rangeID, the rwLock will be held when waiting for in-flight
// requests to complete.
taskKeyManager *taskKeyManager
// exist only in memory
remoteClusterInfos map[string]*remoteClusterInfo
handoverNamespaces map[namespace.Name]*namespaceHandOverInfo // keyed on namespace name
acquireShardRetryPolicy backoff.RetryPolicy
}
remoteClusterInfo struct {
CurrentTime time.Time
AckedReplicationTaskIDs map[int32]int64
AckedReplicationTimestamps map[int32]time.Time
}
namespaceHandOverInfo struct {
MaxReplicationTaskID int64
NotificationVersion int64
}
// These are the requests that can be passed to transition to change state:
contextRequest interface{}
contextRequestAcquire struct{}
contextRequestAcquired struct{ engine Engine }
contextRequestLost struct{}
contextRequestStop struct{ reason stopReason }
contextRequestFinishStop struct{}
stopReason int
)
const (
stopReasonUnspecified stopReason = iota
stopReasonOwnershipLost
)
var _ Context = (*ContextImpl)(nil)
var (
// ErrShardStatusUnknown means we're not sure if we have the shard lock or not. This may be returned
// during short windows at initialization and if we've lost the connection to the database.
ErrShardStatusUnknown = serviceerror.NewUnavailable("shard status unknown")
// errInvalidTransition is an internal error used for acquireShard and transition
errInvalidTransition = errors.New("invalid state transition request")
)
const (
logWarnImmediateTaskLag = 3000000 // 3 million
logWarnScheduledTaskLag = time.Duration(30 * time.Minute)
historySizeLogThreshold = 10 * 1024 * 1024
minContextTimeout = 2 * time.Second * debug.TimeoutMultiplier
)
func (s *ContextImpl) String() string {
// constant from initialization, no need for locks
return s.stringRepr
}
func (s *ContextImpl) GetShardID() int32 {
// constant from initialization, no need for locks
return s.shardID
}
func (s *ContextImpl) GetRangeID() int64 {
s.rLock()
defer s.rUnlock()
return s.getRangeIDLocked()
}
func (s *ContextImpl) GetOwner() string {
// constant from initialization, no need for locks
return s.owner
}
func (s *ContextImpl) GetExecutionManager() persistence.ExecutionManager {
// constant from initialization, no need for locks
return s.executionManager
}
func (s *ContextImpl) GetPingChecks() []common.PingCheck {
return []common.PingCheck{
{
Name: s.String() + "-shard-lock",
// rwLock may be held for the duration of renewing shard rangeID, which are called with a
// timeout of shardIOTimeout. add a few more seconds for reliability.
Timeout: shardIOTimeout + 5*time.Second,
Ping: func() []common.Pingable {
// call rwLock.Lock directly to bypass metrics since this isn't a real request
s.rwLock.Lock()
//nolint:staticcheck // SA2001 just checking if we can acquire the lock
s.rwLock.Unlock()
return nil
},
MetricsName: metrics.DDShardLockLatency.Name(),
},
{
Name: s.String() + "-io-semaphore",
// ioSemaphore is for the duration of a persistence op which has a persistence connection timeout
// of 10 sec.
Timeout: 10 * time.Second,
Ping: func() []common.Pingable {
_ = s.ioSemaphore.Acquire(context.Background(), 1)
s.ioSemaphore.Release(1)
return nil
},
MetricsName: metrics.DDShardIOSemaphoreLatency.Name(),
},
}
}
func (s *ContextImpl) GetEngine(
ctx context.Context,
) (Engine, error) {
return s.engineFuture.Get(ctx)
}
func (s *ContextImpl) AssertOwnership(
ctx context.Context,
) error {
if err := s.ioSemaphoreAcquire(ctx); err != nil {
return err
}
defer s.ioSemaphoreRelease()
s.wLock()
// timeout check should be done within the shard lock, in case of shard lock contention
ctx, cancel, err := s.newDetachedContext(ctx)
if err != nil {
s.wUnlock()
return err
}
defer cancel()
if err := s.errorByState(); err != nil {
s.wUnlock()
return err
}
request := &persistence.AssertShardOwnershipRequest{
ShardID: s.shardID,
RangeID: s.getRangeIDLocked(),
}
s.wUnlock()
err = s.persistenceShardManager.AssertShardOwnership(ctx, request)
return s.handleWriteError(request.RangeID, err)
}
func (s *ContextImpl) NewVectorClock() (*clockspb.VectorClock, error) {
s.wLock()
defer s.wUnlock()
clock, err := s.generateTaskIDLocked()
if err != nil {
return nil, err
}
return vclock.NewVectorClock(s.clusterMetadata.GetClusterID(), s.shardID, clock), nil
}
func (s *ContextImpl) CurrentVectorClock() *clockspb.VectorClock {
s.rLock()
defer s.rUnlock()
nextTaskKey := s.taskKeyManager.peekTaskKey(tasks.CategoryTransfer)
return vclock.NewVectorClock(s.clusterMetadata.GetClusterID(), s.shardID, nextTaskKey.TaskID)
}
func (s *ContextImpl) GenerateTaskID() (int64, error) {
s.wLock()
defer s.wUnlock()
return s.generateTaskIDLocked()
}
func (s *ContextImpl) GenerateTaskIDs(number int) ([]int64, error) {
s.wLock()
defer s.wUnlock()
result := []int64{}
for i := 0; i < number; i++ {
id, err := s.generateTaskIDLocked()
if err != nil {
return nil, err
}
result = append(result, id)
}
return result, nil
}
func (s *ContextImpl) GetQueueExclusiveHighReadWatermark(
category tasks.Category,
) tasks.Key {
s.wLock()
defer s.wUnlock()
return s.taskKeyManager.getExclusiveReaderHighWatermark(category)
}
func (s *ContextImpl) GetQueueState(
category tasks.Category,
) (*persistencespb.QueueState, bool) {
s.rLock()
defer s.rUnlock()
queueState, ok := s.shardInfo.QueueStates[int32(category.ID())]
if !ok {
return nil, false
}
// need to make a deep copy, in case UpdateReplicationQueueReaderState does a partial update
blob, _ := serialization.QueueStateToBlob(queueState)
queueState, _ = serialization.QueueStateFromBlob(blob.Data, blob.EncodingType.String())
return queueState, ok
}
func (s *ContextImpl) SetQueueState(
category tasks.Category,
state *persistencespb.QueueState,
) error {
return s.updateShardInfo(func() {
categoryID := category.ID()
s.shardInfo.QueueStates[int32(categoryID)] = state
})
}
func (s *ContextImpl) UpdateReplicationQueueReaderState(
readerID int64,
readerState *persistencespb.QueueReaderState,
) error {
return s.updateShardInfo(func() {
categoryID := tasks.CategoryReplication.ID()
queueState, ok := s.shardInfo.QueueStates[int32(categoryID)]
if !ok {
queueState = &persistencespb.QueueState{
ExclusiveReaderHighWatermark: nil,
ReaderStates: make(map[int64]*persistencespb.QueueReaderState),
}
s.shardInfo.QueueStates[int32(categoryID)] = queueState
}
queueState.ReaderStates[readerID] = readerState
})
}
// UpdateRemoteClusterInfo deprecated
// Deprecated use UpdateRemoteReaderInfo in the future instead
func (s *ContextImpl) UpdateRemoteClusterInfo(
clusterName string,
ackTaskID int64,
ackTimestamp time.Time,
) {
s.wLock()
defer s.wUnlock()
clusterInfo := s.clusterMetadata.GetAllClusterInfo()
remoteClusterInfo := s.getOrUpdateRemoteClusterInfoLocked(clusterName)
for _, remoteShardID := range common.MapShardID(
clusterInfo[s.clusterMetadata.GetCurrentClusterName()].ShardCount,
clusterInfo[clusterName].ShardCount,
s.shardID,
) {
remoteClusterInfo.AckedReplicationTaskIDs[remoteShardID] = ackTaskID
remoteClusterInfo.AckedReplicationTimestamps[remoteShardID] = ackTimestamp
}
}
// UpdateRemoteReaderInfo do not use streaming replication until remoteClusterInfo is updated to allow both
// streaming & pull based replication
func (s *ContextImpl) UpdateRemoteReaderInfo(
readerID int64,
ackTaskID int64,
ackTimestamp time.Time,
) error {
clusterID, shardID := ReplicationReaderIDToClusterShardID(readerID)
clusterName, _, ok := clusterNameInfoFromClusterID(s.clusterMetadata.GetAllClusterInfo(), clusterID)
if !ok {
// cluster is not present in cluster metadata map
return serviceerror.NewInternal(fmt.Sprintf("unknown cluster ID: %v", clusterID))
}
s.wLock()
defer s.wUnlock()
remoteClusterInfo := s.getOrUpdateRemoteClusterInfoLocked(clusterName)
remoteClusterInfo.AckedReplicationTaskIDs[shardID] = ackTaskID
remoteClusterInfo.AckedReplicationTimestamps[shardID] = ackTimestamp
return nil
}
func (s *ContextImpl) GetReplicatorDLQAckLevel(sourceCluster string) int64 {
s.rLock()
defer s.rUnlock()
if ackLevel, ok := s.shardInfo.ReplicationDlqAckLevel[sourceCluster]; ok {
return ackLevel
}
return -1
}
func (s *ContextImpl) UpdateReplicatorDLQAckLevel(
sourceCluster string,
ackLevel int64,
) error {
if err := s.updateShardInfo(func() {
s.shardInfo.ReplicationDlqAckLevel[sourceCluster] = ackLevel
}); err != nil {
return err
}
s.GetMetricsHandler().Gauge(metrics.ReplicationDLQAckLevelGauge.Name()).
Record(float64(ackLevel),
metrics.OperationTag(metrics.ReplicationDLQStatsScope),
metrics.TargetClusterTag(sourceCluster),
metrics.InstanceTag(convert.Int32ToString(s.shardID)))
return nil
}
func (s *ContextImpl) UpdateHandoverNamespace(ns *namespace.Namespace, deletedFromDb bool) {
nsName := ns.Name()
// NOTE: replication state field won't be replicated and currently we only update a namespace
// to handover state from active cluster, so the second condition will always be true. Adding
// it here to be more safe in case above assumption no longer holds in the future.
isHandoverNamespace := ns.IsGlobalNamespace() &&
ns.ActiveInCluster(s.GetClusterMetadata().GetCurrentClusterName()) &&
ns.ReplicationState() == enums.REPLICATION_STATE_HANDOVER
s.wLock()
if deletedFromDb || !isHandoverNamespace {
delete(s.handoverNamespaces, ns.Name())
s.wUnlock()
return
}
maxReplicationTaskID := s.taskKeyManager.getExclusiveReaderHighWatermark(tasks.CategoryReplication).TaskID - 1
if s.errorByState() != nil {
// if shard state is not acquired, we don't know that's the max taskID
// as there might be in-flight requests
maxReplicationTaskID = pendingMaxReplicationTaskID
}
if handover, ok := s.handoverNamespaces[nsName]; ok {
if handover.NotificationVersion < ns.NotificationVersion() {
handover.NotificationVersion = ns.NotificationVersion()
handover.MaxReplicationTaskID = maxReplicationTaskID
}
} else {
s.handoverNamespaces[nsName] = &namespaceHandOverInfo{
NotificationVersion: ns.NotificationVersion(),
MaxReplicationTaskID: maxReplicationTaskID,
}
}
s.wUnlock()
if maxReplicationTaskID != pendingMaxReplicationTaskID {
// notification is for making sure replication queue is able to
// ack to the recorded taskID. If the taskID is pending, then
// don't notify. Otherwise, replication queue will think (for a period of time)
// that the max generated taskID is pendingMaxReplicationTaskID which is MaxInt64.
s.notifyReplicationQueueProcessor(maxReplicationTaskID)
}
}
func (s *ContextImpl) AddTasks(
ctx context.Context,
request *persistence.AddHistoryTasksRequest,
) error {
engine, err := s.GetEngine(ctx)
if err != nil {
return err
}
if err := s.ioSemaphoreAcquire(ctx); err != nil {
return err
}
defer s.ioSemaphoreRelease()
err = s.addTasksSemaphoreAcquired(ctx, request)
if OperationPossiblySucceeded(err) {
engine.NotifyNewTasks(request.Tasks)
}
return err
}
func (s *ContextImpl) AddSpeculativeWorkflowTaskTimeoutTask(
task *tasks.WorkflowTaskTimeoutTask,
) error {
// Use a cancelled context to avoid blocking if engineFuture is not ready.
cancelledCtx, cancel := context.WithCancel(context.Background())
cancel()
// err should never be returned here. engineFuture must always be ready.
engine, err := s.engineFuture.Get(cancelledCtx)
if err != nil {
return err
}
engine.AddSpeculativeWorkflowTaskTimeoutTask(task)
return nil
}
func (s *ContextImpl) CreateWorkflowExecution(
ctx context.Context,
request *persistence.CreateWorkflowExecutionRequest,
) (*persistence.CreateWorkflowExecutionResponse, error) {
// do not try to get namespace cache within shard lock
namespaceID := namespace.ID(request.NewWorkflowSnapshot.ExecutionInfo.NamespaceId)
namespaceEntry, err := s.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
if err := s.ioSemaphoreAcquire(ctx); err != nil {
return nil, err
}
defer s.ioSemaphoreRelease()
s.wLock()
// timeout check should be done within the shard lock, in case of shard lock contention
ctx, cancel, err := s.newDetachedContext(ctx)
if err != nil {
s.wUnlock()
return nil, err
}
defer cancel()
if err := s.errorByState(); err != nil {
s.wUnlock()
return nil, err
}
if err := s.errorByNamespaceStateLocked(namespaceEntry.Name()); err != nil {
s.wUnlock()
return nil, err
}
requestCompletionFn, err := s.taskKeyManager.setAndTrackTaskKeys(
request.NewWorkflowSnapshot.Tasks,
)
if err != nil {
s.wUnlock()
return nil, err
}
s.updateCloseTaskIDs(request.NewWorkflowSnapshot.ExecutionInfo, request.NewWorkflowSnapshot.Tasks)
currentRangeID := s.getRangeIDLocked()
request.RangeID = currentRangeID
s.wUnlock()
resp, err := s.executionManager.CreateWorkflowExecution(ctx, request)
requestCompletionFn(err)
if err = s.handleWriteError(request.RangeID, err); err != nil {
return nil, err
}
return resp, nil
}
func (s *ContextImpl) UpdateWorkflowExecution(
ctx context.Context,
request *persistence.UpdateWorkflowExecutionRequest,
) (*persistence.UpdateWorkflowExecutionResponse, error) {
// do not try to get namespace cache within shard lock
namespaceID := namespace.ID(request.UpdateWorkflowMutation.ExecutionInfo.NamespaceId)
namespaceEntry, err := s.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
if err := s.ioSemaphoreAcquire(ctx); err != nil {
return nil, err
}
defer s.ioSemaphoreRelease()
s.wLock()
// timeout check should be done within the shard lock, in case of shard lock contention
ctx, cancel, err := s.newDetachedContext(ctx)
if err != nil {
s.wUnlock()
return nil, err
}
defer cancel()
if err := s.errorByState(); err != nil {
s.wUnlock()
return nil, err
}
if err := s.errorByNamespaceStateLocked(namespaceEntry.Name()); err != nil {
s.wUnlock()
return nil, err
}
taskMaps := make([]map[tasks.Category][]tasks.Task, 0, 2)
taskMaps = append(taskMaps, request.UpdateWorkflowMutation.Tasks)
if request.NewWorkflowSnapshot != nil {
taskMaps = append(taskMaps, request.NewWorkflowSnapshot.Tasks)
}
requestCompletionFn, err := s.taskKeyManager.setAndTrackTaskKeys(taskMaps...)
if err != nil {
s.wUnlock()
return nil, err
}
s.updateCloseTaskIDs(request.UpdateWorkflowMutation.ExecutionInfo, request.UpdateWorkflowMutation.Tasks)
if request.NewWorkflowSnapshot != nil {
s.updateCloseTaskIDs(request.NewWorkflowSnapshot.ExecutionInfo, request.NewWorkflowSnapshot.Tasks)
}
request.RangeID = s.getRangeIDLocked()
s.wUnlock()
resp, err := s.executionManager.UpdateWorkflowExecution(ctx, request)
requestCompletionFn(err)
if err = s.handleWriteError(request.RangeID, err); err != nil {
return nil, err
}
return resp, nil
}
func (s *ContextImpl) updateCloseTaskIDs(executionInfo *persistencespb.WorkflowExecutionInfo, tasksByCategory map[tasks.Category][]tasks.Task) {
for _, t := range tasksByCategory[tasks.CategoryTransfer] {
if t.GetType() == enumsspb.TASK_TYPE_TRANSFER_CLOSE_EXECUTION {
executionInfo.CloseTransferTaskId = t.GetTaskID()
break
}
}
for _, t := range tasksByCategory[tasks.CategoryVisibility] {
if t.GetType() == enumsspb.TASK_TYPE_VISIBILITY_CLOSE_EXECUTION {
executionInfo.CloseVisibilityTaskId = t.GetTaskID()
break
}
}
}
func (s *ContextImpl) ConflictResolveWorkflowExecution(
ctx context.Context,
request *persistence.ConflictResolveWorkflowExecutionRequest,
) (*persistence.ConflictResolveWorkflowExecutionResponse, error) {
// do not try to get namespace cache within shard lock
namespaceID := namespace.ID(request.ResetWorkflowSnapshot.ExecutionInfo.NamespaceId)
namespaceEntry, err := s.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
if err := s.ioSemaphoreAcquire(ctx); err != nil {
return nil, err
}
defer s.ioSemaphoreRelease()
s.wLock()
// timeout check should be done within the shard lock, in case of shard lock contention
ctx, cancel, err := s.newDetachedContext(ctx)
if err != nil {
s.wUnlock()
return nil, err
}
defer cancel()
if err := s.errorByState(); err != nil {
s.wUnlock()
return nil, err
}
if err := s.errorByNamespaceStateLocked(namespaceEntry.Name()); err != nil {
s.wUnlock()
return nil, err
}
taskMaps := make([]map[tasks.Category][]tasks.Task, 0, 3)
if request.CurrentWorkflowMutation != nil {
taskMaps = append(taskMaps, request.CurrentWorkflowMutation.Tasks)
}
taskMaps = append(taskMaps, request.ResetWorkflowSnapshot.Tasks)
if request.NewWorkflowSnapshot != nil {
taskMaps = append(taskMaps, request.NewWorkflowSnapshot.Tasks)
}
requestCompletionFn, err := s.taskKeyManager.setAndTrackTaskKeys(taskMaps...)
if err != nil {
s.wUnlock()
return nil, err
}
request.RangeID = s.getRangeIDLocked()
s.wUnlock()
resp, err := s.executionManager.ConflictResolveWorkflowExecution(ctx, request)
requestCompletionFn(err)
if err = s.handleWriteError(request.RangeID, err); err != nil {
return nil, err
}
return resp, nil
}
func (s *ContextImpl) SetWorkflowExecution(
ctx context.Context,
request *persistence.SetWorkflowExecutionRequest,
) (*persistence.SetWorkflowExecutionResponse, error) {
// do not try to get namespace cache within shard lock
namespaceID := namespace.ID(request.SetWorkflowSnapshot.ExecutionInfo.NamespaceId)
namespaceEntry, err := s.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return nil, err
}
if err := s.ioSemaphoreAcquire(ctx); err != nil {
return nil, err
}
defer s.ioSemaphoreRelease()
s.wLock()
// timeout check should be done within the shard lock, in case of shard lock contention
ctx, cancel, err := s.newDetachedContext(ctx)
if err != nil {
s.wUnlock()
return nil, err
}
defer cancel()
if err := s.errorByState(); err != nil {
s.wUnlock()
return nil, err
}
if err := s.errorByNamespaceStateLocked(namespaceEntry.Name()); err != nil {
s.wUnlock()
return nil, err
}
snapShotRequestCompletionFn, err := s.taskKeyManager.setAndTrackTaskKeys(
request.SetWorkflowSnapshot.Tasks,
)
if err != nil {
s.wUnlock()
return nil, err
}
request.RangeID = s.getRangeIDLocked()
s.wUnlock()
resp, err := s.executionManager.SetWorkflowExecution(ctx, request)
snapShotRequestCompletionFn(err)
if err = s.handleWriteError(request.RangeID, err); err != nil {
return nil, err
}
return resp, nil
}
func (s *ContextImpl) GetCurrentExecution(
ctx context.Context,
request *persistence.GetCurrentExecutionRequest,
) (*persistence.GetCurrentExecutionResponse, error) {
if err := s.errorByState(); err != nil {
return nil, err
}
resp, err := s.executionManager.GetCurrentExecution(ctx, request)
if err = s.handleReadError(err); err != nil {
// also return resp, for RebuildMutableState API
return resp, err
}
return resp, nil
}
func (s *ContextImpl) GetWorkflowExecution(
ctx context.Context,
request *persistence.GetWorkflowExecutionRequest,
) (*persistence.GetWorkflowExecutionResponse, error) {
if err := s.errorByState(); err != nil {
return nil, err
}
resp, err := s.executionManager.GetWorkflowExecution(ctx, request)
if err = s.handleReadError(err); err != nil {
// also return resp, for RebuildMutableState API
return resp, err
}
return resp, nil
}
func (s *ContextImpl) addTasksSemaphoreAcquired(
ctx context.Context,
request *persistence.AddHistoryTasksRequest,
) error {
// do not try to get namespace cache within shard lock
namespaceID := namespace.ID(request.NamespaceID)
namespaceEntry, err := s.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
if err != nil {
return err
}
s.wLock()
// timeout check should be done within the shard lock, in case of shard lock contention
ctx, cancel, err := s.newDetachedContext(ctx)
if err != nil {
s.wUnlock()
return err
}
defer cancel()
if err := s.errorByState(); err != nil {
s.wUnlock()
return err
}
if err := s.errorByNamespaceStateLocked(namespaceEntry.Name()); err != nil {
s.wUnlock()
return err
}
requestCompletionFn, err := s.taskKeyManager.setAndTrackTaskKeys(
request.Tasks,
)
if err != nil {
s.wUnlock()
return err
}
request.RangeID = s.getRangeIDLocked()
s.wUnlock()
err = s.executionManager.AddHistoryTasks(ctx, request)
requestCompletionFn(err)
return s.handleWriteError(request.RangeID, err)
}
func (s *ContextImpl) AppendHistoryEvents(
ctx context.Context,
request *persistence.AppendHistoryNodesRequest,
namespaceID namespace.ID,
execution *commonpb.WorkflowExecution,
) (int, error) {
if err := s.errorByState(); err != nil {
return 0, err
}
request.ShardID = s.shardID
size := 0
defer func() {
// N.B. - Dual emit here makes sense so that we can see aggregate timer stats across all
// namespaces along with the individual namespaces stats
handler := s.GetMetricsHandler().WithTags(metrics.OperationTag(metrics.SessionStatsScope))
handler.Histogram(metrics.HistorySize.Name(), metrics.HistorySize.Unit()).Record(int64(size))
if entry, err := s.GetNamespaceRegistry().GetNamespaceByID(namespaceID); err == nil && entry != nil {
handler.Histogram(metrics.HistorySize.Name(), metrics.HistorySize.Unit()).
Record(int64(size), metrics.NamespaceTag(entry.Name().String()))
}
if size >= historySizeLogThreshold {
s.throttledLogger.Warn("history size threshold breached",
tag.WorkflowID(execution.GetWorkflowId()),
tag.WorkflowRunID(execution.GetRunId()),
tag.WorkflowNamespaceID(namespaceID.String()),
tag.WorkflowHistorySizeBytes(size))
}
}()
resp, err0 := s.GetExecutionManager().AppendHistoryNodes(ctx, request)
if resp != nil {
size = resp.Size
}
return size, err0
}
func (s *ContextImpl) DeleteWorkflowExecution(
ctx context.Context,
key definition.WorkflowKey,
branchToken []byte,
startTime time.Time,
closeTime time.Time,
closeVisibilityTaskId int64,
stage *tasks.DeleteWorkflowExecutionStage,
) (retErr error) {
// DeleteWorkflowExecution is a 4 stages process (order is very important and should not be changed):
// 1. Add visibility delete task, i.e. schedule visibility record delete,
// 2. Delete current workflow execution pointer,
// 3. Delete workflow mutable state,
// 4. Delete history branch.
// This function is called from task processor and should not be called directly.
// It may fail at any stage and task processor will retry. All stages are idempotent.
// If process fails after stage 1 then workflow execution becomes invisible but mutable state is still there and task can be safely retried.
// Stage 2 doesn't affect mutable state neither and doesn't block retry.
// After stage 3 task can't be retried because mutable state is gone and this might leave history branch in DB.
// The history branch won't be accessible (because mutable state is deleted) and special garbage collection workflow will delete it eventually.
// Stage 4 shouldn't be done earlier because if this func fails after it, workflow execution will be accessible but won't have history (inconsistent state).
engine, err := s.GetEngine(ctx)
if err != nil {
return err
}
// Do not get namespace cache within shard lock.
_, err = s.GetNamespaceRegistry().GetNamespaceByID(namespace.ID(key.NamespaceID))
deleteVisibilityRecord := true
if err != nil {
if _, isNotFound := err.(*serviceerror.NamespaceNotFound); isNotFound {
// If namespace is not found, skip visibility record delete but proceed with other deletions.
// This case might happen during namespace deletion.
deleteVisibilityRecord = false
} else {
return err
}
}
validateCtxAndShardState := func() (context.Context, context.CancelFunc, error) {
s.wLock()
defer s.wUnlock()
ctx, cancel, err := s.newDetachedContext(ctx)
if err != nil {
return nil, nil, err
}
if err := s.errorByState(); err != nil {
cancel()
return nil, nil, err
}
return ctx, cancel, nil
}
// Don't acquire shard lock or io semaphore if all stages that require lock are already processed.
if !stage.IsProcessed(
tasks.DeleteWorkflowExecutionStageVisibility |
tasks.DeleteWorkflowExecutionStageCurrent |
tasks.DeleteWorkflowExecutionStageMutableState) {
// Wrap stage 1, 2, and 3 with function to release io semaphore with defer after stage 3.
if err = func() error {
if err := s.ioSemaphoreAcquire(ctx); err != nil {
return err
}