Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveStatistics/sources/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 12689

Last change on this file since 12689 was 12586, checked in by dglaser, 9 years ago

#2388: Merged trunk into HiveStatistics branch

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