Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2389-EpsLexicase/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 17597

Last change on this file since 17597 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 20.6 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.Start("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.Status = "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.Status = "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.Status = "Uploading tasks...";
271
272        var tasks = new List<TS.Task>();
273        foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
274          var task = TS.Task.Factory.StartNew((hj) => {
275            UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, resourceIds, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
276          }, hiveTask);
277          task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
278          tasks.Add(task);
279        }
280        TS.Task.WaitAll(tasks.ToArray());
281      } finally {
282        refreshableJob.Job.Modified = false;
283        refreshableJob.IsProgressing = false;
284        refreshableJob.Progress.Finish();
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>
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) {
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
330        if (hiveTask.ItemTask.ComputeInParallel) {
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) {
344              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
345            }
346          }
347        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
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) {
356              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
357            } else {
358              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
359            }
360          }
361        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
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) {
371          var task = TS.Task.Factory.StartNew((tuple) => {
372            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
373            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
374          }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
375          task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
376          tasks.Add(task);
377        }
378        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
379        TS.Task.WaitAll(tasks.ToArray());
380      } finally {
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;
389      refreshableJob.IsProgressing = true;
390      TaskDownloader downloader = null;
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
397        refreshableJob.Progress.Start("Downloading list of tasks...");
398        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
399        totalJobCount = allTasks.Count();
400
401        refreshableJob.Progress.Status = "Downloading tasks...";
402        downloader = new TaskDownloader(allTasks.Select(x => x.Id));
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;
415        var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
416
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        }
422
423        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
424        if (refreshableJob.IsFinished()) {
425          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
426        } else if (refreshableJob.IsPaused()) {
427          refreshableJob.ExecutionState = Core.ExecutionState.Paused;
428        } else {
429          refreshableJob.ExecutionState = Core.ExecutionState.Started;
430        }
431        refreshableJob.OnLoaded();
432      } finally {
433        refreshableJob.IsProgressing = false;
434        refreshableJob.Progress.Finish();
435        if (downloader != null) {
436          downloader.Dispose();
437        }
438      }
439    }
440
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
444                                                orderby job.DateCreated ascending
445                                                select job;
446      foreach (LightweightTask task in childTasks) {
447        HiveTask childHiveTask = allHiveTasks[task.Id];
448        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
449        parentHiveTask.AddChildHiveTask(childHiveTask);
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)) {
459        return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
460      } else {
461        return new List<string>();
462      }
463    }
464
465    public static ItemTask LoadItemJob(Guid jobId) {
466      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
467      try {
468        return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
469      } catch {
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) {
480        try { action(); return; } catch (Exception e) {
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) {
489      return HiveServiceLocator.Instance.CallHiveService((service) => {
490        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
491        foreach (var hep in jps) {
492          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
493        }
494        return new HiveItemCollection<JobPermission>(jps);
495      });
496    }
497  }
498}
Note: See TracBrowser for help on using the repository browser.