Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1672

  • fixed name of slave windows service

reviewing comments:

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