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