Free cookie consent management tool by TermsFeed Policy Generator

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

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

continued work from #390, removed a fake CreateJob method and replaced all fake Jobs with real ones.

File size: 7.3 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;
[714]39
[768]40
[714]41namespace HeuristicLab.Hive.Client.Core {
42  public class Core {
[768]43
[804]44    public delegate string GetASnapshotDelegate();
45
[768]46    Dictionary<long, Executor> engines = new Dictionary<long, Executor>();
[770]47    Dictionary<long, AppDomain> appDomains = new Dictionary<long, AppDomain>();
48
49    public static StrongName CreateStrongName(Assembly assembly) {
50      if (assembly == null)
51        throw new ArgumentNullException("assembly");
52
53      AssemblyName assemblyName = assembly.GetName();
54      Debug.Assert(assemblyName != null, "Could not get assembly name");
55
56      // get the public key blob
57      byte[] publicKey = assemblyName.GetPublicKey();
58      if (publicKey == null || publicKey.Length == 0)
59        throw new InvalidOperationException("Assembly is not strongly named");
60
61      StrongNamePublicKeyBlob keyBlob = new StrongNamePublicKeyBlob(publicKey);
62
63      // and create the StrongName
64      return new StrongName(keyBlob, assemblyName.Name, assemblyName.Version);
65    }
66
[798]67    private ClientCommunicatorClient clientCommunicator;
68
[790]69    public void Start() {
[811]70      Heartbeat beat = new Heartbeat { Interval = 5000 };
[790]71      beat.StartHeartbeat();
[768]72
[793]73      ClientInfo clientInfo = new ClientInfo { ClientId = Guid.NewGuid() };
[790]74
[798]75      clientCommunicator = ServiceLocator.GetClientCommunicator();
[790]76      clientCommunicator.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(ClientCommunicator_LoginCompleted);
[808]77      clientCommunicator.PullJobCompleted += new EventHandler<PullJobCompletedEventArgs>(ClientCommunicator_PullJobCompleted);
[830]78      clientCommunicator.SendJobResultCompleted += new EventHandler<SendJobResultCompletedEventArgs>(ClientCommunicator_SendJobResultCompleted);
[790]79      clientCommunicator.LoginAsync(clientInfo);
80
[735]81      MessageQueue queue = MessageQueue.GetInstance();
82      while (true) {
83        MessageContainer container = queue.GetMessage();
[779]84        Debug.WriteLine("Main loop received this message: " + container.Message.ToString());
[790]85        Logging.GetInstance().Info(this.ToString(), container.Message.ToString());
[768]86        DetermineAction(container);
[735]87      }
88    }
[768]89
[798]90    void ClientCommunicator_LoginCompleted(object sender, LoginCompletedEventArgs e) {
[790]91      if (e.Result.Success) {
92        Logging.GetInstance().Info(this.ToString(), "Login completed to Hive Server @ " + DateTime.Now);
93        Status.LoginTime = DateTime.Now;
94        Status.LoggedIn = true;
95      } else
96        Logging.GetInstance().Error(this.ToString(), e.Result.StatusMessage);
97    }
98
[770]99    private AppDomain CreateNewAppDomain(bool sandboxed) {
100      PermissionSet pset;
101      if (sandboxed) {
102        pset = new PermissionSet(PermissionState.None);
[790]103        pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
[770]104      } else {
105        pset = new PermissionSet(PermissionState.Unrestricted);
106      }
107      AppDomainSetup setup = new AppDomainSetup();
108      setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
109      //Temp Fix!
110      setup.PrivateBinPath = "plugins";
[790]111      return System.AppDomain.CreateDomain("appD", AppDomain.CurrentDomain.Evidence, setup, pset, CreateStrongName(Assembly.GetExecutingAssembly()));
[770]112
113    }
114
[768]115    private void DetermineAction(MessageContainer container) {
[779]116      switch (container.Message) {
117        case MessageContainer.MessageType.AbortJob:
118          engines[container.JobId].Abort();
119          break;
120        case MessageContainer.MessageType.JobAborted:
121          Debug.WriteLine("-- Job Aborted Message received");
122          break;
[790]123
[779]124        case MessageContainer.MessageType.RequestSnapshot:
125          engines[container.JobId].RequestSnapshot();
126          break;
127        case MessageContainer.MessageType.SnapshotReady:
[811]128          Thread ssr = new Thread(new ParameterizedThreadStart(GetSnapshot));
129          ssr.Start(container.JobId);         
[779]130          break;
[790]131
[811]132        case MessageContainer.MessageType.FetchJob:
[798]133          clientCommunicator.PullJobAsync(Guid.NewGuid());
[811]134          break;         
[779]135        case MessageContainer.MessageType.FinishedJob:
[811]136          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
137          finThread.Start(container.JobId);         
138          break;     
[779]139      }
140    }
[790]141
[811]142    private void GetFinishedJob(object jobId) {
143      long jId = (long)jobId;
[830]144      byte[] sJob = engines[jId].GetFinishedJob();
[816]145     
[830]146      JobResult jobResult = new JobResult { JobId = jId, Result = sJob, Client = null };
147      clientCommunicator.SendJobResultAsync(jobResult, true);
148
[811]149      AppDomain.Unload(appDomains[jId]);
150      appDomains.Remove(jId);
151      engines.Remove(jId);
[830]152      Status.CurrentJobs--;
153      Debug.WriteLine("Decrement CurrentJobs to:" + Status.CurrentJobs.ToString());       
[811]154
[804]155    }
156
[811]157    private void GetSnapshot(object jobId) {
158      long jId = (long)jobId;
[816]159      byte[] obj = engines[jId].GetSnapshot();
[811]160    }
161
[798]162    void ClientCommunicator_PullJobCompleted(object sender, PullJobCompletedEventArgs e) {
163      bool sandboxed = false;
164
[830]165      //IJob job = new TestJob { JobId = e.Result.JobId };
[798]166
[816]167      PluginManager pm = PluginManager.Manager;
168      AppDomain appDomain =  pm.CreateAndInitAppDomain("AppDomain");
169
170      //AppDomain appDomain = CreateNewAppDomain(sandboxed);
[830]171      appDomains.Add(e.Result.JobId, appDomain);
[798]172
173      Executor engine = (Executor)appDomain.CreateInstanceAndUnwrap(typeof(Executor).Assembly.GetName().Name, typeof(Executor).FullName);
[830]174      engine.JobId = e.Result.JobId;
[798]175      engine.Queue = MessageQueue.GetInstance();
[830]176      engine.Start(e.Result.SerializedJob);
177      engines.Add(e.Result.JobId, engine);
[798]178
179      Status.CurrentJobs++;
180
181      Debug.WriteLine("Increment CurrentJobs to:"+Status.CurrentJobs.ToString());
182    }
183
[830]184    void ClientCommunicator_SendJobResultCompleted(object sender, SendJobResultCompletedEventArgs e) {     
185      // TODO Removing of the Engines & AppDomains should happen here, not in the GetFinishedJob Method.
[779]186    }
[714]187  }
188}
Note: See TracBrowser for help on using the repository browser.