Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Hive.Client.Core/Core.cs @ 1242

Last change on this file since 1242 was 1219, checked in by kgrading, 16 years ago

implementation done (#493)

File size: 11.3 KB
RevLine 
[735]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;
[714]23using System.Collections.Generic;
24using System.Linq;
25using System.Text;
[768]26using HeuristicLab.Hive.Client.ExecutionEngine;
[735]27using HeuristicLab.Hive.Client.Common;
[768]28using System.Threading;
[770]29using System.Reflection;
30using System.Diagnostics;
31using System.Security.Permissions;
32using System.Security.Policy;
33using System.Security;
[790]34using HeuristicLab.Hive.Client.Communication;
[793]35using HeuristicLab.Hive.Contracts.BusinessObjects;
36using HeuristicLab.Hive.Contracts;
[804]37using System.Runtime.Remoting.Messaging;
[816]38using HeuristicLab.PluginInfrastructure;
[843]39using System.ServiceModel;
40using System.ServiceModel.Description;
[919]41using HeuristicLab.Hive.Client.Core.ClientConsoleService;
[932]42using HeuristicLab.Hive.Client.Core.ConfigurationManager;
[993]43using HeuristicLab.Hive.Client.Communication.ServerService;
[1001]44using HeuristicLab.Hive.JobBase;
[1219]45using HeuristicLab.Hive.Client.Core.JobStorrage;
[714]46
[768]47
[714]48namespace HeuristicLab.Hive.Client.Core {
[1132]49  /// <summary>
50  /// The core component of the Hive Client
51  /// </summary>
[997]52  public class Core: MarshalByRefObject {
[804]53    public delegate string GetASnapshotDelegate();
54
[1033]55    public static Object Locker { get; set; }
56
[1083]57    public static bool ShutdownFlag { get; set; }
58
[768]59    Dictionary<long, Executor> engines = new Dictionary<long, Executor>();
[770]60    Dictionary<long, AppDomain> appDomains = new Dictionary<long, AppDomain>();
[1005]61    Dictionary<long, Job> jobs = new Dictionary<long, Job>();
62
[923]63    private WcfService wcfService;
[1097]64    private Heartbeat beat;
[1132]65   
66    /// <summary>
67    /// Main Method for the client
68    /// </summary>
[790]69    public void Start() {
[1035]70      Core.Locker = new Object();
[1083]71      ShutdownFlag = false;
72
[1032]73      Logging.GetInstance().Info(this.ToString(), "Hive Client started");
[901]74      ClientConsoleServer server = new ClientConsoleServer();
75      server.StartClientConsoleServer(new Uri("net.tcp://127.0.0.1:8000/ClientConsole/"));
[843]76
[932]77      ConfigManager manager = ConfigManager.Instance;
[908]78      manager.Core = this;
[1132]79     
80      //Register all Wcf Service references
[923]81      wcfService = WcfService.Instance;
[1036]82      wcfService.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(wcfService_LoginCompleted);
83      wcfService.PullJobCompleted += new EventHandler<PullJobCompletedEventArgs>(wcfService_PullJobCompleted);
84      wcfService.SendJobResultCompleted += new EventHandler<SendJobResultCompletedEventArgs>(wcfService_SendJobResultCompleted);
85      wcfService.ConnectionRestored += new EventHandler(wcfService_ConnectionRestored);
86      wcfService.ServerChanged += new EventHandler(wcfService_ServerChanged);
[1081]87      wcfService.Connected += new EventHandler(wcfService_Connected);
[1132]88      //Recover Server IP and Port from the Settings Framework
89      ConnectionContainer cc = ConfigManager.Instance.GetServerIPAndPort();     
[949]90      if (cc.IPAdress != String.Empty && cc.Port != 0) {
91        wcfService.Connect(cc.IPAdress, cc.Port);
[944]92      }
[1036]93   
[1132]94      //Initialize the heartbeat
[1097]95      beat = new Heartbeat { Interval = 10000 };
[841]96      beat.StartHeartbeat();     
97
[735]98      MessageQueue queue = MessageQueue.GetInstance();
[1132]99     
100      //Main processing loop
[1083]101      while (!ShutdownFlag) {
[735]102        MessageContainer container = queue.GetMessage();
[779]103        Debug.WriteLine("Main loop received this message: " + container.Message.ToString());
[790]104        Logging.GetInstance().Info(this.ToString(), container.Message.ToString());
[768]105        DetermineAction(container);
[735]106      }
107    }
[768]108
[1132]109    /// <summary>
110    /// Reads and analyzes the Messages from the MessageQueue and starts corresponding actions
111    /// </summary>
112    /// <param name="container">The Container, containing the message</param>
[768]113    private void DetermineAction(MessageContainer container) {
[779]114      switch (container.Message) {
[1132]115        //Server requests to abort a job
[779]116        case MessageContainer.MessageType.AbortJob:
117          engines[container.JobId].Abort();
118          break;
[1132]119        //Job has been successfully aborted
[779]120        case MessageContainer.MessageType.JobAborted:
121          Debug.WriteLine("-- Job Aborted Message received");
122          break;
[1132]123        //Request a Snapshot from the Execution Engine
[779]124        case MessageContainer.MessageType.RequestSnapshot:
125          engines[container.JobId].RequestSnapshot();
126          break;
[1132]127        //Snapshot is ready and can be sent back to the Server
[779]128        case MessageContainer.MessageType.SnapshotReady:
[811]129          Thread ssr = new Thread(new ParameterizedThreadStart(GetSnapshot));
130          ssr.Start(container.JobId);         
[779]131          break;
[1132]132        //Pull a Job from the Server
[811]133        case MessageContainer.MessageType.FetchJob:
[1150]134          wcfService.PullJobAsync(ConfigManager.Instance.GetClientInfo().ClientId);
[811]135          break;         
[1132]136        //A Job has finished and can be sent back to the server
[779]137        case MessageContainer.MessageType.FinishedJob:
[811]138          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
139          finThread.Start(container.JobId);         
[1085]140          break;     
[1132]141        //Hard shutdown of the client
[1085]142        case MessageContainer.MessageType.Shutdown:
143          ShutdownFlag = true;
[1097]144          beat.StopHeartBeat();
[1085]145          break;
[779]146      }
147    }
[790]148
[1132]149    //Asynchronous Threads for interaction with the Execution Engine
[923]150    #region Async Threads for the EE
151   
[811]152    private void GetFinishedJob(object jobId) {
153      long jId = (long)jobId;
[830]154      byte[] sJob = engines[jId].GetFinishedJob();
[1005]155
[1219]156      if (WcfService.Instance.ConnState == NetworkEnum.WcfConnState.Connected) {
157        wcfService.SendJobResultAsync(ConfigManager.Instance.GetClientInfo().ClientId,
158          jId,
159          sJob,
160          1,
161          null,
162          true);
163      } else {
164        JobStorrageManager.PersistObjectToDisc(wcfService.ServerIP, wcfService.ServerPort, jId, sJob);
165        AppDomain.Unload(appDomains[jId]);
166        appDomains.Remove(jId);
167        engines.Remove(jId);
168        jobs.Remove(jId);
169      }
[804]170    }
171
[811]172    private void GetSnapshot(object jobId) {
173      long jId = (long)jobId;
[816]174      byte[] obj = engines[jId].GetSnapshot();
[1147]175      wcfService.SendJobResultAsync(ConfigManager.Instance.GetClientInfo().ClientId,
176        jId,
177        obj,
178        engines[jId].Progress,
179        null,
180        false);
[811]181    }
182
[923]183    #endregion
184
[1132]185    //Eventhandlers for the communication with the wcf Layer
[923]186    #region wcfService Events
187
188    void wcfService_LoginCompleted(object sender, LoginCompletedEventArgs e) {
189      if (e.Result.Success) {
[944]190        Logging.GetInstance().Info(this.ToString(), "Login completed to Hive Server @ " + DateTime.Now);       
[923]191      } else
192        Logging.GetInstance().Error(this.ToString(), e.Result.StatusMessage);
193    }   
194
195    void wcfService_PullJobCompleted(object sender, PullJobCompletedEventArgs e) {
[960]196      if (e.Result.StatusMessage != ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOBS_LEFT) {
[1199]197        bool sandboxed = true;
[798]198
[960]199        PluginManager.Manager.Initialize();
[1033]200        AppDomain appDomain = PluginManager.Manager.CreateAndInitAppDomainWithSandbox(e.Result.Job.Id.ToString(), sandboxed, typeof(TestJob));
[997]201        appDomain.UnhandledException += new UnhandledExceptionEventHandler(appDomain_UnhandledException);
[1119]202        lock (Locker) {                   
[1033]203          if (!jobs.ContainsKey(e.Result.Job.Id)) {
204            jobs.Add(e.Result.Job.Id, e.Result.Job);
205            appDomains.Add(e.Result.Job.Id, appDomain);
[997]206
[1033]207            Executor engine = (Executor)appDomain.CreateInstanceAndUnwrap(typeof(Executor).Assembly.GetName().Name, typeof(Executor).FullName);
208            engine.JobId = e.Result.Job.Id;
209            engine.Queue = MessageQueue.GetInstance();
[1120]210            engine.Start(e.Result.Job.SerializedJob);
[1033]211            engines.Add(e.Result.Job.Id, engine);
[798]212
[1033]213            ClientStatusInfo.JobsFetched++;
[798]214
[1033]215            Debug.WriteLine("Increment FetchedJobs to:" + ClientStatusInfo.JobsFetched);
216          }
[1031]217        }
[960]218      }
[798]219    }
220
[923]221    void wcfService_SendJobResultCompleted(object sender, SendJobResultCompletedEventArgs e) {
[1147]222      if (e.Result.Success) {       
[1033]223        lock (Locker) {
[1147]224          //if the engine is running again -> we sent an snapshot. Otherwise the job was finished
225          //this method has a risk concerning race conditions.
226          //better expand the sendjobresultcompltedeventargs with a boolean "snapshot?" flag
227          if (e.Result.finished == false) {
228            Logging.GetInstance().Info(this.ToString(), "Snapshot for Job " + e.Result.JobId + " transmitted");
229          } else {
230            AppDomain.Unload(appDomains[e.Result.JobId]);
231            appDomains.Remove(e.Result.JobId);
232            engines.Remove(e.Result.JobId);
233            jobs.Remove(e.Result.JobId);
234            ClientStatusInfo.JobsProcessed++;
235            Debug.WriteLine("ProcessedJobs to:" + ClientStatusInfo.JobsProcessed);
236          }
237        }       
[840]238      } else {
[1147]239        Logging.GetInstance().Error(this.ToString(), "Sending of job " + e.Result.JobId + " failed");
[840]240      }
[779]241    }
[908]242
[932]243    void wcfService_ServerChanged(object sender, EventArgs e) {
[1097]244      Logging.GetInstance().Info(this.ToString(), "ServerChanged has been called");
[1081]245      lock (Locker) {
246        foreach (KeyValuePair<long, AppDomain> entries in appDomains)
247          AppDomain.Unload(appDomains[entries.Key]);
248        appDomains = new Dictionary<long, AppDomain>();
249        engines = new Dictionary<long, Executor>();
250      }
251    }
252
253    void wcfService_Connected(object sender, EventArgs e) {
[1097]254      wcfService.LoginSync(ConfigManager.Instance.GetClientInfo());
[932]255    }
256
[1097]257    //this is a little bit tricky -
[1083]258    void wcfService_ConnectionRestored(object sender, EventArgs e) {
[1097]259      Logging.GetInstance().Info(this.ToString(), "Reconnected to old server - checking currently running appdomains");                 
260
261      foreach (KeyValuePair<long, Executor> execKVP in engines) {
262        if (!execKVP.Value.Running && execKVP.Value.CurrentMessage == MessageContainer.MessageType.NoMessage) {
263          Logging.GetInstance().Info(this.ToString(), "Checking for JobId: " + execKVP.Value.JobId);
264          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
265          finThread.Start(execKVP.Value.JobId);
266        }
267      }
[1083]268    }
[932]269
[923]270    #endregion
271
[908]272    public Dictionary<long, Executor> GetExecutionEngines() {
273      return engines;
274    }
[997]275
276    void appDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
277      Logging.GetInstance().Error(this.ToString(), " Exception: " + e.ExceptionObject.ToString());
278    }
[714]279  }
280}
Note: See TracBrowser for help on using the repository browser.