Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 14927

Last change on this file since 14927 was 14927, checked in by gkronber, 7 years ago

#2520: changed all usages of StorableClass to use StorableType with an auto-generated GUID (did not add StorableType to other type definitions yet)

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