Free cookie consent management tool by TermsFeed Policy Generator

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

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

added licence information and comments (#467)

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