1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
4 | *
|
---|
5 | * This file is part of HeuristicLab.
|
---|
6 | *
|
---|
7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
8 | * it under the terms of the GNU General Public License as published by
|
---|
9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
10 | * (at your option) any later version.
|
---|
11 | *
|
---|
12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | * GNU General Public License for more details.
|
---|
16 | *
|
---|
17 | * You should have received a copy of the GNU General Public License
|
---|
18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | */
|
---|
20 | #endregion
|
---|
21 |
|
---|
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;
|
---|
32 | using HeuristicLab.MainForm;
|
---|
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
|
---|
48 | private HiveItemCollection<RefreshableJob> jobs;
|
---|
49 | public HiveItemCollection<RefreshableJob> Jobs {
|
---|
50 | get { return jobs; }
|
---|
51 | set {
|
---|
52 | if (value != jobs) {
|
---|
53 | jobs = value;
|
---|
54 | OnHiveJobsChanged();
|
---|
55 | }
|
---|
56 | }
|
---|
57 | }
|
---|
58 |
|
---|
59 | private IItemList<Project> projects;
|
---|
60 | public IItemList<Project> Projects {
|
---|
61 | get { return projects; }
|
---|
62 | }
|
---|
63 |
|
---|
64 | private IItemList<Resource> resources;
|
---|
65 | public IItemList<Resource> Resources {
|
---|
66 | get { return resources; }
|
---|
67 | }
|
---|
68 |
|
---|
69 | private Dictionary<Guid, HashSet<Guid>> projectAncestors;
|
---|
70 | public Dictionary<Guid, HashSet<Guid>> ProjectAncestors {
|
---|
71 | get { return projectAncestors; }
|
---|
72 | }
|
---|
73 |
|
---|
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 |
|
---|
89 | private Dictionary<Guid, string> projectNames;
|
---|
90 | public Dictionary<Guid, string> ProjectNames {
|
---|
91 | get { return projectNames; }
|
---|
92 | }
|
---|
93 |
|
---|
94 | private HashSet<Project> disabledParentProjects;
|
---|
95 | public HashSet<Project> DisabledParentProjects {
|
---|
96 | get { return disabledParentProjects; }
|
---|
97 | }
|
---|
98 |
|
---|
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 |
|
---|
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 |
|
---|
122 | private HiveClient() { }
|
---|
123 |
|
---|
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 |
|
---|
140 | #region Refresh
|
---|
141 | public void Refresh() {
|
---|
142 | OnRefreshing();
|
---|
143 |
|
---|
144 | try {
|
---|
145 | projects = new ItemList<Project>();
|
---|
146 | resources = new ItemList<Resource>();
|
---|
147 | jobs = new HiveItemCollection<RefreshableJob>();
|
---|
148 | projectNames = new Dictionary<Guid, string>();
|
---|
149 | resourceNames = new Dictionary<Guid, string>();
|
---|
150 |
|
---|
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 |
|
---|
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)));
|
---|
161 | projectNames = service.GetProjectNames();
|
---|
162 | resourceNames = service.GetResourceNames();
|
---|
163 | });
|
---|
164 |
|
---|
165 | RefreshResourceGenealogy();
|
---|
166 | RefreshProjectGenealogy();
|
---|
167 | RefreshDisabledParentProjects();
|
---|
168 | RefreshDisabledParentResources();
|
---|
169 | }
|
---|
170 | catch {
|
---|
171 | jobs = null;
|
---|
172 | projects = null;
|
---|
173 | resources = null;
|
---|
174 | throw;
|
---|
175 | }
|
---|
176 | finally {
|
---|
177 | OnRefreshed();
|
---|
178 | }
|
---|
179 | }
|
---|
180 |
|
---|
181 | public void RefreshProjectsAndResources() {
|
---|
182 | OnRefreshing();
|
---|
183 |
|
---|
184 | try {
|
---|
185 | projects = new ItemList<Project>();
|
---|
186 | projectNames = new Dictionary<Guid, string>();
|
---|
187 | resources = new ItemList<Resource>();
|
---|
188 | resourceNames = new Dictionary<Guid, string>();
|
---|
189 |
|
---|
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 |
|
---|
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));
|
---|
199 | projectNames = service.GetProjectNames();
|
---|
200 | resourceNames = service.GetResourceNames();
|
---|
201 | });
|
---|
202 |
|
---|
203 | RefreshResourceGenealogy();
|
---|
204 | RefreshProjectGenealogy();
|
---|
205 | RefreshDisabledParentProjects();
|
---|
206 | RefreshDisabledParentResources();
|
---|
207 | } catch {
|
---|
208 | projects = null;
|
---|
209 | resources = null;
|
---|
210 | throw;
|
---|
211 | } finally {
|
---|
212 | OnRefreshed();
|
---|
213 | }
|
---|
214 | }
|
---|
215 |
|
---|
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 | }
|
---|
231 |
|
---|
232 | private void RefreshResourceGenealogy() {
|
---|
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 |
|
---|
252 | private void RefreshProjectGenealogy() {
|
---|
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 |
|
---|
272 | private void RefreshDisabledParentProjects() {
|
---|
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 |
|
---|
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 |
|
---|
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>();
|
---|
305 | }
|
---|
306 |
|
---|
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>();
|
---|
310 | }
|
---|
311 |
|
---|
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>();
|
---|
315 | }
|
---|
316 |
|
---|
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>();
|
---|
320 | }
|
---|
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 | }
|
---|
326 |
|
---|
327 | public IEnumerable<Resource> GetDisabledResourceAncestors(IEnumerable<Resource> availableResources) {
|
---|
328 | var missingParentIds = availableResources
|
---|
329 | .Where(x => x.ParentResourceId.HasValue)
|
---|
330 | .SelectMany(x => resourceAncestors[x.Id]).Distinct()
|
---|
331 | .Where(x => !availableResources.Select(y => y.Id).Contains(x));
|
---|
332 |
|
---|
333 | return resources.OfType<SlaveGroup>().Union(disabledParentResources).Where(x => missingParentIds.Contains(x.Id));
|
---|
334 | }
|
---|
335 | #endregion
|
---|
336 |
|
---|
337 | #region Store
|
---|
338 | public static void Store(IHiveItem item, CancellationToken cancellationToken) {
|
---|
339 | if (item.Id == Guid.Empty) {
|
---|
340 | if (item is RefreshableJob) {
|
---|
341 | item.Id = HiveClient.Instance.UploadJob((RefreshableJob)item, cancellationToken);
|
---|
342 | }
|
---|
343 | if (item is JobPermission) {
|
---|
344 | var hep = (JobPermission)item;
|
---|
345 | hep.GrantedUserId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
|
---|
346 | if (hep.GrantedUserId == Guid.Empty) {
|
---|
347 | throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
|
---|
348 | }
|
---|
349 | HiveServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
|
---|
350 | }
|
---|
351 | if (item is Project) {
|
---|
352 | item.Id = HiveServiceLocator.Instance.CallHiveService(s => s.AddProject((Project)item));
|
---|
353 | }
|
---|
354 | } else {
|
---|
355 | if (item is Job) {
|
---|
356 | var job = (Job)item;
|
---|
357 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJob(job, job.ResourceIds));
|
---|
358 | }
|
---|
359 | if (item is Project)
|
---|
360 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateProject((Project)item));
|
---|
361 | }
|
---|
362 | }
|
---|
363 | public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
|
---|
364 | var call = new Func<Exception>(delegate() {
|
---|
365 | try {
|
---|
366 | Store(item, cancellationToken);
|
---|
367 | }
|
---|
368 | catch (Exception ex) {
|
---|
369 | return ex;
|
---|
370 | }
|
---|
371 | return null;
|
---|
372 | });
|
---|
373 | call.BeginInvoke(delegate(IAsyncResult result) {
|
---|
374 | Exception ex = call.EndInvoke(result);
|
---|
375 | if (ex != null) exceptionCallback(ex);
|
---|
376 | }, null);
|
---|
377 | }
|
---|
378 | #endregion
|
---|
379 |
|
---|
380 | #region Delete
|
---|
381 | public static void Delete(IHiveItem item) {
|
---|
382 | if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
|
---|
383 | return;
|
---|
384 |
|
---|
385 | if (item is Job)
|
---|
386 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJobState(item.Id, JobState.StatisticsPending));
|
---|
387 | if (item is RefreshableJob) {
|
---|
388 | RefreshableJob job = (RefreshableJob)item;
|
---|
389 | if (job.RefreshAutomatically) {
|
---|
390 | job.StopResultPolling();
|
---|
391 | }
|
---|
392 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJobState(item.Id, JobState.StatisticsPending));
|
---|
393 | }
|
---|
394 | if (item is JobPermission) {
|
---|
395 | var hep = (JobPermission)item;
|
---|
396 | HiveServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
|
---|
397 | }
|
---|
398 | item.Id = Guid.Empty;
|
---|
399 | }
|
---|
400 | #endregion
|
---|
401 |
|
---|
402 | #region Events
|
---|
403 | public event EventHandler Refreshing;
|
---|
404 | private void OnRefreshing() {
|
---|
405 | EventHandler handler = Refreshing;
|
---|
406 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
407 | }
|
---|
408 | public event EventHandler Refreshed;
|
---|
409 | private void OnRefreshed() {
|
---|
410 | var handler = Refreshed;
|
---|
411 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
412 | }
|
---|
413 | public event EventHandler HiveJobsChanged;
|
---|
414 | private void OnHiveJobsChanged() {
|
---|
415 | var handler = HiveJobsChanged;
|
---|
416 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
417 | }
|
---|
418 | #endregion
|
---|
419 |
|
---|
420 | public static void StartJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
|
---|
421 | HiveClient.StoreAsync(
|
---|
422 | new Action<Exception>((Exception ex) => {
|
---|
423 | refreshableJob.ExecutionState = ExecutionState.Prepared;
|
---|
424 | exceptionCallback(ex);
|
---|
425 | }), refreshableJob, cancellationToken);
|
---|
426 | refreshableJob.ExecutionState = ExecutionState.Started;
|
---|
427 | }
|
---|
428 |
|
---|
429 | public static void PauseJob(RefreshableJob refreshableJob) {
|
---|
430 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
431 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
432 | if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
|
---|
433 | service.PauseTask(task.Task.Id);
|
---|
434 | }
|
---|
435 | });
|
---|
436 | refreshableJob.ExecutionState = ExecutionState.Paused;
|
---|
437 | }
|
---|
438 |
|
---|
439 | public static void StopJob(RefreshableJob refreshableJob) {
|
---|
440 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
441 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
442 | if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
|
---|
443 | service.StopTask(task.Task.Id);
|
---|
444 | }
|
---|
445 | });
|
---|
446 | refreshableJob.ExecutionState = ExecutionState.Stopped;
|
---|
447 | }
|
---|
448 |
|
---|
449 | public static void ResumeJob(RefreshableJob refreshableJob) {
|
---|
450 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
451 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
452 | if (task.Task.State == TaskState.Paused) {
|
---|
453 | service.RestartTask(task.Task.Id);
|
---|
454 | }
|
---|
455 | }
|
---|
456 | });
|
---|
457 | refreshableJob.ExecutionState = ExecutionState.Started;
|
---|
458 | }
|
---|
459 |
|
---|
460 | public static void UpdateJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
|
---|
461 | refreshableJob.IsProgressing = true;
|
---|
462 | refreshableJob.Progress.Status = "Saving Job...";
|
---|
463 | HiveClient.StoreAsync(
|
---|
464 | new Action<Exception>((Exception ex) => {
|
---|
465 | exceptionCallback(ex);
|
---|
466 | }), refreshableJob.Job, cancellationToken);
|
---|
467 | refreshableJob.IsProgressing = false;
|
---|
468 | refreshableJob.Progress.Finish();
|
---|
469 | }
|
---|
470 |
|
---|
471 | public static void UpdateJob(RefreshableJob refreshableJob) {
|
---|
472 | refreshableJob.IsProgressing = true;
|
---|
473 |
|
---|
474 | try {
|
---|
475 | refreshableJob.Progress.Start("Saving Job...");
|
---|
476 | HiveClient.StoreAsync(new Action<Exception>((Exception ex) => {
|
---|
477 | throw new Exception("Update failed.", ex);
|
---|
478 | }), refreshableJob.Job, new CancellationToken());
|
---|
479 | } finally {
|
---|
480 | refreshableJob.IsProgressing = false;
|
---|
481 | refreshableJob.Progress.Finish();
|
---|
482 | }
|
---|
483 | }
|
---|
484 |
|
---|
485 |
|
---|
486 |
|
---|
487 | #region Upload Job
|
---|
488 | private Semaphore taskUploadSemaphore = new Semaphore(Settings.Default.MaxParallelUploads, Settings.Default.MaxParallelUploads);
|
---|
489 | private static object jobCountLocker = new object();
|
---|
490 | private static object pluginLocker = new object();
|
---|
491 | private Guid UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
|
---|
492 | try {
|
---|
493 | refreshableJob.IsProgressing = true;
|
---|
494 | refreshableJob.Progress.Start("Connecting to server...");
|
---|
495 |
|
---|
496 | foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>()) {
|
---|
497 | hiveJob.SetIndexInParentOptimizerList(null);
|
---|
498 | }
|
---|
499 |
|
---|
500 | // upload Job
|
---|
501 | refreshableJob.Progress.Status = "Uploading Job...";
|
---|
502 | refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job, refreshableJob.Job.ResourceIds));
|
---|
503 | refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
|
---|
504 | cancellationToken.ThrowIfCancellationRequested();
|
---|
505 |
|
---|
506 | int totalJobCount = refreshableJob.GetAllHiveTasks().Count();
|
---|
507 | 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
|
---|
508 | cancellationToken.ThrowIfCancellationRequested();
|
---|
509 |
|
---|
510 | // upload plugins
|
---|
511 | refreshableJob.Progress.Status = "Uploading plugins...";
|
---|
512 | this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
|
---|
513 | this.AlreadyUploadedPlugins = new List<Plugin>();
|
---|
514 | Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
|
---|
515 | this.alreadyUploadedPlugins.Add(configFilePlugin);
|
---|
516 | cancellationToken.ThrowIfCancellationRequested();
|
---|
517 |
|
---|
518 | // upload tasks
|
---|
519 | refreshableJob.Progress.Status = "Uploading tasks...";
|
---|
520 |
|
---|
521 | var tasks = new List<TS.Task>();
|
---|
522 | foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
|
---|
523 | var task = TS.Task.Factory.StartNew((hj) => {
|
---|
524 | UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
|
---|
525 | }, hiveTask);
|
---|
526 | task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
|
---|
527 | tasks.Add(task);
|
---|
528 | }
|
---|
529 | TS.Task.WaitAll(tasks.ToArray());
|
---|
530 | }
|
---|
531 | finally {
|
---|
532 | refreshableJob.Job.Modified = false;
|
---|
533 | refreshableJob.IsProgressing = false;
|
---|
534 | refreshableJob.Progress.Finish();
|
---|
535 | }
|
---|
536 | return (refreshableJob.Job != null) ? refreshableJob.Job.Id : Guid.Empty;
|
---|
537 | }
|
---|
538 |
|
---|
539 | /// <summary>
|
---|
540 | /// Uploads the local configuration file as plugin
|
---|
541 | /// </summary>
|
---|
542 | private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
|
---|
543 | string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
|
---|
544 | string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
|
---|
545 | string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
|
---|
546 | byte[] hash;
|
---|
547 |
|
---|
548 | byte[] data = File.ReadAllBytes(configFilePath);
|
---|
549 | using (SHA1 sha1 = SHA1.Create()) {
|
---|
550 | hash = sha1.ComputeHash(data);
|
---|
551 | }
|
---|
552 |
|
---|
553 | Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
|
---|
554 | PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
|
---|
555 |
|
---|
556 | IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
|
---|
557 |
|
---|
558 | if (onlineConfig.Count() > 0) {
|
---|
559 | return onlineConfig.First();
|
---|
560 | } else {
|
---|
561 | configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
|
---|
562 | return configPlugin;
|
---|
563 | }
|
---|
564 | }
|
---|
565 |
|
---|
566 | /// <summary>
|
---|
567 | /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
|
---|
568 | /// </summary>
|
---|
569 | /// <param name="parentHiveTask">shall be null if its the root task</param>
|
---|
570 | private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
|
---|
571 | taskUploadSemaphore.WaitOne();
|
---|
572 | bool semaphoreReleased = false;
|
---|
573 | try {
|
---|
574 | cancellationToken.ThrowIfCancellationRequested();
|
---|
575 | lock (jobCountLocker) {
|
---|
576 | taskCount[0]++;
|
---|
577 | }
|
---|
578 | TaskData taskData;
|
---|
579 | List<IPluginDescription> plugins;
|
---|
580 |
|
---|
581 | if (hiveTask.ItemTask.ComputeInParallel) {
|
---|
582 | hiveTask.Task.IsParentTask = true;
|
---|
583 | hiveTask.Task.FinishWhenChildJobsFinished = true;
|
---|
584 | taskData = hiveTask.GetAsTaskData(true, out plugins);
|
---|
585 | } else {
|
---|
586 | hiveTask.Task.IsParentTask = false;
|
---|
587 | hiveTask.Task.FinishWhenChildJobsFinished = false;
|
---|
588 | taskData = hiveTask.GetAsTaskData(false, out plugins);
|
---|
589 | }
|
---|
590 | cancellationToken.ThrowIfCancellationRequested();
|
---|
591 |
|
---|
592 | TryAndRepeat(() => {
|
---|
593 | if (!cancellationToken.IsCancellationRequested) {
|
---|
594 | lock (pluginLocker) {
|
---|
595 | HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
|
---|
596 | }
|
---|
597 | }
|
---|
598 | }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
|
---|
599 | cancellationToken.ThrowIfCancellationRequested();
|
---|
600 | hiveTask.Task.PluginsNeededIds.Add(configPluginId);
|
---|
601 | hiveTask.Task.JobId = jobId;
|
---|
602 |
|
---|
603 | log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
|
---|
604 | TryAndRepeat(() => {
|
---|
605 | if (!cancellationToken.IsCancellationRequested) {
|
---|
606 | if (parentHiveTask != null) {
|
---|
607 | hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
|
---|
608 | } else {
|
---|
609 | hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData));
|
---|
610 | }
|
---|
611 | }
|
---|
612 | }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
|
---|
613 | cancellationToken.ThrowIfCancellationRequested();
|
---|
614 |
|
---|
615 | lock (jobCountLocker) {
|
---|
616 | progress.ProgressValue = (double)taskCount[0] / totalJobCount;
|
---|
617 | progress.Status = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
|
---|
618 | }
|
---|
619 |
|
---|
620 | var tasks = new List<TS.Task>();
|
---|
621 | foreach (HiveTask child in hiveTask.ChildHiveTasks) {
|
---|
622 | var task = TS.Task.Factory.StartNew((tuple) => {
|
---|
623 | var arguments = (Tuple<HiveTask, HiveTask>)tuple;
|
---|
624 | UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
|
---|
625 | }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
|
---|
626 | task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
|
---|
627 | tasks.Add(task);
|
---|
628 | }
|
---|
629 | taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
|
---|
630 | TS.Task.WaitAll(tasks.ToArray());
|
---|
631 | } finally {
|
---|
632 | if (!semaphoreReleased) taskUploadSemaphore.Release();
|
---|
633 | }
|
---|
634 | }
|
---|
635 | #endregion
|
---|
636 |
|
---|
637 | #region Download Experiment
|
---|
638 | public static void LoadJob(RefreshableJob refreshableJob) {
|
---|
639 | var hiveExperiment = refreshableJob.Job;
|
---|
640 | refreshableJob.IsProgressing = true;
|
---|
641 | TaskDownloader downloader = null;
|
---|
642 |
|
---|
643 | try {
|
---|
644 | int totalJobCount = 0;
|
---|
645 | IEnumerable<LightweightTask> allTasks;
|
---|
646 |
|
---|
647 | // fetch all task objects to create the full tree of tree of HiveTask objects
|
---|
648 | refreshableJob.Progress.Start("Downloading list of tasks...");
|
---|
649 | allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
|
---|
650 | totalJobCount = allTasks.Count();
|
---|
651 |
|
---|
652 | refreshableJob.Progress.Status = "Downloading tasks...";
|
---|
653 | downloader = new TaskDownloader(allTasks.Select(x => x.Id));
|
---|
654 | downloader.StartAsync();
|
---|
655 |
|
---|
656 | while (!downloader.IsFinished) {
|
---|
657 | refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
|
---|
658 | refreshableJob.Progress.Status = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
|
---|
659 | Thread.Sleep(500);
|
---|
660 |
|
---|
661 | if (downloader.IsFaulted) {
|
---|
662 | throw downloader.Exception;
|
---|
663 | }
|
---|
664 | }
|
---|
665 | IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
|
---|
666 | var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
|
---|
667 |
|
---|
668 | refreshableJob.Progress.Status = "Downloading/deserializing complete. Displaying tasks...";
|
---|
669 | // build child-task tree
|
---|
670 | foreach (HiveTask hiveTask in parents) {
|
---|
671 | BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
|
---|
672 | }
|
---|
673 |
|
---|
674 | refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
|
---|
675 | if (refreshableJob.IsFinished()) {
|
---|
676 | refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
|
---|
677 | } else if (refreshableJob.IsPaused()) {
|
---|
678 | refreshableJob.ExecutionState = Core.ExecutionState.Paused;
|
---|
679 | } else {
|
---|
680 | refreshableJob.ExecutionState = Core.ExecutionState.Started;
|
---|
681 | }
|
---|
682 | refreshableJob.OnLoaded();
|
---|
683 | }
|
---|
684 | finally {
|
---|
685 | refreshableJob.IsProgressing = false;
|
---|
686 | refreshableJob.Progress.Finish();
|
---|
687 | if (downloader != null) {
|
---|
688 | downloader.Dispose();
|
---|
689 | }
|
---|
690 | }
|
---|
691 | }
|
---|
692 |
|
---|
693 | private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
|
---|
694 | IEnumerable<LightweightTask> childTasks = from job in allTasks
|
---|
695 | where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
|
---|
696 | orderby job.DateCreated ascending
|
---|
697 | select job;
|
---|
698 | foreach (LightweightTask task in childTasks) {
|
---|
699 | HiveTask childHiveTask = allHiveTasks[task.Id];
|
---|
700 | BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
|
---|
701 | parentHiveTask.AddChildHiveTask(childHiveTask);
|
---|
702 | }
|
---|
703 | }
|
---|
704 | #endregion
|
---|
705 |
|
---|
706 | /// <summary>
|
---|
707 | /// Converts a string which can contain Ids separated by ';' to a enumerable
|
---|
708 | /// </summary>
|
---|
709 | private static IEnumerable<string> ToResourceNameList(string resourceNames) {
|
---|
710 | if (!string.IsNullOrEmpty(resourceNames)) {
|
---|
711 | return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
|
---|
712 | } else {
|
---|
713 | return new List<string>();
|
---|
714 | }
|
---|
715 | }
|
---|
716 |
|
---|
717 | public static ItemTask LoadItemJob(Guid jobId) {
|
---|
718 | TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
|
---|
719 | try {
|
---|
720 | return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
|
---|
721 | }
|
---|
722 | catch {
|
---|
723 | return null;
|
---|
724 | }
|
---|
725 | }
|
---|
726 |
|
---|
727 | /// <summary>
|
---|
728 | /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
|
---|
729 | /// If repetitions is -1, it is repeated infinitely.
|
---|
730 | /// </summary>
|
---|
731 | public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
|
---|
732 | while (true) {
|
---|
733 | try { action(); return; }
|
---|
734 | catch (Exception e) {
|
---|
735 | if (repetitions == 0) throw new HiveException(errorMessage, e);
|
---|
736 | if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
|
---|
737 | repetitions--;
|
---|
738 | }
|
---|
739 | }
|
---|
740 | }
|
---|
741 |
|
---|
742 | public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
|
---|
743 | return HiveServiceLocator.Instance.CallHiveService((service) => {
|
---|
744 | IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
|
---|
745 | foreach (var hep in jps) {
|
---|
746 | hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
|
---|
747 | }
|
---|
748 | return new HiveItemCollection<JobPermission>(jps);
|
---|
749 | });
|
---|
750 | }
|
---|
751 |
|
---|
752 | public string GetProjectAncestry(Guid projectId) {
|
---|
753 | if (projectId == null || projectId == Guid.Empty) return "";
|
---|
754 | var projects = projectAncestors[projectId].Reverse().ToList();
|
---|
755 | projects.Add(projectId);
|
---|
756 | return string.Join(" » ", projects.Select(x => ProjectNames[x]).ToArray());
|
---|
757 | }
|
---|
758 |
|
---|
759 | public IEnumerable<Resource> GetAssignedResourcesForJob(Guid jobId) {
|
---|
760 | var assignedJobResource = HiveServiceLocator.Instance.CallHiveService(service => service.GetAssignedResourcesForJob(jobId));
|
---|
761 | return Resources.Where(x => assignedJobResource.Select(y => y.ResourceId).Contains(x.Id));
|
---|
762 | }
|
---|
763 | }
|
---|
764 | } |
---|