Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive/3.4/ExperimentManager/ExperimentManagerClient.cs @ 6178

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

#1233

  • added semaphores to ensure an appdomain is never unloaded when the start method has not finished
  • HiveEngine uploading and downloading of jobs works and is displayed in the view
File size: 15.5 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.Configuration;
25using System.IO;
26using System.Linq;
27using System.Threading;
28using HeuristicLab.Clients.Hive.ExperimentManager;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Hive;
32using HeuristicLab.PluginInfrastructure;
33
34namespace HeuristicLab.Clients.Hive {
35  // todo: rename from ExpMgrClient to ExperimentManagerClient
36  [Item("ExperimentManagerClient", "Hive experiment manager client.")]
37  public sealed class ExperimentManagerClient : IContent {
38    private static ExperimentManagerClient instance;
39    public static ExperimentManagerClient Instance {
40      get {
41        if (instance == null) instance = new ExperimentManagerClient();
42        return instance;
43      }
44    }
45
46    #region Properties
47    private ItemCollection<RefreshableHiveExperiment> hiveExperiments;
48    public ItemCollection<RefreshableHiveExperiment> HiveExperiments {
49      get { return hiveExperiments; }
50      set {
51        if (value != hiveExperiments) {
52          hiveExperiments = value;
53          OnHiveExperimentsChanged();
54        }
55      }
56    }
57   
58    private List<Plugin> onlinePlugins;
59    public List<Plugin> OnlinePlugins {
60      get { return onlinePlugins; }
61      set { onlinePlugins = value; }
62    }
63
64    private List<Plugin> alreadyUploadedPlugins;
65    public List<Plugin> AlreadyUploadedPlugins {
66      get { return alreadyUploadedPlugins; }
67      set { alreadyUploadedPlugins = value; }
68    }
69    #endregion
70
71    public ExperimentManagerClient() { }
72
73    #region Refresh
74    public void Refresh() {
75      OnRefreshing();
76
77      try {
78        hiveExperiments = new HiveItemCollection<RefreshableHiveExperiment>();
79        var he = ServiceLocator.Instance.CallHiveService<IEnumerable<HiveExperiment>>(s => s.GetHiveExperiments());
80        hiveExperiments.AddRange(he.Select(x => new RefreshableHiveExperiment(x)).OrderBy(x => x.HiveExperiment.Name));
81      }
82      catch {
83        hiveExperiments = null;
84        throw;
85      }
86      finally {
87        OnRefreshed();
88      }
89    }
90    public void RefreshAsync(Action<Exception> exceptionCallback) {
91      var call = new Func<Exception>(delegate() {
92        try {
93          Refresh();
94        }
95        catch (Exception ex) {
96          return ex;
97        }
98        return null;
99      });
100      call.BeginInvoke(delegate(IAsyncResult result) {
101        Exception ex = call.EndInvoke(result);
102        if (ex != null) exceptionCallback(ex);
103      }, null);
104    }
105    #endregion
106
107    #region Store
108    public static void Store(IHiveItem item) {
109      if (item.Id == Guid.Empty) {
110        if (item is RefreshableHiveExperiment) {
111          ExperimentManagerClient.Instance.UploadExperiment((RefreshableHiveExperiment)item);
112        }
113      } else {
114
115        if (item is HiveExperiment)
116          ServiceLocator.Instance.CallHiveService(s => s.UpdateHiveExperiment((HiveExperiment)item));
117      }
118    }
119    public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item) {
120      var call = new Func<Exception>(delegate() {
121        try {
122          Store(item);
123        }
124        catch (Exception ex) {
125          return ex;
126        }
127        return null;
128      });
129      call.BeginInvoke(delegate(IAsyncResult result) {
130        Exception ex = call.EndInvoke(result);
131        if (ex != null) exceptionCallback(ex);
132      }, null);
133    }
134    #endregion
135
136    #region Delete
137    public static void Delete(IHiveItem item) {
138      if (item is HiveExperiment)
139        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(item.Id));
140      if (item is RefreshableHiveExperiment)
141        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(item.Id));
142      item.Id = Guid.Empty;
143    }
144    #endregion
145
146    #region Events
147    public event EventHandler Refreshing;
148    private void OnRefreshing() {
149      EventHandler handler = Refreshing;
150      if (handler != null) handler(this, EventArgs.Empty);
151    }
152    public event EventHandler Refreshed;
153    private void OnRefreshed() {
154      var handler = Refreshed;
155      if (handler != null) handler(this, EventArgs.Empty);
156    }
157    public event EventHandler HiveExperimentsChanged;
158    private void OnHiveExperimentsChanged() {
159      var handler = HiveExperimentsChanged;
160      if (handler != null) handler(this, EventArgs.Empty);
161    }
162    #endregion
163
164    public static void StartExperiment(Action<Exception> exceptionCallback, RefreshableHiveExperiment refreshableHiveExperiment) {
165      ExperimentManagerClient.StoreAsync(
166        new Action<Exception>((Exception ex) => {
167          refreshableHiveExperiment.HiveExperiment.ExecutionState = ExecutionState.Prepared;
168          exceptionCallback(ex);
169        }), refreshableHiveExperiment);
170      refreshableHiveExperiment.HiveExperiment.ExecutionState = ExecutionState.Started;
171    }
172
173    public static void PauseExperiment(HiveExperiment hiveExperiment) {
174      ServiceLocator.Instance.CallHiveService(service => {
175        foreach (HiveJob job in hiveExperiment.GetAllHiveJobs()) {
176          if (job.Job.State != JobState.Finished && job.Job.State != JobState.Aborted && job.Job.State != JobState.Failed)
177            service.PauseJob(job.Job.Id);
178        }
179      });
180      hiveExperiment.ExecutionState = ExecutionState.Paused;
181    }
182
183    public static void StopExperiment(HiveExperiment hiveExperiment) {
184      ServiceLocator.Instance.CallHiveService(service => {
185        foreach (HiveJob job in hiveExperiment.GetAllHiveJobs()) {
186          if (job.Job.State != JobState.Finished && job.Job.State != JobState.Aborted && job.Job.State != JobState.Failed)
187            service.StopJob(job.Job.Id);
188        }
189      });
190      // execution state does not need to be set. it will be set to Stopped, when all jobs have been downloaded
191    }
192
193    #region Upload Experiment
194    private void UploadExperiment(RefreshableHiveExperiment optimizerHiveExperiment) {
195      try {
196        optimizerHiveExperiment.HiveExperiment.Progress = new Progress("Connecting to server...");
197        optimizerHiveExperiment.HiveExperiment.IsProgressing = true;
198        ServiceLocator.Instance.CallHiveService(service => {
199          IEnumerable<string> resourceNames = ToResourceNameList(optimizerHiveExperiment.HiveExperiment.ResourceNames);
200          var resourceIds = new List<Guid>();
201          foreach (var resourceName in resourceNames) {
202            Guid resourceId = service.GetResourceId(resourceName);
203            if (resourceId == Guid.Empty) {
204              throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
205            }
206            resourceIds.Add(resourceId);
207          }
208
209          foreach (OptimizerHiveJob hiveJob in optimizerHiveExperiment.HiveExperiment.HiveJobs.OfType<OptimizerHiveJob>()) {
210            hiveJob.SetIndexInParentOptimizerList(null);
211          }
212
213          // upload HiveExperiment
214          optimizerHiveExperiment.HiveExperiment.Progress.Status = "Uploading HiveExperiment...";
215          optimizerHiveExperiment.HiveExperiment.Id = service.AddHiveExperiment(optimizerHiveExperiment.HiveExperiment);
216
217          int totalJobCount = optimizerHiveExperiment.HiveExperiment.GetAllHiveJobs().Count();
218          int jobCount = 0;
219
220          // upload plugins
221          optimizerHiveExperiment.HiveExperiment.Progress.Status = "Uploading plugins...";
222          this.OnlinePlugins = service.GetPlugins();
223          this.AlreadyUploadedPlugins = new List<Plugin>();
224          Plugin configFilePlugin = UploadConfigurationFile(service);
225          this.alreadyUploadedPlugins.Add(configFilePlugin);
226
227          // upload jobs
228          optimizerHiveExperiment.HiveExperiment.Progress.Status = "Uploading jobs...";
229
230          foreach (HiveJob hiveJob in optimizerHiveExperiment.HiveExperiment.HiveJobs) {
231            UploadJobWithChildren(optimizerHiveExperiment.HiveExperiment.Progress, service, hiveJob, null, resourceIds, ref jobCount, totalJobCount, configFilePlugin.Id, optimizerHiveExperiment.HiveExperiment.UseLocalPlugins, optimizerHiveExperiment.HiveExperiment.Id);
232          }
233
234          if (optimizerHiveExperiment.RefreshAutomatically) optimizerHiveExperiment.StartResultPolling();
235        });
236      }
237      finally {
238        optimizerHiveExperiment.HiveExperiment.IsProgressing = false;
239      }
240    }
241
242    /// <summary>
243    /// Uploads the local configuration file as plugin
244    /// </summary>
245    private static Plugin UploadConfigurationFile(IHiveService service) {
246      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HeuristicLab 3.3.exe");
247      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
248      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
249
250      Plugin configPlugin = new Plugin() {
251        Name = "Configuration",
252        IsLocal = true,
253        Version = new Version()
254      };
255      PluginData configFile = new PluginData() {
256        FileName = configFileName,
257        Data = File.ReadAllBytes(configFilePath)
258      };
259      configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
260      return configPlugin;
261    }
262
263    /// <summary>
264    /// Uploads the given job and all its child-jobs while setting the proper parentJobId values for the childs
265    /// </summary>
266    /// <param name="service"></param>
267    /// <param name="hiveJob"></param>
268    /// <param name="parentHiveJob">shall be null if its the root job</param>
269    /// <param name="groups"></param>
270    private void UploadJobWithChildren(IProgress progress, IHiveService service, HiveJob hiveJob, HiveJob parentHiveJob, IEnumerable<Guid> groups, ref int jobCount, int totalJobCount, Guid configPluginId, bool useLocalPlugins, Guid hiveExperimentId) {
271      jobCount++;
272      progress.Status = string.Format("Serializing job {0} of {1}", jobCount, totalJobCount);
273      JobData jobData;
274      List<IPluginDescription> plugins;
275
276      if (hiveJob.ItemJob.ComputeInParallel &&
277        (hiveJob.ItemJob.Item is Optimization.Experiment || hiveJob.ItemJob.Item is Optimization.BatchRun)) {
278        hiveJob.Job.IsParentJob = true;
279        hiveJob.Job.FinishWhenChildJobsFinished = true;
280        hiveJob.ItemJob.CollectChildJobs = false; // don't collect child-jobs on slaves
281        jobData = hiveJob.GetAsJobData(true, out plugins);
282      } else {
283        hiveJob.Job.IsParentJob = false;
284        hiveJob.Job.FinishWhenChildJobsFinished = false;
285        jobData = hiveJob.GetAsJobData(false, out plugins);
286      }
287
288      hiveJob.Job.PluginsNeededIds = PluginUtil.GetPluginDependencies(service, this.onlinePlugins, this.alreadyUploadedPlugins, plugins, useLocalPlugins);
289      hiveJob.Job.PluginsNeededIds.Add(configPluginId);
290      hiveJob.Job.HiveExperimentId = hiveExperimentId;
291
292      progress.Status = string.Format("Uploading job {0} of {1} ({2} kb)", jobCount, totalJobCount, jobData.Data.Count() / 1024);
293      progress.ProgressValue = (double)jobCount / totalJobCount;
294
295      if (parentHiveJob != null) {
296        hiveJob.Job.Id = service.AddChildJob(parentHiveJob.Job.Id, hiveJob.Job, jobData);
297      } else {
298        hiveJob.Job.Id = service.AddJob(hiveJob.Job, jobData, groups.ToList());
299      }
300
301      foreach (HiveJob child in hiveJob.ChildHiveJobs) {
302        UploadJobWithChildren(progress, service, child, hiveJob, groups, ref jobCount, totalJobCount, configPluginId, useLocalPlugins, hiveExperimentId);
303      }
304    }
305    #endregion
306
307    #region Download Experiment
308    public static void LoadExperiment(HiveExperiment hiveExperiment) {
309      hiveExperiment.Progress = new Progress();
310      try {
311        hiveExperiment.IsProgressing = true;
312        int totalJobCount = 0;
313        IEnumerable<LightweightJob> allJobs;
314
315        hiveExperiment.Progress.Status = "Connecting to Server...";
316        // fetch all Job objects to create the full tree of tree of HiveJob objects
317        hiveExperiment.Progress.Status = "Downloading list of jobs...";
318        allJobs = ServiceLocator.Instance.CallHiveService(s => s.GetLightweightExperimentJobs(hiveExperiment.Id));
319        totalJobCount = allJobs.Count();
320
321        HiveJobDownloader downloader = new HiveJobDownloader(allJobs.Select(x => x.Id));
322        downloader.StartAsync();
323
324        while (!downloader.IsFinished) {
325          hiveExperiment.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
326          hiveExperiment.Progress.Status = string.Format("Downloading/deserializing jobs... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
327          Thread.Sleep(500);
328        }
329        IDictionary<Guid, HiveJob> allHiveJobs = downloader.Results;
330
331        hiveExperiment.HiveJobs = new ItemCollection<HiveJob>(allHiveJobs.Values.Where(x => !x.Job.ParentJobId.HasValue));
332
333        if (hiveExperiment.IsFinished()) {
334          hiveExperiment.ExecutionState = Core.ExecutionState.Stopped;
335        } else {
336          hiveExperiment.ExecutionState = Core.ExecutionState.Started;
337        }
338
339        // build child-job tree
340        foreach (HiveJob hiveJob in hiveExperiment.HiveJobs) {
341          BuildHiveJobTree(hiveJob, allJobs, allHiveJobs);
342        }
343
344        hiveExperiment.OnLoaded();
345      }
346      finally {
347        hiveExperiment.IsProgressing = false;
348      }
349    }
350
351    private static void BuildHiveJobTree(HiveJob parentHiveJob, IEnumerable<LightweightJob> allJobs, IDictionary<Guid, HiveJob> allHiveJobs) {
352      IEnumerable<LightweightJob> childJobs = from job in allJobs
353                                              where job.ParentJobId.HasValue && job.ParentJobId.Value == parentHiveJob.Job.Id
354                                              orderby job.DateCreated ascending
355                                              select job;
356      foreach (LightweightJob job in childJobs) {
357        HiveJob childHiveJob = allHiveJobs[job.Id];
358        parentHiveJob.AddChildHiveJob(childHiveJob);
359        BuildHiveJobTree(childHiveJob, allJobs, allHiveJobs);
360      }
361    }
362    #endregion
363
364    /// <summary>
365    /// Converts a string which can contain Ids separated by ';' to a enumerable
366    /// </summary>
367    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
368      if (!string.IsNullOrEmpty(resourceNames)) {
369        return resourceNames.Split(';');
370      } else {
371        return new List<string>();
372      }
373    }
374
375    public static ItemJob LoadItemJob(Guid jobId) {
376      JobData jobData = ServiceLocator.Instance.CallHiveService(s => s.GetJobData(jobId));
377      try {
378        return PersistenceUtil.Deserialize<ItemJob>(jobData.Data);
379      }
380      catch {
381        return null;
382      }
383    }
384  }
385}
Note: See TracBrowser for help on using the repository browser.