Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive/3.4/ExperimentManager/RefreshableHiveExperiment.cs @ 6219

Last change on this file since 6219 was 6219, checked in by cneumuel, 13 years ago

#1233

  • improved exception handling for hive experiments
File size: 16.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.ComponentModel;
25using System.Drawing;
26using System.Linq;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Hive;
30
31namespace HeuristicLab.Clients.Hive {
32  public class RefreshableHiveExperiment : IHiveItem, IDeepCloneable, IContent, IProgressReporter {
33    private JobResultPoller jobResultPoller;
34    private ConcurrentJobDownloader<ItemJob> jobDownloader;
35    private static object locker = new object();
36
37    private HiveExperiment hiveExperiment;
38    public HiveExperiment HiveExperiment {
39      get { return hiveExperiment; }
40      set {
41        if (value != hiveExperiment) {
42          if (value == null)
43            throw new ArgumentNullException();
44
45          if (hiveExperiment != null) DergisterHiveExperimentEvents();
46          hiveExperiment = value;
47          if (hiveExperiment != null) RegisterHiveExperimentEvents();
48          OnHiveExperimentChanged();
49        }
50      }
51    }
52
53    /** include jobs when refreshing **/
54    private bool includeJobs;
55    public bool IncludeJobs {
56      get { return includeJobs; }
57      set { includeJobs = value; }
58    }
59
60    private bool refreshAutomatically;
61    public bool RefreshAutomatically {
62      get { return refreshAutomatically; }
63      set {
64        lock (locker) {
65          if (refreshAutomatically != value) {
66            refreshAutomatically = value;
67            OnRefreshAutomaticallyChanged();
68          }
69          if (RefreshAutomatically) {
70            if (hiveExperiment.HiveJobs != null && hiveExperiment.HiveJobs.Count > 0 && (jobResultPoller == null || !jobResultPoller.IsPolling)) {
71              StartResultPolling();
72            }
73          } else {
74            StopResultPolling();
75          }
76        }
77      }
78    }
79
80    // if true, all control buttons should be enabled. otherwise disabled (used for HiveEngine)
81    private bool isControllable = true;
82    public bool IsControllable {
83      get { return isControllable; }
84      set {
85        if (value != isControllable) {
86          isControllable = value;
87          OnIsControllableChanged();
88        }
89      }
90    }
91
92    private ILog log;
93    public ILog Log {
94      get { return log; }
95      set { log = value; }
96    }
97    private static object logLocker = new object();
98   
99
100    #region Constructors and Cloning
101    public RefreshableHiveExperiment() {
102      this.includeJobs = true;
103      this.refreshAutomatically = true;
104      this.HiveExperiment = new HiveExperiment();
105      this.log = new Log();
106      this.jobDownloader = new ConcurrentJobDownloader<ItemJob>(2, 2);
107      this.jobDownloader.ExceptionOccured += new EventHandler<EventArgs<Exception>>(jobDownloader_ExceptionOccured);
108    }
109    public RefreshableHiveExperiment(HiveExperiment hiveExperiment) {
110      this.includeJobs = true;
111      this.refreshAutomatically = true;
112      this.HiveExperiment = hiveExperiment;
113      this.log = new Log();
114      this.jobDownloader = new ConcurrentJobDownloader<ItemJob>(2, 2);
115      this.jobDownloader.ExceptionOccured += new EventHandler<EventArgs<Exception>>(jobDownloader_ExceptionOccured);
116    }
117    protected RefreshableHiveExperiment(RefreshableHiveExperiment original, Cloner cloner) {
118      cloner.RegisterClonedObject(original, this);
119      this.HiveExperiment = original.HiveExperiment;
120      this.IncludeJobs = original.IncludeJobs;
121      this.IsControllable = original.IsControllable;
122      this.Log = cloner.Clone(original.Log);
123      this.RefreshAutomatically = false; // do not start results polling automatically
124      this.jobDownloader = new ConcurrentJobDownloader<ItemJob>(2, 2);
125      this.jobDownloader.ExceptionOccured += new EventHandler<EventArgs<Exception>>(jobDownloader_ExceptionOccured);
126    }
127    public IDeepCloneable Clone(Cloner cloner) {
128      return new RefreshableHiveExperiment(this, cloner);
129    }
130    public object Clone() {
131      return this.Clone(new Cloner());
132    }
133    #endregion
134
135    private void hiveExperiment_HiveJobsChanged(object sender, EventArgs e) {
136      if (jobResultPoller != null && jobResultPoller.IsPolling) {
137        jobResultPoller.Stop();
138        DeregisterResultPollingEvents();
139      }
140      if (hiveExperiment.HiveJobs != null && hiveExperiment.HiveJobs.Count > 0 && hiveExperiment.GetAllHiveJobs().All(x => x.Job.Id != Guid.Empty)) {
141        if (this.RefreshAutomatically)
142          StartResultPolling();
143      }
144    }
145
146    #region JobResultPoller Events
147
148    public void StartResultPolling() {
149      if (jobResultPoller == null) {
150        jobResultPoller = new JobResultPoller(hiveExperiment.Id, /*ApplicationConstants.ResultPollingInterval*/new TimeSpan(0, 0, 5)); //TODO: find a better place for ApplicationConstants
151        RegisterResultPollingEvents();
152        jobResultPoller.AutoResumeOnException = !IsControllable;
153      }
154
155      if (!jobResultPoller.IsPolling) {
156        jobResultPoller.Start();
157      }
158    }
159
160    public void StopResultPolling() {
161      if (jobResultPoller != null && jobResultPoller.IsPolling) {
162        jobResultPoller.Stop();
163      }
164    }
165
166    private void RegisterResultPollingEvents() {
167      jobResultPoller.ExceptionOccured += new EventHandler<EventArgs<Exception>>(jobResultPoller_ExceptionOccured);
168      jobResultPoller.JobResultsReceived += new EventHandler<EventArgs<IEnumerable<LightweightJob>>>(jobResultPoller_JobResultReceived);
169      jobResultPoller.IsPollingChanged += new EventHandler(jobResultPoller_IsPollingChanged);
170    }
171    private void DeregisterResultPollingEvents() {
172      jobResultPoller.ExceptionOccured -= new EventHandler<EventArgs<Exception>>(jobResultPoller_ExceptionOccured);
173      jobResultPoller.JobResultsReceived -= new EventHandler<EventArgs<IEnumerable<LightweightJob>>>(jobResultPoller_JobResultReceived);
174      jobResultPoller.IsPollingChanged -= new EventHandler(jobResultPoller_IsPollingChanged);
175    }
176    private void jobResultPoller_IsPollingChanged(object sender, EventArgs e) {
177      this.refreshAutomatically = jobResultPoller.IsPolling;
178      OnRefreshAutomaticallyChanged();
179    }
180    private void jobResultPoller_JobResultReceived(object sender, EventArgs<IEnumerable<LightweightJob>> e) {
181      foreach (LightweightJob lightweightJob in e.Value) {
182        HiveJob hiveJob = GetHiveJobById(lightweightJob.Id);
183        if (hiveJob != null) {
184          // lastJobDataUpdate equals DateTime.MinValue right after it was uploaded. When the first results are polled, this value is updated
185          if (hiveJob.Job.State == JobState.Offline && lightweightJob.State != JobState.Finished && lightweightJob.State != JobState.Failed && lightweightJob.State != JobState.Aborted) {
186            hiveJob.Job.LastJobDataUpdate = lightweightJob.LastJobDataUpdate;
187          }
188
189          hiveJob.UpdateFromLightweightJob(lightweightJob);
190
191          if (!hiveJob.IsFinishedJobDownloaded && !hiveJob.IsDownloading && hiveJob.Job.LastJobDataUpdate < lightweightJob.LastJobDataUpdate) {
192            LogMessage(string.Format("Downloading job {0}", lightweightJob.Id));
193            hiveJob.IsDownloading = true;
194            jobDownloader.DownloadJob(hiveJob.Job, (localJob, itemJob) => {
195              LogMessage(string.Format("Finished downloading job {0}", localJob.Id));
196              HiveJob localHiveJob = GetHiveJobById(localJob.Id);
197
198              if (itemJob == null) {
199                localHiveJob.IsDownloading = false;
200              }
201
202              if (itemJob == null) {
203                // something bad happened to this job. bad job, BAAAD job!
204              } else {
205                // if the job is paused, download but don't integrate into parent optimizer (to avoid Prepare)
206
207                if (localJob.State == JobState.Paused) {
208                  localHiveJob.ItemJob = itemJob;
209                } else {
210                  if (localJob.ParentJobId.HasValue) {
211                    HiveJob parentHiveJob = GetHiveJobById(localJob.ParentJobId.Value);
212                    parentHiveJob.IntegrateChild(itemJob, localJob.Id);
213                  } else {
214                    localHiveJob.ItemJob = itemJob;
215                  }
216                }
217                localHiveJob.IsDownloading = false;
218                localHiveJob.Job.LastJobDataUpdate = localJob.LastJobDataUpdate;
219              }
220            });
221          }
222        }
223      }
224      GC.Collect(); // force GC, because .NET is too lazy here (deserialization takes a lot of memory)
225      if (AllJobsFinished()) {
226        hiveExperiment.ExecutionState = Core.ExecutionState.Stopped;
227        StopResultPolling();
228      }
229      UpdateTotalExecutionTime();
230      UpdateStatistics();
231    }
232
233    // synchronized logging
234    private void LogException(Exception exception) {
235      lock (logLocker) {
236        this.log.LogException(exception);
237      }
238    }
239    // synchronized logging
240    private void LogMessage(string message) {
241      lock (logLocker) {
242        this.log.LogMessage(message);
243      }
244    }
245
246    public HiveJob GetHiveJobById(Guid jobId) {
247      foreach (HiveJob job in hiveExperiment.HiveJobs) {
248        var hj = job.GetHiveJobByJobId(jobId);
249        if (hj != null)
250          return hj;
251      }
252      return null;
253    }
254    private void UpdateStatistics() {
255      var jobs = hiveExperiment.GetAllHiveJobs();
256      hiveExperiment.JobCount = jobs.Count();
257      hiveExperiment.CalculatingCount = jobs.Count(j => j.Job.State == JobState.Calculating);
258      hiveExperiment.FinishedCount = jobs.Count(j => j.Job.State == JobState.Finished);
259      OnJobStatisticsChanged();
260    }
261
262    public bool AllJobsFinished() {
263      return hiveExperiment.GetAllHiveJobs().All(j => (j.Job.State == JobState.Finished
264                                                   || j.Job.State == JobState.Aborted
265                                                   || j.Job.State == JobState.Failed)
266                                                   && j.IsFinishedJobDownloaded);
267    }
268
269    private void jobResultPoller_ExceptionOccured(object sender, EventArgs<Exception> e) {
270      OnExceptionOccured(e.Value);
271    }
272    private void jobDownloader_ExceptionOccured(object sender, EventArgs<Exception> e) {
273      OnExceptionOccured(e.Value);
274    }
275    public void UpdateTotalExecutionTime() {
276      hiveExperiment.ExecutionTime = TimeSpan.FromMilliseconds(hiveExperiment.GetAllHiveJobs().Sum(x => x.Job.ExecutionTime.HasValue ? x.Job.ExecutionTime.Value.TotalMilliseconds : 0));
277    }
278    #endregion
279
280    private void RegisterHiveExperimentEvents() {
281      hiveExperiment.HiveJobsChanged += new EventHandler(hiveExperiment_HiveJobsChanged);
282      hiveExperiment.ToStringChanged += new EventHandler(hiveExperiment_ToStringChanged);
283      hiveExperiment.PropertyChanged += new PropertyChangedEventHandler(hiveExperiment_PropertyChanged);
284      hiveExperiment.ItemImageChanged += new EventHandler(hiveExperiment_ItemImageChanged);
285      hiveExperiment.ModifiedChanged += new EventHandler(hiveExperiment_ModifiedChanged);
286      hiveExperiment.IsProgressingChanged += new EventHandler(hiveExperiment_IsProgressingChanged);
287      hiveExperiment.Loaded += new EventHandler(hiveExperiment_Loaded);
288    }
289
290    private void DergisterHiveExperimentEvents() {
291      hiveExperiment.HiveJobsChanged -= new EventHandler(hiveExperiment_HiveJobsChanged);
292      hiveExperiment.ToStringChanged -= new EventHandler(hiveExperiment_ToStringChanged);
293      hiveExperiment.PropertyChanged -= new PropertyChangedEventHandler(hiveExperiment_PropertyChanged);
294      hiveExperiment.ItemImageChanged -= new EventHandler(hiveExperiment_ItemImageChanged);
295      hiveExperiment.ModifiedChanged -= new EventHandler(hiveExperiment_ModifiedChanged);
296      hiveExperiment.IsProgressingChanged -= new EventHandler(hiveExperiment_IsProgressingChanged);
297      hiveExperiment.Loaded -= new EventHandler(hiveExperiment_Loaded);
298    }
299
300    private void hiveExperiment_Loaded(object sender, EventArgs e) {
301      this.UpdateTotalExecutionTime();
302
303      if (hiveExperiment.ExecutionState != ExecutionState.Stopped) {
304        this.RefreshAutomatically = true;
305      }
306    }
307
308    #region Events
309    public event EventHandler RefreshAutomaticallyChanged;
310    private void OnRefreshAutomaticallyChanged() {
311      var handler = RefreshAutomaticallyChanged;
312      if (handler != null) handler(this, EventArgs.Empty);
313    }
314
315    public event EventHandler HiveExperimentChanged;
316    private void OnHiveExperimentChanged() {
317      var handler = HiveExperimentChanged;
318      if (handler != null) handler(this, EventArgs.Empty);
319    }
320
321    public event EventHandler ModifiedChanged;
322    private void hiveExperiment_ModifiedChanged(object sender, EventArgs e) {
323      var handler = ModifiedChanged;
324      if (handler != null) handler(sender, e);
325    }
326
327    public event EventHandler ItemImageChanged;
328    private void hiveExperiment_ItemImageChanged(object sender, EventArgs e) {
329      var handler = ItemImageChanged;
330      if (handler != null) handler(this, e);
331    }
332
333    public event PropertyChangedEventHandler PropertyChanged;
334    private void hiveExperiment_PropertyChanged(object sender, PropertyChangedEventArgs e) {
335      var handler = PropertyChanged;
336      if (handler != null) handler(sender, e);
337    }
338
339    public event EventHandler ToStringChanged;
340    private void hiveExperiment_ToStringChanged(object sender, EventArgs e) {
341      var handler = ToStringChanged;
342      if (handler != null) handler(this, e);
343    }
344
345    public event EventHandler IsProgressingChanged;
346    private void hiveExperiment_IsProgressingChanged(object sender, EventArgs e) {
347      var handler = IsProgressingChanged;
348      if (handler != null) handler(sender, e);
349    }
350
351    public event EventHandler IsControllableChanged;
352    private void OnIsControllableChanged() {
353      var handler = IsControllableChanged;
354      if (handler != null) handler(this, EventArgs.Empty);
355    }
356
357    public event EventHandler JobStatisticsChanged;
358    private void OnJobStatisticsChanged() {
359      var handler = JobStatisticsChanged;
360      if (handler != null) handler(this, EventArgs.Empty);
361    }
362
363    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
364    private void OnExceptionOccured(Exception exception) {
365      LogException(exception);
366      var handler = ExceptionOccured;
367      if (handler != null) handler(this, new EventArgs<Exception>(exception));
368    }
369    #endregion
370
371    public Guid Id {
372      get { return hiveExperiment.Id; }
373      set { hiveExperiment.Id = value; }
374    }
375    public bool Modified {
376      get { return hiveExperiment.Modified; }
377    }
378    public void Store() {
379      hiveExperiment.Store();
380    }
381    public string ItemDescription {
382      get { return hiveExperiment.ItemDescription; }
383    }
384    public Image ItemImage {
385      get { return hiveExperiment.ItemImage; }
386    }
387    public string ItemName {
388      get { return hiveExperiment.ItemName; }
389    }
390    public Version ItemVersion {
391      get { return hiveExperiment.ItemVersion; }
392    }
393
394
395    #region IProgressReporter Members
396    public IProgress Progress {
397      get { return HiveExperiment.Progress; }
398    }
399
400    public bool IsProgressing {
401      get { return HiveExperiment.IsProgressing; }
402    }
403    #endregion
404
405    public override string ToString() {
406      return HiveExperiment.ToString();
407    }
408  }
409}
Note: See TracBrowser for help on using the repository browser.