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

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

#2839

  • updated Heartbeat processing (regarding: checking against AssignedJobResources and handling of the updated Job deletion routine)
  • updated Job deletion routine(still in progress at GenerateStatistics)
File size: 24.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      }
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    #region Upload Job
252    private Semaphore taskUploadSemaphore = new Semaphore(Settings.Default.MaxParallelUploads, Settings.Default.MaxParallelUploads);
253    private static object jobCountLocker = new object();
254    private static object pluginLocker = new object();
255    private void UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
256      try {
257        refreshableJob.IsProgressing = true;
258        refreshableJob.Progress.Start("Connecting to server...");
259
260        foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>()) {
261          hiveJob.SetIndexInParentOptimizerList(null);
262        }
263
264        // upload Job
265        refreshableJob.Progress.Status = "Uploading Job...";
266        refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job, refreshableJob.Job.ResourceIds));
267        refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
268        cancellationToken.ThrowIfCancellationRequested();
269
270        int totalJobCount = refreshableJob.GetAllHiveTasks().Count();
271        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
272        cancellationToken.ThrowIfCancellationRequested();
273
274        // upload plugins
275        refreshableJob.Progress.Status = "Uploading plugins...";
276        this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
277        this.AlreadyUploadedPlugins = new List<Plugin>();
278        Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
279        this.alreadyUploadedPlugins.Add(configFilePlugin);
280        cancellationToken.ThrowIfCancellationRequested();
281
282        // upload tasks
283        refreshableJob.Progress.Status = "Uploading tasks...";
284
285        var tasks = new List<TS.Task>();
286        foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
287          var task = TS.Task.Factory.StartNew((hj) => {
288            UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
289          }, hiveTask);
290          task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
291          tasks.Add(task);
292        }
293        TS.Task.WaitAll(tasks.ToArray());
294      }
295      finally {
296        refreshableJob.Job.Modified = false;
297        refreshableJob.IsProgressing = false;
298        refreshableJob.Progress.Finish();
299      }
300    }
301
302    /// <summary>
303    /// Uploads the local configuration file as plugin
304    /// </summary>
305    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
306      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
307      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
308      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
309      byte[] hash;
310
311      byte[] data = File.ReadAllBytes(configFilePath);
312      using (SHA1 sha1 = SHA1.Create()) {
313        hash = sha1.ComputeHash(data);
314      }
315
316      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
317      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
318
319      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
320
321      if (onlineConfig.Count() > 0) {
322        return onlineConfig.First();
323      } else {
324        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
325        return configPlugin;
326      }
327    }
328
329    /// <summary>
330    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
331    /// </summary>
332    /// <param name="parentHiveTask">shall be null if its the root task</param>
333    private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
334      taskUploadSemaphore.WaitOne();
335      bool semaphoreReleased = false;
336      try {
337        cancellationToken.ThrowIfCancellationRequested();
338        lock (jobCountLocker) {
339          taskCount[0]++;
340        }
341        TaskData taskData;
342        List<IPluginDescription> plugins;
343
344        if (hiveTask.ItemTask.ComputeInParallel) {
345          hiveTask.Task.IsParentTask = true;
346          hiveTask.Task.FinishWhenChildJobsFinished = true;
347          taskData = hiveTask.GetAsTaskData(true, out plugins);
348        } else {
349          hiveTask.Task.IsParentTask = false;
350          hiveTask.Task.FinishWhenChildJobsFinished = false;
351          taskData = hiveTask.GetAsTaskData(false, out plugins);
352        }
353        cancellationToken.ThrowIfCancellationRequested();
354
355        TryAndRepeat(() => {
356          if (!cancellationToken.IsCancellationRequested) {
357            lock (pluginLocker) {
358              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
359            }
360          }
361        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
362        cancellationToken.ThrowIfCancellationRequested();
363        hiveTask.Task.PluginsNeededIds.Add(configPluginId);
364        hiveTask.Task.JobId = jobId;
365
366        log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
367        TryAndRepeat(() => {
368          if (!cancellationToken.IsCancellationRequested) {
369            if (parentHiveTask != null) {
370              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
371            } else {
372              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData));
373            }
374          }
375        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
376        cancellationToken.ThrowIfCancellationRequested();
377
378        lock (jobCountLocker) {
379          progress.ProgressValue = (double)taskCount[0] / totalJobCount;
380          progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
381        }
382
383        var tasks = new List<TS.Task>();
384        foreach (HiveTask child in hiveTask.ChildHiveTasks) {
385          var task = TS.Task.Factory.StartNew((tuple) => {
386            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
387            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
388          }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
389          task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
390          tasks.Add(task);
391        }
392        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
393        TS.Task.WaitAll(tasks.ToArray());
394      } finally {
395        if (!semaphoreReleased) taskUploadSemaphore.Release();
396      }
397    }
398
399
400    /// <summary>
401    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
402    /// </summary>
403    /// <param name="parentHiveTask">shall be null if its the root task</param>
404    //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) {
405    //  taskUploadSemaphore.WaitOne();
406    //  bool semaphoreReleased = false;
407    //  try {
408    //    cancellationToken.ThrowIfCancellationRequested();
409    //    lock (jobCountLocker) {
410    //      taskCount[0]++;
411    //    }
412    //    TaskData taskData;
413    //    List<IPluginDescription> plugins;
414
415    //    if (hiveTask.ItemTask.ComputeInParallel) {
416    //      hiveTask.Task.IsParentTask = true;
417    //      hiveTask.Task.FinishWhenChildJobsFinished = true;
418    //      taskData = hiveTask.GetAsTaskData(true, out plugins);
419    //    } else {
420    //      hiveTask.Task.IsParentTask = false;
421    //      hiveTask.Task.FinishWhenChildJobsFinished = false;
422    //      taskData = hiveTask.GetAsTaskData(false, out plugins);
423    //    }
424    //    cancellationToken.ThrowIfCancellationRequested();
425
426    //    TryAndRepeat(() => {
427    //      if (!cancellationToken.IsCancellationRequested) {
428    //        lock (pluginLocker) {
429    //          HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
430    //        }
431    //      }
432    //    }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
433    //    cancellationToken.ThrowIfCancellationRequested();
434    //    hiveTask.Task.PluginsNeededIds.Add(configPluginId);
435    //    hiveTask.Task.JobId = jobId;
436
437    //    log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
438    //    TryAndRepeat(() => {
439    //      if (!cancellationToken.IsCancellationRequested) {
440    //        if (parentHiveTask != null) {
441    //          hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
442    //        } else {
443    //          hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
444    //        }
445    //      }
446    //    }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
447    //    cancellationToken.ThrowIfCancellationRequested();
448
449    //    lock (jobCountLocker) {
450    //      progress.ProgressValue = (double)taskCount[0] / totalJobCount;
451    //      progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
452    //    }
453
454    //    var tasks = new List<TS.Task>();
455    //    foreach (HiveTask child in hiveTask.ChildHiveTasks) {
456    //      var task = TS.Task.Factory.StartNew((tuple) => {
457    //        var arguments = (Tuple<HiveTask, HiveTask>)tuple;
458    //        UploadTaskWithChildren_Old(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
459    //      }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
460    //      task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
461    //      tasks.Add(task);
462    //    }
463    //    taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
464    //    TS.Task.WaitAll(tasks.ToArray());
465    //  }
466    //  finally {
467    //    if (!semaphoreReleased) taskUploadSemaphore.Release();
468    //  }
469    //}
470   
471    #endregion
472
473    #region Download Experiment
474    public static void LoadJob(RefreshableJob refreshableJob) {
475      var hiveExperiment = refreshableJob.Job;
476      refreshableJob.IsProgressing = true;
477      TaskDownloader downloader = null;
478
479      try {
480        int totalJobCount = 0;
481        IEnumerable<LightweightTask> allTasks;
482
483        // fetch all task objects to create the full tree of tree of HiveTask objects
484        refreshableJob.Progress.Start("Downloading list of tasks...");
485        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
486        totalJobCount = allTasks.Count();
487
488        refreshableJob.Progress.Status = "Downloading tasks...";
489        downloader = new TaskDownloader(allTasks.Select(x => x.Id));
490        downloader.StartAsync();
491
492        while (!downloader.IsFinished) {
493          refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
494          refreshableJob.Progress.Status = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
495          Thread.Sleep(500);
496
497          if (downloader.IsFaulted) {
498            throw downloader.Exception;
499          }
500        }
501        IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
502        var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
503
504        refreshableJob.Progress.Status = "Downloading/deserializing complete. Displaying tasks...";
505        // build child-task tree
506        foreach (HiveTask hiveTask in parents) {
507          BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
508        }
509
510        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
511        if (refreshableJob.IsFinished()) {
512          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
513        } else if (refreshableJob.IsPaused()) {
514          refreshableJob.ExecutionState = Core.ExecutionState.Paused;
515        } else {
516          refreshableJob.ExecutionState = Core.ExecutionState.Started;
517        }
518        refreshableJob.OnLoaded();
519      }
520      finally {
521        refreshableJob.IsProgressing = false;
522        refreshableJob.Progress.Finish();
523        if (downloader != null) {
524          downloader.Dispose();
525        }
526      }
527    }
528
529    private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
530      IEnumerable<LightweightTask> childTasks = from job in allTasks
531                                                where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
532                                                orderby job.DateCreated ascending
533                                                select job;
534      foreach (LightweightTask task in childTasks) {
535        HiveTask childHiveTask = allHiveTasks[task.Id];
536        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
537        parentHiveTask.AddChildHiveTask(childHiveTask);
538      }
539    }
540    #endregion
541
542    /// <summary>
543    /// Converts a string which can contain Ids separated by ';' to a enumerable
544    /// </summary>
545    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
546      if (!string.IsNullOrEmpty(resourceNames)) {
547        return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
548      } else {
549        return new List<string>();
550      }
551    }
552
553    public static ItemTask LoadItemJob(Guid jobId) {
554      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
555      try {
556        return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
557      }
558      catch {
559        return null;
560      }
561    }
562
563    /// <summary>
564    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
565    /// If repetitions is -1, it is repeated infinitely.
566    /// </summary>
567    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
568      while (true) {
569        try { action(); return; }
570        catch (Exception e) {
571          if (repetitions == 0) throw new HiveException(errorMessage, e);
572          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
573          repetitions--;
574        }
575      }
576    }
577
578    public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
579      return HiveServiceLocator.Instance.CallHiveService((service) => {
580        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
581        foreach (var hep in jps) {
582          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
583        }
584        return new HiveItemCollection<JobPermission>(jps);
585      });
586    }
587  }
588}
Note: See TracBrowser for help on using the repository browser.