Free cookie consent management tool by TermsFeed Policy Generator

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

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

worked on #401

File size: 8.6 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 HeuristicLab.Hive.Client.Communication.Interfaces;
41using System.ServiceModel.Description;
42
43
44namespace HeuristicLab.Hive.Client.Core {
45  public class Core {
46
47    public delegate string GetASnapshotDelegate();
48
49    Dictionary<long, Executor> engines = new Dictionary<long, Executor>();
50    Dictionary<long, AppDomain> appDomains = new Dictionary<long, AppDomain>();
51
52    public static StrongName CreateStrongName(Assembly assembly) {
53      if (assembly == null)
54        throw new ArgumentNullException("assembly");
55
56      AssemblyName assemblyName = assembly.GetName();
57      Debug.Assert(assemblyName != null, "Could not get assembly name");
58
59      // get the public key blob
60      byte[] publicKey = assemblyName.GetPublicKey();
61      if (publicKey == null || publicKey.Length == 0)
62        throw new InvalidOperationException("Assembly is not strongly named");
63
64      StrongNamePublicKeyBlob keyBlob = new StrongNamePublicKeyBlob(publicKey);
65
66      // and create the StrongName
67      return new StrongName(keyBlob, assemblyName.Name, assemblyName.Version);
68    }
69
70    private ClientCommunicatorClient clientCommunicator;
71
72    public void Start() {
73       DiscoveryService discService =
74        new DiscoveryService();
75      IClientConsoleCommunicator[] clientCommunicatorInstances =
76        discService.GetInstances<IClientConsoleCommunicator>();
77
78      if (clientCommunicatorInstances.Length > 0) {
79        ServiceHost serviceHost =
80                new ServiceHost(clientCommunicatorInstances[0].GetType(),
81                  new Uri("http://localhost:9000/ClientConsole"));
82
83        System.ServiceModel.Channels.Binding binding =
84          new NetNamedPipeBinding();
85
86        serviceHost.AddServiceEndpoint(
87          typeof(IClientConsoleCommunicator),
88              binding,
89              "ClientConsoleCommunicator");
90
91        ServiceMetadataBehavior behavior =
92              new ServiceMetadataBehavior();
93        serviceHost.Description.Behaviors.Add(behavior);
94
95        serviceHost.AddServiceEndpoint(
96            typeof(IMetadataExchange),
97            MetadataExchangeBindings.CreateMexNamedPipeBinding(),
98            "mex");
99
100        serviceHost.Open();
101      }
102
103      clientCommunicator = ServiceLocator.GetClientCommunicator();
104      clientCommunicator.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(ClientCommunicator_LoginCompleted);
105      clientCommunicator.PullJobCompleted += new EventHandler<PullJobCompletedEventArgs>(ClientCommunicator_PullJobCompleted);
106      clientCommunicator.SendJobResultCompleted += new EventHandler<SendJobResultCompletedEventArgs>(ClientCommunicator_SendJobResultCompleted);
107      clientCommunicator.LoginAsync(ConfigurationManager.GetInstance().GetClientInfo());
108
109      Heartbeat beat = new Heartbeat { Interval = 5000 };
110      beat.StartHeartbeat();     
111
112      MessageQueue queue = MessageQueue.GetInstance();
113      while (true) {
114        MessageContainer container = queue.GetMessage();
115        Debug.WriteLine("Main loop received this message: " + container.Message.ToString());
116        Logging.GetInstance().Info(this.ToString(), container.Message.ToString());
117        DetermineAction(container);
118      }
119    }
120
121    void ClientCommunicator_LoginCompleted(object sender, LoginCompletedEventArgs e) {
122      if (e.Result.Success) {
123        Logging.GetInstance().Info(this.ToString(), "Login completed to Hive Server @ " + DateTime.Now);
124        ConfigurationManager.GetInstance().Loggedin();
125        Status.LoginTime = DateTime.Now;
126        Status.LoggedIn = true;
127      } else
128        Logging.GetInstance().Error(this.ToString(), e.Result.StatusMessage);
129    }
130
131    private AppDomain CreateNewAppDomain(bool sandboxed) {
132      PermissionSet pset;
133      if (sandboxed) {
134        pset = new PermissionSet(PermissionState.None);
135        pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
136      } else {
137        pset = new PermissionSet(PermissionState.Unrestricted);
138      }
139      AppDomainSetup setup = new AppDomainSetup();
140      setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
141      //Temp Fix!
142      setup.PrivateBinPath = "plugins";
143      return System.AppDomain.CreateDomain("appD", AppDomain.CurrentDomain.Evidence, setup, pset, CreateStrongName(Assembly.GetExecutingAssembly()));
144
145    }
146
147    private void DetermineAction(MessageContainer container) {
148      switch (container.Message) {
149        case MessageContainer.MessageType.AbortJob:
150          engines[container.JobId].Abort();
151          break;
152        case MessageContainer.MessageType.JobAborted:
153          Debug.WriteLine("-- Job Aborted Message received");
154          break;
155
156        case MessageContainer.MessageType.RequestSnapshot:
157          engines[container.JobId].RequestSnapshot();
158          break;
159        case MessageContainer.MessageType.SnapshotReady:
160          Thread ssr = new Thread(new ParameterizedThreadStart(GetSnapshot));
161          ssr.Start(container.JobId);         
162          break;
163
164        case MessageContainer.MessageType.FetchJob:
165          clientCommunicator.PullJobAsync(Guid.NewGuid());
166          break;         
167        case MessageContainer.MessageType.FinishedJob:
168          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
169          finThread.Start(container.JobId);         
170          break;     
171      }
172    }
173
174    private void GetFinishedJob(object jobId) {
175      long jId = (long)jobId;
176      byte[] sJob = engines[jId].GetFinishedJob();
177     
178      JobResult jobResult = new JobResult { JobId = jId, Result = sJob, Client = ConfigurationManager.GetInstance().GetClientInfo() };
179      clientCommunicator.SendJobResultAsync(jobResult, true);
180    }
181
182    private void GetSnapshot(object jobId) {
183      long jId = (long)jobId;
184      byte[] obj = engines[jId].GetSnapshot();
185    }
186
187    void ClientCommunicator_PullJobCompleted(object sender, PullJobCompletedEventArgs e) {
188      bool sandboxed = false;
189
190      //IJob job = new TestJob { JobId = e.Result.JobId };
191
192      PluginManager pm = PluginManager.Manager;
193      AppDomain appDomain =  pm.CreateAndInitAppDomain("AppDomain");
194
195      //AppDomain appDomain = CreateNewAppDomain(sandboxed);
196      appDomains.Add(e.Result.JobId, appDomain);
197
198      Executor engine = (Executor)appDomain.CreateInstanceAndUnwrap(typeof(Executor).Assembly.GetName().Name, typeof(Executor).FullName);
199      engine.JobId = e.Result.JobId;
200      engine.Queue = MessageQueue.GetInstance();
201      engine.Start(e.Result.SerializedJob);
202      engines.Add(e.Result.JobId, engine);
203
204      Status.CurrentJobs++;
205
206      Debug.WriteLine("Increment CurrentJobs to:"+Status.CurrentJobs.ToString());
207    }
208
209    void ClientCommunicator_SendJobResultCompleted(object sender, SendJobResultCompletedEventArgs e) {
210      if (e.Result.Success) {
211        AppDomain.Unload(appDomains[e.Result.JobId]);
212        appDomains.Remove(e.Result.JobId);
213        engines.Remove(e.Result.JobId);
214        Status.CurrentJobs--;
215        Debug.WriteLine("Decrement CurrentJobs to:" + Status.CurrentJobs.ToString());
216      } else {
217        Debug.WriteLine("Job sending FAILED!");
218      }
219    }
220  }
221}
Note: See TracBrowser for help on using the repository browser.