PsProcessProviderBase.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 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. Task.Run(async () =>
  74. {
  75. try
  76. {
  77. await TimeoutUtils.ExecuteWithTimeoutAsync(async () =>
  78. {
  79. await OnProcess().ContinueWith(task =>
  80. {
  81. ProcessDoneOk("Succesfuly done.");
  82. });
  83. }, timeout);
  84. }
  85. catch (Exception e)
  86. {
  87. await OnProcessError(e).ContinueWith(task =>
  88. {
  89. ProcessDoneFailed(e.Message, e);
  90. });
  91. }
  92. });
  93. }
  94. /// <inheritdoc />
  95. public void Stop()
  96. {
  97. if (!IsRunning)
  98. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotRunning, GetType().Name, ItemId);
  99. _cancelationToken?.Cancel();
  100. ProcessDoneFailed("Process was forced stopped.");
  101. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' was forced stopped.");
  102. }
  103. /// <summary>
  104. /// Generates all arguments collection
  105. /// </summary>
  106. /// <returns>Full scoped arguments collection</returns>
  107. public static IEnumerable<TypedArgument> CreateArguments()
  108. {
  109. var list = new List<TypedArgument>
  110. {
  111. new TypedArgument(CS_ARG_RESULT_CODE, typeof(long), true),
  112. new TypedArgument(CS_ARG_RESULT_TEXT, typeof(string), true),
  113. new TypedArgument(CS_ARG_PROCESS_TIMEOUT, typeof(TimeSpan), false)
  114. };
  115. return list;
  116. }
  117. /// <inheritdoc />
  118. public void WaitToDone()
  119. {
  120. while (IsRunning)
  121. {
  122. Task.Delay(100).Wait();
  123. };
  124. Log.Log(LogSeverityEnum.Debug, $"Provider for ItemId='{ItemId}' detect that process finished.");
  125. }
  126. #endregion
  127. #region *** Protected Operations ***
  128. protected TValue? GetArgumentValue<TValue>(string name)
  129. {
  130. if (string.IsNullOrEmpty(name))
  131. throw new ArgumentNullException(nameof(name));
  132. if (Arguments.TryGetValue(name, out var arg))
  133. return arg.GetTypedValue<TValue>();
  134. return default;
  135. }
  136. protected bool ContainsArgument(string name)
  137. {
  138. if (string.IsNullOrEmpty(name))
  139. throw new ArgumentNullException(nameof(name));
  140. return Arguments.ContainsKey(name);
  141. }
  142. protected virtual void OnValidate()
  143. {
  144. if (!ContainsArgument(CS_ARG_RESULT_CODE) || !Arguments[CS_ARG_RESULT_CODE].IsOutput)
  145. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_CODE);
  146. if (!ContainsArgument(CS_ARG_RESULT_TEXT) || !Arguments[CS_ARG_RESULT_TEXT].IsOutput)
  147. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_RESULT_TEXT);
  148. if (!ContainsArgument(CS_ARG_PROCESS_TIMEOUT) || Arguments[CS_ARG_PROCESS_TIMEOUT].IsOutput)
  149. throw new PsProcessProviderException(PsProcessProviderException.ErrorCodes.ProcessProviderNotDefinedArgument, GetType().Name, ItemId, CS_ARG_PROCESS_TIMEOUT);
  150. }
  151. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  152. protected virtual async Task OnProcessError(Exception exception)
  153. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  154. {
  155. if (exception == null)
  156. throw new ArgumentNullException(nameof(exception));
  157. if (ProcessStdOutputCallback != null)
  158. ProcessStdOutputCallback(ItemId, exception.Message);
  159. if (ContainsArgument(CS_ARG_RESULT_TEXT))
  160. Arguments[CS_ARG_RESULT_TEXT].Value = exception.Message;
  161. }
  162. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  163. protected virtual async Task OnProcess()
  164. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  165. {
  166. //nothing to do
  167. }
  168. /// <inheritdoc />
  169. protected override void OnDisposing()
  170. {
  171. _cancelationToken?.Dispose();
  172. ProcessDoneCallback = null!;
  173. ProcessStdOutputCallback = null!;
  174. _cancelationToken = null;
  175. }
  176. private void ProcessDoneFailed(string message, Exception? e = null)
  177. {
  178. Log.Log(LogSeverityEnum.Error, $"Provider running failed. Duration {(DateTime.Now - StartedTimestamp.GetValueOrDefault()).ToReadableString()}.", e);
  179. if (ProcessDoneCallback != null)
  180. ProcessDoneCallback(ItemId, PsStatusEnum.DoneFailed, message);
  181. IsRunning = false;
  182. FinishedTimestamp = DateTime.Now;
  183. }
  184. private void ProcessDoneOk(string message)
  185. {
  186. Log.Log(LogSeverityEnum.Info, $"Provider for ItemId='{ItemId}' done. Duration {(DateTime.Now - StartedTimestamp.GetValueOrDefault()).ToReadableString()}.");
  187. if (ProcessDoneCallback != null)
  188. ProcessDoneCallback(ItemId, PsStatusEnum.DoneOk, message);
  189. IsRunning = false;
  190. FinishedTimestamp = DateTime.Now;
  191. }
  192. #endregion
  193. }
  194. }