Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fixed bugs in preparation of engines for execution on hive. Used HL.Tracing instead of trace statements. #642 (Hive backend for CEDMA)

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<JobResult> response = SavelyExecute(() => executionEngine.GetLastResult(guid, false));
51      if (response != null && response.Success == true &&
52        (response.StatusMessage == ApplicationConstants.RESPONSE_JOB_RESULT_NOT_YET_HERE ||
53          response.StatusMessage == ApplicationConstants.RESPONSE_JOB_REQUEST_SET ||
54          response.StatusMessage == ApplicationConstants.RESPONSE_JOB_REQUEST_ALLREADY_SET ||
55          response.StatusMessage == ApplicationConstants.RESPONSE_JOB_JOB_RESULT_SENT)) {
56        return HeuristicLab.Grid.JobState.Busy;
57      } else return HeuristicLab.Grid.JobState.Unknown;
58    }
59
60    public Guid BeginExecuteEngine(byte[] engine) {
61      var jobObj = CreateJobObj(engine);
62
63      ResponseObject<HeuristicLab.Hive.Contracts.BusinessObjects.Job> res = SavelyExecute(() => executionEngine.AddJob(jobObj));
64      return res == null ? Guid.Empty : res.Obj.Id;
65    }
66
67    public byte[] TryEndExecuteEngine(Guid guid) {
68      ResponseObject<JobResult> response = SavelyExecute(() => executionEngine.GetLastResult(guid, false));
69      if (response != null &&
70        response.Success && response.Obj != null) {
71        HeuristicLab.Hive.Engine.Job restoredJob = (HeuristicLab.Hive.Engine.Job)PersistenceManager.RestoreFromGZip(response.Obj.Result);
72        // Serialize the engine
73        MemoryStream memStream = new MemoryStream();
74        GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
75        XmlDocument document = PersistenceManager.CreateXmlDocument();
76        Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
77        XmlNode rootNode = document.CreateElement("Root");
78        document.AppendChild(rootNode);
79        rootNode.AppendChild(PersistenceManager.Persist(restoredJob.Engine, document, dictionary));
80        document.Save(stream);
81        stream.Close();
82        return memStream.ToArray();
83      } else return null;
84    }
85
86    private HeuristicLab.Hive.Contracts.BusinessObjects.Job CreateJobObj(byte[] serializedEngine) {
87      HeuristicLab.Hive.Contracts.BusinessObjects.Job jobObj = new HeuristicLab.Hive.Contracts.BusinessObjects.Job();
88
89      List<HivePluginInfo> requiredPlugins = new List<HivePluginInfo>();
90      IEngine engine = RestoreEngine(serializedEngine, requiredPlugins);
91
92      HeuristicLab.Hive.Engine.Job job = new HeuristicLab.Hive.Engine.Job();
93      job.Engine.OperatorGraph.AddOperator(engine.OperatorGraph.InitialOperator);
94      job.Engine.OperatorGraph.InitialOperator = engine.OperatorGraph.InitialOperator;
95      job.Engine.Reset();
96
97      // Serialize the job
98      MemoryStream memStream = new MemoryStream();
99      GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
100      XmlDocument document = PersistenceManager.CreateXmlDocument();
101      Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
102      XmlNode rootNode = document.CreateElement("Root");
103      document.AppendChild(rootNode);
104      rootNode.AppendChild(PersistenceManager.Persist(job, document, dictionary));
105      document.Save(stream);
106      stream.Close();
107
108      jobObj.SerializedJob = memStream.ToArray();
109      jobObj.CoresNeeded = 1;
110      jobObj.PluginsNeeded = requiredPlugins;
111      jobObj.State = HeuristicLab.Hive.Contracts.BusinessObjects.State.offline;
112      return jobObj;
113    }
114
115    private IEngine RestoreEngine(byte[] serializedEngine, List<HivePluginInfo> requiredPlugins) {
116      // unzip and restore to determine the list of required plugins (NB: inefficient!)
117      MemoryStream memStream = new MemoryStream(serializedEngine);
118      GZipStream stream = new GZipStream(memStream, CompressionMode.Decompress, true);
119      XmlDocument document = new XmlDocument();
120      document.Load(stream);
121
122      Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
123      XmlNode rootNode = document.ChildNodes[1].ChildNodes[0];
124      IEngine engine = (IEngine)PersistenceManager.Restore(rootNode, dictionary);
125      stream.Close();
126
127      DiscoveryService service = new DiscoveryService();
128      List<PluginInfo> plugins = new List<PluginInfo>();
129
130      foreach (IStorable storeable in dictionary.Values) {
131        PluginInfo pluginInfo = service.GetDeclaringPlugin(storeable.GetType());
132        if (!plugins.Contains(pluginInfo)) {
133          plugins.Add(pluginInfo);
134          foreach (var dependency in pluginInfo.Dependencies) {
135            if (!plugins.Contains(dependency)) plugins.Add(dependency);
136          }
137        }
138      }
139
140      foreach (PluginInfo uniquePlugin in plugins) {
141        HivePluginInfo pluginInfo =
142          new HivePluginInfo();
143        pluginInfo.Name = uniquePlugin.Name;
144        pluginInfo.Version = uniquePlugin.Version.ToString();
145        pluginInfo.BuildDate = uniquePlugin.BuildDate;
146        requiredPlugins.Add(pluginInfo);
147      }
148      return engine;
149    }
150
151    private TResult SavelyExecute<TResult>(Func<TResult> a) where TResult : Response {
152      int retries = 0;
153      if (executionEngine == null)
154        executionEngine = ServiceLocator.CreateExecutionEngineFacade(address);
155
156      do {
157        try {
158          lock (connectionLock) {
159            return a();
160          }
161        }
162        catch (TimeoutException) {
163          retries++;
164          Thread.Sleep(TimeSpan.FromSeconds(RETRY_TIMEOUT_SEC));
165        }
166        catch (CommunicationException) {
167          executionEngine = ServiceLocator.CreateExecutionEngineFacade(address);
168          retries++;
169          Thread.Sleep(TimeSpan.FromSeconds(RETRY_TIMEOUT_SEC));
170        }
171      } while (retries < MAX_CONNECTION_RETRIES);
172      Logger.Warn("Reached max connection retries");
173      return null;
174    }
175  }
176}
Note: See TracBrowser for help on using the repository browser.