Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2913_MatlabScriptProblemInstanceProvider/HeuristicLab.DebugEngine/3.3/DebugEngine.cs @ 17328

Last change on this file since 17328 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 10.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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        ae.FlattenAndHandle(new[] { typeof(OperationCanceledException) }, e => OnExceptionOccurred(e));
184      } catch (Exception e) {
185        OnExceptionOccurred(e);
186      }
187
188      cancellationTokenSource.Dispose();
189      cancellationTokenSource = null;
190      if (stopPending) ExecutionStack.Clear();
191      if (stopPending || !CanContinue) OnStopped();
192      else OnPaused();
193    }
194    protected override void OnStarted() {
195      Log.LogMessage("Engine started");
196      base.OnStarted();
197    }
198
199    public override void Pause() {
200      base.Pause();
201      cancellationTokenSource.Cancel();
202    }
203
204    protected override void OnPaused() {
205      Log.LogMessage("Engine paused");
206      base.OnPaused();
207    }
208
209    public override void Stop() {
210      CurrentOperation = null;
211      base.Stop();
212      if (ExecutionState == ExecutionState.Paused) {
213        ExecutionStack.Clear();
214        OnStopped();
215      } else {
216        stopPending = true;
217        cancellationTokenSource.Cancel();
218      }
219    }
220
221    protected override void OnStopped() {
222      Log.LogMessage("Engine stopped");
223      base.OnStopped();
224    }
225
226    protected override void OnExceptionOccurred(Exception exception) {
227      Log.LogException(exception);
228      base.OnExceptionOccurred(exception);
229    }
230
231    private void Run(object state) {
232      CancellationToken cancellationToken = (CancellationToken)state;
233
234      OnStarted();
235      lastUpdateTime = DateTime.UtcNow;
236      timer.Start();
237      try {
238        if (!cancellationToken.IsCancellationRequested && CanContinue)
239          ProcessNextOperation(false, cancellationToken);
240        while (!cancellationToken.IsCancellationRequested && CanContinue && !IsAtBreakpoint)
241          ProcessNextOperation(false, cancellationToken);
242        cancellationToken.ThrowIfCancellationRequested();
243      } finally {
244        timer.Stop();
245        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
246
247        if (IsAtBreakpoint)
248          Log.LogMessage(string.Format("Breaking before: {0}", CurrentAtomicOperation.Operator.Name));
249      }
250    }
251
252    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
253      System.Timers.Timer timer = (System.Timers.Timer)sender;
254      timer.Enabled = false;
255      DateTime now = DateTime.UtcNow;
256      ExecutionTime += now - lastUpdateTime;
257      lastUpdateTime = now;
258      timer.Enabled = true;
259    }
260    #endregion
261
262    #region Methods
263
264
265
266    /// <summary>
267    /// Deals with the next operation, if it is an <see cref="AtomicOperation"/> it is executed,
268    /// if it is a <see cref="CompositeOperation"/> its single operations are pushed on the execution stack.
269    /// </summary>
270    /// <remarks>If an error occurs during the execution the operation is aborted and the operation
271    /// is pushed on the stack again.<br/>
272    /// If the execution was successful <see cref="EngineBase.OnOperationExecuted"/> is called.</remarks>
273    protected virtual void ProcessNextOperation(bool logOperations, CancellationToken cancellationToken) {
274      IAtomicOperation atomicOperation = CurrentOperation as IAtomicOperation;
275      OperationCollection operations = CurrentOperation as OperationCollection;
276      if (atomicOperation != null && operations != null)
277        throw new InvalidOperationException("Current operation is both atomic and an operation collection");
278
279      if (atomicOperation != null) {
280        if (logOperations)
281          Log.LogMessage(string.Format("Performing atomic operation {0}", Utils.Name(atomicOperation)));
282        PerformAtomicOperation(atomicOperation, cancellationToken);
283      } else if (operations != null) {
284        if (logOperations)
285          Log.LogMessage("Expanding operation collection");
286        ExecutionStack.AddRange(operations.Reverse());
287        CurrentOperation = null;
288      } else if (ExecutionStack.Count > 0) {
289        if (logOperations)
290          Log.LogMessage("Popping execution stack");
291        CurrentOperation = ExecutionStack.Last();
292        ExecutionStack.RemoveAt(ExecutionStack.Count - 1);
293      } else {
294        if (logOperations)
295          Log.LogMessage("Nothing to do");
296      }
297      OperatorTrace.Regenerate(CurrentAtomicOperation);
298    }
299
300    protected virtual void PerformAtomicOperation(IAtomicOperation operation, CancellationToken cancellationToken) {
301      if (operation != null) {
302        try {
303          IOperation successor = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
304          if (successor != null) {
305            OperatorTrace.RegisterParenthood(operation, successor);
306            ExecutionStack.Add(successor);
307          }
308          CurrentOperation = null;
309        } catch (Exception ex) {
310          if (ex is OperationCanceledException) throw;
311          else throw new OperatorExecutionException(operation.Operator, ex);
312        }
313      }
314    }
315
316    #endregion
317  }
318}
Note: See TracBrowser for help on using the repository browser.