source: branches/HiveProjectManagement/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 15642

Last change on this file since 15642 was 15642, checked in by jzenisek, 3 years ago

#2839

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