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
RevLine 
[6976]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6976]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;
[7582]32using HeuristicLab.MainForm;
[6976]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
[9219]48    private HiveItemCollection<RefreshableJob> jobs;
49    public HiveItemCollection<RefreshableJob> Jobs {
[6976]50      get { return jobs; }
51      set {
52        if (value != jobs) {
53          jobs = value;
[9219]54          OnHiveJobsChanged();
[6976]55        }
56      }
57    }
58
[15658]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
[15913]69    private Dictionary<Guid, HashSet<Guid>> projectAncestors;
70    public Dictionary<Guid, HashSet<Guid>> ProjectAncestors {
71      get { return projectAncestors; }
72    }
[15658]73
[15913]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
[15978]89    private Dictionary<Guid, string> projectNames;
90    public Dictionary<Guid, string> ProjectNames {
91      get { return projectNames; }
92    }
[15913]93
[15978]94    private HashSet<Project> disabledParentProjects;
95    public HashSet<Project> DisabledParentProjects {
96      get { return disabledParentProjects; }
97    }
98
[15995]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
[6976]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
[12579]122    private HiveClient() { }
[6976]123
[9219]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
[6976]140    #region Refresh
141    public void Refresh() {
142      OnRefreshing();
143
144      try {
[15658]145        projects = new ItemList<Project>();
146        resources = new ItemList<Resource>();
[6976]147        jobs = new HiveItemCollection<RefreshableJob>();
[15978]148        projectNames = new Dictionary<Guid, string>();
[15995]149        resourceNames = new Dictionary<Guid, string>();
[6976]150
[15913]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
[15658]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)));
[15978]161          projectNames = service.GetProjectNames();
[15995]162          resourceNames = service.GetResourceNames();
[15658]163        });
[15913]164
[15992]165        RefreshResourceGenealogy();
166        RefreshProjectGenealogy();
167        RefreshDisabledParentProjects();
[15995]168        RefreshDisabledParentResources();
[6976]169      }
170      catch {
171        jobs = null;
[15658]172        projects = null;
173        resources = null;
[6976]174        throw;
[7582]175      }
176      finally {
[6976]177        OnRefreshed();
178      }
179    }
[9219]180
[15658]181    public void RefreshProjectsAndResources() {
182      OnRefreshing();
183
184      try {
185        projects = new ItemList<Project>();
[15978]186        projectNames = new Dictionary<Guid, string>();
[15658]187        resources = new ItemList<Resource>();
[15995]188        resourceNames = new Dictionary<Guid, string>();
[15658]189
[15913]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
[15658]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));
[15978]199          projectNames = service.GetProjectNames();
[15995]200          resourceNames = service.GetResourceNames();
[15658]201        });
[15913]202
[15992]203        RefreshResourceGenealogy();
204        RefreshProjectGenealogy();
205        RefreshDisabledParentProjects();
[15995]206        RefreshDisabledParentResources();
[15658]207      } catch {
208        projects = null;
209        resources = null;
210        throw;
211      } finally {
212        OnRefreshed();
213      }
214    }
215
[6976]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    }
[15913]231
[15992]232    private void RefreshResourceGenealogy() {
[15913]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
[15992]252    private void RefreshProjectGenealogy() {
[15913]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
[15992]272    private void RefreshDisabledParentProjects() {
[15978]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
[15995]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
[15922]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>();
[15913]305    }
306
[15922]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>();
[15913]310    }
311
[15922]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>();
[15913]315    }
316
[15922]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>();
[15913]320    }
[6976]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) {
[15742]327          item.Id = HiveClient.Instance.UploadJob((RefreshableJob)item, cancellationToken);
[6976]328        }
329        if (item is JobPermission) {
330          var hep = (JobPermission)item;
[7132]331          hep.GrantedUserId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
[6976]332          if (hep.GrantedUserId == Guid.Empty) {
333            throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
334          }
[7132]335          HiveServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
[6976]336        }
[15401]337        if (item is Project) {
[15742]338          item.Id = HiveServiceLocator.Instance.CallHiveService(s => s.AddProject((Project)item));
[15401]339        }
[6976]340      } else {
[15630]341        if (item is Job) {
342          var job = (Job)item;
343          HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJob(job, job.ResourceIds));
344        }
[15401]345        if (item is Project)
346          HiveServiceLocator.Instance.CallHiveService(s => s.UpdateProject((Project)item));
[6976]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) {
[7059]368      if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
[6976]369        return;
370
371      if (item is Job)
[15630]372        HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJobState(item.Id, JobState.StatisticsPending));
[7144]373      if (item is RefreshableJob) {
374        RefreshableJob job = (RefreshableJob)item;
375        if (job.RefreshAutomatically) {
376          job.StopResultPolling();
377        }
[15630]378        HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJobState(item.Id, JobState.StatisticsPending));
[7144]379      }
[6976]380      if (item is JobPermission) {
381        var hep = (JobPermission)item;
[7132]382        HiveServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
[6976]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    }
[9219]399    public event EventHandler HiveJobsChanged;
400    private void OnHiveJobsChanged() {
401      var handler = HiveJobsChanged;
[6976]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) {
[7132]416      HiveServiceLocator.Instance.CallHiveService(service => {
[6976]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) {
[7132]426      HiveServiceLocator.Instance.CallHiveService(service => {
[6976]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      });
[7156]432      refreshableJob.ExecutionState = ExecutionState.Stopped;
[6976]433    }
434
[7156]435    public static void ResumeJob(RefreshableJob refreshableJob) {
436      HiveServiceLocator.Instance.CallHiveService(service => {
437        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
[7165]438          if (task.Task.State == TaskState.Paused) {
439            service.RestartTask(task.Task.Id);
[7156]440          }
441        }
442      });
443      refreshableJob.ExecutionState = ExecutionState.Started;
444    }
445
[15642]446    public static void UpdateJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
[15992]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();
[15642]455    }
456
[15992]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
[6976]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();
[15742]477    private Guid UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
[6976]478      try {
[8156]479        refreshableJob.IsProgressing = true;
[9893]480        refreshableJob.Progress.Start("Connecting to server...");
[6976]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...";
[15630]488        refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job, refreshableJob.Job.ResourceIds));
[7132]489        refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
[6976]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...";
[7132]498        this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
[6976]499        this.AlreadyUploadedPlugins = new List<Plugin>();
[7132]500        Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
[6976]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) {
[8939]509          var task = TS.Task.Factory.StartNew((hj) => {
[15630]510            UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
[8939]511          }, hiveTask);
512          task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
513          tasks.Add(task);
[6976]514        }
[8939]515        TS.Task.WaitAll(tasks.ToArray());
[7582]516      }
517      finally {
[8939]518        refreshableJob.Job.Modified = false;
[8159]519        refreshableJob.IsProgressing = false;
[8156]520        refreshableJob.Progress.Finish();
[6976]521      }
[15742]522      return (refreshableJob.Job != null) ? refreshableJob.Job.Id : Guid.Empty;
[6976]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>
[15630]556    private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
[6976]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
[10130]567        if (hiveTask.ItemTask.ComputeInParallel) {
[6976]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) {
[7132]581              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
[6976]582            }
583          }
[7125]584        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
[6976]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) {
[7132]593              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
[6976]594            } else {
[15630]595              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData));
[6976]596            }
597          }
[7125]598        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
[6976]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) {
[8939]608          var task = TS.Task.Factory.StartNew((tuple) => {
[6976]609            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
[15630]610            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
[8939]611          }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
612          task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
613          tasks.Add(task);
[6976]614        }
615        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
[8939]616        TS.Task.WaitAll(tasks.ToArray());
[15630]617      } finally {
[6976]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;
[8156]626      refreshableJob.IsProgressing = true;
[9219]627      TaskDownloader downloader = null;
[6976]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
[9893]634        refreshableJob.Progress.Start("Downloading list of tasks...");
[9219]635        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
[6976]636        totalJobCount = allTasks.Count();
637
[7125]638        refreshableJob.Progress.Status = "Downloading tasks...";
[9219]639        downloader = new TaskDownloader(allTasks.Select(x => x.Id));
[6976]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;
[7165]652        var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
[6976]653
[7165]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        }
[6976]659
[7165]660        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
[6976]661        if (refreshableJob.IsFinished()) {
662          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
[14901]663        } else if (refreshableJob.IsPaused()) {
664          refreshableJob.ExecutionState = Core.ExecutionState.Paused;
665        } else {
[6976]666          refreshableJob.ExecutionState = Core.ExecutionState.Started;
667        }
668        refreshableJob.OnLoaded();
[7582]669      }
670      finally {
[8159]671        refreshableJob.IsProgressing = false;
[8156]672        refreshableJob.Progress.Finish();
[9219]673        if (downloader != null) {
674          downloader.Dispose();
675        }
[6976]676      }
677    }
678
[7125]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
[6976]682                                                orderby job.DateCreated ascending
683                                                select job;
684      foreach (LightweightTask task in childTasks) {
[7125]685        HiveTask childHiveTask = allHiveTasks[task.Id];
[8700]686        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
[7125]687        parentHiveTask.AddChildHiveTask(childHiveTask);
[6976]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)) {
[8109]697        return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
[6976]698      } else {
699        return new List<string>();
700      }
701    }
702
703    public static ItemTask LoadItemJob(Guid jobId) {
[7132]704      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
[6976]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) {
[7132]729      return HiveServiceLocator.Instance.CallHiveService((service) => {
[6976]730        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
731        foreach (var hep in jps) {
[7059]732          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
[6976]733        }
734        return new HiveItemCollection<JobPermission>(jps);
735      });
736    }
[15992]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    }
[6976]744  }
[10130]745}
Note: See TracBrowser for help on using the repository browser.