Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Operator Architecture Refactoring/HeuristicLab.Hive.Engine/3.2/HiveEngine.cs @ 2092

Last change on this file since 2092 was 1990, checked in by gkronber, 16 years ago
  • Refactoring: renamed method LoadPlugins to LoadAssemblies in class Runner.
  • Added cache of loaded assemblies in the Runner.
  • Added an AssemblyResolveEvent that returns already loaded assemblies from the cache.

#658 (For the execution of jobs assemblies have to be loaded dynamically in the correct order)

File size: 9.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Text;
25using HeuristicLab.Core;
26using System.Threading;
27using HeuristicLab.Hive.JobBase;
28using HeuristicLab.Hive.Contracts.Interfaces;
29using HeuristicLab.Hive.Contracts;
30using HeuristicLab.PluginInfrastructure;
31using HeuristicLab.Hive.Contracts.BusinessObjects;
32using System.IO;
33using System.Xml;
34using System.IO.Compression;
35
36namespace HeuristicLab.Hive.Engine {
37  /// <summary>
38  /// Represents an engine that executes its operator-graph on the hive.
39  /// in parallel.
40  /// </summary>
41  public class HiveEngine : ItemBase, IEngine, IEditable {
42    private Guid jobId;
43    private Job job;
44    public string HiveServerUrl { get; set; }
45
46    public HiveEngine() {
47      job = new Job();
48    }
49
50    #region IEngine Members
51
52    public IOperatorGraph OperatorGraph {
53      get { return job.Engine.OperatorGraph; }
54    }
55
56    public IScope GlobalScope {
57      get { return job.Engine.GlobalScope; }
58    }
59
60    public TimeSpan ExecutionTime {
61      get { return job.Engine.ExecutionTime; }
62    }
63
64    public ThreadPriority Priority {
65      get { return job.Engine.Priority; }
66      set { job.Engine.Priority = value; }
67    }
68
69    public bool Running {
70      get { return job.Engine.Running; }
71    }
72
73    public bool Canceled {
74      get { return job.Engine.Canceled; }
75    }
76
77    public bool Terminated {
78      get { return job.Engine.Terminated; }
79    }
80
81    public void Execute() {
82      var jobObj = CreateJobObj();
83
84      IExecutionEngineFacade executionEngineFacade = ServiceLocator.CreateExecutionEngineFacade(HiveServerUrl);
85      ResponseObject<Contracts.BusinessObjects.Job> res = executionEngineFacade.AddJob(jobObj);
86      jobId = res.Obj.Id;
87    }
88
89    private HeuristicLab.Hive.Contracts.BusinessObjects.Job CreateJobObj() {
90      HeuristicLab.Hive.Contracts.BusinessObjects.Job jobObj = new HeuristicLab.Hive.Contracts.BusinessObjects.Job();
91
92      MemoryStream memStream = new MemoryStream();
93      GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
94      XmlDocument document = PersistenceManager.CreateXmlDocument();
95      Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
96      XmlNode rootNode = document.CreateElement("Root");
97      document.AppendChild(rootNode);
98      rootNode.AppendChild(PersistenceManager.Persist(job, document, dictionary));
99      document.Save(stream);
100      stream.Close();
101      jobObj.SerializedJob = memStream.ToArray();
102
103      DiscoveryService service = new DiscoveryService();
104      List<PluginInfo> plugins = new List<PluginInfo>();
105
106      foreach (IStorable storeable in dictionary.Values) {
107        PluginInfo pluginInfo = service.GetDeclaringPlugin(storeable.GetType());
108        if (!plugins.Contains(pluginInfo)) {
109          plugins.Add(pluginInfo);
110          foreach (var dependency in pluginInfo.Dependencies) {
111            if (!plugins.Contains(dependency)) plugins.Add(dependency);
112          }
113        }
114      }
115
116      List<HivePluginInfo> pluginsNeeded =
117        new List<HivePluginInfo>();
118      foreach (PluginInfo uniquePlugin in plugins) {
119        HivePluginInfo pluginInfo =
120          new HivePluginInfo();
121        pluginInfo.Name = uniquePlugin.Name;
122        pluginInfo.Version = uniquePlugin.Version.ToString();
123        pluginInfo.BuildDate = uniquePlugin.BuildDate;
124        pluginsNeeded.Add(pluginInfo);
125      }
126
127      jobObj.CoresNeeded = 1;
128      jobObj.PluginsNeeded = pluginsNeeded;
129      jobObj.State = HeuristicLab.Hive.Contracts.BusinessObjects.State.offline;
130      return jobObj;
131    }
132
133    public void RequestSnapshot() {
134      IExecutionEngineFacade executionEngineFacade = ServiceLocator.CreateExecutionEngineFacade(HiveServerUrl);
135
136      // poll until snapshot is ready
137      ResponseObject<JobResult> response;
138
139      // request snapshot
140      Response snapShotResponse = executionEngineFacade.RequestSnapshot(jobId);
141      if (snapShotResponse.StatusMessage == ApplicationConstants.RESPONSE_JOB_IS_NOT_BEEING_CALCULATED) {
142        response = executionEngineFacade.GetLastResult(jobId, false);
143      } else {
144        do {
145          response = executionEngineFacade.GetLastResult(jobId, true);
146          if (response.Success && response.StatusMessage == ApplicationConstants.RESPONSE_JOB_RESULT_NOT_YET_HERE) {
147            Thread.Sleep(1000);
148          }
149        } while (response.Success && response.StatusMessage == ApplicationConstants.RESPONSE_JOB_RESULT_NOT_YET_HERE);
150      }
151      if (response.Success) {
152        JobResult jobResult = response.Obj;
153        if (jobResult != null) {
154          job = (Job)PersistenceManager.RestoreFromGZip(jobResult.Result);
155          PluginManager.ControlManager.ShowControl(job.Engine.CreateView());
156        }
157      } else {
158        Exception ex = new Exception(response.Obj.Exception.Message);
159        ThreadPool.QueueUserWorkItem(delegate(object state) { OnExceptionOccurred(ex); });
160      }
161    }
162
163
164    public void ExecuteStep() {
165      throw new NotSupportedException();
166    }
167
168    public void ExecuteSteps(int steps) {
169      throw new NotSupportedException();
170    }
171
172    public void Abort() {
173      IExecutionEngineFacade executionEngineFacade = ServiceLocator.CreateExecutionEngineFacade(HiveServerUrl);
174      executionEngineFacade.AbortJob(jobId);
175      OnFinished();
176    }
177
178    public void Reset() {
179      job.Engine.Reset();
180      jobId = Guid.NewGuid();
181      OnInitialized();
182    }
183
184    public event EventHandler Initialized;
185    /// <summary>
186    /// Fires a new <c>Initialized</c> event.
187    /// </summary>
188    protected virtual void OnInitialized() {
189      if (Initialized != null)
190        Initialized(this, new EventArgs());
191    }
192
193    public event EventHandler<OperationEventArgs> OperationExecuted;
194    /// <summary>
195    /// Fires a new <c>OperationExecuted</c> event.
196    /// </summary>
197    /// <param name="operation">The operation that has been executed.</param>
198    protected virtual void OnOperationExecuted(IOperation operation) {
199      if (OperationExecuted != null)
200        OperationExecuted(this, new OperationEventArgs(operation));
201    }
202
203    public event EventHandler<ExceptionEventArgs> ExceptionOccurred;
204    /// <summary>
205    /// Aborts the execution and fires a new <c>ExceptionOccurred</c> event.
206    /// </summary>
207    /// <param name="exception">The exception that was thrown.</param>
208    protected virtual void OnExceptionOccurred(Exception exception) {
209      Abort();
210      if (ExceptionOccurred != null)
211        ExceptionOccurred(this, new ExceptionEventArgs(exception));
212    }
213
214    public event EventHandler ExecutionTimeChanged;
215    /// <summary>
216    /// Fires a new <c>ExecutionTimeChanged</c> event.
217    /// </summary>
218    protected virtual void OnExecutionTimeChanged() {
219      if (ExecutionTimeChanged != null)
220        ExecutionTimeChanged(this, new EventArgs());
221    }
222
223    public event EventHandler Finished;
224    /// <summary>
225    /// Fires a new <c>Finished</c> event.
226    /// </summary>
227    protected virtual void OnFinished() {
228      if (Finished != null)
229        Finished(this, new EventArgs());
230    }
231
232    #endregion
233
234    public override IView CreateView() {
235      return new HiveEngineEditor(this);
236    }
237
238    #region IEditable Members
239
240    public IEditor CreateEditor() {
241      return new HiveEngineEditor(this);
242    }
243    #endregion
244
245    public override System.Xml.XmlNode GetXmlNode(string name, System.Xml.XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
246      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
247      XmlAttribute attr = document.CreateAttribute("HiveServerUrl");
248      attr.Value = HiveServerUrl;
249      node.Attributes.Append(attr);
250      node.AppendChild(PersistenceManager.Persist("Job", job, document, persistedObjects));
251      return node;
252    }
253
254    public override void Populate(System.Xml.XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
255      base.Populate(node, restoredObjects);
256      HiveServerUrl = node.Attributes["HiveServerUrl"].Value;
257      job = (Job)PersistenceManager.Restore(node.SelectSingleNode("Job"), restoredObjects);
258    }
259  }
260}
Note: See TracBrowser for help on using the repository browser.