Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Clients.Hive/3.3/HiveClient.cs @ 7144

Last change on this file since 7144 was 7144, checked in by ascheibe, 12 years ago

#1672 stop result polling before deleting a job

File size: 22.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.PluginInfrastructure;
33using TS = System.Threading.Tasks;
34
35namespace HeuristicLab.Clients.Hive {
36  [Item("HiveClient", "Hive client.")]
37  public sealed class HiveClient : IContent {
38    private static HiveClient instance;
39    public static HiveClient Instance {
40      get {
41        if (instance == null) instance = new HiveClient();
42        return instance;
43      }
44    }
45
46    #region Properties
47    private ItemCollection<RefreshableJob> jobs;
48    public ItemCollection<RefreshableJob> Jobs {
49      get { return jobs; }
50      set {
51        if (value != jobs) {
52          jobs = value;
53          OnHiveExperimentsChanged();
54        }
55      }
56    }
57
58    private List<Plugin> onlinePlugins;
59    public List<Plugin> OnlinePlugins {
60      get { return onlinePlugins; }
61      set { onlinePlugins = value; }
62    }
63
64    private List<Plugin> alreadyUploadedPlugins;
65    public List<Plugin> AlreadyUploadedPlugins {
66      get { return alreadyUploadedPlugins; }
67      set { alreadyUploadedPlugins = value; }
68    }
69
70    private bool isAllowedPrivileged;
71    public bool IsAllowedPrivileged {
72      get { return isAllowedPrivileged; }
73      set { isAllowedPrivileged = value; }
74    }
75    #endregion
76
77    private HiveClient() { }
78
79    #region Refresh
80    public void Refresh() {
81      OnRefreshing();
82
83      try {
84        this.IsAllowedPrivileged = HiveServiceLocator.Instance.CallHiveService((s) => s.IsAllowedPrivileged());
85
86        var oldJobs = jobs ?? new ItemCollection<RefreshableJob>();
87        jobs = new HiveItemCollection<RefreshableJob>();
88        var jobsLoaded = HiveServiceLocator.Instance.CallHiveService<IEnumerable<Job>>(s => s.GetJobs());
89
90        foreach (var j in jobsLoaded) {
91          var job = oldJobs.SingleOrDefault(x => x.Id == j.Id);
92          if (job == null) {
93            // new
94            jobs.Add(new RefreshableJob(j) { IsAllowedPrivileged = this.isAllowedPrivileged });
95          } else {
96            // update
97            job.Job = j;
98            job.IsAllowedPrivileged = this.isAllowedPrivileged;
99            jobs.Add(job);
100          }
101        }
102        // remove those which were not in the list of loaded hiveexperiments
103        foreach (var job in oldJobs) {
104          if (job.Id == Guid.Empty) {
105            // experiment not uploaded... keep
106            jobs.Add(job);
107          } else {
108            job.RefreshAutomatically = false; // stop results polling
109          }
110        }
111      }
112      catch {
113        jobs = null;
114        throw;
115      } finally {
116        OnRefreshed();
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 HiveExperimentsChanged;
206    private void OnHiveExperimentsChanged() {
207      var handler = HiveExperimentsChanged;
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      // execution state does not need to be set. it will be set to Stopped, when all jobs have been downloaded
239    }
240
241    #region Upload Job
242    private Semaphore taskUploadSemaphore = new Semaphore(Settings.Default.MaxParallelUploads, Settings.Default.MaxParallelUploads);
243    private static object jobCountLocker = new object();
244    private static object pluginLocker = new object();
245    private void UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
246      try {
247        refreshableJob.Progress = new Progress("Connecting to server...");
248        refreshableJob.IsProgressing = true;
249
250        IEnumerable<string> resourceNames = ToResourceNameList(refreshableJob.Job.ResourceNames);
251        var resourceIds = new List<Guid>();
252        foreach (var resourceName in resourceNames) {
253          Guid resourceId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetResourceId(resourceName));
254          if (resourceId == Guid.Empty) {
255            throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
256          }
257          resourceIds.Add(resourceId);
258        }
259
260        foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>()) {
261          hiveJob.SetIndexInParentOptimizerList(null);
262        }
263
264        // upload Job
265        refreshableJob.Progress.Status = "Uploading Job...";
266        refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job));
267        bool isPrivileged = refreshableJob.Job.IsPrivileged;
268        refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
269        refreshableJob.Job.IsPrivileged = isPrivileged;
270        cancellationToken.ThrowIfCancellationRequested();
271
272        int totalJobCount = refreshableJob.GetAllHiveTasks().Count();
273        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
274        cancellationToken.ThrowIfCancellationRequested();
275
276        // upload plugins
277        refreshableJob.Progress.Status = "Uploading plugins...";
278        this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
279        this.AlreadyUploadedPlugins = new List<Plugin>();
280        Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
281        this.alreadyUploadedPlugins.Add(configFilePlugin);
282        cancellationToken.ThrowIfCancellationRequested();
283
284        if (refreshableJob.RefreshAutomatically) refreshableJob.StartResultPolling();
285
286        // upload tasks
287        refreshableJob.Progress.Status = "Uploading tasks...";
288
289        var tasks = new List<TS.Task>();
290        foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
291          tasks.Add(TS.Task.Factory.StartNew((hj) => {
292            UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, resourceIds, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, refreshableJob.Job.IsPrivileged, cancellationToken);
293          }, hiveTask)
294          .ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted));
295        }
296        try {
297          TS.Task.WaitAll(tasks.ToArray());
298        }
299        catch (AggregateException ae) {
300          if (!ae.InnerExceptions.All(e => e is TaskCanceledException)) throw ae; // for some reason the WaitAll throws a AggregateException containg a TaskCanceledException. i don't know where it comes from, however the tasks all finish properly, so for now just ignore it
301        }
302        refreshableJob.Job.Modified = false;
303      } finally {
304        refreshableJob.IsProgressing = false;
305      }
306    }
307
308    /// <summary>
309    /// Uploads the local configuration file as plugin
310    /// </summary>
311    private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
312      string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
313      string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
314      string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
315      byte[] hash;
316
317      byte[] data = File.ReadAllBytes(configFilePath);
318      using (SHA1 sha1 = SHA1.Create()) {
319        hash = sha1.ComputeHash(data);
320      }
321
322      Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
323      PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
324
325      IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
326
327      if (onlineConfig.Count() > 0) {
328        return onlineConfig.First();
329      } else {
330        configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
331        return configPlugin;
332      }
333    }
334
335    /// <summary>
336    /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
337    /// </summary>
338    /// <param name="parentHiveTask">shall be null if its the root task</param>
339    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) {
340      taskUploadSemaphore.WaitOne();
341      bool semaphoreReleased = false;
342      try {
343        cancellationToken.ThrowIfCancellationRequested();
344        lock (jobCountLocker) {
345          taskCount[0]++;
346        }
347        TaskData taskData;
348        List<IPluginDescription> plugins;
349
350        if (hiveTask.ItemTask.ComputeInParallel && (hiveTask.ItemTask.Item is Optimization.Experiment || hiveTask.ItemTask.Item is Optimization.BatchRun)) {
351          hiveTask.Task.IsParentTask = true;
352          hiveTask.Task.FinishWhenChildJobsFinished = true;
353          taskData = hiveTask.GetAsTaskData(true, out plugins);
354        } else {
355          hiveTask.Task.IsParentTask = false;
356          hiveTask.Task.FinishWhenChildJobsFinished = false;
357          taskData = hiveTask.GetAsTaskData(false, out plugins);
358        }
359        cancellationToken.ThrowIfCancellationRequested();
360
361        TryAndRepeat(() => {
362          if (!cancellationToken.IsCancellationRequested) {
363            lock (pluginLocker) {
364              HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
365            }
366          }
367        }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
368        cancellationToken.ThrowIfCancellationRequested();
369        hiveTask.Task.PluginsNeededIds.Add(configPluginId);
370        hiveTask.Task.JobId = jobId;
371        hiveTask.Task.IsPrivileged = isPrivileged;
372
373        log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
374        TryAndRepeat(() => {
375          if (!cancellationToken.IsCancellationRequested) {
376            if (parentHiveTask != null) {
377              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
378            } else {
379              hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
380            }
381          }
382        }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
383        cancellationToken.ThrowIfCancellationRequested();
384
385        lock (jobCountLocker) {
386          progress.ProgressValue = (double)taskCount[0] / totalJobCount;
387          progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
388        }
389
390        var tasks = new List<TS.Task>();
391        foreach (HiveTask child in hiveTask.ChildHiveTasks) {
392          tasks.Add(TS.Task.Factory.StartNew((tuple) => {
393            var arguments = (Tuple<HiveTask, HiveTask>)tuple;
394            UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, isPrivileged, cancellationToken);
395          }, new Tuple<HiveTask, HiveTask>(child, hiveTask))
396          .ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted));
397        }
398        taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
399        try {
400          TS.Task.WaitAll(tasks.ToArray());
401        }
402        catch (AggregateException ae) {
403          if (!ae.InnerExceptions.All(e => e is TaskCanceledException)) throw ae; // for some reason the WaitAll throws a AggregateException containg a TaskCanceledException. i don't know where it comes from, however the tasks all finish properly, so for now just ignore it
404        }
405      } finally {
406        if (!semaphoreReleased) taskUploadSemaphore.Release();
407      }
408    }
409    #endregion
410
411    #region Download Experiment
412    public static void LoadJob(RefreshableJob refreshableJob) {
413      var hiveExperiment = refreshableJob.Job;
414      refreshableJob.Progress = new Progress();
415
416      try {
417        refreshableJob.IsProgressing = true;
418        int totalJobCount = 0;
419        IEnumerable<LightweightTask> allTasks;
420
421        refreshableJob.Progress.Status = "Connecting to Server...";
422        // fetch all task objects to create the full tree of tree of HiveTask objects
423        refreshableJob.Progress.Status = "Downloading list of tasks...";
424        allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasks(hiveExperiment.Id));
425        totalJobCount = allTasks.Count();
426
427        refreshableJob.Progress.Status = "Downloading tasks...";
428        TaskDownloader downloader = new TaskDownloader(allTasks.Select(x => x.Id));
429        downloader.StartAsync();
430
431        while (!downloader.IsFinished) {
432          refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
433          refreshableJob.Progress.Status = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
434          Thread.Sleep(500);
435
436          if (downloader.IsFaulted) {
437            throw downloader.Exception;
438          }
439        }
440        IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
441
442        refreshableJob.HiveTasks = new ItemCollection<HiveTask>(allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue));
443
444        if (refreshableJob.IsFinished()) {
445          refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
446        } else {
447          refreshableJob.ExecutionState = Core.ExecutionState.Started;
448        }
449
450        refreshableJob.Progress.Status = "Downloading/deserializing complete. Displaying tasks...";
451        // build child-task tree
452        foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
453          BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
454        }
455
456        refreshableJob.OnLoaded();
457      } finally {
458        refreshableJob.IsProgressing = false;
459      }
460    }
461
462    private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
463      IEnumerable<LightweightTask> childTasks = from job in allTasks
464                                                where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
465                                                orderby job.DateCreated ascending
466                                                select job;
467      foreach (LightweightTask task in childTasks) {
468        HiveTask childHiveTask = allHiveTasks[task.Id];
469        parentHiveTask.AddChildHiveTask(childHiveTask);
470        BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
471      }
472    }
473    #endregion
474
475    /// <summary>
476    /// Converts a string which can contain Ids separated by ';' to a enumerable
477    /// </summary>
478    private static IEnumerable<string> ToResourceNameList(string resourceNames) {
479      if (!string.IsNullOrEmpty(resourceNames)) {
480        return resourceNames.Split(';');
481      } else {
482        return new List<string>();
483      }
484    }
485
486    public static ItemTask LoadItemJob(Guid jobId) {
487      TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
488      try {
489        return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
490      }
491      catch {
492        return null;
493      }
494    }
495
496    /// <summary>
497    /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
498    /// If repetitions is -1, it is repeated infinitely.
499    /// </summary>
500    public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
501      while (true) {
502        try { action(); return; }
503        catch (Exception e) {
504          if (repetitions == 0) throw new HiveException(errorMessage, e);
505          if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
506          repetitions--;
507        }
508      }
509    }
510
511    public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
512      return HiveServiceLocator.Instance.CallHiveService((service) => {
513        IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
514        foreach (var hep in jps) {
515          hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
516        }
517        return new HiveItemCollection<JobPermission>(jps);
518      });
519    }
520  }
521}
Note: See TracBrowser for help on using the repository browser.