Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1233

  • finished experiment sharing
  • added role for executing privileged jobs
  • refreshing experiments in experimentManager does not delete already downloaded jobs
  • moved some properties from HiveExperiment into RefreshableHiveExperiment
File size: 22.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.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 is HiveExperiment)
175        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(item.Id));
176      if (item is RefreshableHiveExperiment)
177        ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(item.Id));
178      if (item is HiveExperimentPermission) {
179        var hep = (HiveExperimentPermission)item;
180        ServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.HiveExperimentId, hep.GrantedUserId));
181      }
182      item.Id = Guid.Empty;
183    }
184    #endregion
185
186    #region Events
187    public event EventHandler Refreshing;
188    private void OnRefreshing() {
189      EventHandler handler = Refreshing;
190      if (handler != null) handler(this, EventArgs.Empty);
191    }
192    public event EventHandler Refreshed;
193    private void OnRefreshed() {
194      var handler = Refreshed;
195      if (handler != null) handler(this, EventArgs.Empty);
196    }
197    public event EventHandler HiveExperimentsChanged;
198    private void OnHiveExperimentsChanged() {
199      var handler = HiveExperimentsChanged;
200      if (handler != null) handler(this, EventArgs.Empty);
201    }
202    #endregion
203
204    public static void StartExperiment(Action<Exception> exceptionCallback, RefreshableHiveExperiment refreshableHiveExperiment, CancellationToken cancellationToken) {
205      HiveClient.StoreAsync(
206        new Action<Exception>((Exception ex) => {
207          refreshableHiveExperiment.ExecutionState = ExecutionState.Prepared;
208          exceptionCallback(ex);
209        }), refreshableHiveExperiment, cancellationToken);
210      refreshableHiveExperiment.ExecutionState = ExecutionState.Started;
211    }
212
213    public static void PauseExperiment(RefreshableHiveExperiment refreshableHiveExperiment) {
214      ServiceLocator.Instance.CallHiveService(service => {
215        foreach (HiveJob job in refreshableHiveExperiment.GetAllHiveJobs()) {
216          if (job.Job.State != JobState.Finished && job.Job.State != JobState.Aborted && job.Job.State != JobState.Failed)
217            service.PauseJob(job.Job.Id);
218        }
219      });
220      refreshableHiveExperiment.ExecutionState = ExecutionState.Paused;
221    }
222
223    public static void StopExperiment(RefreshableHiveExperiment refreshableHiveExperiment) {
224      ServiceLocator.Instance.CallHiveService(service => {
225        foreach (HiveJob job in refreshableHiveExperiment.GetAllHiveJobs()) {
226          if (job.Job.State != JobState.Finished && job.Job.State != JobState.Aborted && job.Job.State != JobState.Failed)
227            service.StopJob(job.Job.Id);
228        }
229      });
230      // execution state does not need to be set. it will be set to Stopped, when all jobs have been downloaded
231    }
232
233    #region Upload Experiment
234    private Semaphore jobUploadSemaphore = new Semaphore(4, 4); // todo: take magic number into config
235    private static object jobCountLocker = new object();
236    private static object pluginLocker = new object();
237    private void UploadExperiment(RefreshableHiveExperiment refreshableHiveExperiment, CancellationToken cancellationToken) {
238      try {
239        refreshableHiveExperiment.Progress = new Progress("Connecting to server...");
240        refreshableHiveExperiment.IsProgressing = true;
241
242        IEnumerable<string> resourceNames = ToResourceNameList(refreshableHiveExperiment.HiveExperiment.ResourceNames);
243        var resourceIds = new List<Guid>();
244        foreach (var resourceName in resourceNames) {
245          Guid resourceId = ServiceLocator.Instance.CallHiveService((s) => s.GetResourceId(resourceName));
246          if (resourceId == Guid.Empty) {
247            throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
248          }
249          resourceIds.Add(resourceId);
250        }
251
252        foreach (OptimizerHiveJob hiveJob in refreshableHiveExperiment.HiveJobs.OfType<OptimizerHiveJob>()) {
253          hiveJob.SetIndexInParentOptimizerList(null);
254        }
255
256        // upload HiveExperiment
257        refreshableHiveExperiment.Progress.Status = "Uploading HiveExperiment...";
258        refreshableHiveExperiment.HiveExperiment.Id = ServiceLocator.Instance.CallHiveService((s) => s.AddHiveExperiment(refreshableHiveExperiment.HiveExperiment));
259        refreshableHiveExperiment.HiveExperiment = ServiceLocator.Instance.CallHiveService((s) => s.GetHiveExperiment(refreshableHiveExperiment.HiveExperiment.Id)); // update owner and permissions
260        cancellationToken.ThrowIfCancellationRequested();
261
262        int totalJobCount = refreshableHiveExperiment.GetAllHiveJobs().Count();
263        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
264        cancellationToken.ThrowIfCancellationRequested();
265
266        // upload plugins
267        refreshableHiveExperiment.Progress.Status = "Uploading plugins...";
268        this.OnlinePlugins = ServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
269        this.AlreadyUploadedPlugins = new List<Plugin>();
270        Plugin configFilePlugin = ServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
271        this.alreadyUploadedPlugins.Add(configFilePlugin);
272        cancellationToken.ThrowIfCancellationRequested();
273
274        if (refreshableHiveExperiment.RefreshAutomatically) refreshableHiveExperiment.StartResultPolling();
275
276        // upload jobs
277        refreshableHiveExperiment.Progress.Status = "Uploading jobs...";
278
279        var tasks = new List<Task>();
280        foreach (HiveJob hiveJob in refreshableHiveExperiment.HiveJobs) {
281          tasks.Add(Task.Factory.StartNew((hj) => {
282            UploadJobWithChildren(refreshableHiveExperiment.Progress, (HiveJob)hj, null, resourceIds, jobCount, totalJobCount, configFilePlugin.Id, refreshableHiveExperiment.HiveExperiment.Id, refreshableHiveExperiment.Log, refreshableHiveExperiment.HiveExperiment.IsPrivileged, cancellationToken);
283          }, hiveJob)
284          .ContinueWith((x) => refreshableHiveExperiment.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted));
285        }
286        try {
287          Task.WaitAll(tasks.ToArray());
288        }
289        catch (AggregateException ae) {
290          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
291        }
292        refreshableHiveExperiment.HiveExperiment.Modified = false;
293      }
294      finally {
295        refreshableHiveExperiment.IsProgressing = false;
296      }
297    }
298
299    /// <summary>
300    /// Uploads the local configuration file as plugin
301    /// </summary>
302    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
303      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HeuristicLab 3.3.exe");
304      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
305      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
306      byte[] hash;
307
308      byte[] data = File.ReadAllBytes(configFilePath);
309      using (SHA1 sha1 = SHA1.Create()) {
310        hash = sha1.ComputeHash(data);
311      }
312
313      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
314      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
315
316      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
317
318      if (onlineConfig.Count() > 0) {
319        return onlineConfig.First();
320      } else {
321        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
322        return configPlugin;
323      }
324    }
325
326    /// <summary>
327    /// Uploads the given job and all its child-jobs while setting the proper parentJobId values for the childs
328    /// </summary>
329    /// <param name="parentHiveJob">shall be null if its the root job</param>
330    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) {
331      jobUploadSemaphore.WaitOne();
332      bool semaphoreReleased = false;
333      try {
334        cancellationToken.ThrowIfCancellationRequested();
335        lock (jobCountLocker) {
336          jobCount[0]++;
337        }
338        JobData jobData;
339        List<IPluginDescription> plugins;
340
341        if (hiveJob.ItemJob.ComputeInParallel && (hiveJob.ItemJob.Item is Optimization.Experiment || hiveJob.ItemJob.Item is Optimization.BatchRun)) {
342          hiveJob.Job.IsParentJob = true;
343          hiveJob.Job.FinishWhenChildJobsFinished = true;
344          jobData = hiveJob.GetAsJobData(true, out plugins);
345        } else {
346          hiveJob.Job.IsParentJob = false;
347          hiveJob.Job.FinishWhenChildJobsFinished = false;
348          jobData = hiveJob.GetAsJobData(false, out plugins);
349        }
350        cancellationToken.ThrowIfCancellationRequested();
351
352        TryAndRepeat(() => {
353          if (!cancellationToken.IsCancellationRequested) {
354            lock (pluginLocker) {
355              ServiceLocator.Instance.CallHiveService((s) => hiveJob.Job.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
356            }
357          }
358        }, -1, "Failed to upload plugins");
359        cancellationToken.ThrowIfCancellationRequested();
360        hiveJob.Job.PluginsNeededIds.Add(configPluginId);
361        hiveJob.Job.HiveExperimentId = hiveExperimentId;
362        hiveJob.Job.IsPrivileged = isPrivileged;
363
364        log.LogMessage(string.Format("Uploading job ({0} kb, {1} objects)", jobData.Data.Count() / 1024, hiveJob.ItemJob.GetObjectGraphObjects().Count()));
365        TryAndRepeat(() => {
366          if (!cancellationToken.IsCancellationRequested) {
367            if (parentHiveJob != null) {
368              hiveJob.Job.Id = ServiceLocator.Instance.CallHiveService((s) => s.AddChildJob(parentHiveJob.Job.Id, hiveJob.Job, jobData));
369            } else {
370              hiveJob.Job.Id = ServiceLocator.Instance.CallHiveService((s) => s.AddJob(hiveJob.Job, jobData, groups.ToList()));
371            }
372          }
373        }, 50, "Failed to add job", log);
374        cancellationToken.ThrowIfCancellationRequested();
375
376        lock (jobCountLocker) {
377          progress.ProgressValue = (double)jobCount[0] / totalJobCount;
378          progress.Status = string.Format("Uploaded job ({0} of {1})", jobCount[0], totalJobCount);
379        }
380
381        var tasks = new List<Task>();
382        foreach (HiveJob child in hiveJob.ChildHiveJobs) {
383          tasks.Add(Task.Factory.StartNew((tuple) => {
384            var arguments = (Tuple<HiveJob, HiveJob>)tuple;
385            UploadJobWithChildren(progress, arguments.Item1, arguments.Item2, groups, jobCount, totalJobCount, configPluginId, hiveExperimentId, log, isPrivileged, cancellationToken);
386          }, new Tuple<HiveJob, HiveJob>(child, hiveJob))
387          .ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted));
388        }
389        jobUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
390        try {
391          Task.WaitAll(tasks.ToArray());
392        }
393        catch (AggregateException ae) {
394          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
395        }
396      }
397      finally {
398        if (!semaphoreReleased) jobUploadSemaphore.Release();
399      }
400    }
401    #endregion
402
403    #region Download Experiment
404    public static void LoadExperiment(RefreshableHiveExperiment refreshableHiveExperiment) {
405      var hiveExperiment = refreshableHiveExperiment.HiveExperiment;
406      refreshableHiveExperiment.Progress = new Progress();
407
408      try {
409        refreshableHiveExperiment.IsProgressing = true;
410        int totalJobCount = 0;
411        IEnumerable<LightweightJob> allJobs;
412
413        refreshableHiveExperiment.Progress.Status = "Connecting to Server...";
414        // fetch all Job objects to create the full tree of tree of HiveJob objects
415        refreshableHiveExperiment.Progress.Status = "Downloading list of jobs...";
416        allJobs = ServiceLocator.Instance.CallHiveService(s => s.GetLightweightExperimentJobs(hiveExperiment.Id));
417        totalJobCount = allJobs.Count();
418
419        HiveJobDownloader downloader = new HiveJobDownloader(allJobs.Select(x => x.Id));
420        downloader.StartAsync();
421
422        while (!downloader.IsFinished) {
423          refreshableHiveExperiment.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
424          refreshableHiveExperiment.Progress.Status = string.Format("Downloading/deserializing jobs... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
425          Thread.Sleep(500);
426
427          if (downloader.IsFaulted) {
428            throw downloader.Exception;
429          }
430        }
431        IDictionary<Guid, HiveJob> allHiveJobs = downloader.Results;
432
433        refreshableHiveExperiment.HiveJobs = new ItemCollection<HiveJob>(allHiveJobs.Values.Where(x => !x.Job.ParentJobId.HasValue));
434
435        if (refreshableHiveExperiment.IsFinished()) {
436          refreshableHiveExperiment.ExecutionState = Core.ExecutionState.Stopped;
437        } else {
438          refreshableHiveExperiment.ExecutionState = Core.ExecutionState.Started;
439        }
440
441        // build child-job tree
442        foreach (HiveJob hiveJob in refreshableHiveExperiment.HiveJobs) {
443          BuildHiveJobTree(hiveJob, allJobs, allHiveJobs);
444        }
445
446        refreshableHiveExperiment.OnLoaded();
447      }
448      finally {
449        refreshableHiveExperiment.IsProgressing = false;
450      }
451    }
452
453    private static void BuildHiveJobTree(HiveJob parentHiveJob, IEnumerable<LightweightJob> allJobs, IDictionary<Guid, HiveJob> allHiveJobs) {
454      IEnumerable<LightweightJob> childJobs = from job in allJobs
455                                              where job.ParentJobId.HasValue && job.ParentJobId.Value == parentHiveJob.Job.Id
456                                              orderby job.DateCreated ascending
457                                              select job;
458      foreach (LightweightJob job in childJobs) {
459        HiveJob childHiveJob = allHiveJobs[job.Id];
460        parentHiveJob.AddChildHiveJob(childHiveJob);
461        BuildHiveJobTree(childHiveJob, allJobs, allHiveJobs);
462      }
463    }
464    #endregion
465
466    /// <summary>
467    /// Converts a string which can contain Ids separated by ';' to a enumerable
468    /// </summary>
469    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
470      if (!string.IsNullOrEmpty(resourceNames)) {
471        return resourceNames.Split(';');
472      } else {
473        return new List<string>();
474      }
475    }
476
477    public static ItemJob LoadItemJob(Guid jobId) {
478      JobData jobData = ServiceLocator.Instance.CallHiveService(s => s.GetJobData(jobId));
479      try {
480        return PersistenceUtil.Deserialize<ItemJob>(jobData.Data);
481      }
482      catch {
483        return null;
484      }
485    }
486
487    /// <summary>
488    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
489    /// If repetitions is -1, it is repeated infinitely.
490    /// </summary>
491    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
492      while (true) {
493        try { action(); return; }
494        catch (Exception e) {
495          if (repetitions == 0) throw new HiveException(errorMessage, e);
496          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
497          repetitions--;
498        }
499      }
500    }
501
502    public static HiveItemCollection<HiveExperimentPermission> GetHiveExperimentPermissions(Guid hiveExperimentId) {
503      return ServiceLocator.Instance.CallHiveService((service) => {
504        IEnumerable<HiveExperimentPermission> heps = service.GetHiveExperimentPermissions(hiveExperimentId);
505        foreach (var hep in heps) {
506          hep.GrantedUserName = service.GetUsernameByUserId(hep.GrantedUserId);
507        }
508        return new HiveItemCollection<HiveExperimentPermission>(heps);
509      });
510    }
511  }
512}
Note: See TracBrowser for help on using the repository browser.