1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.IO;
|
---|
4 | using System.Linq;
|
---|
5 | using System.Reflection;
|
---|
6 | using System.Threading;
|
---|
7 | using System.Threading.Tasks;
|
---|
8 | using HeuristicLab.Algorithms.GeneticAlgorithm;
|
---|
9 | using HeuristicLab.Clients.Hive.Jobs;
|
---|
10 | using HeuristicLab.Clients.Hive.SlaveCore;
|
---|
11 | using HeuristicLab.Common;
|
---|
12 | using HeuristicLab.Core;
|
---|
13 | using HeuristicLab.Hive;
|
---|
14 | using HeuristicLab.Persistence.Default.Xml;
|
---|
15 | using HeuristicLab.PluginInfrastructure;
|
---|
16 | using HeuristicLab.Problems.TestFunctions;
|
---|
17 |
|
---|
18 | namespace HeuristicLab.Clients.Hive.Slave.Tests {
|
---|
19 | #region Test Setup
|
---|
20 | public class Program {
|
---|
21 | static void Main(string[] args) {
|
---|
22 | //TestThreadSafeLog(); return;
|
---|
23 | //TestThreadSafePersistence(); return;
|
---|
24 | string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
---|
25 |
|
---|
26 | DeleteDirectory(Path.Combine(path, "PluginCache"));
|
---|
27 | DeleteDirectory(Path.Combine(path, "PluginTemp"));
|
---|
28 |
|
---|
29 | var pm = new HeuristicLab.PluginInfrastructure.Manager.PluginManager(path);
|
---|
30 | pm.DiscoverAndCheckPlugins();
|
---|
31 | var app = pm.Applications.Where(x => x.Name == "HeuristicLab.Clients.Hive.Slave.Tests").Single();
|
---|
32 | pm.Run(app);
|
---|
33 | }
|
---|
34 |
|
---|
35 | private static void TestThreadSafeLog() {
|
---|
36 | ILog log = new ThreadSafeLog(new Log());
|
---|
37 | bool abortOutputThread = false;
|
---|
38 |
|
---|
39 | Task outputTask = Task.Factory.StartNew(() => {
|
---|
40 | while (!abortOutputThread) {
|
---|
41 | Console.Clear();
|
---|
42 | foreach (var m in log.Messages) {
|
---|
43 | Console.WriteLine(m);
|
---|
44 | }
|
---|
45 | }
|
---|
46 | });
|
---|
47 |
|
---|
48 | int n = 50;
|
---|
49 | Task[] tasks = new Task[n];
|
---|
50 | for (int i = 0; i < n; i++) {
|
---|
51 | tasks[i] = Task.Factory.StartNew((idx) => {
|
---|
52 | for (int j = 0; j < 5000; j++) {
|
---|
53 | log.LogMessage(string.Format("Message {0}, Task {1}", j, idx));
|
---|
54 | }
|
---|
55 | }, i);
|
---|
56 | }
|
---|
57 | Task.WaitAll(tasks);
|
---|
58 | abortOutputThread = true;
|
---|
59 | outputTask.Wait();
|
---|
60 | Console.WriteLine("Finished, {0} messages", log.Messages.Count());
|
---|
61 | Console.ReadLine();
|
---|
62 | }
|
---|
63 |
|
---|
64 | private static void TestThreadSafePersistence() {
|
---|
65 | int n = 100;
|
---|
66 | Task[] tasks = new Task[n];
|
---|
67 | for (int i = 0; i < n; i++) {
|
---|
68 | tasks[i] = Task.Factory.StartNew((idx) => {
|
---|
69 | var alg = new GeneticAlgorithm { Engine = new SequentialEngine.SequentialEngine(), Problem = new SingleObjectiveTestFunctionProblem() };
|
---|
70 | byte[] data = Serialize(alg);
|
---|
71 | Console.WriteLine("Object #{0} serialized", idx);
|
---|
72 | }, i);
|
---|
73 | }
|
---|
74 | Task.WaitAll(tasks);
|
---|
75 | }
|
---|
76 | public static byte[] Serialize(object obj) {
|
---|
77 | MemoryStream memStream = new MemoryStream();
|
---|
78 | XmlGenerator.Serialize(obj, memStream);
|
---|
79 | byte[] jobByteArray = memStream.ToArray();
|
---|
80 | memStream.Dispose();
|
---|
81 | return jobByteArray;
|
---|
82 | }
|
---|
83 |
|
---|
84 | public static bool DeleteDirectory(string target_dir) {
|
---|
85 | if (!Directory.Exists(target_dir))
|
---|
86 | return true;
|
---|
87 |
|
---|
88 | bool result = false;
|
---|
89 |
|
---|
90 | string[] files = Directory.GetFiles(target_dir);
|
---|
91 | string[] dirs = Directory.GetDirectories(target_dir);
|
---|
92 |
|
---|
93 | foreach (string file in files) {
|
---|
94 | File.SetAttributes(file, FileAttributes.Normal);
|
---|
95 | File.Delete(file);
|
---|
96 | }
|
---|
97 |
|
---|
98 | foreach (string dir in dirs) {
|
---|
99 | DeleteDirectory(dir);
|
---|
100 | }
|
---|
101 |
|
---|
102 | Directory.Delete(target_dir, false);
|
---|
103 |
|
---|
104 | return result;
|
---|
105 | }
|
---|
106 | }
|
---|
107 | #endregion
|
---|
108 |
|
---|
109 | [Plugin("HeuristicLab.Clients.Hive.Slave.Tests", "1.0.0.0")]
|
---|
110 | [PluginFile("HeuristicLab.Clients.Hive.Slave-3.4.Tests.exe", PluginFileType.Assembly)]
|
---|
111 | public class TestPlugin : PluginBase { }
|
---|
112 |
|
---|
113 | [Application("HeuristicLab.Clients.Hive.Slave.Tests")]
|
---|
114 | public class TestApp : ApplicationBase {
|
---|
115 |
|
---|
116 | public override void Run() {
|
---|
117 | var mockPluginService = new MockPluginService();
|
---|
118 | var pluginManager = new PluginManager(mockPluginService, new Log());
|
---|
119 | JobManager jobManager = new JobManager(pluginManager, new Log());
|
---|
120 |
|
---|
121 | jobManager.JobStarted += new EventHandler<EventArgs<SlaveJob>>(jobManager_JobStarted);
|
---|
122 | jobManager.JobPaused += new EventHandler<EventArgs<SlaveJob, JobData>>(jobManager_JobPaused);
|
---|
123 | jobManager.JobStopped += new EventHandler<EventArgs<SlaveJob, JobData>>(jobManager_JobStopped);
|
---|
124 | jobManager.JobFailed += new EventHandler<EventArgs<Tuple<SlaveJob, JobData, Exception>>>(jobManager_JobFailed);
|
---|
125 | jobManager.ExceptionOccured += new EventHandler<EventArgs<SlaveJob, Exception>>(jobManager_ExceptionOccured);
|
---|
126 |
|
---|
127 | ConfigManager.Instance = new ConfigManager(jobManager);
|
---|
128 |
|
---|
129 | //TestCalculateJobs(mockPluginService, jobManager);
|
---|
130 | //TestPauseJob(mockPluginService, jobManager);
|
---|
131 | //TestStopJob(mockPluginService, jobManager);
|
---|
132 | //TestFailJob(mockPluginService, jobManager);
|
---|
133 |
|
---|
134 | //TestAbortAll(mockPluginService, jobManager);
|
---|
135 | //TestStopAll(mockPluginService, jobManager);
|
---|
136 | //TestPauseAll(mockPluginService, jobManager);
|
---|
137 |
|
---|
138 | Console.WriteLine(jobManager.JobCount);
|
---|
139 | }
|
---|
140 |
|
---|
141 | // calculate many jobs and request execution times rapidly
|
---|
142 | private static void TestCalculateJobs(MockPluginService mockPluginService, JobManager jobManager) {
|
---|
143 | StartStatusObservationThread();
|
---|
144 |
|
---|
145 | Task[] tasks = CreateAndStartJobs(mockPluginService, jobManager, 10, 1000);
|
---|
146 | Task.WaitAll(tasks);
|
---|
147 |
|
---|
148 | Console.ReadLine();
|
---|
149 | }
|
---|
150 |
|
---|
151 | // calculate jobs and stop them
|
---|
152 | private void TestStopJob(MockPluginService mockPluginService, JobManager jobManager) {
|
---|
153 | for (int i = 0; i < 5; i++) {
|
---|
154 | var optimizerJob = new OptimizerJob(new GeneticAlgorithm { Engine = new SequentialEngine.SequentialEngine(), Problem = new SingleObjectiveTestFunctionProblem() });
|
---|
155 |
|
---|
156 | Job job;
|
---|
157 | JobData jobData;
|
---|
158 | CreateJob(mockPluginService, optimizerJob, out job, out jobData);
|
---|
159 |
|
---|
160 | jobManager.StartJobAsync(job, jobData);
|
---|
161 | Thread.Sleep(i * 1000);
|
---|
162 |
|
---|
163 | jobManager.StopJobAsync(job.Id);
|
---|
164 | }
|
---|
165 | }
|
---|
166 |
|
---|
167 | // calculate jobs and pause them
|
---|
168 | private void TestPauseJob(MockPluginService mockPluginService, JobManager jobManager) {
|
---|
169 | for (int i = 4; i < 5; i++) {
|
---|
170 | var optimizerJob = new OptimizerJob(new GeneticAlgorithm { Engine = new SequentialEngine.SequentialEngine(), Problem = new SingleObjectiveTestFunctionProblem() });
|
---|
171 |
|
---|
172 | Job job;
|
---|
173 | JobData jobData;
|
---|
174 | CreateJob(mockPluginService, optimizerJob, out job, out jobData);
|
---|
175 |
|
---|
176 | jobManager.StartJobAsync(job, jobData);
|
---|
177 | Thread.Sleep(i * 1000);
|
---|
178 |
|
---|
179 | jobManager.PauseJobAsync(job.Id);
|
---|
180 | }
|
---|
181 | }
|
---|
182 |
|
---|
183 | // start many jobs and then abort all
|
---|
184 | private void TestAbortAll(MockPluginService mockPluginService, JobManager jobManager) {
|
---|
185 | StartStatusObservationThread();
|
---|
186 |
|
---|
187 | Task[] tasks = CreateAndStartJobs(mockPluginService, jobManager, 4, 5000);
|
---|
188 | Task.WaitAll(tasks);
|
---|
189 |
|
---|
190 | Console.WriteLine("Aborting all jobs");
|
---|
191 | jobManager.AbortAllJobs();
|
---|
192 | Console.ReadLine();
|
---|
193 | }
|
---|
194 |
|
---|
195 | // start many jobs and then stop all and observe results from GA
|
---|
196 | private void TestStopAll(MockPluginService mockPluginService, JobManager jobManager) {
|
---|
197 | StartStatusObservationThread();
|
---|
198 |
|
---|
199 | Task[] tasks = CreateAndStartJobs(mockPluginService, jobManager, 8, 5000);
|
---|
200 | Task.WaitAll(tasks);
|
---|
201 |
|
---|
202 | Console.WriteLine("Stopping all jobs");
|
---|
203 | jobManager.StopAllJobsAsync();
|
---|
204 | Console.ReadLine();
|
---|
205 | }
|
---|
206 |
|
---|
207 | // start many jobs and then pause all and observe results from GA
|
---|
208 | private void TestPauseAll(MockPluginService mockPluginService, JobManager jobManager) {
|
---|
209 | StartStatusObservationThread();
|
---|
210 |
|
---|
211 | Task[] tasks = CreateAndStartJobs(mockPluginService, jobManager, 4, 1000);
|
---|
212 | Task.WaitAll(tasks);
|
---|
213 |
|
---|
214 | Console.WriteLine("Pausing all jobs");
|
---|
215 | jobManager.PauseAllJobsAsync();
|
---|
216 | Console.ReadLine();
|
---|
217 | }
|
---|
218 |
|
---|
219 | #region Helpers
|
---|
220 | private static Task[] CreateAndStartJobs(MockPluginService mockPluginService, JobManager jobManager, int n, int generations = 1000) {
|
---|
221 | Task[] tasks = new Task[n];
|
---|
222 | for (int i = 0; i < n; i++) {
|
---|
223 | tasks[i] = Task.Factory.StartNew((idx) => {
|
---|
224 | var ga = new GeneticAlgorithm { Engine = new SequentialEngine.SequentialEngine(), Problem = new SingleObjectiveTestFunctionProblem() };
|
---|
225 | ga.MaximumGenerations.Value = generations;
|
---|
226 | var mockJob = new OptimizerJob(ga);
|
---|
227 |
|
---|
228 | Job job;
|
---|
229 | JobData jobData;
|
---|
230 | CreateJob(mockPluginService, mockJob, out job, out jobData);
|
---|
231 |
|
---|
232 | jobManager.StartJobAsync(job, jobData);
|
---|
233 | }, i);
|
---|
234 | }
|
---|
235 | return tasks;
|
---|
236 | }
|
---|
237 |
|
---|
238 | private static void StartStatusObservationThread(int intervalMs = 5000) {
|
---|
239 | Task.Factory.StartNew(() => {
|
---|
240 | while (true) {
|
---|
241 | Thread.Sleep(intervalMs);
|
---|
242 | PrintInfo();
|
---|
243 | }
|
---|
244 | });
|
---|
245 | }
|
---|
246 |
|
---|
247 | private static void PrintInfo() {
|
---|
248 | var info = ConfigManager.Instance.GetClientInfo();
|
---|
249 | var heartBeatData = new Heartbeat {
|
---|
250 | SlaveId = info.Id,
|
---|
251 | FreeCores = info.Cores.HasValue ? info.Cores.Value - SlaveStatusInfo.UsedCores : 0,
|
---|
252 | FreeMemory = ConfigManager.GetFreeMemory(),
|
---|
253 | CpuUtilization = ConfigManager.Instance.GetCpuUtilization(),
|
---|
254 | JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs(),
|
---|
255 | AssignJob = !ConfigManager.Instance.Asleep
|
---|
256 | };
|
---|
257 | Console.WriteLine(heartBeatData);
|
---|
258 | Console.WriteLine(ConfigManager.Instance.GetStatusForClientConsole().ToString());
|
---|
259 | }
|
---|
260 |
|
---|
261 | private static object locker = new object();
|
---|
262 | private static void CreateJob(MockPluginService mockPluginService, IJob mockJob, out Job job, out JobData jobData) {
|
---|
263 | job = new Job { Id = Guid.NewGuid(), CoresNeeded = 1, MemoryNeeded = 0 };
|
---|
264 | job.PluginsNeededIds = new List<Guid>();
|
---|
265 | jobData = new JobData { JobId = job.Id };
|
---|
266 | IEnumerable<Type> types;
|
---|
267 | jobData.Data = PersistenceUtil.Serialize(mockJob, out types);
|
---|
268 |
|
---|
269 | // make plugins available through mockPluginService
|
---|
270 | var plugins = new List<IPluginDescription>();
|
---|
271 | PluginUtil.CollectDeclaringPlugins(plugins, types);
|
---|
272 | foreach (var plugin in plugins) {
|
---|
273 | var p = PluginUtil.CreatePlugin(plugin, false);
|
---|
274 | p.Id = Guid.NewGuid();
|
---|
275 | lock (locker) {
|
---|
276 | if (!mockPluginService.Plugins.ContainsKey(p.Id)) {
|
---|
277 | mockPluginService.Plugins[p.Id] = p;
|
---|
278 | mockPluginService.PluginDatas[p.Id] = PluginUtil.CreatePluginDatas(plugin);
|
---|
279 | }
|
---|
280 | }
|
---|
281 | foreach (var pd in mockPluginService.PluginDatas[p.Id]) {
|
---|
282 | pd.Id = Guid.NewGuid();
|
---|
283 | pd.PluginId = p.Id;
|
---|
284 | }
|
---|
285 | job.PluginsNeededIds.Add(p.Id);
|
---|
286 | }
|
---|
287 | }
|
---|
288 | #endregion
|
---|
289 |
|
---|
290 | #region Events
|
---|
291 | private void jobManager_JobStarted(object sender, EventArgs<SlaveJob> e) {
|
---|
292 | Console.WriteLine("# Job Started: {0}", e.Value.JobId);
|
---|
293 | }
|
---|
294 | private void jobManager_JobPaused(object sender, EventArgs<SlaveJob, JobData> e) {
|
---|
295 | Console.WriteLine("# Job Paused: {0}", e.Value.JobId);
|
---|
296 | PrintJobResultInfo(e.Value2);
|
---|
297 | }
|
---|
298 |
|
---|
299 | private void jobManager_JobStopped(object sender, EventArgs<SlaveJob, JobData> e) {
|
---|
300 | Console.WriteLine("# Job Stopped: {0}", e.Value.JobId);
|
---|
301 | PrintJobResultInfo(e.Value2);
|
---|
302 | }
|
---|
303 | private void jobManager_JobFailed(object sender, EventArgs<Tuple<SlaveJob, JobData, Exception>> e) {
|
---|
304 | Console.WriteLine("# Job Failed: {0}", e.Value.Item3.ToString());
|
---|
305 | if (e.Value.Item2 != null) {
|
---|
306 | PrintJobResultInfo(e.Value.Item2);
|
---|
307 | }
|
---|
308 | }
|
---|
309 | private void jobManager_ExceptionOccured(object sender, EventArgs<SlaveJob, Exception> e) {
|
---|
310 | Console.WriteLine("# Exception Occured: {0}", e.Value2);
|
---|
311 | }
|
---|
312 |
|
---|
313 | private static void PrintJobResultInfo(JobData jobData) {
|
---|
314 | var ga = (GeneticAlgorithm)PersistenceUtil.Deserialize<OptimizerJob>(jobData.Data).Item;
|
---|
315 | var results = ga.Results;
|
---|
316 | Console.WriteLine("# State: {0}, ExecTime: {1}, Generations: {2}", ga.ExecutionState, ga.ExecutionTime, results.ContainsKey("Generations") ? results["Generations"].Value.ToString() : "-");
|
---|
317 | }
|
---|
318 | #endregion
|
---|
319 | }
|
---|
320 | }
|
---|