1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using HeuristicLab.Hive.ExperimentManager.Jobs;
|
---|
6 | using System.Threading;
|
---|
7 | using System.Threading.Tasks;
|
---|
8 | using HeuristicLab.Hive.Contracts.BusinessObjects;
|
---|
9 | using HeuristicLab.Hive.Contracts.Interfaces;
|
---|
10 | using HeuristicLab.Clients.Common;
|
---|
11 |
|
---|
12 | namespace HeuristicLab.Hive.ExperimentManager {
|
---|
13 | public class HiveJobDownloader {
|
---|
14 | private IEnumerable<Guid> jobIds;
|
---|
15 | private List<Task<HiveJob>> tasks;
|
---|
16 |
|
---|
17 | public bool IsFinished {
|
---|
18 | get {
|
---|
19 | return tasks.TrueForAll(t => t.Status == TaskStatus.RanToCompletion ||
|
---|
20 | t.Status == TaskStatus.Faulted ||
|
---|
21 | t.Status == TaskStatus.Canceled);
|
---|
22 | }
|
---|
23 | }
|
---|
24 |
|
---|
25 | public int FinishedCount {
|
---|
26 | get {
|
---|
27 | return tasks.Count(t => t.Status == TaskStatus.RanToCompletion ||
|
---|
28 | t.Status == TaskStatus.Faulted ||
|
---|
29 | t.Status == TaskStatus.Canceled);
|
---|
30 | }
|
---|
31 | }
|
---|
32 |
|
---|
33 | public IDictionary<Guid, HiveJob> Results {
|
---|
34 | get {
|
---|
35 | var results = new Dictionary<Guid, HiveJob>();
|
---|
36 | foreach(var t in tasks) {
|
---|
37 | results.Add(t.Result.JobDto.Id, t.Result);
|
---|
38 | }
|
---|
39 | return results;
|
---|
40 | }
|
---|
41 | }
|
---|
42 |
|
---|
43 | public HiveJobDownloader(IEnumerable<Guid> jobIds) {
|
---|
44 | this.jobIds = jobIds;
|
---|
45 | }
|
---|
46 |
|
---|
47 |
|
---|
48 | public void StartAsync() {
|
---|
49 | tasks = new List<Task<HiveJob>>();
|
---|
50 | foreach (Guid jobId in jobIds) {
|
---|
51 | tasks.Add(Task<SerializedJob>.Factory.StartNew(
|
---|
52 | (x) => DownloadJob(x), jobId)
|
---|
53 | .ContinueWith((x) => DeserializeJob(x.Result)));
|
---|
54 | }
|
---|
55 | }
|
---|
56 | // use semaphore to ensure only few tasks download concurrently (so not too many connections are open)
|
---|
57 | private Semaphore taskSemaphore = new Semaphore(2, 2);
|
---|
58 | protected SerializedJob DownloadJob(object jobId) {
|
---|
59 | taskSemaphore.WaitOne(Timeout.Infinite);
|
---|
60 | using (Disposable<IClientFacade> service = ServiceLocator.Instance.StreamedClientFacadePool.GetService()) {
|
---|
61 | return service.Obj.GetLastSerializedResult((Guid)jobId).Obj;
|
---|
62 | }
|
---|
63 | }
|
---|
64 |
|
---|
65 | protected HiveJob DeserializeJob(SerializedJob serializedJob) {
|
---|
66 | HiveJob job = new HiveJob(serializedJob, false);
|
---|
67 | job.Job.Prepare(); // reduce memory consumption.
|
---|
68 | taskSemaphore.Release();
|
---|
69 | job.JobDto = serializedJob.JobInfo;
|
---|
70 | return job;
|
---|
71 | }
|
---|
72 | }
|
---|
73 | }
|
---|