Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CloningRefactorBranch/HeuristicLab.Hive.Client.Core/Core.cs @ 848

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

fixed the problem with (#385)

File size: 7.0 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;
38
39
40namespace HeuristicLab.Hive.Client.Core {
41  public class Core {
42
43    public delegate string GetASnapshotDelegate();
44
45    Dictionary<long, Executor> engines = new Dictionary<long, Executor>();
46    Dictionary<long, AppDomain> appDomains = new Dictionary<long, AppDomain>();
47
48    public static StrongName CreateStrongName(Assembly assembly) {
49      if (assembly == null)
50        throw new ArgumentNullException("assembly");
51
52      AssemblyName assemblyName = assembly.GetName();
53      Debug.Assert(assemblyName != null, "Could not get assembly name");
54
55      // get the public key blob
56      byte[] publicKey = assemblyName.GetPublicKey();
57      if (publicKey == null || publicKey.Length == 0)
58        throw new InvalidOperationException("Assembly is not strongly named");
59
60      StrongNamePublicKeyBlob keyBlob = new StrongNamePublicKeyBlob(publicKey);
61
62      // and create the StrongName
63      return new StrongName(keyBlob, assemblyName.Name, assemblyName.Version);
64    }
65
66    private ClientCommunicatorClient clientCommunicator;
67
68    public void Start() {
69      Heartbeat beat = new Heartbeat { Interval = 30000 };
70      beat.StartHeartbeat();
71
72      ClientInfo clientInfo = new ClientInfo { ClientId = Guid.NewGuid() };
73
74      clientCommunicator = ServiceLocator.GetClientCommunicator();
75      clientCommunicator.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(ClientCommunicator_LoginCompleted);
76      clientCommunicator.PullJobCompleted += new EventHandler<PullJobCompletedEventArgs>(ClientCommunicator_PullJobCompleted);
77      clientCommunicator.LoginAsync(clientInfo);
78
79      MessageQueue queue = MessageQueue.GetInstance();
80      while (true) {
81        MessageContainer container = queue.GetMessage();
82        Debug.WriteLine("Main loop received this message: " + container.Message.ToString());
83        Logging.GetInstance().Info(this.ToString(), container.Message.ToString());
84        DetermineAction(container);
85      }
86    }
87
88    void ClientCommunicator_LoginCompleted(object sender, LoginCompletedEventArgs e) {
89      if (e.Result.Success) {
90        Logging.GetInstance().Info(this.ToString(), "Login completed to Hive Server @ " + DateTime.Now);
91        Status.LoginTime = DateTime.Now;
92        Status.LoggedIn = true;
93      } else
94        Logging.GetInstance().Error(this.ToString(), e.Result.StatusMessage);
95    }
96
97    private AppDomain CreateNewAppDomain(bool sandboxed) {
98      PermissionSet pset;
99      if (sandboxed) {
100        pset = new PermissionSet(PermissionState.None);
101        pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
102      } else {
103        pset = new PermissionSet(PermissionState.Unrestricted);
104      }
105      AppDomainSetup setup = new AppDomainSetup();
106      setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
107      //Temp Fix!
108      setup.PrivateBinPath = "plugins";
109      return System.AppDomain.CreateDomain("appD", AppDomain.CurrentDomain.Evidence, setup, pset, CreateStrongName(Assembly.GetExecutingAssembly()));
110
111    }
112
113    private void DetermineAction(MessageContainer container) {
114      switch (container.Message) {
115        case MessageContainer.MessageType.AbortJob:
116          engines[container.JobId].Abort();
117          break;
118        case MessageContainer.MessageType.JobAborted:
119          Debug.WriteLine("-- Job Aborted Message received");
120          break;
121
122        case MessageContainer.MessageType.RequestSnapshot:
123          engines[container.JobId].RequestSnapshot();
124          break;
125        case MessageContainer.MessageType.SnapshotReady:
126          //Grabbing of the snapshot will need some time, so let's make this functun async
127          GetASnapshotDelegate ssd = new GetASnapshotDelegate(engines[container.JobId].GetSnapshot);
128          ssd.BeginInvoke(new AsyncCallback(SnapshotReceived), null);
129          //engines[container.JobId].GetSnapshot();
130          break;
131
132
133        case MessageContainer.MessageType.FetchJob:         
134          clientCommunicator.PullJobAsync(Guid.NewGuid());
135          break;
136
137        case MessageContainer.MessageType.FinishedJob:
138          engines[container.JobId].GetFinishedJob();
139          AppDomain.Unload(appDomains[container.JobId]);
140          appDomains.Remove(container.JobId);
141          engines.Remove(container.JobId);
142          Status.CurrentJobs--;
143          Debug.WriteLine("Decrement CurrentJobs to:"+Status.CurrentJobs.ToString());
144          break;
145      }
146    }
147
148    void SnapshotReceived(IAsyncResult res) {
149      AsyncResult ar = (AsyncResult) res;
150      GetASnapshotDelegate gss = (GetASnapshotDelegate) ar.AsyncDelegate;
151      String objectRepr = gss.EndInvoke(res);
152    }
153
154    void ClientCommunicator_PullJobCompleted(object sender, PullJobCompletedEventArgs e) {
155      bool sandboxed = false;
156
157      IJob job = new TestJob { JobId = e.Result.JobId };
158
159      AppDomain appDomain = CreateNewAppDomain(sandboxed);
160      appDomains.Add(job.JobId, appDomain);
161
162      Executor engine = (Executor)appDomain.CreateInstanceAndUnwrap(typeof(Executor).Assembly.GetName().Name, typeof(Executor).FullName);
163      engine.Job = job;
164      engine.JobId = job.JobId;
165      engine.Queue = MessageQueue.GetInstance();
166      engine.Start();
167      engines.Add(engine.JobId, engine);
168
169      Status.CurrentJobs++;
170
171      Debug.WriteLine("Increment CurrentJobs to:"+Status.CurrentJobs.ToString());
172    }
173
174    /// <summary>
175    /// Simulator Class for new Jobs. will be replaced with fetching Jobs from the Interface
176    /// </summary>
177    /// <returns></returns>
178    private IJob CreateNewJob() {
179      Random random = new Random();
180      IJob job = new TestJob();
181      job.JobId = random.Next();
182      return job;
183    }
184  }
185}
Note: See TracBrowser for help on using the repository browser.