source: branches/UnloadJobs/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 9169

Last change on this file since 9169 was 9169, checked in by ascheibe, 9 years ago

#2005

  • renamed some events and methods
  • fixed some memory leaks
File size: 22.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.MainForm;
33using HeuristicLab.PluginInfrastructure;
34using TS = System.Threading.Tasks;
35
36namespace HeuristicLab.Clients.Hive {
37  [Item("HiveClient", "Hive client.")]
38  public sealed class HiveClient : IContent {
39    private static HiveClient instance;
40    public static HiveClient Instance {
41      get {
42        if (instance == null) instance = new HiveClient();
43        return instance;
44      }
45    }
46
47    #region Properties
48    private ItemCollection<RefreshableJob> jobs;
49    public ItemCollection<RefreshableJob> Jobs {
50      get { return jobs; }
51      set {
52        if (value != jobs) {
53          jobs = value;
54          OnHiveJobsChanged();
55        }
56      }
57    }
58
59    private List<Plugin> onlinePlugins;
60    public List<Plugin> OnlinePlugins {
61      get { return onlinePlugins; }
62      set { onlinePlugins = value; }
63    }
64
65    private List<Plugin> alreadyUploadedPlugins;
66    public List<Plugin> AlreadyUploadedPlugins {
67      get { return alreadyUploadedPlugins; }
68      set { alreadyUploadedPlugins = value; }
69    }
70
71    private bool isAllowedPrivileged;
72    public bool IsAllowedPrivileged {
73      get { return isAllowedPrivileged; }
74      set { isAllowedPrivileged = value; }
75    }
76    #endregion
77
78    private HiveClient() { }
79
80    public void ClearHiveClient() {
81      foreach (var j in Jobs) {
82        if (j.RefreshAutomatically) {
83          j.RefreshAutomatically = false; // stop result polling
84          j.Dispose();
85        }
86      }
87      Jobs = null;
88      if (onlinePlugins != null)
89        onlinePlugins.Clear();
90      if (alreadyUploadedPlugins != null)
91        alreadyUploadedPlugins.Clear();
92    }
93
94    #region Refresh
95    public void Refresh() {
96      OnRefreshing();
97
98      try {
99        IsAllowedPrivileged = HiveServiceLocator.Instance.CallHiveService((s) => s.IsAllowedPrivileged());
100
101        var oldJobs = jobs ?? new ItemCollection<RefreshableJob>();
102        jobs = new HiveItemCollection<RefreshableJob>();
103        var jobsLoaded = HiveServiceLocator.Instance.CallHiveService<IEnumerable<Job>>(s => s.GetJobs());
104
105        foreach (var j in jobsLoaded) {
106          var job = oldJobs.SingleOrDefault(x => x.Id == j.Id);
107          if (job == null) {
108            // new
109            jobs.Add(new RefreshableJob(j) { IsAllowedPrivileged = this.isAllowedPrivileged });
110          } else {
111            // update
112            job.Job = j;
113            job.IsAllowedPrivileged = this.isAllowedPrivileged;
114            jobs.Add(job);
115          }
116        }
117        // remove those which were not in the list of loaded hiveexperiments
118        foreach (var job in oldJobs) {
119          if (job.Id == Guid.Empty) {
120            // experiment not uploaded... keep
121            jobs.Add(job);
122          } else {
123            job.RefreshAutomatically = false; // stop results polling
124          }
125        }
126      }
127      catch {
128        jobs = null;
129        throw;
130      }
131      finally {
132        OnRefreshed();
133      }
134    }
135    public void RefreshAsync(Action<Exception> exceptionCallback) {
136      var call = new Func<Exception>(delegate() {
137        try {
138          Refresh();
139        }
140        catch (Exception ex) {
141          return ex;
142        }
143        return null;
144      });
145      call.BeginInvoke(delegate(IAsyncResult result) {
146        Exception ex = call.EndInvoke(result);
147        if (ex != null) exceptionCallback(ex);
148      }, null);
149    }
150    #endregion
151
152    #region Store
153    public static void Store(IHiveItem item, CancellationToken cancellationToken) {
154      if (item.Id == Guid.Empty) {
155        if (item is RefreshableJob) {
156          HiveClient.Instance.UploadJob((RefreshableJob)item, cancellationToken);
157        }
158        if (item is JobPermission) {
159          var hep = (JobPermission)item;
160          hep.GrantedUserId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
161          if (hep.GrantedUserId == Guid.Empty) {
162            throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
163          }
164          HiveServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
165        }
166      } else {
167        if (item is Job)
168          HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJob((Job)item));
169      }
170    }
171    public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
172      var call = new Func<Exception>(delegate() {
173        try {
174          Store(item, cancellationToken);
175        }
176        catch (Exception ex) {
177          return ex;
178        }
179        return null;
180      });
181      call.BeginInvoke(delegate(IAsyncResult result) {
182        Exception ex = call.EndInvoke(result);
183        if (ex != null) exceptionCallback(ex);
184      }, null);
185    }
186    #endregion
187
188    #region Delete
189    public static void Delete(IHiveItem item) {
190      if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
191        return;
192
193      if (item is Job)
194        HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(item.Id));
195      if (item is RefreshableJob) {
196        RefreshableJob job = (RefreshableJob)item;
197        if (job.RefreshAutomatically) {
198          job.StopResultPolling();
199        }
200        HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(item.Id));
201      }
202      if (item is JobPermission) {
203        var hep = (JobPermission)item;
204        HiveServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
205      }
206      item.Id = Guid.Empty;
207    }
208    #endregion
209
210    #region Events
211    public event EventHandler Refreshing;
212    private void OnRefreshing() {
213      EventHandler handler = Refreshing;
214      if (handler != null) handler(this, EventArgs.Empty);
215    }
216    public event EventHandler Refreshed;
217    private void OnRefreshed() {
218      var handler = Refreshed;
219      if (handler != null) handler(this, EventArgs.Empty);
220    }
221    public event EventHandler HiveJobsChanged;
222    private void OnHiveJobsChanged() {
223      var handler = HiveJobsChanged;
224      if (handler != null) handler(this, EventArgs.Empty);
225    }
226    #endregion
227
228    public static void StartJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
229      HiveClient.StoreAsync(
230        new Action<Exception>((Exception ex) => {
231          refreshableJob.ExecutionState = ExecutionState.Prepared;
232          exceptionCallback(ex);
233        }), refreshableJob, cancellationToken);
234      refreshableJob.ExecutionState = ExecutionState.Started;
235    }
236
237    public static void PauseJob(RefreshableJob refreshableJob) {
238      HiveServiceLocator.Instance.CallHiveService(service => {
239        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
240          if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
241            service.PauseTask(task.Task.Id);
242        }
243      });
244      refreshableJob.ExecutionState = ExecutionState.Paused;
245    }
246
247    public static void StopJob(RefreshableJob refreshableJob) {
248      HiveServiceLocator.Instance.CallHiveService(service => {
249        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
250          if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
251            service.StopTask(task.Task.Id);
252        }
253      });
254      refreshableJob.ExecutionState = ExecutionState.Stopped;
255    }
256
257    public static void ResumeJob(RefreshableJob refreshableJob) {
258      HiveServiceLocator.Instance.CallHiveService(service => {
259        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
260          if (task.Task.State == TaskState.Paused) {
261            service.RestartTask(task.Task.Id);
262          }
263        }
264      });
265      refreshableJob.ExecutionState = ExecutionState.Started;
266    }
267
268    #region Upload Job
269    private Semaphore taskUploadSemaphore = new Semaphore(Settings.Default.MaxParallelUploads, Settings.Default.MaxParallelUploads);
270    private static object jobCountLocker = new object();
271    private static object pluginLocker = new object();
272    private void UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
273      try {
274        refreshableJob.IsProgressing = true;
275        refreshableJob.Progress = new Progress("Connecting to server...");
276        IEnumerable<string> resourceNames = ToResourceNameList(refreshableJob.Job.ResourceNames);
277        var resourceIds = new List<Guid>();
278        foreach (var resourceName in resourceNames) {
279          Guid resourceId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetResourceId(resourceName));
280          if (resourceId == Guid.Empty) {
281            throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
282          }
283          resourceIds.Add(resourceId);
284        }
285
286        foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>()) {
287          hiveJob.SetIndexInParentOptimizerList(null);
288        }
289
290        // upload Job
291        refreshableJob.Progress.Status = "Uploading Job...";
292        refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job));
293        bool isPrivileged = refreshableJob.Job.IsPrivileged;
294        refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
295        refreshableJob.Job.IsPrivileged = isPrivileged;
296        cancellationToken.ThrowIfCancellationRequested();
297
298        int totalJobCount = refreshableJob.GetAllHiveTasks().Count();
299        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
300        cancellationToken.ThrowIfCancellationRequested();
301
302        // upload plugins
303        refreshableJob.Progress.Status = "Uploading plugins...";
304        this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
305        this.AlreadyUploadedPlugins = new List<Plugin>();
306        Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
307        this.alreadyUploadedPlugins.Add(configFilePlugin);
308        cancellationToken.ThrowIfCancellationRequested();
309
310        // upload tasks
311        refreshableJob.Progress.Status = "Uploading tasks...";
312
313        var tasks = new List<TS.Task>();
314        foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
315          var task = TS.Task.Factory.StartNew((hj) => {
316            UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, resourceIds, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, refreshableJob.Job.IsPrivileged, cancellationToken);
317          }, hiveTask);
318          task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
319          tasks.Add(task);
320        }
321        TS.Task.WaitAll(tasks.ToArray());
322      }
323      finally {
324        //refreshableJob.RefreshAutomatically = true;       
325        refreshableJob.Job.Modified = false;
326        refreshableJob.IsProgressing = false;
327        refreshableJob.Progress.Finish();
328      }
329    }
330
331    /// <summary>
332    /// Uploads the local configuration file as plugin
333    /// </summary>
334    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
335      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
336      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
337      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
338      byte[] hash;
339
340      byte[] data = File.ReadAllBytes(configFilePath);
341      using (SHA1 sha1 = SHA1.Create()) {
342        hash = sha1.ComputeHash(data);
343      }
344
345      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
346      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
347
348      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
349
350      if (onlineConfig.Count() > 0) {
351        return onlineConfig.First();
352      } else {
353        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
354        return configPlugin;
355      }
356    }
357
358    /// <summary>
359    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
360    /// </summary>
361    /// <param name="parentHiveTask">shall be null if its the root task</param>
362    private void UploadTaskWithChildren(Progress progress, HiveTask hiveTask, HiveTask parentHiveTask, IEnumerable<Guid> groups, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, bool isPrivileged, CancellationToken cancellationToken) {
363      taskUploadSemaphore.WaitOne();
364      bool semaphoreReleased = false;
365      try {
366        cancellationToken.ThrowIfCancellationRequested();
367        lock (jobCountLocker) {
368          taskCount[0]++;
369        }
370        TaskData taskData;
371        List<IPluginDescription> plugins;
372
373        if (hiveTask.ItemTask.ComputeInParallel && (hiveTask.ItemTask.Item is Optimization.Experiment || hiveTask.ItemTask.Item is Optimization.BatchRun)) {
374          hiveTask.Task.IsParentTask = true;
375          hiveTask.Task.FinishWhenChildJobsFinished = true;
376          taskData = hiveTask.GetAsTaskData(true, out plugins);
377        } else {
378          hiveTask.Task.IsParentTask = false;
379          hiveTask.Task.FinishWhenChildJobsFinished = false;
380          taskData = hiveTask.GetAsTaskData(false, out plugins);
381        }
382        cancellationToken.ThrowIfCancellationRequested();
383
384        TryAndRepeat(() => {
385          if (!cancellationToken.IsCancellationRequested) {
386            lock (pluginLocker) {
387              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
388            }
389          }
390        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
391        cancellationToken.ThrowIfCancellationRequested();
392        hiveTask.Task.PluginsNeededIds.Add(configPluginId);
393        hiveTask.Task.JobId = jobId;
394        hiveTask.Task.IsPrivileged = isPrivileged;
395
396        log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
397        TryAndRepeat(() => {
398          if (!cancellationToken.IsCancellationRequested) {
399            if (parentHiveTask != null) {
400              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
401            } else {
402              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
403            }
404          }
405        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
406        cancellationToken.ThrowIfCancellationRequested();
407
408        lock (jobCountLocker) {
409          progress.ProgressValue = (double)taskCount[0] / totalJobCount;
410          progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
411        }
412
413        var tasks = new List<TS.Task>();
414        foreach (HiveTask child in hiveTask.ChildHiveTasks) {
415          var task = TS.Task.Factory.StartNew((tuple) => {
416            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
417            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, isPrivileged, cancellationToken);
418          }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
419          task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
420          tasks.Add(task);
421        }
422        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
423        TS.Task.WaitAll(tasks.ToArray());
424      }
425      finally {
426        if (!semaphoreReleased) taskUploadSemaphore.Release();
427      }
428    }
429    #endregion
430
431    #region Download Experiment
432    public static void LoadJob(RefreshableJob refreshableJob) {
433      var hiveExperiment = refreshableJob.Job;
434      refreshableJob.IsProgressing = true;
435      refreshableJob.Progress = new Progress();
436      TaskDownloader downloader = null;
437
438      try {
439        int totalJobCount = 0;
440        IEnumerable<LightweightTask> allTasks;
441
442        refreshableJob.Progress.Status = "Connecting to Server...";
443        // fetch all task objects to create the full tree of tree of HiveTask objects
444        refreshableJob.Progress.Status = "Downloading list of tasks...";
445        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasks(hiveExperiment.Id));
446        totalJobCount = allTasks.Count();
447
448        refreshableJob.Progress.Status = "Downloading tasks...";
449        downloader = new TaskDownloader(allTasks.Select(x => x.Id));
450        downloader.StartAsync();
451
452        while (!downloader.IsFinished) {
453          refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
454          refreshableJob.Progress.Status = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
455          Thread.Sleep(500);
456
457          if (downloader.IsFaulted) {
458            throw downloader.Exception;
459          }
460        }
461        IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
462        var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
463
464        refreshableJob.Progress.Status = "Downloading/deserializing complete. Displaying tasks...";
465        // build child-task tree
466        foreach (HiveTask hiveTask in parents) {
467          BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
468        }
469
470        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
471        if (refreshableJob.IsFinished()) {
472          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
473        } else {
474          refreshableJob.ExecutionState = Core.ExecutionState.Started;
475        }
476        refreshableJob.OnLoaded();
477      }
478      finally {
479        refreshableJob.IsProgressing = false;
480        refreshableJob.Progress.Finish();
481        if (downloader != null) {
482          downloader.Dispose();
483        }
484      }
485    }
486
487    private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
488      IEnumerable<LightweightTask> childTasks = from job in allTasks
489                                                where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
490                                                orderby job.DateCreated ascending
491                                                select job;
492      foreach (LightweightTask task in childTasks) {
493        HiveTask childHiveTask = allHiveTasks[task.Id];
494        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
495        parentHiveTask.AddChildHiveTask(childHiveTask);
496      }
497    }
498    #endregion
499
500    /// <summary>
501    /// Converts a string which can contain Ids separated by ';' to a enumerable
502    /// </summary>
503    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
504      if (!string.IsNullOrEmpty(resourceNames)) {
505        return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
506      } else {
507        return new List<string>();
508      }
509    }
510
511    public static ItemTask LoadItemJob(Guid jobId) {
512      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
513      try {
514        return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
515      }
516      catch {
517        return null;
518      }
519    }
520
521    /// <summary>
522    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
523    /// If repetitions is -1, it is repeated infinitely.
524    /// </summary>
525    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
526      while (true) {
527        try { action(); return; }
528        catch (Exception e) {
529          if (repetitions == 0) throw new HiveException(errorMessage, e);
530          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
531          repetitions--;
532        }
533      }
534    }
535
536    public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
537      return HiveServiceLocator.Instance.CallHiveService((service) => {
538        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
539        foreach (var hep in jps) {
540          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
541        }
542        return new HiveItemCollection<JobPermission>(jps);
543      });
544    }
545  }
546}
Note: See TracBrowser for help on using the repository browser.