-
Notifications
You must be signed in to change notification settings - Fork 291
/
AzureStorageOrchestrationService.cs
1939 lines (1672 loc) · 86.8 KB
/
AzureStorageOrchestrationService.cs
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
// ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
namespace DurableTask.AzureStorage
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DurableTask.AzureStorage.Messaging;
using DurableTask.AzureStorage.Monitoring;
using DurableTask.AzureStorage.Partitioning;
using DurableTask.AzureStorage.Storage;
using DurableTask.AzureStorage.Tracking;
using DurableTask.Core;
using DurableTask.Core.Exceptions;
using DurableTask.Core.History;
using Microsoft.WindowsAzure.Storage;
using Newtonsoft.Json;
/// <summary>
/// Orchestration service provider for the Durable Task Framework which uses Azure Storage as the durable store.
/// </summary>
public sealed class AzureStorageOrchestrationService :
IOrchestrationService,
IOrchestrationServiceClient,
IDisposable
{
static readonly HistoryEvent[] EmptyHistoryEventList = new HistoryEvent[0];
static readonly OrchestrationInstance EmptySourceInstance = new OrchestrationInstance
{
InstanceId = string.Empty,
ExecutionId = string.Empty
};
readonly AzureStorageClient azureStorageClient;
readonly AzureStorageOrchestrationServiceSettings settings;
readonly AzureStorageOrchestrationServiceStats stats;
readonly ConcurrentDictionary<string, ControlQueue> allControlQueues;
readonly WorkItemQueue workItemQueue;
readonly ConcurrentDictionary<string, ActivitySession> activeActivitySessions;
readonly MessageManager messageManager;
readonly ITrackingStore trackingStore;
readonly ResettableLazy<Task> taskHubCreator;
readonly BlobLeaseManager leaseManager;
readonly AppLeaseManager appLeaseManager;
readonly OrchestrationSessionManager orchestrationSessionManager;
readonly IPartitionManager partitionManager;
readonly object hubCreationLock;
bool isStarted;
Task statsLoop;
CancellationTokenSource shutdownSource;
/// <summary>
/// Initializes a new instance of the <see cref="AzureStorageOrchestrationService"/> class.
/// </summary>
/// <param name="settings">The settings used to configure the orchestration service.</param>
public AzureStorageOrchestrationService(AzureStorageOrchestrationServiceSettings settings)
: this(settings, null)
{ }
/// <inheritdoc/>
public override string ToString()
{
string blobAccountName = this.azureStorageClient.BlobAccountName;
string queueAccountName = this.azureStorageClient.QueueAccountName;
string tableAccountName = this.azureStorageClient.TableAccountName;
return blobAccountName == queueAccountName && blobAccountName == tableAccountName
? $"AzureStorageOrchestrationService on {blobAccountName}"
: $"AzureStorageOrchestrationService on {blobAccountName} for blobs, {queueAccountName} for queues, and {tableAccountName} for tables";
}
/// <summary>
/// Initializes a new instance of the <see cref="AzureStorageOrchestrationService"/> class with a custom instance store.
/// </summary>
/// <param name="settings">The settings used to configure the orchestration service.</param>
/// <param name="customInstanceStore">Custom UserDefined Instance store to be used with the AzureStorageOrchestrationService</param>
public AzureStorageOrchestrationService(AzureStorageOrchestrationServiceSettings settings, IOrchestrationServiceInstanceStore customInstanceStore)
{
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
ValidateSettings(settings);
this.settings = settings;
this.azureStorageClient = new AzureStorageClient(settings);
this.stats = this.azureStorageClient.Stats;
string compressedMessageBlobContainerName = $"{settings.TaskHubName.ToLowerInvariant()}-largemessages";
this.messageManager = new MessageManager(this.settings, this.azureStorageClient, compressedMessageBlobContainerName);
this.allControlQueues = new ConcurrentDictionary<string, ControlQueue>();
for (int index = 0; index < this.settings.PartitionCount; index++)
{
var controlQueueName = GetControlQueueName(this.settings.TaskHubName, index);
ControlQueue controlQueue = new ControlQueue(this.azureStorageClient, controlQueueName, this.messageManager);
this.allControlQueues.TryAdd(controlQueue.Name, controlQueue);
}
var workItemQueueName = GetWorkItemQueueName(this.settings.TaskHubName);
this.workItemQueue = new WorkItemQueue(this.azureStorageClient, workItemQueueName, this.messageManager);
if (customInstanceStore == null)
{
this.trackingStore = new AzureTableTrackingStore(this.azureStorageClient, this.messageManager);
}
else
{
this.trackingStore = new InstanceStoreBackedTrackingStore(customInstanceStore);
}
this.activeActivitySessions = new ConcurrentDictionary<string, ActivitySession>(StringComparer.OrdinalIgnoreCase);
this.hubCreationLock = new object();
this.taskHubCreator = new ResettableLazy<Task>(
this.GetTaskHubCreatorTask,
LazyThreadSafetyMode.ExecutionAndPublication);
this.leaseManager = GetBlobLeaseManager(
this.azureStorageClient,
"default");
this.orchestrationSessionManager = new OrchestrationSessionManager(
this.azureStorageClient.QueueAccountName,
this.settings,
this.stats,
this.trackingStore);
if (this.settings.UseLegacyPartitionManagement)
{
this.partitionManager = new LegacyPartitionManager(
this,
this.azureStorageClient);
}
else
{
this.partitionManager = new SafePartitionManager(
this,
this.azureStorageClient,
this.orchestrationSessionManager);
}
this.appLeaseManager = new AppLeaseManager(
this.azureStorageClient,
this.partitionManager,
this.settings.TaskHubName.ToLowerInvariant() + "-applease",
this.settings.TaskHubName.ToLowerInvariant() + "-appleaseinfo",
this.settings.AppLeaseOptions);
}
internal string WorkerId => this.settings.WorkerId;
internal IEnumerable<ControlQueue> AllControlQueues => this.allControlQueues.Values;
internal IEnumerable<ControlQueue> OwnedControlQueues => this.orchestrationSessionManager.Queues;
internal WorkItemQueue WorkItemQueue => this.workItemQueue;
internal ITrackingStore TrackingStore => this.trackingStore;
internal static string GetControlQueueName(string taskHub, int partitionIndex)
{
return GetQueueName(taskHub, $"control-{partitionIndex:00}");
}
internal static string GetWorkItemQueueName(string taskHub)
{
return GetQueueName(taskHub, "workitems");
}
internal static string GetQueueName(string taskHub, string suffix)
{
if (string.IsNullOrEmpty(taskHub))
{
throw new ArgumentNullException(nameof(taskHub));
}
string queueName = $"{taskHub.ToLowerInvariant()}-{suffix}";
return queueName;
}
internal static BlobLeaseManager GetBlobLeaseManager(
AzureStorageClient azureStorageClient,
string leaseType)
{
return new BlobLeaseManager(
azureStorageClient,
leaseContainerName: azureStorageClient.Settings.TaskHubName.ToLowerInvariant() + "-leases",
leaseType: leaseType);
}
static void ValidateSettings(AzureStorageOrchestrationServiceSettings settings)
{
if (settings.ControlQueueBatchSize > 32)
{
throw new ArgumentOutOfRangeException(nameof(settings), "The control queue batch size must not exceed 32.");
}
if (settings.PartitionCount < 1 || settings.PartitionCount > 16)
{
throw new ArgumentOutOfRangeException(nameof(settings), "The number of partitions must be a positive integer and no greater than 16.");
}
// TODO: More validation.
}
#region IOrchestrationService
/// <summary>
/// Gets or sets the maximum number of orchestrations that can be processed concurrently on a single node.
/// </summary>
public int MaxConcurrentTaskOrchestrationWorkItems
{
get { return this.settings.MaxConcurrentTaskOrchestrationWorkItems; }
}
/// <summary>
/// Gets or sets the maximum number of work items that can be processed concurrently on a single node.
/// </summary>
public int MaxConcurrentTaskActivityWorkItems
{
get { return this.settings.MaxConcurrentTaskActivityWorkItems; }
}
/// <summary>
/// Should we carry over unexecuted raised events to the next iteration of an orchestration on ContinueAsNew
/// </summary>
public BehaviorOnContinueAsNew EventBehaviourForContinueAsNew
{
get { return this.settings.EventBehaviourForContinueAsNew; }
}
// We always leave the dispatcher counts at one unless we can find a customer workload that requires more.
/// <inheritdoc />
public int TaskActivityDispatcherCount { get; } = 1;
/// <inheritdoc />
public int TaskOrchestrationDispatcherCount { get; } = 1;
#region Management Operations (Create/Delete/Start/Stop)
/// <summary>
/// Deletes and creates the neccesary Azure Storage resources for the orchestration service.
/// </summary>
public async Task CreateAsync()
{
await this.DeleteAsync();
await this.EnsureTaskHubAsync();
}
/// <summary>
/// Creates the necessary Azure Storage resources for the orchestration service if they don't already exist.
/// </summary>
public Task CreateIfNotExistsAsync()
{
return this.EnsureTaskHubAsync();
}
async Task EnsureTaskHubAsync()
{
try
{
await this.taskHubCreator.Value;
}
catch (Exception e)
{
this.settings.Logger.GeneralError(
this.azureStorageClient.QueueAccountName,
this.settings.TaskHubName,
$"Failed to create the task hub: {e}");
// Don't want to cache the failed task
this.taskHubCreator.Reset();
throw;
}
}
// Internal logic used by the lazy taskHubCreator
async Task GetTaskHubCreatorTask()
{
TaskHubInfo hubInfo = GetTaskHubInfo(this.settings.TaskHubName, this.settings.PartitionCount);
await this.appLeaseManager.CreateContainerIfNotExistsAsync();
await this.partitionManager.CreateLeaseStore();
var tasks = new List<Task>();
tasks.Add(this.trackingStore.CreateAsync());
tasks.Add(this.workItemQueue.CreateIfNotExistsAsync());
foreach (ControlQueue controlQueue in this.allControlQueues.Values)
{
tasks.Add(controlQueue.CreateIfNotExistsAsync());
tasks.Add(this.partitionManager.CreateLease(controlQueue.Name));
}
await Task.WhenAll(tasks.ToArray());
}
/// <summary>
/// Deletes the Azure Storage resources used by the orchestration service.
/// </summary>
public Task DeleteAsync()
{
return this.DeleteAsync(deleteInstanceStore: true);
}
/// <inheritdoc />
public async Task CreateAsync(bool recreateInstanceStore)
{
if (recreateInstanceStore)
{
await DeleteTrackingStore();
this.taskHubCreator.Reset();
}
await this.taskHubCreator.Value;
}
/// <inheritdoc />
public async Task DeleteAsync(bool deleteInstanceStore)
{
var tasks = new List<Task>();
foreach (string partitionId in this.allControlQueues.Keys)
{
if (this.allControlQueues.TryGetValue(partitionId, out ControlQueue controlQueue))
{
tasks.Add(controlQueue.DeleteIfExistsAsync());
}
}
tasks.Add(this.workItemQueue.DeleteIfExistsAsync());
if (deleteInstanceStore)
{
tasks.Add(DeleteTrackingStore());
}
tasks.Add(this.partitionManager.DeleteLeases());
tasks.Add(this.appLeaseManager.DeleteContainerAsync());
tasks.Add(this.messageManager.DeleteContainerAsync());
await Task.WhenAll(tasks.ToArray());
this.taskHubCreator.Reset();
}
private Task DeleteTrackingStore()
{
return this.trackingStore.DeleteAsync();
}
/// <inheritdoc />
public async Task StartAsync()
{
if (this.isStarted)
{
throw new InvalidOperationException("The orchestration service has already started.");
}
await this.CreateIfNotExistsAsync();
await this.trackingStore.StartAsync();
// Disable nagling to improve storage access latency:
// https://blogs.msdn.microsoft.com/windowsazurestorage/2010/06/25/nagles-algorithm-is-not-friendly-towards-small-requests/
// Ad-hoc testing has shown very nice improvements (20%-50% drop in queue message age for simple scenarios).
ServicePointManager.FindServicePoint(this.workItemQueue.Uri).UseNagleAlgorithm = false;
this.shutdownSource?.Dispose();
this.shutdownSource = new CancellationTokenSource();
this.statsLoop = Task.Run(() => this.ReportStatsLoop(this.shutdownSource.Token));
await this.appLeaseManager.StartAsync();
this.isStarted = true;
}
/// <inheritdoc />
public Task StopAsync()
{
return this.StopAsync(isForced: false);
}
/// <inheritdoc />
public async Task StopAsync(bool isForced)
{
this.shutdownSource.Cancel();
await this.statsLoop;
await this.appLeaseManager.StopAsync();
this.isStarted = false;
}
async Task ReportStatsLoop(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
this.ReportStats();
}
catch (TaskCanceledException)
{
// shutting down
break;
}
catch (Exception e)
{
this.settings.Logger.GeneralError(
this.azureStorageClient.QueueAccountName,
this.settings.TaskHubName,
$"Unexpected error in {nameof(ReportStatsLoop)}: {e}");
}
}
// Final reporting of stats
this.ReportStats();
}
void ReportStats()
{
// The following stats are reported on a per-interval basis.
long storageRequests = this.stats.StorageRequests.Reset();
long messagesSent = this.stats.MessagesSent.Reset();
long messagesRead = this.stats.MessagesRead.Reset();
long messagesUpdated = this.stats.MessagesUpdated.Reset();
long tableEntitiesWritten = this.stats.TableEntitiesWritten.Reset();
long tableEntitiesRead = this.stats.TableEntitiesRead.Reset();
// The remaining stats are running numbers
this.orchestrationSessionManager.GetStats(
out int pendingOrchestratorInstances,
out int pendingOrchestrationMessages,
out int activeOrchestrationSessions);
this.settings.Logger.OrchestrationServiceStats(
this.azureStorageClient.QueueAccountName,
this.settings.TaskHubName,
storageRequests,
messagesSent,
messagesRead,
messagesUpdated,
tableEntitiesWritten,
tableEntitiesRead,
pendingOrchestratorInstances,
pendingOrchestrationMessages,
activeOrchestrationSessions,
this.stats.ActiveActivityExecutions.Value);
}
internal async Task OnIntentLeaseAquiredAsync(BlobLease lease)
{
var controlQueue = new ControlQueue(this.azureStorageClient, lease.PartitionId, this.messageManager);
await controlQueue.CreateIfNotExistsAsync();
this.orchestrationSessionManager.ResumeListeningIfOwnQueue(lease.PartitionId, controlQueue, this.shutdownSource.Token);
}
internal Task OnIntentLeaseReleasedAsync(BlobLease lease, CloseReason reason)
{
// Mark the queue as released so it will stop grabbing new messages.
this.orchestrationSessionManager.ReleaseQueue(lease.PartitionId, reason, "Intent LeaseCollectionBalancer");
return Utils.CompletedTask;
}
internal async Task OnOwnershipLeaseAquiredAsync(BlobLease lease)
{
var controlQueue = new ControlQueue(this.azureStorageClient, lease.PartitionId, this.messageManager);
await controlQueue.CreateIfNotExistsAsync();
this.orchestrationSessionManager.AddQueue(lease.PartitionId, controlQueue, this.shutdownSource.Token);
this.allControlQueues[lease.PartitionId] = controlQueue;
}
internal Task OnOwnershipLeaseReleasedAsync(BlobLease lease, CloseReason reason)
{
this.orchestrationSessionManager.RemoveQueue(lease.PartitionId, reason, "Ownership LeaseCollectionBalancer");
return Utils.CompletedTask;
}
// Used for testing
internal Task<IEnumerable<BlobLease>> ListBlobLeasesAsync()
{
return this.partitionManager.GetOwnershipBlobLeases();
}
internal static async Task<Queue[]> GetControlQueuesAsync(
AzureStorageClient azureStorageClient,
int defaultPartitionCount)
{
if (azureStorageClient == null)
{
throw new ArgumentNullException(nameof(azureStorageClient));
}
string taskHub = azureStorageClient.Settings.TaskHubName;
BlobLeaseManager inactiveLeaseManager = GetBlobLeaseManager(azureStorageClient, "inactive");
TaskHubInfo hubInfo = await inactiveLeaseManager.GetOrCreateTaskHubInfoAsync(
GetTaskHubInfo(taskHub, defaultPartitionCount),
checkIfStale: false);
var controlQueues = new Queue[hubInfo.PartitionCount];
for (int i = 0; i < hubInfo.PartitionCount; i++)
{
controlQueues[i] = azureStorageClient.GetQueueReference(GetControlQueueName(taskHub, i));
}
return controlQueues;
}
internal static Queue GetWorkItemQueue(AzureStorageClient azureStorageClient)
{
string queueName = GetWorkItemQueueName(azureStorageClient.Settings.TaskHubName);
return azureStorageClient.GetQueueReference(queueName);
}
static TaskHubInfo GetTaskHubInfo(string taskHub, int partitionCount)
{
return new TaskHubInfo(taskHub, DateTime.UtcNow, partitionCount);
}
#endregion
#region Orchestration Work Item Methods
/// <inheritdoc />
public async Task<TaskOrchestrationWorkItem> LockNextTaskOrchestrationWorkItemAsync(
TimeSpan receiveTimeout,
CancellationToken cancellationToken)
{
Guid traceActivityId = StartNewLogicalTraceScope(useExisting: true);
await this.EnsureTaskHubAsync();
using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, this.shutdownSource.Token))
{
OrchestrationSession session = null;
TaskOrchestrationWorkItem orchestrationWorkItem = null;
try
{
// This call will block until the next session is ready
session = await this.orchestrationSessionManager.GetNextSessionAsync(linkedCts.Token);
if (session == null)
{
return null;
}
// Make sure we still own the partition. If not, abandon the session.
if (session.ControlQueue.IsReleased)
{
await this.AbandonAndReleaseSessionAsync(session);
return null;
}
session.StartNewLogicalTraceScope();
List<MessageData> outOfOrderMessages = null;
foreach (MessageData message in session.CurrentMessageBatch)
{
if (session.IsOutOfOrderMessage(message))
{
if (outOfOrderMessages == null)
{
outOfOrderMessages = new List<MessageData>();
}
// This can happen if a lease change occurs and a new node receives a message for an
// orchestration that has not yet checkpointed its history. We abandon such messages
// so that they can be reprocessed after the history checkpoint has completed.
this.settings.Logger.ReceivedOutOfOrderMessage(
this.azureStorageClient.QueueAccountName,
this.settings.TaskHubName,
session.Instance.InstanceId,
session.Instance.ExecutionId,
session.ControlQueue.Name,
message.TaskMessage.Event.EventType.ToString(),
Utils.GetTaskEventId(message.TaskMessage.Event),
message.OriginalQueueMessage.Id,
message.Episode.GetValueOrDefault(-1),
session.LastCheckpointTime);
outOfOrderMessages.Add(message);
}
else
{
session.TraceProcessingMessage(message, isExtendedSession: false);
}
}
if (outOfOrderMessages?.Count > 0)
{
// This will also remove the messages from the current batch.
await this.AbandonMessagesAsync(session, outOfOrderMessages);
}
if (session.CurrentMessageBatch.Count == 0)
{
// All messages were removed. Release the work item.
await this.AbandonAndReleaseSessionAsync(session);
return null;
}
// Create or restore Correlation TraceContext
TraceContextBase currentRequestTraceContext = null;
CorrelationTraceClient.Propagate(
() =>
{
var isReplaying = session.RuntimeState.ExecutionStartedEvent?.IsPlayed ?? false;
TraceContextBase parentTraceContext = GetParentTraceContext(session);
currentRequestTraceContext = GetRequestTraceContext(isReplaying, parentTraceContext);
});
orchestrationWorkItem = new TaskOrchestrationWorkItem
{
InstanceId = session.Instance.InstanceId,
LockedUntilUtc = session.CurrentMessageBatch.Min(msg => msg.OriginalQueueMessage.NextVisibleTime.Value.UtcDateTime),
NewMessages = session.CurrentMessageBatch.Select(m => m.TaskMessage).ToList(),
OrchestrationRuntimeState = session.RuntimeState,
Session = this.settings.ExtendedSessionsEnabled ? session : null,
TraceContext = currentRequestTraceContext,
};
if (!this.IsExecutableInstance(session.RuntimeState, orchestrationWorkItem.NewMessages, out string warningMessage))
{
// If all messages belong to the same execution ID, then all of them need to be discarded.
// However, it's also possible to have messages for *any* execution ID batched together with messages
// to a *specific* (non-executable) execution ID. Those messages should *not* be discarded since
// they might be consumable by another orchestration with the same instance id but different execution ID.
var messagesToDiscard = new List<MessageData>();
var messagesToAbandon = new List<MessageData>();
foreach (MessageData msg in session.CurrentMessageBatch)
{
if (msg.TaskMessage.OrchestrationInstance.ExecutionId == session.Instance.ExecutionId)
{
messagesToDiscard.Add(msg);
}
else
{
messagesToAbandon.Add(msg);
}
}
// If no messages have a matching execution ID, then delete all of them. This means all the
// messages are external (external events, termination, etc.) and were sent to an instance that
// doesn't exist or is no longer in a running state.
if (messagesToDiscard.Count == 0)
{
messagesToDiscard.AddRange(messagesToAbandon);
messagesToAbandon.Clear();
}
// Add all abandoned messages to the deferred list. These messages will not be deleted right now.
// If they can be matched with another orchestration, then great. Otherwise they will be deleted
// the next time they are picked up.
messagesToAbandon.ForEach(session.DeferMessage);
var eventListBuilder = new StringBuilder(orchestrationWorkItem.NewMessages.Count * 40);
foreach (MessageData msg in messagesToDiscard)
{
eventListBuilder.Append(msg.TaskMessage.Event.EventType.ToString()).Append(',');
}
this.settings.Logger.DiscardingWorkItem(
this.azureStorageClient.QueueAccountName,
this.settings.TaskHubName,
session.Instance.InstanceId,
session.Instance.ExecutionId,
orchestrationWorkItem.NewMessages.Count,
session.RuntimeState.Events.Count,
eventListBuilder.ToString(0, eventListBuilder.Length - 1) /* remove trailing comma */,
warningMessage);
// The instance has already completed or never existed. Delete this message batch.
await this.DeleteMessageBatchAsync(session, messagesToDiscard);
await this.ReleaseTaskOrchestrationWorkItemAsync(orchestrationWorkItem);
return null;
}
return orchestrationWorkItem;
}
catch (OperationCanceledException)
{
if (session != null)
{
// host is shutting down - release any queued messages
await this.AbandonAndReleaseSessionAsync(session);
}
return null;
}
catch (Exception e)
{
this.settings.Logger.OrchestrationProcessingFailure(
this.azureStorageClient.QueueAccountName,
this.settings.TaskHubName,
session?.Instance.InstanceId ?? string.Empty,
session?.Instance.ExecutionId ?? string.Empty,
e.ToString());
if (orchestrationWorkItem != null)
{
// The work-item needs to be released so that it can be retried later.
await this.ReleaseTaskOrchestrationWorkItemAsync(orchestrationWorkItem);
}
throw;
}
}
}
TraceContextBase GetParentTraceContext(OrchestrationSession session)
{
var messages = session.CurrentMessageBatch;
TraceContextBase parentTraceContext = null;
bool foundEventRaised = false;
foreach(var message in messages)
{
if (message.SerializableTraceContext != null)
{
var traceContext = TraceContextBase.Restore(message.SerializableTraceContext);
switch(message.TaskMessage.Event)
{
// Dependency Execution finished.
case TaskCompletedEvent tc:
case TaskFailedEvent tf:
case SubOrchestrationInstanceCompletedEvent sc:
case SubOrchestrationInstanceFailedEvent sf:
if (traceContext.OrchestrationTraceContexts.Count != 0)
{
var orchestrationDependencyTraceContext = traceContext.OrchestrationTraceContexts.Pop();
CorrelationTraceClient.TrackDepencencyTelemetry(orchestrationDependencyTraceContext);
}
parentTraceContext = traceContext;
break;
// Retry and Timer that includes Dependency Telemetry needs to remove
case TimerFiredEvent tf:
if (traceContext.OrchestrationTraceContexts.Count != 0)
traceContext.OrchestrationTraceContexts.Pop();
parentTraceContext = traceContext;
break;
default:
// When internal error happens, multiple message could come, however, it should not be prioritized.
if (parentTraceContext == null ||
parentTraceContext.OrchestrationTraceContexts.Count < traceContext.OrchestrationTraceContexts.Count)
{
parentTraceContext = traceContext;
}
break;
}
} else
{
// In this case, we set the parentTraceContext later in this method
if (message.TaskMessage.Event is EventRaisedEvent)
{
foundEventRaised = true;
}
}
}
// When EventRaisedEvent is present, it will not, out of the box, share the same operation
// identifiers as the rest of the trace events. Thus, we need to explicitely group it with the
// rest of events by using the context string of the ExecutionStartedEvent.
if (parentTraceContext is null && foundEventRaised)
{
// Restore the parent trace context from the correlation state of the execution start event
string traceContextString = session.RuntimeState.ExecutionStartedEvent?.Correlation;
parentTraceContext = TraceContextBase.Restore(traceContextString);
}
return parentTraceContext ?? TraceContextFactory.Empty;
}
static bool IsActivityOrOrchestrationFailedOrCompleted(IList<MessageData> messages)
{
foreach(var message in messages)
{
if (message.TaskMessage.Event is DurableTask.Core.History.SubOrchestrationInstanceCompletedEvent ||
message.TaskMessage.Event is DurableTask.Core.History.SubOrchestrationInstanceFailedEvent ||
message.TaskMessage.Event is DurableTask.Core.History.TaskCompletedEvent ||
message.TaskMessage.Event is DurableTask.Core.History.TaskFailedEvent ||
message.TaskMessage.Event is DurableTask.Core.History.TimerFiredEvent)
{
return true;
}
}
return false;
}
static TraceContextBase GetRequestTraceContext(bool isReplaying, TraceContextBase parentTraceContext)
{
TraceContextBase currentRequestTraceContext = TraceContextFactory.Empty;
if (!isReplaying)
{
var name = $"{TraceConstants.Orchestrator}";
currentRequestTraceContext = TraceContextFactory.Create(name);
currentRequestTraceContext.SetParentAndStart(parentTraceContext);
currentRequestTraceContext.TelemetryType = TelemetryType.Request;
currentRequestTraceContext.OrchestrationTraceContexts.Push(currentRequestTraceContext);
}
else
{
// TODO Chris said that there is not case in this root. Double check or write test to prove it.
bool noCorrelation = parentTraceContext.OrchestrationTraceContexts.Count == 0;
if (noCorrelation)
{
// Terminate, external events, etc. are examples of messages that not contain any trace context.
// In those cases, we just return an empty trace context and continue on.
return TraceContextFactory.Empty;
}
currentRequestTraceContext = parentTraceContext.GetCurrentOrchestrationRequestTraceContext();
currentRequestTraceContext.OrchestrationTraceContexts = parentTraceContext.OrchestrationTraceContexts.Clone();
currentRequestTraceContext.IsReplay = true;
return currentRequestTraceContext;
}
return currentRequestTraceContext;
}
internal static Guid StartNewLogicalTraceScope(bool useExisting)
{
// Starting in DurableTask.Core v2.4.0, a new trace activity will already be
// started and we don't need to start one ourselves.
// TODO: When distributed correlation is merged, use that instead.
Guid traceActivityId;
if (useExisting && EventSource.CurrentThreadActivityId != Guid.Empty)
{
traceActivityId = EventSource.CurrentThreadActivityId;
}
else
{
// No ambient trace activity ID was found or doesn't apply - create a new one
traceActivityId = Guid.NewGuid();
}
AnalyticsEventSource.SetLogicalTraceActivityId(traceActivityId);
return traceActivityId;
}
internal static void TraceMessageReceived(AzureStorageOrchestrationServiceSettings settings, MessageData data, string storageAccountName)
{
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
TaskMessage taskMessage = data.TaskMessage;
QueueMessage queueMessage = data.OriginalQueueMessage;
settings.Logger.ReceivedMessage(
data.ActivityId,
storageAccountName,
settings.TaskHubName,
taskMessage.Event.EventType.ToString(),
Utils.GetTaskEventId(taskMessage.Event),
taskMessage.OrchestrationInstance.InstanceId,
taskMessage.OrchestrationInstance.ExecutionId,
queueMessage.Id,
Math.Max(0, (int)DateTimeOffset.UtcNow.Subtract(queueMessage.InsertionTime.Value).TotalMilliseconds),
queueMessage.DequeueCount,
queueMessage.NextVisibleTime.GetValueOrDefault().DateTime.ToString("o"),
data.TotalMessageSizeBytes,
data.QueueName /* PartitionId */,
data.SequenceNumber,
data.Episode.GetValueOrDefault(-1));
}
bool IsExecutableInstance(OrchestrationRuntimeState runtimeState, IList<TaskMessage> newMessages, out string message)
{
if (runtimeState.ExecutionStartedEvent == null && !newMessages.Any(msg => msg.Event is ExecutionStartedEvent))
{
var instanceId = newMessages[0].OrchestrationInstance.InstanceId;
if (DurableTask.Core.Common.Entities.AutoStart(instanceId, newMessages))
{
message = null;
return true;
}
else
{
// A non-zero event count usually happens when an instance's history is overwritten by a
// new instance or by a ContinueAsNew. When history is overwritten by new instances, we
// overwrite the old history with new history (with a new execution ID), but this is done
// gradually as we build up the new history over time. If we haven't yet overwritten *all*
// the old history and we receive a message from the old instance (this happens frequently
// with canceled durable timer messages) we'll end up loading just the history that hasn't
// been fully overwritten. We know it's invalid because it's missing the ExecutionStartedEvent.
message = runtimeState.Events.Count == 0 ? "No such instance" : "Invalid history (may have been overwritten by a newer instance)";
return false;
}
}
if (runtimeState.ExecutionStartedEvent != null &&
runtimeState.OrchestrationStatus != OrchestrationStatus.Running &&
runtimeState.OrchestrationStatus != OrchestrationStatus.Pending)
{
message = $"Instance is {runtimeState.OrchestrationStatus}";
return false;
}
message = null;
return true;
}
async Task AbandonAndReleaseSessionAsync(OrchestrationSession session)
{
try
{
await this.AbandonSessionAsync(session);
}
finally
{
await this.ReleaseSessionAsync(session.Instance.InstanceId);
}
}
/// <inheritdoc />
public async Task CompleteTaskOrchestrationWorkItemAsync(
TaskOrchestrationWorkItem workItem,
OrchestrationRuntimeState newOrchestrationRuntimeState,
IList<TaskMessage> outboundMessages,
IList<TaskMessage> orchestratorMessages,
IList<TaskMessage> timerMessages,
TaskMessage continuedAsNewMessage,
OrchestrationState orchestrationState)
{
OrchestrationSession session;
if (!this.orchestrationSessionManager.TryGetExistingSession(workItem.InstanceId, out session))
{
this.settings.Logger.AssertFailure(
this.azureStorageClient.QueueAccountName,
this.settings.TaskHubName,
$"{nameof(CompleteTaskOrchestrationWorkItemAsync)}: Session for instance {workItem.InstanceId} was not found!");
return;
}
session.StartNewLogicalTraceScope();
OrchestrationRuntimeState runtimeState = newOrchestrationRuntimeState ?? workItem.OrchestrationRuntimeState;
string instanceId = workItem.InstanceId;
string executionId = runtimeState.OrchestrationInstance?.ExecutionId;
if (executionId == null)
{
this.settings.Logger.GeneralWarning(
this.azureStorageClient.QueueAccountName,
this.settings.TaskHubName,
$"{nameof(CompleteTaskOrchestrationWorkItemAsync)}: Could not find execution id.",
instanceId: instanceId);
}
// Correlation
CorrelationTraceClient.Propagate(() =>
{
// In case of Extended Session, Emit the Dependency Telemetry.
if (workItem.IsExtendedSession)
{
this.TrackExtendedSessionDependencyTelemetry(session);
}
});
TraceContextBase currentTraceContextBaseOnComplete = null;
CorrelationTraceClient.Propagate(() =>
currentTraceContextBaseOnComplete = CreateOrRestoreRequestTraceContextWithDependencyTrackingSettings(