Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5786 was 5786, checked in by cneumuel, 13 years ago

#1233

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