[6976] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[14185] | 3 | * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[6976] | 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 |
|
---|
| 22 | using System;
|
---|
| 23 | using System.Collections.Generic;
|
---|
| 24 | using System.Configuration;
|
---|
| 25 | using System.IO;
|
---|
| 26 | using System.Linq;
|
---|
| 27 | using System.Security.Cryptography;
|
---|
| 28 | using System.Threading;
|
---|
| 29 | using System.Threading.Tasks;
|
---|
| 30 | using HeuristicLab.Common;
|
---|
| 31 | using HeuristicLab.Core;
|
---|
[7582] | 32 | using HeuristicLab.MainForm;
|
---|
[6976] | 33 | using HeuristicLab.PluginInfrastructure;
|
---|
| 34 | using TS = System.Threading.Tasks;
|
---|
| 35 |
|
---|
| 36 | namespace 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
|
---|
[9219] | 48 | private HiveItemCollection<RefreshableJob> jobs;
|
---|
| 49 | public HiveItemCollection<RefreshableJob> Jobs {
|
---|
[6976] | 50 | get { return jobs; }
|
---|
| 51 | set {
|
---|
| 52 | if (value != jobs) {
|
---|
| 53 | jobs = value;
|
---|
[9219] | 54 | OnHiveJobsChanged();
|
---|
[6976] | 55 | }
|
---|
| 56 | }
|
---|
| 57 | }
|
---|
| 58 |
|
---|
[15658] | 59 | private IItemList<Project> projects;
|
---|
| 60 | public IItemList<Project> Projects {
|
---|
| 61 | get { return projects; }
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | private IItemList<Resource> resources;
|
---|
| 65 | public IItemList<Resource> Resources {
|
---|
| 66 | get { return resources; }
|
---|
| 67 | }
|
---|
| 68 |
|
---|
| 69 |
|
---|
[6976] | 70 | private List<Plugin> onlinePlugins;
|
---|
| 71 | public List<Plugin> OnlinePlugins {
|
---|
| 72 | get { return onlinePlugins; }
|
---|
| 73 | set { onlinePlugins = value; }
|
---|
| 74 | }
|
---|
| 75 |
|
---|
| 76 | private List<Plugin> alreadyUploadedPlugins;
|
---|
| 77 | public List<Plugin> AlreadyUploadedPlugins {
|
---|
| 78 | get { return alreadyUploadedPlugins; }
|
---|
| 79 | set { alreadyUploadedPlugins = value; }
|
---|
| 80 | }
|
---|
| 81 | #endregion
|
---|
| 82 |
|
---|
[12579] | 83 | private HiveClient() { }
|
---|
[6976] | 84 |
|
---|
[9219] | 85 | public void ClearHiveClient() {
|
---|
| 86 | Jobs.ClearWithoutHiveDeletion();
|
---|
| 87 | foreach (var j in Jobs) {
|
---|
| 88 | if (j.RefreshAutomatically) {
|
---|
| 89 | j.RefreshAutomatically = false; // stop result polling
|
---|
| 90 | }
|
---|
| 91 | j.Dispose();
|
---|
| 92 | }
|
---|
| 93 | Jobs = null;
|
---|
| 94 |
|
---|
| 95 | if (onlinePlugins != null)
|
---|
| 96 | onlinePlugins.Clear();
|
---|
| 97 | if (alreadyUploadedPlugins != null)
|
---|
| 98 | alreadyUploadedPlugins.Clear();
|
---|
| 99 | }
|
---|
| 100 |
|
---|
[6976] | 101 | #region Refresh
|
---|
| 102 | public void Refresh() {
|
---|
| 103 | OnRefreshing();
|
---|
| 104 |
|
---|
| 105 | try {
|
---|
[15658] | 106 | projects = new ItemList<Project>();
|
---|
| 107 | resources = new ItemList<Resource>();
|
---|
[6976] | 108 | jobs = new HiveItemCollection<RefreshableJob>();
|
---|
| 109 |
|
---|
[15658] | 110 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
| 111 | service.GetProjects().ForEach(p => projects.Add(p));
|
---|
| 112 | service.GetSlaveGroups().ForEach(g => resources.Add(g));
|
---|
| 113 | service.GetSlaves().ForEach(s => resources.Add(s));
|
---|
| 114 | service.GetJobs().ForEach(p => jobs.Add(new RefreshableJob(p)));
|
---|
| 115 | });
|
---|
[6976] | 116 | }
|
---|
| 117 | catch {
|
---|
| 118 | jobs = null;
|
---|
[15658] | 119 | projects = null;
|
---|
| 120 | resources = null;
|
---|
[6976] | 121 | throw;
|
---|
[7582] | 122 | }
|
---|
| 123 | finally {
|
---|
[6976] | 124 | OnRefreshed();
|
---|
| 125 | }
|
---|
| 126 | }
|
---|
[9219] | 127 |
|
---|
[15658] | 128 | public void RefreshProjectsAndResources() {
|
---|
| 129 | OnRefreshing();
|
---|
| 130 |
|
---|
| 131 | try {
|
---|
| 132 | projects = new ItemList<Project>();
|
---|
| 133 | resources = new ItemList<Resource>();
|
---|
| 134 |
|
---|
| 135 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
| 136 | service.GetProjects().ForEach(p => projects.Add(p));
|
---|
| 137 | service.GetSlaveGroups().ForEach(g => resources.Add(g));
|
---|
| 138 | service.GetSlaves().ForEach(s => resources.Add(s));
|
---|
| 139 | });
|
---|
| 140 | } catch {
|
---|
| 141 | projects = null;
|
---|
| 142 | resources = null;
|
---|
| 143 | throw;
|
---|
| 144 | } finally {
|
---|
| 145 | OnRefreshed();
|
---|
| 146 | }
|
---|
| 147 | }
|
---|
| 148 |
|
---|
[6976] | 149 | public void RefreshAsync(Action<Exception> exceptionCallback) {
|
---|
| 150 | var call = new Func<Exception>(delegate() {
|
---|
| 151 | try {
|
---|
| 152 | Refresh();
|
---|
| 153 | }
|
---|
| 154 | catch (Exception ex) {
|
---|
| 155 | return ex;
|
---|
| 156 | }
|
---|
| 157 | return null;
|
---|
| 158 | });
|
---|
| 159 | call.BeginInvoke(delegate(IAsyncResult result) {
|
---|
| 160 | Exception ex = call.EndInvoke(result);
|
---|
| 161 | if (ex != null) exceptionCallback(ex);
|
---|
| 162 | }, null);
|
---|
| 163 | }
|
---|
[15658] | 164 |
|
---|
[6976] | 165 | #endregion
|
---|
| 166 |
|
---|
| 167 | #region Store
|
---|
| 168 | public static void Store(IHiveItem item, CancellationToken cancellationToken) {
|
---|
| 169 | if (item.Id == Guid.Empty) {
|
---|
| 170 | if (item is RefreshableJob) {
|
---|
| 171 | HiveClient.Instance.UploadJob((RefreshableJob)item, cancellationToken);
|
---|
| 172 | }
|
---|
| 173 | if (item is JobPermission) {
|
---|
| 174 | var hep = (JobPermission)item;
|
---|
[7132] | 175 | hep.GrantedUserId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
|
---|
[6976] | 176 | if (hep.GrantedUserId == Guid.Empty) {
|
---|
| 177 | throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
|
---|
| 178 | }
|
---|
[7132] | 179 | HiveServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
|
---|
[6976] | 180 | }
|
---|
[15401] | 181 | if (item is Project) {
|
---|
| 182 | HiveServiceLocator.Instance.CallHiveService(s => s.AddProject((Project)item));
|
---|
| 183 | }
|
---|
[6976] | 184 | } else {
|
---|
[15630] | 185 | if (item is Job) {
|
---|
| 186 | var job = (Job)item;
|
---|
| 187 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJob(job, job.ResourceIds));
|
---|
| 188 | }
|
---|
[15401] | 189 | if (item is Project)
|
---|
| 190 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateProject((Project)item));
|
---|
[6976] | 191 | }
|
---|
| 192 | }
|
---|
| 193 | public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
|
---|
| 194 | var call = new Func<Exception>(delegate() {
|
---|
| 195 | try {
|
---|
| 196 | Store(item, cancellationToken);
|
---|
| 197 | }
|
---|
| 198 | catch (Exception ex) {
|
---|
| 199 | return ex;
|
---|
| 200 | }
|
---|
| 201 | return null;
|
---|
| 202 | });
|
---|
| 203 | call.BeginInvoke(delegate(IAsyncResult result) {
|
---|
| 204 | Exception ex = call.EndInvoke(result);
|
---|
| 205 | if (ex != null) exceptionCallback(ex);
|
---|
| 206 | }, null);
|
---|
| 207 | }
|
---|
| 208 | #endregion
|
---|
| 209 |
|
---|
| 210 | #region Delete
|
---|
| 211 | public static void Delete(IHiveItem item) {
|
---|
[7059] | 212 | if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
|
---|
[6976] | 213 | return;
|
---|
| 214 |
|
---|
| 215 | if (item is Job)
|
---|
[15630] | 216 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJobState(item.Id, JobState.StatisticsPending));
|
---|
[7144] | 217 | if (item is RefreshableJob) {
|
---|
| 218 | RefreshableJob job = (RefreshableJob)item;
|
---|
| 219 | if (job.RefreshAutomatically) {
|
---|
| 220 | job.StopResultPolling();
|
---|
| 221 | }
|
---|
[15630] | 222 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJobState(item.Id, JobState.StatisticsPending));
|
---|
[7144] | 223 | }
|
---|
[6976] | 224 | if (item is JobPermission) {
|
---|
| 225 | var hep = (JobPermission)item;
|
---|
[7132] | 226 | HiveServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
|
---|
[6976] | 227 | }
|
---|
| 228 | item.Id = Guid.Empty;
|
---|
| 229 | }
|
---|
| 230 | #endregion
|
---|
| 231 |
|
---|
| 232 | #region Events
|
---|
| 233 | public event EventHandler Refreshing;
|
---|
| 234 | private void OnRefreshing() {
|
---|
| 235 | EventHandler handler = Refreshing;
|
---|
| 236 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
| 237 | }
|
---|
| 238 | public event EventHandler Refreshed;
|
---|
| 239 | private void OnRefreshed() {
|
---|
| 240 | var handler = Refreshed;
|
---|
| 241 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
| 242 | }
|
---|
[9219] | 243 | public event EventHandler HiveJobsChanged;
|
---|
| 244 | private void OnHiveJobsChanged() {
|
---|
| 245 | var handler = HiveJobsChanged;
|
---|
[6976] | 246 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
| 247 | }
|
---|
| 248 | #endregion
|
---|
| 249 |
|
---|
| 250 | public static void StartJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
|
---|
| 251 | HiveClient.StoreAsync(
|
---|
| 252 | new Action<Exception>((Exception ex) => {
|
---|
| 253 | refreshableJob.ExecutionState = ExecutionState.Prepared;
|
---|
| 254 | exceptionCallback(ex);
|
---|
| 255 | }), refreshableJob, cancellationToken);
|
---|
| 256 | refreshableJob.ExecutionState = ExecutionState.Started;
|
---|
| 257 | }
|
---|
| 258 |
|
---|
| 259 | public static void PauseJob(RefreshableJob refreshableJob) {
|
---|
[7132] | 260 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
[6976] | 261 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
| 262 | if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
|
---|
| 263 | service.PauseTask(task.Task.Id);
|
---|
| 264 | }
|
---|
| 265 | });
|
---|
| 266 | refreshableJob.ExecutionState = ExecutionState.Paused;
|
---|
| 267 | }
|
---|
| 268 |
|
---|
| 269 | public static void StopJob(RefreshableJob refreshableJob) {
|
---|
[7132] | 270 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
[6976] | 271 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
| 272 | if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
|
---|
| 273 | service.StopTask(task.Task.Id);
|
---|
| 274 | }
|
---|
| 275 | });
|
---|
[7156] | 276 | refreshableJob.ExecutionState = ExecutionState.Stopped;
|
---|
[6976] | 277 | }
|
---|
| 278 |
|
---|
[7156] | 279 | public static void ResumeJob(RefreshableJob refreshableJob) {
|
---|
| 280 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
| 281 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
[7165] | 282 | if (task.Task.State == TaskState.Paused) {
|
---|
| 283 | service.RestartTask(task.Task.Id);
|
---|
[7156] | 284 | }
|
---|
| 285 | }
|
---|
| 286 | });
|
---|
| 287 | refreshableJob.ExecutionState = ExecutionState.Started;
|
---|
| 288 | }
|
---|
| 289 |
|
---|
[15642] | 290 | public static void UpdateJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
|
---|
| 291 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
| 292 | HiveClient.StoreAsync(
|
---|
| 293 | new Action<Exception>((Exception ex) => {
|
---|
| 294 | //refreshableJob.ExecutionState = ExecutionState.Prepared;
|
---|
| 295 | exceptionCallback(ex);
|
---|
| 296 | }), refreshableJob.Job, cancellationToken);
|
---|
| 297 | });
|
---|
| 298 | }
|
---|
| 299 |
|
---|
[6976] | 300 | #region Upload Job
|
---|
| 301 | private Semaphore taskUploadSemaphore = new Semaphore(Settings.Default.MaxParallelUploads, Settings.Default.MaxParallelUploads);
|
---|
| 302 | private static object jobCountLocker = new object();
|
---|
| 303 | private static object pluginLocker = new object();
|
---|
| 304 | private void UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
|
---|
| 305 | try {
|
---|
[8156] | 306 | refreshableJob.IsProgressing = true;
|
---|
[9893] | 307 | refreshableJob.Progress.Start("Connecting to server...");
|
---|
[6976] | 308 |
|
---|
| 309 | foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>()) {
|
---|
| 310 | hiveJob.SetIndexInParentOptimizerList(null);
|
---|
| 311 | }
|
---|
| 312 |
|
---|
| 313 | // upload Job
|
---|
| 314 | refreshableJob.Progress.Status = "Uploading Job...";
|
---|
[15630] | 315 | refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job, refreshableJob.Job.ResourceIds));
|
---|
[7132] | 316 | refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
|
---|
[6976] | 317 | cancellationToken.ThrowIfCancellationRequested();
|
---|
| 318 |
|
---|
| 319 | int totalJobCount = refreshableJob.GetAllHiveTasks().Count();
|
---|
| 320 | 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
|
---|
| 321 | cancellationToken.ThrowIfCancellationRequested();
|
---|
| 322 |
|
---|
| 323 | // upload plugins
|
---|
| 324 | refreshableJob.Progress.Status = "Uploading plugins...";
|
---|
[7132] | 325 | this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
|
---|
[6976] | 326 | this.AlreadyUploadedPlugins = new List<Plugin>();
|
---|
[7132] | 327 | Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
|
---|
[6976] | 328 | this.alreadyUploadedPlugins.Add(configFilePlugin);
|
---|
| 329 | cancellationToken.ThrowIfCancellationRequested();
|
---|
| 330 |
|
---|
| 331 | // upload tasks
|
---|
| 332 | refreshableJob.Progress.Status = "Uploading tasks...";
|
---|
| 333 |
|
---|
| 334 | var tasks = new List<TS.Task>();
|
---|
| 335 | foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
|
---|
[8939] | 336 | var task = TS.Task.Factory.StartNew((hj) => {
|
---|
[15630] | 337 | UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
|
---|
[8939] | 338 | }, hiveTask);
|
---|
| 339 | task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
|
---|
| 340 | tasks.Add(task);
|
---|
[6976] | 341 | }
|
---|
[8939] | 342 | TS.Task.WaitAll(tasks.ToArray());
|
---|
[7582] | 343 | }
|
---|
| 344 | finally {
|
---|
[8939] | 345 | refreshableJob.Job.Modified = false;
|
---|
[8159] | 346 | refreshableJob.IsProgressing = false;
|
---|
[8156] | 347 | refreshableJob.Progress.Finish();
|
---|
[6976] | 348 | }
|
---|
| 349 | }
|
---|
| 350 |
|
---|
| 351 | /// <summary>
|
---|
| 352 | /// Uploads the local configuration file as plugin
|
---|
| 353 | /// </summary>
|
---|
| 354 | private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
|
---|
| 355 | string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
|
---|
| 356 | string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
|
---|
| 357 | string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
|
---|
| 358 | byte[] hash;
|
---|
| 359 |
|
---|
| 360 | byte[] data = File.ReadAllBytes(configFilePath);
|
---|
| 361 | using (SHA1 sha1 = SHA1.Create()) {
|
---|
| 362 | hash = sha1.ComputeHash(data);
|
---|
| 363 | }
|
---|
| 364 |
|
---|
| 365 | Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
|
---|
| 366 | PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
|
---|
| 367 |
|
---|
| 368 | IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
|
---|
| 369 |
|
---|
| 370 | if (onlineConfig.Count() > 0) {
|
---|
| 371 | return onlineConfig.First();
|
---|
| 372 | } else {
|
---|
| 373 | configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
|
---|
| 374 | return configPlugin;
|
---|
| 375 | }
|
---|
| 376 | }
|
---|
| 377 |
|
---|
| 378 | /// <summary>
|
---|
| 379 | /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
|
---|
| 380 | /// </summary>
|
---|
| 381 | /// <param name="parentHiveTask">shall be null if its the root task</param>
|
---|
[15630] | 382 | private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
|
---|
[6976] | 383 | taskUploadSemaphore.WaitOne();
|
---|
| 384 | bool semaphoreReleased = false;
|
---|
| 385 | try {
|
---|
| 386 | cancellationToken.ThrowIfCancellationRequested();
|
---|
| 387 | lock (jobCountLocker) {
|
---|
| 388 | taskCount[0]++;
|
---|
| 389 | }
|
---|
| 390 | TaskData taskData;
|
---|
| 391 | List<IPluginDescription> plugins;
|
---|
| 392 |
|
---|
[10130] | 393 | if (hiveTask.ItemTask.ComputeInParallel) {
|
---|
[6976] | 394 | hiveTask.Task.IsParentTask = true;
|
---|
| 395 | hiveTask.Task.FinishWhenChildJobsFinished = true;
|
---|
| 396 | taskData = hiveTask.GetAsTaskData(true, out plugins);
|
---|
| 397 | } else {
|
---|
| 398 | hiveTask.Task.IsParentTask = false;
|
---|
| 399 | hiveTask.Task.FinishWhenChildJobsFinished = false;
|
---|
| 400 | taskData = hiveTask.GetAsTaskData(false, out plugins);
|
---|
| 401 | }
|
---|
| 402 | cancellationToken.ThrowIfCancellationRequested();
|
---|
| 403 |
|
---|
| 404 | TryAndRepeat(() => {
|
---|
| 405 | if (!cancellationToken.IsCancellationRequested) {
|
---|
| 406 | lock (pluginLocker) {
|
---|
[7132] | 407 | HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
|
---|
[6976] | 408 | }
|
---|
| 409 | }
|
---|
[7125] | 410 | }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
|
---|
[6976] | 411 | cancellationToken.ThrowIfCancellationRequested();
|
---|
| 412 | hiveTask.Task.PluginsNeededIds.Add(configPluginId);
|
---|
| 413 | hiveTask.Task.JobId = jobId;
|
---|
| 414 |
|
---|
| 415 | log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
|
---|
| 416 | TryAndRepeat(() => {
|
---|
| 417 | if (!cancellationToken.IsCancellationRequested) {
|
---|
| 418 | if (parentHiveTask != null) {
|
---|
[7132] | 419 | hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
|
---|
[6976] | 420 | } else {
|
---|
[15630] | 421 | hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData));
|
---|
[6976] | 422 | }
|
---|
| 423 | }
|
---|
[7125] | 424 | }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
|
---|
[6976] | 425 | cancellationToken.ThrowIfCancellationRequested();
|
---|
| 426 |
|
---|
| 427 | lock (jobCountLocker) {
|
---|
| 428 | progress.ProgressValue = (double)taskCount[0] / totalJobCount;
|
---|
| 429 | progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
|
---|
| 430 | }
|
---|
| 431 |
|
---|
| 432 | var tasks = new List<TS.Task>();
|
---|
| 433 | foreach (HiveTask child in hiveTask.ChildHiveTasks) {
|
---|
[8939] | 434 | var task = TS.Task.Factory.StartNew((tuple) => {
|
---|
[6976] | 435 | var arguments = (Tuple<HiveTask, HiveTask>)tuple;
|
---|
[15630] | 436 | UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
|
---|
[8939] | 437 | }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
|
---|
| 438 | task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
|
---|
| 439 | tasks.Add(task);
|
---|
[6976] | 440 | }
|
---|
| 441 | taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
|
---|
[8939] | 442 | TS.Task.WaitAll(tasks.ToArray());
|
---|
[15630] | 443 | } finally {
|
---|
[6976] | 444 | if (!semaphoreReleased) taskUploadSemaphore.Release();
|
---|
| 445 | }
|
---|
| 446 | }
|
---|
[15630] | 447 |
|
---|
| 448 |
|
---|
| 449 | /// <summary>
|
---|
| 450 | /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
|
---|
| 451 | /// </summary>
|
---|
| 452 | /// <param name="parentHiveTask">shall be null if its the root task</param>
|
---|
| 453 | //private void UploadTaskWithChildren_Old(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, IEnumerable<Guid> groups, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
|
---|
| 454 | // taskUploadSemaphore.WaitOne();
|
---|
| 455 | // bool semaphoreReleased = false;
|
---|
| 456 | // try {
|
---|
| 457 | // cancellationToken.ThrowIfCancellationRequested();
|
---|
| 458 | // lock (jobCountLocker) {
|
---|
| 459 | // taskCount[0]++;
|
---|
| 460 | // }
|
---|
| 461 | // TaskData taskData;
|
---|
| 462 | // List<IPluginDescription> plugins;
|
---|
| 463 |
|
---|
| 464 | // if (hiveTask.ItemTask.ComputeInParallel) {
|
---|
| 465 | // hiveTask.Task.IsParentTask = true;
|
---|
| 466 | // hiveTask.Task.FinishWhenChildJobsFinished = true;
|
---|
| 467 | // taskData = hiveTask.GetAsTaskData(true, out plugins);
|
---|
| 468 | // } else {
|
---|
| 469 | // hiveTask.Task.IsParentTask = false;
|
---|
| 470 | // hiveTask.Task.FinishWhenChildJobsFinished = false;
|
---|
| 471 | // taskData = hiveTask.GetAsTaskData(false, out plugins);
|
---|
| 472 | // }
|
---|
| 473 | // cancellationToken.ThrowIfCancellationRequested();
|
---|
| 474 |
|
---|
| 475 | // TryAndRepeat(() => {
|
---|
| 476 | // if (!cancellationToken.IsCancellationRequested) {
|
---|
| 477 | // lock (pluginLocker) {
|
---|
| 478 | // HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
|
---|
| 479 | // }
|
---|
| 480 | // }
|
---|
| 481 | // }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
|
---|
| 482 | // cancellationToken.ThrowIfCancellationRequested();
|
---|
| 483 | // hiveTask.Task.PluginsNeededIds.Add(configPluginId);
|
---|
| 484 | // hiveTask.Task.JobId = jobId;
|
---|
| 485 |
|
---|
| 486 | // log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
|
---|
| 487 | // TryAndRepeat(() => {
|
---|
| 488 | // if (!cancellationToken.IsCancellationRequested) {
|
---|
| 489 | // if (parentHiveTask != null) {
|
---|
| 490 | // hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
|
---|
| 491 | // } else {
|
---|
| 492 | // hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
|
---|
| 493 | // }
|
---|
| 494 | // }
|
---|
| 495 | // }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
|
---|
| 496 | // cancellationToken.ThrowIfCancellationRequested();
|
---|
| 497 |
|
---|
| 498 | // lock (jobCountLocker) {
|
---|
| 499 | // progress.ProgressValue = (double)taskCount[0] / totalJobCount;
|
---|
| 500 | // progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
|
---|
| 501 | // }
|
---|
| 502 |
|
---|
| 503 | // var tasks = new List<TS.Task>();
|
---|
| 504 | // foreach (HiveTask child in hiveTask.ChildHiveTasks) {
|
---|
| 505 | // var task = TS.Task.Factory.StartNew((tuple) => {
|
---|
| 506 | // var arguments = (Tuple<HiveTask, HiveTask>)tuple;
|
---|
| 507 | // UploadTaskWithChildren_Old(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
|
---|
| 508 | // }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
|
---|
| 509 | // task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
|
---|
| 510 | // tasks.Add(task);
|
---|
| 511 | // }
|
---|
| 512 | // taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
|
---|
| 513 | // TS.Task.WaitAll(tasks.ToArray());
|
---|
| 514 | // }
|
---|
| 515 | // finally {
|
---|
| 516 | // if (!semaphoreReleased) taskUploadSemaphore.Release();
|
---|
| 517 | // }
|
---|
| 518 | //}
|
---|
| 519 |
|
---|
[6976] | 520 | #endregion
|
---|
| 521 |
|
---|
| 522 | #region Download Experiment
|
---|
| 523 | public static void LoadJob(RefreshableJob refreshableJob) {
|
---|
| 524 | var hiveExperiment = refreshableJob.Job;
|
---|
[8156] | 525 | refreshableJob.IsProgressing = true;
|
---|
[9219] | 526 | TaskDownloader downloader = null;
|
---|
[6976] | 527 |
|
---|
| 528 | try {
|
---|
| 529 | int totalJobCount = 0;
|
---|
| 530 | IEnumerable<LightweightTask> allTasks;
|
---|
| 531 |
|
---|
| 532 | // fetch all task objects to create the full tree of tree of HiveTask objects
|
---|
[9893] | 533 | refreshableJob.Progress.Start("Downloading list of tasks...");
|
---|
[9219] | 534 | allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
|
---|
[6976] | 535 | totalJobCount = allTasks.Count();
|
---|
| 536 |
|
---|
[7125] | 537 | refreshableJob.Progress.Status = "Downloading tasks...";
|
---|
[9219] | 538 | downloader = new TaskDownloader(allTasks.Select(x => x.Id));
|
---|
[6976] | 539 | downloader.StartAsync();
|
---|
| 540 |
|
---|
| 541 | while (!downloader.IsFinished) {
|
---|
| 542 | refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
|
---|
| 543 | refreshableJob.Progress.Status = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
|
---|
| 544 | Thread.Sleep(500);
|
---|
| 545 |
|
---|
| 546 | if (downloader.IsFaulted) {
|
---|
| 547 | throw downloader.Exception;
|
---|
| 548 | }
|
---|
| 549 | }
|
---|
| 550 | IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
|
---|
[7165] | 551 | var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
|
---|
[6976] | 552 |
|
---|
[7165] | 553 | refreshableJob.Progress.Status = "Downloading/deserializing complete. Displaying tasks...";
|
---|
| 554 | // build child-task tree
|
---|
| 555 | foreach (HiveTask hiveTask in parents) {
|
---|
| 556 | BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
|
---|
| 557 | }
|
---|
[6976] | 558 |
|
---|
[7165] | 559 | refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
|
---|
[6976] | 560 | if (refreshableJob.IsFinished()) {
|
---|
| 561 | refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
|
---|
[14901] | 562 | } else if (refreshableJob.IsPaused()) {
|
---|
| 563 | refreshableJob.ExecutionState = Core.ExecutionState.Paused;
|
---|
| 564 | } else {
|
---|
[6976] | 565 | refreshableJob.ExecutionState = Core.ExecutionState.Started;
|
---|
| 566 | }
|
---|
| 567 | refreshableJob.OnLoaded();
|
---|
[7582] | 568 | }
|
---|
| 569 | finally {
|
---|
[8159] | 570 | refreshableJob.IsProgressing = false;
|
---|
[8156] | 571 | refreshableJob.Progress.Finish();
|
---|
[9219] | 572 | if (downloader != null) {
|
---|
| 573 | downloader.Dispose();
|
---|
| 574 | }
|
---|
[6976] | 575 | }
|
---|
| 576 | }
|
---|
| 577 |
|
---|
[7125] | 578 | private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
|
---|
| 579 | IEnumerable<LightweightTask> childTasks = from job in allTasks
|
---|
| 580 | where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
|
---|
[6976] | 581 | orderby job.DateCreated ascending
|
---|
| 582 | select job;
|
---|
| 583 | foreach (LightweightTask task in childTasks) {
|
---|
[7125] | 584 | HiveTask childHiveTask = allHiveTasks[task.Id];
|
---|
[8700] | 585 | BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
|
---|
[7125] | 586 | parentHiveTask.AddChildHiveTask(childHiveTask);
|
---|
[6976] | 587 | }
|
---|
| 588 | }
|
---|
| 589 | #endregion
|
---|
| 590 |
|
---|
| 591 | /// <summary>
|
---|
| 592 | /// Converts a string which can contain Ids separated by ';' to a enumerable
|
---|
| 593 | /// </summary>
|
---|
| 594 | private static IEnumerable<string> ToResourceNameList(string resourceNames) {
|
---|
| 595 | if (!string.IsNullOrEmpty(resourceNames)) {
|
---|
[8109] | 596 | return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
|
---|
[6976] | 597 | } else {
|
---|
| 598 | return new List<string>();
|
---|
| 599 | }
|
---|
| 600 | }
|
---|
| 601 |
|
---|
| 602 | public static ItemTask LoadItemJob(Guid jobId) {
|
---|
[7132] | 603 | TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
|
---|
[6976] | 604 | try {
|
---|
| 605 | return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
|
---|
| 606 | }
|
---|
| 607 | catch {
|
---|
| 608 | return null;
|
---|
| 609 | }
|
---|
| 610 | }
|
---|
| 611 |
|
---|
| 612 | /// <summary>
|
---|
| 613 | /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
|
---|
| 614 | /// If repetitions is -1, it is repeated infinitely.
|
---|
| 615 | /// </summary>
|
---|
| 616 | public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
|
---|
| 617 | while (true) {
|
---|
| 618 | try { action(); return; }
|
---|
| 619 | catch (Exception e) {
|
---|
| 620 | if (repetitions == 0) throw new HiveException(errorMessage, e);
|
---|
| 621 | if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
|
---|
| 622 | repetitions--;
|
---|
| 623 | }
|
---|
| 624 | }
|
---|
| 625 | }
|
---|
| 626 |
|
---|
| 627 | public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
|
---|
[7132] | 628 | return HiveServiceLocator.Instance.CallHiveService((service) => {
|
---|
[6976] | 629 | IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
|
---|
| 630 | foreach (var hep in jps) {
|
---|
[7059] | 631 | hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
|
---|
[6976] | 632 | }
|
---|
| 633 | return new HiveItemCollection<JobPermission>(jps);
|
---|
| 634 | });
|
---|
| 635 | }
|
---|
| 636 | }
|
---|
[10130] | 637 | } |
---|