Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6033 was 6033, checked in by cneumuel, 14 years ago

#1233

  • created baseclass for jobs (ItemJob) which derives OperatorJobs and EngineJobs
  • created special view for OptimizerJobs which derives from a more general view
  • removed logic from domain class HiveExperiment and moved it into RefreshableHiveExperiment
  • improved ItemTreeView
  • corrected plugin dependencies
  • fixed bug in database trigger when deleting HiveExperiments
  • added delete cascade for Plugin and PluginData
  • lots of fixes
File size: 20.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;
10using HeuristicLab.PluginInfrastructure;
11
12namespace HeuristicLab.HiveEngine {
13  /// <summary>
14  /// Represents an engine that executes operations which can be executed in parallel on the hive
15  /// </summary>
16  [StorableClass]
17  [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.")]
18  public class HiveEngine : Engine {
19    private Semaphore maxConcurrentConnections = new Semaphore(4, 4); // avoid too many connections
20    private Semaphore maxSerializedJobsInMemory = new Semaphore(4, 4); // avoid memory problems
21    private CancellationToken cancellationToken;
22
23    [Storable]
24    private IOperator currentOperator;
25
26    [Storable]
27    public string ResourceNames { get; set; }
28
29    [Storable]
30    private int priority;
31    public int Priority {
32      get { return priority; }
33      set { priority = value; }
34    }
35
36    [Storable]
37    private TimeSpan executionTimeOnHive;
38    public TimeSpan ExecutionTimeOnHive {
39      get { return executionTimeOnHive; }
40      set {
41        if (value != executionTimeOnHive) {
42          executionTimeOnHive = value;
43          OnExecutionTimeOnHiveChanged();
44        }
45      }
46    }
47
48    [Storable]
49    private bool useLocalPlugins;
50    public bool UseLocalPlugins {
51      get { return useLocalPlugins; }
52      set { useLocalPlugins = value; }
53    }
54
55    [Storable]
56    private ItemCollection<RefreshableHiveExperiment> hiveExperiments;
57    public ItemCollection<RefreshableHiveExperiment> HiveExperiments {
58      get { return hiveExperiments; }
59      set { hiveExperiments = value; }
60    }
61
62    private List<Plugin> onlinePlugins;
63    public List<Plugin> OnlinePlugins {
64      get { return onlinePlugins; }
65      set { onlinePlugins = value; }
66    }
67
68    private List<Plugin> alreadyUploadedPlugins;
69    public List<Plugin> AlreadyUploadedPlugins {
70      get { return alreadyUploadedPlugins; }
71      set { alreadyUploadedPlugins = value; }
72    }
73
74    #region constructors and cloning
75    public HiveEngine() {
76      ResourceNames = "HEAL";
77      HiveExperiments = new ItemCollection<RefreshableHiveExperiment>();
78      Priority = 0;
79    }
80
81    [StorableConstructor]
82    protected HiveEngine(bool deserializing) : base(deserializing) { }
83    protected HiveEngine(HiveEngine original, Cloner cloner)
84      : base(original, cloner) {
85      this.ResourceNames = original.ResourceNames;
86      this.currentOperator = cloner.Clone(original.currentOperator);
87      this.priority = original.priority;
88      this.executionTimeOnHive = original.executionTimeOnHive;
89      this.useLocalPlugins = original.useLocalPlugins;
90    }
91    public override IDeepCloneable Clone(Cloner cloner) {
92      return new HiveEngine(this, cloner);
93    }
94    #endregion
95
96    #region Events
97    protected override void OnPrepared() {
98      base.OnPrepared();
99      this.ExecutionTimeOnHive = TimeSpan.Zero;
100    }
101
102    public event EventHandler ExecutionTimeOnHiveChanged;
103    protected virtual void OnExecutionTimeOnHiveChanged() {
104      var handler = ExecutionTimeOnHiveChanged;
105      if (handler != null) handler(this, EventArgs.Empty);
106    }
107    #endregion
108
109    protected override void Run(CancellationToken cancellationToken) {
110      this.cancellationToken = cancellationToken;
111      Run(ExecutionStack);
112    }
113
114    private void Run(object state) {
115      Stack<IOperation> executionStack = (Stack<IOperation>)state;
116      IOperation next;
117      OperationCollection coll;
118      IAtomicOperation operation;
119      TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
120
121      this.OnlinePlugins = ServiceLocator.Instance.CallHiveService(s => s.GetPlugins()).Where(x => x.IsLocal == false).ToList();
122      this.AlreadyUploadedPlugins = new List<Plugin>();
123
124      while (ExecutionStack.Count > 0) {
125        cancellationToken.ThrowIfCancellationRequested();
126
127        next = ExecutionStack.Pop();
128        if (next is OperationCollection) {
129          coll = (OperationCollection)next;
130          if (coll.Parallel) {
131            // 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
132            IScope parentScopeClone = (IScope)((IAtomicOperation)coll.First()).Scope.Parent.Clone();
133            parentScopeClone.SubScopes.Clear();
134            parentScopeClone.ClearParentScopes();
135
136            EngineJob[] jobs = new EngineJob[coll.Count];
137            for (int i = 0; i < coll.Count; i++) {
138              jobs[i] = new EngineJob(coll[i], new SequentialEngine.SequentialEngine());
139            }
140
141            IScope[] scopes = ExecuteOnHive(jobs, parentScopeClone, cancellationToken);
142           
143            for (int i = 0; i < coll.Count; i++) {
144              if (coll[i] is IAtomicOperation) {
145                ExchangeScope(scopes[i], ((IAtomicOperation)coll[i]).Scope);
146              } else if (coll[i] is OperationCollection) {
147                // todo ??
148              }
149            }
150          } else {
151            for (int i = coll.Count - 1; i >= 0; i--)
152              if (coll[i] != null) executionStack.Push(coll[i]);
153          }
154        } else if (next is IAtomicOperation) {
155          operation = (IAtomicOperation)next;
156          try {
157            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
158          }
159          catch (Exception ex) {
160            ExecutionStack.Push(operation);
161            if (ex is OperationCanceledException) throw ex;
162            else throw new OperatorExecutionException(operation.Operator, ex);
163          }
164          if (next != null) ExecutionStack.Push(next);
165
166          if (operation.Operator.Breakpoint) {
167            LogMessage(string.Format("Breakpoint: {0}", operation.Operator.Name != string.Empty ? operation.Operator.Name : operation.Operator.ItemName));
168            Pause();
169          }
170        }
171      }
172    }
173
174    private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
175      e.SetObserved(); // avoid crash of process
176    }
177
178    private IRandom FindRandomParameter(IExecutionContext ec) {
179      try {
180        if (ec == null)
181          return null;
182
183        foreach (var p in ec.Parameters) {
184          if (p.Name == "Random" && p is IValueParameter)
185            return ((IValueParameter)p).Value as IRandom;
186        }
187        return FindRandomParameter(ec.Parent);
188      }
189      catch { return null; }
190    }
191
192    private static void ReIntegrateScope(IAtomicOperation source, IAtomicOperation target) {
193      ExchangeScope(source.Scope, target.Scope);
194    }
195
196    private static void ExchangeScope(IScope source, IScope target) {
197      target.Variables.Clear();
198      target.Variables.AddRange(source.Variables);
199      target.SubScopes.Clear();
200      target.SubScopes.AddRange(source.SubScopes);
201      // TODO: validate if parent scopes match - otherwise source is invalid
202    }
203
204    // testfunction:
205    //private IScope[] ExecuteLocally(EngineJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
206    //  IScope[] scopes = new Scope[jobs.Length];
207    //  for (int i = 0; i < jobs.Length; i++) {
208    //    var job = (EngineJob)jobs[i].Clone();
209    //    job.Start();
210    //    while (job.ExecutionState != ExecutionState.Stopped) {
211    //      Thread.Sleep(100);
212    //    }
213    //    scopes[i] = ((IAtomicOperation)job.InitialOperation).Scope;
214    //  }
215    //  return scopes;
216    //}
217
218    /// <summary>
219    /// This method blocks until all jobs are finished
220    /// TODO: Cancelation needs to be refined; all tasks currently stay in Semaphore.WaitOne after cancelation
221    /// </summary>
222    /// <param name="jobs"></param>
223    private IScope[] ExecuteOnHive(EngineJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
224      LogMessage(string.Format("Executing {0} operations on the hive.", jobs.Length));
225      IScope[] scopes = new Scope[jobs.Length];
226      object locker = new object();
227      IDictionary<Guid, int> jobIndices = new Dictionary<Guid, int>();
228      var hiveExperiment = new HiveExperiment();;
229
230      try {
231        List<Guid> remainingJobIds = new List<Guid>();
232        List<LightweightJob> lightweightJobs;
233
234        int finishedCount = 0;
235        int uploadCount = 0;
236
237        // create hive experiment
238        hiveExperiment.Name = "HiveEngine Run " + hiveExperiments.Count;
239        hiveExperiment.UseLocalPlugins = this.UseLocalPlugins;
240        hiveExperiment.ResourceNames = this.ResourceNames;
241        hiveExperiment.Id = ServiceLocator.Instance.CallHiveService(s => s.AddHiveExperiment(hiveExperiment));
242        hiveExperiments.Add(new RefreshableHiveExperiment(hiveExperiment));
243
244        // create upload-tasks
245        var uploadTasks = new List<Task<Job>>();
246        for (int i = 0; i < jobs.Length; i++) {
247          var job = jobs[i];
248
249          // shuffle random variable to avoid the same random sequence in each operation; todo: does not yet work (it cannot find the random variable)
250          IRandom random = FindRandomParameter(job.InitialOperation as IExecutionContext);
251          if (random != null)
252            random.Reset(random.Next());
253
254          uploadTasks.Add(Task.Factory.StartNew<Job>((keyValuePairObj) => {
255            return UploadJob(keyValuePairObj, parentScopeClone, cancellationToken, GetResourceIds(), hiveExperiment.Id);
256          }, new KeyValuePair<int, EngineJob>(i, job), cancellationToken));
257        }
258
259        Task processUploadedJobsTask = new Task(() => {
260          // process finished upload-tasks
261          int uploadTasksCount = uploadTasks.Count;
262          for (int i = 0; i < uploadTasksCount; i++) {
263            cancellationToken.ThrowIfCancellationRequested();
264
265            var uploadTasksArray = uploadTasks.ToArray();
266            var task = uploadTasksArray[Task.WaitAny(uploadTasksArray)];
267            if (task.Status == TaskStatus.Faulted) {
268              LogException(task.Exception);
269              throw task.Exception;
270            }
271
272            int key = ((KeyValuePair<int, EngineJob>)task.AsyncState).Key;
273            Job job = task.Result;
274            lock (locker) {
275              uploadCount++;
276              jobIndices.Add(job.Id, key);
277              remainingJobIds.Add(job.Id);
278            }
279            jobs[key] = null; // relax memory
280            LogMessage(string.Format("Uploaded job #{0}", key + 1, job.Id));
281            uploadTasks.Remove(task);
282          }
283        }, cancellationToken, TaskCreationOptions.PreferFairness);
284        processUploadedJobsTask.Start();
285
286        // poll job-statuses and create tasks for those which are finished
287        var downloadTasks = new List<Task<EngineJob>>();
288        var executionTimes = new List<TimeSpan>();
289        var executionTimeOnHiveBefore = executionTimeOnHive;
290        while (processUploadedJobsTask.Status != TaskStatus.RanToCompletion || remainingJobIds.Count > 0) {
291          cancellationToken.ThrowIfCancellationRequested();
292
293          Thread.Sleep(10000);
294          try {
295            lightweightJobs = ServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobs(remainingJobIds));
296
297            var jobsFinished = lightweightJobs.Where(j => j.State == JobState.Finished || j.State == JobState.Failed || j.State == JobState.Aborted);
298            finishedCount += jobsFinished.Count();
299            if (jobsFinished.Count() > 0) LogMessage(string.Format("Finished: {0}/{1}", finishedCount, jobs.Length));
300            ExecutionTimeOnHive = executionTimeOnHiveBefore + executionTimes.Sum() + lightweightJobs.Select(x => x.ExecutionTime.HasValue ? x.ExecutionTime.Value : TimeSpan.Zero).Sum();
301
302            foreach (var result in jobsFinished) {
303              if (result.State == JobState.Finished) {
304                downloadTasks.Add(Task.Factory.StartNew<EngineJob>((jobIdObj) => {
305                  return DownloadJob(jobIndices, jobIdObj, cancellationToken);
306                }, result.Id, cancellationToken));
307              } else if (result.State == JobState.Aborted) {
308                LogMessage(string.Format("Job #{0} aborted (id: {1})", jobIndices[result.Id] + 1, result.Id));
309              } else if (result.State == JobState.Failed) {
310                LogMessage(string.Format("Job #{0} failed (id: {1}): {2}", jobIndices[result.Id] + 1, result.Id, result.CurrentStateLog != null ? result.CurrentStateLog.Exception : string.Empty));
311              }
312              remainingJobIds.Remove(result.Id);
313              executionTimes.Add(result.ExecutionTime.HasValue ? result.ExecutionTime.Value : TimeSpan.Zero);
314            }
315          }
316          catch (Exception e) {
317            LogException(e);
318          }
319        }
320
321        // process finished download-tasks
322        int downloadTasksCount = downloadTasks.Count;
323        for (int i = 0; i < downloadTasksCount; i++) {
324          cancellationToken.ThrowIfCancellationRequested();
325
326          var downloadTasksArray = downloadTasks.ToArray();
327          var task = downloadTasksArray[Task.WaitAny(downloadTasksArray)];
328          var jobId = (Guid)task.AsyncState;
329          if (task.Status == TaskStatus.Faulted) {
330            LogException(task.Exception);
331            throw task.Exception;
332          }
333          scopes[jobIndices[(Guid)task.AsyncState]] = ((IAtomicOperation)task.Result.InitialOperation).Scope;
334          downloadTasks.Remove(task);
335        }
336
337        LogMessage(string.Format("All jobs finished (TotalExecutionTime: {0}).", executionTimes.Sum()));
338        DeleteHiveExperiment(hiveExperiment.Id);
339
340        return scopes;
341      }
342      catch (OperationCanceledException e) {
343        lock (locker) {
344          if (jobIndices != null) DeleteHiveExperiment(hiveExperiment.Id);
345        }
346        throw e;
347      }
348      catch (Exception e) {
349        lock (locker) {
350          if (jobIndices != null) DeleteHiveExperiment(hiveExperiment.Id);
351        }
352        LogException(e);
353        throw e;
354      }
355    }
356
357    private void DeleteHiveExperiment(Guid hiveExperimentId) {
358      TryAndRepeat(() => {
359        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(hiveExperimentId));
360      }, 5, string.Format("Could not delete jobs"));
361    }
362
363    private static object locker = new object();
364    private Job UploadJob(object keyValuePairObj, IScope parentScopeClone, CancellationToken cancellationToken, List<Guid> resourceIds, Guid hiveExperimentId) {
365      var keyValuePair = (KeyValuePair<int, EngineJob>)keyValuePairObj;
366      Job job = new Job();
367
368      try {
369        maxSerializedJobsInMemory.WaitOne();
370        JobData jobData = new JobData();
371        IEnumerable<Type> usedTypes;
372
373        // clone operation and remove unnecessary scopes; don't do this earlier to avoid memory problems
374        lock (locker) {
375          ((IAtomicOperation)keyValuePair.Value.InitialOperation).Scope.Parent = parentScopeClone;
376          keyValuePair.Value.InitialOperation = (IOperation)keyValuePair.Value.InitialOperation.Clone();
377          if (keyValuePair.Value.InitialOperation is IAtomicOperation)
378            ((IAtomicOperation)keyValuePair.Value.InitialOperation).Scope.ClearParentScopes();
379          jobData.Data = PersistenceUtil.Serialize(keyValuePair.Value, out usedTypes);
380        }
381        var neededPlugins = new List<IPluginDescription>();
382        PluginUtil.CollectDeclaringPlugins(neededPlugins, usedTypes);
383
384        job.CoresNeeded = 1;
385        job.PluginsNeededIds = ServiceLocator.Instance.CallHiveService(s => PluginUtil.GetPluginDependencies(s, this.OnlinePlugins, this.AlreadyUploadedPlugins, neededPlugins, false));
386        job.Priority = priority;
387        job.HiveExperimentId = hiveExperimentId;
388
389        try {
390          maxConcurrentConnections.WaitOne();
391          while (job.Id == Guid.Empty) { // repeat until success
392            cancellationToken.ThrowIfCancellationRequested();
393            try {
394              job.Id = ServiceLocator.Instance.CallHiveService(s => s.AddJob(job, jobData, resourceIds));
395            }
396            catch (Exception e) {
397              LogException(e);
398              LogMessage("Repeating upload");
399            }
400          }
401        }
402        finally {
403          maxConcurrentConnections.Release();
404        }
405      }
406      finally {
407        maxSerializedJobsInMemory.Release();
408      }
409      return job;
410    }
411
412    private List<Guid> GetResourceIds() {
413      return ServiceLocator.Instance.CallHiveService(service => {
414        var resourceNames = ResourceNames.Split(';');
415        var resourceIds = new List<Guid>();
416        foreach (var resourceName in resourceNames) {
417          Guid resourceId = service.GetResourceId(resourceName);
418          if (resourceId == Guid.Empty) {
419            throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
420          }
421          resourceIds.Add(resourceId);
422        }
423        return resourceIds;
424      });
425    }
426
427    private EngineJob DownloadJob(IDictionary<Guid, int> jobIndices, object jobIdObj, CancellationToken cancellationToken) {
428      Guid jobId = (Guid)jobIdObj;
429      JobData jobData = null;
430      EngineJob engineJob = null;
431      try {
432        maxSerializedJobsInMemory.WaitOne();
433        maxConcurrentConnections.WaitOne();
434        while (jobData == null) { // repeat until success
435          cancellationToken.ThrowIfCancellationRequested();
436          try {
437            jobData = ServiceLocator.Instance.CallHiveService(s => s.GetJobData(jobId));
438          }
439          catch (Exception e) {
440            LogException(e);
441            LogMessage("Repeating download");
442          }
443        }
444        engineJob = PersistenceUtil.Deserialize<EngineJob>(jobData.Data);
445        jobData = null;
446        LogMessage(string.Format("Downloaded job #{0}", jobIndices[jobId] + 1, jobId));
447      }
448      finally {
449        maxConcurrentConnections.Release();
450        maxSerializedJobsInMemory.Release();
451      }
452      return engineJob;
453    }
454
455    /// <summary>
456    /// Threadsafe message logging
457    /// </summary>
458    private void LogMessage(string message) {
459      lock (Log) {
460        Log.LogMessage(message);
461      }
462    }
463
464    /// <summary>
465    /// Threadsafe exception logging
466    /// </summary>
467    private void LogException(Exception exception) {
468      lock (Log) {
469        Log.LogException(exception);
470      }
471    }
472
473    /// <summary>
474    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
475    /// If repetitions is -1, it is repeated infinitely.
476    /// </summary>
477    private static void TryAndRepeat(Action action, int repetitions, string errorMessage) {
478      try { action(); }
479      catch (Exception e) {
480        repetitions--;
481        if (repetitions <= 0)
482          throw new HiveEngineException(errorMessage, e);
483        TryAndRepeat(action, repetitions, errorMessage);
484      }
485    }
486  }
487
488  public static class ScopeExtensions {
489    public static void ClearParentScopes(this IScope scope) {
490      scope.ClearParentScopes(null);
491    }
492
493    public static void ClearParentScopes(this IScope scope, IScope childScope) {
494      if (childScope != null) {
495        scope.SubScopes.Clear();
496        scope.SubScopes.Add(childScope);
497      }
498      if (scope.Parent != null)
499        scope.Parent.ClearParentScopes(scope);
500    }
501  }
502
503  public static class EnumerableExtensions {
504    public static TimeSpan Sum(this IEnumerable<TimeSpan> times) {
505      return TimeSpan.FromMilliseconds(times.Select(e => e.TotalMilliseconds).Sum());
506    }
507  }
508}
Note: See TracBrowser for help on using the repository browser.