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

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

#2005

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