source: branches/2839_HiveProjectManagement/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 15913

Last change on this file since 15913 was 15913, checked in by jzenisek, 4 years ago

#2839: updated genealogy computation for hive job administrator

File size: 64.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Security;
26using System.ServiceModel;
27using HeuristicLab.Services.Access;
28using HeuristicLab.Services.Hive.DataAccess.Interfaces;
29using HeuristicLab.Services.Hive.DataTransfer;
30using HeuristicLab.Services.Hive.Manager;
31using HeuristicLab.Services.Hive.ServiceContracts;
32using DA = HeuristicLab.Services.Hive.DataAccess;
33using DT = HeuristicLab.Services.Hive.DataTransfer;
34
35namespace HeuristicLab.Services.Hive {
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]
42  public class HiveService : IHiveService {
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";
45
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    }
63    private IEventManager EventManager {
64      get { return ServiceLocator.Instance.EventManager; }
65    }
66    private HeartbeatManager HeartbeatManager {
67      get { return ServiceLocator.Instance.HeartbeatManager; }
68    }
69
70    #region Task Methods
71
72    public Guid AddTask(DT.Task task, DT.TaskData taskData) {
73      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
74      AuthorizationManager.AuthorizeForJob(task.JobId, DT.Permission.Full);
75      var pm = PersistenceManager;
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);
97      }
98    }
99
100    public Guid AddChildTask(Guid parentTaskId, DT.Task task, DT.TaskData taskData) {
101      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
102      task.ParentTaskId = parentTaskId;
103      return AddTask(task, taskData);
104    }
105
106    public DT.Task GetTask(Guid taskId) {
107      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
108      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
109      var pm = PersistenceManager;
110      using (new PerformanceLogger("GetTask")) {
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);
122      var pm = PersistenceManager;
123      using (new PerformanceLogger("GetLightweightJobTasks")) {
124        var taskDao = pm.TaskDao;
125        return pm.UseTransaction(() => {
126          return taskDao.GetByJobId(jobId)
127            .ToList()
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
138            })
139            .ToList();
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);
147      var pm = PersistenceManager;
148      using (new PerformanceLogger("GetLightweightJobTasksWithoutStateLog")) {
149        var taskDao = pm.TaskDao;
150        return pm.UseTransaction(() => {
151          return taskDao.GetByJobId(jobId)
152            .ToList()
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
161            })
162            .ToList();
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);
170      var pm = PersistenceManager;
171      using (new PerformanceLogger("GetTaskData")) {
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);
180      var pm = PersistenceManager;
181      using (new PerformanceLogger("UpdateTask")) {
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);
194      var pm = PersistenceManager;
195      using (new PerformanceLogger("UpdateTaskData")) {
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);
212      var pm = PersistenceManager;
213      using (new PerformanceLogger("UpdateTaskState")) {
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    }
223    #endregion
224
225    #region Task Control Methods
226    public void StopTask(Guid taskId) {
227      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
228      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
229      var pm = PersistenceManager;
230      using (new PerformanceLogger("StopTask")) {
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);
249      var pm = PersistenceManager;
250      using (new PerformanceLogger("PauseTask")) {
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;
256          } else if (task.State != DA.TaskState.Paused
257                     && task.State != DA.TaskState.Aborted
258                     && task.State != DA.TaskState.Finished
259                     && task.State != DA.TaskState.Failed) {
260            UpdateTaskState(pm, task, DT.TaskState.Paused, null, null, string.Empty);
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);
270      var pm = PersistenceManager;
271      using (new PerformanceLogger("RestartTask")) {
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    }
281    #endregion
282
283    #region Job Methods
284    public DT.Job GetJob(Guid id) {
285      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
286      AuthorizationManager.AuthorizeForJob(id, DT.Permission.Read);
287      var pm = PersistenceManager;
288      using (new PerformanceLogger("GetJob")) {
289        var jobDao = pm.JobDao;
290        var jobPermissionDao = pm.JobPermissionDao;
291        var taskDao = pm.TaskDao;
292        var currentUserId = UserManager.CurrentUserId;
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            }
308            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
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            }
315          }
316          return job;
317        });
318      }
319    }
320
321    public IEnumerable<DT.Job> GetJobs() {
322      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
323      var pm = PersistenceManager;
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()
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                          )
336            .Select(x => x.ToDto())
337            .ToList();
338          var statistics = taskDao.GetAll()
339              .Where(x => jobs.Select(y => y.Id).Contains(x.JobId))
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            }
355            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
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      }
366    }
367
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
385          if (resourceIds != null && resourceIds.Any()) {           
386            newJob.AssignedJobResources.AddRange(resourceIds.Select(
387              x => new DA.AssignedJobResource {
388                ResourceId = x
389              }));
390          }
391
392          var job = jobDao.Save(newJob);
393          if (userPriorityDao.GetById(newJob.OwnerUserId) == null) {
394            userPriorityDao.Save(new DA.UserPriority {
395              UserId = newJob.OwnerUserId,
396              DateEnqueued = newJob.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) {
426            // add resource assignments
427            if (resourceIds != null && resourceIds.Any()) {
428              job.AssignedJobResources.AddRange(resourceIds.Select(
429                x => new DA.AssignedJobResource {
430                  ResourceId = x
431              }));
432            }
433            jobDao.Save(job);
434          } else if(resourceIds != null) {
435            var addedJobResourceIds = resourceIds.Except(job.AssignedJobResources.Select(x => x.ResourceId));
436            var removedJobResourceIds = job.AssignedJobResources
437              .Select(x => x.ResourceId)
438              .Except(resourceIds)
439              .ToArray();
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              }));
452          }
453          pm.SubmitChanges();
454        });
455      }
456    }
457
458    public void UpdateJobState(Guid jobId, DT.JobState jobState) {
459      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
460      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
461      var pm = PersistenceManager;
462      using (new PerformanceLogger("UpdateJobState")) {
463        var jobDao = pm.JobDao;
464        pm.UseTransaction(() => {
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          }
484        });
485      }
486    }
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    }
501    #endregion
502
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);
507      var pm = PersistenceManager;
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      }
516    }
517
518    public void RevokePermission(Guid jobId, Guid grantedUserId) {
519      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
520      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
521      var pm = PersistenceManager;
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      }
530    }
531
532    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
533      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
534      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
535      var pm = PersistenceManager;
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      }
543    }
544
545    // BackwardsCompatibility3.3
546    #region Backwards compatible code, remove with 3.4
547    public bool IsAllowedPrivileged() {
548      return true;
549    }
550    #endregion
551    #endregion
552
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      }
559      var pm = PersistenceManager;
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      }
578    }
579
580    public void GoodBye(Guid slaveId) {
581      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
582      var pm = PersistenceManager;
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      }
593    }
594    #endregion
595
596    #region Heartbeat Methods
597    public List<MessageContainer> Heartbeat(DT.Heartbeat heartbeat) {
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        }
604      } catch (Exception ex) {
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;
611    }
612    #endregion
613
614    #region Plugin Methods
615    public DT.Plugin GetPlugin(Guid pluginId) {
616      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
617      var pm = PersistenceManager;
618      using (new PerformanceLogger("GetPlugin")) {
619        var pluginDao = pm.PluginDao;
620        return pm.UseTransaction(() => pluginDao.GetById(pluginId).ToDto());
621      }
622    }
623
624    public Guid AddPlugin(DT.Plugin plugin, List<DT.PluginData> pluginData) {
625      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
626      var pm = PersistenceManager;
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) {
638            data.PluginId = default(Guid); // real id will be assigned from linq2sql
639            pluginEntity.PluginData.Add(data.ToEntity());
640          }
641          pluginDao.Save(pluginEntity);
642          pm.SubmitChanges();
643          return pluginEntity.PluginId;
644        });
645      }
646    }
647
648    public IEnumerable<DT.Plugin> GetPlugins() {
649      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
650      var pm = PersistenceManager;
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      }
659    }
660
661    public IEnumerable<DT.PluginData> GetPluginDatas(List<Guid> pluginIds) {
662      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
663      var pm = PersistenceManager;
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      }
672    }
673    #endregion
674
675    #region Project Methods
676    public Guid AddProject(DT.Project projectDto) {
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, false);
683        } else {
684          throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
685        }
686      }
687     
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) {
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, false);
704      }
705
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) {
722      if (projectId == Guid.Empty) return;
723      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
724      // check if current (non-admin) user is owner of one of the projectDto's-parents
725      if (!RoleVerifier.IsInRole(HiveRoles.Administrator)) {
726        AuthorizationManager.AuthorizeForProjectAdministration(projectId, true);
727      }
728
729      var pm = PersistenceManager;
730      using (new PerformanceLogger("DeleteProject")) {
731        var projectDao = pm.ProjectDao;
732        var assignedJobResourceDao = pm.AssignedJobResourceDao;
733        pm.UseTransaction(() => {
734          var projectIds = new HashSet<Guid> { projectId };
735          projectIds.Union(projectDao.GetChildProjectIdsById(projectId));
736
737          assignedJobResourceDao.DeleteByProjectIds(projectIds);
738          projectDao.DeleteByIds(projectIds);
739          pm.SubmitChanges();
740        });
741      }
742    }
743
744    // query granted project for use (i.e. to calculate on)
745    public DT.Project GetProject(Guid projectId) {
746      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
747      var pm = PersistenceManager;
748      using (new PerformanceLogger("GetProject")) {
749        var projectDao = pm.ProjectDao;
750        var currentUserId = UserManager.CurrentUserId;
751        var userAndGroupIds = new List<Guid> { currentUserId };
752        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
753        return pm.UseTransaction(() => {
754          return projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
755          .Where(x => x.ProjectId == projectId)
756          .Select(x => x.ToDto())
757          .SingleOrDefault();
758        });
759      }
760    }
761
762    // query granted projects for use (i.e. to calculate on)
763    public IEnumerable<DT.Project> GetProjects() {
764      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
765      var pm = PersistenceManager;
766      using (new PerformanceLogger("GetProjects")) {
767        var projectDao = pm.ProjectDao;
768        var currentUserId = UserManager.CurrentUserId;
769        var userAndGroupIds = new List<Guid> { currentUserId };
770        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
771        return pm.UseTransaction(() => {
772          return projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
773            .Select(x => x.ToDto()).ToList();
774        });
775      }
776    }
777
778    public IEnumerable<DT.Project> GetProjectsForAdministration() {
779      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
780      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
781      var pm = PersistenceManager;
782      using (new PerformanceLogger("GetProjectsForAdministration")) {
783        var projectDao = pm.ProjectDao;
784       
785        return pm.UseTransaction(() => {
786          if(isAdministrator) {
787            return projectDao.GetAll().Select(x => x.ToDto()).ToList();
788          } else {
789            var currentUserId = UserManager.CurrentUserId;
790            return projectDao.GetAdministrationGrantedProjectsForUser(currentUserId)
791              .Select(x => x.ToDto()).ToList();
792
793          }
794        });
795      }
796    }
797
798    public IDictionary<Guid, HashSet<Guid>> GetProjectGenealogy() {
799      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
800      var pm = PersistenceManager;
801      using(new PerformanceLogger("GetProjectGenealogy")) {
802        var projectDao = pm.ProjectDao;
803        var projectAncestors = new Dictionary<Guid, HashSet<Guid>>();
804        return pm.UseTransaction(() => {
805          var projects = projectDao.GetAll().ToList();
806          projects.ForEach(p => projectAncestors.Add(p.ProjectId, new HashSet<Guid>()));
807          foreach (var p in projects) {
808            var parentProject = p.ParentProject;
809            while(parentProject != null) {
810              projectAncestors[p.ProjectId].Add(parentProject.ProjectId);
811              parentProject = parentProject.ParentProject;
812            }
813          }
814          return projectAncestors;
815        });
816      }
817    }
818    #endregion
819
820    #region ProjectPermission Methods
821    public void SaveProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool reassign, bool cascading, bool reassignCascading) {
822      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
823      if (projectId == null || grantedUserIds == null) return;
824      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
825      var pm = PersistenceManager;
826      using (new PerformanceLogger("SaveProjectPermissions")) {
827        var projectDao = pm.ProjectDao;
828        var projectPermissionDao = pm.ProjectPermissionDao;
829        var assignedJobResourceDao = pm.AssignedJobResourceDao;
830
831        pm.UseTransaction(() => {
832          var project = projectDao.GetById(projectId);
833          if (project == null) return;
834          var projectPermissions = project.ProjectPermissions.Select(x => x.GrantedUserId).ToArray();
835          //var addedPermissions = grantedUserIds.Except(projectPermissions);
836          var removedPermissions = projectPermissions.Except(grantedUserIds);
837
838          // remove job assignments and project permissions
839          if (reassign) {
840            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
841            project.ProjectPermissions.Clear();
842          } else {
843            assignedJobResourceDao.DeleteByProjectIdAndUserIds(project.ProjectId, removedPermissions);
844            foreach(var item in project.ProjectPermissions
845              .Where(x => removedPermissions.Contains(x.GrantedUserId))
846              .ToList()) {
847              project.ProjectPermissions.Remove(item);
848            }
849          }
850          pm.SubmitChanges();
851
852          // add project permissions
853          foreach (var id in grantedUserIds) {
854            if(project.ProjectPermissions.All(x => x.GrantedUserId != id)) {
855              project.ProjectPermissions.Add(new DA.ProjectPermission {
856                GrantedUserId = id,
857                GrantedByUserId = UserManager.CurrentUserId
858              });
859            }
860          }
861          pm.SubmitChanges();
862
863          if (cascading) {
864            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
865            var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
866
867            // remove job assignments
868            if (reassignCascading) {
869              assignedJobResourceDao.DeleteByProjectIds(childProjectIds);
870            } else {
871              assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, removedPermissions);
872            }
873
874            foreach(var p in childProjects) {
875              // remove project permissions
876              if(reassignCascading) {
877                p.ProjectPermissions.Clear();
878              } else {
879                foreach(var item in p.ProjectPermissions
880                  .Where(x => removedPermissions.Contains(x.GrantedUserId))
881                  .ToList()) {
882                  p.ProjectPermissions.Remove(item);
883                }
884              }
885              pm.SubmitChanges();
886
887              // add project permissions
888              foreach (var id in grantedUserIds) {
889                if (p.ProjectPermissions.All(x => x.GrantedUserId != id)) {
890                  p.ProjectPermissions.Add(new DA.ProjectPermission {
891                    GrantedUserId = id,
892                    GrantedByUserId = UserManager.CurrentUserId
893                  });
894                }
895              }
896            }
897          }
898          pm.SubmitChanges();
899        });
900      }
901    }
902
903    //private void GrantProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
904    //  throw new NotImplementedException();
905    //}
906
907    //private void RevokeProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
908    //  RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
909    //  if (projectId == null || grantedUserIds == null || !grantedUserIds.Any()) return;
910    //  AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
911    //  var pm = PersistenceManager;
912    //  using (new PerformanceLogger("RevokeProjectPermissions")) {
913    //    var projectPermissionDao = pm.ProjectPermissionDao;
914    //    var projectDao = pm.ProjectDao;
915    //    var assignedJobResourceDao = pm.AssignedJobResourceDao;
916    //    pm.UseTransaction(() => {
917    //      if (cascading) {
918    //        var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
919    //        projectPermissionDao.DeleteByProjectIdsAndGrantedUserIds(childProjectIds, grantedUserIds);
920    //        assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, grantedUserIds);
921    //      }
922    //      projectPermissionDao.DeleteByProjectIdAndGrantedUserIds(projectId, grantedUserIds);
923    //      assignedJobResourceDao.DeleteByProjectIdAndUserIds(projectId, grantedUserIds);
924    //      pm.SubmitChanges();
925    //    });
926    //  }
927    //}
928
929    public IEnumerable<DT.ProjectPermission> GetProjectPermissions(Guid projectId) {
930      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
931      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
932      var pm = PersistenceManager;
933      using (new PerformanceLogger("GetProjectPermissions")) {
934        var projectPermissionDao = pm.ProjectPermissionDao;
935        return pm.UseTransaction(() => projectPermissionDao.GetByProjectId(projectId)
936          .Select(x => x.ToDto())
937          .ToList()
938        );
939      }
940    }
941    #endregion
942
943    #region AssignedProjectResource Methods
944    // basic: remove and add assignments (resourceIds) to projectId and its depending jobs
945    // reassign: clear all assignments from project and its depending jobs, before adding new ones (resourceIds)
946    // cascading: "basic" mode for child-projects
947    // reassignCascading: "reassign" mode for child-projects
948    public void SaveProjectResourceAssignments(Guid projectId, List<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
949      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
950      if (projectId == null || resourceIds == null) return;
951      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
952      var pm = PersistenceManager;
953      using (new PerformanceLogger("SaveProjectResourceAssignments")) {
954        var projectDao = pm.ProjectDao;
955        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
956        var assignedJobResourceDao = pm.AssignedJobResourceDao;
957        pm.UseTransaction(() => {
958          var project = projectDao.GetById(projectId);
959          var assignedResources = project.AssignedProjectResources.Select(x => x.ResourceId).ToArray();
960          var removedAssignments = assignedResources.Except(resourceIds);
961
962          // remove job and project assignments
963          if (reassign) {
964            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
965            project.AssignedProjectResources.Clear();
966          } else {
967            assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, removedAssignments);
968            foreach (var item in project.AssignedProjectResources
969              .Where(x => removedAssignments.Contains(x.ResourceId))
970              .ToList()) {
971              project.AssignedProjectResources.Remove(item);
972            }
973          }
974          pm.SubmitChanges();
975
976          // add project assignments
977          foreach (var id in resourceIds) {
978            if (project.AssignedProjectResources.All(x => x.ResourceId != id)) {
979              project.AssignedProjectResources.Add(new DA.AssignedProjectResource {
980                ResourceId = id
981              });
982            }
983          }
984          pm.SubmitChanges();
985
986          if (cascading) {
987            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
988
989            // remove job assignments
990            if (reassignCascading) {
991              assignedJobResourceDao.DeleteByProjectIds(childProjects.Select(x => x.ProjectId).ToList());
992            } else {
993              var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
994              assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, removedAssignments);
995            }
996            foreach (var p in childProjects) {
997              // remove project assignments
998              if (reassignCascading) {
999                p.AssignedProjectResources.Clear();
1000              } else {
1001                foreach (var item in p.AssignedProjectResources
1002                  .Where(x => removedAssignments.Contains(x.ResourceId))
1003                  .ToList()) {
1004                  p.AssignedProjectResources.Remove(item);
1005                }
1006              }
1007              pm.SubmitChanges();
1008
1009              // add project assignments
1010              foreach (var id in resourceIds) {
1011                if(p.AssignedProjectResources.All(x => x.ResourceId != id)) {
1012                  p.AssignedProjectResources.Add(new DA.AssignedProjectResource {
1013                    ResourceId = id
1014                  });
1015                }
1016              }
1017            }
1018          }
1019          pm.SubmitChanges();
1020        });
1021      }
1022    }
1023
1024    //private void AssignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
1025    //  throw new NotImplementedException();
1026    //}
1027
1028    //private void UnassignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
1029    //  RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1030    //  if (projectId == null || resourceIds == null || !resourceIds.Any()) return;
1031    //  AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
1032    //  var pm = PersistenceManager;
1033    //  using (new PerformanceLogger("UnassignProjectResources")) {
1034    //    var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1035    //    var assignedJobResourceDao = pm.AssignedJobResourceDao;
1036    //    var projectDao = pm.ProjectDao;
1037    //    pm.UseTransaction(() => {
1038    //      if (cascading) {
1039    //        var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
1040    //        assignedProjectResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
1041    //        assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
1042    //      }
1043    //      assignedProjectResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
1044    //      assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
1045    //      pm.SubmitChanges();
1046    //    });
1047    //  }
1048    //}
1049
1050    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProject(Guid projectId) {
1051      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1052      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, projectId);
1053      var pm = PersistenceManager;
1054      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1055        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1056        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1057          .Select(x => x.ToDto())
1058          .ToList()
1059        );
1060      }
1061    }
1062
1063    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProjectAdministration(Guid projectId) {
1064      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1065      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
1066      var pm = PersistenceManager;
1067      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1068        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1069        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1070          .Select(x => x.ToDto())
1071          .ToList()
1072        );
1073      }
1074    }
1075
1076    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProjectsAdministration(IEnumerable<Guid> projectIds) {
1077      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1078      foreach(var id in projectIds)
1079        AuthorizationManager.AuthorizeForProjectAdministration(id, false);
1080
1081      var pm = PersistenceManager;
1082      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1083        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1084        var assignments = new List<DT.AssignedProjectResource>();
1085        pm.UseTransaction(() => {
1086          foreach (var id in projectIds) {
1087            assignments.AddRange(assignedProjectResourceDao.GetByProjectId(id)
1088              .Select(x => x.ToDto()));
1089          }
1090        });
1091        return assignments.Distinct();
1092      }
1093    }
1094
1095    #endregion
1096
1097    #region Slave Methods
1098    public Guid AddSlave(DT.Slave slaveDto) {
1099      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1100      var pm = PersistenceManager;
1101      using (new PerformanceLogger("AddSlave")) {
1102        var slaveDao = pm.SlaveDao;
1103        return pm.UseTransaction(() => {
1104          var slave = slaveDao.Save(slaveDto.ToEntity());
1105          pm.SubmitChanges();
1106          return slave.ResourceId;
1107        });
1108      }
1109    }
1110
1111    public Guid AddSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1112      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1113      var pm = PersistenceManager;
1114      using (new PerformanceLogger("AddSlaveGroup")) {
1115        var slaveGroupDao = pm.SlaveGroupDao;
1116        return pm.UseTransaction(() => {
1117          if (slaveGroupDto.Id == Guid.Empty) {
1118            slaveGroupDto.Id = Guid.NewGuid();
1119          }
1120          var slaveGroup = slaveGroupDao.Save(slaveGroupDto.ToEntity());
1121          pm.SubmitChanges();
1122          return slaveGroup.ResourceId;
1123        });
1124      }
1125    }
1126
1127    public DT.Slave GetSlave(Guid slaveId) {
1128      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1129      var pm = PersistenceManager;
1130      using (new PerformanceLogger("GetSlave")) {
1131        var slaveDao = pm.SlaveDao;
1132        return pm.UseTransaction(() => slaveDao.GetById(slaveId).ToDto());
1133      }
1134    }
1135
1136    // query granted slaves for use (i.e. to calculate on)
1137    public IEnumerable<DT.Slave> GetSlaves() {
1138      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1139      var pm = PersistenceManager;
1140      using (new PerformanceLogger("GetSlaves")) {
1141        var slaveDao = pm.SlaveDao;
1142        var projectDao = pm.ProjectDao;
1143        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1144
1145        // collect user information
1146        var currentUserId = UserManager.CurrentUserId;
1147        var userAndGroupIds = new List<Guid> { currentUserId };
1148        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
1149
1150        return pm.UseTransaction(() => {
1151          var slaves = slaveDao.GetAll()
1152            .Select(x => x.ToDto())
1153            .ToList();
1154          var grantedProjectIds = projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
1155            .Select(x => x.ProjectId)
1156            .ToList();
1157          var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourcesByProjectIds(grantedProjectIds)
1158            .Select(x => x.ResourceId)
1159            .ToList();
1160
1161          return slaves
1162            .Where(x => grantedResourceIds.Contains(x.Id))
1163            .ToList();
1164        });
1165      }
1166    }
1167
1168    // query granted slave groups for use (i.e. to calculate on)
1169    public IEnumerable<DT.SlaveGroup> GetSlaveGroups() {
1170      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1171      var pm = PersistenceManager;
1172      using (new PerformanceLogger("GetSlaveGroups")) {
1173        var slaveGroupDao = pm.SlaveGroupDao;
1174        var projectDao = pm.ProjectDao;
1175        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1176
1177        // collect user information
1178        var currentUserId = UserManager.CurrentUserId;
1179        var userAndGroupIds = new List<Guid> { currentUserId };
1180        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
1181
1182        return pm.UseTransaction(() => {
1183          var slaveGroups = slaveGroupDao.GetAll()
1184            .Select(x => x.ToDto())
1185            .ToList();
1186          var grantedProjectIds = projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
1187            .Select(x => x.ProjectId)
1188            .ToList();
1189          var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourcesByProjectIds(grantedProjectIds)
1190            .Select(x => x.ResourceId)
1191            .ToList();
1192
1193          return slaveGroups
1194            .Where(x => grantedResourceIds.Contains(x.Id))
1195            .ToList();
1196        });
1197      }
1198    }
1199
1200    // query granted slaves for resource administration
1201    public IEnumerable<DT.Slave> GetSlavesForAdministration() {
1202      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1203      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1204      var pm = PersistenceManager;
1205      using (new PerformanceLogger("GetSlavesForAdministration")) {
1206        var slaveDao = pm.SlaveDao;
1207        var currentUserId = UserManager.CurrentUserId;
1208
1209        if (isAdministrator) {
1210          return pm.UseTransaction(() => {
1211            return slaveDao.GetAll()
1212              .Select(x => x.ToDto())
1213              .ToList();
1214          });
1215        } else {
1216          var slaves = slaveDao.GetAll()
1217            .Select(x => x.ToDto())
1218            .ToList();
1219          var projectDao = pm.ProjectDao;
1220          var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1221          var projects = projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).ToList();
1222          var resourceIds = assignedProjectResourceDao
1223            .GetAllGrantedResourcesByProjectIds(projects.Select(x => x.ProjectId).ToList())
1224            .Select(x => x.ResourceId)
1225            .ToList();
1226
1227          return slaves
1228            .Where(x => resourceIds.Contains(x.Id))
1229            .ToList();
1230        }
1231      }
1232    }
1233
1234    // query granted slave groups for resource administration
1235    public IEnumerable<DT.SlaveGroup> GetSlaveGroupsForAdministration() {
1236      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1237      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1238      var pm = PersistenceManager;
1239      using (new PerformanceLogger("GetSlaveGroupsForAdministration")) {
1240        var slaveGroupDao = pm.SlaveGroupDao;
1241        var currentUserId = UserManager.CurrentUserId;
1242
1243        if (isAdministrator) {
1244          return pm.UseTransaction(() => {
1245            return slaveGroupDao.GetAll()
1246              .Select(x => x.ToDto())
1247              .ToList();
1248          });
1249        } else {
1250          var slaveGroups = slaveGroupDao.GetAll()
1251            .Select(x => x.ToDto())
1252            .ToList();
1253          var projectDao = pm.ProjectDao;
1254          var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1255          var projects = projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).ToList();
1256          var resourceIds = assignedProjectResourceDao
1257            .GetAllGrantedResourcesByProjectIds(projects.Select(x => x.ProjectId).ToList())
1258            .Select(x => x.ResourceId)
1259            .ToList();
1260
1261          return slaveGroups
1262            .Where(x => resourceIds.Contains(x.Id))
1263            .ToList();
1264        }
1265      }
1266    }
1267
1268    public IDictionary<Guid, HashSet<Guid>> GetResourceGenealogy() {
1269      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1270      var pm = PersistenceManager;
1271      using (new PerformanceLogger("GetResourceGenealogy")) {
1272        var resourceDao = pm.ResourceDao;
1273        var resourceAncestors = new Dictionary<Guid, HashSet<Guid>>();
1274        return pm.UseTransaction(() => {
1275          var resources = resourceDao.GetAll().ToList();
1276          resources.ForEach(r => resourceAncestors.Add(r.ResourceId, new HashSet<Guid>()));
1277         
1278          foreach(var r in resources) {
1279            var parentResource = r.ParentResource;
1280            while(parentResource != null) {
1281              resourceAncestors[r.ResourceId].Add(parentResource.ResourceId);
1282              parentResource = parentResource.ParentResource;
1283            }
1284          }
1285          return resourceAncestors;
1286        });
1287      }
1288    }
1289
1290    public void UpdateSlave(DT.Slave slaveDto) {
1291      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1292      if (slaveDto == null) return;
1293      AuthorizationManager.AuthorizeForResourceAdministration(slaveDto.Id);
1294      var pm = PersistenceManager;
1295      using (new PerformanceLogger("UpdateSlave")) {
1296        var slaveDao = pm.SlaveDao;
1297        pm.UseTransaction(() => {
1298          var slave = slaveDao.GetById(slaveDto.Id);
1299          if (slave != null) {
1300            slaveDto.CopyToEntity(slave);
1301          } else {
1302            slaveDao.Save(slaveDto.ToEntity());
1303          }
1304          pm.SubmitChanges();
1305        });
1306      }
1307    }
1308
1309    public void UpdateSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1310      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1311      if (slaveGroupDto == null) return;
1312      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupDto.Id);
1313      var pm = PersistenceManager;
1314      using (new PerformanceLogger("UpdateSlaveGroup")) {
1315        var slaveGroupDao = pm.SlaveGroupDao;
1316        pm.UseTransaction(() => {
1317          var slaveGroup = slaveGroupDao.GetById(slaveGroupDto.Id);
1318          if (slaveGroup != null) {
1319            slaveGroupDto.CopyToEntity(slaveGroup);
1320          } else {
1321            slaveGroupDao.Save(slaveGroupDto.ToEntity());
1322          }
1323          pm.SubmitChanges();
1324        });
1325      }
1326    }
1327
1328    public void DeleteSlave(Guid slaveId) {
1329      if (slaveId == Guid.Empty) return;
1330      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1331      AuthorizationManager.AuthorizeForResourceAdministration(slaveId);
1332      var pm = PersistenceManager;
1333      using (new PerformanceLogger("DeleteSlave")) {
1334        var slaveDao = pm.SlaveDao;
1335        pm.UseTransaction(() => {
1336          slaveDao.Delete(slaveId);
1337          pm.SubmitChanges();
1338        });
1339      }
1340    }
1341
1342    public void DeleteSlaveGroup(Guid slaveGroupId) {
1343      if (slaveGroupId == Guid.Empty) return;
1344      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1345      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupId);
1346      var pm = PersistenceManager;
1347      using (new PerformanceLogger("DeleteSlaveGroup")) {
1348        var resourceDao = pm.ResourceDao;
1349        pm.UseTransaction(() => {
1350          var resourceIds = new HashSet<Guid> { slaveGroupId };
1351          resourceIds.Union(resourceDao.GetChildResourceIdsById(slaveGroupId));
1352          resourceDao.DeleteByIds(resourceIds);
1353          pm.SubmitChanges();
1354        });
1355      }
1356    }
1357
1358    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
1359      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1360      var pm = PersistenceManager;
1361      using (new PerformanceLogger("AddResourceToGroup")) {
1362        var resourceDao = pm.ResourceDao;
1363        pm.UseTransaction(() => {
1364          var resource = resourceDao.GetById(resourceId);
1365          resource.ParentResourceId = slaveGroupId;
1366          pm.SubmitChanges();
1367        });
1368      }
1369    }
1370
1371    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
1372      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1373      var pm = PersistenceManager;
1374      using (new PerformanceLogger("RemoveResourceFromGroup")) {
1375        var resourceDao = pm.ResourceDao;
1376        pm.UseTransaction(() => {
1377          var resource = resourceDao.GetById(resourceId);
1378          resource.ParentResourceId = null;
1379          pm.SubmitChanges();
1380        });
1381      }
1382    }
1383
1384    public Guid GetResourceId(string resourceName) {
1385      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1386      var pm = PersistenceManager;
1387      using (new PerformanceLogger("GetResourceId")) {
1388        var resourceDao = pm.ResourceDao;
1389        return pm.UseTransaction(() => {
1390          var resource = resourceDao.GetByName(resourceName);
1391          return resource != null ? resource.ResourceId : Guid.Empty;
1392        });
1393      }
1394    }
1395
1396    public void TriggerEventManager(bool force) {
1397      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1398      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
1399      bool cleanup;
1400      var pm = PersistenceManager;
1401      using (new PerformanceLogger("TriggerEventManager")) {
1402        cleanup = false;
1403        var lifecycleDao = pm.LifecycleDao;
1404        pm.UseTransaction(() => {
1405          var lastLifecycle = lifecycleDao.GetLastLifecycle();
1406          DateTime lastCleanup = lastLifecycle != null ? lastLifecycle.LastCleanup : DateTime.MinValue;
1407          if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
1408            lifecycleDao.UpdateLifecycle();
1409            cleanup = true;
1410            pm.SubmitChanges();
1411          }
1412        }, true);
1413      }
1414      if (cleanup) {
1415        EventManager.Cleanup();
1416      }
1417    }
1418
1419    public int GetNewHeartbeatInterval(Guid slaveId) {
1420      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
1421      var pm = PersistenceManager;
1422      using (new PerformanceLogger("GetNewHeartbeatInterval")) {
1423        var slaveDao = pm.SlaveDao;
1424        return pm.UseTransaction(() => {
1425          var slave = slaveDao.GetById(slaveId);
1426          if (slave != null) {
1427            return slave.HbInterval;
1428          }
1429          return -1;
1430        });
1431      }
1432    }
1433    #endregion
1434
1435    #region Downtime Methods
1436    public Guid AddDowntime(DT.Downtime downtimeDto) {
1437      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1438      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1439      var pm = PersistenceManager;
1440      using (new PerformanceLogger("AddDowntime")) {
1441        var downtimeDao = pm.DowntimeDao;
1442        return pm.UseTransaction(() => {
1443          var downtime = downtimeDao.Save(downtimeDto.ToEntity());
1444          pm.SubmitChanges();
1445          return downtime.ResourceId;
1446        });
1447      }
1448    }
1449
1450    public void DeleteDowntime(Guid downtimeId) {
1451      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1452      var pm = PersistenceManager;
1453      using (new PerformanceLogger("DeleteDowntime")) {
1454        var downtimeDao = pm.DowntimeDao;
1455        pm.UseTransaction(() => {
1456          downtimeDao.Delete(downtimeId);
1457          pm.SubmitChanges();
1458        });
1459      }
1460    }
1461
1462    public void UpdateDowntime(DT.Downtime downtimeDto) {
1463      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1464      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1465      var pm = PersistenceManager;
1466      using (new PerformanceLogger("UpdateDowntime")) {
1467        var downtimeDao = pm.DowntimeDao;
1468        pm.UseTransaction(() => {
1469          var downtime = downtimeDao.GetById(downtimeDto.Id);
1470          if (downtime != null) {
1471            downtimeDto.CopyToEntity(downtime);
1472          } else {
1473            downtimeDao.Save(downtimeDto.ToEntity());
1474          }
1475          pm.SubmitChanges();
1476        });
1477      }
1478    }
1479
1480    public IEnumerable<DT.Downtime> GetDowntimesForResource(Guid resourceId) {
1481      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1482      var pm = PersistenceManager;
1483      using (new PerformanceLogger("GetDowntimesForResource")) {
1484        var downtimeDao = pm.DowntimeDao;
1485        return pm.UseTransaction(() => downtimeDao.GetByResourceId(resourceId)
1486          .Select(x => x.ToDto())
1487          .ToList()
1488        );
1489      }
1490    }
1491    #endregion
1492
1493    #region User Methods
1494    public string GetUsernameByUserId(Guid userId) {
1495      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1496      var user = UserManager.GetUserById(userId);
1497      return user != null ? user.UserName : null;
1498    }
1499
1500    public Guid GetUserIdByUsername(string username) {
1501      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1502      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
1503      return user != null ? (Guid?)user.ProviderUserKey ?? Guid.Empty : Guid.Empty;
1504    }
1505   
1506    public Dictionary<Guid, HashSet<Guid>> GetUserGroupTree() {
1507      var userGroupTree = new Dictionary<Guid, HashSet<Guid>>();
1508      var userGroupMapping = UserManager.GetUserGroupMapping();
1509
1510      foreach(var ugm in userGroupMapping) {
1511        if (ugm.Parent == null || ugm.Child == null) continue;
1512
1513        if (!userGroupTree.ContainsKey(ugm.Parent)) {
1514          userGroupTree.Add(ugm.Parent, new HashSet<Guid>());
1515        }
1516        userGroupTree[ugm.Parent].Add(ugm.Child);
1517      }
1518
1519      return userGroupTree;
1520    }
1521
1522    public bool CheckAccessToAdminAreaGranted() {
1523      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1524      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1525      var pm = PersistenceManager;
1526      using(new PerformanceLogger("CheckAccessToAdminAreaGranted")) {
1527        if (isAdministrator) {
1528          return true;
1529        } else {
1530          var projectDao = pm.ProjectDao;
1531          var currentUserId = UserManager.CurrentUserId;
1532          return projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).Any();
1533        }
1534      }
1535    }
1536    #endregion
1537
1538    #region UserPriorities Methods
1539    public IEnumerable<DT.UserPriority> GetUserPriorities() {
1540      var pm = PersistenceManager;
1541      using (new PerformanceLogger("GetUserPriorities")) {
1542        var userPriorityDao = pm.UserPriorityDao;
1543        return pm.UseTransaction(() => userPriorityDao.GetAll()
1544          .Select(x => x.ToDto())
1545          .ToList()
1546        );
1547      }
1548    }
1549    #endregion
1550
1551    #region Private Helper Methods
1552    private void UpdateTaskState(IPersistenceManager pm, DA.Task task, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
1553      var stateLogDao = pm.StateLogDao;
1554      var taskStateEntity = taskState.ToEntity();
1555
1556      if (task.State == DA.TaskState.Transferring && taskStateEntity == DA.TaskState.Paused && task.Command == null) {
1557        // slave paused and uploaded the task (no user-command) -> set waiting.
1558        taskStateEntity = DA.TaskState.Waiting;
1559      }
1560
1561      stateLogDao.Save(new DA.StateLog {
1562        State = taskStateEntity,
1563        DateTime = DateTime.Now,
1564        TaskId = task.TaskId,
1565        UserId = userId,
1566        SlaveId = slaveId,
1567        Exception = exception
1568      });
1569
1570      task.State = taskStateEntity;
1571
1572      if (task.Command == DA.Command.Pause && task.State == DA.TaskState.Paused
1573          || task.Command == DA.Command.Abort && task.State == DA.TaskState.Aborted
1574          || task.Command == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
1575        task.Command = null;
1576      }
1577    }
1578
1579    #endregion
1580  }
1581}
Note: See TracBrowser for help on using the repository browser.