Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 15419

Last change on this file since 15419 was 15419, checked in by pfleck, 6 years ago

#2846: Fixed uncaught ObjectDisposedException in HiveJobManagerView.

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