Free cookie consent management tool by TermsFeed Policy Generator

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

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

implemented the async calls to GetSnapshot and GetFinishedJob (#383)

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 = 5000 };
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          Thread ssr = new Thread(new ParameterizedThreadStart(GetSnapshot));
127          ssr.Start(container.JobId);         
128          break;
129
130        case MessageContainer.MessageType.FetchJob:
131          clientCommunicator.PullJobAsync(Guid.NewGuid());
132          break;         
133        case MessageContainer.MessageType.FinishedJob:
134          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
135          finThread.Start(container.JobId);         
136          break;     
137      }
138    }
139
140    private void GetFinishedJob(object jobId) {
141      long jId = (long)jobId;
142      String obj = engines[jId].GetFinishedJob();
143      engines[jId].GetFinishedJob();
144      AppDomain.Unload(appDomains[jId]);
145      appDomains.Remove(jId);
146      engines.Remove(jId);
147
148      Status.CurrentJobs--;
149      Debug.WriteLine("Decrement CurrentJobs to:" + Status.CurrentJobs.ToString());     
150    }
151
152    private void GetSnapshot(object jobId) {
153      long jId = (long)jobId;
154      String obj = engines[jId].GetSnapshot();
155    }
156
157    void ClientCommunicator_PullJobCompleted(object sender, PullJobCompletedEventArgs e) {
158      bool sandboxed = false;
159
160      IJob job = new TestJob { JobId = e.Result.JobId };
161
162      AppDomain appDomain = CreateNewAppDomain(sandboxed);
163      appDomains.Add(job.JobId, appDomain);
164
165      Executor engine = (Executor)appDomain.CreateInstanceAndUnwrap(typeof(Executor).Assembly.GetName().Name, typeof(Executor).FullName);
166      engine.Job = job;
167      engine.JobId = job.JobId;
168      engine.Queue = MessageQueue.GetInstance();
169      engine.Start();
170      engines.Add(engine.JobId, engine);
171
172      Status.CurrentJobs++;
173
174      Debug.WriteLine("Increment CurrentJobs to:"+Status.CurrentJobs.ToString());
175    }
176
177    /// <summary>
178    /// Simulator Class for new Jobs. will be replaced with fetching Jobs from the Interface
179    /// </summary>
180    /// <returns></returns>
181    private IJob CreateNewJob() {
182      Random random = new Random();
183      IJob job = new TestJob();
184      job.JobId = random.Next();
185      return job;
186    }
187  }
188}
Note: See TracBrowser for help on using the repository browser.