Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2839:

  • adapted icons: replaced ".PublishToWeb" with ".Save"
  • pre-select project with all resources for new jobs, if it is the only available
File size: 29.8 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
322    public IEnumerable<Resource> GetAvailableResourcesForProject(Guid id) {
323      var assignedProjectResources = HiveServiceLocator.Instance.CallHiveService(s => s.GetAssignedResourcesForProject(id));
324      return resources.Where(x => assignedProjectResources.Select(y => y.ResourceId).Contains(x.Id));
325    }
326    #endregion
327
328    #region Store
329    public static void Store(IHiveItem item, CancellationToken cancellationToken) {
330      if (item.Id == Guid.Empty) {
331        if (item is RefreshableJob) {
332          item.Id = HiveClient.Instance.UploadJob((RefreshableJob)item, cancellationToken);
333        }
334        if (item is JobPermission) {
335          var hep = (JobPermission)item;
336          hep.GrantedUserId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
337          if (hep.GrantedUserId == Guid.Empty) {
338            throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
339          }
340          HiveServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
341        }
342        if (item is Project) {
343          item.Id = HiveServiceLocator.Instance.CallHiveService(s => s.AddProject((Project)item));
344        }
345      } else {
346        if (item is Job) {
347          var job = (Job)item;
348          HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJob(job, job.ResourceIds));
349        }
350        if (item is Project)
351          HiveServiceLocator.Instance.CallHiveService(s => s.UpdateProject((Project)item));
352      }
353    }
354    public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
355      var call = new Func<Exception>(delegate() {
356        try {
357          Store(item, cancellationToken);
358        }
359        catch (Exception ex) {
360          return ex;
361        }
362        return null;
363      });
364      call.BeginInvoke(delegate(IAsyncResult result) {
365        Exception ex = call.EndInvoke(result);
366        if (ex != null) exceptionCallback(ex);
367      }, null);
368    }
369    #endregion
370
371    #region Delete
372    public static void Delete(IHiveItem item) {
373      if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
374        return;
375
376      if (item is Job)
377        HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJobState(item.Id, JobState.StatisticsPending));
378      if (item is RefreshableJob) {
379        RefreshableJob job = (RefreshableJob)item;
380        if (job.RefreshAutomatically) {
381          job.StopResultPolling();
382        }
383        HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJobState(item.Id, JobState.StatisticsPending));
384      }
385      if (item is JobPermission) {
386        var hep = (JobPermission)item;
387        HiveServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
388      }
389      item.Id = Guid.Empty;
390    }
391    #endregion
392
393    #region Events
394    public event EventHandler Refreshing;
395    private void OnRefreshing() {
396      EventHandler handler = Refreshing;
397      if (handler != null) handler(this, EventArgs.Empty);
398    }
399    public event EventHandler Refreshed;
400    private void OnRefreshed() {
401      var handler = Refreshed;
402      if (handler != null) handler(this, EventArgs.Empty);
403    }
404    public event EventHandler HiveJobsChanged;
405    private void OnHiveJobsChanged() {
406      var handler = HiveJobsChanged;
407      if (handler != null) handler(this, EventArgs.Empty);
408    }
409    #endregion
410
411    public static void StartJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
412      HiveClient.StoreAsync(
413        new Action<Exception>((Exception ex) => {
414          refreshableJob.ExecutionState = ExecutionState.Prepared;
415          exceptionCallback(ex);
416        }), refreshableJob, cancellationToken);
417      refreshableJob.ExecutionState = ExecutionState.Started;
418    }
419
420    public static void PauseJob(RefreshableJob refreshableJob) {
421      HiveServiceLocator.Instance.CallHiveService(service => {
422        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
423          if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
424            service.PauseTask(task.Task.Id);
425        }
426      });
427      refreshableJob.ExecutionState = ExecutionState.Paused;
428    }
429
430    public static void StopJob(RefreshableJob refreshableJob) {
431      HiveServiceLocator.Instance.CallHiveService(service => {
432        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
433          if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
434            service.StopTask(task.Task.Id);
435        }
436      });
437      refreshableJob.ExecutionState = ExecutionState.Stopped;
438    }
439
440    public static void ResumeJob(RefreshableJob refreshableJob) {
441      HiveServiceLocator.Instance.CallHiveService(service => {
442        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
443          if (task.Task.State == TaskState.Paused) {
444            service.RestartTask(task.Task.Id);
445          }
446        }
447      });
448      refreshableJob.ExecutionState = ExecutionState.Started;
449    }
450
451    public static void UpdateJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
452      refreshableJob.IsProgressing = true;
453      refreshableJob.Progress.Status = "Saving Job...";
454      HiveClient.StoreAsync(
455        new Action<Exception>((Exception ex) => {
456          exceptionCallback(ex);
457        }), refreshableJob.Job, cancellationToken);
458      refreshableJob.IsProgressing = false;
459      refreshableJob.Progress.Finish();
460    }
461
462    public static void UpdateJob(RefreshableJob refreshableJob) {
463      refreshableJob.IsProgressing = true;
464
465      try {
466        refreshableJob.Progress.Start("Saving Job...");
467        HiveClient.StoreAsync(new Action<Exception>((Exception ex) => {
468          throw new Exception("Update failed.", ex);
469        }), refreshableJob.Job, new CancellationToken());
470      } finally {
471        refreshableJob.IsProgressing = false;
472        refreshableJob.Progress.Finish();
473      }
474    }
475
476
477
478    #region Upload Job
479    private Semaphore taskUploadSemaphore = new Semaphore(Settings.Default.MaxParallelUploads, Settings.Default.MaxParallelUploads);
480    private static object jobCountLocker = new object();
481    private static object pluginLocker = new object();
482    private Guid UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
483      try {
484        refreshableJob.IsProgressing = true;
485        refreshableJob.Progress.Start("Connecting to server...");
486
487        foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>()) {
488          hiveJob.SetIndexInParentOptimizerList(null);
489        }
490
491        // upload Job
492        refreshableJob.Progress.Status = "Uploading Job...";
493        refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job, refreshableJob.Job.ResourceIds));
494        refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
495        cancellationToken.ThrowIfCancellationRequested();
496
497        int totalJobCount = refreshableJob.GetAllHiveTasks().Count();
498        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
499        cancellationToken.ThrowIfCancellationRequested();
500
501        // upload plugins
502        refreshableJob.Progress.Status = "Uploading plugins...";
503        this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
504        this.AlreadyUploadedPlugins = new List<Plugin>();
505        Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
506        this.alreadyUploadedPlugins.Add(configFilePlugin);
507        cancellationToken.ThrowIfCancellationRequested();
508
509        // upload tasks
510        refreshableJob.Progress.Status = "Uploading tasks...";
511
512        var tasks = new List<TS.Task>();
513        foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
514          var task = TS.Task.Factory.StartNew((hj) => {
515            UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
516          }, hiveTask);
517          task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
518          tasks.Add(task);
519        }
520        TS.Task.WaitAll(tasks.ToArray());
521      }
522      finally {
523        refreshableJob.Job.Modified = false;
524        refreshableJob.IsProgressing = false;
525        refreshableJob.Progress.Finish();
526      }
527      return (refreshableJob.Job != null) ? refreshableJob.Job.Id : Guid.Empty;
528    }
529
530    /// <summary>
531    /// Uploads the local configuration file as plugin
532    /// </summary>
533    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
534      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
535      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
536      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
537      byte[] hash;
538
539      byte[] data = File.ReadAllBytes(configFilePath);
540      using (SHA1 sha1 = SHA1.Create()) {
541        hash = sha1.ComputeHash(data);
542      }
543
544      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
545      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
546
547      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
548
549      if (onlineConfig.Count() > 0) {
550        return onlineConfig.First();
551      } else {
552        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
553        return configPlugin;
554      }
555    }
556
557    /// <summary>
558    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
559    /// </summary>
560    /// <param name="parentHiveTask">shall be null if its the root task</param>
561    private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
562      taskUploadSemaphore.WaitOne();
563      bool semaphoreReleased = false;
564      try {
565        cancellationToken.ThrowIfCancellationRequested();
566        lock (jobCountLocker) {
567          taskCount[0]++;
568        }
569        TaskData taskData;
570        List<IPluginDescription> plugins;
571
572        if (hiveTask.ItemTask.ComputeInParallel) {
573          hiveTask.Task.IsParentTask = true;
574          hiveTask.Task.FinishWhenChildJobsFinished = true;
575          taskData = hiveTask.GetAsTaskData(true, out plugins);
576        } else {
577          hiveTask.Task.IsParentTask = false;
578          hiveTask.Task.FinishWhenChildJobsFinished = false;
579          taskData = hiveTask.GetAsTaskData(false, out plugins);
580        }
581        cancellationToken.ThrowIfCancellationRequested();
582
583        TryAndRepeat(() => {
584          if (!cancellationToken.IsCancellationRequested) {
585            lock (pluginLocker) {
586              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
587            }
588          }
589        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
590        cancellationToken.ThrowIfCancellationRequested();
591        hiveTask.Task.PluginsNeededIds.Add(configPluginId);
592        hiveTask.Task.JobId = jobId;
593
594        log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
595        TryAndRepeat(() => {
596          if (!cancellationToken.IsCancellationRequested) {
597            if (parentHiveTask != null) {
598              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
599            } else {
600              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData));
601            }
602          }
603        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
604        cancellationToken.ThrowIfCancellationRequested();
605
606        lock (jobCountLocker) {
607          progress.ProgressValue = (double)taskCount[0] / totalJobCount;
608          progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
609        }
610
611        var tasks = new List<TS.Task>();
612        foreach (HiveTask child in hiveTask.ChildHiveTasks) {
613          var task = TS.Task.Factory.StartNew((tuple) => {
614            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
615            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
616          }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
617          task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
618          tasks.Add(task);
619        }
620        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
621        TS.Task.WaitAll(tasks.ToArray());
622      } finally {
623        if (!semaphoreReleased) taskUploadSemaphore.Release();
624      }
625    }
626    #endregion
627
628    #region Download Experiment
629    public static void LoadJob(RefreshableJob refreshableJob) {
630      var hiveExperiment = refreshableJob.Job;
631      refreshableJob.IsProgressing = true;
632      TaskDownloader downloader = null;
633
634      try {
635        int totalJobCount = 0;
636        IEnumerable<LightweightTask> allTasks;
637
638        // fetch all task objects to create the full tree of tree of HiveTask objects
639        refreshableJob.Progress.Start("Downloading list of tasks...");
640        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
641        totalJobCount = allTasks.Count();
642
643        refreshableJob.Progress.Status = "Downloading tasks...";
644        downloader = new TaskDownloader(allTasks.Select(x => x.Id));
645        downloader.StartAsync();
646
647        while (!downloader.IsFinished) {
648          refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
649          refreshableJob.Progress.Status = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
650          Thread.Sleep(500);
651
652          if (downloader.IsFaulted) {
653            throw downloader.Exception;
654          }
655        }
656        IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
657        var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
658
659        refreshableJob.Progress.Status = "Downloading/deserializing complete. Displaying tasks...";
660        // build child-task tree
661        foreach (HiveTask hiveTask in parents) {
662          BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
663        }
664
665        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
666        if (refreshableJob.IsFinished()) {
667          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
668        } else if (refreshableJob.IsPaused()) {
669          refreshableJob.ExecutionState = Core.ExecutionState.Paused;
670        } else {
671          refreshableJob.ExecutionState = Core.ExecutionState.Started;
672        }
673        refreshableJob.OnLoaded();
674      }
675      finally {
676        refreshableJob.IsProgressing = false;
677        refreshableJob.Progress.Finish();
678        if (downloader != null) {
679          downloader.Dispose();
680        }
681      }
682    }
683
684    private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
685      IEnumerable<LightweightTask> childTasks = from job in allTasks
686                                                where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
687                                                orderby job.DateCreated ascending
688                                                select job;
689      foreach (LightweightTask task in childTasks) {
690        HiveTask childHiveTask = allHiveTasks[task.Id];
691        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
692        parentHiveTask.AddChildHiveTask(childHiveTask);
693      }
694    }
695    #endregion
696
697    /// <summary>
698    /// Converts a string which can contain Ids separated by ';' to a enumerable
699    /// </summary>
700    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
701      if (!string.IsNullOrEmpty(resourceNames)) {
702        return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
703      } else {
704        return new List<string>();
705      }
706    }
707
708    public static ItemTask LoadItemJob(Guid jobId) {
709      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
710      try {
711        return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
712      }
713      catch {
714        return null;
715      }
716    }
717
718    /// <summary>
719    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
720    /// If repetitions is -1, it is repeated infinitely.
721    /// </summary>
722    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
723      while (true) {
724        try { action(); return; }
725        catch (Exception e) {
726          if (repetitions == 0) throw new HiveException(errorMessage, e);
727          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
728          repetitions--;
729        }
730      }
731    }
732
733    public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
734      return HiveServiceLocator.Instance.CallHiveService((service) => {
735        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
736        foreach (var hep in jps) {
737          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
738        }
739        return new HiveItemCollection<JobPermission>(jps);
740      });
741    }
742
743    public string GetProjectAncestry(Guid projectId) {
744      if (projectId == null || projectId == Guid.Empty) return "";
745      var projects = projectAncestors[projectId].Reverse().ToList();
746      projects.Add(projectId);
747      return string.Join(" » ", projects.Select(x => ProjectNames[x]).ToArray());
748    }
749  }
750}
Note: See TracBrowser for help on using the repository browser.