-
Notifications
You must be signed in to change notification settings - Fork 300
/
Copy pathAzureTableTrackingStore.cs
1254 lines (1058 loc) · 60.1 KB
/
AzureTableTrackingStore.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.Tracking
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DurableTask.AzureStorage.Monitoring;
using DurableTask.AzureStorage.Storage;
using DurableTask.Core;
using DurableTask.Core.History;
using Microsoft.WindowsAzure.Storage.Table;
/// <summary>
/// Tracking store for use with <see cref="AzureStorageOrchestrationService"/>. Uses Azure Tables and Azure Blobs to store runtime state.
/// </summary>
class AzureTableTrackingStore : TrackingStoreBase
{
const string NameProperty = "Name";
const string InputProperty = "Input";
const string ResultProperty = "Result";
const string OutputProperty = "Output";
const string RowKeyProperty = "RowKey";
const string PartitionKeyProperty = "PartitionKey";
const string SentinelRowKey = "sentinel";
const string IsCheckpointCompleteProperty = "IsCheckpointComplete";
const string CheckpointCompletedTimestampProperty = "CheckpointCompletedTimestamp";
// See https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-the-table-service-data-model#property-types
const int MaxTablePropertySizeInBytes = 60 * 1024; // 60KB to give buffer
static readonly string[] VariableSizeEntityProperties = new[]
{
NameProperty,
InputProperty,
ResultProperty,
OutputProperty,
"Reason",
"Details",
"Correlation"
};
readonly string storageAccountName;
readonly string taskHubName;
readonly AzureStorageClient azureStorageClient;
readonly AzureStorageOrchestrationServiceSettings settings;
readonly AzureStorageOrchestrationServiceStats stats;
readonly TableEntityConverter tableEntityConverter;
readonly IReadOnlyDictionary<EventType, Type> eventTypeMap;
readonly MessageManager messageManager;
public AzureTableTrackingStore(
AzureStorageClient azureStorageClient,
MessageManager messageManager)
{
this.azureStorageClient = azureStorageClient;
this.messageManager = messageManager;
this.settings = this.azureStorageClient.Settings;
this.stats = this.azureStorageClient.Stats;
this.tableEntityConverter = new TableEntityConverter();
this.taskHubName = settings.TaskHubName;
this.storageAccountName = this.azureStorageClient.TableAccountName;
string historyTableName = settings.HistoryTableName;
string instancesTableName = settings.InstanceTableName;
this.HistoryTable = this.azureStorageClient.GetTableReference(historyTableName);
this.InstancesTable = this.azureStorageClient.GetTableReference(instancesTableName);
// Use reflection to learn all the different event types supported by DTFx.
// This could have been hardcoded, but I generally try to avoid hardcoding of point-in-time DTFx knowledge.
Type historyEventType = typeof(HistoryEvent);
IEnumerable<Type> historyEventTypes = historyEventType.Assembly.GetTypes().Where(
t => !t.IsAbstract && t.IsSubclassOf(historyEventType));
PropertyInfo eventTypeProperty = historyEventType.GetProperty(nameof(HistoryEvent.EventType));
this.eventTypeMap = historyEventTypes.ToDictionary(
type => ((HistoryEvent)FormatterServices.GetUninitializedObject(type)).EventType);
}
// For testing
internal AzureTableTrackingStore(
AzureStorageOrchestrationServiceStats stats,
Table instancesTable
)
{
this.stats = stats;
this.InstancesTable = instancesTable;
this.settings = new AzureStorageOrchestrationServiceSettings();
// Have to set FetchLargeMessageDataEnabled to false, as no MessageManager is
// instantiated for this test.
this.settings.FetchLargeMessageDataEnabled = false;
}
internal Table HistoryTable { get; }
internal Table InstancesTable { get; }
/// <inheritdoc />
public override Task CreateAsync()
{
return Task.WhenAll(new Task[]
{
this.HistoryTable.CreateIfNotExistsAsync(),
this.InstancesTable.CreateIfNotExistsAsync()
});
}
/// <inheritdoc />
public override Task DeleteAsync()
{
return Task.WhenAll(new Task[]
{
this.HistoryTable.DeleteIfExistsAsync(),
this.InstancesTable.DeleteIfExistsAsync()
});
}
/// <inheritdoc />
public override async Task<bool> ExistsAsync()
{
return this.HistoryTable != null && this.InstancesTable != null && await this.HistoryTable.ExistsAsync() && await this.InstancesTable.ExistsAsync();
}
/// <inheritdoc />
public override async Task<OrchestrationHistory> GetHistoryEventsAsync(string instanceId, string expectedExecutionId, CancellationToken cancellationToken = default(CancellationToken))
{
var historyEntitiesResponseInfo = await this.GetHistoryEntitiesResponseInfoAsync(
instanceId,
expectedExecutionId,
null,
cancellationToken);
IList<DynamicTableEntity> tableEntities = historyEntitiesResponseInfo.ReturnedEntities;
IList<HistoryEvent> historyEvents;
string executionId;
DynamicTableEntity sentinel = null;
if (tableEntities.Count > 0)
{
// The most recent generation will always be in the first history event.
executionId = tableEntities[0].Properties["ExecutionId"].StringValue;
// Convert the table entities into history events.
var events = new List<HistoryEvent>(tableEntities.Count);
foreach (DynamicTableEntity entity in tableEntities)
{
if (entity.Properties["ExecutionId"].StringValue != executionId)
{
// The remaining entities are from a previous generation and can be discarded.
break;
}
// The sentinel row does not contain any history events, so save it for later
// and continue
if (entity.RowKey == SentinelRowKey)
{
sentinel = entity;
continue;
}
// Some entity properties may be stored in blob storage.
await this.DecompressLargeEntityProperties(entity);
events.Add((HistoryEvent)this.tableEntityConverter.ConvertFromTableEntity(entity, GetTypeForTableEntity));
}
historyEvents = events;
}
else
{
historyEvents = EmptyHistoryEventList;
executionId = expectedExecutionId;
}
// Read the checkpoint completion time from the sentinel row, which should always be the last row.
// A sentinel won't exist only if no instance of this ID has ever existed or the instance history
// was purged.The IsCheckpointCompleteProperty was newly added _after_ v1.6.4.
DateTime checkpointCompletionTime = DateTime.MinValue;
sentinel = sentinel ?? tableEntities.LastOrDefault(e => e.RowKey == SentinelRowKey);
string eTagValue = sentinel?.ETag;
if (sentinel != null &&
sentinel.Properties.TryGetValue(CheckpointCompletedTimestampProperty, out EntityProperty timestampProperty))
{
checkpointCompletionTime = timestampProperty.DateTime ?? DateTime.MinValue;
}
int currentEpisodeNumber = Utils.GetEpisodeNumber(historyEvents);
this.settings.Logger.FetchedInstanceHistory(
this.storageAccountName,
this.taskHubName,
instanceId,
executionId,
historyEvents.Count,
currentEpisodeNumber,
historyEntitiesResponseInfo.RequestCount,
historyEntitiesResponseInfo.ElapsedMilliseconds,
eTagValue,
checkpointCompletionTime);
return new OrchestrationHistory(historyEvents, checkpointCompletionTime, eTagValue);
}
async Task<TableEntitiesResponseInfo<DynamicTableEntity>> GetHistoryEntitiesResponseInfoAsync(string instanceId, string expectedExecutionId, IList<string> projectionColumns, CancellationToken cancellationToken = default(CancellationToken))
{
var sanitizedInstanceId = KeySanitation.EscapePartitionKey(instanceId);
string filterCondition = TableQuery.GenerateFilterCondition(PartitionKeyProperty, QueryComparisons.Equal, sanitizedInstanceId);
if (!string.IsNullOrEmpty(expectedExecutionId))
{
// Filter down to a specific generation.
var rowKeyOrExecutionId = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, SentinelRowKey),
TableOperators.Or,
TableQuery.GenerateFilterCondition("ExecutionId", QueryComparisons.Equal, expectedExecutionId));
filterCondition = TableQuery.CombineFilters(filterCondition, TableOperators.And, rowKeyOrExecutionId);
}
TableQuery<DynamicTableEntity> query = new TableQuery<DynamicTableEntity>().Where(filterCondition);
if (projectionColumns != null)
{
query.Select(projectionColumns);
}
var tableEntitiesResponseInfo = await this.HistoryTable.ExecuteQueryAsync(query, cancellationToken);
return tableEntitiesResponseInfo;
}
async Task<IList<DynamicTableEntity>> QueryHistoryAsync(TableQuery<DynamicTableEntity> query, string instanceId, CancellationToken cancellationToken)
{
var tableEntitiesResponseInfo = await this.HistoryTable.ExecuteQueryAsync(query, cancellationToken);
var entities = tableEntitiesResponseInfo.ReturnedEntities;
string executionId = entities.Count > 0 && entities.First().Properties.ContainsKey("ExecutionId") ?
entities[0].Properties["ExecutionId"].StringValue :
string.Empty;
this.settings.Logger.FetchedInstanceHistory(
this.storageAccountName,
this.taskHubName,
instanceId,
executionId,
entities.Count,
episode: -1, // We don't have enough information to get the episode number. It's also not important to have for this particular trace.
tableEntitiesResponseInfo.RequestCount,
tableEntitiesResponseInfo.ElapsedMilliseconds,
eTag: string.Empty,
DateTime.MinValue);
return entities;
}
public override async Task<IList<string>> RewindHistoryAsync(string instanceId, IList<string> failedLeaves, CancellationToken cancellationToken)
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// REWIND ALGORITHM:
// 1. Finds failed execution of specified orchestration instance to rewind
// 2. Finds failure entities to clear and over-writes them (as well as corresponding trigger events)
// 3. Identifies sub-orchestration failure(s) from parent instance and calls RewindHistoryAsync recursively on failed sub-orchestration child instance(s)
// 4. Resets orchestration status of rewound instance in instance store table to prepare it to be restarted
// 5. Returns "failedLeaves", a list of the deepest failed instances on each failed branch to revive with RewindEvent messages
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool hasFailedSubOrchestrations = false;
string sanitizedInstanceId = KeySanitation.EscapePartitionKey(instanceId);
var partitionFilter = TableQuery.GenerateFilterCondition(PartitionKeyProperty, QueryComparisons.Equal, sanitizedInstanceId);
var orchestratorStartedFilterCondition = partitionFilter;
var orchestratorStartedEventFilter = TableQuery.GenerateFilterCondition("EventType", QueryComparisons.Equal, nameof(EventType.OrchestratorStarted));
orchestratorStartedFilterCondition = TableQuery.CombineFilters(orchestratorStartedFilterCondition, TableOperators.And, orchestratorStartedEventFilter);
var orchestratorStartedQuery = new TableQuery<DynamicTableEntity>().Where(orchestratorStartedFilterCondition);
var orchestratorStartedEntities = await this.QueryHistoryAsync(orchestratorStartedQuery, instanceId, cancellationToken);
// get most recent orchestratorStarted event
var recentStartRowKey = orchestratorStartedEntities.Max(x => x.RowKey);
var recentStartRow = orchestratorStartedEntities.Where(y => y.RowKey == recentStartRowKey).ToList();
var executionId = recentStartRow[0].Properties["ExecutionId"].StringValue;
var instanceTimestamp = recentStartRow[0].Timestamp.DateTime;
var rowsToUpdateFilterCondition = partitionFilter;
var executionIdFilter = TableQuery.GenerateFilterCondition("ExecutionId", QueryComparisons.Equal, executionId);
rowsToUpdateFilterCondition = TableQuery.CombineFilters(rowsToUpdateFilterCondition, TableOperators.And, executionIdFilter);
var orchestrationStatusFilter = TableQuery.GenerateFilterCondition("OrchestrationStatus", QueryComparisons.Equal, "Failed");
var failedEventFilter = TableQuery.GenerateFilterCondition("EventType", QueryComparisons.Equal, nameof(EventType.TaskFailed));
var failedSubOrchestrationEventFilter = TableQuery.GenerateFilterCondition("EventType", QueryComparisons.Equal, nameof(EventType.SubOrchestrationInstanceFailed));
var failedQuerySegment = orchestrationStatusFilter;
failedQuerySegment = TableQuery.CombineFilters(failedQuerySegment, TableOperators.Or, failedEventFilter);
failedQuerySegment = TableQuery.CombineFilters(failedQuerySegment, TableOperators.Or, failedSubOrchestrationEventFilter);
rowsToUpdateFilterCondition = TableQuery.CombineFilters(rowsToUpdateFilterCondition, TableOperators.And, failedQuerySegment);
var rowsToUpdateQuery = new TableQuery<DynamicTableEntity>().Where(rowsToUpdateFilterCondition);
var entitiesToClear = await this.QueryHistoryAsync(rowsToUpdateQuery, instanceId, cancellationToken);
foreach (DynamicTableEntity entity in entitiesToClear)
{
if (entity.Properties["ExecutionId"].StringValue != executionId)
{
// the remaining entities are from a previous generation and can be discarded.
break;
}
if (entity.RowKey == SentinelRowKey)
{
continue;
}
// delete TaskScheduled corresponding to TaskFailed event
if (entity.Properties["EventType"].StringValue == nameof(EventType.TaskFailed))
{
var taskScheduledId = entity.Properties["TaskScheduledId"].Int32Value.Value;
var taskScheduledFilterCondition = partitionFilter;
taskScheduledFilterCondition = TableQuery.CombineFilters(taskScheduledFilterCondition, TableOperators.And, executionIdFilter);
var eventIdFilter = TableQuery.GenerateFilterConditionForInt("EventId", QueryComparisons.Equal, taskScheduledId);
taskScheduledFilterCondition = TableQuery.CombineFilters(taskScheduledFilterCondition, TableOperators.And, eventIdFilter);
var taskScheduledEventFilter = TableQuery.GenerateFilterCondition("EventType", QueryComparisons.Equal, nameof(EventType.TaskScheduled));
taskScheduledFilterCondition = TableQuery.CombineFilters(taskScheduledFilterCondition, TableOperators.And, taskScheduledEventFilter);
var taskScheduledQuery = new TableQuery<DynamicTableEntity>().Where(taskScheduledFilterCondition);
var taskScheduledEntities = await QueryHistoryAsync(taskScheduledQuery, instanceId, cancellationToken);
taskScheduledEntities[0].Properties["Reason"] = new EntityProperty("Rewound: " + taskScheduledEntities[0].Properties["EventType"].StringValue);
taskScheduledEntities[0].Properties["EventType"] = new EntityProperty(nameof(EventType.GenericEvent));
await this.HistoryTable.ReplaceAsync(taskScheduledEntities[0]);
}
// delete SubOrchestratorCreated corresponding to SubOrchestraionInstanceFailed event
if (entity.Properties["EventType"].StringValue == nameof(EventType.SubOrchestrationInstanceFailed))
{
hasFailedSubOrchestrations = true;
var subOrchestrationId = entity.Properties["TaskScheduledId"].Int32Value.Value;
var subOrchestratorCreatedFilterCondition = partitionFilter;
subOrchestratorCreatedFilterCondition = TableQuery.CombineFilters(subOrchestratorCreatedFilterCondition, TableOperators.And, executionIdFilter);
var eventIdFilter = TableQuery.GenerateFilterConditionForInt("EventId", QueryComparisons.Equal, subOrchestrationId);
subOrchestratorCreatedFilterCondition = TableQuery.CombineFilters(subOrchestratorCreatedFilterCondition, TableOperators.And, eventIdFilter);
var subOrchestrationCreatedFilter = TableQuery.GenerateFilterCondition("EventType", QueryComparisons.Equal, nameof(EventType.SubOrchestrationInstanceCreated));
subOrchestratorCreatedFilterCondition = TableQuery.CombineFilters(subOrchestratorCreatedFilterCondition, TableOperators.And, subOrchestrationCreatedFilter);
var subOrchestratorCreatedQuery = new TableQuery<DynamicTableEntity>().Where(subOrchestratorCreatedFilterCondition);
var subOrchesratrationEntities = await QueryHistoryAsync(subOrchestratorCreatedQuery, instanceId, cancellationToken);
var soInstanceId = subOrchesratrationEntities[0].Properties["InstanceId"].StringValue;
// the SubORchestrationCreatedEvent is still healthy and will not be overwritten, just marked as rewound
subOrchesratrationEntities[0].Properties["Reason"] = new EntityProperty("Rewound: " + subOrchesratrationEntities[0].Properties["EventType"].StringValue);
await this.HistoryTable.ReplaceAsync(subOrchesratrationEntities[0]);
// recursive call to clear out failure events on child instances
await this.RewindHistoryAsync(soInstanceId, failedLeaves, cancellationToken);
}
// "clear" failure event by making RewindEvent: replay ignores row while dummy event preserves rowKey
entity.Properties["Reason"] = new EntityProperty("Rewound: " + entity.Properties["EventType"].StringValue);
entity.Properties["EventType"] = new EntityProperty(nameof(EventType.GenericEvent));
await this.HistoryTable.ReplaceAsync(entity);
}
// reset orchestration status in instance store table
await UpdateStatusForRewindAsync(instanceId);
if (!hasFailedSubOrchestrations)
{
failedLeaves.Add(instanceId);
}
return failedLeaves;
}
/// <inheritdoc />
public override async Task<IList<OrchestrationState>> GetStateAsync(string instanceId, bool allExecutions, bool fetchInput)
{
return new[] { await this.GetStateAsync(instanceId, executionId: null, fetchInput: fetchInput) };
}
#nullable enable
/// <inheritdoc />
public override async Task<OrchestrationState?> GetStateAsync(string instanceId, string executionId, bool fetchInput)
{
InstanceStatus? instanceStatus = await this.FetchInstanceStatusInternalAsync(instanceId, fetchInput);
return instanceStatus?.State;
}
/// <inheritdoc />
public override Task<InstanceStatus?> FetchInstanceStatusAsync(string instanceId)
{
return this.FetchInstanceStatusInternalAsync(instanceId, fetchInput: false);
}
/// <inheritdoc />
async Task<InstanceStatus?> FetchInstanceStatusInternalAsync(string instanceId, bool fetchInput)
{
if (instanceId == null)
{
throw new ArgumentNullException(nameof(instanceId));
}
var queryCondition = new OrchestrationInstanceStatusQueryCondition
{
InstanceId = instanceId,
FetchInput = fetchInput,
};
var tableEntitiesResponseInfo = await this.InstancesTable.ExecuteQueryAsync(queryCondition.ToTableQuery<DynamicTableEntity>());
var tableEntity = tableEntitiesResponseInfo.ReturnedEntities.FirstOrDefault();
OrchestrationState? orchestrationState = null;
if (tableEntity != null)
{
orchestrationState = await this.ConvertFromAsync(tableEntity);
}
this.settings.Logger.FetchedInstanceStatus(
this.storageAccountName,
this.taskHubName,
instanceId,
orchestrationState?.OrchestrationInstance.ExecutionId ?? string.Empty,
orchestrationState?.OrchestrationStatus.ToString() ?? "NotFound",
tableEntitiesResponseInfo.ElapsedMilliseconds);
if (tableEntity == null || orchestrationState == null)
{
return null;
}
return new InstanceStatus(orchestrationState, tableEntity.ETag);
}
#nullable disable
Task<OrchestrationState> ConvertFromAsync(DynamicTableEntity tableEntity)
{
var properties = tableEntity.Properties;
var orchestrationInstanceStatus = ConvertFromAsync(properties);
var instanceId = KeySanitation.UnescapePartitionKey(tableEntity.PartitionKey);
return ConvertFromAsync(orchestrationInstanceStatus, instanceId);
}
static OrchestrationInstanceStatus ConvertFromAsync(IDictionary<string, EntityProperty> properties)
{
var orchestrationInstanceStatus = new OrchestrationInstanceStatus();
var type = typeof(OrchestrationInstanceStatus);
foreach (var pair in properties)
{
var property = type.GetProperty(pair.Key);
if (property != null)
{
var value = pair.Value;
if (value != null)
{
if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
{
property.SetValue(orchestrationInstanceStatus, value.DateTime);
}
else
{
property.SetValue(orchestrationInstanceStatus, value.StringValue);
}
}
}
}
return orchestrationInstanceStatus;
}
async Task<OrchestrationState> ConvertFromAsync(OrchestrationInstanceStatus orchestrationInstanceStatus, string instanceId)
{
var orchestrationState = new OrchestrationState();
if (!Enum.TryParse(orchestrationInstanceStatus.RuntimeStatus, out orchestrationState.OrchestrationStatus))
{
// This is not expected, but could happen if there is invalid data in the Instances table.
orchestrationState.OrchestrationStatus = (OrchestrationStatus)(-1);
}
orchestrationState.OrchestrationInstance = new OrchestrationInstance
{
InstanceId = instanceId,
ExecutionId = orchestrationInstanceStatus.ExecutionId,
};
orchestrationState.Name = orchestrationInstanceStatus.Name;
orchestrationState.Version = orchestrationInstanceStatus.Version;
orchestrationState.Status = orchestrationInstanceStatus.CustomStatus;
orchestrationState.CreatedTime = orchestrationInstanceStatus.CreatedTime;
orchestrationState.CompletedTime = orchestrationInstanceStatus.CompletedTime.GetValueOrDefault();
orchestrationState.LastUpdatedTime = orchestrationInstanceStatus.LastUpdatedTime;
orchestrationState.Input = orchestrationInstanceStatus.Input;
orchestrationState.Output = orchestrationInstanceStatus.Output;
orchestrationState.ScheduledStartTime = orchestrationInstanceStatus.ScheduledStartTime;
if (this.settings.FetchLargeMessageDataEnabled)
{
orchestrationState.Input = await this.messageManager.FetchLargeMessageIfNecessary(orchestrationState.Input);
orchestrationState.Output = await this.messageManager.FetchLargeMessageIfNecessary(orchestrationState.Output);
}
return orchestrationState;
}
/// <inheritdoc />
public override async Task<IList<OrchestrationState>> GetStateAsync(IEnumerable<string> instanceIds)
{
if (instanceIds == null || !instanceIds.Any())
{
return Array.Empty<OrchestrationState>();
}
// In theory this could exceed MaxStorageOperationConcurrency, but the hard maximum of parallel requests is tied to control queue
// batch size, which is generally roughly the same value as MaxStorageOperationConcurrency. In almost every case, we would expect this
// to only be a small handful of parallel requests, so keeping the code simple until the storage refactor adds global throttling.
var instanceQueries = instanceIds.Select(instance => this.GetStateAsync(instance, allExecutions: true, fetchInput: false));
IEnumerable<IList<OrchestrationState>> instanceQueriesResults = await Task.WhenAll(instanceQueries);
return instanceQueriesResults.SelectMany(result => result).Where(orchestrationState => orchestrationState != null).ToList();
}
/// <inheritdoc />
public override Task<IList<OrchestrationState>> GetStateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
TableQuery<OrchestrationInstanceStatus> query = new TableQuery<OrchestrationInstanceStatus>().
Where(TableQuery.GenerateFilterCondition(RowKeyProperty, QueryComparisons.Equal, string.Empty));
return this.QueryStateAsync(query, cancellationToken);
}
public override Task<IList<OrchestrationState>> GetStateAsync(DateTime createdTimeFrom, DateTime? createdTimeTo, IEnumerable<OrchestrationStatus> runtimeStatus, CancellationToken cancellationToken = default(CancellationToken))
{
return this.QueryStateAsync(OrchestrationInstanceStatusQueryCondition.Parse(createdTimeFrom, createdTimeTo, runtimeStatus)
.ToTableQuery<OrchestrationInstanceStatus>(), cancellationToken);
}
public override Task<DurableStatusQueryResult> GetStateAsync(DateTime createdTimeFrom, DateTime? createdTimeTo, IEnumerable<OrchestrationStatus> runtimeStatus, int top, string continuationToken, CancellationToken cancellationToken = default(CancellationToken))
{
return this.QueryStateAsync(
OrchestrationInstanceStatusQueryCondition.Parse(createdTimeFrom, createdTimeTo, runtimeStatus)
.ToTableQuery<OrchestrationInstanceStatus>(),
top,
continuationToken,
cancellationToken);
}
public override Task<DurableStatusQueryResult> GetStateAsync(OrchestrationInstanceStatusQueryCondition condition, int top, string continuationToken, CancellationToken cancellationToken = default(CancellationToken))
{
return this.QueryStateAsync(
condition.ToTableQuery<OrchestrationInstanceStatus>(),
top,
continuationToken,
cancellationToken);
}
async Task<DurableStatusQueryResult> QueryStateAsync(TableQuery<OrchestrationInstanceStatus> query, int top, string continuationToken, CancellationToken cancellationToken)
{
var orchestrationStates = new List<OrchestrationState>(top);
query.Take(top);
var tableEntitiesResponseInfo = await this.InstancesTable.ExecuteQuerySegmentAsync(query, cancellationToken, continuationToken);
IEnumerable<OrchestrationState> result = await Task.WhenAll(tableEntitiesResponseInfo.ReturnedEntities.Select( status => this.ConvertFromAsync(status, KeySanitation.UnescapePartitionKey(status.PartitionKey))));
orchestrationStates.AddRange(result);
var queryResult = new DurableStatusQueryResult()
{
OrchestrationState = orchestrationStates,
ContinuationToken = tableEntitiesResponseInfo.ContinuationToken,
};
return queryResult;
}
async Task<IList<OrchestrationState>> QueryStateAsync(TableQuery<OrchestrationInstanceStatus> query, CancellationToken cancellationToken)
{
var orchestrationStates = new List<OrchestrationState>(100);
var tableEntitiesResponseInfo = await this.InstancesTable.ExecuteQueryAsync(query, cancellationToken);
IEnumerable<OrchestrationState> result = await Task.WhenAll(tableEntitiesResponseInfo.ReturnedEntities.Select(
status => this.ConvertFromAsync(status, KeySanitation.UnescapePartitionKey(status.PartitionKey))));
orchestrationStates.AddRange(result);
return orchestrationStates;
}
async Task<PurgeHistoryResult> DeleteHistoryAsync(DateTime createdTimeFrom, DateTime? createdTimeTo, IEnumerable<OrchestrationStatus> runtimeStatus)
{
TableQuery<OrchestrationInstanceStatus> query = OrchestrationInstanceStatusQueryCondition.Parse(createdTimeFrom, createdTimeTo, runtimeStatus)
.ToTableQuery<OrchestrationInstanceStatus>();
int storageRequests = 0;
int rowsDeleted = 0;
var tableEntitiesResponseInfo = await this.InstancesTable.ExecuteQueryAsync(query);
var results = tableEntitiesResponseInfo.ReturnedEntities;
foreach (OrchestrationInstanceStatus orchestrationInstanceStatus in results)
{
var statisticsFromDeletion = await this.DeleteAllDataForOrchestrationInstance(orchestrationInstanceStatus);
storageRequests += statisticsFromDeletion.StorageRequests;
rowsDeleted += statisticsFromDeletion.RowsDeleted;
}
return new PurgeHistoryResult(storageRequests, results.Count, rowsDeleted);
}
async Task<PurgeHistoryResult> DeleteAllDataForOrchestrationInstance(OrchestrationInstanceStatus orchestrationInstanceStatus)
{
int storageRequests = 0;
int rowsDeleted = 0;
var historyEntitiesResponseInfo = await this.GetHistoryEntitiesResponseInfoAsync(
KeySanitation.UnescapePartitionKey(orchestrationInstanceStatus.PartitionKey),
null,
new []
{
RowKeyProperty
});
storageRequests += historyEntitiesResponseInfo.RequestCount;
var historyEntities = historyEntitiesResponseInfo.ReturnedEntities;
await this.messageManager.DeleteLargeMessageBlobs(orchestrationInstanceStatus.PartitionKey);
var deletedEntitiesResponseInfo = await this.HistoryTable.DeleteBatchAsync(historyEntities);
rowsDeleted += deletedEntitiesResponseInfo.TableResults.Count;
storageRequests += deletedEntitiesResponseInfo.RequestCount;
await this.InstancesTable.DeleteAsync(new DynamicTableEntity
{
PartitionKey = orchestrationInstanceStatus.PartitionKey,
RowKey = string.Empty,
ETag = "*"
});
storageRequests++;
return new PurgeHistoryResult(storageRequests, 1, rowsDeleted);
}
/// <inheritdoc />
public override Task PurgeHistoryAsync(DateTime thresholdDateTimeUtc, OrchestrationStateTimeRangeFilterType timeRangeFilterType)
{
throw new NotSupportedException();
}
/// <inheritdoc />
public override async Task<PurgeHistoryResult> PurgeInstanceHistoryAsync(string instanceId)
{
string sanitizedInstanceId = KeySanitation.EscapePartitionKey(instanceId);
TableQuery<OrchestrationInstanceStatus> query = new TableQuery<OrchestrationInstanceStatus>().Where(
TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(PartitionKeyProperty, QueryComparisons.Equal, sanitizedInstanceId),
TableOperators.And,
TableQuery.GenerateFilterCondition(RowKeyProperty, QueryComparisons.Equal, string.Empty)));
var tableEntitiesResponseInfo = await this.InstancesTable.ExecuteQueryAsync(query);
OrchestrationInstanceStatus orchestrationInstanceStatus = tableEntitiesResponseInfo.ReturnedEntities.FirstOrDefault();
if (orchestrationInstanceStatus != null)
{
PurgeHistoryResult result = await this.DeleteAllDataForOrchestrationInstance(orchestrationInstanceStatus);
this.settings.Logger.PurgeInstanceHistory(
this.storageAccountName,
this.taskHubName,
instanceId,
DateTime.MinValue.ToString(),
DateTime.MinValue.ToString(),
string.Empty,
result.StorageRequests,
result.InstancesDeleted,
tableEntitiesResponseInfo.ElapsedMilliseconds);
return result;
}
return new PurgeHistoryResult(0, 0, 0);
}
/// <inheritdoc />
public override async Task<PurgeHistoryResult> PurgeInstanceHistoryAsync(
DateTime createdTimeFrom,
DateTime? createdTimeTo,
IEnumerable<OrchestrationStatus> runtimeStatus)
{
Stopwatch stopwatch = Stopwatch.StartNew();
List<OrchestrationStatus> runtimeStatusList = runtimeStatus?.Where(
status => status == OrchestrationStatus.Completed ||
status == OrchestrationStatus.Terminated ||
status == OrchestrationStatus.Canceled ||
status == OrchestrationStatus.Failed).ToList();
PurgeHistoryResult result = await this.DeleteHistoryAsync(createdTimeFrom, createdTimeTo, runtimeStatusList);
this.settings.Logger.PurgeInstanceHistory(
this.storageAccountName,
this.taskHubName,
string.Empty,
createdTimeFrom.ToString(),
createdTimeTo.ToString() ?? DateTime.MinValue.ToString(),
runtimeStatus != null ?
string.Join(",", runtimeStatus.Select(x => x.ToString())) :
string.Empty,
result.StorageRequests,
result.InstancesDeleted,
stopwatch.ElapsedMilliseconds);
return result;
}
/// <inheritdoc />
public override async Task<bool> SetNewExecutionAsync(
ExecutionStartedEvent executionStartedEvent,
string eTag,
string inputStatusOverride)
{
string sanitizedInstanceId = KeySanitation.EscapePartitionKey(executionStartedEvent.OrchestrationInstance.InstanceId);
DynamicTableEntity entity = new DynamicTableEntity(sanitizedInstanceId, "")
{
ETag = eTag,
Properties =
{
["Input"] = new EntityProperty(inputStatusOverride ?? executionStartedEvent.Input),
["CreatedTime"] = new EntityProperty(executionStartedEvent.Timestamp),
["Name"] = new EntityProperty(executionStartedEvent.Name),
["Version"] = new EntityProperty(executionStartedEvent.Version),
["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.Pending.ToString()),
["LastUpdatedTime"] = new EntityProperty(DateTime.UtcNow),
["TaskHubName"] = new EntityProperty(this.settings.TaskHubName),
["ScheduledStartTime"] = new EntityProperty(executionStartedEvent.ScheduledStartTime),
["ExecutionId"] = new EntityProperty(executionStartedEvent.OrchestrationInstance.ExecutionId),
}
};
// It is possible that the queue message was small enough to be written directly to a queue message,
// not a blob, but is too large to be written to a table property.
await this.CompressLargeMessageAsync(entity);
Stopwatch stopwatch = Stopwatch.StartNew();
try
{
if (eTag == null)
{
// This is the case for creating a new instance.
await this.InstancesTable.InsertAsync(entity);
}
else
{
// This is the case for overwriting an existing instance.
await this.InstancesTable.ReplaceAsync(entity);
}
}
catch (DurableTaskStorageException e) when (
e.HttpStatusCode == 409 /* Conflict */ ||
e.HttpStatusCode == 412 /* Precondition failed */)
{
// Ignore. The main scenario for this is handling race conditions in status update.
return false;
}
// Episode 0 means the orchestrator hasn't started yet.
int currentEpisodeNumber = 0;
this.settings.Logger.InstanceStatusUpdate(
this.storageAccountName,
this.taskHubName,
executionStartedEvent.OrchestrationInstance.InstanceId,
executionStartedEvent.OrchestrationInstance.ExecutionId,
OrchestrationStatus.Pending,
currentEpisodeNumber,
stopwatch.ElapsedMilliseconds);
return true;
}
/// <inheritdoc />
public override async Task UpdateStatusForRewindAsync(string instanceId)
{
string sanitizedInstanceId = KeySanitation.EscapePartitionKey(instanceId);
DynamicTableEntity entity = new DynamicTableEntity(sanitizedInstanceId, "")
{
ETag = "*",
Properties =
{
["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.Pending.ToString()),
["LastUpdatedTime"] = new EntityProperty(DateTime.UtcNow),
}
};
Stopwatch stopwatch = Stopwatch.StartNew();
await this.InstancesTable.MergeAsync(entity);
// We don't have enough information to get the episode number.
// It's also not important to have for this particular trace.
int currentEpisodeNumber = 0;
this.settings.Logger.InstanceStatusUpdate(
this.storageAccountName,
this.taskHubName,
instanceId,
string.Empty,
OrchestrationStatus.Pending,
currentEpisodeNumber,
stopwatch.ElapsedMilliseconds);
}
/// <inheritdoc />
public override Task StartAsync()
{
ServicePointManager.FindServicePoint(this.HistoryTable.Uri).UseNagleAlgorithm = false;
ServicePointManager.FindServicePoint(this.InstancesTable.Uri).UseNagleAlgorithm = false;
return Utils.CompletedTask;
}
/// <inheritdoc />
public override async Task<string> UpdateStateAsync(
OrchestrationRuntimeState newRuntimeState,
OrchestrationRuntimeState oldRuntimeState,
string instanceId,
string executionId,
string eTagValue)
{
int estimatedBytes = 0;
IList<HistoryEvent> newEvents = newRuntimeState.NewEvents;
IList<HistoryEvent> allEvents = newRuntimeState.Events;
int episodeNumber = Utils.GetEpisodeNumber(newRuntimeState);
var newEventListBuffer = new StringBuilder(4000);
var historyEventBatch = new TableBatchOperation();
OrchestrationStatus runtimeStatus = OrchestrationStatus.Running;
string sanitizedInstanceId = KeySanitation.EscapePartitionKey(instanceId);
var instanceEntity = new DynamicTableEntity(sanitizedInstanceId, string.Empty)
{
Properties =
{
// TODO: Translating null to "null" is a temporary workaround. We should prioritize
// https://github.com/Azure/durabletask/issues/477 so that this is no longer necessary.
["CustomStatus"] = new EntityProperty(newRuntimeState.Status ?? "null"),
["ExecutionId"] = new EntityProperty(executionId),
["LastUpdatedTime"] = new EntityProperty(newEvents.Last().Timestamp),
}
};
for (int i = 0; i < newEvents.Count; i++)
{
bool isFinalEvent = i == newEvents.Count - 1;
HistoryEvent historyEvent = newEvents[i];
var historyEntity = this.tableEntityConverter.ConvertToTableEntity(historyEvent);
historyEntity.PartitionKey = sanitizedInstanceId;
newEventListBuffer.Append(historyEvent.EventType.ToString()).Append(',');
// The row key is the sequence number, which represents the chronological ordinal of the event.
long sequenceNumber = i + (allEvents.Count - newEvents.Count);
historyEntity.RowKey = sequenceNumber.ToString("X16");
historyEntity.Properties["ExecutionId"] = new EntityProperty(executionId);
await this.CompressLargeMessageAsync(historyEntity);
// Replacement can happen if the orchestration episode gets replayed due to a commit failure in one of the steps below.
historyEventBatch.InsertOrReplace(historyEntity);
// Keep track of the byte count to ensure we don't hit the 4 MB per-batch maximum
estimatedBytes += GetEstimatedByteCount(historyEntity);
// Monitor for orchestration instance events
switch (historyEvent.EventType)
{
case EventType.ExecutionStarted:
runtimeStatus = OrchestrationStatus.Running;
ExecutionStartedEvent executionStartedEvent = (ExecutionStartedEvent)historyEvent;
instanceEntity.Properties["Name"] = new EntityProperty(executionStartedEvent.Name);
instanceEntity.Properties["Version"] = new EntityProperty(executionStartedEvent.Version);
instanceEntity.Properties["CreatedTime"] = new EntityProperty(executionStartedEvent.Timestamp);
instanceEntity.Properties["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.Running.ToString());
if (executionStartedEvent.ScheduledStartTime.HasValue) {
instanceEntity.Properties["ScheduledStartTime"] = new EntityProperty(executionStartedEvent.ScheduledStartTime);
}
this.SetInstancesTablePropertyFromHistoryProperty(
historyEntity,
instanceEntity,
historyPropertyName: nameof(executionStartedEvent.Input),
instancePropertyName: InputProperty,
data: executionStartedEvent.Input);
break;
case EventType.ExecutionCompleted:
ExecutionCompletedEvent executionCompleted = (ExecutionCompletedEvent)historyEvent;
runtimeStatus = executionCompleted.OrchestrationStatus;
instanceEntity.Properties["RuntimeStatus"] = new EntityProperty(executionCompleted.OrchestrationStatus.ToString());
instanceEntity.Properties["CompletedTime"] = new EntityProperty(DateTime.UtcNow);
this.SetInstancesTablePropertyFromHistoryProperty(
historyEntity,
instanceEntity,
historyPropertyName: nameof(executionCompleted.Result),
instancePropertyName: OutputProperty,
data: executionCompleted.Result);
break;
case EventType.ExecutionTerminated:
runtimeStatus = OrchestrationStatus.Terminated;
ExecutionTerminatedEvent executionTerminatedEvent = (ExecutionTerminatedEvent)historyEvent;
instanceEntity.Properties["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.Terminated.ToString());
instanceEntity.Properties["CompletedTime"] = new EntityProperty(DateTime.UtcNow);
this.SetInstancesTablePropertyFromHistoryProperty(
historyEntity,
instanceEntity,
historyPropertyName: nameof(executionTerminatedEvent.Input),
instancePropertyName: OutputProperty,
data: executionTerminatedEvent.Input);
break;
case EventType.ContinueAsNew:
runtimeStatus = OrchestrationStatus.ContinuedAsNew;
ExecutionCompletedEvent executionCompletedEvent = (ExecutionCompletedEvent)historyEvent;
instanceEntity.Properties["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.ContinuedAsNew.ToString());
this.SetInstancesTablePropertyFromHistoryProperty(
historyEntity,
instanceEntity,
historyPropertyName: nameof(executionCompletedEvent.Result),
instancePropertyName: OutputProperty,
data: executionCompletedEvent.Result);
break;
}
// Table storage only supports inserts of up to 100 entities at a time or 4 MB at a time.
if (historyEventBatch.Count == 99 || estimatedBytes > 3 * 1024 * 1024 /* 3 MB */)
{
eTagValue = await this.UploadHistoryBatch(
instanceId,
sanitizedInstanceId,
executionId,
historyEventBatch,
newEventListBuffer,
allEvents.Count,
episodeNumber,
estimatedBytes,
eTagValue,
isFinalBatch: isFinalEvent);
// Reset local state for the next batch
newEventListBuffer.Clear();
historyEventBatch.Clear();
estimatedBytes = 0;
}
}
// First persistence step is to commit history to the history table. Messages must come after.
if (historyEventBatch.Count > 0)
{
eTagValue = await this.UploadHistoryBatch(
instanceId,
sanitizedInstanceId,
executionId,
historyEventBatch,
newEventListBuffer,
allEvents.Count,
episodeNumber,
estimatedBytes,
eTagValue,
isFinalBatch: true);