Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14615 was 13349, checked in by jkarder, 9 years ago

#2258: added StartAsync to IExecutable

File size: 11.2 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 System.Threading.Tasks;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.DebugEngine {
31
32  [StorableClass]
33  [Item("Debug Engine", "Engine for debugging algorithms.")]
34  public class DebugEngine : Executable, IEngine {
35
36    #region Construction and Cloning
37
38    [StorableConstructor]
39    protected DebugEngine(bool deserializing)
40      : base(deserializing) {
41      InitializeTimer();
42    }
43
44    protected DebugEngine(DebugEngine original, Cloner cloner)
45      : base(original, cloner) {
46      if (original.ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
47      Log = cloner.Clone(original.Log);
48      ExecutionStack = cloner.Clone(original.ExecutionStack);
49      OperatorTrace = cloner.Clone(original.OperatorTrace);
50      InitializeTimer();
51      currentOperation = cloner.Clone(original.currentOperation);
52    }
53    public DebugEngine()
54      : base() {
55      Log = new Log();
56      ExecutionStack = new ExecutionStack();
57      OperatorTrace = new OperatorTrace();
58      InitializeTimer();
59    }
60
61    public override IDeepCloneable Clone(Cloner cloner) {
62      return new DebugEngine(this, cloner);
63    }
64
65    private void InitializeTimer() {
66      timer = new System.Timers.Timer(250);
67      timer.AutoReset = true;
68      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
69    }
70
71    #endregion
72
73    #region Fields and Properties
74
75    [Storable]
76    public ILog Log { get; private set; }
77
78    [Storable]
79    public ExecutionStack ExecutionStack { get; private set; }
80
81    [Storable]
82    public OperatorTrace OperatorTrace { get; private set; }
83
84    private CancellationTokenSource cancellationTokenSource;
85    private bool stopPending;
86    private DateTime lastUpdateTime;
87    private System.Timers.Timer timer;
88
89    [Storable]
90    private IOperation currentOperation;
91    public IOperation CurrentOperation {
92      get { return currentOperation; }
93      private set {
94        if (value != currentOperation) {
95          currentOperation = value;
96          OnOperationChanged(value);
97        }
98      }
99    }
100
101    public virtual IAtomicOperation CurrentAtomicOperation {
102      get { return CurrentOperation as IAtomicOperation; }
103    }
104
105    public virtual IExecutionContext CurrentExecutionContext {
106      get { return CurrentOperation as IExecutionContext; }
107    }
108
109    public virtual bool CanContinue {
110      get { return CurrentOperation != null || ExecutionStack.Count > 0; }
111    }
112
113    public virtual bool IsAtBreakpoint {
114      get { return CurrentAtomicOperation != null && CurrentAtomicOperation.Operator != null && CurrentAtomicOperation.Operator.Breakpoint; }
115    }
116
117    #endregion
118
119    #region Events
120
121    public event EventHandler<OperationChangedEventArgs> CurrentOperationChanged;
122    protected virtual void OnOperationChanged(IOperation newOperation) {
123      EventHandler<OperationChangedEventArgs> handler = CurrentOperationChanged;
124      if (handler != null) {
125        handler(this, new OperationChangedEventArgs(newOperation));
126      }
127    }
128
129    #endregion
130
131    #region Std Methods
132    public sealed override void Prepare() {
133      base.Prepare();
134      ExecutionStack.Clear();
135      CurrentOperation = null;
136      OperatorTrace.Reset();
137      OnPrepared();
138    }
139    public void Prepare(IOperation initialOperation) {
140      base.Prepare();
141      ExecutionStack.Clear();
142      if (initialOperation != null)
143        ExecutionStack.Add(initialOperation);
144      CurrentOperation = null;
145      OperatorTrace.Reset();
146      OnPrepared();
147    }
148    protected override void OnPrepared() {
149      Log.LogMessage("Engine prepared");
150      base.OnPrepared();
151    }
152
153    public virtual void Step(bool skipStackOperations) {
154      OnStarted();
155      cancellationTokenSource = new CancellationTokenSource();
156      stopPending = false;
157      lastUpdateTime = DateTime.UtcNow;
158      timer.Start();
159      try {
160        ProcessNextOperation(true, cancellationTokenSource.Token);
161        while (skipStackOperations && !(CurrentOperation is IAtomicOperation) && CanContinue)
162          ProcessNextOperation(true, cancellationTokenSource.Token);
163      }
164      catch (Exception ex) {
165        OnExceptionOccurred(ex);
166      }
167      timer.Stop();
168      ExecutionTime += DateTime.UtcNow - lastUpdateTime;
169      cancellationTokenSource.Dispose();
170      cancellationTokenSource = null;
171      if (stopPending) ExecutionStack.Clear();
172      if (stopPending || !CanContinue) OnStopped();
173      else OnPaused();
174    }
175
176    public override async Task StartAsync(CancellationToken cancellationToken) {
177      await base.StartAsync(cancellationToken);
178      cancellationTokenSource = new CancellationTokenSource();
179      stopPending = false;
180      using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationToken)) {
181        Task task = Task.Factory.StartNew(Run, cts.Token, cts.Token);
182        await task.ContinueWith(t => {
183          try {
184            t.Wait();
185          }
186          catch (AggregateException ex) {
187            try {
188              ex.Flatten().Handle(x => x is OperationCanceledException);
189            }
190            catch (AggregateException remaining) {
191              if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
192              else OnExceptionOccurred(remaining);
193            }
194          }
195          cancellationTokenSource.Dispose();
196          cancellationTokenSource = null;
197
198          if (stopPending) ExecutionStack.Clear();
199          if (stopPending || !CanContinue) OnStopped();
200          else OnPaused();
201        });
202      }
203    }
204
205    protected override void OnStarted() {
206      Log.LogMessage("Engine started");
207      base.OnStarted();
208    }
209
210    public override void Pause() {
211      base.Pause();
212      cancellationTokenSource.Cancel();
213    }
214
215    protected override void OnPaused() {
216      Log.LogMessage("Engine paused");
217      base.OnPaused();
218    }
219
220    public override void Stop() {
221      CurrentOperation = null;
222      base.Stop();
223      if (ExecutionState == ExecutionState.Paused) {
224        ExecutionStack.Clear();
225        OnStopped();
226      } else {
227        stopPending = true;
228        cancellationTokenSource.Cancel();
229      }
230    }
231
232    protected override void OnStopped() {
233      Log.LogMessage("Engine stopped");
234      base.OnStopped();
235    }
236
237    protected override void OnExceptionOccurred(Exception exception) {
238      Log.LogException(exception);
239      base.OnExceptionOccurred(exception);
240    }
241
242    private void Run(object state) {
243      CancellationToken cancellationToken = (CancellationToken)state;
244
245      OnStarted();
246      lastUpdateTime = DateTime.UtcNow;
247      timer.Start();
248      try {
249        if (!cancellationToken.IsCancellationRequested && CanContinue)
250          ProcessNextOperation(false, cancellationToken);
251        while (!cancellationToken.IsCancellationRequested && CanContinue && !IsAtBreakpoint)
252          ProcessNextOperation(false, cancellationToken);
253        cancellationToken.ThrowIfCancellationRequested();
254      }
255      finally {
256        timer.Stop();
257        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
258
259        if (IsAtBreakpoint)
260          Log.LogMessage(string.Format("Breaking before: {0}", CurrentAtomicOperation.Operator.Name));
261      }
262    }
263
264    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
265      System.Timers.Timer timer = (System.Timers.Timer)sender;
266      timer.Enabled = false;
267      DateTime now = DateTime.UtcNow;
268      ExecutionTime += now - lastUpdateTime;
269      lastUpdateTime = now;
270      timer.Enabled = true;
271    }
272    #endregion
273
274    #region Methods
275
276
277
278    /// <summary>
279    /// Deals with the next operation, if it is an <see cref="AtomicOperation"/> it is executed,
280    /// if it is a <see cref="CompositeOperation"/> its single operations are pushed on the execution stack.
281    /// </summary>
282    /// <remarks>If an error occurs during the execution the operation is aborted and the operation
283    /// is pushed on the stack again.<br/>
284    /// If the execution was successful <see cref="EngineBase.OnOperationExecuted"/> is called.</remarks>
285    protected virtual void ProcessNextOperation(bool logOperations, CancellationToken cancellationToken) {
286      IAtomicOperation atomicOperation = CurrentOperation as IAtomicOperation;
287      OperationCollection operations = CurrentOperation as OperationCollection;
288      if (atomicOperation != null && operations != null)
289        throw new InvalidOperationException("Current operation is both atomic and an operation collection");
290
291      if (atomicOperation != null) {
292        if (logOperations)
293          Log.LogMessage(string.Format("Performing atomic operation {0}", Utils.Name(atomicOperation)));
294        PerformAtomicOperation(atomicOperation, cancellationToken);
295      } else if (operations != null) {
296        if (logOperations)
297          Log.LogMessage("Expanding operation collection");
298        ExecutionStack.AddRange(operations.Reverse());
299        CurrentOperation = null;
300      } else if (ExecutionStack.Count > 0) {
301        if (logOperations)
302          Log.LogMessage("Popping execution stack");
303        CurrentOperation = ExecutionStack.Last();
304        ExecutionStack.RemoveAt(ExecutionStack.Count - 1);
305      } else {
306        if (logOperations)
307          Log.LogMessage("Nothing to do");
308      }
309      OperatorTrace.Regenerate(CurrentAtomicOperation);
310    }
311
312    protected virtual void PerformAtomicOperation(IAtomicOperation operation, CancellationToken cancellationToken) {
313      if (operation != null) {
314        try {
315          IOperation successor = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
316          if (successor != null) {
317            OperatorTrace.RegisterParenthood(operation, successor);
318            ExecutionStack.Add(successor);
319          }
320          CurrentOperation = null;
321        }
322        catch (Exception ex) {
323          if (ex is OperationCanceledException) throw ex;
324          else throw new OperatorExecutionException(operation.Operator, ex);
325        }
326      }
327    }
328
329    #endregion
330  }
331}
Note: See TracBrowser for help on using the repository browser.