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 List<Plugin> onlinePlugins;
|
---|
60 | public List<Plugin> OnlinePlugins {
|
---|
61 | get { return onlinePlugins; }
|
---|
62 | set { onlinePlugins = value; }
|
---|
63 | }
|
---|
64 |
|
---|
65 | private List<Plugin> alreadyUploadedPlugins;
|
---|
66 | public List<Plugin> AlreadyUploadedPlugins {
|
---|
67 | get { return alreadyUploadedPlugins; }
|
---|
68 | set { alreadyUploadedPlugins = value; }
|
---|
69 | }
|
---|
70 | #endregion
|
---|
71 |
|
---|
72 | private HiveClient() { }
|
---|
73 |
|
---|
74 | public void ClearHiveClient() {
|
---|
75 | Jobs.ClearWithoutHiveDeletion();
|
---|
76 | foreach (var j in Jobs) {
|
---|
77 | if (j.RefreshAutomatically) {
|
---|
78 | j.RefreshAutomatically = false; // stop result polling
|
---|
79 | }
|
---|
80 | j.Dispose();
|
---|
81 | }
|
---|
82 | Jobs = null;
|
---|
83 |
|
---|
84 | if (onlinePlugins != null)
|
---|
85 | onlinePlugins.Clear();
|
---|
86 | if (alreadyUploadedPlugins != null)
|
---|
87 | alreadyUploadedPlugins.Clear();
|
---|
88 | }
|
---|
89 |
|
---|
90 | #region Refresh
|
---|
91 | public void Refresh() {
|
---|
92 | OnRefreshing();
|
---|
93 |
|
---|
94 | try {
|
---|
95 | jobs = new HiveItemCollection<RefreshableJob>();
|
---|
96 | var jobsLoaded = HiveServiceLocator.Instance.CallHiveService<IEnumerable<Job>>(s => s.GetJobs());
|
---|
97 |
|
---|
98 | foreach (var j in jobsLoaded) {
|
---|
99 | jobs.Add(new RefreshableJob(j));
|
---|
100 | }
|
---|
101 | }
|
---|
102 | catch {
|
---|
103 | jobs = null;
|
---|
104 | throw;
|
---|
105 | }
|
---|
106 | finally {
|
---|
107 | OnRefreshed();
|
---|
108 | }
|
---|
109 | }
|
---|
110 |
|
---|
111 | public void RefreshAsync(Action<Exception> exceptionCallback) {
|
---|
112 | var call = new Func<Exception>(delegate() {
|
---|
113 | try {
|
---|
114 | Refresh();
|
---|
115 | }
|
---|
116 | catch (Exception ex) {
|
---|
117 | return ex;
|
---|
118 | }
|
---|
119 | return null;
|
---|
120 | });
|
---|
121 | call.BeginInvoke(delegate(IAsyncResult result) {
|
---|
122 | Exception ex = call.EndInvoke(result);
|
---|
123 | if (ex != null) exceptionCallback(ex);
|
---|
124 | }, null);
|
---|
125 | }
|
---|
126 | #endregion
|
---|
127 |
|
---|
128 | #region Store
|
---|
129 | public static void Store(IHiveItem item, CancellationToken cancellationToken) {
|
---|
130 | if (item.Id == Guid.Empty) {
|
---|
131 | if (item is RefreshableJob) {
|
---|
132 | HiveClient.Instance.UploadJob((RefreshableJob)item, cancellationToken);
|
---|
133 | }
|
---|
134 | if (item is JobPermission) {
|
---|
135 | var hep = (JobPermission)item;
|
---|
136 | hep.GrantedUserId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
|
---|
137 | if (hep.GrantedUserId == Guid.Empty) {
|
---|
138 | throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
|
---|
139 | }
|
---|
140 | HiveServiceLocator.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
|
---|
141 | }
|
---|
142 | } else {
|
---|
143 | if (item is Job)
|
---|
144 | HiveServiceLocator.Instance.CallHiveService(s => s.UpdateJob((Job)item));
|
---|
145 | }
|
---|
146 | }
|
---|
147 | public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken) {
|
---|
148 | var call = new Func<Exception>(delegate() {
|
---|
149 | try {
|
---|
150 | Store(item, cancellationToken);
|
---|
151 | }
|
---|
152 | catch (Exception ex) {
|
---|
153 | return ex;
|
---|
154 | }
|
---|
155 | return null;
|
---|
156 | });
|
---|
157 | call.BeginInvoke(delegate(IAsyncResult result) {
|
---|
158 | Exception ex = call.EndInvoke(result);
|
---|
159 | if (ex != null) exceptionCallback(ex);
|
---|
160 | }, null);
|
---|
161 | }
|
---|
162 | #endregion
|
---|
163 |
|
---|
164 | #region Delete
|
---|
165 | public static void Delete(IHiveItem item) {
|
---|
166 | if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
|
---|
167 | return;
|
---|
168 |
|
---|
169 | if (item is Job)
|
---|
170 | HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(item.Id));
|
---|
171 | if (item is RefreshableJob) {
|
---|
172 | RefreshableJob job = (RefreshableJob)item;
|
---|
173 | if (job.RefreshAutomatically) {
|
---|
174 | job.StopResultPolling();
|
---|
175 | }
|
---|
176 | HiveServiceLocator.Instance.CallHiveService(s => s.DeleteJob(item.Id));
|
---|
177 | }
|
---|
178 | if (item is JobPermission) {
|
---|
179 | var hep = (JobPermission)item;
|
---|
180 | HiveServiceLocator.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
|
---|
181 | }
|
---|
182 | item.Id = Guid.Empty;
|
---|
183 | }
|
---|
184 | #endregion
|
---|
185 |
|
---|
186 | #region Events
|
---|
187 | public event EventHandler Refreshing;
|
---|
188 | private void OnRefreshing() {
|
---|
189 | EventHandler handler = Refreshing;
|
---|
190 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
191 | }
|
---|
192 | public event EventHandler Refreshed;
|
---|
193 | private void OnRefreshed() {
|
---|
194 | var handler = Refreshed;
|
---|
195 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
196 | }
|
---|
197 | public event EventHandler HiveJobsChanged;
|
---|
198 | private void OnHiveJobsChanged() {
|
---|
199 | var handler = HiveJobsChanged;
|
---|
200 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
201 | }
|
---|
202 | #endregion
|
---|
203 |
|
---|
204 | public static void StartJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken) {
|
---|
205 | HiveClient.StoreAsync(
|
---|
206 | new Action<Exception>((Exception ex) => {
|
---|
207 | refreshableJob.ExecutionState = ExecutionState.Prepared;
|
---|
208 | exceptionCallback(ex);
|
---|
209 | }), refreshableJob, cancellationToken);
|
---|
210 | refreshableJob.ExecutionState = ExecutionState.Started;
|
---|
211 | }
|
---|
212 |
|
---|
213 | public static void PauseJob(RefreshableJob refreshableJob) {
|
---|
214 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
215 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
216 | if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
|
---|
217 | service.PauseTask(task.Task.Id);
|
---|
218 | }
|
---|
219 | });
|
---|
220 | refreshableJob.ExecutionState = ExecutionState.Paused;
|
---|
221 | }
|
---|
222 |
|
---|
223 | public static void StopJob(RefreshableJob refreshableJob) {
|
---|
224 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
225 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
226 | if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
|
---|
227 | service.StopTask(task.Task.Id);
|
---|
228 | }
|
---|
229 | });
|
---|
230 | refreshableJob.ExecutionState = ExecutionState.Stopped;
|
---|
231 | }
|
---|
232 |
|
---|
233 | public static void ResumeJob(RefreshableJob refreshableJob) {
|
---|
234 | HiveServiceLocator.Instance.CallHiveService(service => {
|
---|
235 | foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
|
---|
236 | if (task.Task.State == TaskState.Paused) {
|
---|
237 | service.RestartTask(task.Task.Id);
|
---|
238 | }
|
---|
239 | }
|
---|
240 | });
|
---|
241 | refreshableJob.ExecutionState = ExecutionState.Started;
|
---|
242 | }
|
---|
243 |
|
---|
244 | #region Upload Job
|
---|
245 | private Semaphore taskUploadSemaphore = new Semaphore(Settings.Default.MaxParallelUploads, Settings.Default.MaxParallelUploads);
|
---|
246 | private static object jobCountLocker = new object();
|
---|
247 | private static object pluginLocker = new object();
|
---|
248 | private void UploadJob(RefreshableJob refreshableJob, CancellationToken cancellationToken) {
|
---|
249 | try {
|
---|
250 | refreshableJob.IsProgressing = true;
|
---|
251 | refreshableJob.Progress.StartMarquee("Connecting to server...");
|
---|
252 | IEnumerable<string> resourceNames = ToResourceNameList(refreshableJob.Job.ResourceNames);
|
---|
253 | var resourceIds = new List<Guid>();
|
---|
254 | foreach (var resourceName in resourceNames) {
|
---|
255 | Guid resourceId = HiveServiceLocator.Instance.CallHiveService((s) => s.GetResourceId(resourceName));
|
---|
256 | if (resourceId == Guid.Empty) {
|
---|
257 | throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
|
---|
258 | }
|
---|
259 | resourceIds.Add(resourceId);
|
---|
260 | }
|
---|
261 |
|
---|
262 | foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>()) {
|
---|
263 | hiveJob.SetIndexInParentOptimizerList(null);
|
---|
264 | }
|
---|
265 |
|
---|
266 | // upload Job
|
---|
267 | refreshableJob.Progress.Message = "Uploading Job...";
|
---|
268 | refreshableJob.Job.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job));
|
---|
269 | refreshableJob.Job = HiveServiceLocator.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
|
---|
270 | cancellationToken.ThrowIfCancellationRequested();
|
---|
271 |
|
---|
272 | int totalJobCount = refreshableJob.GetAllHiveTasks().Count();
|
---|
273 | 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
|
---|
274 | cancellationToken.ThrowIfCancellationRequested();
|
---|
275 |
|
---|
276 | // upload plugins
|
---|
277 | refreshableJob.Progress.Message = "Uploading plugins...";
|
---|
278 | this.OnlinePlugins = HiveServiceLocator.Instance.CallHiveService((s) => s.GetPlugins());
|
---|
279 | this.AlreadyUploadedPlugins = new List<Plugin>();
|
---|
280 | Plugin configFilePlugin = HiveServiceLocator.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
|
---|
281 | this.alreadyUploadedPlugins.Add(configFilePlugin);
|
---|
282 | cancellationToken.ThrowIfCancellationRequested();
|
---|
283 |
|
---|
284 | // upload tasks
|
---|
285 | refreshableJob.Progress.Message = "Uploading tasks...";
|
---|
286 | refreshableJob.Progress.ProgressBarMode = ProgressBarMode.Continuous;
|
---|
287 | refreshableJob.Progress.ProgressValue = 0;
|
---|
288 |
|
---|
289 | var tasks = new List<TS.Task>();
|
---|
290 | foreach (HiveTask hiveTask in refreshableJob.HiveTasks) {
|
---|
291 | var task = TS.Task.Factory.StartNew((hj) => {
|
---|
292 | UploadTaskWithChildren(refreshableJob.Progress, (HiveTask)hj, null, resourceIds, jobCount, totalJobCount, configFilePlugin.Id, refreshableJob.Job.Id, refreshableJob.Log, cancellationToken);
|
---|
293 | }, hiveTask);
|
---|
294 | task.ContinueWith((x) => refreshableJob.Log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
|
---|
295 | tasks.Add(task);
|
---|
296 | }
|
---|
297 | TS.Task.WaitAll(tasks.ToArray());
|
---|
298 | }
|
---|
299 | finally {
|
---|
300 | refreshableJob.Job.Modified = false;
|
---|
301 | refreshableJob.IsProgressing = false;
|
---|
302 | refreshableJob.Progress.Finish();
|
---|
303 | }
|
---|
304 | }
|
---|
305 |
|
---|
306 | /// <summary>
|
---|
307 | /// Uploads the local configuration file as plugin
|
---|
308 | /// </summary>
|
---|
309 | private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins) {
|
---|
310 | string exeFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
|
---|
311 | string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
|
---|
312 | string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;
|
---|
313 | byte[] hash;
|
---|
314 |
|
---|
315 | byte[] data = File.ReadAllBytes(configFilePath);
|
---|
316 | using (SHA1 sha1 = SHA1.Create()) {
|
---|
317 | hash = sha1.ComputeHash(data);
|
---|
318 | }
|
---|
319 |
|
---|
320 | Plugin configPlugin = new Plugin() { Name = "Configuration", Version = new Version(), Hash = hash };
|
---|
321 | PluginData configFile = new PluginData() { FileName = configFileName, Data = data };
|
---|
322 |
|
---|
323 | IEnumerable<Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));
|
---|
324 |
|
---|
325 | if (onlineConfig.Count() > 0) {
|
---|
326 | return onlineConfig.First();
|
---|
327 | } else {
|
---|
328 | configPlugin.Id = service.AddPlugin(configPlugin, new List<PluginData> { configFile });
|
---|
329 | return configPlugin;
|
---|
330 | }
|
---|
331 | }
|
---|
332 |
|
---|
333 | /// <summary>
|
---|
334 | /// Uploads the given task and all its child-jobs while setting the proper parentJobId values for the childs
|
---|
335 | /// </summary>
|
---|
336 | /// <param name="parentHiveTask">shall be null if its the root task</param>
|
---|
337 | private void UploadTaskWithChildren(IProgress progress, HiveTask hiveTask, HiveTask parentHiveTask, IEnumerable<Guid> groups, int[] taskCount, int totalJobCount, Guid configPluginId, Guid jobId, ILog log, CancellationToken cancellationToken) {
|
---|
338 | taskUploadSemaphore.WaitOne();
|
---|
339 | bool semaphoreReleased = false;
|
---|
340 | try {
|
---|
341 | cancellationToken.ThrowIfCancellationRequested();
|
---|
342 | lock (jobCountLocker) {
|
---|
343 | taskCount[0]++;
|
---|
344 | }
|
---|
345 | TaskData taskData;
|
---|
346 | List<IPluginDescription> plugins;
|
---|
347 |
|
---|
348 | if (hiveTask.ItemTask.ComputeInParallel) {
|
---|
349 | hiveTask.Task.IsParentTask = true;
|
---|
350 | hiveTask.Task.FinishWhenChildJobsFinished = true;
|
---|
351 | taskData = hiveTask.GetAsTaskData(true, out plugins);
|
---|
352 | } else {
|
---|
353 | hiveTask.Task.IsParentTask = false;
|
---|
354 | hiveTask.Task.FinishWhenChildJobsFinished = false;
|
---|
355 | taskData = hiveTask.GetAsTaskData(false, out plugins);
|
---|
356 | }
|
---|
357 | cancellationToken.ThrowIfCancellationRequested();
|
---|
358 |
|
---|
359 | TryAndRepeat(() => {
|
---|
360 | if (!cancellationToken.IsCancellationRequested) {
|
---|
361 | lock (pluginLocker) {
|
---|
362 | HiveServiceLocator.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
|
---|
363 | }
|
---|
364 | }
|
---|
365 | }, Settings.Default.MaxRepeatServiceCalls, "Failed to upload plugins");
|
---|
366 | cancellationToken.ThrowIfCancellationRequested();
|
---|
367 | hiveTask.Task.PluginsNeededIds.Add(configPluginId);
|
---|
368 | hiveTask.Task.JobId = jobId;
|
---|
369 |
|
---|
370 | log.LogMessage(string.Format("Uploading task ({0} kb, {1} objects)", taskData.Data.Count() / 1024, hiveTask.ItemTask.GetObjectGraphObjects().Count()));
|
---|
371 | TryAndRepeat(() => {
|
---|
372 | if (!cancellationToken.IsCancellationRequested) {
|
---|
373 | if (parentHiveTask != null) {
|
---|
374 | hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
|
---|
375 | } else {
|
---|
376 | hiveTask.Task.Id = HiveServiceLocator.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
|
---|
377 | }
|
---|
378 | }
|
---|
379 | }, Settings.Default.MaxRepeatServiceCalls, "Failed to add task", log);
|
---|
380 | cancellationToken.ThrowIfCancellationRequested();
|
---|
381 |
|
---|
382 | lock (jobCountLocker) {
|
---|
383 | progress.ProgressValue = (double)taskCount[0] / totalJobCount;
|
---|
384 | progress.Message = string.Format("Uploaded task ({0} of {1})", taskCount[0], totalJobCount);
|
---|
385 | }
|
---|
386 |
|
---|
387 | var tasks = new List<TS.Task>();
|
---|
388 | foreach (HiveTask child in hiveTask.ChildHiveTasks) {
|
---|
389 | var task = TS.Task.Factory.StartNew((tuple) => {
|
---|
390 | var arguments = (Tuple<HiveTask, HiveTask>)tuple;
|
---|
391 | UploadTaskWithChildren(progress, arguments.Item1, arguments.Item2, groups, taskCount, totalJobCount, configPluginId, jobId, log, cancellationToken);
|
---|
392 | }, new Tuple<HiveTask, HiveTask>(child, hiveTask));
|
---|
393 | task.ContinueWith((x) => log.LogException(x.Exception), TaskContinuationOptions.OnlyOnFaulted);
|
---|
394 | tasks.Add(task);
|
---|
395 | }
|
---|
396 | taskUploadSemaphore.Release(); semaphoreReleased = true; // the semaphore has to be release before waitall!
|
---|
397 | TS.Task.WaitAll(tasks.ToArray());
|
---|
398 | }
|
---|
399 | finally {
|
---|
400 | if (!semaphoreReleased) taskUploadSemaphore.Release();
|
---|
401 | }
|
---|
402 | }
|
---|
403 | #endregion
|
---|
404 |
|
---|
405 | #region Download Experiment
|
---|
406 | public static void LoadJob(RefreshableJob refreshableJob) {
|
---|
407 | var hiveExperiment = refreshableJob.Job;
|
---|
408 | refreshableJob.IsProgressing = true;
|
---|
409 | TaskDownloader downloader = null;
|
---|
410 |
|
---|
411 | try {
|
---|
412 | int totalJobCount = 0;
|
---|
413 | IEnumerable<LightweightTask> allTasks;
|
---|
414 |
|
---|
415 | // fetch all task objects to create the full tree of tree of HiveTask objects
|
---|
416 | refreshableJob.Progress.StartMarquee("Downloading list of tasks...");
|
---|
417 | allTasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
|
---|
418 | totalJobCount = allTasks.Count();
|
---|
419 |
|
---|
420 | refreshableJob.Progress.Message = "Downloading tasks...";
|
---|
421 | refreshableJob.Progress.ProgressBarMode = ProgressBarMode.Continuous;
|
---|
422 | refreshableJob.Progress.ProgressValue = 0.0;
|
---|
423 | downloader = new TaskDownloader(allTasks.Select(x => x.Id));
|
---|
424 | downloader.StartAsync();
|
---|
425 |
|
---|
426 | while (!downloader.IsFinished) {
|
---|
427 | refreshableJob.Progress.ProgressValue = downloader.FinishedCount / (double)totalJobCount;
|
---|
428 | refreshableJob.Progress.Message = string.Format("Downloading/deserializing tasks... ({0}/{1} finished)", downloader.FinishedCount, totalJobCount);
|
---|
429 | Thread.Sleep(500);
|
---|
430 |
|
---|
431 | if (downloader.IsFaulted) {
|
---|
432 | throw downloader.Exception;
|
---|
433 | }
|
---|
434 | }
|
---|
435 | IDictionary<Guid, HiveTask> allHiveTasks = downloader.Results;
|
---|
436 | var parents = allHiveTasks.Values.Where(x => !x.Task.ParentTaskId.HasValue);
|
---|
437 |
|
---|
438 | refreshableJob.Progress.Message = "Downloading/deserializing complete. Displaying tasks...";
|
---|
439 | refreshableJob.Progress.ProgressBarMode = ProgressBarMode.Marquee;
|
---|
440 |
|
---|
441 | // build child-task tree
|
---|
442 | foreach (HiveTask hiveTask in parents) {
|
---|
443 | BuildHiveJobTree(hiveTask, allTasks, allHiveTasks);
|
---|
444 | }
|
---|
445 |
|
---|
446 | refreshableJob.HiveTasks = new ItemCollection<HiveTask>(parents);
|
---|
447 | if (refreshableJob.IsFinished()) {
|
---|
448 | refreshableJob.ExecutionState = Core.ExecutionState.Stopped;
|
---|
449 | } else if (refreshableJob.IsPaused()) {
|
---|
450 | refreshableJob.ExecutionState = Core.ExecutionState.Paused;
|
---|
451 | } else {
|
---|
452 | refreshableJob.ExecutionState = Core.ExecutionState.Started;
|
---|
453 | }
|
---|
454 | refreshableJob.OnLoaded();
|
---|
455 | }
|
---|
456 | finally {
|
---|
457 | refreshableJob.IsProgressing = false;
|
---|
458 | refreshableJob.Progress.Finish();
|
---|
459 | if (downloader != null) {
|
---|
460 | downloader.Dispose();
|
---|
461 | }
|
---|
462 | }
|
---|
463 | }
|
---|
464 |
|
---|
465 | private static void BuildHiveJobTree(HiveTask parentHiveTask, IEnumerable<LightweightTask> allTasks, IDictionary<Guid, HiveTask> allHiveTasks) {
|
---|
466 | IEnumerable<LightweightTask> childTasks = from job in allTasks
|
---|
467 | where job.ParentTaskId.HasValue && job.ParentTaskId.Value == parentHiveTask.Task.Id
|
---|
468 | orderby job.DateCreated ascending
|
---|
469 | select job;
|
---|
470 | foreach (LightweightTask task in childTasks) {
|
---|
471 | HiveTask childHiveTask = allHiveTasks[task.Id];
|
---|
472 | BuildHiveJobTree(childHiveTask, allTasks, allHiveTasks);
|
---|
473 | parentHiveTask.AddChildHiveTask(childHiveTask);
|
---|
474 | }
|
---|
475 | }
|
---|
476 | #endregion
|
---|
477 |
|
---|
478 | /// <summary>
|
---|
479 | /// Converts a string which can contain Ids separated by ';' to a enumerable
|
---|
480 | /// </summary>
|
---|
481 | private static IEnumerable<string> ToResourceNameList(string resourceNames) {
|
---|
482 | if (!string.IsNullOrEmpty(resourceNames)) {
|
---|
483 | return resourceNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
|
---|
484 | } else {
|
---|
485 | return new List<string>();
|
---|
486 | }
|
---|
487 | }
|
---|
488 |
|
---|
489 | public static ItemTask LoadItemJob(Guid jobId) {
|
---|
490 | TaskData taskData = HiveServiceLocator.Instance.CallHiveService(s => s.GetTaskData(jobId));
|
---|
491 | try {
|
---|
492 | return PersistenceUtil.Deserialize<ItemTask>(taskData.Data);
|
---|
493 | }
|
---|
494 | catch {
|
---|
495 | return null;
|
---|
496 | }
|
---|
497 | }
|
---|
498 |
|
---|
499 | /// <summary>
|
---|
500 | /// Executes the action. If it throws an exception it is repeated until repetition-count is reached.
|
---|
501 | /// If repetitions is -1, it is repeated infinitely.
|
---|
502 | /// </summary>
|
---|
503 | public static void TryAndRepeat(Action action, int repetitions, string errorMessage, ILog log = null) {
|
---|
504 | while (true) {
|
---|
505 | try { action(); return; }
|
---|
506 | catch (Exception e) {
|
---|
507 | if (repetitions == 0) throw new HiveException(errorMessage, e);
|
---|
508 | if (log != null) log.LogMessage(string.Format("{0}: {1} - will try again!", errorMessage, e.ToString()));
|
---|
509 | repetitions--;
|
---|
510 | }
|
---|
511 | }
|
---|
512 | }
|
---|
513 |
|
---|
514 | public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId) {
|
---|
515 | return HiveServiceLocator.Instance.CallHiveService((service) => {
|
---|
516 | IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
|
---|
517 | foreach (var hep in jps) {
|
---|
518 | hep.UnmodifiedGrantedUserNameUpdate(service.GetUsernameByUserId(hep.GrantedUserId));
|
---|
519 | }
|
---|
520 | return new HiveItemCollection<JobPermission>(jps);
|
---|
521 | });
|
---|
522 | }
|
---|
523 | }
|
---|
524 | } |
---|