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