Free cookie consent management tool by TermsFeed Policy Generator

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

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

extended messagetypes (#456)

File size: 8.6 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 {
[997]48  public class Core: MarshalByRefObject {
[804]49    public delegate string GetASnapshotDelegate();
50
[1033]51    public static Object Locker { get; set; }
52
[1083]53    public static bool ShutdownFlag { get; set; }
54
[768]55    Dictionary<long, Executor> engines = new Dictionary<long, Executor>();
[770]56    Dictionary<long, AppDomain> appDomains = new Dictionary<long, AppDomain>();
[1005]57    Dictionary<long, Job> jobs = new Dictionary<long, Job>();
58
[923]59    private WcfService wcfService;
[798]60
[790]61    public void Start() {
[1035]62      Core.Locker = new Object();
[1083]63      ShutdownFlag = false;
64
[1032]65      Logging.GetInstance().Info(this.ToString(), "Hive Client started");
[901]66      ClientConsoleServer server = new ClientConsoleServer();
67      server.StartClientConsoleServer(new Uri("net.tcp://127.0.0.1:8000/ClientConsole/"));
[843]68
[932]69      ConfigManager manager = ConfigManager.Instance;
[908]70      manager.Core = this;
71
[923]72      wcfService = WcfService.Instance;
[1036]73      wcfService.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(wcfService_LoginCompleted);
74      wcfService.PullJobCompleted += new EventHandler<PullJobCompletedEventArgs>(wcfService_PullJobCompleted);
75      wcfService.SendJobResultCompleted += new EventHandler<SendJobResultCompletedEventArgs>(wcfService_SendJobResultCompleted);
76      wcfService.ConnectionRestored += new EventHandler(wcfService_ConnectionRestored);
77      wcfService.ServerChanged += new EventHandler(wcfService_ServerChanged);
[1081]78      wcfService.Connected += new EventHandler(wcfService_Connected);
[944]79      ConnectionContainer cc = ConfigManager.Instance.GetServerIPAndPort();
[949]80      if (cc.IPAdress != String.Empty && cc.Port != 0) {
81        wcfService.Connect(cc.IPAdress, cc.Port);
[944]82      }
[1036]83   
[900]84      Heartbeat beat = new Heartbeat { Interval = 10000 };
[841]85      beat.StartHeartbeat();     
86
[735]87      MessageQueue queue = MessageQueue.GetInstance();
[1083]88      while (!ShutdownFlag) {
[735]89        MessageContainer container = queue.GetMessage();
[779]90        Debug.WriteLine("Main loop received this message: " + container.Message.ToString());
[790]91        Logging.GetInstance().Info(this.ToString(), container.Message.ToString());
[768]92        DetermineAction(container);
[735]93      }
94    }
[768]95
96    private void DetermineAction(MessageContainer container) {
[779]97      switch (container.Message) {
98        case MessageContainer.MessageType.AbortJob:
99          engines[container.JobId].Abort();
100          break;
101        case MessageContainer.MessageType.JobAborted:
102          Debug.WriteLine("-- Job Aborted Message received");
103          break;
[790]104
[779]105        case MessageContainer.MessageType.RequestSnapshot:
106          engines[container.JobId].RequestSnapshot();
107          break;
108        case MessageContainer.MessageType.SnapshotReady:
[811]109          Thread ssr = new Thread(new ParameterizedThreadStart(GetSnapshot));
110          ssr.Start(container.JobId);         
[779]111          break;
[790]112
[811]113        case MessageContainer.MessageType.FetchJob:
[923]114          wcfService.PullJobAsync(Guid.NewGuid());
[811]115          break;         
[779]116        case MessageContainer.MessageType.FinishedJob:
[811]117          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
118          finThread.Start(container.JobId);         
[1085]119          break;     
120        case MessageContainer.MessageType.Shutdown:
121          ShutdownFlag = true;
122          break;
[779]123      }
124    }
[790]125
[923]126    #region Async Threads for the EE
127   
[811]128    private void GetFinishedJob(object jobId) {
129      long jId = (long)jobId;
[830]130      byte[] sJob = engines[jId].GetFinishedJob();
[1005]131
132      JobResult jobResult = new JobResult { Job = jobs[jId], Result = sJob, Client = ConfigManager.Instance.GetClientInfo() };
[993]133      wcfService.SendJobResultAsync(jobResult, true);     
[804]134    }
135
[811]136    private void GetSnapshot(object jobId) {
137      long jId = (long)jobId;
[816]138      byte[] obj = engines[jId].GetSnapshot();
[811]139    }
140
[923]141    #endregion
142
143    #region wcfService Events
144
145    void wcfService_LoginCompleted(object sender, LoginCompletedEventArgs e) {
146      if (e.Result.Success) {
[944]147        Logging.GetInstance().Info(this.ToString(), "Login completed to Hive Server @ " + DateTime.Now);       
[923]148      } else
149        Logging.GetInstance().Error(this.ToString(), e.Result.StatusMessage);
150    }   
151
152    void wcfService_PullJobCompleted(object sender, PullJobCompletedEventArgs e) {
[960]153      if (e.Result.StatusMessage != ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOBS_LEFT) {
[1001]154        bool sandboxed = false;
[798]155
[960]156        PluginManager.Manager.Initialize();
[1033]157        AppDomain appDomain = PluginManager.Manager.CreateAndInitAppDomainWithSandbox(e.Result.Job.Id.ToString(), sandboxed, typeof(TestJob));
[997]158        appDomain.UnhandledException += new UnhandledExceptionEventHandler(appDomain_UnhandledException);
[1033]159        lock (Locker) {
160          if (!jobs.ContainsKey(e.Result.Job.Id)) {
161            jobs.Add(e.Result.Job.Id, e.Result.Job);
162            appDomains.Add(e.Result.Job.Id, appDomain);
[997]163
[1033]164            Executor engine = (Executor)appDomain.CreateInstanceAndUnwrap(typeof(Executor).Assembly.GetName().Name, typeof(Executor).FullName);
165            engine.JobId = e.Result.Job.Id;
166            engine.Queue = MessageQueue.GetInstance();
167            engine.Start(e.Result.SerializedJob);
168            engines.Add(e.Result.Job.Id, engine);
[798]169
[1033]170            ClientStatusInfo.JobsFetched++;
[798]171
[1033]172            Debug.WriteLine("Increment FetchedJobs to:" + ClientStatusInfo.JobsFetched);
173          }
[1031]174        }
[960]175      }
[798]176    }
177
[923]178    void wcfService_SendJobResultCompleted(object sender, SendJobResultCompletedEventArgs e) {
[840]179      if (e.Result.Success) {
[1033]180        lock (Locker) {
181          AppDomain.Unload(appDomains[e.Result.Job.Id]);
182          appDomains.Remove(e.Result.Job.Id);
183          engines.Remove(e.Result.Job.Id);
184          jobs.Remove(e.Result.Job.Id);
185          ClientStatusInfo.JobsProcessed++;
186        }
[932]187        Debug.WriteLine("ProcessedJobs to:" + ClientStatusInfo.JobsProcessed);
[840]188      } else {
189        Debug.WriteLine("Job sending FAILED!");
190      }
[779]191    }
[908]192
[932]193    void wcfService_ServerChanged(object sender, EventArgs e) {
[1081]194      lock (Locker) {
195        foreach (KeyValuePair<long, AppDomain> entries in appDomains)
196          AppDomain.Unload(appDomains[entries.Key]);
197        appDomains = new Dictionary<long, AppDomain>();
198        engines = new Dictionary<long, Executor>();
199      }
200    }
201
202    void wcfService_Connected(object sender, EventArgs e) {
[993]203      wcfService.LoginAsync(ConfigManager.Instance.GetClientInfo());
[932]204    }
205
[1083]206    void wcfService_ConnectionRestored(object sender, EventArgs e) {
207      //Do some fancy new things here... e.g: check all appdomains if there are still active Jobs that need to be transmitted
208    }
[932]209
[923]210    #endregion
211
[908]212    public Dictionary<long, Executor> GetExecutionEngines() {
213      return engines;
214    }
[997]215
216    void appDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
217      Logging.GetInstance().Error(this.ToString(), " Exception: " + e.ExceptionObject.ToString());
218    }
[714]219  }
220}
Note: See TracBrowser for help on using the repository browser.