Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.DebugEngine/3.3/DebugEngine.cs @ 15218

Last change on this file since 15218 was 15065, checked in by jkarder, 7 years ago

#2258: refactored async methods

  • synchronously called IExecutables are now executed in the caller's thread
  • removed old synchronization code from unit tests
File size: 10.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Linq;
24using System.Threading;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.DebugEngine {
30
31  [StorableClass]
32  [Item("Debug Engine", "Engine for debugging algorithms.")]
33  public class DebugEngine : Executable, IEngine {
34
35    #region Construction and Cloning
36
37    [StorableConstructor]
38    protected DebugEngine(bool deserializing)
39      : base(deserializing) {
40      InitializeTimer();
41    }
42
43    protected DebugEngine(DebugEngine original, Cloner cloner)
44      : base(original, cloner) {
45      if (original.ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
46      Log = cloner.Clone(original.Log);
47      ExecutionStack = cloner.Clone(original.ExecutionStack);
48      OperatorTrace = cloner.Clone(original.OperatorTrace);
49      InitializeTimer();
50      currentOperation = cloner.Clone(original.currentOperation);
51    }
52    public DebugEngine()
53      : base() {
54      Log = new Log();
55      ExecutionStack = new ExecutionStack();
56      OperatorTrace = new OperatorTrace();
57      InitializeTimer();
58    }
59
60    public override IDeepCloneable Clone(Cloner cloner) {
61      return new DebugEngine(this, cloner);
62    }
63
64    private void InitializeTimer() {
65      timer = new System.Timers.Timer(250);
66      timer.AutoReset = true;
67      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
68    }
69
70    #endregion
71
72    #region Fields and Properties
73
74    [Storable]
75    public ILog Log { get; private set; }
76
77    [Storable]
78    public ExecutionStack ExecutionStack { get; private set; }
79
80    [Storable]
81    public OperatorTrace OperatorTrace { get; private set; }
82
83    private CancellationTokenSource cancellationTokenSource;
84    private bool stopPending;
85    private DateTime lastUpdateTime;
86    private System.Timers.Timer timer;
87
88    [Storable]
89    private IOperation currentOperation;
90    public IOperation CurrentOperation {
91      get { return currentOperation; }
92      private set {
93        if (value != currentOperation) {
94          currentOperation = value;
95          OnOperationChanged(value);
96        }
97      }
98    }
99
100    public virtual IAtomicOperation CurrentAtomicOperation {
101      get { return CurrentOperation as IAtomicOperation; }
102    }
103
104    public virtual IExecutionContext CurrentExecutionContext {
105      get { return CurrentOperation as IExecutionContext; }
106    }
107
108    public virtual bool CanContinue {
109      get { return CurrentOperation != null || ExecutionStack.Count > 0; }
110    }
111
112    public virtual bool IsAtBreakpoint {
113      get { return CurrentAtomicOperation != null && CurrentAtomicOperation.Operator != null && CurrentAtomicOperation.Operator.Breakpoint; }
114    }
115
116    #endregion
117
118    #region Events
119
120    public event EventHandler<OperationChangedEventArgs> CurrentOperationChanged;
121    protected virtual void OnOperationChanged(IOperation newOperation) {
122      EventHandler<OperationChangedEventArgs> handler = CurrentOperationChanged;
123      if (handler != null) {
124        handler(this, new OperationChangedEventArgs(newOperation));
125      }
126    }
127
128    #endregion
129
130    #region Std Methods
131    public sealed override void Prepare() {
132      base.Prepare();
133      ExecutionStack.Clear();
134      CurrentOperation = null;
135      OperatorTrace.Reset();
136      OnPrepared();
137    }
138    public void Prepare(IOperation initialOperation) {
139      base.Prepare();
140      ExecutionStack.Clear();
141      if (initialOperation != null)
142        ExecutionStack.Add(initialOperation);
143      CurrentOperation = null;
144      OperatorTrace.Reset();
145      OnPrepared();
146    }
147    protected override void OnPrepared() {
148      Log.LogMessage("Engine prepared");
149      base.OnPrepared();
150    }
151
152    public virtual void Step(bool skipStackOperations) {
153      OnStarted();
154      cancellationTokenSource = new CancellationTokenSource();
155      stopPending = false;
156      lastUpdateTime = DateTime.UtcNow;
157      timer.Start();
158      try {
159        ProcessNextOperation(true, cancellationTokenSource.Token);
160        while (skipStackOperations && !(CurrentOperation is IAtomicOperation) && CanContinue)
161          ProcessNextOperation(true, cancellationTokenSource.Token);
162      } catch (Exception ex) {
163        OnExceptionOccurred(ex);
164      }
165      timer.Stop();
166      ExecutionTime += DateTime.UtcNow - lastUpdateTime;
167      cancellationTokenSource.Dispose();
168      cancellationTokenSource = null;
169      if (stopPending) ExecutionStack.Clear();
170      if (stopPending || !CanContinue) OnStopped();
171      else OnPaused();
172    }
173
174    public override void Start(CancellationToken cancellationToken) {
175      base.Start(cancellationToken);
176      cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
177      stopPending = false;
178
179      try {
180        Run(cancellationTokenSource.Token);
181      } catch (OperationCanceledException) {
182      } catch (AggregateException ae) {
183        if (ae.InnerExceptions.Count == 1) OnExceptionOccurred(ae.InnerExceptions[0]);
184        else OnExceptionOccurred(ae);
185      } catch (Exception e) {
186        OnExceptionOccurred(e);
187      }
188
189      cancellationTokenSource.Dispose();
190      cancellationTokenSource = null;
191      if (stopPending) ExecutionStack.Clear();
192      if (stopPending || !CanContinue) OnStopped();
193      else OnPaused();
194    }
195    protected override void OnStarted() {
196      Log.LogMessage("Engine started");
197      base.OnStarted();
198    }
199
200    public override void Pause() {
201      base.Pause();
202      cancellationTokenSource.Cancel();
203    }
204
205    protected override void OnPaused() {
206      Log.LogMessage("Engine paused");
207      base.OnPaused();
208    }
209
210    public override void Stop() {
211      CurrentOperation = null;
212      base.Stop();
213      if (ExecutionState == ExecutionState.Paused) {
214        ExecutionStack.Clear();
215        OnStopped();
216      } else {
217        stopPending = true;
218        cancellationTokenSource.Cancel();
219      }
220    }
221
222    protected override void OnStopped() {
223      Log.LogMessage("Engine stopped");
224      base.OnStopped();
225    }
226
227    protected override void OnExceptionOccurred(Exception exception) {
228      Log.LogException(exception);
229      base.OnExceptionOccurred(exception);
230    }
231
232    private void Run(object state) {
233      CancellationToken cancellationToken = (CancellationToken)state;
234
235      OnStarted();
236      lastUpdateTime = DateTime.UtcNow;
237      timer.Start();
238      try {
239        if (!cancellationToken.IsCancellationRequested && CanContinue)
240          ProcessNextOperation(false, cancellationToken);
241        while (!cancellationToken.IsCancellationRequested && CanContinue && !IsAtBreakpoint)
242          ProcessNextOperation(false, cancellationToken);
243        cancellationToken.ThrowIfCancellationRequested();
244      } finally {
245        timer.Stop();
246        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
247
248        if (IsAtBreakpoint)
249          Log.LogMessage(string.Format("Breaking before: {0}", CurrentAtomicOperation.Operator.Name));
250      }
251    }
252
253    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
254      System.Timers.Timer timer = (System.Timers.Timer)sender;
255      timer.Enabled = false;
256      DateTime now = DateTime.UtcNow;
257      ExecutionTime += now - lastUpdateTime;
258      lastUpdateTime = now;
259      timer.Enabled = true;
260    }
261    #endregion
262
263    #region Methods
264
265
266
267    /// <summary>
268    /// Deals with the next operation, if it is an <see cref="AtomicOperation"/> it is executed,
269    /// if it is a <see cref="CompositeOperation"/> its single operations are pushed on the execution stack.
270    /// </summary>
271    /// <remarks>If an error occurs during the execution the operation is aborted and the operation
272    /// is pushed on the stack again.<br/>
273    /// If the execution was successful <see cref="EngineBase.OnOperationExecuted"/> is called.</remarks>
274    protected virtual void ProcessNextOperation(bool logOperations, CancellationToken cancellationToken) {
275      IAtomicOperation atomicOperation = CurrentOperation as IAtomicOperation;
276      OperationCollection operations = CurrentOperation as OperationCollection;
277      if (atomicOperation != null && operations != null)
278        throw new InvalidOperationException("Current operation is both atomic and an operation collection");
279
280      if (atomicOperation != null) {
281        if (logOperations)
282          Log.LogMessage(string.Format("Performing atomic operation {0}", Utils.Name(atomicOperation)));
283        PerformAtomicOperation(atomicOperation, cancellationToken);
284      } else if (operations != null) {
285        if (logOperations)
286          Log.LogMessage("Expanding operation collection");
287        ExecutionStack.AddRange(operations.Reverse());
288        CurrentOperation = null;
289      } else if (ExecutionStack.Count > 0) {
290        if (logOperations)
291          Log.LogMessage("Popping execution stack");
292        CurrentOperation = ExecutionStack.Last();
293        ExecutionStack.RemoveAt(ExecutionStack.Count - 1);
294      } else {
295        if (logOperations)
296          Log.LogMessage("Nothing to do");
297      }
298      OperatorTrace.Regenerate(CurrentAtomicOperation);
299    }
300
301    protected virtual void PerformAtomicOperation(IAtomicOperation operation, CancellationToken cancellationToken) {
302      if (operation != null) {
303        try {
304          IOperation successor = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
305          if (successor != null) {
306            OperatorTrace.RegisterParenthood(operation, successor);
307            ExecutionStack.Add(successor);
308          }
309          CurrentOperation = null;
310        } catch (Exception ex) {
311          if (ex is OperationCanceledException) throw ex;
312          else throw new OperatorExecutionException(operation.Operator, ex);
313        }
314      }
315    }
316
317    #endregion
318  }
319}
Note: See TracBrowser for help on using the repository browser.