Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive/3.4/HiveClient.cs @ 6490

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

#1233

  • minor fix
File size: 22.6 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.Security.Cryptography;
28using System.Threading;
29using System.Threading.Tasks;
30using HeuristicLab.Common;
31using HeuristicLab.Core;
32using HeuristicLab.PluginInfrastructure;
33
34namespace HeuristicLab.Clients.Hive {
35  [Item("HiveClient", "Hive client.")]
36  public sealed class HiveClient : IContent {
37    private static HiveClient instance;
38    public static HiveClient Instance {
39      get {
40        if (instance == null) instance = new HiveClient();
41        return instance;
42      }
43    }
44
45    #region Properties
46    private ItemCollection<RefreshableHiveExperiment> hiveExperiments;
47    public ItemCollection<RefreshableHiveExperiment> HiveExperiments {
48      get { return hiveExperiments; }
49      set {
50        if (value != hiveExperiments) {
51          hiveExperiments = value;
52          OnHiveExperimentsChanged();
53        }
54      }
55    }
56
57    private List<Plugin> onlinePlugins;
58    public List<Plugin> OnlinePlugins {
59      get { return onlinePlugins; }
60      set { onlinePlugins = value; }
61    }
62
63    private List<Plugin> alreadyUploadedPlugins;
64    public List<Plugin> AlreadyUploadedPlugins {
65      get { return alreadyUploadedPlugins; }
66      set { alreadyUploadedPlugins = value; }
67    }
68
69    private bool isAllowedPrivileged;
70    public bool IsAllowedPrivileged {
71      get { return isAllowedPrivileged; }
72      set { isAllowedPrivileged = value; }
73    }
74    #endregion
75
76    public HiveClient() { }
77
78    #region Refresh
79    public void Refresh() {
80      OnRefreshing();
81
82      try {
83        this.IsAllowedPrivileged = ServiceLocator.Instance.CallHiveService((s) => s.IsAllowedPrivileged());
84
85        var oldExperiments = hiveExperiments ?? new ItemCollection<RefreshableHiveExperiment>();
86        hiveExperiments = new HiveItemCollection<RefreshableHiveExperiment>();
87        var experimentsLoaded = ServiceLocator.Instance.CallHiveService<IEnumerable<HiveExperiment>>(s => s.GetHiveExperiments());
88
89        foreach (var he in experimentsLoaded) {
90          var hiveExperiment = oldExperiments.SingleOrDefault(x => x.Id == he.Id);
91          if (hiveExperiment == null) {
92            // new
93            hiveExperiments.Add(new RefreshableHiveExperiment(he) { IsAllowedPrivileged = this.isAllowedPrivileged });
94          } else {
95            // update
96            hiveExperiment.HiveExperiment = he;
97            hiveExperiment.IsAllowedPrivileged = this.isAllowedPrivileged;
98            hiveExperiments.Add(hiveExperiment);
99          }
100        }
101        // remove those which were not in the list of loaded hiveexperiments
102        foreach (var experiment in oldExperiments) {
103          if (experiment.Id == Guid.Empty) {
104            // experiment not uploaded... keep
105            hiveExperiments.Add(experiment);
106          } else {
107            experiment.RefreshAutomatically = false; // stop results polling
108          }
109        }
110      }
111      catch {
112        hiveExperiments = null;
113        throw;
114      }
115      finally {
116        OnRefreshed();
117      }
118    }
119    public void RefreshAsync(Action<Exception> exceptionCallback) {
120      var call = new Func<Exception>(delegate() {
121        try {
122          Refresh();
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 Store
137    public static void Store(IHiveItem item, CancellationToken cancellationToken) {
138      if (item.Id == Guid.Empty) {
139        if (item is RefreshableHiveExperiment) {
140          HiveClient.Instance.UploadExperiment((RefreshableHiveExperiment)item, cancellationToken);
141        }
142        if (item is HiveExperimentPermission) {
143          var hep = (HiveExperimentPermission)item;
144          hep.GrantedUserId = ServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
145          if (hep.GrantedUserId == Guid.Empty) {
146            throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
147          }
148          ServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.HiveExperimentId, hep.GrantedUserId, hep.Permission));
149        }
150      } else {
151        if (item is HiveExperiment)
152          ServiceLocator.Instance.CallHiveService(s => s.UpdateHiveExperiment((HiveExperiment)item));
153      }
154    }
155    public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
156      var call = new Func<Exception>(delegate() {
157        try {
158          Store(item, cancellationToken);
159        }
160        catch (Exception ex) {
161          return ex;
162        }
163        return null;
164      });
165      call.BeginInvoke(delegate(IAsyncResult result) {
166        Exception ex = call.EndInvoke(result);
167        if (ex != null) exceptionCallback(ex);
168      }, null);
169    }
170    #endregion
171
172    #region Delete
173    public static void Delete(IHiveItem item) {
174      if (item.Id == Guid.Empty)
175        return;
176
177      if (item is HiveExperiment)
178        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(item.Id));
179      if (item is RefreshableHiveExperiment)
180        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(item.Id));
181      if (item is HiveExperimentPermission) {
182        var hep = (HiveExperimentPermission)item;
183        ServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.HiveExperimentId, hep.GrantedUserId));
184      }
185      item.Id = Guid.Empty;
186    }
187    #endregion
188
189    #region Events
190    public event EventHandler Refreshing;
191    private void OnRefreshing() {
192      EventHandler handler = Refreshing;
193      if (handler != null) handler(this, EventArgs.Empty);
194    }
195    public event EventHandler Refreshed;
196    private void OnRefreshed() {
197      var handler = Refreshed;
198      if (handler != null) handler(this, EventArgs.Empty);
199    }
200    public event EventHandler HiveExperimentsChanged;
201    private void OnHiveExperimentsChanged() {
202      var handler = HiveExperimentsChanged;
203      if (handler != null) handler(this, EventArgs.Empty);
204    }
205    #endregion
206
207    public static void StartExperiment(Action<Exception> exceptionCallback, RefreshableHiveExperiment refreshableHiveExperiment, CancellationToken cancellationToken) {
208      HiveClient.StoreAsync(
209        new Action<Exception>((Exception ex) => {
210          refreshableHiveExperiment.ExecutionState = ExecutionState.Prepared;
211          exceptionCallback(ex);
212        }), refreshableHiveExperiment, cancellationToken);
213      refreshableHiveExperiment.ExecutionState = ExecutionState.Started;
214    }
215
216    public static void PauseExperiment(RefreshableHiveExperiment refreshableHiveExperiment) {
217      ServiceLocator.Instance.CallHiveService(service => {
218        foreach (HiveJob job in refreshableHiveExperiment.GetAllHiveJobs()) {
219          if (job.Job.State != JobState.Finished && job.Job.State != JobState.Aborted && job.Job.State != JobState.Failed)
220            service.PauseJob(job.Job.Id);
221        }
222      });
223      refreshableHiveExperiment.ExecutionState = ExecutionState.Paused;
224    }
225
226    public static void StopExperiment(RefreshableHiveExperiment refreshableHiveExperiment) {
227      ServiceLocator.Instance.CallHiveService(service => {
228        foreach (HiveJob job in refreshableHiveExperiment.GetAllHiveJobs()) {
229          if (job.Job.State != JobState.Finished && job.Job.State != JobState.Aborted && job.Job.State != JobState.Failed)
230            service.StopJob(job.Job.Id);
231        }
232      });
233      // execution state does not need to be set. it will be set to Stopped, when all jobs have been downloaded
234    }
235
236    #region Upload Experiment
237    private Semaphore jobUploadSemaphore = new Semaphore(4, 4); // todo: take magic number into config
238    private static object jobCountLocker = new object();
239    private static object pluginLocker = new object();
240    private void UploadExperiment(RefreshableHiveExperiment refreshableHiveExperiment, CancellationToken cancellationToken) {
241      try {
242        refreshableHiveExperiment.Progress = new Progress("Connecting to server...");
243        refreshableHiveExperiment.IsProgressing = true;
244
245        IEnumerable<string> resourceNames = ToResourceNameList(refreshableHiveExperiment.HiveExperiment.ResourceNames);
246        var resourceIds = new List<Guid>();
247        foreach (var resourceName in resourceNames) {
248          Guid resourceId = ServiceLocator.Instance.CallHiveService((s) => s.GetResourceId(resourceName));
249          if (resourceId == Guid.Empty) {
250            throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
251          }
252          resourceIds.Add(resourceId);
253        }
254
255        foreach (OptimizerHiveJob hiveJob in refreshableHiveExperiment.HiveJobs.OfType<OptimizerHiveJob>()) {
256          hiveJob.SetIndexInParentOptimizerList(null);
257        }
258
259        // upload HiveExperiment
260        refreshableHiveExperiment.Progress.Status = "Uploading HiveExperiment...";
261        refreshableHiveExperiment.HiveExperiment.Id = ServiceLocator.Instance.CallHiveService((s) => s.AddHiveExperiment(refreshableHiveExperiment.HiveExperiment));
262        bool isPrivileged = refreshableHiveExperiment.HiveExperiment.IsPrivileged;
263        refreshableHiveExperiment.HiveExperiment = ServiceLocator.Instance.CallHiveService((s) => s.GetHiveExperiment(refreshableHiveExperiment.HiveExperiment.Id)); // update owner and permissions
264        refreshableHiveExperiment.HiveExperiment.IsPrivileged = isPrivileged;
265        cancellationToken.ThrowIfCancellationRequested();
266
267        int totalJobCount = refreshableHiveExperiment.GetAllHiveJobs().Count();
268        int[] jobCount = new int[1]; // use a reference type (int-array) instead of value type (int) in order to pass the value via a delegate to task-parallel-library
269        cancellationToken.ThrowIfCancellationRequested();
270
271        // upload plugins
272        refreshableHiveExperiment.Progress.Status = "Uploading plugins...";
273        this.OnlinePlugins = ServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
274        this.AlreadyUploadedPlugins = new List<Plugin>();
275        Plugin configFilePlugin = ServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
276        this.alreadyUploadedPlugins.Add(configFilePlugin);
277        cancellationToken.ThrowIfCancellationRequested();
278
279        if (refreshableHiveExperiment.RefreshAutomatically) refreshableHiveExperiment.StartResultPolling();
280
281        // upload jobs
282        refreshableHiveExperiment.Progress.Status = "Uploading jobs...";
283
284        var tasks = new List<Task>();
285        foreach (HiveJob hiveJob in refreshableHiveExperiment.HiveJobs) {
286          tasks.Add(Task.Factory.StartNew((hj) => {
287            UploadJobWithChildren(refreshableHiveExperiment.Progress, (HiveJob)hj, null, resourceIds, jobCount, totalJobCount, configFilePlugin.Id, refreshableHiveExperiment.HiveExperiment.Id, refreshableHiveExperiment.Log, refreshableHiveExperiment.HiveExperiment.IsPrivileged, cancellationToken);
288          }, hiveJob)
289          .ContinueWith((x) => refreshableHiveExperiment.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted));
290        }
291        try {
292          Task.WaitAll(tasks.ToArray());
293        }
294        catch (AggregateException ae) {
295          if (!ae.InnerExceptions.All(e => e is TaskCanceledException)) throw ae; // for some reason the WaitAll throws a AggregateException containg a TaskCanceledException. i don't know where it comes from, however the tasks all finish properly, so for now just ignore it
296        }
297        refreshableHiveExperiment.HiveExperiment.Modified = false;
298      }
299      finally {
300        refreshableHiveExperiment.IsProgressing = false;
301      }
302    }
303
304    /// <summary>
305    /// Uploads the local configuration file as plugin
306    /// </summary>
307    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
308      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HeuristicLab 3.3.exe");
309      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
310      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
311      byte[] hash;
312
313      byte[] data = File.ReadAllBytes(configFilePath);
314      using (SHA1 sha1 = SHA1.Create()) {
315        hash = sha1.ComputeHash(data);
316      }
317
318      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
319      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
320
321      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
322
323      if (onlineConfig.Count() > 0) {
324        return onlineConfig.First();
325      } else {
326        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
327        return configPlugin;
328      }
329    }
330
331    /// <summary>
332    /// Uploads the given job and all its child-jobs while setting the proper parentJobId values for the childs
333    /// </summary>
334    /// <param name="parentHiveJob">shall be null if its the root job</param>
335    private void UploadJobWithChildren(IProgress progress, HiveJob hiveJob, HiveJob parentHiveJob, IEnumerable<Guid> groups, int[] jobCount, int totalJobCount, Guid configPluginId, Guid hiveExperimentId, ILog log, bool isPrivileged, CancellationToken cancellationToken) {
336      jobUploadSemaphore.WaitOne();
337      bool semaphoreReleased = false;
338      try {
339        cancellationToken.ThrowIfCancellationRequested();
340        lock (jobCountLocker) {
341          jobCount[0]++;
342        }
343        JobData jobData;
344        List<IPluginDescription> plugins;
345
346        if (hiveJob.ItemJob.ComputeInParallel && (hiveJob.ItemJob.Item is Optimization.Experiment || hiveJob.ItemJob.Item is Optimization.BatchRun)) {
347          hiveJob.Job.IsParentJob = true;
348          hiveJob.Job.FinishWhenChildJobsFinished = true;
349          jobData = hiveJob.GetAsJobData(true, out plugins);
350        } else {
351          hiveJob.Job.IsParentJob = false;
352          hiveJob.Job.FinishWhenChildJobsFinished = false;
353          jobData = hiveJob.GetAsJobData(false, out plugins);
354        }
355        cancellationToken.ThrowIfCancellationRequested();
356
357        TryAndRepeat(() => {
358          if (!cancellationToken.IsCancellationRequested) {
359            lock (pluginLocker) {
360              ServiceLocator.Instance.CallHiveService((s) => hiveJob.Job.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
361            }
362          }
363        }, -1, "Failed to upload plugins");
364        cancellationToken.ThrowIfCancellationRequested();
365        hiveJob.Job.PluginsNeededIds.Add(configPluginId);
366        hiveJob.Job.HiveExperimentId = hiveExperimentId;
367        hiveJob.Job.IsPrivileged = isPrivileged;
368
369        log.LogMessage(string.Format("Uploading job ({0} kb, {1} objects)", jobData.Data.Count() / 1024, hiveJob.ItemJob.GetObjectGraphObjects().Count()));
370        TryAndRepeat(() => {
371          if (!cancellationToken.IsCancellationRequested) {
372            if (parentHiveJob != null) {
373              hiveJob.Job.Id = ServiceLocator.Instance.CallHiveService((s) => s.AddChildJob(parentHiveJob.Job.Id, hiveJob.Job, jobData));
374            } else {
375              hiveJob.Job.Id = ServiceLocator.Instance.CallHiveService((s) => s.AddJob(hiveJob.Job, jobData, groups.ToList()));
376            }
377          }
378        }, 50, "Failed to add job", log);
379        cancellationToken.ThrowIfCancellationRequested();
380
381        lock (jobCountLocker) {
382          progress.ProgressValue = (double)jobCount[0] / totalJobCount;
383          progress.Status = string.Format("Uploaded job ({0} of {1})", jobCount[0], totalJobCount);
384        }
385
386        var tasks = new List<Task>();
387        foreach (HiveJob child in hiveJob.ChildHiveJobs) {
388          tasks.Add(Task.Factory.StartNew((tuple) => {
389            var arguments = (Tuple<HiveJob, HiveJob>)tuple;
390            UploadJobWithChildren(progress, arguments.Item1, arguments.Item2, groups, jobCount, totalJobCount, configPluginId, hiveExperimentId, log, isPrivileged, cancellationToken);
391          }, new Tuple<HiveJob, HiveJob>(child, hiveJob))
392          .ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted));
393        }
394        jobUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
395        try {
396          Task.WaitAll(tasks.ToArray());
397        }
398        catch (AggregateException ae) {
399          if (!ae.InnerExceptions.All(e => e is TaskCanceledException)) throw ae; // for some reason the WaitAll throws a AggregateException containg a TaskCanceledException. i don't know where it comes from, however the tasks all finish properly, so for now just ignore it
400        }
401      }
402      finally {
403        if (!semaphoreReleased) jobUploadSemaphore.Release();
404      }
405    }
406    #endregion
407
408    #region Download Experiment
409    public static void LoadExperiment(RefreshableHiveExperiment refreshableHiveExperiment) {
410      var hiveExperiment = refreshableHiveExperiment.HiveExperiment;
411      refreshableHiveExperiment.Progress = new Progress();
412
413      try {
414        refreshableHiveExperiment.IsProgressing = true;
415        int totalJobCount = 0;
416        IEnumerable<LightweightJob> allJobs;
417
418        refreshableHiveExperiment.Progress.Status = "Connecting to Server...";
419        // fetch all Job objects to create the full tree of tree of HiveJob objects
420        refreshableHiveExperiment.Progress.Status = "Downloading list of jobs...";
421        allJobs = ServiceLocator.Instance.CallHiveService(s => s.GetLightweightExperimentJobs(hiveExperiment.Id));
422        totalJobCount = allJobs.Count();
423
424        HiveJobDownloader downloader = new HiveJobDownloader(allJobs.Select(x => x.Id));
425        downloader.StartAsync();
426
427        while (!downloader.IsFinished) {
428          refreshableHiveExperiment.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
429          refreshableHiveExperiment.Progress.Status = string.Format("Downloading/deserializing jobs... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
430          Thread.Sleep(500);
431
432          if (downloader.IsFaulted) {
433            throw downloader.Exception;
434          }
435        }
436        IDictionary<Guid, HiveJob> allHiveJobs = downloader.Results;
437
438        refreshableHiveExperiment.HiveJobs = new ItemCollection<HiveJob>(allHiveJobs.Values.Where(x => !x.Job.ParentJobId.HasValue));
439
440        if (refreshableHiveExperiment.IsFinished()) {
441          refreshableHiveExperiment.ExecutionState = Core.ExecutionState.Stopped;
442        } else {
443          refreshableHiveExperiment.ExecutionState = Core.ExecutionState.Started;
444        }
445
446        // build child-job tree
447        foreach (HiveJob hiveJob in refreshableHiveExperiment.HiveJobs) {
448          BuildHiveJobTree(hiveJob, allJobs, allHiveJobs);
449        }
450
451        refreshableHiveExperiment.OnLoaded();
452      }
453      finally {
454        refreshableHiveExperiment.IsProgressing = false;
455      }
456    }
457
458    private static void BuildHiveJobTree(HiveJob parentHiveJob, IEnumerable<LightweightJob> allJobs, IDictionary<Guid, HiveJob> allHiveJobs) {
459      IEnumerable<LightweightJob> childJobs = from job in allJobs
460                                              where job.ParentJobId.HasValue && job.ParentJobId.Value == parentHiveJob.Job.Id
461                                              orderby job.DateCreated ascending
462                                              select job;
463      foreach (LightweightJob job in childJobs) {
464        HiveJob childHiveJob = allHiveJobs[job.Id];
465        parentHiveJob.AddChildHiveJob(childHiveJob);
466        BuildHiveJobTree(childHiveJob, allJobs, allHiveJobs);
467      }
468    }
469    #endregion
470
471    /// <summary>
472    /// Converts a string which can contain Ids separated by ';' to a enumerable
473    /// </summary>
474    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
475      if (!string.IsNullOrEmpty(resourceNames)) {
476        return resourceNames.Split(';');
477      } else {
478        return new List<string>();
479      }
480    }
481
482    public static ItemJob LoadItemJob(Guid jobId) {
483      JobData jobData = ServiceLocator.Instance.CallHiveService(s => s.GetJobData(jobId));
484      try {
485        return PersistenceUtil.Deserialize<ItemJob>(jobData.Data);
486      }
487      catch {
488        return null;
489      }
490    }
491
492    /// <summary>
493    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
494    /// If repetitions is -1, it is repeated infinitely.
495    /// </summary>
496    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
497      while (true) {
498        try { action(); return; }
499        catch (Exception e) {
500          if (repetitions == 0) throw new HiveException(errorMessage, e);
501          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
502          repetitions--;
503        }
504      }
505    }
506
507    public static HiveItemCollection<HiveExperimentPermission> GetHiveExperimentPermissions(Guid hiveExperimentId) {
508      return ServiceLocator.Instance.CallHiveService((service) => {
509        IEnumerable<HiveExperimentPermission> heps = service.GetHiveExperimentPermissions(hiveExperimentId);
510        foreach (var hep in heps) {
511          hep.GrantedUserName = service.GetUsernameByUserId(hep.GrantedUserId);
512        }
513        return new HiveItemCollection<HiveExperimentPermission>(heps);
514      });
515    }
516  }
517}
Note: See TracBrowser for help on using the repository browser.