Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveProjectManagement/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 15728

Last change on this file since 15728 was 15715, checked in by jzenisek, 7 years ago

#2839 improved permission checking of HiveService methods

File size: 61.6 KB
RevLine 
[12691]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[12691]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;
[12584]23using System.Collections.Generic;
24using System.Linq;
[12691]25using System.Security;
26using System.ServiceModel;
[12584]27using HeuristicLab.Services.Access;
28using HeuristicLab.Services.Hive.DataAccess.Interfaces;
29using HeuristicLab.Services.Hive.DataTransfer;
[12691]30using HeuristicLab.Services.Hive.Manager;
[12584]31using HeuristicLab.Services.Hive.ServiceContracts;
32using DA = HeuristicLab.Services.Hive.DataAccess;
33using DT = HeuristicLab.Services.Hive.DataTransfer;
34
35namespace HeuristicLab.Services.Hive {
[12691]36  /// <summary>
37  /// Implementation of the Hive service (interface <see cref="IHiveService"/>).
38  /// We need 'IgnoreExtensionDataObject' Attribute for the slave to work.
39  /// </summary>
40  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, IgnoreExtensionDataObject = true)]
41  [HiveOperationContextBehavior]
[12861]42  public class HiveService : IHiveService {
[15530]43    private const string NOT_AUTHORIZED_PROJECTRESOURCE = "Selected project is not authorized to access the requested resource";
44    private const string NOT_AUTHORIZED_USERPROJECT = "Current user is not authorized to access the requested project";
[15503]45
[12584]46    private static readonly DA.TaskState[] CompletedStates = { DA.TaskState.Finished, DA.TaskState.Aborted, DA.TaskState.Failed };
47
48    private IPersistenceManager PersistenceManager {
49      get { return ServiceLocator.Instance.PersistenceManager; }
50    }
51
52    private IUserManager UserManager {
53      get { return ServiceLocator.Instance.UserManager; }
54    }
55
56    private IRoleVerifier RoleVerifier {
57      get { return ServiceLocator.Instance.RoleVerifier; }
58    }
59
60    private IAuthorizationManager AuthorizationManager {
61      get { return ServiceLocator.Instance.AuthorizationManager; }
62    }
[12691]63    private IEventManager EventManager {
64      get { return ServiceLocator.Instance.EventManager; }
65    }
[12861]66    private HeartbeatManager HeartbeatManager {
67      get { return ServiceLocator.Instance.HeartbeatManager; }
[12691]68    }
[12584]69
[12691]70    #region Task Methods
[15497]71
[15530]72    public Guid AddTask(DT.Task task, DT.TaskData taskData) {
[12584]73      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15715]74      AuthorizationManager.AuthorizeForJob(task.JobId, DT.Permission.Full);
[12857]75      var pm = PersistenceManager;
[15530]76      using (new PerformanceLogger("AddTask")) {
77        var taskDao = pm.TaskDao;
78        var stateLogDao = pm.StateLogDao;
79        var newTask = task.ToEntity();
80        newTask.JobData = taskData.ToEntity();
81        newTask.JobData.LastUpdate = DateTime.Now;
82        newTask.State = DA.TaskState.Waiting;
83        return pm.UseTransaction(() => {
84          taskDao.Save(newTask);
85          pm.SubmitChanges();
86          stateLogDao.Save(new DA.StateLog {
87            State = DA.TaskState.Waiting,
88            DateTime = DateTime.Now,
89            TaskId = newTask.TaskId,
90            UserId = UserManager.CurrentUserId,
91            SlaveId = null,
92            Exception = null
93          });
94          pm.SubmitChanges();
95          return newTask.TaskId;
96        }, false, true);
[12584]97      }
[15530]98    }
99
100    public Guid AddChildTask(Guid parentTaskId, DT.Task task, DT.TaskData taskData) {
101      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12584]102      task.ParentTaskId = parentTaskId;
[15530]103      return AddTask(task, taskData);
[12584]104    }
105
106    public DT.Task GetTask(Guid taskId) {
107      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
108      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
[12857]109      var pm = PersistenceManager;
[12691]110      using (new PerformanceLogger("GetTask")) {
[12584]111        var taskDao = pm.TaskDao;
112        return pm.UseTransaction(() => {
113          var task = taskDao.GetById(taskId);
114          return task.ToDto();
115        });
116      }
117    }
118
119    public IEnumerable<DT.LightweightTask> GetLightweightJobTasks(Guid jobId) {
120      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
121      AuthorizationManager.AuthorizeForJob(jobId, Permission.Read);
[12857]122      var pm = PersistenceManager;
[12691]123      using (new PerformanceLogger("GetLightweightJobTasks")) {
[12584]124        var taskDao = pm.TaskDao;
125        return pm.UseTransaction(() => {
126          return taskDao.GetByJobId(jobId)
[12691]127            .ToList()
[12584]128            .Select(x => new DT.LightweightTask {
129              Id = x.TaskId,
130              ExecutionTime = TimeSpan.FromMilliseconds(x.ExecutionTimeMs),
131              ParentTaskId = x.ParentTaskId,
132              StateLog = x.StateLogs.OrderBy(y => y.DateTime)
133                                    .Select(z => z.ToDto())
134                                    .ToList(),
135              State = x.State.ToDto(),
136              Command = x.Command.ToDto(),
137              LastTaskDataUpdate = x.JobData.LastUpdate
[12691]138            })
139            .ToList();
[12584]140        }, false, true);
141      }
142    }
143
144    public IEnumerable<DT.LightweightTask> GetLightweightJobTasksWithoutStateLog(Guid jobId) {
145      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
146      AuthorizationManager.AuthorizeForJob(jobId, Permission.Read);
[12857]147      var pm = PersistenceManager;
[12691]148      using (new PerformanceLogger("GetLightweightJobTasksWithoutStateLog")) {
[12584]149        var taskDao = pm.TaskDao;
150        return pm.UseTransaction(() => {
151          return taskDao.GetByJobId(jobId)
[12691]152            .ToList()
[12584]153            .Select(x => new DT.LightweightTask {
154              Id = x.TaskId,
155              ExecutionTime = TimeSpan.FromMilliseconds(x.ExecutionTimeMs),
156              ParentTaskId = x.ParentTaskId,
157              StateLog = new List<DT.StateLog>(),
158              State = x.State.ToDto(),
159              Command = x.Command.ToDto(),
160              LastTaskDataUpdate = x.JobData.LastUpdate
[12691]161            })
162            .ToList();
[12584]163        }, false, true);
164      }
165    }
166
167    public DT.TaskData GetTaskData(Guid taskId) {
168      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
169      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
[12857]170      var pm = PersistenceManager;
[12691]171      using (new PerformanceLogger("GetTaskData")) {
[12584]172        var taskDataDao = pm.TaskDataDao;
173        return pm.UseTransaction(() => taskDataDao.GetById(taskId).ToDto());
174      }
175    }
176
177    public void UpdateTask(DT.Task taskDto) {
178      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
179      AuthorizationManager.AuthorizeForTask(taskDto.Id, Permission.Full);
[12857]180      var pm = PersistenceManager;
[12691]181      using (new PerformanceLogger("UpdateTask")) {
[12584]182        var taskDao = pm.TaskDao;
183        pm.UseTransaction(() => {
184          var task = taskDao.GetById(taskDto.Id);
185          taskDto.CopyToEntity(task);
186          pm.SubmitChanges();
187        });
188      }
189    }
190
191    public void UpdateTaskData(DT.Task taskDto, DT.TaskData taskDataDto) {
192      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
193      AuthorizationManager.AuthorizeForTask(taskDto.Id, Permission.Full);
[12857]194      var pm = PersistenceManager;
[12691]195      using (new PerformanceLogger("UpdateTaskData")) {
[12584]196        var taskDao = pm.TaskDao;
197        var taskDataDao = pm.TaskDataDao;
198        pm.UseTransaction(() => {
199          var task = taskDao.GetById(taskDto.Id);
200          var taskData = taskDataDao.GetById(taskDataDto.TaskId);
201          taskDto.CopyToEntity(task);
202          taskDataDto.CopyToEntity(taskData);
203          taskData.LastUpdate = DateTime.Now;
204          pm.SubmitChanges();
205        });
206      }
207    }
208
209    public DT.Task UpdateTaskState(Guid taskId, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
210      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
211      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
[12857]212      var pm = PersistenceManager;
[12691]213      using (new PerformanceLogger("UpdateTaskState")) {
[12584]214        var taskDao = pm.TaskDao;
215        return pm.UseTransaction(() => {
216          var task = taskDao.GetById(taskId);
217          UpdateTaskState(pm, task, taskState, slaveId, userId, exception);
218          pm.SubmitChanges();
219          return task.ToDto();
220        });
221      }
222    }
[12691]223    #endregion
[12584]224
[12691]225    #region Task Control Methods
[12584]226    public void StopTask(Guid taskId) {
227      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
228      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
[12857]229      var pm = PersistenceManager;
[12691]230      using (new PerformanceLogger("StopTask")) {
[12584]231        var taskDao = pm.TaskDao;
232        pm.UseTransaction(() => {
233          var task = taskDao.GetById(taskId);
234          if (task.State == DA.TaskState.Calculating || task.State == DA.TaskState.Transferring) {
235            task.Command = DA.Command.Stop;
236          } else if (task.State != DA.TaskState.Aborted
237                     && task.State != DA.TaskState.Finished
238                     && task.State != DA.TaskState.Failed) {
239            UpdateTaskState(pm, task, DT.TaskState.Aborted, null, null, string.Empty);
240          }
241          pm.SubmitChanges();
242        });
243      }
244    }
245
246    public void PauseTask(Guid taskId) {
247      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
248      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
[12857]249      var pm = PersistenceManager;
[12691]250      using (new PerformanceLogger("PauseTask")) {
[12584]251        var taskDao = pm.TaskDao;
252        pm.UseTransaction(() => {
253          var task = taskDao.GetById(taskId);
254          if (task.State == DA.TaskState.Calculating || task.State == DA.TaskState.Transferring) {
255            task.Command = DA.Command.Pause;
[15121]256          } else if (task.State != DA.TaskState.Paused
257                     && task.State != DA.TaskState.Aborted
[14901]258                     && task.State != DA.TaskState.Finished
259                     && task.State != DA.TaskState.Failed) {
260            UpdateTaskState(pm, task, DT.TaskState.Paused, null, null, string.Empty);
[12584]261          }
262          pm.SubmitChanges();
263        });
264      }
265    }
266
267    public void RestartTask(Guid taskId) {
268      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
269      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
[12857]270      var pm = PersistenceManager;
[12691]271      using (new PerformanceLogger("RestartTask")) {
[12584]272        var taskDao = pm.TaskDao;
273        pm.UseTransaction(() => {
274          var task = taskDao.GetById(taskId);
275          task.Command = null;
276          UpdateTaskState(pm, task, DT.TaskState.Waiting, null, UserManager.CurrentUserId, string.Empty);
277          pm.SubmitChanges();
278        });
279      }
280    }
[12691]281    #endregion
[12584]282
[12691]283    #region Job Methods
284    public DT.Job GetJob(Guid id) {
[12584]285      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12691]286      AuthorizationManager.AuthorizeForJob(id, DT.Permission.Read);
[12857]287      var pm = PersistenceManager;
[12691]288      using (new PerformanceLogger("GetJob")) {
[12584]289        var jobDao = pm.JobDao;
290        var jobPermissionDao = pm.JobPermissionDao;
291        var taskDao = pm.TaskDao;
[12691]292        var currentUserId = UserManager.CurrentUserId;
[12584]293        return pm.UseTransaction(() => {
294          var job = jobDao.GetById(id).ToDto();
295          if (job != null) {
296            var statistics = taskDao.GetByJobId(job.Id)
297              .GroupBy(x => x.JobId)
298              .Select(x => new {
299                TotalCount = x.Count(),
300                CalculatingCount = x.Count(y => y.State == DA.TaskState.Calculating),
301                FinishedCount = x.Count(y => CompletedStates.Contains(y.State))
302              }).FirstOrDefault();
303            if (statistics != null) {
304              job.JobCount = statistics.TotalCount;
305              job.CalculatingCount = statistics.CalculatingCount;
306              job.FinishedCount = statistics.FinishedCount;
307            }
[12932]308            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
[12691]309            if (currentUserId == job.OwnerUserId) {
310              job.Permission = Permission.Full;
311            } else {
312              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
313              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
314            }
[12584]315          }
316          return job;
317        });
318      }
319    }
320
[12691]321    public IEnumerable<DT.Job> GetJobs() {
322      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12857]323      var pm = PersistenceManager;
[12691]324      using (new PerformanceLogger("GetJobs")) {
325        var jobDao = pm.JobDao;
326        var jobPermissionDao = pm.JobPermissionDao;
327        var taskDao = pm.TaskDao;
328        var currentUserId = UserManager.CurrentUserId;
329        return pm.UseTransaction(() => {
330          var jobs = jobDao.GetAll()
[15630]331            .Where(x => x.State == DA.JobState.Online
332                          && (x.OwnerUserId == currentUserId
333                            || x.JobPermissions.Count(y => y.Permission != DA.Permission.NotAllowed
334                              && y.GrantedUserId == currentUserId) > 0)
335                          )
[12691]336            .Select(x => x.ToDto())
337            .ToList();
338          var statistics = taskDao.GetAll()
[15552]339              .Where(x => jobs.Select(y => y.Id).Contains(x.JobId))
[12691]340              .GroupBy(x => x.JobId)
341              .Select(x => new {
342                x.Key,
343                TotalCount = x.Count(),
344                CalculatingCount = x.Count(y => y.State == DA.TaskState.Calculating),
345                FinishedCount = x.Count(y => CompletedStates.Contains(y.State))
346              })
347              .ToList();
348          foreach (var job in jobs) {
349            var statistic = statistics.FirstOrDefault(x => x.Key == job.Id);
350            if (statistic != null) {
351              job.JobCount = statistic.TotalCount;
352              job.CalculatingCount = statistic.CalculatingCount;
353              job.FinishedCount = statistic.FinishedCount;
354            }
[12932]355            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
[12691]356            if (currentUserId == job.OwnerUserId) {
357              job.Permission = Permission.Full;
358            } else {
359              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
360              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
361            }
362          }
363          return jobs;
364        });
365      }
[12584]366    }
367
[15530]368    public Guid AddJob(DT.Job jobDto, IEnumerable<Guid> resourceIds) {
369      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
370      // check user - project
371      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, jobDto.ProjectId);
372      // check project - resources
373      AuthorizationManager.AuthorizeProjectForResourcesUse(jobDto.ProjectId, resourceIds);
374      var pm = PersistenceManager;
375      using (new PerformanceLogger("AddJob")) {
376        var jobDao = pm.JobDao;
377        var userPriorityDao = pm.UserPriorityDao;
378
379        return pm.UseTransaction(() => {
380          var newJob = jobDto.ToEntity();
381          newJob.OwnerUserId = UserManager.CurrentUserId;
382          newJob.DateCreated = DateTime.Now;
383
384          // add resource assignments
[15715]385          if (resourceIds != null && resourceIds.Any()) {           
386            newJob.AssignedJobResources.AddRange(resourceIds.Select(
387              x => new DA.AssignedJobResource {
388                ResourceId = x
389              }));
390          }
[15547]391
[15530]392          var job = jobDao.Save(newJob);
393          if (userPriorityDao.GetById(jobDto.OwnerUserId) == null) {
394            userPriorityDao.Save(new DA.UserPriority {
395              UserId = jobDto.OwnerUserId,
396              DateEnqueued = jobDto.DateCreated
397            });
398          }
399          pm.SubmitChanges();
400          return job.JobId;
401        });
402      }
403    }
404
405    public void UpdateJob(DT.Job jobDto, IEnumerable<Guid> resourceIds) {
406      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
407      AuthorizationManager.AuthorizeForJob(jobDto.Id, DT.Permission.Full);
408      // check user - project permission
409      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, jobDto.ProjectId);
410      // check project - resources permission
411      AuthorizationManager.AuthorizeProjectForResourcesUse(jobDto.ProjectId, resourceIds);
412
413      var pm = PersistenceManager;
414      using (new PerformanceLogger("UpdateJob")) {
415        bool exists = true;
416        var jobDao = pm.JobDao;
417        pm.UseTransaction(() => {
418          var job = jobDao.GetById(jobDto.Id);
419          if (job == null) {
420            exists = false;
421            job = new DA.Job();
422          }
423          jobDto.CopyToEntity(job);
424
425          if (!exists) {
[15628]426            // add resource assignments
[15715]427            if (resourceIds != null && resourceIds.Any()) {
428              job.AssignedJobResources.AddRange(resourceIds.Select(
429                x => new DA.AssignedJobResource {
430                  ResourceId = x
[15628]431              }));
[15715]432            }
[15530]433            jobDao.Save(job);
[15715]434          } else if(resourceIds != null) {
[15628]435            var addedJobResourceIds = resourceIds.Except(job.AssignedJobResources.Select(x => x.ResourceId));
[15643]436            var removedJobResourceIds = job.AssignedJobResources
437              .Select(x => x.ResourceId)
438              .Except(resourceIds)
439              .ToArray();
[15628]440           
441            // remove resource assignments
442            foreach(var rid in removedJobResourceIds) {
443              var ajr = job.AssignedJobResources.Where(x => x.ResourceId == rid).SingleOrDefault();
444              if (ajr != null) job.AssignedJobResources.Remove(ajr);
445            }
446
447            // add resource assignments
448            job.AssignedJobResources.AddRange(addedJobResourceIds.Select(
449              x => new DA.AssignedJobResource {
450                ResourceId = x
451              }));
[15530]452          }
453          pm.SubmitChanges();
454        });
455      }
456    }
457
[15630]458    public void UpdateJobState(Guid jobId, DT.JobState jobState) {
[12691]459      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
460      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
[12857]461      var pm = PersistenceManager;
[15630]462      using (new PerformanceLogger("UpdateJobState")) {
[12691]463        var jobDao = pm.JobDao;
464        pm.UseTransaction(() => {
[15630]465          var job = jobDao.GetById(jobId);
466          if(job != null) {
467            var jobStateEntity = jobState.ToEntity();
468            // note: allow solely state changes from "Online" to "StatisticsPending"
469            // and from "StatisticsPending" to "DeletionPending"
470            if (job.State == DA.JobState.Online && jobStateEntity == DA.JobState.StatisticsPending) {
471              job.State = jobStateEntity;
472              foreach(var task in job.Tasks
473              .Where(x => x.State == DA.TaskState.Waiting
474                || x.State == DA.TaskState.Paused
475                || x.State == DA.TaskState.Offline)) {
476                task.State = DA.TaskState.Aborted;
477              }
478              pm.SubmitChanges();
479            } else if(job.State == DA.JobState.StatisticsPending && jobStateEntity == DA.JobState.DeletionPending) {
480              job.State = jobStateEntity;
481              pm.SubmitChanges();
482            }
483          }
[12691]484        });
485      }
[12584]486    }
[15628]487
488    public IEnumerable<DT.AssignedJobResource> GetAssignedResourcesForJob(Guid jobId) {
489      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
490      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
491      var pm = PersistenceManager;
492      var assignedJobResourceDao = pm.AssignedJobResourceDao;
493      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
494        return pm.UseTransaction(() =>
495          assignedJobResourceDao.GetByJobId(jobId)
496          .Select(x => x.ToDto())
497          .ToList()
498        );
499      }
500    }
[12691]501    #endregion
[12584]502
[12691]503    #region JobPermission Methods
504    public void GrantPermission(Guid jobId, Guid grantedUserId, DT.Permission permission) {
505      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
506      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
[12857]507      var pm = PersistenceManager;
[12691]508      using (new PerformanceLogger("GrantPermission")) {
509        var jobPermissionDao = pm.JobPermissionDao;
510        var currentUserId = UserManager.CurrentUserId;
511        pm.UseTransaction(() => {
512          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, permission.ToEntity());
513          pm.SubmitChanges();
514        });
515      }
[12584]516    }
517
[12691]518    public void RevokePermission(Guid jobId, Guid grantedUserId) {
519      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
520      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
[12857]521      var pm = PersistenceManager;
[12691]522      using (new PerformanceLogger("RevokePermission")) {
523        var jobPermissionDao = pm.JobPermissionDao;
524        var currentUserId = UserManager.CurrentUserId;
525        pm.UseTransaction(() => {
526          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, DA.Permission.NotAllowed);
527          pm.SubmitChanges();
528        });
529      }
[12584]530    }
531
532    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
[12691]533      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
534      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
[12857]535      var pm = PersistenceManager;
[12691]536      using (new PerformanceLogger("GetJobPermissions")) {
537        var jobPermissionDao = pm.JobPermissionDao;
538        return pm.UseTransaction(() => jobPermissionDao.GetByJobId(jobId)
539          .Select(x => x.ToDto())
540          .ToList()
541        );
542      }
[12584]543    }
544
[12926]545    // BackwardsCompatibility3.3
546    #region Backwards compatible code, remove with 3.4
[12584]547    public bool IsAllowedPrivileged() {
[12926]548      return true;
[12584]549    }
[12691]550    #endregion
[12926]551    #endregion
[12584]552
[12691]553    #region Login Methods
554    public void Hello(DT.Slave slaveInfo) {
555      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
556      if (UserManager.CurrentUser.UserName != "hiveslave") {
557        slaveInfo.OwnerUserId = UserManager.CurrentUserId;
558      }
[12857]559      var pm = PersistenceManager;
[12691]560      using (new PerformanceLogger("Hello")) {
561        var slaveDao = pm.SlaveDao;
562        pm.UseTransaction(() => {
563          var slave = slaveDao.GetById(slaveInfo.Id);
564          if (slave == null) {
565            slaveDao.Save(slaveInfo.ToEntity());
566          } else {
567            bool oldIsAllowedToCalculate = slave.IsAllowedToCalculate;
568            Guid? oldParentResourceId = slave.ParentResourceId;
569            slaveInfo.CopyToEntity(slave);
570            slave.IsAllowedToCalculate = oldIsAllowedToCalculate;
571            slave.ParentResourceId = oldParentResourceId;
572            slave.LastHeartbeat = DateTime.Now;
573            slave.SlaveState = DA.SlaveState.Idle;
574          }
575          pm.SubmitChanges();
576        });
577      }
[12584]578    }
579
580    public void GoodBye(Guid slaveId) {
[12691]581      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
[12857]582      var pm = PersistenceManager;
[12691]583      using (new PerformanceLogger("GoodBye")) {
584        var slaveDao = pm.SlaveDao;
585        pm.UseTransaction(() => {
586          var slave = slaveDao.GetById(slaveId);
587          if (slave != null) {
588            slave.SlaveState = DA.SlaveState.Offline;
589            pm.SubmitChanges();
590          }
591        });
592      }
[12584]593    }
[12691]594    #endregion
[12584]595
[12691]596    #region Heartbeat Methods
[12776]597    public List<MessageContainer> Heartbeat(DT.Heartbeat heartbeat) {
[12691]598      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
599      List<MessageContainer> result = new List<MessageContainer>();
600      try {
601        using (new PerformanceLogger("ProcessHeartbeat")) {
602          result = HeartbeatManager.ProcessHeartbeat(heartbeat);
603        }
[15379]604      } catch (Exception ex) {
[12691]605        DA.LogFactory.GetLogger(this.GetType().Namespace).Log(string.Format("Exception processing Heartbeat: {0}", ex));
606      }
607      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
608        TriggerEventManager(false);
609      }
610      return result;
[12584]611    }
[12691]612    #endregion
[12584]613
[12691]614    #region Plugin Methods
[12776]615    public DT.Plugin GetPlugin(Guid pluginId) {
[12691]616      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
[12857]617      var pm = PersistenceManager;
[12691]618      using (new PerformanceLogger("GetPlugin")) {
619        var pluginDao = pm.PluginDao;
620        return pm.UseTransaction(() => pluginDao.GetById(pluginId).ToDto());
621      }
[12584]622    }
623
[12776]624    public Guid AddPlugin(DT.Plugin plugin, List<DT.PluginData> pluginData) {
[12691]625      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12857]626      var pm = PersistenceManager;
[12691]627      using (new PerformanceLogger("AddPlugin")) {
628        var pluginDao = pm.PluginDao;
629        plugin.UserId = UserManager.CurrentUserId;
630        plugin.DateCreated = DateTime.Now;
631        return pm.UseTransaction(() => {
632          var pluginEntity = pluginDao.GetByHash(plugin.Hash).SingleOrDefault();
633          if (pluginEntity != null) {
634            throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(pluginEntity.PluginId));
635          }
636          pluginEntity = plugin.ToEntity();
637          foreach (var data in pluginData) {
[12776]638            data.PluginId = default(Guid); // real id will be assigned from linq2sql
[12691]639            pluginEntity.PluginData.Add(data.ToEntity());
640          }
641          pluginDao.Save(pluginEntity);
642          pm.SubmitChanges();
643          return pluginEntity.PluginId;
644        });
645      }
[12584]646    }
647
[12776]648    public IEnumerable<DT.Plugin> GetPlugins() {
[12691]649      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
[12857]650      var pm = PersistenceManager;
[12691]651      using (new PerformanceLogger("GetPlugins")) {
652        var pluginDao = pm.PluginDao;
653        return pm.UseTransaction(() => pluginDao.GetAll()
654          .Where(x => x.Hash != null)
655          .Select(x => x.ToDto())
656          .ToList()
657        );
658      }
[12584]659    }
660
[12776]661    public IEnumerable<DT.PluginData> GetPluginDatas(List<Guid> pluginIds) {
[12691]662      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
[12857]663      var pm = PersistenceManager;
[12691]664      using (new PerformanceLogger("GetPluginDatas")) {
665        var pluginDataDao = pm.PluginDataDao;
666        return pm.UseTransaction(() => pluginDataDao.GetAll()
667            .Where(x => pluginIds.Contains(x.PluginId))
668            .Select(x => x.ToDto())
669            .ToList()
670        );
671      }
[12584]672    }
[12691]673    #endregion
[12584]674
[15379]675    #region Project Methods
676    public Guid AddProject(DT.Project projectDto) {
[15715]677      if (projectDto == null) return Guid.Empty;
678      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
679      // check if current (non-admin) user is owner of one of projectDto's-parents
680      if (!RoleVerifier.IsInRole(HiveRoles.Administrator)) {
681        if(projectDto.ParentProjectId.HasValue) {
682          AuthorizationManager.AuthorizeForProjectAdministration(projectDto.ParentProjectId.Value);
683        } else {
684          throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
685        }
686      }
687     
[15379]688      var pm = PersistenceManager;
689      using (new PerformanceLogger("AddProject")) {
690        var projectDao = pm.ProjectDao;
691        return pm.UseTransaction(() => {
692          var project = projectDao.Save(projectDto.ToEntity());
693          pm.SubmitChanges();
694          return project.ProjectId;
695        });
696      }
697    }
698
699    public void UpdateProject(DT.Project projectDto) {
[15715]700      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
701      // check if current (non-admin) user is owner of the project or the projectDto's-parents
702      if (!RoleVerifier.IsInRole(HiveRoles.Administrator)) {
703        AuthorizationManager.AuthorizeForProjectAdministration(projectDto.Id);
704      }
705
[15379]706      var pm = PersistenceManager;
707      using (new PerformanceLogger("UpdateProject")) {
708        var projectDao = pm.ProjectDao;
709        pm.UseTransaction(() => {
710          var project = projectDao.GetById(projectDto.Id);
711          if (project != null) {
712            projectDto.CopyToEntity(project);
713          } else {
714            projectDao.Save(projectDto.ToEntity());
715          }
716          pm.SubmitChanges();
717        });
718      }
719    }
720
721    public void DeleteProject(Guid projectId) {
[15715]722      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
723      // check if current (non-admin) user is owner of the project or the projectDto's-parents
724      if (!RoleVerifier.IsInRole(HiveRoles.Administrator)) {
725        AuthorizationManager.AuthorizeForProjectAdministration(projectId);
726      }
727
[15379]728      var pm = PersistenceManager;
729      using (new PerformanceLogger("DeleteProject")) {
730        var projectDao = pm.ProjectDao;
[15552]731        var assignedJobResourceDao = pm.AssignedJobResourceDao;
[15379]732        pm.UseTransaction(() => {
[15552]733          assignedJobResourceDao.DeleteByProjectId(projectId);
[15379]734          projectDao.Delete(projectId);
735          pm.SubmitChanges();
736        });
737      }
738    }
739
[15715]740    // query granted project for use (i.e. to calculate on)
[15379]741    public DT.Project GetProject(Guid projectId) {
[15628]742      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15379]743      var pm = PersistenceManager;
744      using (new PerformanceLogger("GetProject")) {
745        var projectDao = pm.ProjectDao;
[15715]746        var currentUserId = UserManager.CurrentUserId;
747        var userAndGroupIds = new List<Guid> { currentUserId };
748        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
749        return pm.UseTransaction(() => {
750          return projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
751          .Where(x => x.ProjectId == projectId)
752          .Select(x => x.ToDto())
753          .SingleOrDefault();
754        });
[15379]755      }
756    }
757
[15552]758    // query granted projects for use (i.e. to calculate on)
[15379]759    public IEnumerable<DT.Project> GetProjects() {
[12691]760      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12857]761      var pm = PersistenceManager;
[15379]762      using (new PerformanceLogger("GetProjects")) {
763        var projectDao = pm.ProjectDao;
764        var currentUserId = UserManager.CurrentUserId;
[15577]765        var userAndGroupIds = new List<Guid> { currentUserId };
766        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
[15379]767        return pm.UseTransaction(() => {
[15577]768          return projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
769            .Select(x => x.ToDto()).ToList();
770        });
771      }
772    }
773
774    public IEnumerable<DT.Project> GetProjectsForAdministration() {
775      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
776      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
777      var pm = PersistenceManager;
778      using (new PerformanceLogger("GetProjectsForAdministration")) {
779        var projectDao = pm.ProjectDao;
780       
781        return pm.UseTransaction(() => {
782          if(isAdministrator) {
783            return projectDao.GetAll().Select(x => x.ToDto()).ToList();
784          } else {
785            var currentUserId = UserManager.CurrentUserId;
786            return projectDao.GetAdministrationGrantedProjectsForUser(currentUserId)
787              .Select(x => x.ToDto()).ToList();
788
789          }
[15379]790        });
791      }
792    }
793    #endregion
794
795    #region ProjectPermission Methods
[15577]796    public void SaveProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool reassign, bool cascading, bool reassignCascading) {
[15379]797      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15577]798      if (projectId == null || grantedUserIds == null) return;
[15380]799      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
[15379]800      var pm = PersistenceManager;
[15643]801      using (new PerformanceLogger("SaveProjectPermissions")) {
[15508]802        var projectDao = pm.ProjectDao;
[15577]803        var projectPermissionDao = pm.ProjectPermissionDao;
804        var assignedJobResourceDao = pm.AssignedJobResourceDao;
[15547]805
[12691]806        pm.UseTransaction(() => {
[15508]807          var project = projectDao.GetById(projectId);
[15628]808          if (project == null) return;
[15643]809          var projectPermissions = project.ProjectPermissions.Select(x => x.GrantedUserId).ToArray();
810          //var addedPermissions = grantedUserIds.Except(projectPermissions);
[15577]811          var removedPermissions = projectPermissions.Except(grantedUserIds);
812
813          // remove job assignments and project permissions
814          if (reassign) {
815            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
816            project.ProjectPermissions.Clear();
817          } else {
818            assignedJobResourceDao.DeleteByProjectIdAndUserIds(project.ProjectId, removedPermissions);
[15643]819            foreach(var item in project.ProjectPermissions
820              .Where(x => removedPermissions.Contains(x.GrantedUserId))
821              .ToList()) {
[15577]822              project.ProjectPermissions.Remove(item);
823            }
824          }
825          pm.SubmitChanges();
826
827          // add project permissions
[12691]828          foreach (var id in grantedUserIds) {
[15577]829            if(project.ProjectPermissions.All(x => x.GrantedUserId != id)) {
[15379]830              project.ProjectPermissions.Add(new DA.ProjectPermission {
[12691]831                GrantedUserId = id,
832                GrantedByUserId = UserManager.CurrentUserId
833              });
834            }
835          }
[15577]836          pm.SubmitChanges();
837
[15547]838          if (cascading) {
[15577]839            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
840            var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
841
842            // remove job assignments
843            if (reassignCascading) {
844              assignedJobResourceDao.DeleteByProjectIds(childProjectIds);
845            } else {
846              assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, removedPermissions);
847            }
848
849            foreach(var p in childProjects) {
850              // remove project permissions
851              if(reassignCascading) {
[15580]852                p.ProjectPermissions.Clear();
[15577]853              } else {
[15643]854                foreach(var item in p.ProjectPermissions
855                  .Where(x => removedPermissions.Contains(x.GrantedUserId))
856                  .ToList()) {
[15577]857                  p.ProjectPermissions.Remove(item);
858                }
859              }
860              pm.SubmitChanges();
861
862              // add project permissions
[15530]863              foreach (var id in grantedUserIds) {
[15577]864                if (p.ProjectPermissions.All(x => x.GrantedUserId != id)) {
865                  p.ProjectPermissions.Add(new DA.ProjectPermission {
866                    GrantedUserId = id,
867                    GrantedByUserId = UserManager.CurrentUserId
868                  });
869                }
[15530]870              }
871            }
872          }
[12691]873          pm.SubmitChanges();
874        });
875      }
[12584]876    }
877
[15715]878    private void GrantProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
[15577]879      throw new NotImplementedException();
880    }
881
[15715]882    private void RevokeProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
[12691]883      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15577]884      if (projectId == null || grantedUserIds == null || !grantedUserIds.Any()) return;
[15380]885      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
[12857]886      var pm = PersistenceManager;
[15379]887      using (new PerformanceLogger("RevokeProjectPermissions")) {
888        var projectPermissionDao = pm.ProjectPermissionDao;
[15530]889        var projectDao = pm.ProjectDao;
[15552]890        var assignedJobResourceDao = pm.AssignedJobResourceDao;
[12691]891        pm.UseTransaction(() => {
[15547]892          if (cascading) {
[15577]893            var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
[15530]894            projectPermissionDao.DeleteByProjectIdsAndGrantedUserIds(childProjectIds, grantedUserIds);
[15552]895            assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, grantedUserIds);
[15530]896          }
897          projectPermissionDao.DeleteByProjectIdAndGrantedUserIds(projectId, grantedUserIds);
[15552]898          assignedJobResourceDao.DeleteByProjectIdAndUserIds(projectId, grantedUserIds);
[12972]899          pm.SubmitChanges();
[12691]900        });
901      }
[12584]902    }
903
[15379]904    public IEnumerable<DT.ProjectPermission> GetProjectPermissions(Guid projectId) {
[12691]905      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15552]906      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
[12857]907      var pm = PersistenceManager;
[15379]908      using (new PerformanceLogger("GetProjectPermissions")) {
909        var projectPermissionDao = pm.ProjectPermissionDao;
910        return pm.UseTransaction(() => projectPermissionDao.GetByProjectId(projectId)
[12691]911          .Select(x => x.ToDto())
912          .ToList()
913        );
914      }
[12584]915    }
[12691]916    #endregion
[12584]917
[15411]918    #region AssignedProjectResource Methods
[15577]919    // basic: remove and add assignments (resourceIds) to projectId and its depending jobs
920    // reassign: clear all assignments from project and its depending jobs, before adding new ones (resourceIds)
921    // cascading: "basic" mode for child-projects
922    // reassignCascading: "reassign" mode for child-projects
923    public void SaveProjectResourceAssignments(Guid projectId, List<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
[15411]924      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15577]925      if (projectId == null || resourceIds == null) return;
[15546]926      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
[15411]927      var pm = PersistenceManager;
[15643]928      using (new PerformanceLogger("SaveProjectResourceAssignments")) {
[15508]929        var projectDao = pm.ProjectDao;
[15577]930        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
931        var assignedJobResourceDao = pm.AssignedJobResourceDao;
[15411]932        pm.UseTransaction(() => {
[15508]933          var project = projectDao.GetById(projectId);
[15643]934          var assignedResources = project.AssignedProjectResources.Select(x => x.ResourceId).ToArray();
[15577]935          var removedAssignments = assignedResources.Except(resourceIds);
[15508]936
[15577]937          // remove job and project assignments
938          if (reassign) {
939            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
940            project.AssignedProjectResources.Clear();
941          } else {
942            assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, removedAssignments);
[15643]943            foreach (var item in project.AssignedProjectResources
944              .Where(x => removedAssignments.Contains(x.ResourceId))
945              .ToList()) {
[15577]946              project.AssignedProjectResources.Remove(item);
947            }
948          }
949          pm.SubmitChanges();
950
951          // add project assignments
[15411]952          foreach (var id in resourceIds) {
[15577]953            if (project.AssignedProjectResources.All(x => x.ResourceId != id)) {
[15411]954              project.AssignedProjectResources.Add(new DA.AssignedProjectResource {
955                ResourceId = id
956              });
957            }
958          }
[15577]959          pm.SubmitChanges();
960
[15547]961          if (cascading) {
[15577]962            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
963
964            // remove job assignments
965            if (reassignCascading) {
966              assignedJobResourceDao.DeleteByProjectIds(childProjects.Select(x => x.ProjectId).ToList());
967            } else {
968              var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
969              assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, removedAssignments);
970            }
[15547]971            foreach (var p in childProjects) {
[15577]972              // remove project assignments
973              if (reassignCascading) {
974                p.AssignedProjectResources.Clear();
975              } else {
[15643]976                foreach (var item in p.AssignedProjectResources
977                  .Where(x => removedAssignments.Contains(x.ResourceId))
978                  .ToList()) {
[15577]979                  p.AssignedProjectResources.Remove(item);
980                }
981              }
982              pm.SubmitChanges();
983
984              // add project assignments
[15547]985              foreach (var id in resourceIds) {
[15577]986                if(p.AssignedProjectResources.All(x => x.ResourceId != id)) {
987                  p.AssignedProjectResources.Add(new DA.AssignedProjectResource {
988                    ResourceId = id
989                  });
990                }
[15546]991              }
992            }
993          }
[15411]994          pm.SubmitChanges();
995        });
996      }
997    }
998
[15715]999    private void AssignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
[15577]1000      throw new NotImplementedException();
1001    }
1002
1003    // basic: unassign resourceIds from project and depending jobs
1004    // cascading: unassign resourceIds from all child-projects and their depending jobs
[15715]1005    private void UnassignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
[15411]1006      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15577]1007      if (projectId == null || resourceIds == null || !resourceIds.Any()) return;
[15546]1008      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
[15411]1009      var pm = PersistenceManager;
1010      using (new PerformanceLogger("UnassignProjectResources")) {
1011        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
[15552]1012        var assignedJobResourceDao = pm.AssignedJobResourceDao;
[15546]1013        var projectDao = pm.ProjectDao;
[15411]1014        pm.UseTransaction(() => {
[15547]1015          if (cascading) {
[15577]1016            var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
[15546]1017            assignedProjectResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
[15552]1018            assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
[15546]1019          }
1020          assignedProjectResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
[15552]1021          assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
[15411]1022          pm.SubmitChanges();
1023        });
1024      }
1025    }
1026
[15552]1027    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProject(Guid projectId) {
[15411]1028      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15628]1029      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, projectId);
[15411]1030      var pm = PersistenceManager;
1031      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1032        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1033        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1034          .Select(x => x.ToDto())
1035          .ToList()
1036        );
1037      }
1038    }
[15552]1039
[15628]1040    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProjectAdministration(Guid projectId) {
1041      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1042      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
1043      var pm = PersistenceManager;
1044      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1045        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1046        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1047          .Select(x => x.ToDto())
1048          .ToList()
1049        );
1050      }
1051    }
1052
[15411]1053    #endregion
1054
[12691]1055    #region Slave Methods
1056    public Guid AddSlave(DT.Slave slaveDto) {
1057      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
[12857]1058      var pm = PersistenceManager;
[12691]1059      using (new PerformanceLogger("AddSlave")) {
1060        var slaveDao = pm.SlaveDao;
1061        return pm.UseTransaction(() => {
1062          var slave = slaveDao.Save(slaveDto.ToEntity());
1063          pm.SubmitChanges();
1064          return slave.ResourceId;
1065        });
1066      }
[12584]1067    }
1068
[12691]1069    public Guid AddSlaveGroup(DT.SlaveGroup slaveGroupDto) {
[15715]1070      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
[12857]1071      var pm = PersistenceManager;
[12691]1072      using (new PerformanceLogger("AddSlaveGroup")) {
1073        var slaveGroupDao = pm.SlaveGroupDao;
1074        return pm.UseTransaction(() => {
1075          if (slaveGroupDto.Id == Guid.Empty) {
1076            slaveGroupDto.Id = Guid.NewGuid();
1077          }
1078          var slaveGroup = slaveGroupDao.Save(slaveGroupDto.ToEntity());
1079          pm.SubmitChanges();
1080          return slaveGroup.ResourceId;
1081        });
1082      }
[12584]1083    }
1084
[12776]1085    public DT.Slave GetSlave(Guid slaveId) {
[12691]1086      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
[12857]1087      var pm = PersistenceManager;
[12691]1088      using (new PerformanceLogger("GetSlave")) {
1089        var slaveDao = pm.SlaveDao;
1090        return pm.UseTransaction(() => slaveDao.GetById(slaveId).ToDto());
1091      }
[12584]1092    }
1093
[15715]1094    // query granted slaves for use (i.e. to calculate on)
[12776]1095    public IEnumerable<DT.Slave> GetSlaves() {
[12691]1096      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12857]1097      var pm = PersistenceManager;
[12691]1098      using (new PerformanceLogger("GetSlaves")) {
1099        var slaveDao = pm.SlaveDao;
[15658]1100        var projectDao = pm.ProjectDao;
1101        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1102
1103        // collect user information
[12691]1104        var currentUserId = UserManager.CurrentUserId;
[15658]1105        var userAndGroupIds = new List<Guid> { currentUserId };
1106        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
1107
[12691]1108        return pm.UseTransaction(() => {
[15658]1109          var slaves = slaveDao.GetAll()
1110            .Select(x => x.ToDto())
1111            .ToList();
1112          var grantedProjectIds = projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
1113            .Select(x => x.ProjectId)
1114            .ToList();
1115          var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourcesByProjectIds(grantedProjectIds)
1116            .Select(x => x.ResourceId)
1117            .ToList();
1118
1119          return slaves
1120            .Where(x => grantedResourceIds.Contains(x.Id))
1121            .ToList();
[12691]1122        });
1123      }
[12584]1124    }
1125
[15715]1126    // query granted slave groups for use (i.e. to calculate on)
[12776]1127    public IEnumerable<DT.SlaveGroup> GetSlaveGroups() {
[12691]1128      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12857]1129      var pm = PersistenceManager;
[12691]1130      using (new PerformanceLogger("GetSlaveGroups")) {
1131        var slaveGroupDao = pm.SlaveGroupDao;
[15658]1132        var projectDao = pm.ProjectDao;
1133        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1134
1135        // collect user information
[12691]1136        var currentUserId = UserManager.CurrentUserId;
[15658]1137        var userAndGroupIds = new List<Guid> { currentUserId };
1138        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
1139
[12691]1140        return pm.UseTransaction(() => {
[15658]1141          var slaveGroups = slaveGroupDao.GetAll()
[12691]1142            .Select(x => x.ToDto())
1143            .ToList();
[15658]1144          var grantedProjectIds = projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
1145            .Select(x => x.ProjectId)
1146            .ToList();
1147          var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourcesByProjectIds(grantedProjectIds)
1148            .Select(x => x.ResourceId)
1149            .ToList();
1150
1151          return slaveGroups
1152            .Where(x => grantedResourceIds.Contains(x.Id))
1153            .ToList();
[12691]1154        });
1155      }
[12584]1156    }
1157
[15715]1158    // query granted slaves for resource administration
[15658]1159    public IEnumerable<DT.Slave> GetSlavesForAdministration() {
1160      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1161      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1162      var pm = PersistenceManager;
1163      using (new PerformanceLogger("GetSlavesForAdministration")) {
1164        var slaveDao = pm.SlaveDao;
1165        var currentUserId = UserManager.CurrentUserId;
1166
1167        if (isAdministrator) {
1168          return pm.UseTransaction(() => {
1169            return slaveDao.GetAll()
1170              .Select(x => x.ToDto())
1171              .ToList();
1172          });
1173        } else {
1174          var slaves = slaveDao.GetAll()
1175            .Select(x => x.ToDto())
1176            .ToList();
1177          var projectDao = pm.ProjectDao;
1178          var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1179          var projects = projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).ToList();
1180          var resourceIds = assignedProjectResourceDao
1181            .GetAllGrantedResourcesByProjectIds(projects.Select(x => x.ProjectId).ToList())
1182            .Select(x => x.ResourceId)
1183            .ToList();
1184
1185          return slaves
1186            .Where(x => resourceIds.Contains(x.Id))
1187            .ToList();
1188        }
1189      }
1190    }
1191
[15715]1192    // query granted slave groups for resource administration
[15658]1193    public IEnumerable<DT.SlaveGroup> GetSlaveGroupsForAdministration() {
1194      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1195      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1196      var pm = PersistenceManager;
1197      using (new PerformanceLogger("GetSlaveGroupsForAdministration")) {
1198        var slaveGroupDao = pm.SlaveGroupDao;
1199        var currentUserId = UserManager.CurrentUserId;
1200
1201        if (isAdministrator) {
1202          return pm.UseTransaction(() => {
1203            return slaveGroupDao.GetAll()
1204              .Select(x => x.ToDto())
1205              .ToList();
1206          });
1207        } else {
1208          var slaveGroups = slaveGroupDao.GetAll()
1209            .Select(x => x.ToDto())
1210            .ToList();
1211          var projectDao = pm.ProjectDao;
1212          var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1213          var projects = projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).ToList();
1214          var resourceIds = assignedProjectResourceDao
1215            .GetAllGrantedResourcesByProjectIds(projects.Select(x => x.ProjectId).ToList())
1216            .Select(x => x.ResourceId)
1217            .ToList();
1218
1219          return slaveGroups
1220            .Where(x => resourceIds.Contains(x.Id))
1221            .ToList();
1222        }
1223      }
1224    }
1225
[12691]1226    public void UpdateSlave(DT.Slave slaveDto) {
1227      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15715]1228      if (slaveDto == null) return;
[15658]1229      AuthorizationManager.AuthorizeForResourceAdministration(slaveDto.Id);
[12857]1230      var pm = PersistenceManager;
[12691]1231      using (new PerformanceLogger("UpdateSlave")) {
1232        var slaveDao = pm.SlaveDao;
1233        pm.UseTransaction(() => {
1234          var slave = slaveDao.GetById(slaveDto.Id);
1235          if (slave != null) {
1236            slaveDto.CopyToEntity(slave);
1237          } else {
1238            slaveDao.Save(slaveDto.ToEntity());
1239          }
1240          pm.SubmitChanges();
1241        });
1242      }
[12584]1243    }
1244
[12691]1245    public void UpdateSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1246      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[15715]1247      if (slaveGroupDto == null) return;
[15658]1248      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupDto.Id);
[12857]1249      var pm = PersistenceManager;
[12691]1250      using (new PerformanceLogger("UpdateSlaveGroup")) {
1251        var slaveGroupDao = pm.SlaveGroupDao;
1252        pm.UseTransaction(() => {
1253          var slaveGroup = slaveGroupDao.GetById(slaveGroupDto.Id);
1254          if (slaveGroup != null) {
1255            slaveGroupDto.CopyToEntity(slaveGroup);
1256          } else {
1257            slaveGroupDao.Save(slaveGroupDto.ToEntity());
1258          }
1259          pm.SubmitChanges();
1260        });
1261      }
[12584]1262    }
1263
1264    public void DeleteSlave(Guid slaveId) {
[12691]1265      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1266      AuthorizationManager.AuthorizeForResourceAdministration(slaveId);
[12857]1267      var pm = PersistenceManager;
[12691]1268      using (new PerformanceLogger("DeleteSlave")) {
1269        var slaveDao = pm.SlaveDao;
1270        pm.UseTransaction(() => {
1271          slaveDao.Delete(slaveId);
[12972]1272          pm.SubmitChanges();
[12691]1273        });
1274      }
[12584]1275    }
1276
1277    public void DeleteSlaveGroup(Guid slaveGroupId) {
[12691]1278      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1279      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupId);
[12857]1280      var pm = PersistenceManager;
[12691]1281      using (new PerformanceLogger("DeleteSlaveGroup")) {
1282        var slaveGroupDao = pm.SlaveGroupDao;
1283        pm.UseTransaction(() => {
1284          slaveGroupDao.Delete(slaveGroupId);
[12972]1285          pm.SubmitChanges();
[12691]1286        });
1287      }
[12584]1288    }
1289
1290    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
[12691]1291      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
[12857]1292      var pm = PersistenceManager;
[12691]1293      using (new PerformanceLogger("AddResourceToGroup")) {
1294        var resourceDao = pm.ResourceDao;
1295        pm.UseTransaction(() => {
1296          var resource = resourceDao.GetById(resourceId);
1297          resource.ParentResourceId = slaveGroupId;
1298          pm.SubmitChanges();
1299        });
1300      }
[12584]1301    }
1302
1303    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
[12691]1304      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
[12857]1305      var pm = PersistenceManager;
[12691]1306      using (new PerformanceLogger("RemoveResourceFromGroup")) {
1307        var resourceDao = pm.ResourceDao;
1308        pm.UseTransaction(() => {
1309          var resource = resourceDao.GetById(resourceId);
1310          resource.ParentResourceId = null;
1311          pm.SubmitChanges();
1312        });
1313      }
[12584]1314    }
1315
1316    public Guid GetResourceId(string resourceName) {
[12691]1317      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12857]1318      var pm = PersistenceManager;
[12691]1319      using (new PerformanceLogger("GetResourceId")) {
1320        var resourceDao = pm.ResourceDao;
1321        return pm.UseTransaction(() => {
1322          var resource = resourceDao.GetByName(resourceName);
1323          return resource != null ? resource.ResourceId : Guid.Empty;
1324        });
1325      }
[12584]1326    }
1327
1328    public void TriggerEventManager(bool force) {
[12857]1329      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
[12691]1330      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
1331      bool cleanup;
[12857]1332      var pm = PersistenceManager;
[12691]1333      using (new PerformanceLogger("TriggerEventManager")) {
1334        cleanup = false;
1335        var lifecycleDao = pm.LifecycleDao;
1336        pm.UseTransaction(() => {
1337          var lastLifecycle = lifecycleDao.GetLastLifecycle();
1338          DateTime lastCleanup = lastLifecycle != null ? lastLifecycle.LastCleanup : DateTime.MinValue;
1339          if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
1340            lifecycleDao.UpdateLifecycle();
1341            cleanup = true;
1342            pm.SubmitChanges();
1343          }
1344        }, true);
1345      }
1346      if (cleanup) {
1347        EventManager.Cleanup();
1348      }
[12584]1349    }
1350
1351    public int GetNewHeartbeatInterval(Guid slaveId) {
[12691]1352      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
[12857]1353      var pm = PersistenceManager;
[12691]1354      using (new PerformanceLogger("GetNewHeartbeatInterval")) {
1355        var slaveDao = pm.SlaveDao;
1356        return pm.UseTransaction(() => {
1357          var slave = slaveDao.GetById(slaveId);
1358          if (slave != null) {
1359            return slave.HbInterval;
1360          }
1361          return -1;
1362        });
1363      }
[12584]1364    }
[12691]1365    #endregion
[12584]1366
[12691]1367    #region Downtime Methods
1368    public Guid AddDowntime(DT.Downtime downtimeDto) {
1369      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1370      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
[12857]1371      var pm = PersistenceManager;
[12691]1372      using (new PerformanceLogger("AddDowntime")) {
1373        var downtimeDao = pm.DowntimeDao;
1374        return pm.UseTransaction(() => {
1375          var downtime = downtimeDao.Save(downtimeDto.ToEntity());
1376          pm.SubmitChanges();
1377          return downtime.ResourceId;
1378        });
1379      }
[12584]1380    }
1381
1382    public void DeleteDowntime(Guid downtimeId) {
[12691]1383      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12857]1384      var pm = PersistenceManager;
[12691]1385      using (new PerformanceLogger("DeleteDowntime")) {
1386        var downtimeDao = pm.DowntimeDao;
1387        pm.UseTransaction(() => {
1388          downtimeDao.Delete(downtimeId);
1389          pm.SubmitChanges();
1390        });
1391      }
[12584]1392    }
1393
[12691]1394    public void UpdateDowntime(DT.Downtime downtimeDto) {
1395      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1396      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
[12857]1397      var pm = PersistenceManager;
[12691]1398      using (new PerformanceLogger("UpdateDowntime")) {
1399        var downtimeDao = pm.DowntimeDao;
1400        pm.UseTransaction(() => {
1401          var downtime = downtimeDao.GetById(downtimeDto.Id);
1402          if (downtime != null) {
1403            downtimeDto.CopyToEntity(downtime);
1404          } else {
1405            downtimeDao.Save(downtimeDto.ToEntity());
1406          }
1407          pm.SubmitChanges();
1408        });
1409      }
[12584]1410    }
1411
[12776]1412    public IEnumerable<DT.Downtime> GetDowntimesForResource(Guid resourceId) {
[12691]1413      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[12857]1414      var pm = PersistenceManager;
[12691]1415      using (new PerformanceLogger("GetDowntimesForResource")) {
1416        var downtimeDao = pm.DowntimeDao;
1417        return pm.UseTransaction(() => downtimeDao.GetByResourceId(resourceId)
1418          .Select(x => x.ToDto())
1419          .ToList()
1420        );
1421      }
[12584]1422    }
[12691]1423    #endregion
[12584]1424
[12691]1425    #region User Methods
[12584]1426    public string GetUsernameByUserId(Guid userId) {
[12691]1427      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1428      var user = UserManager.GetUserById(userId);
1429      return user != null ? user.UserName : null;
[12584]1430    }
1431
1432    public Guid GetUserIdByUsername(string username) {
[12691]1433      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1434      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
1435      return user != null ? (Guid?)user.ProviderUserKey ?? Guid.Empty : Guid.Empty;
[12584]1436    }
[15577]1437   
1438    public Dictionary<Guid, HashSet<Guid>> GetUserGroupTree() {
1439      var userGroupTree = new Dictionary<Guid, HashSet<Guid>>();
1440      var userGroupMapping = UserManager.GetUserGroupMapping();
1441
1442      foreach(var ugm in userGroupMapping) {
1443        if (ugm.Parent == null || ugm.Child == null) continue;
1444
1445        if (!userGroupTree.ContainsKey(ugm.Parent)) {
1446          userGroupTree.Add(ugm.Parent, new HashSet<Guid>());
1447        }
1448        userGroupTree[ugm.Parent].Add(ugm.Child);
1449      }
1450
1451      return userGroupTree;
1452    }
[15658]1453
1454    public bool CheckAccessToAdminAreaGranted() {
1455      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1456      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1457      var pm = PersistenceManager;
1458      using(new PerformanceLogger("CheckAccessToAdminAreaGranted")) {
1459        if (isAdministrator) {
1460          return true;
1461        } else {
1462          var projectDao = pm.ProjectDao;
1463          var currentUserId = UserManager.CurrentUserId;
1464          return projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).Any();
1465        }
1466      }
1467    }
[12691]1468    #endregion
[12584]1469
[12691]1470    #region UserPriorities Methods
[12776]1471    public IEnumerable<DT.UserPriority> GetUserPriorities() {
[12857]1472      var pm = PersistenceManager;
[12691]1473      using (new PerformanceLogger("GetUserPriorities")) {
1474        var userPriorityDao = pm.UserPriorityDao;
1475        return pm.UseTransaction(() => userPriorityDao.GetAll()
1476          .Select(x => x.ToDto())
1477          .ToList()
1478        );
1479      }
[12584]1480    }
[12691]1481    #endregion
[12584]1482
[12691]1483    #region Private Helper Methods
1484    private void UpdateTaskState(IPersistenceManager pm, DA.Task task, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
1485      var stateLogDao = pm.StateLogDao;
1486      var taskStateEntity = taskState.ToEntity();
[14901]1487
[15358]1488      if (task.State == DA.TaskState.Transferring && taskStateEntity == DA.TaskState.Paused && task.Command == null) {
[12857]1489        // slave paused and uploaded the task (no user-command) -> set waiting.
[12691]1490        taskStateEntity = DA.TaskState.Waiting;
1491      }
[14901]1492
[12691]1493      stateLogDao.Save(new DA.StateLog {
1494        State = taskStateEntity,
1495        DateTime = DateTime.Now,
1496        TaskId = task.TaskId,
1497        UserId = userId,
1498        SlaveId = slaveId,
1499        Exception = exception
1500      });
[14901]1501
[12691]1502      task.State = taskStateEntity;
[14901]1503
1504      if (task.Command == DA.Command.Pause && task.State == DA.TaskState.Paused
1505          || task.Command == DA.Command.Abort && task.State == DA.TaskState.Aborted
1506          || task.Command == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
1507        task.Command = null;
1508      }
[12691]1509    }
[15547]1510
[12691]1511    #endregion
[12584]1512  }
1513}
Note: See TracBrowser for help on using the repository browser.