Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1233

  • created events when statelog changed
  • fixed memory leak in hiveengine
  • extended timeout for long running transactions and database contexts (when jobdata is stored)
  • replaced random guids in database with sequential guids for performance reasons
  • minor fixes and cleanups
File size: 16.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using System.Threading.Tasks;
27using HeuristicLab.Clients.Hive;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.HiveEngine {
33  /// <summary>
34  /// Represents an engine that executes operations which can be executed in parallel on the hive
35  /// </summary>
36  [StorableClass]
37  [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.")]
38  public class HiveEngine : Engine {
39    private static object locker = new object();
40    private static object logLocker = new object();
41    private CancellationToken cancellationToken;
42    private bool firstRun = true;
43
44    [Storable]
45    private IOperator currentOperator;
46
47    [Storable]
48    public string ResourceNames { get; set; }
49
50    [Storable]
51    private int priority;
52    public int Priority {
53      get { return priority; }
54      set { priority = value; }
55    }
56
57    [Storable]
58    private TimeSpan executionTimeOnHive;
59    public TimeSpan ExecutionTimeOnHive {
60      get { return executionTimeOnHive; }
61      set {
62        if (value != executionTimeOnHive) {
63          executionTimeOnHive = value;
64          OnExecutionTimeOnHiveChanged();
65        }
66      }
67    }
68
69    [Storable]
70    private bool useLocalPlugins;
71    public bool UseLocalPlugins {
72      get { return useLocalPlugins; }
73      set { useLocalPlugins = value; }
74    }
75
76    [Storable]
77    private bool isPrivileged;
78    public bool IsPrivileged {
79      get { return isPrivileged; }
80      set { isPrivileged = value; }
81    }
82
83    // [Storable] -> HiveExperiment can't be storable, so RefreshableHiveExperiment can't be stored
84    private ItemCollection<RefreshableHiveExperiment> hiveExperiments = new ItemCollection<RefreshableHiveExperiment>();
85    public ItemCollection<RefreshableHiveExperiment> HiveExperiments {
86      get { return hiveExperiments; }
87      set { hiveExperiments = value; }
88    }
89
90    private List<Plugin> onlinePlugins;
91    public List<Plugin> OnlinePlugins {
92      get { return onlinePlugins; }
93      set { onlinePlugins = value; }
94    }
95
96    private List<Plugin> alreadyUploadedPlugins;
97    public List<Plugin> AlreadyUploadedPlugins {
98      get { return alreadyUploadedPlugins; }
99      set { alreadyUploadedPlugins = value; }
100    }
101
102    #region constructors and cloning
103    public HiveEngine() {
104      ResourceNames = "HEAL";
105      Priority = 0;
106    }
107
108    [StorableConstructor]
109    protected HiveEngine(bool deserializing) : base(deserializing) { }
110    protected HiveEngine(HiveEngine original, Cloner cloner)
111      : base(original, cloner) {
112      this.ResourceNames = original.ResourceNames;
113      this.currentOperator = cloner.Clone(original.currentOperator);
114      this.priority = original.priority;
115      this.executionTimeOnHive = original.executionTimeOnHive;
116      this.useLocalPlugins = original.useLocalPlugins;
117      this.IsPrivileged = original.IsPrivileged;
118      // this.hiveExperiments = cloner.Clone(original.hiveExperiments); do not clone hiveExperiments - otherwise they would be sent with every job
119    }
120    public override IDeepCloneable Clone(Cloner cloner) {
121      return new HiveEngine(this, cloner);
122    }
123    #endregion
124
125    #region Events
126    protected override void OnPrepared() {
127      base.OnPrepared();
128      this.ExecutionTimeOnHive = TimeSpan.Zero;
129    }
130
131    public event EventHandler ExecutionTimeOnHiveChanged;
132    protected virtual void OnExecutionTimeOnHiveChanged() {
133      var handler = ExecutionTimeOnHiveChanged;
134      if (handler != null) handler(this, EventArgs.Empty);
135    }
136    #endregion
137
138    protected override void Run(CancellationToken cancellationToken) {
139      this.cancellationToken = cancellationToken;
140      Run(ExecutionStack);
141    }
142
143    private void Run(object state) {
144      Stack<IOperation> executionStack = (Stack<IOperation>)state;
145      IOperation next;
146      OperationCollection coll;
147      IAtomicOperation operation;
148
149      if (firstRun) {
150        TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
151        this.OnlinePlugins = ServiceLocator.Instance.CallHiveService(s => s.GetPlugins()).Where(x => x.IsLocal == false).ToList();
152        this.AlreadyUploadedPlugins = new List<Plugin>();
153        firstRun = false;
154      }
155
156      while (executionStack.Count > 0) {
157        cancellationToken.ThrowIfCancellationRequested();
158
159        next = executionStack.Pop();
160        //bool isOpCollection = next is OperationCollection;
161        //int collCount = isOpCollection ? ((OperationCollection)next).Count : 0;
162        //string opName = !isOpCollection ? ((IAtomicOperation)next).Operator.Name : "OpCollection";
163
164        if (next is OperationCollection) {
165          coll = (OperationCollection)next;
166
167          //bool isPMOEvaluator = coll.Count > 0 && coll.First() is HeuristicLab.Core.ExecutionContext && ((HeuristicLab.Core.ExecutionContext)coll.First()).Operator.GetType().Name == "PMOEvaluator";
168          //bool isAlgorithmEvaluator = coll.Count > 0 && coll.First() is HeuristicLab.Core.ExecutionContext && ((HeuristicLab.Core.ExecutionContext)coll.First()).Operator.GetType().Name == "AlgorithmEvaluator";
169
170          //if (coll.Parallel && isPMOEvaluator) {
171          //  Task[] tasks = new Task[coll.Count];
172          //  Stack<IOperation>[] stacks = new Stack<IOperation>[coll.Count];
173          //  for (int i = 0; i < coll.Count; i++) {
174          //    stacks[i] = new Stack<IOperation>();
175          //    stacks[i].Push(coll[i]);
176          //    tasks[i] = Task.Factory.StartNew(Run, stacks[i], cancellationToken);
177          //  }
178          //  try {
179          //    Task.WaitAll(tasks);
180          //  }
181          //  catch (AggregateException ex) {
182          //    OperationCollection remaining = new OperationCollection() { Parallel = true };
183          //    for (int i = 0; i < stacks.Length; i++) {
184          //      if (stacks[i].Count == 1)
185          //        remaining.Add(stacks[i].Pop());
186          //      if (stacks[i].Count > 1) {
187          //        OperationCollection ops = new OperationCollection();
188          //        while (stacks[i].Count > 0)
189          //          ops.Add(stacks[i].Pop());
190          //        remaining.Add(ops);
191          //      }
192          //    }
193          //    if (remaining.Count > 0) executionStack.Push(remaining);
194          //    throw ex;
195          //  }
196          //} else if (coll.Parallel) {
197          if (coll.Parallel) {
198            try {
199              // 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
200              IScope parentScopeClone = (IScope)((IAtomicOperation)coll.First()).Scope.Parent.Clone();
201              parentScopeClone.SubScopes.Clear();
202              parentScopeClone.ClearParentScopes();
203
204              EngineJob[] jobs = new EngineJob[coll.Count];
205              for (int i = 0; i < coll.Count; i++) {
206                jobs[i] = new EngineJob(coll[i], new SequentialEngine.SequentialEngine());
207              }
208
209              var experiment = CreateHiveExperiment();
210              IScope[] scopes = ExecuteOnHive(experiment, jobs, parentScopeClone, cancellationToken);
211
212              for (int i = 0; i < coll.Count; i++) {
213                if (coll[i] is IAtomicOperation) {
214                  ExchangeScope(scopes[i], ((IAtomicOperation)coll[i]).Scope);
215                } else if (coll[i] is OperationCollection) {
216                  // todo ??
217                }
218              }
219            }
220            catch {
221              executionStack.Push(coll); throw;
222            }
223          } else {
224            for (int i = coll.Count - 1; i >= 0; i--)
225              if (coll[i] != null) executionStack.Push(coll[i]);
226          }
227        } else if (next is IAtomicOperation) {
228          operation = (IAtomicOperation)next;
229          try {
230            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
231          }
232          catch (Exception ex) {
233            executionStack.Push(operation);
234            if (ex is OperationCanceledException) throw ex;
235            else throw new OperatorExecutionException(operation.Operator, ex);
236          }
237          if (next != null) executionStack.Push(next);
238
239          if (operation.Operator.Breakpoint) {
240            LogMessage(string.Format("Breakpoint: {0}", operation.Operator.Name != string.Empty ? operation.Operator.Name : operation.Operator.ItemName));
241            Pause();
242          }
243        }
244      }
245    }
246
247    private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
248      e.SetObserved(); // avoid crash of process
249    }
250
251    private IRandom FindRandomParameter(IExecutionContext ec) {
252      try {
253        if (ec == null)
254          return null;
255
256        foreach (var p in ec.Parameters) {
257          if (p.Name == "Random" && p is IValueParameter)
258            return ((IValueParameter)p).Value as IRandom;
259        }
260        return FindRandomParameter(ec.Parent);
261      }
262      catch { return null; }
263    }
264
265    private static void ReIntegrateScope(IAtomicOperation source, IAtomicOperation target) {
266      ExchangeScope(source.Scope, target.Scope);
267    }
268
269    private static void ExchangeScope(IScope source, IScope target) {
270      target.Variables.Clear();
271      target.Variables.AddRange(source.Variables);
272      target.SubScopes.Clear();
273      target.SubScopes.AddRange(source.SubScopes);
274      // TODO: validate if parent scopes match - otherwise source is invalid
275    }
276
277    /// <summary>
278    /// This method blocks until all jobs are finished
279    /// TODO: Cancelation needs to be refined; all tasks currently stay in Semaphore.WaitOne after cancelation
280    /// </summary>
281    /// <param name="jobs"></param>
282    private IScope[] ExecuteOnHive(RefreshableHiveExperiment refreshableHiveExperiment, EngineJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
283      LogMessage(string.Format("Executing {0} operations on the hive.", jobs.Length));
284      IScope[] scopes = new Scope[jobs.Length];
285      object locker = new object();
286      var hiveExperiment = refreshableHiveExperiment.HiveExperiment;
287
288      try {
289        // create upload-tasks
290        for (int i = 0; i < jobs.Length; i++) {
291          var engineHiveJob = new EngineHiveJob(jobs[i], parentScopeClone);
292          engineHiveJob.Job.Priority = this.Priority;
293          hiveExperiment.HiveJobs.Add(engineHiveJob);
294
295          // shuffle random variable to avoid the same random sequence in each operation; todo: does not yet work (it cannot find the random variable)
296          IRandom random = FindRandomParameter(jobs[i].InitialOperation as IExecutionContext);
297          if (random != null)
298            random.Reset(random.Next());
299        }
300        HiveClient.StartExperiment((e) => { LogException(e); }, refreshableHiveExperiment);
301
302        // do polling until experiment is finished and all jobs are downloaded
303        while (!refreshableHiveExperiment.AllJobsFinished()) {
304          Thread.Sleep(2000);
305          this.ExecutionTimeOnHive = TimeSpan.FromMilliseconds(hiveExperiments.Sum(x => x.HiveExperiment.ExecutionTime.TotalMilliseconds));
306          cancellationToken.ThrowIfCancellationRequested();
307        }
308        LogMessage(string.Format("{0} finished (TotalExecutionTime: {1}).", refreshableHiveExperiment.ToString(), refreshableHiveExperiment.HiveExperiment.ExecutionTime));
309
310        var failedJobs = hiveExperiment.HiveJobs.Where(x => x.Job.State == JobState.Failed);
311        if (failedJobs.Count() > 0) {
312          throw new HiveEngineException("Job failed: " + failedJobs.First().Job.StateLog.Last().Exception);
313        }
314
315        // get scopes
316        int j = 0;
317        foreach (var hiveJob in hiveExperiment.HiveJobs) {
318          var scope = ((IAtomicOperation)((EngineJob)hiveJob.ItemJob).InitialOperation).Scope;
319          scopes[j++] = scope;
320        }
321        return scopes;
322      }
323      catch (OperationCanceledException e) {
324        throw e;
325      }
326      catch (Exception e) {
327        LogException(e);
328        throw e;
329      }
330      finally {
331        DisposeHiveExperiment(refreshableHiveExperiment);
332      }
333    }
334
335    private RefreshableHiveExperiment CreateHiveExperiment() {
336      lock (locker) {
337        var hiveExperiment = new HiveExperiment();
338        hiveExperiment.Name = "HiveEngine Run " + hiveExperiments.Count;
339        hiveExperiment.DateCreated = DateTime.Now;
340        hiveExperiment.UseLocalPlugins = this.UseLocalPlugins;
341        hiveExperiment.ResourceNames = this.ResourceNames;
342        hiveExperiment.IsPrivileged = this.IsPrivileged;
343        var refreshableHiveExperiment = new RefreshableHiveExperiment(hiveExperiment);
344        refreshableHiveExperiment.IsControllable = false;
345        hiveExperiments.Add(refreshableHiveExperiment);
346        return refreshableHiveExperiment;
347      }
348    }
349
350    private void DisposeHiveExperiment(RefreshableHiveExperiment refreshableHiveExperiment) {
351      refreshableHiveExperiment.RefreshAutomatically = false;
352      DeleteHiveExperiment(refreshableHiveExperiment.HiveExperiment.Id);
353      ClearData(refreshableHiveExperiment);
354    }
355
356    private void ClearData(RefreshableHiveExperiment refreshableHiveExperiment) {
357      var jobs = refreshableHiveExperiment.HiveExperiment.GetAllHiveJobs();
358      foreach (var job in jobs) {
359        job.ClearData();
360      }
361    }
362
363    private void DeleteHiveExperiment(Guid hiveExperimentId) {
364      HiveClient.TryAndRepeat(() => {
365        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(hiveExperimentId));
366      }, 5, string.Format("Could not delete jobs"));
367    }
368
369    private List<Guid> GetResourceIds() {
370      return ServiceLocator.Instance.CallHiveService(service => {
371        var resourceNames = ResourceNames.Split(';');
372        var resourceIds = new List<Guid>();
373        foreach (var resourceName in resourceNames) {
374          Guid resourceId = service.GetResourceId(resourceName);
375          if (resourceId == Guid.Empty) {
376            throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
377          }
378          resourceIds.Add(resourceId);
379        }
380        return resourceIds;
381      });
382    }
383
384    /// <summary>
385    /// Threadsafe message logging
386    /// </summary>
387    private void LogMessage(string message) {
388      lock (logLocker) {
389        Log.LogMessage(message);
390      }
391    }
392
393    /// <summary>
394    /// Threadsafe exception logging
395    /// </summary>
396    private void LogException(Exception exception) {
397      lock (logLocker) {
398        Log.LogException(exception);
399      }
400    }
401
402    // testfunction:
403    //private IScope[] ExecuteLocally(EngineJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
404    //  IScope[] scopes = new Scope[jobs.Length];
405    //  for (int i = 0; i < jobs.Length; i++) {
406    //    var serialized = PersistenceUtil.Serialize(jobs[i]);
407    //    var deserialized = PersistenceUtil.Deserialize<IJob>(serialized);
408    //    deserialized.Start();
409    //    while (deserialized.ExecutionState != ExecutionState.Stopped) {
410    //      Thread.Sleep(100);
411    //    }
412    //    var serialized2 = PersistenceUtil.Serialize(deserialized);
413    //    var deserialized2 = PersistenceUtil.Deserialize<EngineJob>(serialized2);
414    //    var newScope = ((IAtomicOperation)deserialized2.InitialOperation).Scope;
415    //    scopes[i] = newScope;
416    //  }
417    //  return scopes;
418    //}
419  }
420}
Note: See TracBrowser for help on using the repository browser.