Free cookie consent management tool by TermsFeed Policy Generator

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

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

bugfix for #401

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