Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Clients.Hive.Administrator/3.3/Views/ProjectJobsView.cs

Last change on this file was 17226, checked in by mkommend, 5 years ago

#2521: Merged trunk changes into problem refactoring branch.

File size: 15.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Threading.Tasks;
27using System.Windows.Forms;
28using HeuristicLab.Clients.Hive.Views;
29using HeuristicLab.Core;
30using HeuristicLab.Core.Views;
31using HeuristicLab.Data;
32using HeuristicLab.MainForm;
33using HeuristicLab.MainForm.WindowsForms;
34
35namespace HeuristicLab.Clients.Hive.Administrator.Views {
36  [View("ProjectView")]
37  [Content(typeof(Project), IsDefaultView = false)]
38  public partial class ProjectJobsView : ItemView {
39    private const string JOB_ID = "Id";
40    private const string JOB_NAME = "Name";
41    private const string JOB_OWNER = "Owner";
42    private const string JOB_OWNERID = "Owner Id";
43    private const string JOB_DATECREATED = "Date Created";
44    private const string JOB_STATE = "State";
45    private const string JOB_EXECUTIONSTATE = "Execution State";
46    private const string JOB_EXECUTIONTIME = "Execution Time";
47    private const string JOB_DESCRIPTION = "Description";
48    private const string JOB_TASKCOUNT = "Tasks";
49    private const string JOB_WAITINGTASKCOUNT = "Waiting";
50    private const string JOB_CALCULATINGTASKCOUNT = "Calculating";
51    private const string JOB_FINISHEDTASKCOUNT = "Finished";
52
53    private readonly Color onlineStatusColor = Color.FromArgb(255, 189, 249, 143); // #bdf98f
54    private readonly Color onlineStatusColor2 = Color.FromArgb(255, 157, 249, 143); // #9df98f
55    private readonly Color statisticsPendingStatusColor = Color.FromArgb(255, 249, 210, 145); // #f9d291
56    private readonly Color deletionPendingStatusColor = Color.FromArgb(255, 249, 172, 144); // #f9ac90
57    private readonly Color deletionPendingStatusColor2 = Color.FromArgb(255, 249, 149, 143); // #f9958f
58
59    private IProgress progress;
60    public IProgress Progress {
61      get { return progress; }
62      set {
63        this.progress = value;
64        OnIsProgressingChanged();
65      }
66    }
67
68    public new Project Content {
69      get { return (Project)base.Content; }
70      set { base.Content = value; }
71    }
72
73    public ProjectJobsView() {
74      InitializeComponent();
75      progress = new Progress();
76
77      removeButton.Enabled = false;
78    }
79
80    protected override void RegisterContentEvents() {
81      base.RegisterContentEvents();
82      matrixView.DataGridView.SelectionChanged += DataGridView_SelectionChanged;
83      MainForm.Progress.Show(this, progress);
84    }
85
86    protected override void DeregisterContentEvents() {
87      matrixView.DataGridView.SelectionChanged -= DataGridView_SelectionChanged;
88      MainForm.Progress.Hide(this, false);
89      base.DeregisterContentEvents();
90    }
91
92    private void DataGridView_SelectionChanged(object sender, EventArgs e) {
93      SetEnabledStateOfControls();
94    }
95
96    #region Overrides
97    protected override void OnContentChanged() {
98      base.OnContentChanged();
99      removeButton.Enabled = false;
100      UpdateJobs();
101      SetEnabledStateOfControls();
102    }
103
104    protected override void SetEnabledStateOfControls() {
105      base.SetEnabledStateOfControls();
106      bool enabled = Content != null && !Locked && !ReadOnly;
107
108      matrixView.Enabled = enabled;
109
110      // Buttons (start/resume, pause, stop, remove)
111      refreshButton.Enabled = startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = removeButton.Enabled = false;
112
113      if (enabled && progress.ProgressState != ProgressState.Started) {
114        var jobs = GetSelectedJobs().ToList();
115        if (jobs.Any()) {
116
117          startButton.Enabled = jobs.All(x =>
118            !x.IsProgressing && HiveAdminClient.Instance.Tasks.ContainsKey(x.Id) && HiveAdminClient.Instance.Tasks[x.Id].Count > 0
119            && x.Job.ProjectId != Guid.Empty //&& x.Job.ResourceIds != null && x.Job.ResourceIds.Any()
120            && (x.ExecutionState == ExecutionState.Prepared || x.ExecutionState == ExecutionState.Paused));
121          pauseButton.Enabled = jobs.All(x => !x.IsProgressing && x.ExecutionState == ExecutionState.Started);
122          stopButton.Enabled = jobs.All(x => !x.IsProgressing && (x.ExecutionState == ExecutionState.Started || x.ExecutionState == ExecutionState.Paused));
123          removeButton.Enabled = jobs.All(x => !x.IsProgressing && x.Job.State == JobState.Online);
124        }
125      }
126
127      // refresh Button
128      if (Content != null && !Locked && progress.ProgressState != ProgressState.Started) {
129        refreshButton.Enabled = true;
130      }
131    }
132
133    #endregion Overrides
134
135    #region Event Handlers
136    private void ProjectJobsView_Load(object sender, EventArgs e) {
137
138    }
139
140    private void refreshButton_Click(object sender, EventArgs e) {
141      progress.Start("Refreshing jobs...", ProgressMode.Indeterminate);
142      SetEnabledStateOfControls();
143      var task = System.Threading.Tasks.Task.Factory.StartNew(RefreshJobsAsync);
144
145      task.ContinueWith((t) => {
146        progress.Finish();
147        SetEnabledStateOfControls();
148      });
149    }
150
151    private void removeButton_Click(object sender, EventArgs e) {
152      var jobs = GetSelectedJobs();
153
154      if (jobs.Any()) {
155        var result = MessageBox.Show("Do you really want to remove following job(s):\n\n"
156                                     + String.Join("\n", jobs.Select(x => x.Job.Name)),
157          "HeuristicLab Hive Administrator",
158          MessageBoxButtons.YesNo,
159          MessageBoxIcon.Question);
160
161        if (result == DialogResult.Yes) {
162          progress.Start("Removing job(s)...", ProgressMode.Indeterminate);
163          SetEnabledStateOfControls();
164          var task = System.Threading.Tasks.Task.Factory.StartNew(RemoveJobsAsync, jobs);
165
166          task.ContinueWith((t) => {
167            RefreshJobs();
168            progress.Finish();
169            SetEnabledStateOfControls();
170          }, TaskContinuationOptions.NotOnFaulted);
171
172          task.ContinueWith((t) => {
173            RefreshJobs();
174            progress.Finish();
175            SetEnabledStateOfControls();
176            MessageBox.Show("An error occured removing the job(s).", "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
177          }, TaskContinuationOptions.OnlyOnFaulted);
178        }
179      }
180    }
181
182    private void startButton_Click(object sender, EventArgs e) {
183      var jobs = GetSelectedJobs();
184
185      if (jobs.Any()) {
186        var result = MessageBox.Show("Do you really want to resume following job(s):\n\n"
187                                     + String.Join("\n", jobs.Select(x => x.Job.Name)),
188          "HeuristicLab Hive Administrator",
189          MessageBoxButtons.YesNo,
190          MessageBoxIcon.Question);
191
192        if (result == DialogResult.Yes) {
193          progress.Start("Resuming job(s)...", ProgressMode.Indeterminate);
194          SetEnabledStateOfControls();
195          var task = System.Threading.Tasks.Task.Factory.StartNew(ResumeJobsAsync, jobs);
196
197          task.ContinueWith((t) => {
198            RefreshJobs();
199            progress.Finish();
200            SetEnabledStateOfControls();
201          }, TaskContinuationOptions.NotOnFaulted);
202
203          task.ContinueWith((t) => {
204            RefreshJobs();
205            progress.Finish();
206            SetEnabledStateOfControls();
207            MessageBox.Show("An error occured resuming the job(s).", "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
208          }, TaskContinuationOptions.OnlyOnFaulted);
209        }
210      }
211    }
212
213    private void pauseButton_Click(object sender, EventArgs e) {
214      var jobs = GetSelectedJobs();
215
216      if (jobs.Any()) {
217        var result = MessageBox.Show("Do you really want to pause following job(s):\n\n"
218                                     + String.Join("\n", jobs.Select(x => x.Job.Name)),
219          "HeuristicLab Hive Administrator",
220          MessageBoxButtons.YesNo,
221          MessageBoxIcon.Question);
222
223        if (result == DialogResult.Yes) {
224          progress.Start("Pausing job(s)...");
225          SetEnabledStateOfControls();
226          var task = System.Threading.Tasks.Task.Factory.StartNew(PauseJobsAsync, jobs);
227
228          task.ContinueWith((t) => {
229            RefreshJobs();
230            progress.Finish();
231            SetEnabledStateOfControls();
232          }, TaskContinuationOptions.NotOnFaulted);
233
234          task.ContinueWith((t) => {
235            RefreshJobs();
236            progress.Finish();
237            SetEnabledStateOfControls();
238            MessageBox.Show("An error occured pausing the job(s).", "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
239          }, TaskContinuationOptions.OnlyOnFaulted);
240        }
241      }
242    }
243
244    private void stopButton_Click(object sender, EventArgs e) {
245      var jobs = GetSelectedJobs();
246
247      if (jobs.Any()) {
248        var result = MessageBox.Show("Do you really want to stop following job(s):\n\n"
249                                     + String.Join("\n", jobs.Select(x => x.Job.Name)),
250          "HeuristicLab Hive Administrator",
251          MessageBoxButtons.YesNo,
252          MessageBoxIcon.Question);
253
254        if (result == DialogResult.Yes) {
255          progress.Start("Stopping job(s)...", ProgressMode.Indeterminate);
256          SetEnabledStateOfControls();
257          var task = System.Threading.Tasks.Task.Factory.StartNew(StopJobsAsync, jobs);
258
259          task.ContinueWith((t) => {
260            RefreshJobs();
261            progress.Finish();
262            SetEnabledStateOfControls();
263          }, TaskContinuationOptions.NotOnFaulted);
264
265          task.ContinueWith((t) => {
266            RefreshJobs();
267            progress.Finish();
268            SetEnabledStateOfControls();
269            MessageBox.Show("An error occured stopping the job(s).", "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
270          }, TaskContinuationOptions.OnlyOnFaulted);
271        }
272      }
273    }
274
275    public event EventHandler IsProgressingChanged;
276    private void OnIsProgressingChanged() {
277      var handler = IsProgressingChanged;
278      if (handler != null) handler(this, EventArgs.Empty);
279    }
280    #endregion Event Handlers
281
282    #region Helpers
283
284    private IEnumerable<RefreshableJob> GetSelectedJobs() {
285      if (Content == null || matrixView.DataGridView.SelectedRows == null || matrixView.DataGridView.SelectedRows.Count == 0)
286        return Enumerable.Empty<RefreshableJob>();
287
288      var jobs = new List<RefreshableJob>();
289      foreach (DataGridViewRow r in matrixView.DataGridView.SelectedRows) {
290        if (((string)r.Cells[0].Value) == JobState.Online.ToString()) {
291          jobs.Add(HiveAdminClient.Instance.Jobs[Content.Id].FirstOrDefault(x => x.Id == Guid.Parse((string)r.Cells[11].Value)));
292        }
293      }
294
295      return jobs;
296    }
297
298    private void RefreshJobs() {
299      HiveAdminClient.Instance.RefreshJobs(Content.Id);
300      UpdateJobs();
301      SetEnabledStateOfControls();
302    }
303
304    private StringMatrix CreateValueMatrix() {
305      if (Content == null || Content.Id == Guid.Empty || !HiveAdminClient.Instance.Jobs.ContainsKey(Content.Id))
306        return new StringMatrix();
307
308      var jobs = HiveAdminClient.Instance.Jobs[Content.Id];
309      var resources = HiveAdminClient.Instance.Resources;
310      string[,] values = new string[jobs.Count, 13];
311
312      for (int i = 0; i < jobs.Count; i++) {
313        var job = jobs.ElementAt(i);
314        values[i, 0] = job.Job.State.ToString();
315        values[i, 1] = job.ExecutionState.ToString();
316        values[i, 2] = job.ExecutionTime.ToString();
317        values[i, 3] = job.Job.DateCreated.ToString();
318        values[i, 4] = job.Job.OwnerUsername;
319        values[i, 5] = job.Job.Name;
320        values[i, 6] = job.Job.JobCount.ToString();
321        values[i, 7] = (job.Job.JobCount - job.Job.CalculatingCount - job.Job.FinishedCount).ToString();
322        values[i, 8] = job.Job.CalculatingCount.ToString();
323        values[i, 9] = job.Job.FinishedCount.ToString();
324        values[i, 10] = job.Job.Description;
325        values[i, 11] = job.Job.Id.ToString();
326        values[i, 12] = job.Job.OwnerUserId.ToString();
327      }
328
329      var matrix = new StringMatrix(values);
330      matrix.ColumnNames = new string[] { JOB_STATE, JOB_EXECUTIONSTATE, JOB_EXECUTIONTIME, JOB_DATECREATED, JOB_OWNER, JOB_NAME, JOB_TASKCOUNT, JOB_WAITINGTASKCOUNT, JOB_CALCULATINGTASKCOUNT, JOB_FINISHEDTASKCOUNT, JOB_DESCRIPTION, JOB_ID, JOB_OWNERID };
331      matrix.SortableView = true;
332      return matrix;
333    }
334
335    private void UpdateJobs() {
336      if (InvokeRequired) Invoke((Action)UpdateJobs);
337      else {
338        if (Content != null && Content.Id != null && Content.Id != Guid.Empty) {
339          var matrix = CreateValueMatrix();
340          matrixView.Content = matrix;
341          if (matrix != null) {
342            foreach (DataGridViewRow row in matrixView.DataGridView.Rows) {
343              string val = ((string)row.Cells[0].Value);
344              if (val == JobState.Online.ToString()) {
345                row.DefaultCellStyle.BackColor = onlineStatusColor;
346              } else if (val == JobState.StatisticsPending.ToString()) {
347                row.DefaultCellStyle.BackColor = statisticsPendingStatusColor;
348              } else if (val == JobState.DeletionPending.ToString()) {
349                row.DefaultCellStyle.BackColor = deletionPendingStatusColor;
350              }
351            }
352
353            matrixView.DataGridView.AutoResizeColumns();
354          }
355        }
356      }
357    }
358
359    private void RefreshJobsAsync() {
360      HiveAdminClient.Instance.RefreshJobs(Content.Id);
361      UpdateJobs();
362    }
363
364    private void ResumeJobsAsync(object jobs) {
365      var jobList = (IEnumerable<RefreshableJob>)jobs;
366      foreach (var job in jobList) {
367        progress.Message = "Resuming job \"" + job.Job.Name + "\"...";
368        HiveAdminClient.ResumeJob(job);
369      }
370    }
371
372    private void PauseJobsAsync(object jobs) {
373      var jobList = (IEnumerable<RefreshableJob>)jobs;
374      foreach (var job in jobList) {
375        progress.Message = "Pausing job \"" + job.Job.Name + "\"...";
376        HiveAdminClient.PauseJob(job);
377      }
378    }
379
380    private void StopJobsAsync(object jobs) {
381      var jobList = (IEnumerable<RefreshableJob>)jobs;
382      foreach (var job in jobList) {
383        progress.Message = "Stopping job \"" + job.Job.Name + "\"...";
384        HiveAdminClient.StopJob(job);
385      }
386    }
387
388    private void RemoveJobsAsync(object jobs) {
389      var jobList = (IEnumerable<RefreshableJob>)jobs;
390      progress.Start("", ProgressMode.Indeterminate);
391      foreach (var job in jobList) {
392        progress.Message = "Removing job \"" + job.Job.Name + "\"...";
393        HiveAdminClient.RemoveJob(job);
394      }
395      progress.Finish();
396    }
397
398    private void ShowHiveInformationDialog() {
399      if (InvokeRequired) Invoke((Action)ShowHiveInformationDialog);
400      else {
401        using (HiveInformationDialog dialog = new HiveInformationDialog()) {
402          dialog.ShowDialog(this);
403        }
404      }
405    }
406    #endregion Helpers
407  }
408}
Note: See TracBrowser for help on using the repository browser.