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