Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2522_RefactorPluginInfrastructure/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 16811

Last change on this file since 16811 was 15973, checked in by gkronber, 6 years ago

#2522: merged trunk changes from r13402:15972 to branch resolving conflicts where necessary

File size: 20.6 KB
RevLine 
[6976]1#region License Information
2/* HeuristicLab
[15973]3 * Copyright (C) 2002-2018 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
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
[12579]72    private HiveClient() { }
[6976]73
[9219]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
[6976]90    #region Refresh
91    public void Refresh() {
92      OnRefreshing();
93
94      try {
95        jobs = new HiveItemCollection<RefreshableJob>();
[7132]96        var jobsLoaded = HiveServiceLocator.Instance.CallHiveService<IEnumerable<Job>>(s => s.GetJobs());
[6976]97
[15973]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
[6976]104        }
[15973]105      } catch {
[6976]106        jobs = null;
107        throw;
[15973]108      } finally {
[6976]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;
[7132]122          hep.GrantedUserId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
[6976]123          if (hep.GrantedUserId == Guid.Empty) {
124            throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
125          }
[7132]126          HiveServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
[6976]127        }
128      } else {
129        if (item is Job)
[7132]130          HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJob((Job)item));
[6976]131      }
132    }
133    public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
[15973]134      var call = new Func<Exception>(delegate () {
[6976]135        try {
136          Store(item, cancellationToken);
[15973]137        } catch (Exception ex) {
[6976]138          return ex;
139        }
140        return null;
141      });
[15973]142      call.BeginInvoke(delegate (IAsyncResult result) {
[6976]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) {
[7059]151      if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
[6976]152        return;
153
154      if (item is Job)
[7132]155        HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(item.Id));
[7144]156      if (item is RefreshableJob) {
157        RefreshableJob job = (RefreshableJob)item;
158        if (job.RefreshAutomatically) {
159          job.StopResultPolling();
160        }
[7132]161        HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(item.Id));
[7144]162      }
[6976]163      if (item is JobPermission) {
164        var hep = (JobPermission)item;
[7132]165        HiveServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
[6976]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    }
[9219]182    public event EventHandler HiveJobsChanged;
183    private void OnHiveJobsChanged() {
184      var handler = HiveJobsChanged;
[6976]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) {
[7132]199      HiveServiceLocator.Instance.CallHiveService(service => {
[6976]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) {
[7132]209      HiveServiceLocator.Instance.CallHiveService(service => {
[6976]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      });
[7156]215      refreshableJob.ExecutionState = ExecutionState.Stopped;
[6976]216    }
217
[7156]218    public static void ResumeJob(RefreshableJob refreshableJob) {
219      HiveServiceLocator.Instance.CallHiveService(service => {
220        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
[7165]221          if (task.Task.State == TaskState.Paused) {
222            service.RestartTask(task.Task.Id);
[7156]223          }
224        }
225      });
226      refreshableJob.ExecutionState = ExecutionState.Started;
227    }
228
[6976]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 {
[8156]235        refreshableJob.IsProgressing = true;
[9893]236        refreshableJob.Progress.Start("Connecting to server...");
[6976]237        IEnumerable<string> resourceNames = ToResourceNameList(refreshableJob.Job.ResourceNames);
238        var resourceIds = new List<Guid>();
239        foreach (var resourceName in resourceNames) {
[7132]240          Guid resourceId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetResourceId(resourceName));
[6976]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.Status = "Uploading Job...";
[7132]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
[6976]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.Status = "Uploading plugins...";
[7132]263        this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
[6976]264        this.AlreadyUploadedPlugins = new List<Plugin>();
[7132]265        Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
[6976]266        this.alreadyUploadedPlugins.Add(configFilePlugin);
267        cancellationToken.ThrowIfCancellationRequested();
268
269        // upload tasks
270        refreshableJob.Progress.Status = "Uploading tasks...";
271
272        var tasks = new List<TS.Task>();
273        foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
[8939]274          var task = TS.Task.Factory.StartNew((hj) => {
[12926]275            UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, resourceIds, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
[8939]276          }, hiveTask);
277          task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
278          tasks.Add(task);
[6976]279        }
[8939]280        TS.Task.WaitAll(tasks.ToArray());
[15973]281      } finally {
[8939]282        refreshableJob.Job.Modified = false;
[8159]283        refreshableJob.IsProgressing = false;
[8156]284        refreshableJob.Progress.Finish();
[6976]285      }
286    }
287
288    /// <summary>
289    /// Uploads the local configuration file as plugin
290    /// </summary>
291    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
292      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
293      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
294      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
295      byte[] hash;
296
297      byte[] data = File.ReadAllBytes(configFilePath);
298      using (SHA1 sha1 = SHA1.Create()) {
299        hash = sha1.ComputeHash(data);
300      }
301
302      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
303      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
304
305      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
306
307      if (onlineConfig.Count() > 0) {
308        return onlineConfig.First();
309      } else {
310        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
311        return configPlugin;
312      }
313    }
314
315    /// <summary>
316    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
317    /// </summary>
318    /// <param name="parentHiveTask">shall be null if its the root task</param>
[12926]319    private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, IEnumerable<Guid> groups, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
[6976]320      taskUploadSemaphore.WaitOne();
321      bool semaphoreReleased = false;
322      try {
323        cancellationToken.ThrowIfCancellationRequested();
324        lock (jobCountLocker) {
325          taskCount[0]++;
326        }
327        TaskData taskData;
328        List<IPluginDescription> plugins;
329
[10130]330        if (hiveTask.ItemTask.ComputeInParallel) {
[6976]331          hiveTask.Task.IsParentTask = true;
332          hiveTask.Task.FinishWhenChildJobsFinished = true;
333          taskData = hiveTask.GetAsTaskData(true, out plugins);
334        } else {
335          hiveTask.Task.IsParentTask = false;
336          hiveTask.Task.FinishWhenChildJobsFinished = false;
337          taskData = hiveTask.GetAsTaskData(false, out plugins);
338        }
339        cancellationToken.ThrowIfCancellationRequested();
340
341        TryAndRepeat(() => {
342          if (!cancellationToken.IsCancellationRequested) {
343            lock (pluginLocker) {
[7132]344              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
[6976]345            }
346          }
[7125]347        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
[6976]348        cancellationToken.ThrowIfCancellationRequested();
349        hiveTask.Task.PluginsNeededIds.Add(configPluginId);
350        hiveTask.Task.JobId = jobId;
351
352        log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
353        TryAndRepeat(() => {
354          if (!cancellationToken.IsCancellationRequested) {
355            if (parentHiveTask != null) {
[7132]356              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
[6976]357            } else {
[7132]358              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
[6976]359            }
360          }
[7125]361        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
[6976]362        cancellationToken.ThrowIfCancellationRequested();
363
364        lock (jobCountLocker) {
365          progress.ProgressValue = (double)taskCount[0] / totalJobCount;
366          progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
367        }
368
369        var tasks = new List<TS.Task>();
370        foreach (HiveTask child in hiveTask.ChildHiveTasks) {
[8939]371          var task = TS.Task.Factory.StartNew((tuple) => {
[6976]372            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
[12926]373            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
[8939]374          }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
375          task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
376          tasks.Add(task);
[6976]377        }
378        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
[8939]379        TS.Task.WaitAll(tasks.ToArray());
[15973]380      } finally {
[6976]381        if (!semaphoreReleased) taskUploadSemaphore.Release();
382      }
383    }
384    #endregion
385
386    #region Download Experiment
387    public static void LoadJob(RefreshableJob refreshableJob) {
388      var hiveExperiment = refreshableJob.Job;
[8156]389      refreshableJob.IsProgressing = true;
[9219]390      TaskDownloader downloader = null;
[6976]391
392      try {
393        int totalJobCount = 0;
394        IEnumerable<LightweightTask> allTasks;
395
396        // fetch all task objects to create the full tree of tree of HiveTask objects
[9893]397        refreshableJob.Progress.Start("Downloading list of tasks...");
[9219]398        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
[6976]399        totalJobCount = allTasks.Count();
400
[7125]401        refreshableJob.Progress.Status = "Downloading tasks...";
[9219]402        downloader = new TaskDownloader(allTasks.Select(x => x.Id));
[6976]403        downloader.StartAsync();
404
405        while (!downloader.IsFinished) {
406          refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
407          refreshableJob.Progress.Status = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
408          Thread.Sleep(500);
409
410          if (downloader.IsFaulted) {
411            throw downloader.Exception;
412          }
413        }
414        IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
[7165]415        var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
[6976]416
[7165]417        refreshableJob.Progress.Status = "Downloading/deserializing complete. Displaying tasks...";
418        // build child-task tree
419        foreach (HiveTask hiveTask in parents) {
420          BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
421        }
[6976]422
[7165]423        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
[6976]424        if (refreshableJob.IsFinished()) {
425          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
[15973]426        } else if (refreshableJob.IsPaused()) {
427          refreshableJob.ExecutionState = Core.ExecutionState.Paused;
[6976]428        } else {
429          refreshableJob.ExecutionState = Core.ExecutionState.Started;
430        }
431        refreshableJob.OnLoaded();
[15973]432      } finally {
[8159]433        refreshableJob.IsProgressing = false;
[8156]434        refreshableJob.Progress.Finish();
[9219]435        if (downloader != null) {
436          downloader.Dispose();
437        }
[6976]438      }
439    }
440
[7125]441    private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
442      IEnumerable<LightweightTask> childTasks = from job in allTasks
443                                                where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
[6976]444                                                orderby job.DateCreated ascending
445                                                select job;
446      foreach (LightweightTask task in childTasks) {
[7125]447        HiveTask childHiveTask = allHiveTasks[task.Id];
[8700]448        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
[7125]449        parentHiveTask.AddChildHiveTask(childHiveTask);
[6976]450      }
451    }
452    #endregion
453
454    /// <summary>
455    /// Converts a string which can contain Ids separated by ';' to a enumerable
456    /// </summary>
457    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
458      if (!string.IsNullOrEmpty(resourceNames)) {
[8109]459        return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
[6976]460      } else {
461        return new List<string>();
462      }
463    }
464
465    public static ItemTask LoadItemJob(Guid jobId) {
[7132]466      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
[6976]467      try {
468        return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
[15973]469      } catch {
[6976]470        return null;
471      }
472    }
473
474    /// <summary>
475    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
476    /// If repetitions is -1, it is repeated infinitely.
477    /// </summary>
478    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
479      while (true) {
[15973]480        try { action(); return; } catch (Exception e) {
[6976]481          if (repetitions == 0) throw new HiveException(errorMessage, e);
482          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
483          repetitions--;
484        }
485      }
486    }
487
488    public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
[7132]489      return HiveServiceLocator.Instance.CallHiveService((service) => {
[6976]490        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
491        foreach (var hep in jps) {
[7059]492          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
[6976]493        }
494        return new HiveItemCollection<JobPermission>(jps);
495      });
496    }
497  }
[10130]498}
Note: See TracBrowser for help on using the repository browser.