1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2010 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 |
|
---|
22 | using System;
|
---|
23 | using System.Linq;
|
---|
24 | using HeuristicLab.Common;
|
---|
25 | using HeuristicLab.Core;
|
---|
26 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
27 | using HeuristicLab.Optimization;
|
---|
28 | using System.Drawing;
|
---|
29 | using HeuristicLab.Collections;
|
---|
30 | using System.Collections.Generic;
|
---|
31 | using HeuristicLab.Hive.Contracts.BusinessObjects;
|
---|
32 | using System.IO;
|
---|
33 | using HeuristicLab.Persistence.Default.Xml;
|
---|
34 | using HeuristicLab.PluginInfrastructure;
|
---|
35 | using System.Reflection;
|
---|
36 | using HeuristicLab.Hive.Contracts.Interfaces;
|
---|
37 | using HeuristicLab.Hive.Contracts;
|
---|
38 | using System.Threading;
|
---|
39 | using HeuristicLab.Tracing;
|
---|
40 | using HeuristicLab.Hive.JobBase;
|
---|
41 | using System.Diagnostics;
|
---|
42 | using System.Collections;
|
---|
43 | using System.ServiceModel;
|
---|
44 | using HeuristicLab.Hive.Contracts.ResponseObjects;
|
---|
45 | using HeuristicLab.Hive.Experiment.Properties;
|
---|
46 | using System.ComponentModel;
|
---|
47 | using HeuristicLab.Hive.Experiment.Jobs;
|
---|
48 |
|
---|
49 | namespace HeuristicLab.Hive.Experiment {
|
---|
50 | /// <summary>
|
---|
51 | /// An experiment which contains multiple batch runs of algorithms.
|
---|
52 | /// </summary>
|
---|
53 | [Item(itemName, itemDescription)]
|
---|
54 | [StorableClass]
|
---|
55 | public class HiveExperiment : NamedItem, IExecutable {
|
---|
56 | private const string itemName = "Hive Experiment";
|
---|
57 | private const string itemDescription = "A runner for a single experiment, which's algorithms are executed in the Hive.";
|
---|
58 | private const int resultPollingIntervalMs = 5000;
|
---|
59 | private const int snapshotPollingIntervalMs = 1000;
|
---|
60 | private const int maxSnapshotRetries = 20;
|
---|
61 | private object locker = new object();
|
---|
62 |
|
---|
63 | private System.Timers.Timer timer;
|
---|
64 | private bool pausePending, stopPending;
|
---|
65 |
|
---|
66 | // ensure that only 2 threads can fetch jobresults simultaniously
|
---|
67 | private Semaphore fetchJobSemaphore = new Semaphore(2, 2);
|
---|
68 |
|
---|
69 | private static object pendingOptimizerMappingsLocker = new object();
|
---|
70 |
|
---|
71 | private bool stopResultsPollingPending = false;
|
---|
72 |
|
---|
73 | private Thread resultPollingThread;
|
---|
74 |
|
---|
75 | private bool isPollingResults;
|
---|
76 | public bool IsPollingResults {
|
---|
77 | get { return isPollingResults; }
|
---|
78 | private set {
|
---|
79 | if (isPollingResults != value) {
|
---|
80 | isPollingResults = value;
|
---|
81 | OnIsPollingResultsChanged();
|
---|
82 | }
|
---|
83 | }
|
---|
84 | }
|
---|
85 |
|
---|
86 | public IEnumerable<string> ResourceGroups {
|
---|
87 | get {
|
---|
88 | if (!string.IsNullOrEmpty(resourceIds)) {
|
---|
89 | return resourceIds.Split(';');
|
---|
90 | } else {
|
---|
91 | return new List<string>();
|
---|
92 | }
|
---|
93 | }
|
---|
94 | }
|
---|
95 |
|
---|
96 | #region Storable Properties
|
---|
97 | [Storable]
|
---|
98 | private DateTime lastUpdateTime;
|
---|
99 |
|
---|
100 | [Storable]
|
---|
101 | private string resourceIds;
|
---|
102 | public string ResourceIds {
|
---|
103 | get { return resourceIds; }
|
---|
104 | set {
|
---|
105 | if (resourceIds != value) {
|
---|
106 | resourceIds = value;
|
---|
107 | OnResourceIdsChanged();
|
---|
108 | }
|
---|
109 | }
|
---|
110 | }
|
---|
111 |
|
---|
112 | [Storable]
|
---|
113 | private HeuristicLab.Optimization.Experiment experiment;
|
---|
114 | public HeuristicLab.Optimization.Experiment Experiment {
|
---|
115 | get { return experiment; }
|
---|
116 | set {
|
---|
117 | if (experiment != value) {
|
---|
118 | experiment = value;
|
---|
119 | OnExperimentChanged();
|
---|
120 | }
|
---|
121 | }
|
---|
122 | }
|
---|
123 |
|
---|
124 | [Storable]
|
---|
125 | private ILog log;
|
---|
126 | public ILog Log {
|
---|
127 | get { return log; }
|
---|
128 | }
|
---|
129 |
|
---|
130 | [Storable]
|
---|
131 | private Core.ExecutionState executionState;
|
---|
132 | public ExecutionState ExecutionState {
|
---|
133 | get { return executionState; }
|
---|
134 | private set {
|
---|
135 | if (executionState != value) {
|
---|
136 | executionState = value;
|
---|
137 | OnExecutionStateChanged();
|
---|
138 | }
|
---|
139 | }
|
---|
140 | }
|
---|
141 |
|
---|
142 | [Storable]
|
---|
143 | private TimeSpan executionTime;
|
---|
144 | public TimeSpan ExecutionTime {
|
---|
145 | get { return executionTime; }
|
---|
146 | private set {
|
---|
147 | if (executionTime != value) {
|
---|
148 | executionTime = value;
|
---|
149 | OnExecutionTimeChanged();
|
---|
150 | }
|
---|
151 | }
|
---|
152 | }
|
---|
153 |
|
---|
154 | [Storable]
|
---|
155 | private IJob rootJob;
|
---|
156 | public IJob RootJob {
|
---|
157 | get { return rootJob; }
|
---|
158 | set {
|
---|
159 | if (rootJob != value) {
|
---|
160 | rootJob = value;
|
---|
161 | OnRootJobChanged();
|
---|
162 | }
|
---|
163 | }
|
---|
164 | }
|
---|
165 |
|
---|
166 | private JobItem rootJobItem;
|
---|
167 | public JobItem RootJobItem {
|
---|
168 | get { return rootJobItem; }
|
---|
169 | set {
|
---|
170 | if (rootJobItem != null) {
|
---|
171 | DeregisterRootJobItemEvents();
|
---|
172 | }
|
---|
173 | if (rootJobItem != value) {
|
---|
174 | rootJobItem = value;
|
---|
175 | RegisterRootJobItemEvents();
|
---|
176 | OnRootJobItemChanged();
|
---|
177 | }
|
---|
178 | }
|
---|
179 | }
|
---|
180 |
|
---|
181 | private void RegisterRootJobItemEvents() {
|
---|
182 | rootJobItem.FinalResultAvailable += new EventHandler(rootJobItem_FinalResultAvailable);
|
---|
183 | }
|
---|
184 |
|
---|
185 | private void DeregisterRootJobItemEvents() {
|
---|
186 | rootJobItem.FinalResultAvailable -= new EventHandler(rootJobItem_FinalResultAvailable);
|
---|
187 | }
|
---|
188 |
|
---|
189 | #endregion
|
---|
190 |
|
---|
191 | [StorableConstructor]
|
---|
192 | public HiveExperiment(bool deserializing)
|
---|
193 | : base(deserializing) {
|
---|
194 | }
|
---|
195 |
|
---|
196 | public HiveExperiment()
|
---|
197 | : base(itemName, itemDescription) {
|
---|
198 | this.ResourceIds = HeuristicLab.Hive.Experiment.Properties.Settings.Default.ResourceIds;
|
---|
199 | this.log = new Log();
|
---|
200 | pausePending = stopPending = false;
|
---|
201 | isPollingResults = false;
|
---|
202 | InitTimer();
|
---|
203 | }
|
---|
204 |
|
---|
205 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
206 | LogMessage("I am beeing cloned");
|
---|
207 | HiveExperiment clone = (HiveExperiment)base.Clone(cloner);
|
---|
208 | clone.resourceIds = this.resourceIds;
|
---|
209 | clone.experiment = (HeuristicLab.Optimization.Experiment)cloner.Clone(experiment);
|
---|
210 | clone.executionState = this.executionState;
|
---|
211 | clone.executionTime = this.executionTime;
|
---|
212 | clone.log = (ILog)cloner.Clone(log);
|
---|
213 | clone.stopPending = this.stopPending;
|
---|
214 | clone.pausePending = this.pausePending;
|
---|
215 | clone.lastUpdateTime = this.lastUpdateTime;
|
---|
216 | clone.isPollingResults = this.isPollingResults;
|
---|
217 | clone.rootJob = (IJob)cloner.Clone(this.rootJob);
|
---|
218 | return clone;
|
---|
219 | }
|
---|
220 |
|
---|
221 | [StorableHook(HookType.AfterDeserialization)]
|
---|
222 | private void AfterDeserialization() {
|
---|
223 | InitTimer();
|
---|
224 | this.IsPollingResults = false;
|
---|
225 | this.stopResultsPollingPending = false;
|
---|
226 | RegisterEvents();
|
---|
227 | LogMessage("I was deserialized.");
|
---|
228 | }
|
---|
229 |
|
---|
230 | private void RegisterEvents() {
|
---|
231 | RootJobChanged += new EventHandler(HiveExperiment_RootJobChanged);
|
---|
232 | }
|
---|
233 |
|
---|
234 | private void DeRegisterEvents() {
|
---|
235 | RootJobChanged -= new EventHandler(HiveExperiment_RootJobChanged);
|
---|
236 | }
|
---|
237 |
|
---|
238 | #region Execution Time Timer
|
---|
239 | private void InitTimer() {
|
---|
240 | timer = new System.Timers.Timer(100);
|
---|
241 | timer.AutoReset = true;
|
---|
242 | timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
|
---|
243 | }
|
---|
244 |
|
---|
245 | private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
|
---|
246 | DateTime now = DateTime.Now;
|
---|
247 | ExecutionTime += now - lastUpdateTime;
|
---|
248 | lastUpdateTime = now;
|
---|
249 | }
|
---|
250 | #endregion
|
---|
251 |
|
---|
252 | #region IExecutable Methods
|
---|
253 | public void Pause() {
|
---|
254 | throw new NotSupportedException();
|
---|
255 | }
|
---|
256 |
|
---|
257 | public void Prepare() {
|
---|
258 | if (experiment != null) {
|
---|
259 | StopResultPolling();
|
---|
260 | experiment.Prepare();
|
---|
261 | this.ExecutionState = Core.ExecutionState.Prepared;
|
---|
262 | OnPrepared();
|
---|
263 | }
|
---|
264 | }
|
---|
265 |
|
---|
266 | public void Start() {
|
---|
267 | OnStarted();
|
---|
268 | ExecutionTime = new TimeSpan();
|
---|
269 | lastUpdateTime = DateTime.Now;
|
---|
270 | this.ExecutionState = Core.ExecutionState.Started;
|
---|
271 |
|
---|
272 | Thread t = new Thread(() => {
|
---|
273 | using (Disposable<IClientFacade> service = ServiceLocator.Instance.StreamedClientFacadePool.GetService()) {
|
---|
274 | try {
|
---|
275 | RootJobItem = ToJobItem(RootJob);
|
---|
276 |
|
---|
277 | IEnumerable<string> groups = ResourceGroups;
|
---|
278 | SerializedJob serializedJob = RootJobItem.ToSerializedJob();
|
---|
279 | ResponseObject<JobDto> response = service.Obj.AddJobWithGroupStrings(serializedJob, groups);
|
---|
280 |
|
---|
281 | if (response.StatusMessage != ResponseStatus.Ok) {
|
---|
282 | throw new Exception(response.StatusMessage.ToString());
|
---|
283 | } else {
|
---|
284 | RootJobItem.JobDto = response.Obj;
|
---|
285 | LogMessage(RootJobItem.JobDto.Id, "Job sent to Hive");
|
---|
286 |
|
---|
287 | StartResultPolling();
|
---|
288 | }
|
---|
289 | }
|
---|
290 | catch (Exception e) {
|
---|
291 | LogMessage("Error: Starting HiveExperiment failed: " + e.Message);
|
---|
292 | this.ExecutionState = Core.ExecutionState.Stopped;
|
---|
293 | OnStopped();
|
---|
294 | }
|
---|
295 | }
|
---|
296 | });
|
---|
297 | t.Start();
|
---|
298 | }
|
---|
299 |
|
---|
300 | public void Stop() {
|
---|
301 | if (IsPollingResults)
|
---|
302 | StopResultPolling();
|
---|
303 | this.ExecutionState = Core.ExecutionState.Stopped;
|
---|
304 | OnStopped();
|
---|
305 | }
|
---|
306 | #endregion
|
---|
307 |
|
---|
308 | #region Job Management
|
---|
309 | public void RefreshJobTree() {
|
---|
310 | this.RootJob = CreateJobTree(this.Experiment);
|
---|
311 | }
|
---|
312 |
|
---|
313 | private IJob CreateJobTree(IOptimizer optimizer) {
|
---|
314 | IJob job = null;
|
---|
315 | if (optimizer is HeuristicLab.Optimization.Experiment) {
|
---|
316 | HeuristicLab.Optimization.Experiment exp = (HeuristicLab.Optimization.Experiment)optimizer;
|
---|
317 | ExperimentJob expJob = new ExperimentJob(exp);
|
---|
318 | foreach (IOptimizer opt in exp.Optimizers) {
|
---|
319 | expJob.AddChildJob(CreateJobTree(opt));
|
---|
320 | }
|
---|
321 | job = expJob;
|
---|
322 | } else if (optimizer is BatchRun) {
|
---|
323 | job = new BatchRunJob(optimizer);
|
---|
324 | } else {
|
---|
325 | job = new OptimizerJob(optimizer);
|
---|
326 | }
|
---|
327 | return job;
|
---|
328 | }
|
---|
329 |
|
---|
330 | private JobItem ToJobItem(IJob j) {
|
---|
331 | return new JobItem() {
|
---|
332 | Job = j,
|
---|
333 | JobDto = new JobDto() {
|
---|
334 | State = JobState.Offline,
|
---|
335 | PluginsNeeded = HivePluginInfoDto.FindPluginsNeeded(j.GetType())
|
---|
336 | }
|
---|
337 | };
|
---|
338 | }
|
---|
339 |
|
---|
340 | /// <summary>
|
---|
341 | /// Updates all JobItems with the results
|
---|
342 | /// if one is finished, the serialized job is downloaded and updated
|
---|
343 | /// </summary>
|
---|
344 | /// <param name="jobResultList"></param>
|
---|
345 | private void UpdateJobItems(JobResultList jobResultList) {
|
---|
346 | if (RootJobItem == null) {
|
---|
347 | var rootResults = jobResultList.Where(res => !res.ParentJobId.HasValue);
|
---|
348 | if (rootResults.Count() > 0) {
|
---|
349 | RootJobItem = new JobItem(rootResults.First());
|
---|
350 | } else {
|
---|
351 | LogMessage("Error: Could not find JobResult for RootJobItem");
|
---|
352 | return;
|
---|
353 | }
|
---|
354 | }
|
---|
355 |
|
---|
356 | using (Disposable<IClientFacade> service = ServiceLocator.Instance.StreamedClientFacadePool.GetService()) {
|
---|
357 | foreach (JobResult jobResult in jobResultList) {
|
---|
358 | JobItem jobItem = FindJobItem(RootJobItem, jobResult.Id);
|
---|
359 | if (jobItem != null) {
|
---|
360 | jobItem.UpdateJob(jobResult);
|
---|
361 | if (jobItem.JobDto.State == JobState.Finished && !jobItem.IsFinalResultAvailable) {
|
---|
362 | // job is finished but the final result was not yet downloaded
|
---|
363 | SerializedJob serializedJob = service.Obj.GetLastSerializedResult(jobResult.Id).Obj;
|
---|
364 | jobItem.Job = XmlParser.Deserialize<IJob>(new MemoryStream(serializedJob.SerializedJobData));
|
---|
365 | UpdateChildJobs(jobItem);
|
---|
366 | this.Experiment.Runs.AddRange(((OptimizerJob)jobItem.Job).Optimizer.Runs);
|
---|
367 | //ReplaceOptimizerInExperiment(jobItem.JobDto.Id, jobItem.Job);
|
---|
368 | }
|
---|
369 | } else {
|
---|
370 | // job does not yet exist locally
|
---|
371 | JobItem parentJobItem = FindJobItem(RootJobItem, jobResult.ParentJobId.Value);
|
---|
372 | if (parentJobItem != null) {
|
---|
373 | LogMessage(jobResult.Id, "Creating JobItem");
|
---|
374 | SerializedJob serializedJob = service.Obj.GetLastSerializedResult(jobResult.Id).Obj;
|
---|
375 | JobItem newJobItem = new JobItem();
|
---|
376 | newJobItem.JobDto = serializedJob.JobInfo;
|
---|
377 | newJobItem.Job = XmlParser.Deserialize<IJob>(new MemoryStream(serializedJob.SerializedJobData));
|
---|
378 | parentJobItem.AddChildJob(newJobItem);
|
---|
379 | if (newJobItem.JobDto.State == JobState.Finished && newJobItem.IsFinalResultAvailable) {
|
---|
380 | this.Experiment.Runs.AddRange(((OptimizerJob)newJobItem.Job).Optimizer.Runs);
|
---|
381 | UpdateChildJobs(newJobItem);
|
---|
382 | //ReplaceOptimizerInExperiment(jobItem.JobDto.Id, jobItem.Job);
|
---|
383 | }
|
---|
384 | } else {
|
---|
385 | LogMessage("Error: Could not update JobResult for " + jobResult.Id);
|
---|
386 | }
|
---|
387 | }
|
---|
388 | }
|
---|
389 | }
|
---|
390 | }
|
---|
391 |
|
---|
392 | /// <summary>
|
---|
393 | /// Updates the ChildJobItems of a JobItem according to the IJob.ChildJobs of JobItem.Job (pretty confusing, right)
|
---|
394 | /// </summary>
|
---|
395 | /// <param name="jobItem"></param>
|
---|
396 | private void UpdateChildJobs(JobItem jobItem) {
|
---|
397 | List<JobItem> newJobItems = new List<JobItem>();
|
---|
398 | foreach (IJob job in jobItem.Job.ChildJobs) {
|
---|
399 | if (!jobItem.ReplaceChildJob(job)) {
|
---|
400 | newJobItems.Add(ToJobItem(job));
|
---|
401 | }
|
---|
402 | }
|
---|
403 | foreach (JobItem item in newJobItems) {
|
---|
404 | jobItem.AddChildJob(item);
|
---|
405 | }
|
---|
406 | }
|
---|
407 |
|
---|
408 | private JobItem FindJobItem(JobItem parentJobItem, Guid jobId) {
|
---|
409 | if (parentJobItem.JobDto.Id == jobId) {
|
---|
410 | return parentJobItem;
|
---|
411 | } else {
|
---|
412 | foreach (JobItem child in parentJobItem.ChildJobItems) {
|
---|
413 | JobItem result = FindJobItem(child, jobId);
|
---|
414 | if (result != null)
|
---|
415 | return result;
|
---|
416 | }
|
---|
417 | }
|
---|
418 | return null;
|
---|
419 | }
|
---|
420 |
|
---|
421 | private void JobItem_JobStateChanged(object sender, EventArgs e) {
|
---|
422 | JobItem jobItem = (JobItem)sender;
|
---|
423 |
|
---|
424 | Thread t = new Thread(() => {
|
---|
425 | try {
|
---|
426 | if (jobItem.JobDto.State == JobState.Finished) {
|
---|
427 | FetchAndUpdateJob(jobItem.JobDto.Id);
|
---|
428 | } else if (jobItem.JobDto.State == JobState.Failed) {
|
---|
429 |
|
---|
430 | }
|
---|
431 | }
|
---|
432 | catch (Exception ex) {
|
---|
433 | LogMessage("JobItem_JobStateChanged failed badly: " + ex.Message);
|
---|
434 | }
|
---|
435 | });
|
---|
436 | t.Start();
|
---|
437 | }
|
---|
438 |
|
---|
439 | /// <summary>
|
---|
440 | /// Fetches the finished job from the server and updates the jobItem
|
---|
441 | /// </summary>
|
---|
442 | private void FetchAndUpdateJob(Guid jobId) {
|
---|
443 | bool tryagain = false;
|
---|
444 | LogMessage(jobId, "FetchAndUpdateJob started");
|
---|
445 | if (fetchJobSemaphore.WaitOne(new TimeSpan(0, 2, 0))) {
|
---|
446 |
|
---|
447 | try {
|
---|
448 | using (Disposable<IClientFacade> service = ServiceLocator.Instance.StreamedClientFacadePool.GetService()) {
|
---|
449 | ResponseObject<SerializedJob> jobResponse = service.Obj.GetLastSerializedResult(jobId);
|
---|
450 | IJob restoredObject = XmlParser.Deserialize<IJob>(new MemoryStream(jobResponse.Obj.SerializedJobData));
|
---|
451 | IOptimizer restoredOptimizer = ((OptimizerJob)restoredObject).Optimizer;
|
---|
452 | LogMessage(jobId, "FetchAndUpdateJob ended");
|
---|
453 | }
|
---|
454 | }
|
---|
455 | catch (Exception e) {
|
---|
456 | LogMessage(jobId, "FetchAndUpdateJob failed: " + e.Message + ". Will try again!");
|
---|
457 | tryagain = true;
|
---|
458 | }
|
---|
459 | finally {
|
---|
460 | fetchJobSemaphore.Release();
|
---|
461 | }
|
---|
462 | } else {
|
---|
463 | LogMessage(jobId, "FetchAndUpdateJob timed out. Will try again!");
|
---|
464 | tryagain = true;
|
---|
465 | }
|
---|
466 |
|
---|
467 | if (tryagain) {
|
---|
468 | FetchAndUpdateJob(jobId);
|
---|
469 | }
|
---|
470 | }
|
---|
471 |
|
---|
472 | public void AbortJob(Guid jobId) {
|
---|
473 | using (Disposable<IClientFacade> service = ServiceLocator.Instance.ClientFacadePool.GetService()) {
|
---|
474 | Response response = service.Obj.AbortJob(jobId);
|
---|
475 | LogMessage(jobId, "Aborting Job: " + response.StatusMessage);
|
---|
476 | }
|
---|
477 | }
|
---|
478 | #endregion
|
---|
479 |
|
---|
480 | #region Result Polling
|
---|
481 | public void StartResultPolling() {
|
---|
482 | this.stopResultsPollingPending = false;
|
---|
483 | this.IsPollingResults = true;
|
---|
484 | resultPollingThread = new Thread(RunResultPollingThread);
|
---|
485 | if (resultPollingThread.ThreadState != System.Threading.ThreadState.Running)
|
---|
486 | resultPollingThread.Start();
|
---|
487 | }
|
---|
488 |
|
---|
489 | public void StopResultPolling() {
|
---|
490 | this.stopResultsPollingPending = true;
|
---|
491 | if (resultPollingThread != null) {
|
---|
492 | if (resultPollingThread.ThreadState == System.Threading.ThreadState.WaitSleepJoin) {
|
---|
493 | resultPollingThread.Interrupt();
|
---|
494 | }
|
---|
495 | resultPollingThread.Join();
|
---|
496 | }
|
---|
497 | this.stopResultsPollingPending = false;
|
---|
498 | }
|
---|
499 |
|
---|
500 | private void RunResultPollingThread() {
|
---|
501 | try {
|
---|
502 | do {
|
---|
503 | if (RootJobItem.JobDto.State != JobState.Finished) {
|
---|
504 | using (Disposable<IClientFacade> service = ServiceLocator.Instance.StreamedClientFacadePool.GetService()) {
|
---|
505 | LogMessage("Polling results");
|
---|
506 | try {
|
---|
507 | ResponseObject<JobResultList> response = service.Obj.GetChildJobResults(RootJobItem.JobDto.Id, true, true);
|
---|
508 | if (response.StatusMessage == ResponseStatus.Ok) {
|
---|
509 | JobResultList jobItemList = response.Obj;
|
---|
510 | UpdateJobItems(jobItemList);
|
---|
511 |
|
---|
512 | LogMessage("Polling successfully finished");
|
---|
513 | } else {
|
---|
514 | throw new Exception(response.StatusMessage.ToString());
|
---|
515 | }
|
---|
516 | }
|
---|
517 | catch (Exception e) {
|
---|
518 | LogMessage("Polling results failed: " + e.Message);
|
---|
519 | }
|
---|
520 | }
|
---|
521 | Thread.Sleep(resultPollingIntervalMs);
|
---|
522 | } else {
|
---|
523 | // all the jobs have been sent to hive, but non are to query any more (all finished or failed)
|
---|
524 | this.stopResultsPollingPending = true;
|
---|
525 | }
|
---|
526 | } while (!this.stopResultsPollingPending);
|
---|
527 | }
|
---|
528 | catch (ThreadInterruptedException) {
|
---|
529 | // thread has been interuppted
|
---|
530 | }
|
---|
531 | catch (Exception e) {
|
---|
532 | LogMessage("Result Polling Thread failed badly: " + e.Message);
|
---|
533 | }
|
---|
534 | finally {
|
---|
535 | this.IsPollingResults = false;
|
---|
536 | }
|
---|
537 | }
|
---|
538 |
|
---|
539 | #endregion
|
---|
540 |
|
---|
541 | #region Snapshots
|
---|
542 |
|
---|
543 | //private void UpdateSnapshot(ResponseObject<SerializedJob> response) {
|
---|
544 | // JobItem jobItem = jobItems.Single(x => x.JobDto.Id == response.Obj.JobInfo.Id);
|
---|
545 | // jobItem.LatestSnapshot = response;
|
---|
546 | //}
|
---|
547 |
|
---|
548 | //public void RequestSnapshot(Guid jobId) {
|
---|
549 | // Thread t = new Thread(() => {
|
---|
550 | // IClientFacade clientFacade = null;
|
---|
551 | // try {
|
---|
552 | // clientFacade = CreateStreamedClientFacade();
|
---|
553 |
|
---|
554 | // ResponseObject<SerializedJob> response;
|
---|
555 | // int retryCount = 0;
|
---|
556 |
|
---|
557 | // Response snapShotResponse = clientFacade.RequestSnapshot(jobId);
|
---|
558 | // if (snapShotResponse.StatusMessage == ResponseStatus.RequestSnapshot_JobIsNotBeeingCalculated) {
|
---|
559 | // // job already finished
|
---|
560 | // Logger.Debug("HiveExperiment: Abort - GetLastResult(false)");
|
---|
561 | // response = clientFacade.GetLastSerializedResult(jobId, false, false);
|
---|
562 | // Logger.Debug("HiveExperiment: Abort - Server: " + response.StatusMessage);
|
---|
563 | // } else {
|
---|
564 | // // server sent snapshot request to client
|
---|
565 | // // poll until snapshot is ready
|
---|
566 | // do {
|
---|
567 | // Thread.Sleep(snapshotPollingIntervalMs);
|
---|
568 | // Logger.Debug("HiveExperiment: Abort - GetLastResult(true)");
|
---|
569 | // response = clientFacade.GetLastSerializedResult(jobId, false, true);
|
---|
570 | // Logger.Debug("HiveExperiment: Abort - Server: " + response.StatusMessage);
|
---|
571 | // retryCount++;
|
---|
572 | // // loop while
|
---|
573 | // // 1. problem with communication with server
|
---|
574 | // // 2. job result not yet ready
|
---|
575 | // } while (
|
---|
576 | // (retryCount < maxSnapshotRetries) && (
|
---|
577 | // response.StatusMessage == ResponseStatus.GetLastSerializedResult_JobResultNotYetThere)
|
---|
578 | // );
|
---|
579 | // }
|
---|
580 | // if (response.StatusMessage == ResponseStatus.Ok) {
|
---|
581 | // LogMessage(jobId, "Snapshot polling successfull for job " + jobId);
|
---|
582 | // //UpdateSnapshot(response);
|
---|
583 | // } else {
|
---|
584 | // LogMessage(jobId, "Error: Polling of Snapshot failed for job " + jobId + ": " + response.StatusMessage);
|
---|
585 | // }
|
---|
586 | // }
|
---|
587 | // catch (Exception e) {
|
---|
588 | // LogMessage("RequestSnapshot Thread failed badly: " + e.Message);
|
---|
589 | // Logger.Error("RequestSnapshot Thread failed badly: " + e.Message);
|
---|
590 | // }
|
---|
591 | // finally {
|
---|
592 | // ServiceLocator.DisposeClientFacade(clientFacade);
|
---|
593 | // }
|
---|
594 | // });
|
---|
595 | // t.Start();
|
---|
596 | //}
|
---|
597 |
|
---|
598 | //void JobItem_SnapshotRequestedStateChanged(object sender, EventArgs e) {
|
---|
599 | // JobItem jobItem = (JobItem)sender;
|
---|
600 | // if (jobItem.SnapshotRequestedState == SnapshotRequestedState.Requested) {
|
---|
601 | // RequestSnapshot(jobItem.JobDto.Id);
|
---|
602 | // }
|
---|
603 | //}
|
---|
604 |
|
---|
605 | #endregion
|
---|
606 |
|
---|
607 | #region Eventhandler
|
---|
608 |
|
---|
609 | public event EventHandler ExecutionTimeChanged;
|
---|
610 | private void OnExecutionTimeChanged() {
|
---|
611 | EventHandler handler = ExecutionTimeChanged;
|
---|
612 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
613 | }
|
---|
614 |
|
---|
615 | public event EventHandler ExecutionStateChanged;
|
---|
616 | private void OnExecutionStateChanged() {
|
---|
617 | LogMessage("ExecutionState changed to " + executionState.ToString());
|
---|
618 | EventHandler handler = ExecutionStateChanged;
|
---|
619 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
620 | }
|
---|
621 |
|
---|
622 | public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
|
---|
623 |
|
---|
624 | public event EventHandler Started;
|
---|
625 | private void OnStarted() {
|
---|
626 | LogMessage("Started");
|
---|
627 | timer.Start();
|
---|
628 | EventHandler handler = Started;
|
---|
629 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
630 | }
|
---|
631 |
|
---|
632 | public event EventHandler Stopped;
|
---|
633 | private void OnStopped() {
|
---|
634 | timer.Stop();
|
---|
635 | LogMessage("Stopped");
|
---|
636 | EventHandler handler = Stopped;
|
---|
637 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
638 | }
|
---|
639 |
|
---|
640 | public event EventHandler Paused;
|
---|
641 | private void OnPaused() {
|
---|
642 | timer.Stop();
|
---|
643 | LogMessage("Paused");
|
---|
644 | EventHandler handler = Paused;
|
---|
645 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
646 | }
|
---|
647 |
|
---|
648 | public event EventHandler Prepared;
|
---|
649 | protected virtual void OnPrepared() {
|
---|
650 | LogMessage("Prepared");
|
---|
651 | EventHandler handler = Prepared;
|
---|
652 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
653 | }
|
---|
654 |
|
---|
655 | public event EventHandler ResourceIdsChanged;
|
---|
656 | protected virtual void OnResourceIdsChanged() {
|
---|
657 | EventHandler handler = ResourceIdsChanged;
|
---|
658 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
659 | }
|
---|
660 |
|
---|
661 | public event EventHandler ExperimentChanged;
|
---|
662 | protected virtual void OnExperimentChanged() {
|
---|
663 | LogMessage("Experiment changed");
|
---|
664 | EventHandler handler = ExperimentChanged;
|
---|
665 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
666 | }
|
---|
667 |
|
---|
668 | public event EventHandler RootJobChanged;
|
---|
669 | private void OnRootJobChanged() {
|
---|
670 | EventHandler handler = RootJobChanged;
|
---|
671 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
672 | }
|
---|
673 |
|
---|
674 | public event EventHandler RootJobItemChanged;
|
---|
675 | private void OnRootJobItemChanged() {
|
---|
676 | EventHandler handler = RootJobItemChanged;
|
---|
677 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
678 | }
|
---|
679 |
|
---|
680 | public event EventHandler IsResultsPollingChanged;
|
---|
681 | private void OnIsPollingResultsChanged() {
|
---|
682 | if (this.IsPollingResults) {
|
---|
683 | LogMessage("Results Polling Started");
|
---|
684 | timer.Start();
|
---|
685 | } else {
|
---|
686 | LogMessage("Results Polling Stopped");
|
---|
687 | timer.Stop();
|
---|
688 | }
|
---|
689 | EventHandler handler = IsResultsPollingChanged;
|
---|
690 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
691 | }
|
---|
692 |
|
---|
693 | void HiveExperiment_RootJobChanged(object sender, EventArgs e) {
|
---|
694 | this.Experiment = (Optimization.Experiment)((ExperimentJob)rootJobItem.Job).Optimizer;
|
---|
695 | }
|
---|
696 |
|
---|
697 | void rootJobItem_FinalResultAvailable(object sender, EventArgs e) {
|
---|
698 | this.Experiment = (Optimization.Experiment)((ExperimentJob)rootJobItem.Job).Optimizer;
|
---|
699 | }
|
---|
700 | #endregion
|
---|
701 |
|
---|
702 | #region Logging
|
---|
703 | private void LogMessage(string message) {
|
---|
704 | // HeuristicLab.Log is not Thread-Safe, so lock on every call
|
---|
705 | lock (locker) {
|
---|
706 | log.LogMessage(message);
|
---|
707 | Logger.Debug(message);
|
---|
708 | }
|
---|
709 | }
|
---|
710 |
|
---|
711 | private void LogMessage(Guid jobId, string message) {
|
---|
712 | //GetJobItemById(jobId).LogMessage(message);
|
---|
713 | LogMessage(message + " (jobId: " + jobId + ")");
|
---|
714 | }
|
---|
715 |
|
---|
716 | #endregion
|
---|
717 |
|
---|
718 | /// <summary>
|
---|
719 | /// Downloads the root job from hive and sets the experiment, rootJob and rootJobItem
|
---|
720 | /// </summary>
|
---|
721 | public void LoadExperimentFromHive() {
|
---|
722 | using (Disposable<IClientFacade> service = ServiceLocator.Instance.StreamedClientFacadePool.GetService()) {
|
---|
723 | ResponseObject<SerializedJob> response = service.Obj.GetLastSerializedResult(RootJobItem.JobDto.Id);
|
---|
724 | IJob job = XmlParser.Deserialize<IJob>(new MemoryStream(response.Obj.SerializedJobData));
|
---|
725 | RootJob = job;
|
---|
726 | RootJobItem.JobDto = response.Obj.JobInfo;
|
---|
727 | this.Experiment = (Optimization.Experiment)((OptimizerJob)job).Optimizer;
|
---|
728 | if (rootJobItem.JobDto.State == JobState.Finished) {
|
---|
729 | // set execution time and finish up
|
---|
730 | } else if (rootJobItem.JobDto.State != JobState.Aborted && rootJobItem.JobDto.State != JobState.Failed) {
|
---|
731 | this.ExecutionState = Core.ExecutionState.Started;
|
---|
732 | }
|
---|
733 | }
|
---|
734 | }
|
---|
735 | }
|
---|
736 | }
|
---|