Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive.Slave/3.4/Core.cs @ 5826

Last change on this file since 5826 was 5826, checked in by ascheibe, 13 years ago

#1233 slave ui now receives status information and displays it in doughnut chart

File size: 20.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Diagnostics;
25using System.IO;
26using System.ServiceModel;
27using System.Threading;
28using System.Threading.Tasks;
29using HeuristicLab.Clients.Hive.SlaveCore.ServiceContracts;
30using HeuristicLab.Common;
31using HeuristicLab.Core;
32
33
34namespace HeuristicLab.Clients.Hive.SlaveCore {
35  /// <summary>
36  /// The core component of the Hive Slave.
37  /// Handles commands sent from the Hive Server.
38  /// </summary>
39  public class Core : MarshalByRefObject {
40    public EventLog ServiceEventLog { get; set; }
41
42    public static bool abortRequested { get; set; }
43    private Semaphore waitShutdownSem = new Semaphore(0, 1);
44    public static ILog Log { get; set; }
45
46    private Dictionary<Guid, Executor> engines = new Dictionary<Guid, Executor>();
47    private Dictionary<Guid, AppDomain> appDomains = new Dictionary<Guid, AppDomain>();
48    private Dictionary<Guid, Job> jobs = new Dictionary<Guid, Job>();
49
50    private WcfService wcfService;
51    private HeartbeatManager heartbeatManager;
52    private int coreThreadId;
53
54    private ISlaveCommunication clientCom;
55    private ServiceHost slaveComm;
56
57    public Dictionary<Guid, Executor> ExecutionEngines {
58      get { return engines; }
59    }
60
61    internal Dictionary<Guid, Job> Jobs {
62      get { return jobs; }
63    }
64
65    public Core() { }
66
67    /// <summary>
68    /// Main Method for the client
69    /// </summary>
70    public void Start() {
71      coreThreadId = Thread.CurrentThread.ManagedThreadId;
72      abortRequested = false;
73
74      try {
75        ConfigManager manager = ConfigManager.Instance;
76        manager.Core = this;
77
78        //start the client communication service (pipe between slave and slave gui)
79        slaveComm = new ServiceHost(typeof(SlaveCommunicationService));
80        slaveComm.Open();
81
82        clientCom = SlaveClientCom.Instance.ClientCom;
83        clientCom.LogMessage("Hive Slave started");
84
85        wcfService = WcfService.Instance;
86        RegisterServiceEvents();
87
88        StartHeartbeats(); // Start heartbeats thread       
89        DispatchMessageQueue(); // dispatch messages until abortRequested
90      }
91      catch (Exception ex) {
92        if (ServiceEventLog != null) {
93          try {
94            ServiceEventLog.WriteEntry("Hive Slave threw exception: " + ex.ToString() + " with stack trace: " + ex.StackTrace);
95          }
96          catch (Exception) { }
97        } else {
98          throw ex;
99        }
100      }
101      finally {
102        DeRegisterServiceEvents();
103        waitShutdownSem.Release();
104      }
105    }
106
107    private void StartHeartbeats() {
108      //Initialize the heartbeat     
109      if (heartbeatManager == null) {
110        heartbeatManager = new HeartbeatManager { Interval = new TimeSpan(0, 0, 10) };
111        heartbeatManager.StartHeartbeat();
112      }
113    }
114
115    private void DispatchMessageQueue() {
116      MessageQueue queue = MessageQueue.GetInstance();
117      while (!abortRequested) {
118        MessageContainer container = queue.GetMessage();
119        DetermineAction(container);
120        clientCom.StatusChanged(ConfigManager.Instance.GetStatusForClientConsole());
121      }
122    }
123
124    private void RegisterServiceEvents() {
125      WcfService.Instance.Connected += new EventHandler(WcfService_Connected);
126      WcfService.Instance.ExceptionOccured += new EventHandler<EventArgs<Exception>>(WcfService_ExceptionOccured);
127    }
128
129    private void DeRegisterServiceEvents() {
130      WcfService.Instance.Connected -= WcfService_Connected;
131      WcfService.Instance.ExceptionOccured -= WcfService_ExceptionOccured;
132    }
133
134    void WcfService_ExceptionOccured(object sender, EventArgs<Exception> e) {
135      clientCom.LogMessage("Connection to server interruped with exception: " + e.Value.Message);
136    }
137
138    void WcfService_Connected(object sender, EventArgs e) {
139      clientCom.LogMessage("Connected successfully to Hive server");
140    }
141
142    /// <summary>
143    /// Reads and analyzes the Messages from the MessageQueue and starts corresponding actions
144    /// </summary>
145    /// <param name="container">The container, containing the message</param>
146    private void DetermineAction(MessageContainer container) {
147      clientCom.LogMessage("Message: " + container.Message.ToString() + " for job: " + container.JobId);
148
149      if (container is ExecutorMessageContainer<Guid>) {
150        ExecutorMessageContainer<Guid> c = (ExecutorMessageContainer<Guid>)container;
151        c.execute();
152      } else if (container is MessageContainer) {
153        switch (container.Message) {
154          case MessageContainer.MessageType.CalculateJob:
155            Task.Factory.StartNew((jobIdObj) => {
156              Guid jobId = (Guid)jobIdObj;
157              Job job = wcfService.GetJob(jobId);
158              if (job == null) throw new JobNotFoundException(jobId);
159              lock (engines) {
160                if (!jobs.ContainsKey(job.Id)) {
161                  jobs.Add(job.Id, job);
162                }
163              }
164              JobData jobData = wcfService.GetJobData(job.Id);
165              if (jobData == null) throw new JobDataNotFoundException(jobId);
166              SlaveStatusInfo.JobsFetched++;
167              job = wcfService.UpdateJobState(job.Id, JobState.Calculating, null);
168              StartJobInAppDomain(job, jobData);
169            }, container.JobId)
170            .ContinueWith((t) => {
171              // handle exception of task
172              clientCom.LogMessage(t.Exception.ToString());
173            }, TaskContinuationOptions.OnlyOnFaulted);
174            break;
175          case MessageContainer.MessageType.ShutdownSlave:
176            ShutdownCore();
177            break;
178          case MessageContainer.MessageType.StopAll:
179            DoStopAll();
180            break;
181          case MessageContainer.MessageType.PauseAll:
182            DoPauseAll();
183            break;
184          case MessageContainer.MessageType.AbortAll:
185            DoAbortAll();
186            break;
187          case MessageContainer.MessageType.AbortJob:
188            KillAppDomain(container.JobId);
189            break;
190          case MessageContainer.MessageType.StopJob:
191            DoStopJob(container.JobId);
192            break;
193          case MessageContainer.MessageType.PauseJob:
194            DoPauseJob(container.JobId);
195            break;
196          case MessageContainer.MessageType.Restart:
197            DoStartSlave();
198            break;
199          case MessageContainer.MessageType.Sleep:
200            Sleep();
201            break;
202          case MessageContainer.MessageType.SayHello:
203            wcfService.Connect(ConfigManager.Instance.GetClientInfo());
204            break;
205        }
206      } else {
207        clientCom.LogMessage("Unknown MessageContainer: " + container);
208      }
209    }
210
211    private void DoPauseJob(Guid jobId) {
212      if (!Jobs.ContainsKey(jobId)) {
213        clientCom.LogMessage("DoPauseJob: Can't find job with id " + jobId);
214      } else {
215        Job job = Jobs[jobId];
216
217        if (job != null) {
218          engines[job.Id].Pause();
219          JobData sJob = engines[job.Id].GetPausedJob();
220          job.ExecutionTime = engines[job.Id].ExecutionTime;
221
222          try {
223            clientCom.LogMessage("Sending the paused job with id: " + job.Id);
224            wcfService.UpdateJobData(job, sJob, ConfigManager.Instance.GetClientInfo().Id, JobState.Paused);
225          }
226          catch (Exception e) {
227            clientCom.LogMessage("Transmitting to server failed. Storing the paused job with id: " + job.Id + " to hdd (" + e.ToString() + ")");
228          }
229          finally {
230            KillAppDomain(job.Id); // kill app-domain in every case         
231          }
232        }
233      }
234    }
235
236    private void DoStopJob(Guid jobId) {
237      if (!Jobs.ContainsKey(jobId)) {
238        clientCom.LogMessage("DoStopJob: Can't find job with id " + jobId);
239      } else {
240        Job job = Jobs[jobId];
241
242        if (job != null) {
243          engines[job.Id].Stop();
244          JobData sJob = engines[job.Id].GetFinishedJob();
245          job.ExecutionTime = engines[job.Id].ExecutionTime;
246
247          try {
248            clientCom.LogMessage("Sending the stoppped job with id: " + job.Id);
249            wcfService.UpdateJobData(job, sJob, ConfigManager.Instance.GetClientInfo().Id, JobState.Finished);
250          }
251          catch (Exception e) {
252            clientCom.LogMessage("Transmitting to server failed. Storing the paused job with id: " + job.Id + " to hdd (" + e.ToString() + ")");
253          }
254          finally {
255            KillAppDomain(job.Id); // kill app-domain in every case         
256          }
257        }
258      }
259    }
260
261    /// <summary>
262    /// aborts all running jobs, no results are sent back
263    /// </summary>
264    private void DoAbortAll() {
265      List<Guid> guids = new List<Guid>();
266      foreach (Guid job in Jobs.Keys) {
267        guids.Add(job);
268      }
269
270      foreach (Guid g in guids) {
271        KillAppDomain(g);
272      }
273
274      clientCom.LogMessage("Aborted all jobs!");
275    }
276
277    /// <summary>
278    /// wait for jobs to finish, then pause client
279    /// </summary>
280    private void DoPauseAll() {
281      clientCom.LogMessage("Pause all received");
282
283      //copy guids because there will be removed items from 'Jobs'
284      List<Guid> guids = new List<Guid>();
285      foreach (Guid job in Jobs.Keys) {
286        guids.Add(job);
287      }
288
289      foreach (Guid g in guids) {
290        DoPauseJob(g);
291      }
292    }
293
294    /// <summary>
295    /// pause slave immediately
296    /// </summary>
297    private void DoStopAll() {
298      clientCom.LogMessage("Stop all received");
299
300      //copy guids because there will be removed items from 'Jobs'
301      List<Guid> guids = new List<Guid>();
302      foreach (Guid job in Jobs.Keys) {
303        guids.Add(job);
304      }
305
306      foreach (Guid g in guids) {
307        DoStopJob(g);
308      }
309    }
310
311    /// <summary>
312    /// completly shudown slave
313    /// </summary>
314    public void Shutdown() {
315      MessageContainer mc = new MessageContainer(MessageContainer.MessageType.ShutdownSlave);
316      MessageQueue.GetInstance().AddMessage(mc);
317      waitShutdownSem.WaitOne();
318    }
319
320    /// <summary>
321    /// complete shutdown, should be called before the the application is exited
322    /// </summary>
323    private void ShutdownCore() {
324      clientCom.LogMessage("Shutdown Signal received");
325      clientCom.LogMessage("Stopping heartbeat");
326      heartbeatManager.StopHeartBeat();
327      abortRequested = true;
328      clientCom.LogMessage("Logging out");
329
330
331      lock (engines) {
332        clientCom.LogMessage("engines locked");
333        foreach (KeyValuePair<Guid, AppDomain> kvp in appDomains) {
334          clientCom.LogMessage("Shutting down Appdomain for " + kvp.Key);
335          appDomains[kvp.Key].UnhandledException -= new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
336          AppDomain.Unload(kvp.Value);
337        }
338      }
339      WcfService.Instance.Disconnect();
340      clientCom.Shutdown();
341      SlaveClientCom.Close();
342
343      if (slaveComm.State != CommunicationState.Closed)
344        slaveComm.Close();
345    }
346
347    /// <summary>
348    /// reinitializes everything and continues operation,
349    /// can be called after Sleep()
350    /// </summary> 
351    private void DoStartSlave() {
352      clientCom.LogMessage("Restart received");
353      StartHeartbeats();
354      clientCom.LogMessage("Restart done");
355    }
356
357    /// <summary>
358    /// stop slave, except for client gui communication,
359    /// primarily used by gui if core is running as windows service
360    /// </summary>   
361    private void Sleep() {
362      clientCom.LogMessage("Sleep received");
363      heartbeatManager.StopHeartBeat();
364      heartbeatManager = null;
365      DoStopAll();
366      WcfService.Instance.Disconnect();
367      clientCom.LogMessage("Sleep done");
368    }
369
370    /// <summary>
371    /// Pauses a job, which means sending it to the server and killing it locally;
372    /// atm only used when executor is waiting for child jobs
373    /// </summary>
374    public void PauseWaitJob(JobData data) {
375      if (!Jobs.ContainsKey(data.JobId)) {
376        clientCom.LogMessage("Can't find job with id " + data.JobId);
377      } else {
378        Job job = Jobs[data.JobId];
379        wcfService.UpdateJobData(job, data, ConfigManager.Instance.GetClientInfo().Id, JobState.Paused);
380        wcfService.UpdateJobState(job.Id, JobState.Waiting, null);
381      }
382      KillAppDomain(data.JobId);
383    }
384
385    /// <summary>
386    /// serializes the finished job and submits it to the server. If, at the time, a network connection is unavailable, the Job gets stored on the disk.
387    /// once the connection gets reestablished, the job gets submitted
388    /// </summary>
389    public void SendFinishedJob(Guid jobId) {
390      try {
391        clientCom.LogMessage("Getting the finished job with id: " + jobId);
392        if (!engines.ContainsKey(jobId)) {
393          clientCom.LogMessage("Engine doesn't exist");
394          return;
395        }
396        if (!jobs.ContainsKey(jobId)) {
397          clientCom.LogMessage("Job doesn't exist");
398          return;
399        }
400        Job cJob = jobs[jobId];
401        cJob.ExecutionTime = engines[jobId].ExecutionTime;
402
403        if (engines[jobId].Aborted) {
404          SlaveStatusInfo.JobsAborted++;
405        } else {
406          SlaveStatusInfo.JobsProcessed++;
407        }
408
409        if (engines[jobId].CurrentException != string.Empty) {
410          wcfService.UpdateJobState(jobId, JobState.Failed, engines[jobId].CurrentException);
411        }
412
413        JobData sJob = engines[jobId].GetFinishedJob();
414        try {
415          clientCom.LogMessage("Sending the finished job with id: " + jobId);
416          wcfService.UpdateJobData(cJob, sJob, ConfigManager.Instance.GetClientInfo().Id, JobState.Finished);
417        }
418        catch (Exception e) {
419          clientCom.LogMessage("Transmitting to server failed. Storing the finished job with id: " + jobId + " to hdd (" + e.ToString() + ")");
420        }
421        finally {
422          KillAppDomain(jobId);
423          heartbeatManager.AwakeHeartBeatThread();
424        }
425      }
426      catch (Exception e) {
427        OnExceptionOccured(e);
428      }
429    }
430
431    /// <summary>
432    /// A new Job from the wcfService has been received and will be started within a AppDomain.
433    /// </summary>   
434    private void StartJobInAppDomain(Job myJob, JobData jobData) {
435      clientCom.LogMessage("Received new job with id " + myJob.Id);
436      clientCom.StatusChanged(ConfigManager.Instance.GetStatusForClientConsole());
437      if (engines.ContainsKey(myJob.Id))
438        throw new Exception("Job with key " + myJob.Id + " already exists");
439
440      String pluginDir = Path.Combine(PluginCache.Instance.PluginTempBaseDir, myJob.Id.ToString());
441      bool pluginsPrepared = false;
442      string configFileName = string.Empty;
443
444      try {
445        PluginCache.Instance.PreparePlugins(myJob, out configFileName);
446        clientCom.LogMessage("Plugins fetched for job " + myJob.Id);
447        pluginsPrepared = true;
448      }
449      catch (Exception exception) {
450        clientCom.LogMessage(string.Format("Copying plugins for job {0} failed: {1}", myJob.Id, exception));
451      }
452
453      if (pluginsPrepared) {
454        try {
455          AppDomain appDomain = HeuristicLab.PluginInfrastructure.Sandboxing.SandboxManager.CreateAndInitSandbox(myJob.Id.ToString(), pluginDir, Path.Combine(pluginDir, configFileName));
456          appDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
457          lock (engines) {
458            appDomains.Add(myJob.Id, appDomain);
459            clientCom.LogMessage("Creating AppDomain");
460            Executor engine = (Executor)appDomain.CreateInstanceAndUnwrap(typeof(Executor).Assembly.GetName().Name, typeof(Executor).FullName);
461            clientCom.LogMessage("Created AppDomain");
462            engine.JobId = myJob.Id;
463            engine.Core = this;
464            clientCom.LogMessage("Starting Engine for job " + myJob.Id);
465            engines.Add(myJob.Id, engine);
466            engine.Start(jobData.Data);
467          }
468        }
469        catch (Exception exception) {
470          clientCom.LogMessage("Creating the Appdomain and loading the job failed for job " + myJob.Id);
471          clientCom.LogMessage("Error thrown is: " + exception.ToString());
472          KillAppDomain(myJob.Id);
473        }
474      }
475      heartbeatManager.AwakeHeartBeatThread();
476    }
477
478    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
479    private void OnExceptionOccured(Exception e) {
480      clientCom.LogMessage("Error: " + e.ToString());
481      var handler = ExceptionOccured;
482      if (handler != null) handler(this, new EventArgs<Exception>(e));
483    }
484
485    private void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
486      clientCom.LogMessage("Exception in AppDomain: " + e.ExceptionObject.ToString());
487      KillAppDomain(new Guid(e.ExceptionObject.ToString()));
488    }
489
490    /// <summary>
491    /// Enqueues messages from the executor to the message queue.
492    /// This is necessary if the core thread has to execute certain actions, e.g.
493    /// killing of an app domain.
494    /// </summary>   
495    /// <returns>true if the calling method can continue execution, else false</returns>
496    public void EnqueueExecutorMessage<T>(Action<T> action, T parameter) {
497      ExecutorMessageContainer<T> container = new ExecutorMessageContainer<T>();
498      container.Callback = action;
499      container.CallbackParameter = parameter;
500      MessageQueue.GetInstance().AddMessage(container);
501    }
502
503    /// <summary>
504    /// Kill a appdomain with a specific id.
505    /// </summary>
506    /// <param name="id">the GUID of the job</param>   
507    public void KillAppDomain(Guid id) {
508      if (Thread.CurrentThread.ManagedThreadId != this.coreThreadId) {
509        EnqueueExecutorMessage<Guid>(KillAppDomain, id);
510        return;
511      }
512
513      clientCom.LogMessage("Shutting down Appdomain for Job " + id);
514      lock (engines) {
515        try {
516          if (engines.ContainsKey(id)) {
517            engines[id].Dispose();
518            engines.Remove(id);
519          }
520
521          if (appDomains.ContainsKey(id)) {
522            appDomains[id].UnhandledException -= new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
523
524            int repeat = 5;
525            while (repeat > 0) {
526              try {
527                AppDomain.Unload(appDomains[id]);
528                repeat = 0;
529              }
530              catch (CannotUnloadAppDomainException) {
531                clientCom.LogMessage("Could not unload AppDomain, will try again in 1 sec.");
532                Thread.Sleep(1000);
533                repeat--;
534                if (repeat == 0) {
535                  throw; // rethrow and let app crash
536                }
537              }
538            }
539            appDomains.Remove(id);
540          }
541
542          jobs.Remove(id);
543          PluginCache.Instance.DeletePluginsForJob(id);
544          GC.Collect();
545        }
546        catch (Exception ex) {
547          clientCom.LogMessage("Exception when unloading the appdomain: " + ex.ToString());
548        }
549      }
550      GC.Collect();
551      clientCom.StatusChanged(ConfigManager.Instance.GetStatusForClientConsole());
552    }
553  }
554}
Note: See TracBrowser for help on using the repository browser.