Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive/3.4/ExperimentManager/HiveJob.cs @ 6372

Last change on this file since 6372 was 6372, checked in by ascheibe, 13 years ago

#1233 changed year to 2011

File size: 15.4 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.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.PluginInfrastructure;
32
33namespace HeuristicLab.Clients.Hive {
34
35  [Item("Hive Job", "Represents a hive job.")]
36  [StorableClass]
37  public class HiveJob : NamedItem, IItemTree<HiveJob> {
38    protected static object locker = new object();
39
40    public override Image ItemImage {
41      get {
42        if (job.Id == Guid.Empty) { // not yet uploaded
43          return HeuristicLab.Common.Resources.VSImageLibrary.Event;
44        } else {
45          if (job.State == JobState.Waiting) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
46          else if (job.State == JobState.Calculating) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
47          else if (job.State == JobState.Transferring) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
48          else if (job.State == JobState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
49          else if (job.State == JobState.Aborted) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
50          else if (job.State == JobState.Failed) return HeuristicLab.Common.Resources.VSImageLibrary.Error;
51          else if (job.State == JobState.Finished) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
52          else return HeuristicLab.Common.Resources.VSImageLibrary.Event;
53        }
54      }
55    }
56
57    [Storable]
58    protected Job job;
59    public Job Job {
60      get { return job; }
61      set {
62        if (job != value) {
63          DeregisterJobEvents();
64          job = value;
65          RegisterJobEvents();
66          IsFinishedJobDownloaded = false;
67          OnJobChanged();
68          OnToStringChanged();
69          OnItemImageChanged();
70        }
71
72      }
73    }
74
75    [Storable]
76    protected ItemJob itemJob;
77    public ItemJob ItemJob {
78      get { return itemJob; }
79      internal set {
80        if (itemJob != null && syncJobsWithOptimizers) {
81          this.childHiveJobs.Clear();
82        }
83        if (itemJob != value) {
84          DergisterItemJobEvents();
85          itemJob = value;
86          RegisterItemJobEvents();
87          OnItemJobChanged();
88          IsFinishedJobDownloaded = true;
89        }
90      }
91    }
92
93    // job downloaded since last status change
94    [Storable]
95    private bool isFinishedJobDownloaded = false;
96    public bool IsFinishedJobDownloaded {
97      get { return isFinishedJobDownloaded; }
98      set {
99        if (value != isFinishedJobDownloaded) {
100          this.isFinishedJobDownloaded = value;
101          OnIsFinishedJobDownloadedChanged();
102        }
103      }
104    }
105
106    public bool IsDownloading { get; set; }
107
108    [Storable]
109    protected ItemList<HiveJob> childHiveJobs;
110    public virtual ReadOnlyItemList<HiveJob> ChildHiveJobs {
111      get { return childHiveJobs.AsReadOnly(); }
112    }
113
114    [Storable]
115    protected bool syncJobsWithOptimizers = true;
116
117    #region Constructors and Cloning
118    public HiveJob() {
119      this.Job = new Job() {
120        CoresNeeded = 1,
121        MemoryNeeded = 0
122      };
123      job.State = JobState.Offline;
124      this.childHiveJobs = new ItemList<HiveJob>();
125      syncJobsWithOptimizers = true;
126      RegisterChildHiveJobEvents();
127    }
128
129    public HiveJob(ItemJob itemJob, bool autoCreateChildHiveJobs)
130      : this() {
131      this.syncJobsWithOptimizers = autoCreateChildHiveJobs;
132      this.ItemJob = itemJob;
133      this.syncJobsWithOptimizers = true;
134    }
135
136    public HiveJob(Job job, JobData jobData, bool autoCreateChildHiveJobs) {
137      this.syncJobsWithOptimizers = autoCreateChildHiveJobs;
138      this.Job = job;
139      try {
140        this.ItemJob = PersistenceUtil.Deserialize<ItemJob>(jobData.Data);
141      }
142      catch {
143        this.ItemJob = null;
144      }
145      this.childHiveJobs = new ItemList<HiveJob>();
146      this.syncJobsWithOptimizers = true;
147      RegisterChildHiveJobEvents();
148    }
149
150    protected HiveJob(HiveJob original, Cloner cloner)
151      : base(original, cloner) {
152      this.Job = cloner.Clone(original.job);
153      this.ItemJob = cloner.Clone(original.ItemJob);
154      this.childHiveJobs = cloner.Clone(original.childHiveJobs);
155      this.syncJobsWithOptimizers = original.syncJobsWithOptimizers;
156      this.isFinishedJobDownloaded = original.isFinishedJobDownloaded;
157    }
158    public override IDeepCloneable Clone(Cloner cloner) {
159      return new HiveJob(this, cloner);
160    }
161    #endregion
162
163    protected virtual void UpdateChildHiveJobs() { }
164
165    protected virtual void RegisterItemJobEvents() {
166      if (ItemJob != null) {
167        ItemJob.ComputeInParallelChanged += new EventHandler(ItemJob_ComputeInParallelChanged);
168        ItemJob.ToStringChanged += new EventHandler(ItemJob_ToStringChanged);
169      }
170    }
171    protected virtual void DergisterItemJobEvents() {
172      if (ItemJob != null) {
173        ItemJob.ComputeInParallelChanged -= new EventHandler(ItemJob_ComputeInParallelChanged);
174        ItemJob.ToStringChanged -= new EventHandler(ItemJob_ToStringChanged);
175      }
176    }
177
178    protected virtual void RegisterChildHiveJobEvents() {
179      this.childHiveJobs.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<HiveJob>>(OnItemsAdded);
180      this.childHiveJobs.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<HiveJob>>(OnItemsRemoved);
181      this.childHiveJobs.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<HiveJob>>(OnCollectionReset);
182    }
183    protected virtual void DeregisterChildHiveJobEvents() {
184      this.childHiveJobs.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<HiveJob>>(OnItemsAdded);
185      this.childHiveJobs.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<HiveJob>>(OnItemsRemoved);
186      this.childHiveJobs.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<HiveJob>>(OnCollectionReset);
187    }
188
189    protected virtual void ItemJob_ToStringChanged(object sender, EventArgs e) {
190      this.OnToStringChanged();
191    }
192
193    protected virtual void ItemJob_ComputeInParallelChanged(object sender, EventArgs e) {
194      if (ItemJob != null && syncJobsWithOptimizers) {
195        this.UpdateChildHiveJobs();
196      }
197    }
198
199    public virtual void AddChildHiveJob(HiveJob hiveJob) {
200      this.childHiveJobs.Add(hiveJob);
201    }
202
203    public override string ToString() {
204      if (itemJob != null && itemJob.Item != null) {
205        return itemJob.ToString();
206      } else {
207        return Job.Id.ToString();
208      }
209    }
210
211    public virtual void UpdateFromLightweightJob(LightweightJob lightweightJob) {
212      if (lightweightJob != null) {
213        job.Id = lightweightJob.Id;
214        job.ParentJobId = lightweightJob.ParentJobId;
215        job.ExecutionTime = lightweightJob.ExecutionTime;
216        job.State = lightweightJob.State;
217        job.StateLog = new List<StateLog>(lightweightJob.StateLog);
218        job.Command = lightweightJob.Command;
219
220        OnJobStateChanged();
221        OnToStringChanged();
222        OnItemImageChanged();
223      }
224    }
225
226    /// <summary>
227    /// Creates a JobData object containing the Job and the IJob-Object as byte[]
228    /// </summary>
229    /// <param name="withoutChildOptimizers">
230    ///   if true the Child-Optimizers will not be serialized (if the job contains an Experiment)
231    /// </param>
232    public virtual JobData GetAsJobData(bool withoutChildOptimizers, out List<IPluginDescription> plugins) {
233      plugins = new List<IPluginDescription>();
234      if (this.itemJob == null)
235        return null;
236
237      IEnumerable<Type> usedTypes;
238      byte[] jobByteArray = PersistenceUtil.Serialize(this.ItemJob, out usedTypes);
239
240      JobData jobData = new JobData() {
241        JobId = job.Id,
242        Data = jobByteArray
243      };
244
245      PluginUtil.CollectDeclaringPlugins(plugins, usedTypes);
246
247      return jobData;
248    }
249
250    #region Events
251    public event EventHandler JobChanged;
252    private void OnJobChanged() {
253      EventHandler handler = JobChanged;
254      if (handler != null) handler(this, EventArgs.Empty);
255    }
256
257    public event EventHandler JobStateChanged;
258    private void OnJobStateChanged() {
259      EventHandler handler = JobStateChanged;
260      if (handler != null) handler(this, EventArgs.Empty);
261    }
262
263    public event EventHandler ItemJobChanged;
264    private void OnItemJobChanged() {
265      ItemJob_ComputeInParallelChanged(this, EventArgs.Empty);
266      var handler = ItemJobChanged;
267      if (handler != null) handler(this, EventArgs.Empty);
268    }
269
270    public event EventHandler IsFinishedJobDownloadedChanged;
271    private void OnIsFinishedJobDownloadedChanged() {
272      var handler = IsFinishedJobDownloadedChanged;
273      if (handler != null) handler(this, EventArgs.Empty);
274    }
275
276    private void RegisterJobEvents() {
277      if (job != null)
278        job.PropertyChanged += new PropertyChangedEventHandler(job_PropertyChanged);
279    }
280
281    private void DeregisterJobEvents() {
282      if (job != null)
283        job.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(job_PropertyChanged);
284    }
285
286    private void job_PropertyChanged(object sender, PropertyChangedEventArgs e) {
287      if (e.PropertyName == "State") {
288        IsFinishedJobDownloaded = false;
289      }
290    }
291    #endregion
292
293    /// <summary>
294    /// Returns a list of HiveJobs including this and all its child-jobs recursively
295    /// </summary>
296    public IEnumerable<HiveJob> GetAllHiveJobs() {
297      var jobs = new List<HiveJob>();
298      jobs.Add(this);
299      foreach (HiveJob child in this.ChildHiveJobs) {
300        jobs.AddRange(child.GetAllHiveJobs());
301      }
302      return jobs;
303    }
304
305    public HiveJob GetParentByJobId(Guid jobId) {
306      if (this.ChildHiveJobs.SingleOrDefault(j => j.job.Id == jobId) != null)
307        return this;
308      foreach (HiveJob child in this.childHiveJobs) {
309        HiveJob result = child.GetParentByJobId(jobId);
310        if (result != null)
311          return result;
312      }
313      return null;
314    }
315
316    /// <summary>
317    /// Searches for an HiveJob object with the correct jobId recursively
318    /// </summary>
319    public HiveJob GetHiveJobByJobId(Guid jobId) {
320      if (this.Job.Id == jobId) {
321        return this;
322      } else {
323        foreach (HiveJob child in this.ChildHiveJobs) {
324          HiveJob result = child.GetHiveJobByJobId(jobId);
325          if (result != null)
326            return result;
327        }
328      }
329      return null;
330    }
331
332    public void RemoveByJobId(Guid jobId) {
333      IEnumerable<HiveJob> jobs = ChildHiveJobs.Where(j => j.Job.Id == jobId).ToList(); // if Guid.Empty needs to be removed, there could be more than one with this jobId
334      foreach (HiveJob j in jobs) {
335        this.childHiveJobs.Remove(j);
336      }
337      foreach (HiveJob child in ChildHiveJobs) {
338        child.RemoveByJobId(jobId);
339      }
340    }
341
342    public IEnumerable<IItemTree<HiveJob>> GetChildItems() {
343      return this.childHiveJobs;
344    }
345
346    #region INotifyObservableCollectionItemsChanged<IItemTree> Members
347
348    public event CollectionItemsChangedEventHandler<IItemTree<HiveJob>> CollectionReset;
349    private void OnCollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<HiveJob>> e) {
350      var handler = CollectionReset;
351      if (handler != null) handler(this, ToCollectionItemsChangedEventArgs(e));
352    }
353
354    public event CollectionItemsChangedEventHandler<IItemTree<HiveJob>> ItemsAdded;
355    private void OnItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<HiveJob>> e) {
356      var handler = ItemsAdded;
357      if (handler != null) handler(this, ToCollectionItemsChangedEventArgs(e));
358    }
359
360    public event CollectionItemsChangedEventHandler<IItemTree<HiveJob>> ItemsRemoved;
361    private void OnItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<HiveJob>> e) {
362      var handler = ItemsRemoved;
363      if (handler != null) handler(this, ToCollectionItemsChangedEventArgs(e));
364    }
365
366    private static CollectionItemsChangedEventArgs<IItemTree<HiveJob>> ToCollectionItemsChangedEventArgs(CollectionItemsChangedEventArgs<IndexedItem<HiveJob>> e) {
367      return new CollectionItemsChangedEventArgs<IItemTree<HiveJob>>(e.Items.Select(x => x.Value), e.OldItems == null ? null : e.OldItems.Select(x => x.Value));
368    }
369    #endregion
370
371    public void Pause() {
372      if (this.Job.IsParentJob) {
373        foreach (var child in ChildHiveJobs) {
374          ServiceLocator.Instance.CallHiveService(s => s.PauseJob(child.job.Id));
375        }
376      } else {
377        ServiceLocator.Instance.CallHiveService(s => s.PauseJob(this.job.Id));
378      }
379    }
380
381    public void Stop() {
382      if (this.Job.IsParentJob) {
383        foreach (var child in ChildHiveJobs) {
384          ServiceLocator.Instance.CallHiveService(s => s.StopJob(child.job.Id));
385        }
386      } else {
387        ServiceLocator.Instance.CallHiveService(s => s.StopJob(this.job.Id));
388      }
389    }
390
391    public void Restart() {
392      ServiceLocator.Instance.CallHiveService(service => {
393        JobData jobData = new JobData();
394        jobData.JobId = this.job.Id;
395        jobData.Data = PersistenceUtil.Serialize(this.itemJob);
396        service.UpdateJobData(this.Job, jobData);
397        service.RestartJob(this.job.Id);
398        Job job = service.GetJob(this.job.Id);
399        this.job.LastJobDataUpdate = job.LastJobDataUpdate;
400      });
401    }
402
403    public ICollection<IItemTreeNodeAction<HiveJob>> Actions {
404      get {
405        return new List<IItemTreeNodeAction<HiveJob>>();
406      }
407    }
408
409    public virtual void IntegrateChild(ItemJob job, Guid childJobId) { }
410
411    /// <summary>
412    /// Delete ItemJob
413    /// </summary>
414    public void ClearData() {
415      this.ItemJob.Item = null;
416    }
417  }
418
419  [Item("Hive Job", "Represents a hive job.")]
420  [StorableClass]
421  public class HiveJob<T> : HiveJob where T : ItemJob {
422
423    public new T ItemJob {
424      get { return (T)base.ItemJob; }
425      internal set { base.ItemJob = value; }
426    }
427
428    #region Constructors and Cloning
429    public HiveJob() : base() { }
430    public HiveJob(T itemJob) : base(itemJob, true) { }
431    protected HiveJob(HiveJob original, Cloner cloner)
432      : base(original, cloner) {
433    }
434    public override IDeepCloneable Clone(Cloner cloner) {
435      return new HiveJob<T>(this, cloner);
436    }
437    #endregion
438  }
439}
Note: See TracBrowser for help on using the repository browser.