Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.3/sources/HeuristicLab.Hive/HeuristicLab.HiveEngine/3.3/HiveEngine.cs @ 5394

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

#1347

  • jobs are deleted when engine is paused or stopped
  • execution time on hive is computed
File size: 17.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
6using HeuristicLab.Core;
7using HeuristicLab.Common;
8using HeuristicLab.Hive.Contracts.Interfaces;
9using HeuristicLab.Clients.Common;
10using HeuristicLab.Hive.ExperimentManager;
11using HeuristicLab.Hive.Contracts.BusinessObjects;
12using HeuristicLab.PluginInfrastructure;
13using HeuristicLab.Hive.Contracts.ResponseObjects;
14using System.Threading;
15using HeuristicLab.Random;
16using System.Threading.Tasks;
17
18namespace HeuristicLab.HiveEngine {
19  /// <summary>
20  /// Represents an engine that executes operations which can be executed in parallel on the hive
21  /// </summary>
22  [StorableClass]
23  [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.")]
24  public class HiveEngine : Engine {
25    private Semaphore maxConcurrentConnections = new Semaphore(4, 4); // avoid too many connections
26    private Semaphore maxSerializedJobsInMemory = new Semaphore(4, 4); // avoid memory problems
27    private CancellationToken cancellationToken;
28
29    [Storable]
30    private IOperator currentOperator;
31
32    [Storable]
33    public string ResourceIds { get; set; }
34
35    [Storable]
36    private int priority;
37    public int Priority {
38      get { return priority; }
39      set { priority = value; }
40    }
41
42    [Storable]
43    private TimeSpan executionTimeOnHive;
44    public TimeSpan ExecutionTimeOnHive {
45      get { return executionTimeOnHive; }
46      set {
47        if (value != executionTimeOnHive) {
48          executionTimeOnHive = value;
49          OnExecutionTimeOnHiveChanged();
50        }
51      }
52    }
53   
54    #region constructors and cloning
55    public HiveEngine() {
56      ResourceIds = "HEAL";
57    }
58
59    [StorableConstructor]
60    protected HiveEngine(bool deserializing) : base(deserializing) { }
61    protected HiveEngine(HiveEngine original, Cloner cloner)
62      : base(original, cloner) {
63      this.ResourceIds = original.ResourceIds;
64      this.currentOperator = cloner.Clone(original.currentOperator);
65      this.priority = original.priority;
66      this.executionTimeOnHive = original.executionTimeOnHive;
67    }
68    public override IDeepCloneable Clone(Cloner cloner) {
69      return new HiveEngine(this, cloner);
70    }
71    #endregion
72
73    #region Events
74    protected override void OnPrepared() {
75      base.OnPrepared();
76      this.ExecutionTimeOnHive = TimeSpan.Zero;
77    }
78
79    public event EventHandler ExecutionTimeOnHiveChanged;
80    protected virtual void OnExecutionTimeOnHiveChanged() {
81      var handler = ExecutionTimeOnHiveChanged;
82      if (handler != null) handler(this, EventArgs.Empty);
83    }
84    #endregion
85
86    protected override void Run(CancellationToken cancellationToken) {
87      this.cancellationToken = cancellationToken;
88      Run(ExecutionStack);
89    }
90
91    private void Run(object state) {
92      Stack<IOperation> executionStack = (Stack<IOperation>)state;
93      IOperation next;
94      OperationCollection coll;
95      IAtomicOperation operation;
96      TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
97
98      while (ExecutionStack.Count > 0) {
99        cancellationToken.ThrowIfCancellationRequested();
100
101        next = ExecutionStack.Pop();
102        if (next is OperationCollection) {
103          coll = (OperationCollection)next;
104          if (coll.Parallel) {
105            // 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
106            IScope parentScopeClone = (IScope)((IAtomicOperation)coll.First()).Scope.Parent.Clone();
107            parentScopeClone.SubScopes.Clear();
108            parentScopeClone.ClearParentScopes();
109
110            OperationJob[] jobs = new OperationJob[coll.Count];
111            for (int i = 0; i < coll.Count; i++) {
112              jobs[i] = new OperationJob(coll[i]);
113            }
114
115            IScope[] scopes = ExecuteOnHive(jobs, parentScopeClone, cancellationToken);
116
117            for (int i = 0; i < coll.Count; i++) {
118              if (coll[i] is IAtomicOperation) {
119                ExchangeScope(scopes[i], ((IAtomicOperation)coll[i]).Scope);
120              } else if (coll[i] is OperationCollection) {
121                // todo ??
122              }
123            }
124          } else {
125            for (int i = coll.Count - 1; i >= 0; i--)
126              if (coll[i] != null) executionStack.Push(coll[i]);
127          }
128        } else if (next is IAtomicOperation) {
129          operation = (IAtomicOperation)next;
130          try {
131            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
132          }
133          catch (Exception ex) {
134            ExecutionStack.Push(operation);
135            if (ex is OperationCanceledException) throw ex;
136            else throw new OperatorExecutionException(operation.Operator, ex);
137          }
138          if (next != null) ExecutionStack.Push(next);
139
140          if (operation.Operator.Breakpoint) {
141            LogMessage(string.Format("Breakpoint: {0}", operation.Operator.Name != string.Empty ? operation.Operator.Name : operation.Operator.ItemName));
142            Pause();
143          }
144        }
145      }
146    }
147
148    private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
149      e.SetObserved(); // avoid crash of process
150    }
151
152    private IRandom FindRandomParameter(IExecutionContext ec) {
153      try {
154        if (ec == null)
155          return null;
156
157        foreach (var p in ec.Parameters) {
158          if (p.Name == "Random" && p is IValueParameter)
159            return ((IValueParameter)p).Value as IRandom;
160        }
161        return FindRandomParameter(ec.Parent);
162      }
163      catch { return null; }
164    }
165
166    private static void ReIntegrateScope(IAtomicOperation source, IAtomicOperation target) {
167      ExchangeScope(source.Scope, target.Scope);
168    }
169
170    private static void ExchangeScope(IScope source, IScope target) {
171      target.Variables.Clear();
172      target.Variables.AddRange(source.Variables);
173      target.SubScopes.Clear();
174      target.SubScopes.AddRange(source.SubScopes);
175      // TODO: validate if parent scopes match - otherwise source is invalid
176    }
177
178    /// <summary>
179    /// This method blocks until all jobs are finished
180    /// TODO: Cancelation needs to be refined; all tasks currently stay in Semaphore.WaitOne after cancelation
181    /// </summary>
182    /// <param name="jobs"></param>
183    private IScope[] ExecuteOnHive(OperationJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
184      LogMessage(string.Format("Executing {0} operations on the hive.", jobs.Length));
185      IScope[] scopes = new Scope[jobs.Length];
186      object locker = new object();
187      IDictionary<Guid, int> jobIndices = new Dictionary<Guid, int>();
188
189      try {
190        List<Guid> remainingJobIds = new List<Guid>();
191        JobResultList results;
192        var pluginsNeeded = ApplicationManager.Manager.Plugins.Select(x => new HivePluginInfoDto { Name = x.Name, Version = x.Version }).ToList();
193        int finishedCount = 0;
194        int uploadCount = 0;
195
196        // create upload-tasks
197        var uploadTasks = new List<Task<JobDto>>();
198        for (int i = 0; i < jobs.Length; i++) {
199          var job = jobs[i];
200
201          // shuffle random variable to avoid the same random sequence in each operation; todo: does not yet work (it cannot find the random variable)
202          IRandom random = FindRandomParameter(job.Operation as IExecutionContext);
203          if (random != null)
204            random.Reset(random.Next());
205
206          uploadTasks.Add(Task.Factory.StartNew<JobDto>((keyValuePairObj) => {
207            return UploadJob(pluginsNeeded, keyValuePairObj, parentScopeClone, cancellationToken);
208          }, new KeyValuePair<int, OperationJob>(i, job), cancellationToken));
209        }
210
211        Task processUploadedJobsTask = new Task(() => {
212          // process finished upload-tasks
213          int uploadTasksCount = uploadTasks.Count;
214          for (int i = 0; i < uploadTasksCount; i++) {
215            cancellationToken.ThrowIfCancellationRequested();
216
217            var uploadTasksArray = uploadTasks.ToArray();
218            var task = uploadTasksArray[Task.WaitAny(uploadTasksArray)];
219            if (task.Status == TaskStatus.Faulted) {
220              LogException(task.Exception);
221              throw task.Exception;
222            }
223
224            int key = ((KeyValuePair<int, OperationJob>)task.AsyncState).Key;
225            JobDto jobDto = task.Result;
226            lock (locker) {
227              uploadCount++;
228              jobIndices.Add(jobDto.Id, key);
229              remainingJobIds.Add(jobDto.Id);
230            }
231            jobs[key] = null; // relax memory
232            LogMessage(string.Format("Uploaded job #{0}", key + 1, jobDto.Id));
233            uploadTasks.Remove(task);
234          }
235        }, cancellationToken, TaskCreationOptions.PreferFairness);
236        processUploadedJobsTask.Start();
237
238        // poll job-statuses and create tasks for those which are finished
239        var downloadTasks = new List<Task<OperationJob>>();
240        var executionTimes = new List<TimeSpan>();
241        var executionTimeOnHiveBefore = executionTimeOnHive;
242        while (processUploadedJobsTask.Status != TaskStatus.RanToCompletion || remainingJobIds.Count > 0) {
243          cancellationToken.ThrowIfCancellationRequested();
244
245          Thread.Sleep(10000);
246          try {
247            using (Disposable<IClientFacade> service = ServiceLocator.Instance.ClientFacadePool.GetService()) {
248              results = service.Obj.GetJobResults(remainingJobIds).Obj;
249            }
250            var jobsFinished = results.Where(j => j.State == JobState.Finished || j.State == JobState.Failed || j.State == JobState.Aborted);
251            finishedCount += jobsFinished.Count();
252            if (jobsFinished.Count() > 0) LogMessage(string.Format("Finished: {0}/{1}", finishedCount, jobs.Length));
253            ExecutionTimeOnHive = executionTimeOnHiveBefore + executionTimes.Sum() + results.Select(x => x.ExecutionTime).Sum();
254
255            foreach (var result in jobsFinished) {
256              if (result.State == JobState.Finished) {
257                downloadTasks.Add(Task.Factory.StartNew<OperationJob>((jobIdObj) => {
258                  return DownloadJob(jobIndices, jobIdObj, cancellationToken);
259                }, result.Id, cancellationToken));
260              } else if (result.State == JobState.Aborted) {
261                LogMessage(string.Format("Job #{0} aborted (id: {1})", jobIndices[result.Id] + 1, result.Id));
262              } else if (result.State == JobState.Failed) {
263                LogMessage(string.Format("Job #{0} failed (id: {1}): {2}", jobIndices[result.Id] + 1, result.Id, result.Exception));
264              }
265              remainingJobIds.Remove(result.Id);
266              executionTimes.Add(result.ExecutionTime);
267            }
268          }
269          catch (Exception e) {
270            LogException(e);
271          }
272        }
273
274        // process finished download-tasks
275        int downloadTasksCount = downloadTasks.Count;
276        for (int i = 0; i < downloadTasksCount; i++) {
277          cancellationToken.ThrowIfCancellationRequested();
278
279          var downloadTasksArray = downloadTasks.ToArray();
280          var task = downloadTasksArray[Task.WaitAny(downloadTasksArray)];
281          var jobId = (Guid)task.AsyncState;
282          if (task.Status == TaskStatus.Faulted) {
283            LogException(task.Exception);
284            throw task.Exception;
285          }
286          scopes[jobIndices[(Guid)task.AsyncState]] = ((IAtomicOperation)task.Result.Operation).Scope;
287          downloadTasks.Remove(task);
288        }
289
290        LogMessage(string.Format("All jobs finished (TotalExecutionTime: {0}).", executionTimes.Sum()));
291        DeleteJobs(jobIndices);
292
293        return scopes;
294      }
295      catch (OperationCanceledException e) {
296        lock (locker) {
297          if (jobIndices != null) DeleteJobs(jobIndices);
298        }
299        throw e;
300      }
301      catch (Exception e) {
302        lock (locker) {
303          if (jobIndices != null) DeleteJobs(jobIndices);
304        }
305        LogException(e);
306        throw e;
307      }
308    }
309
310    private void DeleteJobs(IDictionary<Guid, int> jobIndices) {
311      if (jobIndices.Count > 0) {
312        using (Disposable<IClientFacade> service = ServiceLocator.Instance.ClientFacadePool.GetService()) {
313          foreach (Guid jobId in jobIndices.Keys) {
314            service.Obj.DeleteJob(jobId);
315          }
316          LogMessage(string.Format("Deleted {0} jobs on hive.", jobIndices.Count));
317          jobIndices.Clear();
318        }
319      }
320    }
321
322    private static object locker = new object();
323    private JobDto UploadJob(List<HivePluginInfoDto> pluginsNeeded, object keyValuePairObj, IScope parentScopeClone, CancellationToken cancellationToken) {
324      var keyValuePair = (KeyValuePair<int, OperationJob>)keyValuePairObj;
325      var groups = ResourceIds.Split(';');
326      ResponseObject<JobDto> response = null;
327      try {
328        maxSerializedJobsInMemory.WaitOne();
329        SerializedJob serializedJob = null;
330        while (serializedJob == null) { // repeat until success; rare race-conditions occur at serializations (enumeration was changed-exceptions); maybe this is because all the parent-scopes and execution-contexts at some point contain the hiveengine and the Log in here
331          cancellationToken.ThrowIfCancellationRequested();
332          try {
333            lock (Log) {
334              serializedJob = new SerializedJob();
335            }
336          }
337          catch (Exception e) {
338            LogException(e);
339          }
340        }
341        // clone operation and remove unnecessary scopes; don't do this earlier to avoid memory problems
342        lock (locker) {
343          ((IAtomicOperation)keyValuePair.Value.Operation).Scope.Parent = parentScopeClone;
344          keyValuePair.Value.Operation = (IOperation)keyValuePair.Value.Operation.Clone();
345          if (keyValuePair.Value.Operation is IAtomicOperation)
346            ((IAtomicOperation)keyValuePair.Value.Operation).Scope.ClearParentScopes();
347          serializedJob.SerializedJobData = SerializedJob.Serialize(keyValuePair.Value);
348        }
349        serializedJob.JobInfo = new JobDto();
350        serializedJob.JobInfo.State = JobState.Offline;
351        serializedJob.JobInfo.CoresNeeded = 1;
352        serializedJob.JobInfo.PluginsNeeded = pluginsNeeded;
353        serializedJob.JobInfo.Priority = priority;
354        try {
355          maxConcurrentConnections.WaitOne();
356          while (response == null) { // repeat until success
357            cancellationToken.ThrowIfCancellationRequested();
358            try {
359              using (Disposable<IClientFacade> service = ServiceLocator.Instance.StreamedClientFacadePool.GetService()) {
360                response = service.Obj.AddJobWithGroupStrings(serializedJob, groups);
361                serializedJob = null;
362              }
363            }
364            catch (Exception e) {
365              LogException(e);
366            }
367          }
368        }
369        finally {
370          maxConcurrentConnections.Release();
371        }
372      }
373      finally {
374        maxSerializedJobsInMemory.Release();
375      }
376      return response.Obj;
377    }
378
379    private OperationJob DownloadJob(IDictionary<Guid, int> jobIndices, object jobIdObj, CancellationToken cancellationToken) {
380      Guid jobId = (Guid)jobIdObj;
381      SerializedJob serializedJob = null;
382      OperationJob operationJob = null;
383      try {
384        maxSerializedJobsInMemory.WaitOne();
385        maxConcurrentConnections.WaitOne();
386        while (serializedJob == null) { // repeat until success
387          cancellationToken.ThrowIfCancellationRequested();
388          try {
389            using (Disposable<IClientFacade> service = ServiceLocator.Instance.StreamedClientFacadePool.GetService()) {
390              serializedJob = service.Obj.GetLastSerializedResult(jobId).Obj;
391            }
392          }
393          catch (Exception e) {
394            LogException(e);
395          }
396        }
397        operationJob = SerializedJob.Deserialize<OperationJob>(serializedJob.SerializedJobData);
398        serializedJob = null;
399        LogMessage(string.Format("Downloaded job #{0}", jobIndices[jobId] + 1, jobId));
400      }
401      finally {
402        maxConcurrentConnections.Release();
403        maxSerializedJobsInMemory.Release();
404      }
405      return operationJob;
406    }
407
408    /// <summary>
409    /// Threadsafe message logging
410    /// </summary>
411    private void LogMessage(string message) {
412      lock (Log) {
413        Log.LogMessage(message);
414      }
415    }
416
417    /// <summary>
418    /// Threadsafe exception logging
419    /// </summary>
420    private void LogException(Exception exception) {
421      lock (Log) {
422        Log.LogException(exception);
423      }
424    }
425  }
426
427  public static class ScopeExtensions {
428    public static void ClearParentScopes(this IScope scope) {
429      scope.ClearParentScopes(null);
430    }
431
432    public static void ClearParentScopes(this IScope scope, IScope childScope) {
433      if (childScope != null) {
434        scope.SubScopes.Clear();
435        scope.SubScopes.Add(childScope);
436      }
437      if (scope.Parent != null)
438        scope.Parent.ClearParentScopes(scope);
439    }
440  }
441
442  public static class EnumerableExtensions {
443    public static TimeSpan Sum(this IEnumerable<TimeSpan> times) {
444      return TimeSpan.FromMilliseconds(times.Select(e => e.TotalMilliseconds).Sum());
445    }
446  }
447}
Note: See TracBrowser for help on using the repository browser.