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