PsProcessProviderBase.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. using qdr.fnd.core.pqueue.Enums;
  2. using qdr.fnd.core.pqueue.Exceptions;
  3. using qdr.fnd.core.pqueue.fnd.candidates;
  4. using Quadarax.Foundation.Core.Data;
  5. using Quadarax.Foundation.Core.Logging;
  6. using Quadarax.Foundation.Core.Object;
  7. using Quadarax.Foundation.Core.Value.Extensions;
  8. namespace qdr.fnd.core.pqueue.Process
  9. {
  10. public delegate void ProcessDoneCallback(string itemId, PsStatusEnum newStatus, string message);
  11. public delegate void ProcessStdOutputCallback(string itemId, string message);
  12. public abstract class PsProcessProviderBase : DisposableObject, IPsProcessProvider
  13. {
  14. #region *** Constants ***
  15. /// <summary>
  16. /// (Output) Argument name for the result code. Type is <see cref="long"/>
  17. /// </summary>
  18. public const string CS_ARG_RESULT_CODE = "result-code";
  19. /// <summary>
  20. /// (Output) Argument name for the result test. Type is <see cref="string"/>
  21. /// </summary>
  22. public const string CS_ARG_RESULT_TEXT = "result-text";
  23. /// <summary>
  24. /// (Input) Argument name for process timeout. Type is <see cref="TimeSpan"/>
  25. /// </summary>
  26. public const string CS_ARG_PROCESS_TIMEOUT = "process-timeout";
  27. #endregion
  28. #region *** Properties ***
  29. protected ILog Log { get; private set; }
  30. protected ProcessDoneCallback ProcessDoneCallback { get; private set; }
  31. protected ProcessStdOutputCallback ProcessStdOutputCallback { get; private set; }
  32. /// <inheritdoc />
  33. public IDictionary<string, TypedArgument> Arguments { get; private set; }
  34. public bool IsRunning { get; private set; }
  35. /// <inheritdoc />
  36. public string ItemId { get; private set; }
  37. /// <inheritdoc />
  38. public DateTime? StartedTimestamp { get; private set; }
  39. /// <inheritdoc />
  40. public DateTime? FinishedTimestamp { get; private set; }
  41. #endregion
  42. #region *** Private fields ***
  43. private CancellationTokenSource? _cancelationToken;
  44. #endregion
  45. #region *** Constructors ***
  46. public PsProcessProviderBase(ProcessDoneCallback processDoneCallback, ProcessStdOutputCallback processStdOutputCallback, string itemId, TypedArgument[] arguments, ILogger logger)
  47. {
  48. if (string.IsNullOrEmpty(itemId)) throw new ArgumentNullException(nameof(itemId));
  49. ProcessDoneCallback = processDoneCallback ?? throw new ArgumentNullException(nameof(processDoneCallback));
  50. ProcessStdOutputCallback = processStdOutputCallback ?? throw new ArgumentNullException(nameof(processStdOutputCallback));
  51. ItemId = itemId;
  52. Log = logger.GetLogger(GetType());
  53. Arguments = arguments.ToDictionary(x => x.Name, x => x);
  54. _cancelationToken = new CancellationTokenSource();
  55. }
  56. #endregion
  57. #region *** Public Operations ***
  58. /// <inheritdoc />
  59. public void Validate()
  60. {
  61. OnValidate();
  62. }
  63. /// <inheritdoc />
  64. public async void Start()
  65. {
  66. if (IsRunning)
  67. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderIsRunning, GetType().Name, ItemId);
  68. Validate();
  69. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' starting.");
  70. IsRunning = true;
  71. StartedTimestamp = DateTime.Now;
  72. var timeout = GetArgumentValue<TimeSpan>(CS_ARG_PROCESS_TIMEOUT);
  73. try
  74. {
  75. await TimeoutUtils.ExecuteWithTimeoutAsync(async () =>
  76. {
  77. await OnProcess().ContinueWith(task =>
  78. {
  79. ProcessDoneOk("Succesfuly done.");
  80. });
  81. }, timeout);
  82. }
  83. catch (Exception e)
  84. {
  85. await OnProcessError(e).ContinueWith(task =>
  86. {
  87. ProcessDoneFailed(e.Message, e);
  88. });
  89. }
  90. }
  91. /// <inheritdoc />
  92. public void Stop()
  93. {
  94. if (!IsRunning)
  95. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotRunning, GetType().Name, ItemId);
  96. _cancelationToken?.Cancel();
  97. ProcessDoneFailed("Process was forced stopped.");
  98. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' was forced stopped.");
  99. }
  100. /// <summary>
  101. /// Generates all arguments collection
  102. /// </summary>
  103. /// <returns>Full scoped arguments collection</returns>
  104. public static IEnumerable<TypedArgument> CreateArguments()
  105. {
  106. var list = new List<TypedArgument>
  107. {
  108. new TypedArgument(CS_ARG_RESULT_CODE, typeof(long), true),
  109. new TypedArgument(CS_ARG_RESULT_TEXT, typeof(string), true),
  110. new TypedArgument(CS_ARG_PROCESS_TIMEOUT, typeof(TimeSpan), false)
  111. };
  112. return list;
  113. }
  114. /// <inheritdoc />
  115. public void WaitToDone()
  116. {
  117. while (IsRunning)
  118. {
  119. Task.Delay(100).Wait();
  120. };
  121. Log.Log(LogSeverityEnum.Debug, $"Provider for ItemId='{ItemId}' detect that process finished.");
  122. }
  123. #endregion
  124. #region *** Protected Operations ***
  125. protected TValue? GetArgumentValue<TValue>(string name)
  126. {
  127. if (string.IsNullOrEmpty(name))
  128. throw new ArgumentNullException(nameof(name));
  129. if (Arguments.TryGetValue(name, out var arg))
  130. return arg.GetTypedValue<TValue>();
  131. return default;
  132. }
  133. protected bool ContainsArgument(string name)
  134. {
  135. if (string.IsNullOrEmpty(name))
  136. throw new ArgumentNullException(nameof(name));
  137. return Arguments.ContainsKey(name);
  138. }
  139. protected virtual void OnValidate()
  140. {
  141. if (!ContainsArgument(CS_ARG_RESULT_CODE) || !Arguments[CS_ARG_RESULT_CODE].IsOutput)
  142. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_CODE);
  143. if (!ContainsArgument(CS_ARG_RESULT_TEXT) || !Arguments[CS_ARG_RESULT_TEXT].IsOutput)
  144. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_TEXT);
  145. if (!ContainsArgument(CS_ARG_PROCESS_TIMEOUT) || Arguments[CS_ARG_PROCESS_TIMEOUT].IsOutput)
  146. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_PROCESS_TIMEOUT);
  147. }
  148. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  149. protected virtual async Task OnProcessError(Exception exception)
  150. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  151. {
  152. if (exception == null)
  153. throw new ArgumentNullException(nameof(exception));
  154. if (ProcessStdOutputCallback != null)
  155. ProcessStdOutputCallback(ItemId, exception.Message);
  156. if (ContainsArgument(CS_ARG_RESULT_TEXT))
  157. Arguments[CS_ARG_RESULT_TEXT].Value = exception.Message;
  158. }
  159. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  160. protected virtual async Task OnProcess()
  161. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  162. {
  163. //nothing to do
  164. }
  165. /// <inheritdoc />
  166. protected override void OnDisposing()
  167. {
  168. _cancelationToken?.Dispose();
  169. ProcessDoneCallback = null!;
  170. ProcessStdOutputCallback = null!;
  171. _cancelationToken = null;
  172. }
  173. private void ProcessDoneFailed(string message, Exception? e = null)
  174. {
  175. Log.Log(LogSeverityEnum.Error, $"Provider running failed. Duration {(DateTime.Now - StartedTimestamp.GetValueOrDefault()).ToReadableString()}.", e);
  176. if (ProcessDoneCallback != null)
  177. ProcessDoneCallback(ItemId, PsStatusEnum.DoneFailed, message);
  178. IsRunning = false;
  179. FinishedTimestamp = DateTime.Now;
  180. }
  181. private void ProcessDoneOk(string message)
  182. {
  183. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' done. Duration {(DateTime.Now - StartedTimestamp.GetValueOrDefault()).ToReadableString()}.");
  184. if (ProcessDoneCallback != null)
  185. ProcessDoneCallback(ItemId, PsStatusEnum.DoneOk, message);
  186. IsRunning = false;
  187. FinishedTimestamp = DateTime.Now;
  188. }
  189. #endregion
  190. }
  191. }