Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2839: adapted illustration of project and resource ancestry in HiveAdministrator and HiveJobAdministrator

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