Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1233

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