Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2845_EnhancedProgress/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 16307

Last change on this file since 16307 was 16307, checked in by pfleck, 5 years ago

#2845 Merged trunk changes before source move into branch

File size: 21.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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 List<Plugin> onlinePlugins;
60    public List<Plugin> OnlinePlugins {
61      get { return onlinePlugins; }
62      set { onlinePlugins = value; }
63    }
64
65    private List<Plugin> alreadyUploadedPlugins;
66    public List<Plugin> AlreadyUploadedPlugins {
67      get { return alreadyUploadedPlugins; }
68      set { alreadyUploadedPlugins = value; }
69    }
70    #endregion
71
72    private HiveClient() { }
73
74    public void ClearHiveClient() {
75      Jobs.ClearWithoutHiveDeletion();
76      foreach (var j in Jobs) {
77        if (j.RefreshAutomatically) {
78          j.RefreshAutomatically = false; // stop result polling
79        }
80        j.Dispose();
81      }
82      Jobs = null;
83
84      if (onlinePlugins != null)
85        onlinePlugins.Clear();
86      if (alreadyUploadedPlugins != null)
87        alreadyUploadedPlugins.Clear();
88    }
89
90    #region Refresh
91    public void Refresh() {
92      OnRefreshing();
93
94      try {
95        jobs = new HiveItemCollection<RefreshableJob>();
96        var jobsLoaded = HiveServiceLocator.Instance.CallHiveService<IEnumerable<Job>>(s => s.GetJobs());
97
98        try {
99          foreach (var j in jobsLoaded) {
100            jobs.Add(new RefreshableJob(j));
101          }
102        } catch (NullReferenceException) {
103          // jobs was set to null during ClearHiveClient
104        }
105      } catch {
106        jobs = null;
107        throw;
108      } finally {
109        OnRefreshed();
110      }
111    }
112    #endregion
113
114    #region Store
115    public static void Store(IHiveItem item, CancellationToken cancellationToken) {
116      if (item.Id == Guid.Empty) {
117        if (item is RefreshableJob) {
118          HiveClient.Instance.UploadJob((RefreshableJob)item, cancellationToken);
119        }
120        if (item is JobPermission) {
121          var hep = (JobPermission)item;
122          hep.GrantedUserId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
123          if (hep.GrantedUserId == Guid.Empty) {
124            throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
125          }
126          HiveServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
127        }
128      } else {
129        if (item is Job)
130          HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJob((Job)item));
131      }
132    }
133    public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
134      var call = new Func<Exception>(delegate () {
135        try {
136          Store(item, cancellationToken);
137        } catch (Exception ex) {
138          return ex;
139        }
140        return null;
141      });
142      call.BeginInvoke(delegate (IAsyncResult result) {
143        Exception ex = call.EndInvoke(result);
144        if (ex != null) exceptionCallback(ex);
145      }, null);
146    }
147    #endregion
148
149    #region Delete
150    public static void Delete(IHiveItem item) {
151      if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
152        return;
153
154      if (item is Job)
155        HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(item.Id));
156      if (item is RefreshableJob) {
157        RefreshableJob job = (RefreshableJob)item;
158        if (job.RefreshAutomatically) {
159          job.StopResultPolling();
160        }
161        HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(item.Id));
162      }
163      if (item is JobPermission) {
164        var hep = (JobPermission)item;
165        HiveServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
166      }
167      item.Id = Guid.Empty;
168    }
169    #endregion
170
171    #region Events
172    public event EventHandler Refreshing;
173    private void OnRefreshing() {
174      EventHandler handler = Refreshing;
175      if (handler != null) handler(this, EventArgs.Empty);
176    }
177    public event EventHandler Refreshed;
178    private void OnRefreshed() {
179      var handler = Refreshed;
180      if (handler != null) handler(this, EventArgs.Empty);
181    }
182    public event EventHandler HiveJobsChanged;
183    private void OnHiveJobsChanged() {
184      var handler = HiveJobsChanged;
185      if (handler != null) handler(this, EventArgs.Empty);
186    }
187    #endregion
188
189    public static void StartJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
190      HiveClient.StoreAsync(
191        new Action<Exception>((Exception ex) => {
192          refreshableJob.ExecutionState = ExecutionState.Prepared;
193          exceptionCallback(ex);
194        }), refreshableJob, cancellationToken);
195      refreshableJob.ExecutionState = ExecutionState.Started;
196    }
197
198    public static void PauseJob(RefreshableJob refreshableJob) {
199      HiveServiceLocator.Instance.CallHiveService(service => {
200        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
201          if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
202            service.PauseTask(task.Task.Id);
203        }
204      });
205      refreshableJob.ExecutionState = ExecutionState.Paused;
206    }
207
208    public static void StopJob(RefreshableJob refreshableJob) {
209      HiveServiceLocator.Instance.CallHiveService(service => {
210        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
211          if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
212            service.StopTask(task.Task.Id);
213        }
214      });
215      refreshableJob.ExecutionState = ExecutionState.Stopped;
216    }
217
218    public static void ResumeJob(RefreshableJob refreshableJob) {
219      HiveServiceLocator.Instance.CallHiveService(service => {
220        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
221          if (task.Task.State == TaskState.Paused) {
222            service.RestartTask(task.Task.Id);
223          }
224        }
225      });
226      refreshableJob.ExecutionState = ExecutionState.Started;
227    }
228
229    #region Upload Job
230    private Semaphore taskUploadSemaphore = new Semaphore(Settings.Default.MaxParallelUploads, Settings.Default.MaxParallelUploads);
231    private static object jobCountLocker = new object();
232    private static object pluginLocker = new object();
233    private void UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
234      try {
235        refreshableJob.IsProgressing = true;
236        refreshableJob.Progress.StartMarquee("Connecting to server...");
237        IEnumerable<string> resourceNames = ToResourceNameList(refreshableJob.Job.ResourceNames);
238        var resourceIds = new List<Guid>();
239        foreach (var resourceName in resourceNames) {
240          Guid resourceId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetResourceId(resourceName));
241          if (resourceId == Guid.Empty) {
242            throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
243          }
244          resourceIds.Add(resourceId);
245        }
246
247        foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>()) {
248          hiveJob.SetIndexInParentOptimizerList(null);
249        }
250
251        // upload Job
252        refreshableJob.Progress.Message = "Uploading Job...";
253        refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job));
254        refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
255        cancellationToken.ThrowIfCancellationRequested();
256
257        int totalJobCount = refreshableJob.GetAllHiveTasks().Count();
258        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
259        cancellationToken.ThrowIfCancellationRequested();
260
261        // upload plugins
262        refreshableJob.Progress.Message = "Uploading plugins...";
263        this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
264        this.AlreadyUploadedPlugins = new List<Plugin>();
265        Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
266        this.alreadyUploadedPlugins.Add(configFilePlugin);
267        cancellationToken.ThrowIfCancellationRequested();
268
269        // upload tasks
270        refreshableJob.Progress.Message = "Uploading tasks...";
271        refreshableJob.Progress.ProgressBarMode = ProgressBarMode.Continuous;
272        refreshableJob.Progress.ProgressValue = 0;
273       
274        var tasks = new List<TS.Task>();
275        foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
276          var task = TS.Task.Factory.StartNew((hj) => {
277            UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, resourceIds, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
278          }, hiveTask);
279          task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
280          tasks.Add(task);
281        }
282        TS.Task.WaitAll(tasks.ToArray());
283      } finally {
284        refreshableJob.Job.Modified = false;
285        refreshableJob.IsProgressing = false;
286        refreshableJob.Progress.Finish();
287      }
288    }
289
290    /// <summary>
291    /// Uploads the local configuration file as plugin
292    /// </summary>
293    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
294      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
295      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
296      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
297      byte[] hash;
298
299      byte[] data = File.ReadAllBytes(configFilePath);
300      using (SHA1 sha1 = SHA1.Create()) {
301        hash = sha1.ComputeHash(data);
302      }
303
304      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
305      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
306
307      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
308
309      if (onlineConfig.Count() > 0) {
310        return onlineConfig.First();
311      } else {
312        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
313        return configPlugin;
314      }
315    }
316
317    /// <summary>
318    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
319    /// </summary>
320    /// <param name="parentHiveTask">shall be null if its the root task</param>
321    private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, IEnumerable<Guid> groups, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
322      taskUploadSemaphore.WaitOne();
323      bool semaphoreReleased = false;
324      try {
325        cancellationToken.ThrowIfCancellationRequested();
326        lock (jobCountLocker) {
327          taskCount[0]++;
328        }
329        TaskData taskData;
330        List<IPluginDescription> plugins;
331
332        if (hiveTask.ItemTask.ComputeInParallel) {
333          hiveTask.Task.IsParentTask = true;
334          hiveTask.Task.FinishWhenChildJobsFinished = true;
335          taskData = hiveTask.GetAsTaskData(true, out plugins);
336        } else {
337          hiveTask.Task.IsParentTask = false;
338          hiveTask.Task.FinishWhenChildJobsFinished = false;
339          taskData = hiveTask.GetAsTaskData(false, out plugins);
340        }
341        cancellationToken.ThrowIfCancellationRequested();
342
343        TryAndRepeat(() => {
344          if (!cancellationToken.IsCancellationRequested) {
345            lock (pluginLocker) {
346              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
347            }
348          }
349        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
350        cancellationToken.ThrowIfCancellationRequested();
351        hiveTask.Task.PluginsNeededIds.Add(configPluginId);
352        hiveTask.Task.JobId = jobId;
353
354        log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
355        TryAndRepeat(() => {
356          if (!cancellationToken.IsCancellationRequested) {
357            if (parentHiveTask != null) {
358              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
359            } else {
360              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
361            }
362          }
363        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
364        cancellationToken.ThrowIfCancellationRequested();
365
366        lock (jobCountLocker) {
367          progress.ProgressValue = (double)taskCount[0] / totalJobCount;
368          progress.Message = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
369        }
370
371        var tasks = new List<TS.Task>();
372        foreach (HiveTask child in hiveTask.ChildHiveTasks) {
373          var task = TS.Task.Factory.StartNew((tuple) => {
374            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
375            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
376          }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
377          task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
378          tasks.Add(task);
379        }
380        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
381        TS.Task.WaitAll(tasks.ToArray());
382      } finally {
383        if (!semaphoreReleased) taskUploadSemaphore.Release();
384      }
385    }
386    #endregion
387
388    #region Download Experiment
389    public static void LoadJob(RefreshableJob refreshableJob) {
390      var hiveExperiment = refreshableJob.Job;
391      refreshableJob.IsProgressing = true;
392      TaskDownloader downloader = null;
393
394      try {
395        int totalJobCount = 0;
396        IEnumerable<LightweightTask> allTasks;
397
398        // fetch all task objects to create the full tree of tree of HiveTask objects
399        refreshableJob.Progress.StartMarquee("Downloading list of tasks...");
400        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
401        totalJobCount = allTasks.Count();
402
403        refreshableJob.Progress.Message = "Downloading tasks...";
404        refreshableJob.Progress.ProgressBarMode = ProgressBarMode.Continuous;
405        refreshableJob.Progress.ProgressValue = 0.0;
406        downloader = new TaskDownloader(allTasks.Select(x => x.Id));
407        downloader.StartAsync();
408
409        while (!downloader.IsFinished) {
410          refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
411          refreshableJob.Progress.Message = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
412          Thread.Sleep(500);
413
414          if (downloader.IsFaulted) {
415            throw downloader.Exception;
416          }
417        }
418        IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
419        var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
420
421        refreshableJob.Progress.Message = "Downloading/deserializing complete. Displaying tasks...";
422        refreshableJob.Progress.ProgressBarMode = ProgressBarMode.Marquee;
423
424        // build child-task tree
425        foreach (HiveTask hiveTask in parents) {
426          BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
427        }
428
429        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
430        if (refreshableJob.IsFinished()) {
431          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
432        } else if (refreshableJob.IsPaused()) {
433          refreshableJob.ExecutionState = Core.ExecutionState.Paused;
434        } else {
435          refreshableJob.ExecutionState = Core.ExecutionState.Started;
436        }
437        refreshableJob.OnLoaded();
438      } finally {
439        refreshableJob.IsProgressing = false;
440        refreshableJob.Progress.Finish();
441        if (downloader != null) {
442          downloader.Dispose();
443        }
444      }
445    }
446
447    private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
448      IEnumerable<LightweightTask> childTasks = from job in allTasks
449                                                where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
450                                                orderby job.DateCreated ascending
451                                                select job;
452      foreach (LightweightTask task in childTasks) {
453        HiveTask childHiveTask = allHiveTasks[task.Id];
454        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
455        parentHiveTask.AddChildHiveTask(childHiveTask);
456      }
457    }
458    #endregion
459
460    /// <summary>
461    /// Converts a string which can contain Ids separated by ';' to a enumerable
462    /// </summary>
463    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
464      if (!string.IsNullOrEmpty(resourceNames)) {
465        return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
466      } else {
467        return new List<string>();
468      }
469    }
470
471    public static ItemTask LoadItemJob(Guid jobId) {
472      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
473      try {
474        return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
475      } catch {
476        return null;
477      }
478    }
479
480    /// <summary>
481    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
482    /// If repetitions is -1, it is repeated infinitely.
483    /// </summary>
484    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
485      while (true) {
486        try { action(); return; } catch (Exception e) {
487          if (repetitions == 0) throw new HiveException(errorMessage, e);
488          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
489          repetitions--;
490        }
491      }
492    }
493
494    public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
495      return HiveServiceLocator.Instance.CallHiveService((service) => {
496        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
497        foreach (var hep in jps) {
498          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
499        }
500        return new HiveItemCollection<JobPermission>(jps);
501      });
502    }
503  }
504}
Note: See TracBrowser for help on using the repository browser.