Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Hive.Engine/3.2/HiveEngine.cs @ 1925

Last change on this file since 1925 was 1925, checked in by gkronber, 15 years ago

Fixed #657 (HiveEngine doesn't add all necessary plugins to the list of necessary plugins for a job)

File size: 9.1 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
175      //This are just Stubs on the server right now. There won't be any effect right now...
176      executionEngineFacade.AbortJob(jobId);
177      OnFinished();
178    }
179
180    public void Reset() {
181      job.Engine.Reset();
182      jobId = Guid.NewGuid();
183      OnInitialized();
184    }
185
186    public event EventHandler Initialized;
187    /// <summary>
188    /// Fires a new <c>Initialized</c> event.
189    /// </summary>
190    protected virtual void OnInitialized() {
191      if (Initialized != null)
192        Initialized(this, new EventArgs());
193    }
194
195    public event EventHandler<OperationEventArgs> OperationExecuted;
196    /// <summary>
197    /// Fires a new <c>OperationExecuted</c> event.
198    /// </summary>
199    /// <param name="operation">The operation that has been executed.</param>
200    protected virtual void OnOperationExecuted(IOperation operation) {
201      if (OperationExecuted != null)
202        OperationExecuted(this, new OperationEventArgs(operation));
203    }
204
205    public event EventHandler<ExceptionEventArgs> ExceptionOccurred;
206    /// <summary>
207    /// Aborts the execution and fires a new <c>ExceptionOccurred</c> event.
208    /// </summary>
209    /// <param name="exception">The exception that was thrown.</param>
210    protected virtual void OnExceptionOccurred(Exception exception) {
211      Abort();
212      if (ExceptionOccurred != null)
213        ExceptionOccurred(this, new ExceptionEventArgs(exception));
214    }
215
216    public event EventHandler ExecutionTimeChanged;
217    /// <summary>
218    /// Fires a new <c>ExecutionTimeChanged</c> event.
219    /// </summary>
220    protected virtual void OnExecutionTimeChanged() {
221      if (ExecutionTimeChanged != null)
222        ExecutionTimeChanged(this, new EventArgs());
223    }
224
225    public event EventHandler Finished;
226    /// <summary>
227    /// Fires a new <c>Finished</c> event.
228    /// </summary>
229    protected virtual void OnFinished() {
230      if (Finished != null)
231        Finished(this, new EventArgs());
232    }
233
234    #endregion
235
236    public override IView CreateView() {
237      return new HiveEngineEditor(this);
238    }
239
240    #region IEditable Members
241
242    public IEditor CreateEditor() {
243      return new HiveEngineEditor(this);
244    }
245    #endregion
246
247    public override System.Xml.XmlNode GetXmlNode(string name, System.Xml.XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
248      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
249      XmlAttribute attr = document.CreateAttribute("HiveServerUrl");
250      attr.Value = HiveServerUrl;
251      node.Attributes.Append(attr);
252      node.AppendChild(PersistenceManager.Persist("Job", job, document, persistedObjects));
253      return node;
254    }
255
256    public override void Populate(System.Xml.XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
257      base.Populate(node, restoredObjects);
258      HiveServerUrl = node.Attributes["HiveServerUrl"].Value;
259      job = (Job)PersistenceManager.Restore(node.SelectSingleNode("Job"), restoredObjects);
260    }
261  }
262}
Note: See TracBrowser for help on using the repository browser.