Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Grid.HiveBridge/3.2/HiveGridServerWrapper.cs @ 3381

Last change on this file since 3381 was 3013, checked in by kgrading, 15 years ago

fixed HiveBridge and removed compile errors (#830)

File size: 7.4 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 System.Threading;
26using HeuristicLab.Hive.Contracts.Interfaces;
27using HeuristicLab.Hive.Contracts;
28using System.IO;
29using System.IO.Compression;
30using System.Xml;
31using HeuristicLab.Core;
32using HeuristicLab.PluginInfrastructure;
33using HeuristicLab.Hive.Contracts.BusinessObjects;
34using System.ServiceModel;
35using HeuristicLab.Tracing;
36
37namespace HeuristicLab.Grid.HiveBridge {
38  public class HiveGridServerWrapper : IGridServer {
39    private const int MAX_CONNECTION_RETRIES = 10;
40    private const int RETRY_TIMEOUT_SEC = 60;
41    private string address;
42    private IExecutionEngineFacade executionEngine;
43    private object connectionLock = new object();
44
45    public HiveGridServerWrapper(string address) {
46      this.address = address;
47    }
48
49    public JobState JobState(Guid guid) {
50      ResponseObject<SerializedJob> response = SavelyExecute(() => executionEngine.GetLastSerializedResult(guid, false));
51      if (response != null) {
52        return HeuristicLab.Grid.JobState.Busy;
53      } else return HeuristicLab.Grid.JobState.Unknown;
54    }
55
56    public Guid BeginExecuteEngine(byte[] engine) {
57      var jobObj = CreateJobObj(engine);
58
59      ResponseObject<HeuristicLab.Hive.Contracts.BusinessObjects.JobDto> res = SavelyExecute(() => executionEngine.AddJob(jobObj));
60      return res == null ? Guid.Empty : res.Obj.Id;
61    }
62
63    public byte[] TryEndExecuteEngine(Guid guid) {
64      ResponseObject<SerializedJob> response = SavelyExecute(() => executionEngine.GetLastSerializedResult(guid, false));
65      if (response != null &&
66        response.Success && response.Obj != null) {
67        HeuristicLab.Hive.Engine.Job restoredJob = (HeuristicLab.Hive.Engine.Job)PersistenceManager.RestoreFromGZip(response.Obj.SerializedJobData);
68        // only return the engine when it wasn't canceled (result is only a snapshot)
69        if (restoredJob.Progress == 1.0) {
70          // Serialize the engine
71          MemoryStream memStream = new MemoryStream();
72          GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
73          XmlDocument document = PersistenceManager.CreateXmlDocument();
74          Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
75          XmlNode rootNode = document.CreateElement("Root");
76          document.AppendChild(rootNode);
77          rootNode.AppendChild(PersistenceManager.Persist(restoredJob.Engine, document, dictionary));
78          document.Save(stream);
79          stream.Close();
80          return memStream.ToArray();
81        }
82      }
83
84      return null;
85    }
86
87    private HeuristicLab.Hive.Contracts.BusinessObjects.SerializedJob CreateJobObj(byte[] serializedEngine) {
88      HeuristicLab.Hive.Contracts.BusinessObjects.JobDto jobObj = new HeuristicLab.Hive.Contracts.BusinessObjects.JobDto();
89
90      List<HivePluginInfoDto> requiredPlugins = new List<HivePluginInfoDto>();
91      IEngine engine = RestoreEngine(serializedEngine, requiredPlugins);
92
93      HeuristicLab.Hive.Engine.Job job = new HeuristicLab.Hive.Engine.Job();
94      job.Engine.OperatorGraph.AddOperator(engine.OperatorGraph.InitialOperator);
95      job.Engine.OperatorGraph.InitialOperator = engine.OperatorGraph.InitialOperator;
96      job.Engine.Reset();
97
98      // Serialize the job
99      MemoryStream memStream = new MemoryStream();
100      GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
101      XmlDocument document = PersistenceManager.CreateXmlDocument();
102      Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
103      XmlNode rootNode = document.CreateElement("Root");
104      document.AppendChild(rootNode);
105      rootNode.AppendChild(PersistenceManager.Persist(job, document, dictionary));
106      document.Save(stream);
107      stream.Close();
108
109      SerializedJob computableJob =
110        new SerializedJob();
111      computableJob.SerializedJobData = memStream.ToArray();
112      jobObj.CoresNeeded = 1;
113      jobObj.PluginsNeeded = requiredPlugins;
114      jobObj.State = HeuristicLab.Hive.Contracts.BusinessObjects.State.offline;
115
116      computableJob.JobInfo = jobObj;
117
118      return computableJob;
119    }
120
121    private IEngine RestoreEngine(byte[] serializedEngine, List<HivePluginInfoDto> requiredPlugins) {
122      // unzip and restore to determine the list of required plugins (NB: inefficient!)
123      MemoryStream memStream = new MemoryStream(serializedEngine);
124      GZipStream stream = new GZipStream(memStream, CompressionMode.Decompress, true);
125      XmlDocument document = new XmlDocument();
126      document.Load(stream);
127
128      Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
129      XmlNode rootNode = document.ChildNodes[1].ChildNodes[0];
130      IEngine engine = (IEngine)PersistenceManager.Restore(rootNode, dictionary);
131      stream.Close();
132
133      List<IPluginDescription> plugins = new List<IPluginDescription>();
134
135      foreach (IStorable storeable in dictionary.Values) {
136        IPluginDescription pluginInfo = ApplicationManager.Manager.GetDeclaringPlugin(storeable.GetType());
137        if (!plugins.Contains(pluginInfo)) {
138          plugins.Add(pluginInfo);
139          foreach (var dependency in pluginInfo.Dependencies) {
140            if (!plugins.Contains(dependency)) plugins.Add(dependency);
141          }
142        }
143      }
144
145      foreach (IPluginDescription uniquePlugin in plugins) {
146        HivePluginInfoDto pluginInfo =
147          new HivePluginInfoDto();
148        pluginInfo.Name = uniquePlugin.Name;
149        pluginInfo.Version = uniquePlugin.Version.ToString();
150        pluginInfo.BuildDate = uniquePlugin.BuildDate;
151        requiredPlugins.Add(pluginInfo);
152      }
153      return engine;
154    }
155
156    private TResult SavelyExecute<TResult>(Func<TResult> a) where TResult : Response {
157      int retries = 0;
158      if (executionEngine == null)
159        executionEngine = ServiceLocator.CreateExecutionEngineFacade(address);
160
161      do {
162        try {
163          lock (connectionLock) {
164            return a();
165          }
166        }
167        catch (TimeoutException) {
168          retries++;
169          Thread.Sleep(TimeSpan.FromSeconds(RETRY_TIMEOUT_SEC));
170        }
171        catch (CommunicationException) {
172          executionEngine = ServiceLocator.CreateExecutionEngineFacade(address);
173          retries++;
174          Thread.Sleep(TimeSpan.FromSeconds(RETRY_TIMEOUT_SEC));
175        }
176      } while (retries < MAX_CONNECTION_RETRIES);
177      Logger.Warn("Reached max connection retries");
178      return null;
179    }
180  }
181}
Note: See TracBrowser for help on using the repository browser.