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
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;
39
40
41namespace HeuristicLab.Hive.Client.Core {
42  public class Core {
43
44    public delegate string GetASnapshotDelegate();
45
46    Dictionary<long, Executor> engines = new Dictionary<long, Executor>();
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
67    private ClientCommunicatorClient clientCommunicator;
68
69    public void Start() {
70      Heartbeat beat = new Heartbeat { Interval = 5000 };
71      beat.StartHeartbeat();
72
73      ClientInfo clientInfo = new ClientInfo { ClientId = Guid.NewGuid() };
74
75      clientCommunicator = ServiceLocator.GetClientCommunicator();
76      clientCommunicator.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(ClientCommunicator_LoginCompleted);
77      clientCommunicator.PullJobCompleted += new EventHandler<PullJobCompletedEventArgs>(ClientCommunicator_PullJobCompleted);
78      clientCommunicator.SendJobResultCompleted += new EventHandler<SendJobResultCompletedEventArgs>(ClientCommunicator_SendJobResultCompleted);
79      clientCommunicator.LoginAsync(clientInfo);
80
81      MessageQueue queue = MessageQueue.GetInstance();
82      while (true) {
83        MessageContainer container = queue.GetMessage();
84        Debug.WriteLine("Main loop received this message: " + container.Message.ToString());
85        Logging.GetInstance().Info(this.ToString(), container.Message.ToString());
86        DetermineAction(container);
87      }
88    }
89
90    void ClientCommunicator_LoginCompleted(object sender, LoginCompletedEventArgs e) {
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
99    private AppDomain CreateNewAppDomain(bool sandboxed) {
100      PermissionSet pset;
101      if (sandboxed) {
102        pset = new PermissionSet(PermissionState.None);
103        pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
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";
111      return System.AppDomain.CreateDomain("appD", AppDomain.CurrentDomain.Evidence, setup, pset, CreateStrongName(Assembly.GetExecutingAssembly()));
112
113    }
114
115    private void DetermineAction(MessageContainer container) {
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;
123
124        case MessageContainer.MessageType.RequestSnapshot:
125          engines[container.JobId].RequestSnapshot();
126          break;
127        case MessageContainer.MessageType.SnapshotReady:
128          Thread ssr = new Thread(new ParameterizedThreadStart(GetSnapshot));
129          ssr.Start(container.JobId);         
130          break;
131
132        case MessageContainer.MessageType.FetchJob:
133          clientCommunicator.PullJobAsync(Guid.NewGuid());
134          break;         
135        case MessageContainer.MessageType.FinishedJob:
136          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
137          finThread.Start(container.JobId);         
138          break;     
139      }
140    }
141
142    private void GetFinishedJob(object jobId) {
143      long jId = (long)jobId;
144      byte[] sJob = engines[jId].GetFinishedJob();
145     
146      JobResult jobResult = new JobResult { JobId = jId, Result = sJob, Client = null };
147      clientCommunicator.SendJobResultAsync(jobResult, true);
148
149      AppDomain.Unload(appDomains[jId]);
150      appDomains.Remove(jId);
151      engines.Remove(jId);
152      Status.CurrentJobs--;
153      Debug.WriteLine("Decrement CurrentJobs to:" + Status.CurrentJobs.ToString());       
154
155    }
156
157    private void GetSnapshot(object jobId) {
158      long jId = (long)jobId;
159      byte[] obj = engines[jId].GetSnapshot();
160    }
161
162    void ClientCommunicator_PullJobCompleted(object sender, PullJobCompletedEventArgs e) {
163      bool sandboxed = false;
164
165      //IJob job = new TestJob { JobId = e.Result.JobId };
166
167      PluginManager pm = PluginManager.Manager;
168      AppDomain appDomain =  pm.CreateAndInitAppDomain("AppDomain");
169
170      //AppDomain appDomain = CreateNewAppDomain(sandboxed);
171      appDomains.Add(e.Result.JobId, appDomain);
172
173      Executor engine = (Executor)appDomain.CreateInstanceAndUnwrap(typeof(Executor).Assembly.GetName().Name, typeof(Executor).FullName);
174      engine.JobId = e.Result.JobId;
175      engine.Queue = MessageQueue.GetInstance();
176      engine.Start(e.Result.SerializedJob);
177      engines.Add(e.Result.JobId, engine);
178
179      Status.CurrentJobs++;
180
181      Debug.WriteLine("Increment CurrentJobs to:"+Status.CurrentJobs.ToString());
182    }
183
184    void ClientCommunicator_SendJobResultCompleted(object sender, SendJobResultCompletedEventArgs e) {     
185      // TODO Removing of the Engines & AppDomains should happen here, not in the GetFinishedJob Method.
186    }
187  }
188}
Note: See TracBrowser for help on using the repository browser.