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, 15 years ago

extended messagetypes (#456)

File size: 8.6 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.Linq;
25using System.Text;
26using HeuristicLab.Hive.Client.ExecutionEngine;
27using HeuristicLab.Hive.Client.Common;
28using System.Threading;
29using System.Reflection;
30using System.Diagnostics;
31using System.Security.Permissions;
32using System.Security.Policy;
33using System.Security;
34using HeuristicLab.Hive.Client.Communication;
35using HeuristicLab.Hive.Contracts.BusinessObjects;
36using HeuristicLab.Hive.Contracts;
37using System.Runtime.Remoting.Messaging;
38using HeuristicLab.PluginInfrastructure;
39using System.ServiceModel;
40using System.ServiceModel.Description;
41using HeuristicLab.Hive.Client.Core.ClientConsoleService;
42using HeuristicLab.Hive.Client.Core.ConfigurationManager;
43using HeuristicLab.Hive.Client.Communication.ServerService;
44using HeuristicLab.Hive.JobBase;
45
46
47namespace HeuristicLab.Hive.Client.Core {
48  public class Core: MarshalByRefObject {
49    public delegate string GetASnapshotDelegate();
50
51    public static Object Locker { get; set; }
52
53    public static bool ShutdownFlag { get; set; }
54
55    Dictionary<long, Executor> engines = new Dictionary<long, Executor>();
56    Dictionary<long, AppDomain> appDomains = new Dictionary<long, AppDomain>();
57    Dictionary<long, Job> jobs = new Dictionary<long, Job>();
58
59    private WcfService wcfService;
60
61    public void Start() {
62      Core.Locker = new Object();
63      ShutdownFlag = false;
64
65      Logging.GetInstance().Info(this.ToString(), "Hive Client started");
66      ClientConsoleServer server = new ClientConsoleServer();
67      server.StartClientConsoleServer(new Uri("net.tcp://127.0.0.1:8000/ClientConsole/"));
68
69      ConfigManager manager = ConfigManager.Instance;
70      manager.Core = this;
71
72      wcfService = WcfService.Instance;
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);
78      wcfService.Connected += new EventHandler(wcfService_Connected);
79      ConnectionContainer cc = ConfigManager.Instance.GetServerIPAndPort();
80      if (cc.IPAdress != String.Empty && cc.Port != 0) {
81        wcfService.Connect(cc.IPAdress, cc.Port);
82      }
83   
84      Heartbeat beat = new Heartbeat { Interval = 10000 };
85      beat.StartHeartbeat();     
86
87      MessageQueue queue = MessageQueue.GetInstance();
88      while (!ShutdownFlag) {
89        MessageContainer container = queue.GetMessage();
90        Debug.WriteLine("Main loop received this message: " + container.Message.ToString());
91        Logging.GetInstance().Info(this.ToString(), container.Message.ToString());
92        DetermineAction(container);
93      }
94    }
95
96    private void DetermineAction(MessageContainer container) {
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;
104
105        case MessageContainer.MessageType.RequestSnapshot:
106          engines[container.JobId].RequestSnapshot();
107          break;
108        case MessageContainer.MessageType.SnapshotReady:
109          Thread ssr = new Thread(new ParameterizedThreadStart(GetSnapshot));
110          ssr.Start(container.JobId);         
111          break;
112
113        case MessageContainer.MessageType.FetchJob:
114          wcfService.PullJobAsync(Guid.NewGuid());
115          break;         
116        case MessageContainer.MessageType.FinishedJob:
117          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
118          finThread.Start(container.JobId);         
119          break;     
120        case MessageContainer.MessageType.Shutdown:
121          ShutdownFlag = true;
122          break;
123      }
124    }
125
126    #region Async Threads for the EE
127   
128    private void GetFinishedJob(object jobId) {
129      long jId = (long)jobId;
130      byte[] sJob = engines[jId].GetFinishedJob();
131
132      JobResult jobResult = new JobResult { Job = jobs[jId], Result = sJob, Client = ConfigManager.Instance.GetClientInfo() };
133      wcfService.SendJobResultAsync(jobResult, true);     
134    }
135
136    private void GetSnapshot(object jobId) {
137      long jId = (long)jobId;
138      byte[] obj = engines[jId].GetSnapshot();
139    }
140
141    #endregion
142
143    #region wcfService Events
144
145    void wcfService_LoginCompleted(object sender, LoginCompletedEventArgs e) {
146      if (e.Result.Success) {
147        Logging.GetInstance().Info(this.ToString(), "Login completed to Hive Server @ " + DateTime.Now);       
148      } else
149        Logging.GetInstance().Error(this.ToString(), e.Result.StatusMessage);
150    }   
151
152    void wcfService_PullJobCompleted(object sender, PullJobCompletedEventArgs e) {
153      if (e.Result.StatusMessage != ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOBS_LEFT) {
154        bool sandboxed = false;
155
156        PluginManager.Manager.Initialize();
157        AppDomain appDomain = PluginManager.Manager.CreateAndInitAppDomainWithSandbox(e.Result.Job.Id.ToString(), sandboxed, typeof(TestJob));
158        appDomain.UnhandledException += new UnhandledExceptionEventHandler(appDomain_UnhandledException);
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);
163
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);
169
170            ClientStatusInfo.JobsFetched++;
171
172            Debug.WriteLine("Increment FetchedJobs to:" + ClientStatusInfo.JobsFetched);
173          }
174        }
175      }
176    }
177
178    void wcfService_SendJobResultCompleted(object sender, SendJobResultCompletedEventArgs e) {
179      if (e.Result.Success) {
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        }
187        Debug.WriteLine("ProcessedJobs to:" + ClientStatusInfo.JobsProcessed);
188      } else {
189        Debug.WriteLine("Job sending FAILED!");
190      }
191    }
192
193    void wcfService_ServerChanged(object sender, EventArgs e) {
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) {
203      wcfService.LoginAsync(ConfigManager.Instance.GetClientInfo());
204    }
205
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    }
209
210    #endregion
211
212    public Dictionary<long, Executor> GetExecutionEngines() {
213      return engines;
214    }
215
216    void appDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
217      Logging.GetInstance().Error(this.ToString(), " Exception: " + e.ExceptionObject.ToString());
218    }
219  }
220}
Note: See TracBrowser for help on using the repository browser.