Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2839_HiveProjectManagement/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 15992

Last change on this file since 15992 was 15992, checked in by jzenisek, 6 years ago

#2839: fixed couple of minor issues

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