Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 798 was 798, checked in by whackl, 16 years ago

implemented serveral services (#376)

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