-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
JobStoreSupport.cs
4014 lines (3626 loc) · 155 KB
/
JobStoreSupport.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
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. All rights reserved.
*
* 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.
*
*/
#endregion
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Globalization;
using Microsoft.Extensions.Logging;
using Quartz.Impl.AdoJobStore.Common;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Logging;
using Quartz.Spi;
using Quartz.Util;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Quartz.Impl.AdoJobStore;
/// <summary>
/// Contains base functionality for ADO.NET-based JobStore implementations.
/// </summary>
/// <author><a href="mailto:jeff@binaryfeed.org">Jeffrey Wescott</a></author>
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
public abstract class JobStoreSupport : AdoConstants, IJobStore
{
protected internal const string LockTriggerAccess = "TRIGGER_ACCESS";
protected internal const string LockStateAccess = "STATE_ACCESS";
private string tablePrefix = DefaultTablePrefix;
private bool useProperties;
protected Type delegateType;
protected readonly Dictionary<string, ICalendar?> calendarCache = new Dictionary<string, ICalendar?>();
private IDriverDelegate driverDelegate = null!;
private TimeSpan misfireThreshold = TimeSpan.FromMinutes(1); // one minute
private TimeSpan? misfirehandlerFrequence;
private ClusterManager? clusterManager;
private MisfireHandler? misfireHandler;
private ITypeLoadHelper typeLoadHelper = null!;
private ISchedulerSignaler schedSignaler = null!;
private volatile bool schedulerRunning;
private volatile bool shutdown;
/// <summary>
/// Initializes a new instance of the <see cref="JobStoreSupport"/> class.
/// </summary>
protected JobStoreSupport()
{
RetryableActionErrorLogThreshold = 4;
DoubleCheckLockMisfireHandler = true;
ClusterCheckinInterval = TimeSpan.FromMilliseconds(7500);
ClusterCheckinMisfireThreshold = TimeSpan.FromMilliseconds(7500);
MaxMisfiresToHandleAtATime = 20;
DbRetryInterval = TimeSpan.FromSeconds(15);
Logger = LogProvider.CreateLogger<JobStoreSupport>();
delegateType = typeof(StdAdoDelegate);
}
/// <summary>
/// Get or set the datasource name.
/// </summary>
public string DataSource { get; set; } = "";
/// <summary>
/// Get or set the database connection manager.
/// </summary>
public IDbConnectionManager ConnectionManager { get; set; } = DBConnectionManager.Instance;
/// <summary>
/// Gets the log.
/// </summary>
/// <value>The log.</value>
internal ILogger<JobStoreSupport> Logger { get; }
/// <summary>
/// Get or sets the prefix that should be pre-pended to all table names.
/// </summary>
public string TablePrefix
{
get => tablePrefix;
set
{
if (value == null)
{
value = "";
}
tablePrefix = value;
}
}
/// <summary>
/// Set whether string-only properties will be handled in JobDataMaps.
/// </summary>
public string UseProperties
{
set
{
if (value == null)
{
value = "false";
}
useProperties = bool.Parse(value);
}
}
/// <summary>
/// Get or set the instance Id of the Scheduler (must be unique within a cluster).
/// </summary>
public virtual string InstanceId { get; set; } = "";
/// <summary>
/// Get or set the instance Id of the Scheduler (must be unique within this server instance).
/// </summary>
public virtual string InstanceName { get; set; } = "";
public int ThreadPoolSize
{
set { }
}
/// <summary>
/// Gets or sets the number of retries before an error is logged for recovery operations.
/// </summary>
public int RetryableActionErrorLogThreshold { get; set; }
public IObjectSerializer? ObjectSerializer { get; set; }
public virtual long EstimatedTimeToReleaseAndAcquireTrigger { get; } = 70;
/// <summary>
/// Get or set whether this instance is part of a cluster.
/// </summary>
public bool Clustered { get; set; }
/// <summary>
/// Get or set the frequency at which this instance "checks-in"
/// with the other instances of the cluster. -- Affects the rate of
/// detecting failed instances.
/// </summary>
[TimeSpanParseRule(TimeSpanParseRule.Milliseconds)]
public TimeSpan ClusterCheckinInterval { get; set; }
/// <summary>
/// The time span by which a check-in must have missed its
/// next-fire-time, in order for it to be considered "misfired" and thus
/// other scheduler instances in a cluster can consider a "misfired" scheduler
/// instance as failed or dead.
/// </summary>
[TimeSpanParseRule(TimeSpanParseRule.Milliseconds)]
public TimeSpan ClusterCheckinMisfireThreshold { get; set; }
/// <summary>
/// Get or set the maximum number of misfired triggers that the misfire handling
/// thread will try to recover at one time (within one transaction). The
/// default is 20.
/// </summary>
public int MaxMisfiresToHandleAtATime { get; set; }
/// <summary>
/// Gets or sets the database retry interval.
/// </summary>
/// <value>The db retry interval.</value>
[TimeSpanParseRule(TimeSpanParseRule.Milliseconds)]
public TimeSpan DbRetryInterval { get; set; }
/// <summary>
/// Get or set whether this instance should use database-based thread
/// synchronization.
/// </summary>
public bool UseDBLocks { get; set; }
/// <summary>
/// Whether or not to obtain locks when inserting new jobs/triggers.
/// </summary>
/// <remarks>
/// <para>
/// Defaults to <see langword="true" />, which is safest - some db's (such as
/// MS SQLServer) seem to require this to avoid deadlocks under high load,
/// while others seem to do fine without. Settings this to false means
/// isolation guarantees between job scheduling and trigger acquisition are
/// entirely enforced by the database. Depending on the database and it's
/// configuration this may cause unusual scheduling behaviors.
/// </para>
/// <para>
/// Setting this property to <see langword="false" /> will provide a
/// significant performance increase during the addition of new jobs
/// and triggers.
/// </para>
/// </remarks>
public virtual bool LockOnInsert { get; set; } = true;
/// <summary>
/// The time span by which a trigger must have missed its
/// next-fire-time, in order for it to be considered "misfired" and thus
/// have its misfire instruction applied.
/// </summary>
[TimeSpanParseRule(TimeSpanParseRule.Milliseconds)]
public virtual TimeSpan MisfireThreshold
{
get => misfireThreshold;
set
{
if (value.TotalMilliseconds < 1)
{
ThrowHelper.ThrowArgumentException("MisfireThreshold must be larger than 0");
}
misfireThreshold = value;
}
}
/// <summary>
/// How often should the misfire handler check for misfires. Defaults to
/// <see cref="MisfireThreshold"/>.
/// </summary>
[TimeSpanParseRule(TimeSpanParseRule.Milliseconds)]
public virtual TimeSpan MisfireHandlerFrequency
{
get { return misfirehandlerFrequence.GetValueOrDefault(MisfireThreshold); }
set
{
if (value.TotalMilliseconds < 1)
{
ThrowHelper.ThrowArgumentException("MisfireHandlerFrequency must be larger than 0");
}
misfirehandlerFrequence = value;
}
}
/// <summary>
/// Don't call set autocommit(false) on connections obtained from the
/// DataSource. This can be helpful in a few situations, such as if you
/// have a driver that complains if it is called when it is already off.
/// </summary>
public virtual bool DontSetAutoCommitFalse { get; set; }
/// <summary>
/// Set the transaction isolation level of DB connections to sequential.
/// </summary>
public virtual bool TxIsolationLevelSerializable { get; set; }
/// <summary>
/// Whether or not the query and update to acquire a Trigger for firing
/// should be performed after obtaining an explicit DB lock (to avoid
/// possible race conditions on the trigger's db row). This is
/// is considered unnecessary for most databases (due to the nature of
/// the SQL update that is performed), and therefore a superfluous performance hit.
/// </summary>
/// <remarks>
/// However, if batch acquisition is used, it is important for this behavior
/// to be used for all dbs.
/// </remarks>
public bool AcquireTriggersWithinLock { get; set; }
/// <summary>
/// Get or set the ADO.NET driver delegate class name.
/// </summary>
public virtual string DriverDelegateType { get; set; } = null!;
/// <summary>
/// The driver delegate's initialization string.
/// </summary>
public string? DriverDelegateInitString { get; set; }
/// <summary>
/// set the SQL statement to use to select and lock a row in the "locks"
/// table.
/// </summary>
/// <seealso cref="StdRowLockSemaphore" />
public virtual string? SelectWithLockSQL { get; set; }
protected virtual ITypeLoadHelper TypeLoadHelper => typeLoadHelper;
/// <summary>
/// Get whether the threads spawned by this JobStore should be
/// marked as daemon. Possible threads include the <see cref="MisfireHandler" />
/// and the <see cref="ClusterManager"/>.
/// </summary>
/// <returns></returns>
public bool MakeThreadsDaemons { get; set; }
/// <summary>
/// Get whether to check to see if there are Triggers that have misfired
/// before actually acquiring the lock to recover them. This should be
/// set to false if the majority of the time, there are misfired
/// Triggers.
/// </summary>
/// <returns></returns>
public bool DoubleCheckLockMisfireHandler { get; set; }
/// <summary>
/// Whether to perform a schema check on scheduler startup and try to determine if correct tables are in place.
/// Defaults to true.
/// </summary>
public bool PerformSchemaValidation { get; set; } = true;
public virtual TimeSpan GetAcquireRetryDelay(int failureCount) => DbRetryInterval;
protected DbMetadata DbMetadata => ConnectionManager.GetDbMetadata(DataSource);
protected abstract ValueTask<ConnectionAndTransactionHolder> GetNonManagedTXConnection();
/// <summary>
/// Gets the connection and starts a new transaction.
/// </summary>
/// <returns></returns>
protected virtual async ValueTask<ConnectionAndTransactionHolder> GetConnection()
{
DbConnection conn;
DbTransaction tx;
try
{
conn = ConnectionManager.GetConnection(DataSource);
await conn.OpenAsync().ConfigureAwait(false);
}
catch (Exception e)
{
ThrowHelper.ThrowJobPersistenceException($"Failed to obtain DB connection from data source '{DataSource}': {e}", e);
return default;
}
try
{
if (TxIsolationLevelSerializable)
{
tx = conn.BeginTransaction(IsolationLevel.Serializable);
}
else
{
// default
tx = conn.BeginTransaction(IsolationLevel.ReadCommitted);
}
}
catch (Exception e)
{
conn.Close();
ThrowHelper.ThrowJobPersistenceException("Failure setting up connection.", e);
return default;
}
return new ConnectionAndTransactionHolder(conn, tx);
}
protected virtual DateTimeOffset MisfireTime
{
get
{
DateTimeOffset misfireTime = SystemTime.UtcNow();
if (MisfireThreshold > TimeSpan.Zero)
{
misfireTime = misfireTime.AddMilliseconds(-1 * MisfireThreshold.TotalMilliseconds);
}
return misfireTime;
}
}
protected virtual string GetFiredTriggerRecordId()
{
Interlocked.Increment(ref ftrCtr);
return InstanceId + ftrCtr;
}
/// <summary>
/// Get the driver delegate for DB operations.
/// </summary>
protected virtual IDriverDelegate Delegate
{
get
{
lock (this)
{
if (driverDelegate == null)
{
try
{
if (!string.IsNullOrWhiteSpace(DriverDelegateType))
{
delegateType = TypeLoadHelper.LoadType(DriverDelegateType)!;
}
IDbProvider dbProvider = ConnectionManager.GetDbProvider(DataSource);
var args = new DelegateInitializationArgs();
args.UseProperties = CanUseProperties;
args.TablePrefix = tablePrefix;
args.InstanceName = InstanceName;
args.InstanceId = InstanceId;
args.DbProvider = dbProvider;
args.TypeLoadHelper = typeLoadHelper;
args.ObjectSerializer = ObjectSerializer;
args.InitString = DriverDelegateInitString;
var ctor = delegateType.GetConstructor(Type.EmptyTypes);
if (ctor == null)
{
ThrowHelper.ThrowInvalidConfigurationException("Configured delegate does not have public constructor that takes no arguments");
}
driverDelegate = (IDriverDelegate) ctor.Invoke(null);
driverDelegate.Initialize(args);
}
catch (Exception e)
{
ThrowHelper.ThrowNoSuchDelegateException("Couldn't instantiate delegate: " + e.Message, e);
}
}
}
return driverDelegate;
}
}
private IDbProvider DbProvider => ConnectionManager.GetDbProvider(DataSource);
protected internal virtual ISemaphore LockHandler { get; set; } = null!;
/// <summary>
/// Get whether String-only properties will be handled in JobDataMaps.
/// </summary>
public virtual bool CanUseProperties => useProperties;
/// <summary>
/// Called by the QuartzScheduler before the <see cref="IJobStore" /> is
/// used, in order to give it a chance to Initialize.
/// </summary>
public virtual async ValueTask Initialize(
ITypeLoadHelper loadHelper,
ISchedulerSignaler signaler,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(DataSource))
{
ThrowHelper.ThrowSchedulerConfigException("DataSource name not set.");
}
typeLoadHelper = loadHelper;
schedSignaler = signaler;
if (Delegate is SQLiteDelegate && (LockHandler == null || LockHandler.GetType() != typeof(UpdateLockRowSemaphore)))
{
Logger.LogInformation("Detected SQLite usage, changing to use UpdateLockRowSemaphore");
var lockHandler = new UpdateLockRowSemaphore(DbProvider)
{
SchedName = InstanceName,
TablePrefix = TablePrefix
};
LockHandler = lockHandler;
}
if (Delegate is SQLiteDelegate)
{
if (Clustered)
{
ThrowHelper.ThrowInvalidConfigurationException("SQLite cannot be used as clustered mode due to locking problems");
}
if (!AcquireTriggersWithinLock)
{
Logger.LogInformation("With SQLite we need to set AcquireTriggersWithinLock to true, changing");
AcquireTriggersWithinLock = true;
}
if (!TxIsolationLevelSerializable)
{
Logger.LogInformation("Detected usage of SQLiteDelegate - defaulting 'txIsolationLevelSerializable' to 'true'");
TxIsolationLevelSerializable = true;
}
}
// If the user hasn't specified an explicit lock handler, then
// choose one based on CMT/Clustered/UseDBLocks.
if (LockHandler == null)
{
// If the user hasn't specified an explicit lock handler,
// then we *must* use DB locks with clustering
if (Clustered)
{
UseDBLocks = true;
}
if (UseDBLocks)
{
if (Delegate is SqlServerDelegate)
{
if (SelectWithLockSQL == null)
{
const string DefaultLockSql = "SELECT * FROM {0}LOCKS WITH (UPDLOCK,ROWLOCK) WHERE " + ColumnSchedulerName + " = @schedulerName AND LOCK_NAME = @lockName";
Logger.LogInformation("Detected usage of SqlServerDelegate - defaulting 'selectWithLockSQL' to '{DefaultLockSql}'.", DefaultLockSql);
SelectWithLockSQL = DefaultLockSql;
}
}
Logger.LogInformation("Using db table-based data access locking (synchronization).");
LockHandler = new StdRowLockSemaphore(TablePrefix, InstanceName, SelectWithLockSQL, DbProvider);
}
else
{
Logger.LogInformation("Using thread monitor-based data access locking (synchronization).");
LockHandler = new SimpleSemaphore();
}
}
else
{
// be ready to give a friendly warning if SQL Server is used and sub-optimal locking
if (LockHandler is UpdateLockRowSemaphore && Delegate is SqlServerDelegate)
{
Logger.LogWarning("Detected usage of SqlServerDelegate and UpdateLockRowSemaphore, removing 'quartz.jobStore.lockHandler.type' would allow more efficient SQL Server specific (UPDLOCK,ROWLOCK) row access");
}
// be ready to give a friendly warning if SQL Server provider and wrong delegate
if (DbProvider.Metadata.ConnectionType?.Namespace != null
&& DbProvider.Metadata.ConnectionType.Namespace.Contains("SqlClient")
&& DbProvider.Metadata.ConnectionType.Name == "SqlConnection"
&& !(Delegate is SqlServerDelegate))
{
Logger.LogWarning("Detected usage of SQL Server provider without SqlServerDelegate, SqlServerDelegate would provide better performance");
}
}
if (PerformSchemaValidation && driverDelegate is StdAdoDelegate adoDelegate)
{
try
{
var objectCount = await ExecuteWithoutLock<int>(conn => adoDelegate.ValidateSchema(conn, cancellationToken), cancellationToken).ConfigureAwait(false);
Logger.LogInformation("Successfully validated presence of {SchemaObjectCount} schema objects", objectCount);
}
catch (Exception ex)
{
const string error = "Database schema validation failed."
+ " Make sure you have created the database tables that Quartz requires using the database schema scripts."
+ " You can disable this check by setting quartz.jobStore.performSchemaValidation to false";
throw new SchedulerException(error, ex);
}
}
}
/// <seealso cref="IJobStore.SchedulerStarted(CancellationToken)" />
public virtual async ValueTask SchedulerStarted(
CancellationToken cancellationToken = default)
{
if (Clustered)
{
clusterManager = new ClusterManager(this);
await clusterManager.Initialize().ConfigureAwait(false);
}
else
{
try
{
await RecoverJobs(cancellationToken).ConfigureAwait(false);
}
catch (SchedulerException se)
{
Logger.LogError(se, "Failure occurred during job recovery: {ExceptionMessage}", se.Message);
ThrowHelper.ThrowSchedulerConfigException("Failure occurred during job recovery.", se);
}
}
misfireHandler = new MisfireHandler(this);
misfireHandler.Initialize();
schedulerRunning = true;
}
/// <summary>
/// Called by the QuartzScheduler to inform the JobStore that
/// the scheduler has been paused.
/// </summary>
public ValueTask SchedulerPaused(CancellationToken cancellationToken = default)
{
schedulerRunning = false;
return default;
}
/// <summary>
/// Called by the QuartzScheduler to inform the JobStore that
/// the scheduler has resumed after being paused.
/// </summary>
public ValueTask SchedulerResumed(CancellationToken cancellationToken = default)
{
schedulerRunning = true;
return default;
}
/// <summary>
/// Called by the QuartzScheduler to inform the <see cref="IJobStore" /> that
/// it should free up all of it's resources because the scheduler is
/// shutting down.
/// </summary>
public virtual async ValueTask Shutdown(CancellationToken cancellationToken = default)
{
shutdown = true;
if (misfireHandler != null)
{
await misfireHandler.Shutdown().ConfigureAwait(false);
}
if (clusterManager != null)
{
await clusterManager.Shutdown().ConfigureAwait(false);
}
try
{
ConnectionManager.Shutdown(DataSource);
}
catch (Exception sqle)
{
Logger.LogWarning(sqle, "Database connection Shutdown unsuccessful.");
}
}
/// <summary>
/// Indicates whether this job store supports persistence.
/// </summary>
/// <value></value>
/// <returns></returns>
public virtual bool SupportsPersistence => true;
protected virtual async ValueTask ReleaseLock(
Guid requestorId,
string lockName,
bool doIt,
CancellationToken cancellationToken)
{
if (doIt)
{
try
{
await LockHandler.ReleaseLock(requestorId, lockName, cancellationToken).ConfigureAwait(false);
}
catch (LockException le)
{
Logger.LogError(le, "Error returning lock: {ExceptionMessage}", le.Message);
}
}
}
/// <summary>
/// Will recover any failed or misfired jobs and clean up the data store as
/// appropriate.
/// </summary>
protected virtual ValueTask<bool> RecoverJobs(CancellationToken cancellationToken)
{
return ExecuteInNonManagedTXLock(
LockTriggerAccess,
conn => RecoverJobs(conn, cancellationToken),
cancellationToken);
}
/// <summary>
/// Will recover any failed or misfired jobs and clean up the data store as
/// appropriate.
/// </summary>
protected virtual async ValueTask RecoverJobs(
ConnectionAndTransactionHolder conn,
CancellationToken cancellationToken = default)
{
try
{
// update inconsistent job states
int rows = await Delegate.UpdateTriggerStatesFromOtherStates(conn, StateWaiting, StateAcquired, StateBlocked, cancellationToken).ConfigureAwait(false);
rows += await Delegate.UpdateTriggerStatesFromOtherStates(conn, StatePaused,
StatePausedBlocked,
StatePausedBlocked, cancellationToken).ConfigureAwait(false);
Logger.LogInformation("Freed {Count} triggers from 'acquired' / 'blocked' state.", rows);
// clean up misfired jobs
await RecoverMisfiredJobs(conn, true, cancellationToken).ConfigureAwait(false);
// recover jobs marked for recovery that were not fully executed
var recoveringJobTriggers = await Delegate.SelectTriggersForRecoveringJobs(conn, cancellationToken).ConfigureAwait(false);
Logger.LogInformation("Recovering {Count} jobs that were in-progress at the time of the last shut-down.", recoveringJobTriggers.Count);
foreach (IOperableTrigger trigger in recoveringJobTriggers)
{
if (await JobExists(conn, trigger.JobKey, cancellationToken).ConfigureAwait(false))
{
trigger.ComputeFirstFireTimeUtc(null);
await StoreTrigger(conn, trigger, null, false, StateWaiting, false, true, cancellationToken).ConfigureAwait(false);
}
}
Logger.LogInformation("Recovery complete.");
// remove lingering 'complete' triggers...
var triggersInState = await Delegate.SelectTriggersInState(conn, StateComplete, cancellationToken).ConfigureAwait(false);
foreach (var trigger in triggersInState)
{
await RemoveTrigger(conn, trigger, cancellationToken).ConfigureAwait(false);
}
Logger.LogInformation("Removed {Count} 'complete' triggers.", triggersInState.Count);
// clean up any fired trigger entries
int n = await Delegate.DeleteFiredTriggers(conn, cancellationToken).ConfigureAwait(false);
Logger.LogInformation("Removed {Count} stale fired job entries.", n);
}
catch (JobPersistenceException)
{
throw;
}
catch (Exception e)
{
ThrowHelper.ThrowJobPersistenceException("Couldn't recover jobs: " + e.Message, e);
}
}
//private int lastRecoverCount = 0;
public virtual async ValueTask<RecoverMisfiredJobsResult> RecoverMisfiredJobs(
ConnectionAndTransactionHolder conn,
bool recovering,
CancellationToken cancellationToken = default)
{
// If recovering, we want to handle all of the misfired
// triggers right away.
int maxMisfiresToHandleAtATime = recovering ? -1 : MaxMisfiresToHandleAtATime;
List<TriggerKey> misfiredTriggers = new List<TriggerKey>();
DateTimeOffset earliestNewTime = DateTimeOffset.MaxValue;
// We must still look for the MISFIRED state in case triggers were left
// in this state when upgrading to this version that does not support it.
bool hasMoreMisfiredTriggers =
await Delegate.HasMisfiredTriggersInState(conn, StateWaiting, MisfireTime, maxMisfiresToHandleAtATime, misfiredTriggers, cancellationToken).ConfigureAwait(false);
if (hasMoreMisfiredTriggers)
{
Logger.LogInformation(
"Handling the first {Count} triggers that missed their scheduled fire-time. More misfired triggers remain to be processed.",
misfiredTriggers.Count);
}
else if (misfiredTriggers.Count > 0)
{
Logger.LogInformation(
"Handling {Count} trigger(s) that missed their scheduled fire-time.", misfiredTriggers.Count);
}
else
{
Logger.LogInformation(
"Found 0 triggers that missed their scheduled fire-time.");
return RecoverMisfiredJobsResult.NoOp;
}
foreach (TriggerKey triggerKey in misfiredTriggers)
{
IOperableTrigger? trig;
try
{
trig = await RetrieveTrigger(conn, triggerKey, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.LogError(e, "Error retrieving the misfired trigger: '{TriggerKey}'", triggerKey);
continue;
}
if (trig == null)
{
continue;
}
try
{
await DoUpdateOfMisfiredTrigger(conn, trig, false, StateWaiting, recovering).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.LogError(e, "Error updating misfired trigger: '{TriggerKey}'", trig.Key);
continue;
}
DateTimeOffset? nextTime = trig.GetNextFireTimeUtc();
if (nextTime.HasValue && nextTime.Value < earliestNewTime)
{
earliestNewTime = nextTime.Value;
}
}
return new RecoverMisfiredJobsResult(hasMoreMisfiredTriggers, misfiredTriggers.Count, earliestNewTime);
}
protected virtual async ValueTask<bool> UpdateMisfiredTrigger(
ConnectionAndTransactionHolder conn,
TriggerKey triggerKey,
string newStateIfNotComplete,
bool forceState,
CancellationToken cancellationToken = default)
{
try
{
var trig = (await RetrieveTrigger(conn, triggerKey, cancellationToken).ConfigureAwait(false))!;
DateTimeOffset misfireTime = SystemTime.UtcNow();
if (MisfireThreshold > TimeSpan.Zero)
{
misfireTime = misfireTime.AddMilliseconds(-1 * MisfireThreshold.TotalMilliseconds);
}
if (trig.GetNextFireTimeUtc().GetValueOrDefault() > misfireTime)
{
return false;
}
await DoUpdateOfMisfiredTrigger(conn, trig, forceState, newStateIfNotComplete, false).ConfigureAwait(false);
return true;
}
catch (Exception e)
{
ThrowHelper.ThrowJobPersistenceException($"Couldn't update misfired trigger '{triggerKey}': {e.Message}", e);
return false;
}
}
private async ValueTask DoUpdateOfMisfiredTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trig,
bool forceState, string newStateIfNotComplete, bool recovering)
{
ICalendar? cal = null;
if (trig.CalendarName != null)
{
cal = await RetrieveCalendar(conn, trig.CalendarName).ConfigureAwait(false);
}
await schedSignaler.NotifyTriggerListenersMisfired(trig).ConfigureAwait(false);
trig.UpdateAfterMisfire(cal);
if (!trig.GetNextFireTimeUtc().HasValue)
{
await StoreTrigger(conn, trig, null, true, StateComplete, forceState, recovering).ConfigureAwait(false);
await schedSignaler.NotifySchedulerListenersFinalized(trig).ConfigureAwait(false);
}
else
{
await StoreTrigger(conn, trig, null, true, newStateIfNotComplete, forceState, recovering).ConfigureAwait(false);
}
}
/// <summary>
/// Store the given <see cref="IJobDetail" /> and <see cref="IOperableTrigger" />.
/// </summary>
/// <param name="newJob">Job to be stored.</param>
/// <param name="newTrigger">Trigger to be stored.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public async ValueTask StoreJobAndTrigger(
IJobDetail newJob,
IOperableTrigger newTrigger,
CancellationToken cancellationToken = default)
{
await ExecuteInLock<object?>(LockOnInsert ? LockTriggerAccess : null, async conn =>
{
await StoreJob(conn, newJob, false, cancellationToken).ConfigureAwait(false);
await StoreTrigger(conn, newTrigger, newJob, false, StateWaiting, false, false, cancellationToken).ConfigureAwait(false);
return null;
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns true if the given JobGroup is paused.
/// </summary>
/// <param name="groupName"></param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns></returns>
public ValueTask<bool> IsJobGroupPaused(
string groupName,
CancellationToken cancellationToken = default)
{
ThrowHelper.ThrowNotImplementedException();
return new ValueTask<bool>(false);
}
/// <summary>
/// Returns true if the given TriggerGroup is paused.
/// </summary>
/// <param name="groupName"></param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <returns></returns>
public ValueTask<bool> IsTriggerGroupPaused(
string groupName,
CancellationToken cancellationToken = default)
{
ThrowHelper.ThrowNotImplementedException();
return new ValueTask<bool>(false);
}
/// <summary>
/// Stores the given <see cref="IJobDetail" />.
/// </summary>
/// <param name="newJob">The <see cref="IJobDetail" /> to be stored.</param>
/// <param name="replaceExisting">
/// If <see langword="true" />, any <see cref="IJob" /> existing in the
/// <see cref="IJobStore" /> with the same name & group should be over-written.
/// </param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public ValueTask<object> StoreJob(
IJobDetail newJob,
bool replaceExisting,
CancellationToken cancellationToken = default)
{
return ExecuteInLock(
LockOnInsert || replaceExisting ? LockTriggerAccess : null,
conn => StoreJob(conn, newJob, replaceExisting, cancellationToken),
cancellationToken);
}
/// <summary> <para>
/// Insert or update a job.
/// </para>
/// </summary>
protected virtual async ValueTask StoreJob(
ConnectionAndTransactionHolder conn,
IJobDetail newJob,
bool replaceExisting,
CancellationToken cancellationToken = default)
{
bool existingJob = await JobExists(conn, newJob.Key, cancellationToken).ConfigureAwait(false);
try
{
if (existingJob)
{
if (!replaceExisting)
{
ThrowHelper.ThrowObjectAlreadyExistsException(newJob);
}
await Delegate.UpdateJobDetail(conn, newJob, cancellationToken).ConfigureAwait(false);
}
else
{
await Delegate.InsertJobDetail(conn, newJob, cancellationToken).ConfigureAwait(false);
}
}
catch (IOException e)
{
ThrowHelper.ThrowJobPersistenceException("Couldn't store job: " + e.Message, e);
}
catch (Exception e)
{
ThrowHelper.ThrowJobPersistenceException("Couldn't store job: " + e.Message, e);
}
}
/// <summary>
/// Check existence of a given job.
/// </summary>
protected virtual async ValueTask<bool> JobExists(
ConnectionAndTransactionHolder conn,
JobKey jobKey,
CancellationToken cancellationToken = default)
{
try
{
return await Delegate.JobExists(conn, jobKey, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
ThrowHelper.ThrowJobPersistenceException("Couldn't determine job existence (" + jobKey + "): " + e.Message, e);
return false;
}
}
/// <summary>
/// Store the given <see cref="ITrigger" />.
/// </summary>
/// <param name="newTrigger">The <see cref="ITrigger" /> to be stored.</param>
/// <param name="replaceExisting">
/// If <see langword="true" />, any <see cref="ITrigger" /> existing in
/// the <see cref="IJobStore" /> with the same name & group should
/// be over-written.
/// </param>
/// <param name="cancellationToken">The cancellation instruction.</param>
/// <exception cref="ObjectAlreadyExistsException">
/// if a <see cref="ITrigger" /> with the same name/group already
/// exists, and replaceExisting is set to false.
/// </exception>
public ValueTask<object> StoreTrigger(
IOperableTrigger newTrigger,