Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1815 was 1815, checked in by swagner, 15 years ago

Added a property for the thread priority of an engine's worker thread to EngineBase (#623)

File size: 8.7 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      IExecutionEngineFacade executionEngineFacade = ServiceLocator.CreateExecutionEngineFacade(HiveServerUrl);
83
84      var jobObj = CreateJobObj();
85
86      ResponseObject<Contracts.BusinessObjects.Job> res = executionEngineFacade.AddJob(jobObj);
87      jobId = res.Obj.Id;
88    }
89
90    private HeuristicLab.Hive.Contracts.BusinessObjects.Job CreateJobObj() {
91      HeuristicLab.Hive.Contracts.BusinessObjects.Job jobObj = new HeuristicLab.Hive.Contracts.BusinessObjects.Job();
92
93      MemoryStream memStream = new MemoryStream();
94      GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
95      XmlDocument document = PersistenceManager.CreateXmlDocument();
96      Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
97      XmlNode rootNode = document.CreateElement("Root");
98      document.AppendChild(rootNode);
99      rootNode.AppendChild(PersistenceManager.Persist(job, document, dictionary));
100      document.Save(stream);
101      stream.Close();
102      jobObj.SerializedJob = memStream.ToArray();
103
104      DiscoveryService service = new DiscoveryService();
105      List<PluginInfo> plugins = new List<PluginInfo>();
106
107      foreach (IStorable storeable in dictionary.Values) {
108        PluginInfo pluginInfo = service.GetDeclaringPlugin(storeable.GetType());
109        if (!plugins.Contains(pluginInfo)) plugins.Add(pluginInfo);
110      }
111
112      List<HivePluginInfo> pluginsNeeded =
113        new List<HivePluginInfo>();
114      foreach (PluginInfo uniquePlugin in plugins) {
115        HivePluginInfo pluginInfo =
116          new HivePluginInfo();
117        pluginInfo.Name = uniquePlugin.Name;
118        pluginInfo.Version = uniquePlugin.Version.ToString();
119        pluginInfo.BuildDate = uniquePlugin.BuildDate;
120        pluginsNeeded.Add(pluginInfo);
121      }
122
123      jobObj.CoresNeeded = 1;
124      jobObj.PluginsNeeded = pluginsNeeded;
125      jobObj.State = HeuristicLab.Hive.Contracts.BusinessObjects.State.offline;
126      return jobObj;
127    }
128
129    public void RequestSnapshot() {
130      IExecutionEngineFacade executionEngineFacade = ServiceLocator.CreateExecutionEngineFacade(HiveServerUrl);
131
132      // request snapshot
133      executionEngineFacade.RequestSnapshot(jobId);
134
135      // poll until snapshot is ready
136      ResponseObject<JobResult> response;
137      do {
138        response = executionEngineFacade.GetLastResult(jobId, true);
139        if (response.Success && response.StatusMessage == ApplicationConstants.RESPONSE_JOB_RESULT_NOT_YET_HERE) {
140          Thread.Sleep(1000);
141        }
142      } while (response.Success && response.StatusMessage == ApplicationConstants.RESPONSE_JOB_RESULT_NOT_YET_HERE);
143
144      if (response.Success) {
145        JobResult jobResult = response.Obj;
146        if (jobResult != null) {
147          job = (Job)PersistenceManager.RestoreFromGZip(jobResult.Result);
148          PluginManager.ControlManager.ShowControl(job.Engine.CreateView());
149        }
150      } else {
151        Exception ex = new Exception(response.Obj.Exception.Message);
152        ThreadPool.QueueUserWorkItem(delegate(object state) { OnExceptionOccurred(ex); });
153      }
154    }
155
156
157    public void ExecuteStep() {
158      throw new NotSupportedException();
159    }
160
161    public void ExecuteSteps(int steps) {
162      throw new NotSupportedException();
163    }
164
165    public void Abort() {
166      IExecutionEngineFacade executionEngineFacade = ServiceLocator.CreateExecutionEngineFacade(HiveServerUrl);
167
168      //This are just Stubs on the server right now. There won't be any effect right now...
169      executionEngineFacade.AbortJob(jobId);
170      OnFinished();
171    }
172
173    public void Reset() {
174      job.Engine.Reset();
175      jobId = Guid.NewGuid();
176      OnInitialized();
177    }
178
179    public event EventHandler Initialized;
180    /// <summary>
181    /// Fires a new <c>Initialized</c> event.
182    /// </summary>
183    protected virtual void OnInitialized() {
184      if (Initialized != null)
185        Initialized(this, new EventArgs());
186    }
187
188    public event EventHandler<OperationEventArgs> OperationExecuted;
189    /// <summary>
190    /// Fires a new <c>OperationExecuted</c> event.
191    /// </summary>
192    /// <param name="operation">The operation that has been executed.</param>
193    protected virtual void OnOperationExecuted(IOperation operation) {
194      if (OperationExecuted != null)
195        OperationExecuted(this, new OperationEventArgs(operation));
196    }
197
198    public event EventHandler<ExceptionEventArgs> ExceptionOccurred;
199    /// <summary>
200    /// Aborts the execution and fires a new <c>ExceptionOccurred</c> event.
201    /// </summary>
202    /// <param name="exception">The exception that was thrown.</param>
203    protected virtual void OnExceptionOccurred(Exception exception) {
204      Abort();
205      if (ExceptionOccurred != null)
206        ExceptionOccurred(this, new ExceptionEventArgs(exception));
207    }
208
209    public event EventHandler ExecutionTimeChanged;
210    /// <summary>
211    /// Fires a new <c>ExecutionTimeChanged</c> event.
212    /// </summary>
213    protected virtual void OnExecutionTimeChanged() {
214      if (ExecutionTimeChanged != null)
215        ExecutionTimeChanged(this, new EventArgs());
216    }
217
218    public event EventHandler Finished;
219    /// <summary>
220    /// Fires a new <c>Finished</c> event.
221    /// </summary>
222    protected virtual void OnFinished() {
223      if (Finished != null)
224        Finished(this, new EventArgs());
225    }
226
227    #endregion
228
229    public override IView CreateView() {
230      return new HiveEngineEditor(this);
231    }
232
233    #region IEditable Members
234
235    public IEditor CreateEditor() {
236      return new HiveEngineEditor(this);
237    }
238    #endregion
239
240    public override System.Xml.XmlNode GetXmlNode(string name, System.Xml.XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
241      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
242      XmlAttribute attr = document.CreateAttribute("HiveServerUrl");
243      attr.Value = HiveServerUrl;
244      node.Attributes.Append(attr);
245      node.AppendChild(PersistenceManager.Persist("Job", job, document, persistedObjects));
246      return node;
247    }
248
249    public override void Populate(System.Xml.XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
250      base.Populate(node, restoredObjects);
251      HiveServerUrl = node.Attributes["HiveServerUrl"].Value;
252      job = (Job)PersistenceManager.Restore(node.SelectSingleNode("Job"), restoredObjects);
253    }
254  }
255}
Note: See TracBrowser for help on using the repository browser.