Changeset 16208 for trunk


Ignore:
Timestamp:
10/03/18 07:18:26 (11 months ago)
Author:
jzenisek
Message:

#2839: updated job execution implementation in ProjectJobsView

Location:
trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/HeuristicLab.Clients.Hive.Administrator/3.3/Views/ProjectJobsView.Designer.cs

    r16205 r16208  
    7676      this.removeButton.Size = new System.Drawing.Size(24, 24);
    7777      this.removeButton.TabIndex = 2;
    78       this.toolTip.SetToolTip(this.removeButton, "Delete job(s)");
     78      this.toolTip.SetToolTip(this.removeButton, "Remove job(s)");
    7979      this.removeButton.UseVisualStyleBackColor = true;
    8080      this.removeButton.Click += new System.EventHandler(this.removeButton_Click);
     
    8282      // startButton
    8383      //
    84       this.startButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
     84      this.startButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
    8585      this.startButton.Image = HeuristicLab.Common.Resources.VSImageLibrary.Play;
    86       this.startButton.Location = new System.Drawing.Point(0, 564);
     86      this.startButton.Location = new System.Drawing.Point(63, 3);
    8787      this.startButton.Name = "startButton";
    8888      this.startButton.Size = new System.Drawing.Size(24, 24);
     
    9494      // pauseButton
    9595      //
    96       this.pauseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
     96      this.pauseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
    9797      this.pauseButton.Enabled = false;
    9898      this.pauseButton.Image = HeuristicLab.Common.Resources.VSImageLibrary.Pause;
    99       this.pauseButton.Location = new System.Drawing.Point(30, 564);
     99      this.pauseButton.Location = new System.Drawing.Point(93, 3);
    100100      this.pauseButton.Name = "pauseButton";
    101101      this.pauseButton.Size = new System.Drawing.Size(24, 24);
     
    107107      // stopButton
    108108      //
    109       this.stopButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
     109      this.stopButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
    110110      this.stopButton.Image = HeuristicLab.Common.Resources.VSImageLibrary.Stop;
    111       this.stopButton.Location = new System.Drawing.Point(60, 564);
     111      this.stopButton.Location = new System.Drawing.Point(123, 3);
    112112      this.stopButton.Name = "stopButton";
    113113      this.stopButton.Size = new System.Drawing.Size(24, 24);
     
    139139      this.Controls.Add(this.refreshButton);
    140140      this.Controls.Add(this.removeButton);
     141      this.Controls.Add(this.startButton);
     142      this.Controls.Add(this.pauseButton);
     143      this.Controls.Add(this.stopButton);
    141144      this.Name = "ProjectJobsView";
    142145      this.Size = new System.Drawing.Size(510, 385);
  • trunk/HeuristicLab.Clients.Hive.Administrator/3.3/Views/ProjectJobsView.cs

    r16205 r16208  
    2424using System.Drawing;
    2525using System.Linq;
     26using System.Threading.Tasks;
    2627using System.Windows.Forms;
    2728using HeuristicLab.MainForm;
     
    3031using HeuristicLab.Data;
    3132using HeuristicLab.Clients.Hive.Views;
     33using HeuristicLab.Core;
    3234
    3335namespace HeuristicLab.Clients.Hive.Administrator.Views {
     
    4143    private const string JOB_DATECREATED = "Date Created";
    4244    private const string JOB_STATE = "State";
     45    private const string JOB_EXECUTIONSTATE = "Execution State";
    4346    private const string JOB_DESCRIPTION = "Description";
    4447    private const string JOB_TASKCOUNT = "Tasks";
    4548    private const string JOB_CALCULATINGTASKCOUNT = "Calculating";
    4649    private const string JOB_FINISHEDTASKCOUNT = "Finished";
    47 
    4850
    4951    private readonly Color onlineStatusColor = Color.FromArgb(255, 189, 249, 143); // #bdf98f
     
    5355    private readonly Color deletionPendingStatusColor2 = Color.FromArgb(255, 249, 149, 143); // #f9958f
    5456
     57    private IProgress progress;
     58    public IProgress Progress {
     59      get { return progress; }
     60      set {
     61        this.progress = value;
     62        OnIsProgressingChanged();
     63      }
     64    }
     65
    5566    public new Project Content {
    5667      get { return (Project)base.Content; }
     
    6071    public ProjectJobsView() {
    6172      InitializeComponent();
    62 
    63       removeButton.Enabled = false;
     73      progress = new Progress();
     74
     75      removeButton.Enabled = false;     
     76    }
     77
     78    protected override void RegisterContentEvents() {
     79      base.RegisterContentEvents();
    6480      matrixView.DataGridView.SelectionChanged += DataGridView_SelectionChanged;
     81      MainFormManager.GetMainForm<HeuristicLab.MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, progress);
     82    }
     83
     84    protected override void DeregisterContentEvents() {
     85      matrixView.DataGridView.SelectionChanged -= DataGridView_SelectionChanged;
     86      MainFormManager.GetMainForm<HeuristicLab.MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this, false);
     87      base.DeregisterContentEvents();
    6588    }
    6689
    6790    private void DataGridView_SelectionChanged(object sender, EventArgs e) {
    68       if (matrixView.DataGridView.SelectedRows == null || matrixView.DataGridView.SelectedRows.Count == 0) return;
    69 
    70       bool anyDeletable = false;
    71       foreach (DataGridViewRow r in matrixView.DataGridView.SelectedRows) {
    72         if (((string)r.Cells[0].Value) == JobState.Online.ToString()) anyDeletable = true;
    73       }
    74 
    75       removeButton.Enabled = anyDeletable;
     91      SetEnabledStateOfControls();
    7692    }
    7793
     
    8197      removeButton.Enabled = false;
    8298      UpdateJobs();
    83     }
     99      SetEnabledStateOfControls();
     100    }
     101
    84102    protected override void SetEnabledStateOfControls() {
    85103      base.SetEnabledStateOfControls();
    86104      bool enabled = Content != null && !Locked && !ReadOnly;
    87105
    88       refreshButton.Enabled = enabled;
    89       removeButton.Enabled = false;
    90106      matrixView.Enabled = enabled;
    91     }
     107
     108      // Buttons (start/resume, pause, stop, remove)
     109      refreshButton.Enabled = startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = removeButton.Enabled = false;
     110
     111      if (enabled && progress.ProgressState != ProgressState.Started) {
     112        var jobs = GetSelectedJobs().ToList();
     113        if (jobs.Any()) {
     114
     115          // TODO: include isControllable?!
     116          startButton.Enabled = jobs.All(x =>
     117            !x.IsProgressing && x.HiveTasks != null && x.HiveTasks.Count > 0
     118            && x.Job.ProjectId != null && x.Job.ProjectId != Guid.Empty && x.Job.ResourceIds != null && x.Job.ResourceIds.Any()
     119            && (x.ExecutionState == ExecutionState.Prepared || x.ExecutionState == ExecutionState.Paused));
     120          pauseButton.Enabled = jobs.All(x => !x.IsProgressing && x.ExecutionState == ExecutionState.Started);
     121          stopButton.Enabled = jobs.All(x => !x.IsProgressing && (x.ExecutionState == ExecutionState.Started || x.ExecutionState == ExecutionState.Paused));
     122          removeButton.Enabled = jobs.All(x => !x.IsProgressing && x.Job.State == JobState.Online);
     123        }
     124      }
     125
     126      // refresh Button
     127      if (Content != null && !Locked && progress.ProgressState != ProgressState.Started) {
     128        refreshButton.Enabled = true;
     129      }
     130    }
     131
    92132    #endregion Overrides
    93133
     
    98138
    99139    private void refreshButton_Click(object sender, EventArgs e) {
    100       RefreshJobs();
    101     }
    102 
    103     private async void removeButton_Click(object sender, EventArgs e) {
    104       if (matrixView.DataGridView.SelectedRows == null || matrixView.DataGridView.SelectedRows.Count == 0) return;
    105 
    106       var jobNamesToDelete = new List<string>();
    107       var jobIdsToDelete = new List<Guid>();
    108       foreach (DataGridViewRow r in matrixView.DataGridView.SelectedRows) {
    109         if(((string)r.Cells[0].Value) == JobState.Online.ToString()) {
    110           jobNamesToDelete.Add(" - " + ((string)r.Cells[3].Value));
    111           jobIdsToDelete.Add(Guid.Parse((string)r.Cells[8].Value));
    112         }
    113       }
    114 
    115       if(jobIdsToDelete.Any()) {
     140      var task = System.Threading.Tasks.Task.Factory.StartNew(RefreshJobsAsync);
     141      progress.Start("Refreshing jobs...");
     142      SetEnabledStateOfControls();
     143
     144      task.ContinueWith((t) => {
     145        matrixView.DataGridView.ClearSelection();
     146      });
     147    }
     148
     149    private void removeButton_Click(object sender, EventArgs e) {
     150      var jobs = GetSelectedJobs();
     151
     152      if (jobs.Any()) {
    116153        var result = MessageBox.Show("Do you really want to remove following job(s):\n\n"
    117           + String.Join("\n", jobNamesToDelete),
     154                                     + String.Join("\n", jobs.Select(x => x.Job.Name)),
    118155          "HeuristicLab Hive Administrator",
    119156          MessageBoxButtons.YesNo,
    120157          MessageBoxIcon.Question);
    121158
     159        if (result == DialogResult.Yes) {         
     160          var task = System.Threading.Tasks.Task.Factory.StartNew(RemoveJobsAsync, jobs);
     161          progress.Start();
     162          SetEnabledStateOfControls();
     163
     164          task.ContinueWith((t) => {
     165            matrixView.DataGridView.ClearSelection();
     166            RefreshJobs();
     167            progress.Finish();
     168          }, TaskContinuationOptions.NotOnFaulted);
     169
     170          task.ContinueWith((t) => {
     171            matrixView.DataGridView.ClearSelection();
     172            RefreshJobs();
     173            progress.Finish();
     174            MessageBox.Show("An error occured removing the job(s). " + t.Exception.Message, "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
     175          }, TaskContinuationOptions.OnlyOnFaulted);
     176        }
     177      }
     178    }
     179
     180    private void startButton_Click(object sender, EventArgs e) {
     181      var jobs = GetSelectedJobs();
     182
     183      if (jobs.Any()) {
     184        var result = MessageBox.Show("Do you really want to resume following job(s):\n\n"
     185                                     + String.Join("\n", jobs.Select(x => x.Job.Name)),
     186          "HeuristicLab Hive Administrator",
     187          MessageBoxButtons.YesNo,
     188          MessageBoxIcon.Question);
     189
    122190        if (result == DialogResult.Yes) {
    123           await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
    124             action: () => {
    125               DeleteJobs(jobIdsToDelete);
    126             },
    127             finallyCallback: () => {
    128               matrixView.DataGridView.ClearSelection();
    129               removeButton.Enabled = false;
    130               RefreshJobs();
    131             });
    132         }
    133       }
    134     }
    135 
    136     private async void startButton_Click(object sender, EventArgs e) {
    137       throw new NotImplementedException();
    138     }
    139 
    140     private async void pauseButton_Click(object sender, EventArgs e) {
    141       throw new NotImplementedException();
    142     }
    143 
    144     private async void stopButton_Click(object sender, EventArgs e) {
    145       throw new NotImplementedException();
    146     }
    147 
     191          var task = System.Threading.Tasks.Task.Factory.StartNew(ResumeJobsAsync, jobs);
     192          progress.Start();
     193          SetEnabledStateOfControls();
     194
     195          task.ContinueWith((t) => {
     196            matrixView.DataGridView.ClearSelection();
     197            RefreshJobs();
     198            progress.Finish();
     199          });
     200
     201          task.ContinueWith((t) => {
     202            matrixView.DataGridView.ClearSelection();
     203            RefreshJobs();
     204            progress.Finish();
     205            MessageBox.Show("An error occured resuming the job(s).", "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
     206          }, TaskContinuationOptions.OnlyOnFaulted);
     207        }
     208      }
     209    }
     210
     211    private void pauseButton_Click(object sender, EventArgs e) {
     212      var jobs = GetSelectedJobs();
     213
     214      if (jobs.Any()) {
     215        var result = MessageBox.Show("Do you really want to pause following job(s):\n\n"
     216                                     + String.Join("\n", jobs.Select(x => x.Job.Name)),
     217          "HeuristicLab Hive Administrator",
     218          MessageBoxButtons.YesNo,
     219          MessageBoxIcon.Question);
     220
     221        if (result == DialogResult.Yes) {
     222          var task = System.Threading.Tasks.Task.Factory.StartNew(PauseJobsAsync, jobs);
     223          progress.Start();
     224          SetEnabledStateOfControls();
     225
     226          task.ContinueWith((t) => {
     227            matrixView.DataGridView.ClearSelection();
     228            RefreshJobs();
     229            progress.Finish();
     230          });
     231
     232          task.ContinueWith((t) => {
     233            matrixView.DataGridView.ClearSelection();
     234            RefreshJobs();
     235            progress.Finish();
     236            MessageBox.Show("An error occured pausing the job(s).", "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
     237          }, TaskContinuationOptions.OnlyOnFaulted);
     238        }
     239      }
     240    }
     241
     242    private void stopButton_Click(object sender, EventArgs e) {
     243      var jobs = GetSelectedJobs();
     244
     245      if (jobs.Any()) {
     246        var result = MessageBox.Show("Do you really want to stop following job(s):\n\n"
     247                                     + String.Join("\n", jobs.Select(x => x.Job.Name)),
     248          "HeuristicLab Hive Administrator",
     249          MessageBoxButtons.YesNo,
     250          MessageBoxIcon.Question);
     251
     252        if (result == DialogResult.Yes) {
     253          var task = System.Threading.Tasks.Task.Factory.StartNew(StopJobsAsync, jobs);
     254          progress.Start();
     255          SetEnabledStateOfControls();
     256
     257          task.ContinueWith((t) => {
     258            matrixView.DataGridView.ClearSelection();
     259            RefreshJobs();
     260            progress.Finish();
     261          });
     262
     263          task.ContinueWith((t) => {
     264            matrixView.DataGridView.ClearSelection();
     265            RefreshJobs();
     266            progress.Finish();
     267            MessageBox.Show("An error occured stopping the job(s).", "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);           
     268          }, TaskContinuationOptions.OnlyOnFaulted);
     269        }
     270      }
     271    }
     272
     273    public event EventHandler IsProgressingChanged;
     274    private void OnIsProgressingChanged() {
     275      var handler = IsProgressingChanged;
     276      if (handler != null) handler(this, EventArgs.Empty);
     277    }
    148278    #endregion Event Handlers
    149279
    150280    #region Helpers
     281
     282    private IEnumerable<RefreshableJob> GetSelectedJobs() {
     283      if (Content == null || matrixView.DataGridView.SelectedRows == null || matrixView.DataGridView.SelectedRows.Count == 0)
     284        return Enumerable.Empty<RefreshableJob>() ;
     285
     286      var jobs = new List<RefreshableJob>();
     287      foreach (DataGridViewRow r in matrixView.DataGridView.SelectedRows) {
     288        if (((string)r.Cells[0].Value) == JobState.Online.ToString()) {
     289          jobs.Add(HiveAdminClient.Instance.Jobs[Content.Id].FirstOrDefault(x => x.Id == Guid.Parse((string) r.Cells[9].Value)));
     290        }
     291      }
     292
     293      return jobs;
     294    }
     295
    151296    private void RefreshJobs() {
    152297      HiveAdminClient.Instance.RefreshJobs();
    153298      UpdateJobs();
     299      SetEnabledStateOfControls();
    154300    }
    155301
     
    160306      var jobs = HiveAdminClient.Instance.Jobs[Content.Id];
    161307      var resources = HiveAdminClient.Instance.Resources;
    162       string[,] values = new string[jobs.Count, 10];
     308      string[,] values = new string[jobs.Count, 11];
    163309
    164310      for(int i = 0; i < jobs.Count; i++) {
    165         var job = jobs.ElementAt(i);
    166        
    167         values[i, 0] = job.State.ToString();
    168         values[i, 1] = job.DateCreated.ToString();
    169         values[i, 2] = job.OwnerUsername;
    170         values[i, 3] = job.Name;
    171         values[i, 4] = job.JobCount.ToString();
    172         values[i, 5] = job.CalculatingCount.ToString();
    173         values[i, 6] = job.FinishedCount.ToString();
    174         values[i, 7] = job.Description;       
    175         values[i, 8] = job.Id.ToString();
    176         values[i, 9] = job.OwnerUserId.ToString();
     311        var job = jobs.ElementAt(i);       
     312        values[i, 0] = job.Job.State.ToString();
     313        values[i, 1] = job.ExecutionState.ToString();
     314        values[i, 2] = job.Job.DateCreated.ToString();
     315        values[i, 3] = job.Job.OwnerUsername;
     316        values[i, 4] = job.Job.Name;
     317        values[i, 5] = job.Job.JobCount.ToString();
     318        values[i, 6] = job.Job.CalculatingCount.ToString();
     319        values[i, 7] = job.Job.FinishedCount.ToString();
     320        values[i, 8] = job.Job.Description;       
     321        values[i, 9] = job.Job.Id.ToString();
     322        values[i, 10] = job.Job.OwnerUserId.ToString();
    177323      }
    178324     
    179325      var matrix = new StringMatrix(values);
    180       matrix.ColumnNames = new string[] { JOB_STATE, JOB_DATECREATED, JOB_OWNER, JOB_NAME, JOB_TASKCOUNT, JOB_CALCULATINGTASKCOUNT, JOB_FINISHEDTASKCOUNT, JOB_DESCRIPTION, JOB_ID, JOB_OWNERID };
     326      matrix.ColumnNames = new string[] { JOB_STATE, JOB_EXECUTIONSTATE, JOB_DATECREATED, JOB_OWNER, JOB_NAME, JOB_TASKCOUNT, JOB_CALCULATINGTASKCOUNT, JOB_FINISHEDTASKCOUNT, JOB_DESCRIPTION, JOB_ID, JOB_OWNERID };
    181327      matrix.SortableView = true;
    182328      return matrix;
     
    205351            matrixView.DataGridView.Columns[1].MinimumWidth = 108;
    206352          }
    207         } else {
    208           refreshButton.Enabled = false;
    209           removeButton.Enabled = false;
    210           matrixView.Content = null;
    211         }
    212       }
    213     }
    214 
    215     private void PauseJobs(List<Guid> jobIds) {
    216       try {
    217         // TODO
    218       } catch (AnonymousUserException) {
    219         ShowHiveInformationDialog();
    220       }
    221     }
    222 
    223     private void StopJobs(List<Guid> jobIds) {
    224       try {
    225         // TODO
    226       } catch (AnonymousUserException) {
    227         ShowHiveInformationDialog();
    228       }
    229     }
    230 
    231     private void DeleteJobs(List<Guid> jobIds) {
    232       try {
    233         HiveAdminClient.DeleteJobs(jobIds);
    234       } catch (AnonymousUserException) {
    235         ShowHiveInformationDialog();
    236       }
     353        }
     354      }
     355    }
     356
     357    private void RefreshJobsAsync() {
     358      RefreshJobs();
     359    }
     360
     361    private void ResumeJobsAsync(object jobs) {
     362      var jobList = (IEnumerable<RefreshableJob>)jobs;
     363      foreach (var job in jobList) {
     364        progress.Status = "Resuming job \"" + job.Job.Name + "\"...";
     365        HiveAdminClient.ResumeJob(job);
     366      }
     367    }
     368
     369    private void PauseJobsAsync(object jobs) {
     370      var jobList = (IEnumerable<RefreshableJob>)jobs;
     371      foreach (var job in jobList) {
     372        progress.Status = "Pausing job \"" + job.Job.Name + "\"...";
     373        HiveAdminClient.PauseJob(job);
     374      }
     375    }
     376
     377    private void StopJobsAsync(object jobs) {
     378      var jobList = (IEnumerable<RefreshableJob>) jobs;
     379      foreach (var job in jobList) {       
     380        progress.Status = "Stopping job \"" + job.Job.Name + "\"...";
     381        HiveAdminClient.StopJob(job);
     382      }
     383    }
     384
     385    private void RemoveJobsAsync(object jobs) {
     386      var jobList = (IEnumerable<RefreshableJob>)jobs;
     387      progress.Start();
     388      foreach (var job in jobList) {
     389        progress.Status = "Deleting job \"" + job.Job.Name + "\"...";
     390        HiveAdminClient.RemoveJob(job);
     391      }
     392      progress.Finish();
    237393    }
    238394
  • trunk/HeuristicLab.Clients.Hive/3.3/HiveAdminClient.cs

    r16202 r16208  
    7171    }
    7272
    73     private Dictionary<Guid, HiveItemCollection<Job>> jobs;
    74     public Dictionary<Guid, HiveItemCollection<Job>> Jobs {
     73    private Dictionary<Guid, HiveItemCollection<RefreshableJob>> jobs;
     74    public Dictionary<Guid, HiveItemCollection<RefreshableJob>> Jobs {
    7575      get { return jobs; }
    7676      set {
     
    144144        projects = new ItemList<Project>();
    145145        projectResourceAssignments = new ItemList<AssignedProjectResource>();
    146         jobs = new Dictionary<Guid, HiveItemCollection<Job>>();
     146        jobs = new Dictionary<Guid, HiveItemCollection<RefreshableJob>>();
    147147        projectNames = new Dictionary<Guid, string>();
    148148        resourceNames = new Dictionary<Guid, string>();
     
    161161            service.GetAssignedResourcesForProjectsAdministration(projectIds)
    162162              .ForEach(a => projectResourceAssignments.Add(a));
    163             projectIds.ForEach(p => jobs.Add(p, new HiveItemCollection<Job>()));
     163            projectIds.ForEach(p => jobs.Add(p, new HiveItemCollection<RefreshableJob>()));
    164164            var unsortedJobs = service.GetJobsByProjectIds(projectIds)
    165165              .OrderBy(x => x.DateCreated).ToList();
    166166
    167             unsortedJobs.Where(j => j.State == JobState.DeletionPending).ToList().ForEach(j => jobs[j.ProjectId].Add(j));
    168             unsortedJobs.Where(j => j.State == JobState.StatisticsPending).ToList().ForEach(j => jobs[j.ProjectId].Add(j));
    169             unsortedJobs.Where(j => j.State == JobState.Online).ToList().ForEach(j => jobs[j.ProjectId].Add(j));
     167            unsortedJobs.Where(j => j.State == JobState.DeletionPending).ToList().ForEach(j => jobs[j.ProjectId].Add(new RefreshableJob(j)));
     168            unsortedJobs.Where(j => j.State == JobState.StatisticsPending).ToList().ForEach(j => jobs[j.ProjectId].Add(new RefreshableJob(j)));
     169            unsortedJobs.Where(j => j.State == JobState.Online).ToList().ForEach(j => jobs[j.ProjectId].Add(new RefreshableJob(j)));
     170
     171            foreach (var job in jobs.SelectMany(x => x.Value))
     172              LoadLightweightJob(job);
    170173
    171174            projectNames = service.GetProjectNames();
     
    307310    public void RefreshJobs() {
    308311      var projectIds = new List<Guid>();
    309       jobs = new Dictionary<Guid, HiveItemCollection<Job>>();
     312      jobs = new Dictionary<Guid, HiveItemCollection<RefreshableJob>>();
    310313
    311314      HiveServiceLocator.Instance.CallHiveService(service => {
    312315        service.GetProjectsForAdministration().ForEach(p => projectIds.Add(p.Id));
    313316        if(projectIds.Any()) {
    314           projectIds.ForEach(p => jobs.Add(p, new HiveItemCollection<Job>()));
     317          projectIds.ForEach(p => jobs.Add(p, new HiveItemCollection<RefreshableJob>()));
    315318          var unsortedJobs = service.GetJobsByProjectIds(projectIds)
    316319            .OrderBy(x => x.DateCreated).ToList();
    317           unsortedJobs.Where(j => j.State == JobState.DeletionPending).ToList().ForEach(j => jobs[j.ProjectId].Add(j));
    318           unsortedJobs.Where(j => j.State == JobState.StatisticsPending).ToList().ForEach(j => jobs[j.ProjectId].Add(j));
    319           unsortedJobs.Where(j => j.State == JobState.Online).ToList().ForEach(j => jobs[j.ProjectId].Add(j));
     320         
     321          unsortedJobs.Where(j => j.State == JobState.DeletionPending).ToList().ForEach(j => jobs[j.ProjectId].Add(new RefreshableJob(j)));
     322          unsortedJobs.Where(j => j.State == JobState.StatisticsPending).ToList().ForEach(j => jobs[j.ProjectId].Add(new RefreshableJob(j)));
     323          unsortedJobs.Where(j => j.State == JobState.Online).ToList().ForEach(j => jobs[j.ProjectId].Add(new RefreshableJob(j)));
     324
     325          foreach(var job in jobs.SelectMany(x => x.Value))
     326            LoadLightweightJob(job);
    320327        }
    321328      });
     329    }
     330
     331    public static void LoadLightweightJob(RefreshableJob refreshableJob) {
     332      var job = refreshableJob.Job;
     333      var tasks = HiveServiceLocator.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(job.Id));
     334      if (tasks != null && tasks.Count > 0 && tasks.All(x => x.Id != Guid.Empty)) {
     335        if (tasks.All(x =>
     336          x.State == TaskState.Finished
     337          || x.State == TaskState.Aborted
     338          || x.State == TaskState.Failed)) {
     339          refreshableJob.ExecutionState = ExecutionState.Stopped;
     340          refreshableJob.RefreshAutomatically = false;
     341        } else if (
     342          tasks
     343            .Where(x => x.ParentTaskId != null)
     344            .All(x =>
     345              x.State != TaskState.Waiting
     346              || x.State != TaskState.Transferring
     347              || x.State != TaskState.Calculating)
     348          && tasks
     349             .Where(x => x.ParentTaskId != null)
     350             .Any(x => x.State == TaskState.Paused)) {
     351          refreshableJob.ExecutionState = ExecutionState.Paused;
     352          refreshableJob.RefreshAutomatically = false;
     353        } else if (tasks.Any(x => x.State == TaskState.Calculating
     354                                  || x.State == TaskState.Transferring
     355                                  || x.State == TaskState.Waiting)) {
     356          refreshableJob.ExecutionState = ExecutionState.Started;
     357        }
     358      }
    322359    }
    323360
     
    327364        var unsortedJobs = jobs.Values.ElementAt(i);
    328365
    329         var sortedJobs = new HiveItemCollection<Job>();
    330         sortedJobs.AddRange(unsortedJobs.Where(j => j.State == JobState.DeletionPending));
    331         sortedJobs.AddRange(unsortedJobs.Where(j => j.State == JobState.StatisticsPending));
    332         sortedJobs.AddRange(unsortedJobs.Where(j => j.State == JobState.Online));
     366        var sortedJobs = new HiveItemCollection<RefreshableJob>();
     367        sortedJobs.AddRange(unsortedJobs.Where(j => j.Job.State == JobState.DeletionPending));
     368        sortedJobs.AddRange(unsortedJobs.Where(j => j.Job.State == JobState.StatisticsPending));
     369        sortedJobs.AddRange(unsortedJobs.Where(j => j.Job.State == JobState.Online));
    333370
    334371        jobs[projectId] = sortedJobs;
     
    405442    }
    406443
    407     public static void DeleteJobs(List<Guid> jobIds) {
    408 
     444    public static void RemoveJobs(List<Guid> jobIds) {
    409445      HiveServiceLocator.Instance.CallHiveService((s) => s.UpdateJobStates(jobIds, JobState.StatisticsPending));
     446    }
     447    #endregion
     448
     449    #region Job Handling
     450
     451    public static void ResumeJob(RefreshableJob refreshableJob) {
     452      HiveServiceLocator.Instance.CallHiveService(service => {
     453        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
     454          if (task.Task.State == TaskState.Paused) {
     455            service.RestartTask(task.Task.Id);
     456          }
     457        }
     458      });
     459      refreshableJob.ExecutionState = ExecutionState.Started;
     460    }
     461
     462    public static void PauseJob(RefreshableJob refreshableJob) {
     463      HiveServiceLocator.Instance.CallHiveService(service => {
     464        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
     465          if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
     466            service.PauseTask(task.Task.Id);
     467        }
     468      });
     469      refreshableJob.ExecutionState = ExecutionState.Paused;
     470    }
     471
     472    public static void StopJob(RefreshableJob refreshableJob) {
     473      HiveServiceLocator.Instance.CallHiveService(service => {
     474        foreach (HiveTask task in refreshableJob.GetAllHiveTasks()) {
     475          if (task.Task.State != TaskState.Finished && task.Task.State != TaskState.Aborted && task.Task.State != TaskState.Failed)
     476            service.StopTask(task.Task.Id);
     477        }
     478      });
     479      refreshableJob.ExecutionState = ExecutionState.Stopped;
     480    }
     481
     482    public static void RemoveJob(RefreshableJob refreshableJob) {
     483      HiveServiceLocator.Instance.CallHiveService((s) => {
     484        s.UpdateJobState(refreshableJob.Id, JobState.StatisticsPending);
     485      });
    410486    }
    411487    #endregion
  • trunk/HeuristicLab.Services.Hive/3.3/HiveService.cs

    r16203 r16208  
    520520
    521521    public void UpdateJobState(Guid jobId, DT.JobState jobState) {
    522       RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    523       AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
     522      if (jobState != JobState.StatisticsPending) return; // only process requests for "StatisticsPending"
     523
     524      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     525      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
     526      var currentUserId = UserManager.CurrentUserId;
     527
    524528      var pm = PersistenceManager;
    525529      using (new PerformanceLogger("UpdateJobState")) {
    526530        var jobDao = pm.JobDao;
     531        var projectDao = pm.ProjectDao;
    527532        pm.UseTransaction(() => {
    528533          var job = jobDao.GetById(jobId);
    529534          if (job != null) {
     535
     536            var administrationGrantedProjects = projectDao
     537              .GetAdministrationGrantedProjectsForUser(currentUserId)
     538              .ToList();
     539
     540            // check if user is an admin, or granted to administer a job-parenting project,...
     541            if (!isAdministrator && !administrationGrantedProjects.Contains(job.Project))
     542              AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full); // ... or job owner
     543
     544            // note: allow solely state changes from "Online" to "StatisticsPending" = deletion request by user for HiveStatisticGenerator           
    530545            var jobStateEntity = jobState.ToEntity();
    531             // note: allow solely state changes from "Online" to "StatisticsPending" = deletion request by user for HiveStatisticGenerator
    532             // and from "StatisticsPending" to "DeletionPending" = deletion request by HiveStatisticGenerator for EventManager
    533546            if (job.State == DA.JobState.Online && jobStateEntity == DA.JobState.StatisticsPending) {
    534547              job.State = jobStateEntity;
     
    540553              }
    541554              pm.SubmitChanges();
    542             } else if (job.State == DA.JobState.StatisticsPending && jobStateEntity == DA.JobState.DeletionPending) {
    543               job.State = jobStateEntity;
    544               pm.SubmitChanges();
    545555            }
    546556          }
     
    561571        var projectDao = pm.ProjectDao;
    562572        pm.UseTransaction(() => {
     573          var administrationGrantedProjects = projectDao
     574            .GetAdministrationGrantedProjectsForUser(currentUserId)
     575            .ToList();
     576
    563577          foreach (var jobId in jobIds) {
    564578            var job = jobDao.GetById(jobId);
    565579            if (job != null) {
    566580
    567               var administrationGrantedProjects = projectDao
    568                 .GetAdministrationGrantedProjectsForUser(currentUserId)
    569                 .ToList();
    570 
    571               // check if user is granted to administer the job-parenting project
    572               if (isAdministrator || administrationGrantedProjects.Contains(job.Project)) {
    573                 // note: allow solely state changes from "Online" to "StatisticsPending" = deletion request by user for HiveStatisticGenerator
    574                 if (job.State == DA.JobState.Online) {
    575                   job.State = DA.JobState.StatisticsPending;
    576                   foreach (var task in job.Tasks
    577                   .Where(x => x.State == DA.TaskState.Waiting
    578                     || x.State == DA.TaskState.Paused
    579                     || x.State == DA.TaskState.Offline)) {
    580                     task.State = DA.TaskState.Aborted;
    581                   }
    582                   pm.SubmitChanges();
     581              // check if user is an admin, or granted to administer a job-parenting project,...
     582              if (!isAdministrator && !administrationGrantedProjects.Contains(job.Project))
     583                AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full); // ... or job owner
     584
     585              // note: allow solely state changes from "Online" to "StatisticsPending" = deletion request by user for HiveStatisticGenerator
     586              var jobStateEntity = jobState.ToEntity();
     587              if (job.State == DA.JobState.Online && jobStateEntity == DA.JobState.StatisticsPending) {
     588                job.State = jobStateEntity;
     589                foreach (var task in job.Tasks
     590                .Where(x => x.State == DA.TaskState.Waiting
     591                  || x.State == DA.TaskState.Paused
     592                  || x.State == DA.TaskState.Offline)) {
     593                  task.State = DA.TaskState.Aborted;
    583594                }
    584               }
     595                pm.SubmitChanges();
     596              }             
    585597            }
    586598          }
Note: See TracChangeset for help on using the changeset viewer.