Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.HiveEngine/3.4/HiveEngine.cs @ 6200

Last change on this file since 6200 was 6200, checked in by cneumuel, 13 years ago

#1233

  • stability improvements for HiveEngine
File size: 13.0 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading;
5using System.Threading.Tasks;
6using HeuristicLab.Clients.Hive;
7using HeuristicLab.Common;
8using HeuristicLab.Core;
9using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
10
11namespace HeuristicLab.HiveEngine {
12  /// <summary>
13  /// Represents an engine that executes operations which can be executed in parallel on the hive
14  /// </summary>
15  [StorableClass]
16  [Item("Hive Engine", "Engine for parallel execution on the hive. You need enable `Parallel` for at least one operator in your operator graph to have all childoperations parallelized. Also those childoperations must not have sideeffects on a higher scope.")]
17  public class HiveEngine : Engine {
18    private static object logLocker = new object();
19    private CancellationToken cancellationToken;
20   
21    [Storable]
22    private IOperator currentOperator;
23
24    [Storable]
25    public string ResourceNames { get; set; }
26
27    [Storable]
28    private int priority;
29    public int Priority {
30      get { return priority; }
31      set { priority = value; }
32    }
33
34    [Storable]
35    private TimeSpan executionTimeOnHive;
36    public TimeSpan ExecutionTimeOnHive {
37      get { return executionTimeOnHive; }
38      set {
39        if (value != executionTimeOnHive) {
40          executionTimeOnHive = value;
41          OnExecutionTimeOnHiveChanged();
42        }
43      }
44    }
45
46    [Storable]
47    private bool useLocalPlugins;
48    public bool UseLocalPlugins {
49      get { return useLocalPlugins; }
50      set { useLocalPlugins = value; }
51    }
52
53    // [Storable] -> HiveExperiment can't be storable, so RefreshableHiveExperiment can't be stored
54    private ItemCollection<RefreshableHiveExperiment> hiveExperiments = new ItemCollection<RefreshableHiveExperiment>();
55    public ItemCollection<RefreshableHiveExperiment> HiveExperiments {
56      get { return hiveExperiments; }
57      set { hiveExperiments = value; }
58    }
59
60    private List<Plugin> onlinePlugins;
61    public List<Plugin> OnlinePlugins {
62      get { return onlinePlugins; }
63      set { onlinePlugins = value; }
64    }
65
66    private List<Plugin> alreadyUploadedPlugins;
67    public List<Plugin> AlreadyUploadedPlugins {
68      get { return alreadyUploadedPlugins; }
69      set { alreadyUploadedPlugins = value; }
70    }
71
72    #region constructors and cloning
73    public HiveEngine() {
74      ResourceNames = "HEAL";
75      Priority = 0;
76    }
77
78    [StorableConstructor]
79    protected HiveEngine(bool deserializing) : base(deserializing) { }
80    protected HiveEngine(HiveEngine original, Cloner cloner)
81      : base(original, cloner) {
82      this.ResourceNames = original.ResourceNames;
83      this.currentOperator = cloner.Clone(original.currentOperator);
84      this.priority = original.priority;
85      this.executionTimeOnHive = original.executionTimeOnHive;
86      this.useLocalPlugins = original.useLocalPlugins;
87      this.hiveExperiments = cloner.Clone(original.hiveExperiments);
88    }
89    public override IDeepCloneable Clone(Cloner cloner) {
90      return new HiveEngine(this, cloner);
91    }
92    #endregion
93
94    #region Events
95    protected override void OnPrepared() {
96      base.OnPrepared();
97      this.ExecutionTimeOnHive = TimeSpan.Zero;
98    }
99
100    public event EventHandler ExecutionTimeOnHiveChanged;
101    protected virtual void OnExecutionTimeOnHiveChanged() {
102      var handler = ExecutionTimeOnHiveChanged;
103      if (handler != null) handler(this, EventArgs.Empty);
104    }
105    #endregion
106
107    protected override void Run(CancellationToken cancellationToken) {
108      this.cancellationToken = cancellationToken;
109      Run(ExecutionStack);
110    }
111
112    private void Run(object state) {
113      Stack<IOperation> executionStack = (Stack<IOperation>)state;
114      IOperation next;
115      OperationCollection coll;
116      IAtomicOperation operation;
117      TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
118
119      this.OnlinePlugins = ServiceLocator.Instance.CallHiveService(s => s.GetPlugins()).Where(x => x.IsLocal == false).ToList();
120      this.AlreadyUploadedPlugins = new List<Plugin>();
121
122      while (ExecutionStack.Count > 0) {
123        cancellationToken.ThrowIfCancellationRequested();
124
125        next = ExecutionStack.Pop();
126        if (next is OperationCollection) {
127          coll = (OperationCollection)next;
128          if (coll.Parallel) {
129            // clone the parent scope here and reuse it for each operation. otherwise for each job the whole scope-tree first needs to be copied and then cleaned, which causes a lot of work for the Garbage Collector
130            IScope parentScopeClone = (IScope)((IAtomicOperation)coll.First()).Scope.Parent.Clone();
131            parentScopeClone.SubScopes.Clear();
132            parentScopeClone.ClearParentScopes();
133
134            EngineJob[] jobs = new EngineJob[coll.Count];
135            for (int i = 0; i < coll.Count; i++) {
136              jobs[i] = new EngineJob(coll[i], new SequentialEngine.SequentialEngine());
137            }
138
139            IScope[] scopes = ExecuteOnHive(jobs, parentScopeClone, cancellationToken);
140            //IScope[] scopes = ExecuteLocally(jobs, parentScopeClone, cancellationToken);
141
142            for (int i = 0; i < coll.Count; i++) {
143              if (coll[i] is IAtomicOperation) {
144                ExchangeScope(scopes[i], ((IAtomicOperation)coll[i]).Scope);
145              } else if (coll[i] is OperationCollection) {
146                // todo ??
147              }
148            }
149          } else {
150            for (int i = coll.Count - 1; i >= 0; i--)
151              if (coll[i] != null) executionStack.Push(coll[i]);
152          }
153        } else if (next is IAtomicOperation) {
154          operation = (IAtomicOperation)next;
155          try {
156            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
157          }
158          catch (Exception ex) {
159            ExecutionStack.Push(operation);
160            if (ex is OperationCanceledException) throw ex;
161            else throw new OperatorExecutionException(operation.Operator, ex);
162          }
163          if (next != null) ExecutionStack.Push(next);
164
165          if (operation.Operator.Breakpoint) {
166            LogMessage(string.Format("Breakpoint: {0}", operation.Operator.Name != string.Empty ? operation.Operator.Name : operation.Operator.ItemName));
167            Pause();
168          }
169        }
170      }
171    }
172
173    private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
174      e.SetObserved(); // avoid crash of process
175    }
176
177    private IRandom FindRandomParameter(IExecutionContext ec) {
178      try {
179        if (ec == null)
180          return null;
181
182        foreach (var p in ec.Parameters) {
183          if (p.Name == "Random" && p is IValueParameter)
184            return ((IValueParameter)p).Value as IRandom;
185        }
186        return FindRandomParameter(ec.Parent);
187      }
188      catch { return null; }
189    }
190
191    private static void ReIntegrateScope(IAtomicOperation source, IAtomicOperation target) {
192      ExchangeScope(source.Scope, target.Scope);
193    }
194
195    private static void ExchangeScope(IScope source, IScope target) {
196      target.Variables.Clear();
197      target.Variables.AddRange(source.Variables);
198      target.SubScopes.Clear();
199      target.SubScopes.AddRange(source.SubScopes);
200      // TODO: validate if parent scopes match - otherwise source is invalid
201    }
202
203    /// <summary>
204    /// This method blocks until all jobs are finished
205    /// TODO: Cancelation needs to be refined; all tasks currently stay in Semaphore.WaitOne after cancelation
206    /// </summary>
207    /// <param name="jobs"></param>
208    private IScope[] ExecuteOnHive(EngineJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
209      LogMessage(string.Format("Executing {0} operations on the hive.", jobs.Length));
210      IScope[] scopes = new Scope[jobs.Length];
211      object locker = new object();
212      IDictionary<Guid, int> jobIndices = new Dictionary<Guid, int>();
213      var hiveExperiment = new HiveExperiment();
214
215      try {
216        List<Guid> remainingJobIds = new List<Guid>();
217
218        // create hive experiment
219        hiveExperiment.Name = "HiveEngine Run " + hiveExperiments.Count;
220        hiveExperiment.DateCreated = DateTime.Now;
221        hiveExperiment.UseLocalPlugins = this.UseLocalPlugins;
222        hiveExperiment.ResourceNames = this.ResourceNames;
223        var refreshableHiveExperiment = new RefreshableHiveExperiment(hiveExperiment);
224        refreshableHiveExperiment.IsControllable = false;
225        hiveExperiments.Add(refreshableHiveExperiment);
226
227        // create upload-tasks
228        var uploadTasks = new List<Task<Job>>();
229        for (int i = 0; i < jobs.Length; i++) {
230          hiveExperiment.HiveJobs.Add(new EngineHiveJob(jobs[i], parentScopeClone));
231
232          // shuffle random variable to avoid the same random sequence in each operation; todo: does not yet work (it cannot find the random variable)
233          IRandom random = FindRandomParameter(jobs[i].InitialOperation as IExecutionContext);
234          if (random != null)
235            random.Reset(random.Next());
236        }
237        ExperimentManagerClient.StartExperiment((e) => {
238          LogException(e);
239        }, refreshableHiveExperiment);
240
241        // do polling until experiment is finished and all jobs are downloaded
242        while (!refreshableHiveExperiment.AllJobsFinished()) {
243          Thread.Sleep(500);
244          this.ExecutionTimeOnHive = TimeSpan.FromMilliseconds(hiveExperiments.Sum(x => x.HiveExperiment.ExecutionTime.TotalMilliseconds));
245          cancellationToken.ThrowIfCancellationRequested();
246        }
247        LogMessage(string.Format("{0} finished (TotalExecutionTime: {1}).", refreshableHiveExperiment.ToString(), refreshableHiveExperiment.HiveExperiment.ExecutionTime));
248
249        // get scopes
250        int j = 0;
251        foreach (var hiveJob in hiveExperiment.HiveJobs) {
252          var scope = ((IAtomicOperation) ((EngineJob)hiveJob.ItemJob).InitialOperation).Scope;
253          scopes[j++] = scope;
254        }
255        refreshableHiveExperiment.RefreshAutomatically = false;
256        DeleteHiveExperiment(hiveExperiment.Id);
257        ClearData(refreshableHiveExperiment);
258        return scopes;
259      }
260      catch (OperationCanceledException e) {
261        lock (locker) {
262          if (jobIndices != null) DeleteHiveExperiment(hiveExperiment.Id);
263        }
264        throw e;
265      }
266      catch (Exception e) {
267        lock (locker) {
268          if (jobIndices != null) DeleteHiveExperiment(hiveExperiment.Id);
269        }
270        LogException(e);
271        throw e;
272      }
273    }
274
275    private void ClearData(RefreshableHiveExperiment refreshableHiveExperiment) {
276      var jobs = refreshableHiveExperiment.HiveExperiment.GetAllHiveJobs();
277      foreach (var job in jobs) {
278        job.ClearData();
279      }
280    }
281
282    private void DeleteHiveExperiment(Guid hiveExperimentId) {
283      ExperimentManagerClient.TryAndRepeat(() => {
284        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(hiveExperimentId));
285      }, 5, string.Format("Could not delete jobs"));
286    }
287   
288    private List<Guid> GetResourceIds() {
289      return ServiceLocator.Instance.CallHiveService(service => {
290        var resourceNames = ResourceNames.Split(';');
291        var resourceIds = new List<Guid>();
292        foreach (var resourceName in resourceNames) {
293          Guid resourceId = service.GetResourceId(resourceName);
294          if (resourceId == Guid.Empty) {
295            throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
296          }
297          resourceIds.Add(resourceId);
298        }
299        return resourceIds;
300      });
301    }
302
303    /// <summary>
304    /// Threadsafe message logging
305    /// </summary>
306    private void LogMessage(string message) {
307      lock (logLocker) {
308        Log.LogMessage(message);
309      }
310    }
311
312    /// <summary>
313    /// Threadsafe exception logging
314    /// </summary>
315    private void LogException(Exception exception) {
316      lock (logLocker) {
317        Log.LogException(exception);
318      }
319    }
320
321    // testfunction:
322    //private IScope[] ExecuteLocally(EngineJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
323    //  IScope[] scopes = new Scope[jobs.Length];
324    //  for (int i = 0; i < jobs.Length; i++) {
325    //    var serialized = PersistenceUtil.Serialize(jobs[i]);
326    //    var deserialized = PersistenceUtil.Deserialize<IJob>(serialized);
327    //    deserialized.Start();
328    //    while (deserialized.ExecutionState != ExecutionState.Stopped) {
329    //      Thread.Sleep(100);
330    //    }
331    //    var serialized2 = PersistenceUtil.Serialize(deserialized);
332    //    var deserialized2 = PersistenceUtil.Deserialize<EngineJob>(serialized2);
333    //    var newScope = ((IAtomicOperation)deserialized2.InitialOperation).Scope;
334    //    scopes[i] = newScope;
335    //  }
336    //  return scopes;
337    //}
338  }
339}
Note: See TracBrowser for help on using the repository browser.