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

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

#2839

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