Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1233

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