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

Last change on this file since 15742 was 15742, checked in by jzenisek, 4 years ago

#2839 worked on HiveAdministrator:

  • corrected and modified CRUD operations
  • improved usability by providing detailed state information, adding dialogs etc.
File size: 26.2 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          item.Id = 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          item.Id = 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 Guid 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      return (refreshableJob.Job != null) ? refreshableJob.Job.Id : Guid.Empty;
350    }
351
352    /// <summary>
353    /// Uploads the local configuration file as plugin
354    /// </summary>
355    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
356      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
357      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
358      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
359      byte[] hash;
360
361      byte[] data = File.ReadAllBytes(configFilePath);
362      using (SHA1 sha1 = SHA1.Create()) {
363        hash = sha1.ComputeHash(data);
364      }
365
366      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
367      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
368
369      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
370
371      if (onlineConfig.Count() > 0) {
372        return onlineConfig.First();
373      } else {
374        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
375        return configPlugin;
376      }
377    }
378
379    /// <summary>
380    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
381    /// </summary>
382    /// <param name="parentHiveTask">shall be null if its the root task</param>
383    private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
384      taskUploadSemaphore.WaitOne();
385      bool semaphoreReleased = false;
386      try {
387        cancellationToken.ThrowIfCancellationRequested();
388        lock (jobCountLocker) {
389          taskCount[0]++;
390        }
391        TaskData taskData;
392        List<IPluginDescription> plugins;
393
394        if (hiveTask.ItemTask.ComputeInParallel) {
395          hiveTask.Task.IsParentTask = true;
396          hiveTask.Task.FinishWhenChildJobsFinished = true;
397          taskData = hiveTask.GetAsTaskData(true, out plugins);
398        } else {
399          hiveTask.Task.IsParentTask = false;
400          hiveTask.Task.FinishWhenChildJobsFinished = false;
401          taskData = hiveTask.GetAsTaskData(false, out plugins);
402        }
403        cancellationToken.ThrowIfCancellationRequested();
404
405        TryAndRepeat(() => {
406          if (!cancellationToken.IsCancellationRequested) {
407            lock (pluginLocker) {
408              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
409            }
410          }
411        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
412        cancellationToken.ThrowIfCancellationRequested();
413        hiveTask.Task.PluginsNeededIds.Add(configPluginId);
414        hiveTask.Task.JobId = jobId;
415
416        log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
417        TryAndRepeat(() => {
418          if (!cancellationToken.IsCancellationRequested) {
419            if (parentHiveTask != null) {
420              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
421            } else {
422              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData));
423            }
424          }
425        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
426        cancellationToken.ThrowIfCancellationRequested();
427
428        lock (jobCountLocker) {
429          progress.ProgressValue = (double)taskCount[0] / totalJobCount;
430          progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
431        }
432
433        var tasks = new List<TS.Task>();
434        foreach (HiveTask child in hiveTask.ChildHiveTasks) {
435          var task = TS.Task.Factory.StartNew((tuple) => {
436            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
437            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
438          }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
439          task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
440          tasks.Add(task);
441        }
442        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
443        TS.Task.WaitAll(tasks.ToArray());
444      } finally {
445        if (!semaphoreReleased) taskUploadSemaphore.Release();
446      }
447    }
448
449
450    /// <summary>
451    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
452    /// </summary>
453    /// <param name="parentHiveTask">shall be null if its the root task</param>
454    //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) {
455    //  taskUploadSemaphore.WaitOne();
456    //  bool semaphoreReleased = false;
457    //  try {
458    //    cancellationToken.ThrowIfCancellationRequested();
459    //    lock (jobCountLocker) {
460    //      taskCount[0]++;
461    //    }
462    //    TaskData taskData;
463    //    List<IPluginDescription> plugins;
464
465    //    if (hiveTask.ItemTask.ComputeInParallel) {
466    //      hiveTask.Task.IsParentTask = true;
467    //      hiveTask.Task.FinishWhenChildJobsFinished = true;
468    //      taskData = hiveTask.GetAsTaskData(true, out plugins);
469    //    } else {
470    //      hiveTask.Task.IsParentTask = false;
471    //      hiveTask.Task.FinishWhenChildJobsFinished = false;
472    //      taskData = hiveTask.GetAsTaskData(false, out plugins);
473    //    }
474    //    cancellationToken.ThrowIfCancellationRequested();
475
476    //    TryAndRepeat(() => {
477    //      if (!cancellationToken.IsCancellationRequested) {
478    //        lock (pluginLocker) {
479    //          HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
480    //        }
481    //      }
482    //    }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
483    //    cancellationToken.ThrowIfCancellationRequested();
484    //    hiveTask.Task.PluginsNeededIds.Add(configPluginId);
485    //    hiveTask.Task.JobId = jobId;
486
487    //    log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
488    //    TryAndRepeat(() => {
489    //      if (!cancellationToken.IsCancellationRequested) {
490    //        if (parentHiveTask != null) {
491    //          hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
492    //        } else {
493    //          hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
494    //        }
495    //      }
496    //    }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
497    //    cancellationToken.ThrowIfCancellationRequested();
498
499    //    lock (jobCountLocker) {
500    //      progress.ProgressValue = (double)taskCount[0] / totalJobCount;
501    //      progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
502    //    }
503
504    //    var tasks = new List<TS.Task>();
505    //    foreach (HiveTask child in hiveTask.ChildHiveTasks) {
506    //      var task = TS.Task.Factory.StartNew((tuple) => {
507    //        var arguments = (Tuple<HiveTask, HiveTask>)tuple;
508    //        UploadTaskWithChildren_Old(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
509    //      }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
510    //      task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
511    //      tasks.Add(task);
512    //    }
513    //    taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
514    //    TS.Task.WaitAll(tasks.ToArray());
515    //  }
516    //  finally {
517    //    if (!semaphoreReleased) taskUploadSemaphore.Release();
518    //  }
519    //}
520   
521    #endregion
522
523    #region Download Experiment
524    public static void LoadJob(RefreshableJob refreshableJob) {
525      var hiveExperiment = refreshableJob.Job;
526      refreshableJob.IsProgressing = true;
527      TaskDownloader downloader = null;
528
529      try {
530        int totalJobCount = 0;
531        IEnumerable<LightweightTask> allTasks;
532
533        // fetch all task objects to create the full tree of tree of HiveTask objects
534        refreshableJob.Progress.Start("Downloading list of tasks...");
535        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
536        totalJobCount = allTasks.Count();
537
538        refreshableJob.Progress.Status = "Downloading tasks...";
539        downloader = new TaskDownloader(allTasks.Select(x => x.Id));
540        downloader.StartAsync();
541
542        while (!downloader.IsFinished) {
543          refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
544          refreshableJob.Progress.Status = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
545          Thread.Sleep(500);
546
547          if (downloader.IsFaulted) {
548            throw downloader.Exception;
549          }
550        }
551        IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
552        var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
553
554        refreshableJob.Progress.Status = "Downloading/deserializing complete. Displaying tasks...";
555        // build child-task tree
556        foreach (HiveTask hiveTask in parents) {
557          BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
558        }
559
560        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
561        if (refreshableJob.IsFinished()) {
562          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
563        } else if (refreshableJob.IsPaused()) {
564          refreshableJob.ExecutionState = Core.ExecutionState.Paused;
565        } else {
566          refreshableJob.ExecutionState = Core.ExecutionState.Started;
567        }
568        refreshableJob.OnLoaded();
569      }
570      finally {
571        refreshableJob.IsProgressing = false;
572        refreshableJob.Progress.Finish();
573        if (downloader != null) {
574          downloader.Dispose();
575        }
576      }
577    }
578
579    private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
580      IEnumerable<LightweightTask> childTasks = from job in allTasks
581                                                where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
582                                                orderby job.DateCreated ascending
583                                                select job;
584      foreach (LightweightTask task in childTasks) {
585        HiveTask childHiveTask = allHiveTasks[task.Id];
586        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
587        parentHiveTask.AddChildHiveTask(childHiveTask);
588      }
589    }
590    #endregion
591
592    /// <summary>
593    /// Converts a string which can contain Ids separated by ';' to a enumerable
594    /// </summary>
595    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
596      if (!string.IsNullOrEmpty(resourceNames)) {
597        return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
598      } else {
599        return new List<string>();
600      }
601    }
602
603    public static ItemTask LoadItemJob(Guid jobId) {
604      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
605      try {
606        return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
607      }
608      catch {
609        return null;
610      }
611    }
612
613    /// <summary>
614    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
615    /// If repetitions is -1, it is repeated infinitely.
616    /// </summary>
617    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
618      while (true) {
619        try { action(); return; }
620        catch (Exception e) {
621          if (repetitions == 0) throw new HiveException(errorMessage, e);
622          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
623          repetitions--;
624        }
625      }
626    }
627
628    public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
629      return HiveServiceLocator.Instance.CallHiveService((service) => {
630        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
631        foreach (var hep in jps) {
632          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
633        }
634        return new HiveItemCollection<JobPermission>(jps);
635      });
636    }
637  }
638}
Note: See TracBrowser for help on using the repository browser.