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

Last change on this file since 15908 was 15908, checked in by jkarder, 4 years ago

#2839: worked on hive project management

  • fixed some bugs
  • cleaned up
File size: 62.9 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    #endregion
798
799    #region ProjectPermission Methods
800    public void SaveProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool reassign, bool cascading, bool reassignCascading) {
801      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
802      if (projectId == null || grantedUserIds == null) return;
803      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
804      var pm = PersistenceManager;
805      using (new PerformanceLogger("SaveProjectPermissions")) {
806        var projectDao = pm.ProjectDao;
807        var projectPermissionDao = pm.ProjectPermissionDao;
808        var assignedJobResourceDao = pm.AssignedJobResourceDao;
809
810        pm.UseTransaction(() => {
811          var project = projectDao.GetById(projectId);
812          if (project == null) return;
813          var projectPermissions = project.ProjectPermissions.Select(x => x.GrantedUserId).ToArray();
814          //var addedPermissions = grantedUserIds.Except(projectPermissions);
815          var removedPermissions = projectPermissions.Except(grantedUserIds);
816
817          // remove job assignments and project permissions
818          if (reassign) {
819            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
820            project.ProjectPermissions.Clear();
821          } else {
822            assignedJobResourceDao.DeleteByProjectIdAndUserIds(project.ProjectId, removedPermissions);
823            foreach(var item in project.ProjectPermissions
824              .Where(x => removedPermissions.Contains(x.GrantedUserId))
825              .ToList()) {
826              project.ProjectPermissions.Remove(item);
827            }
828          }
829          pm.SubmitChanges();
830
831          // add project permissions
832          foreach (var id in grantedUserIds) {
833            if(project.ProjectPermissions.All(x => x.GrantedUserId != id)) {
834              project.ProjectPermissions.Add(new DA.ProjectPermission {
835                GrantedUserId = id,
836                GrantedByUserId = UserManager.CurrentUserId
837              });
838            }
839          }
840          pm.SubmitChanges();
841
842          if (cascading) {
843            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
844            var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
845
846            // remove job assignments
847            if (reassignCascading) {
848              assignedJobResourceDao.DeleteByProjectIds(childProjectIds);
849            } else {
850              assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, removedPermissions);
851            }
852
853            foreach(var p in childProjects) {
854              // remove project permissions
855              if(reassignCascading) {
856                p.ProjectPermissions.Clear();
857              } else {
858                foreach(var item in p.ProjectPermissions
859                  .Where(x => removedPermissions.Contains(x.GrantedUserId))
860                  .ToList()) {
861                  p.ProjectPermissions.Remove(item);
862                }
863              }
864              pm.SubmitChanges();
865
866              // add project permissions
867              foreach (var id in grantedUserIds) {
868                if (p.ProjectPermissions.All(x => x.GrantedUserId != id)) {
869                  p.ProjectPermissions.Add(new DA.ProjectPermission {
870                    GrantedUserId = id,
871                    GrantedByUserId = UserManager.CurrentUserId
872                  });
873                }
874              }
875            }
876          }
877          pm.SubmitChanges();
878        });
879      }
880    }
881
882    //private void GrantProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
883    //  throw new NotImplementedException();
884    //}
885
886    //private void RevokeProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
887    //  RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
888    //  if (projectId == null || grantedUserIds == null || !grantedUserIds.Any()) return;
889    //  AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
890    //  var pm = PersistenceManager;
891    //  using (new PerformanceLogger("RevokeProjectPermissions")) {
892    //    var projectPermissionDao = pm.ProjectPermissionDao;
893    //    var projectDao = pm.ProjectDao;
894    //    var assignedJobResourceDao = pm.AssignedJobResourceDao;
895    //    pm.UseTransaction(() => {
896    //      if (cascading) {
897    //        var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
898    //        projectPermissionDao.DeleteByProjectIdsAndGrantedUserIds(childProjectIds, grantedUserIds);
899    //        assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, grantedUserIds);
900    //      }
901    //      projectPermissionDao.DeleteByProjectIdAndGrantedUserIds(projectId, grantedUserIds);
902    //      assignedJobResourceDao.DeleteByProjectIdAndUserIds(projectId, grantedUserIds);
903    //      pm.SubmitChanges();
904    //    });
905    //  }
906    //}
907
908    public IEnumerable<DT.ProjectPermission> GetProjectPermissions(Guid projectId) {
909      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
910      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
911      var pm = PersistenceManager;
912      using (new PerformanceLogger("GetProjectPermissions")) {
913        var projectPermissionDao = pm.ProjectPermissionDao;
914        return pm.UseTransaction(() => projectPermissionDao.GetByProjectId(projectId)
915          .Select(x => x.ToDto())
916          .ToList()
917        );
918      }
919    }
920    #endregion
921
922    #region AssignedProjectResource Methods
923    // basic: remove and add assignments (resourceIds) to projectId and its depending jobs
924    // reassign: clear all assignments from project and its depending jobs, before adding new ones (resourceIds)
925    // cascading: "basic" mode for child-projects
926    // reassignCascading: "reassign" mode for child-projects
927    public void SaveProjectResourceAssignments(Guid projectId, List<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
928      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
929      if (projectId == null || resourceIds == null) return;
930      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
931      var pm = PersistenceManager;
932      using (new PerformanceLogger("SaveProjectResourceAssignments")) {
933        var projectDao = pm.ProjectDao;
934        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
935        var assignedJobResourceDao = pm.AssignedJobResourceDao;
936        pm.UseTransaction(() => {
937          var project = projectDao.GetById(projectId);
938          var assignedResources = project.AssignedProjectResources.Select(x => x.ResourceId).ToArray();
939          var removedAssignments = assignedResources.Except(resourceIds);
940
941          // remove job and project assignments
942          if (reassign) {
943            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
944            project.AssignedProjectResources.Clear();
945          } else {
946            assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, removedAssignments);
947            foreach (var item in project.AssignedProjectResources
948              .Where(x => removedAssignments.Contains(x.ResourceId))
949              .ToList()) {
950              project.AssignedProjectResources.Remove(item);
951            }
952          }
953          pm.SubmitChanges();
954
955          // add project assignments
956          foreach (var id in resourceIds) {
957            if (project.AssignedProjectResources.All(x => x.ResourceId != id)) {
958              project.AssignedProjectResources.Add(new DA.AssignedProjectResource {
959                ResourceId = id
960              });
961            }
962          }
963          pm.SubmitChanges();
964
965          if (cascading) {
966            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
967
968            // remove job assignments
969            if (reassignCascading) {
970              assignedJobResourceDao.DeleteByProjectIds(childProjects.Select(x => x.ProjectId).ToList());
971            } else {
972              var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
973              assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, removedAssignments);
974            }
975            foreach (var p in childProjects) {
976              // remove project assignments
977              if (reassignCascading) {
978                p.AssignedProjectResources.Clear();
979              } else {
980                foreach (var item in p.AssignedProjectResources
981                  .Where(x => removedAssignments.Contains(x.ResourceId))
982                  .ToList()) {
983                  p.AssignedProjectResources.Remove(item);
984                }
985              }
986              pm.SubmitChanges();
987
988              // add project assignments
989              foreach (var id in resourceIds) {
990                if(p.AssignedProjectResources.All(x => x.ResourceId != id)) {
991                  p.AssignedProjectResources.Add(new DA.AssignedProjectResource {
992                    ResourceId = id
993                  });
994                }
995              }
996            }
997          }
998          pm.SubmitChanges();
999        });
1000      }
1001    }
1002
1003    //private void AssignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
1004    //  throw new NotImplementedException();
1005    //}
1006
1007    //private void UnassignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
1008    //  RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1009    //  if (projectId == null || resourceIds == null || !resourceIds.Any()) return;
1010    //  AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
1011    //  var pm = PersistenceManager;
1012    //  using (new PerformanceLogger("UnassignProjectResources")) {
1013    //    var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1014    //    var assignedJobResourceDao = pm.AssignedJobResourceDao;
1015    //    var projectDao = pm.ProjectDao;
1016    //    pm.UseTransaction(() => {
1017    //      if (cascading) {
1018    //        var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
1019    //        assignedProjectResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
1020    //        assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
1021    //      }
1022    //      assignedProjectResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
1023    //      assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
1024    //      pm.SubmitChanges();
1025    //    });
1026    //  }
1027    //}
1028
1029    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProject(Guid projectId) {
1030      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1031      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, projectId);
1032      var pm = PersistenceManager;
1033      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1034        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1035        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1036          .Select(x => x.ToDto())
1037          .ToList()
1038        );
1039      }
1040    }
1041
1042    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProjectAdministration(Guid projectId) {
1043      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1044      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
1045      var pm = PersistenceManager;
1046      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1047        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1048        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1049          .Select(x => x.ToDto())
1050          .ToList()
1051        );
1052      }
1053    }
1054
1055    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProjectsAdministration(IEnumerable<Guid> projectIds) {
1056      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1057      foreach(var id in projectIds)
1058        AuthorizationManager.AuthorizeForProjectAdministration(id, false);
1059
1060      var pm = PersistenceManager;
1061      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1062        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1063        var assignments = new List<DT.AssignedProjectResource>();
1064        pm.UseTransaction(() => {
1065          foreach (var id in projectIds) {
1066            assignments.AddRange(assignedProjectResourceDao.GetByProjectId(id)
1067              .Select(x => x.ToDto()));
1068          }
1069        });
1070        return assignments.Distinct();
1071      }
1072    }
1073
1074    #endregion
1075
1076    #region Slave Methods
1077    public Guid AddSlave(DT.Slave slaveDto) {
1078      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1079      var pm = PersistenceManager;
1080      using (new PerformanceLogger("AddSlave")) {
1081        var slaveDao = pm.SlaveDao;
1082        return pm.UseTransaction(() => {
1083          var slave = slaveDao.Save(slaveDto.ToEntity());
1084          pm.SubmitChanges();
1085          return slave.ResourceId;
1086        });
1087      }
1088    }
1089
1090    public Guid AddSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1091      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1092      var pm = PersistenceManager;
1093      using (new PerformanceLogger("AddSlaveGroup")) {
1094        var slaveGroupDao = pm.SlaveGroupDao;
1095        return pm.UseTransaction(() => {
1096          if (slaveGroupDto.Id == Guid.Empty) {
1097            slaveGroupDto.Id = Guid.NewGuid();
1098          }
1099          var slaveGroup = slaveGroupDao.Save(slaveGroupDto.ToEntity());
1100          pm.SubmitChanges();
1101          return slaveGroup.ResourceId;
1102        });
1103      }
1104    }
1105
1106    public DT.Slave GetSlave(Guid slaveId) {
1107      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1108      var pm = PersistenceManager;
1109      using (new PerformanceLogger("GetSlave")) {
1110        var slaveDao = pm.SlaveDao;
1111        return pm.UseTransaction(() => slaveDao.GetById(slaveId).ToDto());
1112      }
1113    }
1114
1115    // query granted slaves for use (i.e. to calculate on)
1116    public IEnumerable<DT.Slave> GetSlaves() {
1117      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1118      var pm = PersistenceManager;
1119      using (new PerformanceLogger("GetSlaves")) {
1120        var slaveDao = pm.SlaveDao;
1121        var projectDao = pm.ProjectDao;
1122        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1123
1124        // collect user information
1125        var currentUserId = UserManager.CurrentUserId;
1126        var userAndGroupIds = new List<Guid> { currentUserId };
1127        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
1128
1129        return pm.UseTransaction(() => {
1130          var slaves = slaveDao.GetAll()
1131            .Select(x => x.ToDto())
1132            .ToList();
1133          var grantedProjectIds = projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
1134            .Select(x => x.ProjectId)
1135            .ToList();
1136          var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourcesByProjectIds(grantedProjectIds)
1137            .Select(x => x.ResourceId)
1138            .ToList();
1139
1140          return slaves
1141            .Where(x => grantedResourceIds.Contains(x.Id))
1142            .ToList();
1143        });
1144      }
1145    }
1146
1147    // query granted slave groups for use (i.e. to calculate on)
1148    public IEnumerable<DT.SlaveGroup> GetSlaveGroups() {
1149      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1150      var pm = PersistenceManager;
1151      using (new PerformanceLogger("GetSlaveGroups")) {
1152        var slaveGroupDao = pm.SlaveGroupDao;
1153        var projectDao = pm.ProjectDao;
1154        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1155
1156        // collect user information
1157        var currentUserId = UserManager.CurrentUserId;
1158        var userAndGroupIds = new List<Guid> { currentUserId };
1159        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
1160
1161        return pm.UseTransaction(() => {
1162          var slaveGroups = slaveGroupDao.GetAll()
1163            .Select(x => x.ToDto())
1164            .ToList();
1165          var grantedProjectIds = projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
1166            .Select(x => x.ProjectId)
1167            .ToList();
1168          var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourcesByProjectIds(grantedProjectIds)
1169            .Select(x => x.ResourceId)
1170            .ToList();
1171
1172          return slaveGroups
1173            .Where(x => grantedResourceIds.Contains(x.Id))
1174            .ToList();
1175        });
1176      }
1177    }
1178
1179    // query granted slaves for resource administration
1180    public IEnumerable<DT.Slave> GetSlavesForAdministration() {
1181      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1182      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1183      var pm = PersistenceManager;
1184      using (new PerformanceLogger("GetSlavesForAdministration")) {
1185        var slaveDao = pm.SlaveDao;
1186        var currentUserId = UserManager.CurrentUserId;
1187
1188        if (isAdministrator) {
1189          return pm.UseTransaction(() => {
1190            return slaveDao.GetAll()
1191              .Select(x => x.ToDto())
1192              .ToList();
1193          });
1194        } else {
1195          var slaves = slaveDao.GetAll()
1196            .Select(x => x.ToDto())
1197            .ToList();
1198          var projectDao = pm.ProjectDao;
1199          var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1200          var projects = projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).ToList();
1201          var resourceIds = assignedProjectResourceDao
1202            .GetAllGrantedResourcesByProjectIds(projects.Select(x => x.ProjectId).ToList())
1203            .Select(x => x.ResourceId)
1204            .ToList();
1205
1206          return slaves
1207            .Where(x => resourceIds.Contains(x.Id))
1208            .ToList();
1209        }
1210      }
1211    }
1212
1213    // query granted slave groups for resource administration
1214    public IEnumerable<DT.SlaveGroup> GetSlaveGroupsForAdministration() {
1215      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1216      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1217      var pm = PersistenceManager;
1218      using (new PerformanceLogger("GetSlaveGroupsForAdministration")) {
1219        var slaveGroupDao = pm.SlaveGroupDao;
1220        var currentUserId = UserManager.CurrentUserId;
1221
1222        if (isAdministrator) {
1223          return pm.UseTransaction(() => {
1224            return slaveGroupDao.GetAll()
1225              .Select(x => x.ToDto())
1226              .ToList();
1227          });
1228        } else {
1229          var slaveGroups = slaveGroupDao.GetAll()
1230            .Select(x => x.ToDto())
1231            .ToList();
1232          var projectDao = pm.ProjectDao;
1233          var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1234          var projects = projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).ToList();
1235          var resourceIds = assignedProjectResourceDao
1236            .GetAllGrantedResourcesByProjectIds(projects.Select(x => x.ProjectId).ToList())
1237            .Select(x => x.ResourceId)
1238            .ToList();
1239
1240          return slaveGroups
1241            .Where(x => resourceIds.Contains(x.Id))
1242            .ToList();
1243        }
1244      }
1245    }
1246
1247    public void UpdateSlave(DT.Slave slaveDto) {
1248      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1249      if (slaveDto == null) return;
1250      AuthorizationManager.AuthorizeForResourceAdministration(slaveDto.Id);
1251      var pm = PersistenceManager;
1252      using (new PerformanceLogger("UpdateSlave")) {
1253        var slaveDao = pm.SlaveDao;
1254        pm.UseTransaction(() => {
1255          var slave = slaveDao.GetById(slaveDto.Id);
1256          if (slave != null) {
1257            slaveDto.CopyToEntity(slave);
1258          } else {
1259            slaveDao.Save(slaveDto.ToEntity());
1260          }
1261          pm.SubmitChanges();
1262        });
1263      }
1264    }
1265
1266    public void UpdateSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1267      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1268      if (slaveGroupDto == null) return;
1269      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupDto.Id);
1270      var pm = PersistenceManager;
1271      using (new PerformanceLogger("UpdateSlaveGroup")) {
1272        var slaveGroupDao = pm.SlaveGroupDao;
1273        pm.UseTransaction(() => {
1274          var slaveGroup = slaveGroupDao.GetById(slaveGroupDto.Id);
1275          if (slaveGroup != null) {
1276            slaveGroupDto.CopyToEntity(slaveGroup);
1277          } else {
1278            slaveGroupDao.Save(slaveGroupDto.ToEntity());
1279          }
1280          pm.SubmitChanges();
1281        });
1282      }
1283    }
1284
1285    public void DeleteSlave(Guid slaveId) {
1286      if (slaveId == Guid.Empty) return;
1287      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1288      AuthorizationManager.AuthorizeForResourceAdministration(slaveId);
1289      var pm = PersistenceManager;
1290      using (new PerformanceLogger("DeleteSlave")) {
1291        var slaveDao = pm.SlaveDao;
1292        pm.UseTransaction(() => {
1293          slaveDao.Delete(slaveId);
1294          pm.SubmitChanges();
1295        });
1296      }
1297    }
1298
1299    public void DeleteSlaveGroup(Guid slaveGroupId) {
1300      if (slaveGroupId == Guid.Empty) return;
1301      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1302      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupId);
1303      var pm = PersistenceManager;
1304      using (new PerformanceLogger("DeleteSlaveGroup")) {
1305        var resourceDao = pm.ResourceDao;
1306        pm.UseTransaction(() => {
1307          var resourceIds = new HashSet<Guid> { slaveGroupId };
1308          resourceIds.Union(resourceDao.GetChildResourceIdsById(slaveGroupId));
1309          resourceDao.DeleteByIds(resourceIds);
1310          pm.SubmitChanges();
1311        });
1312      }
1313    }
1314
1315    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
1316      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1317      var pm = PersistenceManager;
1318      using (new PerformanceLogger("AddResourceToGroup")) {
1319        var resourceDao = pm.ResourceDao;
1320        pm.UseTransaction(() => {
1321          var resource = resourceDao.GetById(resourceId);
1322          resource.ParentResourceId = slaveGroupId;
1323          pm.SubmitChanges();
1324        });
1325      }
1326    }
1327
1328    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
1329      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1330      var pm = PersistenceManager;
1331      using (new PerformanceLogger("RemoveResourceFromGroup")) {
1332        var resourceDao = pm.ResourceDao;
1333        pm.UseTransaction(() => {
1334          var resource = resourceDao.GetById(resourceId);
1335          resource.ParentResourceId = null;
1336          pm.SubmitChanges();
1337        });
1338      }
1339    }
1340
1341    public Guid GetResourceId(string resourceName) {
1342      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1343      var pm = PersistenceManager;
1344      using (new PerformanceLogger("GetResourceId")) {
1345        var resourceDao = pm.ResourceDao;
1346        return pm.UseTransaction(() => {
1347          var resource = resourceDao.GetByName(resourceName);
1348          return resource != null ? resource.ResourceId : Guid.Empty;
1349        });
1350      }
1351    }
1352
1353    public void TriggerEventManager(bool force) {
1354      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1355      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
1356      bool cleanup;
1357      var pm = PersistenceManager;
1358      using (new PerformanceLogger("TriggerEventManager")) {
1359        cleanup = false;
1360        var lifecycleDao = pm.LifecycleDao;
1361        pm.UseTransaction(() => {
1362          var lastLifecycle = lifecycleDao.GetLastLifecycle();
1363          DateTime lastCleanup = lastLifecycle != null ? lastLifecycle.LastCleanup : DateTime.MinValue;
1364          if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
1365            lifecycleDao.UpdateLifecycle();
1366            cleanup = true;
1367            pm.SubmitChanges();
1368          }
1369        }, true);
1370      }
1371      if (cleanup) {
1372        EventManager.Cleanup();
1373      }
1374    }
1375
1376    public int GetNewHeartbeatInterval(Guid slaveId) {
1377      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
1378      var pm = PersistenceManager;
1379      using (new PerformanceLogger("GetNewHeartbeatInterval")) {
1380        var slaveDao = pm.SlaveDao;
1381        return pm.UseTransaction(() => {
1382          var slave = slaveDao.GetById(slaveId);
1383          if (slave != null) {
1384            return slave.HbInterval;
1385          }
1386          return -1;
1387        });
1388      }
1389    }
1390    #endregion
1391
1392    #region Downtime Methods
1393    public Guid AddDowntime(DT.Downtime downtimeDto) {
1394      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1395      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1396      var pm = PersistenceManager;
1397      using (new PerformanceLogger("AddDowntime")) {
1398        var downtimeDao = pm.DowntimeDao;
1399        return pm.UseTransaction(() => {
1400          var downtime = downtimeDao.Save(downtimeDto.ToEntity());
1401          pm.SubmitChanges();
1402          return downtime.ResourceId;
1403        });
1404      }
1405    }
1406
1407    public void DeleteDowntime(Guid downtimeId) {
1408      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1409      var pm = PersistenceManager;
1410      using (new PerformanceLogger("DeleteDowntime")) {
1411        var downtimeDao = pm.DowntimeDao;
1412        pm.UseTransaction(() => {
1413          downtimeDao.Delete(downtimeId);
1414          pm.SubmitChanges();
1415        });
1416      }
1417    }
1418
1419    public void UpdateDowntime(DT.Downtime downtimeDto) {
1420      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1421      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1422      var pm = PersistenceManager;
1423      using (new PerformanceLogger("UpdateDowntime")) {
1424        var downtimeDao = pm.DowntimeDao;
1425        pm.UseTransaction(() => {
1426          var downtime = downtimeDao.GetById(downtimeDto.Id);
1427          if (downtime != null) {
1428            downtimeDto.CopyToEntity(downtime);
1429          } else {
1430            downtimeDao.Save(downtimeDto.ToEntity());
1431          }
1432          pm.SubmitChanges();
1433        });
1434      }
1435    }
1436
1437    public IEnumerable<DT.Downtime> GetDowntimesForResource(Guid resourceId) {
1438      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1439      var pm = PersistenceManager;
1440      using (new PerformanceLogger("GetDowntimesForResource")) {
1441        var downtimeDao = pm.DowntimeDao;
1442        return pm.UseTransaction(() => downtimeDao.GetByResourceId(resourceId)
1443          .Select(x => x.ToDto())
1444          .ToList()
1445        );
1446      }
1447    }
1448    #endregion
1449
1450    #region User Methods
1451    public string GetUsernameByUserId(Guid userId) {
1452      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1453      var user = UserManager.GetUserById(userId);
1454      return user != null ? user.UserName : null;
1455    }
1456
1457    public Guid GetUserIdByUsername(string username) {
1458      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1459      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
1460      return user != null ? (Guid?)user.ProviderUserKey ?? Guid.Empty : Guid.Empty;
1461    }
1462   
1463    public Dictionary<Guid, HashSet<Guid>> GetUserGroupTree() {
1464      var userGroupTree = new Dictionary<Guid, HashSet<Guid>>();
1465      var userGroupMapping = UserManager.GetUserGroupMapping();
1466
1467      foreach(var ugm in userGroupMapping) {
1468        if (ugm.Parent == null || ugm.Child == null) continue;
1469
1470        if (!userGroupTree.ContainsKey(ugm.Parent)) {
1471          userGroupTree.Add(ugm.Parent, new HashSet<Guid>());
1472        }
1473        userGroupTree[ugm.Parent].Add(ugm.Child);
1474      }
1475
1476      return userGroupTree;
1477    }
1478
1479    public bool CheckAccessToAdminAreaGranted() {
1480      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1481      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1482      var pm = PersistenceManager;
1483      using(new PerformanceLogger("CheckAccessToAdminAreaGranted")) {
1484        if (isAdministrator) {
1485          return true;
1486        } else {
1487          var projectDao = pm.ProjectDao;
1488          var currentUserId = UserManager.CurrentUserId;
1489          return projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).Any();
1490        }
1491      }
1492    }
1493    #endregion
1494
1495    #region UserPriorities Methods
1496    public IEnumerable<DT.UserPriority> GetUserPriorities() {
1497      var pm = PersistenceManager;
1498      using (new PerformanceLogger("GetUserPriorities")) {
1499        var userPriorityDao = pm.UserPriorityDao;
1500        return pm.UseTransaction(() => userPriorityDao.GetAll()
1501          .Select(x => x.ToDto())
1502          .ToList()
1503        );
1504      }
1505    }
1506    #endregion
1507
1508    #region Private Helper Methods
1509    private void UpdateTaskState(IPersistenceManager pm, DA.Task task, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
1510      var stateLogDao = pm.StateLogDao;
1511      var taskStateEntity = taskState.ToEntity();
1512
1513      if (task.State == DA.TaskState.Transferring && taskStateEntity == DA.TaskState.Paused && task.Command == null) {
1514        // slave paused and uploaded the task (no user-command) -> set waiting.
1515        taskStateEntity = DA.TaskState.Waiting;
1516      }
1517
1518      stateLogDao.Save(new DA.StateLog {
1519        State = taskStateEntity,
1520        DateTime = DateTime.Now,
1521        TaskId = task.TaskId,
1522        UserId = userId,
1523        SlaveId = slaveId,
1524        Exception = exception
1525      });
1526
1527      task.State = taskStateEntity;
1528
1529      if (task.Command == DA.Command.Pause && task.State == DA.TaskState.Paused
1530          || task.Command == DA.Command.Abort && task.State == DA.TaskState.Aborted
1531          || task.Command == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
1532        task.Command = null;
1533      }
1534    }
1535
1536    #endregion
1537  }
1538}
Note: See TracBrowser for help on using the repository browser.