Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.DebugEngine/3.3/DebugEngine.cs @ 16749

Last change on this file since 16749 was 15584, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers on stable

File size: 10.8 KB
RevLine 
[4747]1#region License Information
2/* HeuristicLab
[15584]3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4747]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;
[4871]23using System.Linq;
[4903]24using System.Threading;
[4743]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.")]
[4871]33  public class DebugEngine : Executable, IEngine {
[4743]34
[4903]35    #region Construction and Cloning
[4871]36
[4743]37    [StorableConstructor]
[4903]38    protected DebugEngine(bool deserializing)
39      : base(deserializing) {
[4946]40      InitializeTimer();
[4871]41    }
[4946]42
[4903]43    protected DebugEngine(DebugEngine original, Cloner cloner)
44      : base(original, cloner) {
[4871]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);
[4947]48      OperatorTrace = cloner.Clone(original.OperatorTrace);
[4946]49      InitializeTimer();
50      currentOperation = cloner.Clone(original.currentOperation);
[4871]51    }
[4743]52    public DebugEngine()
53      : base() {
[4871]54      Log = new Log();
55      ExecutionStack = new ExecutionStack();
[4993]56      OperatorTrace = new OperatorTrace();
[4946]57      InitializeTimer();
[4743]58    }
59
[4871]60    public override IDeepCloneable Clone(Cloner cloner) {
61      return new DebugEngine(this, cloner);
[4743]62    }
63
[4946]64    private void InitializeTimer() {
[5240]65      timer = new System.Timers.Timer(250);
[4946]66      timer.AutoReset = true;
67      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
68    }
69
[4871]70    #endregion
[4743]71
[4871]72    #region Fields and Properties
73
74    [Storable]
[5001]75    public ILog Log { get; private set; }
[4871]76
77    [Storable]
[5001]78    public ExecutionStack ExecutionStack { get; private set; }
[4871]79
[4993]80    [Storable]
81    public OperatorTrace OperatorTrace { get; private set; }
82
[5193]83    private CancellationTokenSource cancellationTokenSource;
84    private bool stopPending;
[4871]85    private DateTime lastUpdateTime;
86    private System.Timers.Timer timer;
[4903]87
[4871]88    [Storable]
89    private IOperation currentOperation;
[5002]90    public IOperation CurrentOperation {
[4871]91      get { return currentOperation; }
92      private set {
[4946]93        if (value != currentOperation) {
94          currentOperation = value;
95          OnOperationChanged(value);
96        }
[4871]97      }
[4743]98    }
99
[4871]100    public virtual IAtomicOperation CurrentAtomicOperation {
101      get { return CurrentOperation as IAtomicOperation; }
102    }
103
104    public virtual IExecutionContext CurrentExecutionContext {
[4903]105      get { return CurrentOperation as IExecutionContext; }
[4871]106    }
107
[4947]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
[4871]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;
[4996]135      OperatorTrace.Reset();
[4871]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;
[4996]144      OperatorTrace.Reset();
[4871]145      OnPrepared();
146    }
147    protected override void OnPrepared() {
148      Log.LogMessage("Engine prepared");
149      base.OnPrepared();
150    }
151
[4909]152    public virtual void Step(bool skipStackOperations) {
[4871]153      OnStarted();
[5193]154      cancellationTokenSource = new CancellationTokenSource();
155      stopPending = false;
[9343]156      lastUpdateTime = DateTime.UtcNow;
[4871]157      timer.Start();
[5193]158      try {
159        ProcessNextOperation(true, cancellationTokenSource.Token);
160        while (skipStackOperations && !(CurrentOperation is IAtomicOperation) && CanContinue)
161          ProcessNextOperation(true, cancellationTokenSource.Token);
[15292]162      } catch (Exception ex) {
[5193]163        OnExceptionOccurred(ex);
164      }
[4871]165      timer.Stop();
[9343]166      ExecutionTime += DateTime.UtcNow - lastUpdateTime;
[5193]167      cancellationTokenSource.Dispose();
168      cancellationTokenSource = null;
169      if (stopPending) ExecutionStack.Clear();
170      if (stopPending || !CanContinue) OnStopped();
171      else OnPaused();
[4871]172    }
173
[15292]174    public override void Start(CancellationToken cancellationToken) {
175      base.Start(cancellationToken);
176      cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
[5193]177      stopPending = false;
178
[15292]179      try {
180        Run(cancellationTokenSource.Token);
181      } catch (OperationCanceledException) {
182      } catch (AggregateException ae) {
[15384]183        ae.FlattenAndHandle(new[] { typeof(OperationCanceledException) }, e => OnExceptionOccurred(e));
[15292]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();
[4871]193    }
194    protected override void OnStarted() {
195      Log.LogMessage("Engine started");
196      base.OnStarted();
197    }
198
199    public override void Pause() {
200      base.Pause();
[5193]201      cancellationTokenSource.Cancel();
[4871]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();
[5193]212      if (ExecutionState == ExecutionState.Paused) {
213        ExecutionStack.Clear();
214        OnStopped();
215      } else {
216        stopPending = true;
217        cancellationTokenSource.Cancel();
218      }
[4871]219    }
[4903]220
[4871]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) {
[5193]232      CancellationToken cancellationToken = (CancellationToken)state;
233
[4871]234      OnStarted();
[9343]235      lastUpdateTime = DateTime.UtcNow;
[4871]236      timer.Start();
[5193]237      try {
238        if (!cancellationToken.IsCancellationRequested && CanContinue)
239          ProcessNextOperation(false, cancellationToken);
240        while (!cancellationToken.IsCancellationRequested && CanContinue && !IsAtBreakpoint)
241          ProcessNextOperation(false, cancellationToken);
242        cancellationToken.ThrowIfCancellationRequested();
[15292]243      } finally {
[5193]244        timer.Stop();
[9343]245        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
[4871]246
[5193]247        if (IsAtBreakpoint)
248          Log.LogMessage(string.Format("Breaking before: {0}", CurrentAtomicOperation.Operator.Name));
249      }
[4871]250    }
251
252    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
[5240]253      System.Timers.Timer timer = (System.Timers.Timer)sender;
254      timer.Enabled = false;
[9343]255      DateTime now = DateTime.UtcNow;
[4871]256      ExecutionTime += now - lastUpdateTime;
257      lastUpdateTime = now;
[5240]258      timer.Enabled = true;
[4871]259    }
260    #endregion
261
262    #region Methods
263
264
[4947]265
[4743]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>
[5193]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");
[4871]278
[5193]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");
[4743]296      }
[5193]297      OperatorTrace.Regenerate(CurrentAtomicOperation);
[4871]298    }
299
[5193]300    protected virtual void PerformAtomicOperation(IAtomicOperation operation, CancellationToken cancellationToken) {
[4743]301      if (operation != null) {
302        try {
[5193]303          IOperation successor = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
[4871]304          if (successor != null) {
[4996]305            OperatorTrace.RegisterParenthood(operation, successor);
[4871]306            ExecutionStack.Add(successor);
[4743]307          }
[4904]308          CurrentOperation = null;
[15292]309        } catch (Exception ex) {
[15393]310          if (ex is OperationCanceledException) throw;
[5193]311          else throw new OperatorExecutionException(operation.Operator, ex);
312        }
[4743]313      }
314    }
315
[4871]316    #endregion
[4743]317  }
318}
Note: See TracBrowser for help on using the repository browser.