Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2839 worked on permission checks in listing methods

File size: 50.3 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    [Obsolete]
72    public Guid AddTask(DT.Task task, DT.TaskData taskData, IEnumerable<Guid> resourceIds) {
73      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
74      var pm = PersistenceManager;
75      using (new PerformanceLogger("AddTask")) {
76        var taskDao = pm.TaskDao;
77        var stateLogDao = pm.StateLogDao;
78
79        var newTask = task.ToEntity();
80        newTask.JobData = taskData.ToEntity();
81        newTask.JobData.LastUpdate = DateTime.Now;
82        newTask.AssignedTaskResources.AddRange(resourceIds.Select(
83          x => new DA.AssignedTaskResource {
84            ResourceId = x
85          }));
86        newTask.State = DA.TaskState.Waiting;
87        return pm.UseTransaction(() => {
88          taskDao.Save(newTask);
89          pm.SubmitChanges();
90          stateLogDao.Save(new DA.StateLog {
91            State = DA.TaskState.Waiting,
92            DateTime = DateTime.Now,
93            TaskId = newTask.TaskId,
94            UserId = UserManager.CurrentUserId,
95            SlaveId = null,
96            Exception = null
97          });
98          pm.SubmitChanges();
99          return newTask.TaskId;
100        }, false, true);
101      }
102    }
103
104    public Guid AddTask(DT.Task task, DT.TaskData taskData) {
105      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
106      var pm = PersistenceManager;
107      using (new PerformanceLogger("AddTask")) {
108        var taskDao = pm.TaskDao;
109        var stateLogDao = pm.StateLogDao;
110        var newTask = task.ToEntity();
111        newTask.JobData = taskData.ToEntity();
112        newTask.JobData.LastUpdate = DateTime.Now;
113        newTask.State = DA.TaskState.Waiting;
114        return pm.UseTransaction(() => {
115          taskDao.Save(newTask);
116          pm.SubmitChanges();
117          stateLogDao.Save(new DA.StateLog {
118            State = DA.TaskState.Waiting,
119            DateTime = DateTime.Now,
120            TaskId = newTask.TaskId,
121            UserId = UserManager.CurrentUserId,
122            SlaveId = null,
123            Exception = null
124          });
125          pm.SubmitChanges();
126          return newTask.TaskId;
127        }, false, true);
128      }
129    }
130
131    public Guid AddChildTask(Guid parentTaskId, DT.Task task, DT.TaskData taskData) {
132      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
133      task.ParentTaskId = parentTaskId;
134      return AddTask(task, taskData);
135    }
136
137    public DT.Task GetTask(Guid taskId) {
138      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
139      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
140      var pm = PersistenceManager;
141      using (new PerformanceLogger("GetTask")) {
142        var taskDao = pm.TaskDao;
143        return pm.UseTransaction(() => {
144          var task = taskDao.GetById(taskId);
145          return task.ToDto();
146        });
147      }
148    }
149
150    public IEnumerable<DT.LightweightTask> GetLightweightJobTasks(Guid jobId) {
151      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
152      AuthorizationManager.AuthorizeForJob(jobId, Permission.Read);
153      var pm = PersistenceManager;
154      using (new PerformanceLogger("GetLightweightJobTasks")) {
155        var taskDao = pm.TaskDao;
156        return pm.UseTransaction(() => {
157          return taskDao.GetByJobId(jobId)
158            .ToList()
159            .Select(x => new DT.LightweightTask {
160              Id = x.TaskId,
161              ExecutionTime = TimeSpan.FromMilliseconds(x.ExecutionTimeMs),
162              ParentTaskId = x.ParentTaskId,
163              StateLog = x.StateLogs.OrderBy(y => y.DateTime)
164                                    .Select(z => z.ToDto())
165                                    .ToList(),
166              State = x.State.ToDto(),
167              Command = x.Command.ToDto(),
168              LastTaskDataUpdate = x.JobData.LastUpdate
169            })
170            .ToList();
171        }, false, true);
172      }
173    }
174
175    public IEnumerable<DT.LightweightTask> GetLightweightJobTasksWithoutStateLog(Guid jobId) {
176      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
177      AuthorizationManager.AuthorizeForJob(jobId, Permission.Read);
178      var pm = PersistenceManager;
179      using (new PerformanceLogger("GetLightweightJobTasksWithoutStateLog")) {
180        var taskDao = pm.TaskDao;
181        return pm.UseTransaction(() => {
182          return taskDao.GetByJobId(jobId)
183            .ToList()
184            .Select(x => new DT.LightweightTask {
185              Id = x.TaskId,
186              ExecutionTime = TimeSpan.FromMilliseconds(x.ExecutionTimeMs),
187              ParentTaskId = x.ParentTaskId,
188              StateLog = new List<DT.StateLog>(),
189              State = x.State.ToDto(),
190              Command = x.Command.ToDto(),
191              LastTaskDataUpdate = x.JobData.LastUpdate
192            })
193            .ToList();
194        }, false, true);
195      }
196    }
197
198    public DT.TaskData GetTaskData(Guid taskId) {
199      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
200      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
201      var pm = PersistenceManager;
202      using (new PerformanceLogger("GetTaskData")) {
203        var taskDataDao = pm.TaskDataDao;
204        return pm.UseTransaction(() => taskDataDao.GetById(taskId).ToDto());
205      }
206    }
207
208    public void UpdateTask(DT.Task taskDto) {
209      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
210      AuthorizationManager.AuthorizeForTask(taskDto.Id, Permission.Full);
211      var pm = PersistenceManager;
212      using (new PerformanceLogger("UpdateTask")) {
213        var taskDao = pm.TaskDao;
214        pm.UseTransaction(() => {
215          var task = taskDao.GetById(taskDto.Id);
216          taskDto.CopyToEntity(task);
217          pm.SubmitChanges();
218        });
219      }
220    }
221
222    public void UpdateTaskData(DT.Task taskDto, DT.TaskData taskDataDto) {
223      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
224      AuthorizationManager.AuthorizeForTask(taskDto.Id, Permission.Full);
225      var pm = PersistenceManager;
226      using (new PerformanceLogger("UpdateTaskData")) {
227        var taskDao = pm.TaskDao;
228        var taskDataDao = pm.TaskDataDao;
229        pm.UseTransaction(() => {
230          var task = taskDao.GetById(taskDto.Id);
231          var taskData = taskDataDao.GetById(taskDataDto.TaskId);
232          taskDto.CopyToEntity(task);
233          taskDataDto.CopyToEntity(taskData);
234          taskData.LastUpdate = DateTime.Now;
235          pm.SubmitChanges();
236        });
237      }
238    }
239
240    public DT.Task UpdateTaskState(Guid taskId, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
241      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
242      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
243      var pm = PersistenceManager;
244      using (new PerformanceLogger("UpdateTaskState")) {
245        var taskDao = pm.TaskDao;
246        return pm.UseTransaction(() => {
247          var task = taskDao.GetById(taskId);
248          UpdateTaskState(pm, task, taskState, slaveId, userId, exception);
249          pm.SubmitChanges();
250          return task.ToDto();
251        });
252      }
253    }
254    #endregion
255
256    #region Task Control Methods
257    public void StopTask(Guid taskId) {
258      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
259      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
260      var pm = PersistenceManager;
261      using (new PerformanceLogger("StopTask")) {
262        var taskDao = pm.TaskDao;
263        pm.UseTransaction(() => {
264          var task = taskDao.GetById(taskId);
265          if (task.State == DA.TaskState.Calculating || task.State == DA.TaskState.Transferring) {
266            task.Command = DA.Command.Stop;
267          } else if (task.State != DA.TaskState.Aborted
268                     && task.State != DA.TaskState.Finished
269                     && task.State != DA.TaskState.Failed) {
270            UpdateTaskState(pm, task, DT.TaskState.Aborted, null, null, string.Empty);
271          }
272          pm.SubmitChanges();
273        });
274      }
275    }
276
277    public void PauseTask(Guid taskId) {
278      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
279      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
280      var pm = PersistenceManager;
281      using (new PerformanceLogger("PauseTask")) {
282        var taskDao = pm.TaskDao;
283        pm.UseTransaction(() => {
284          var task = taskDao.GetById(taskId);
285          if (task.State == DA.TaskState.Calculating || task.State == DA.TaskState.Transferring) {
286            task.Command = DA.Command.Pause;
287          } else if (task.State != DA.TaskState.Paused
288                     && task.State != DA.TaskState.Aborted
289                     && task.State != DA.TaskState.Finished
290                     && task.State != DA.TaskState.Failed) {
291            UpdateTaskState(pm, task, DT.TaskState.Paused, null, null, string.Empty);
292          }
293          pm.SubmitChanges();
294        });
295      }
296    }
297
298    public void RestartTask(Guid taskId) {
299      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
300      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
301      var pm = PersistenceManager;
302      using (new PerformanceLogger("RestartTask")) {
303        var taskDao = pm.TaskDao;
304        pm.UseTransaction(() => {
305          var task = taskDao.GetById(taskId);
306          task.Command = null;
307          UpdateTaskState(pm, task, DT.TaskState.Waiting, null, UserManager.CurrentUserId, string.Empty);
308          pm.SubmitChanges();
309        });
310      }
311    }
312    #endregion
313
314    #region Job Methods
315    public DT.Job GetJob(Guid id) {
316      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
317      AuthorizationManager.AuthorizeForJob(id, DT.Permission.Read);
318      var pm = PersistenceManager;
319      using (new PerformanceLogger("GetJob")) {
320        var jobDao = pm.JobDao;
321        var jobPermissionDao = pm.JobPermissionDao;
322        var taskDao = pm.TaskDao;
323        var currentUserId = UserManager.CurrentUserId;
324        return pm.UseTransaction(() => {
325          var job = jobDao.GetById(id).ToDto();
326          if (job != null) {
327            var statistics = taskDao.GetByJobId(job.Id)
328              .GroupBy(x => x.JobId)
329              .Select(x => new {
330                TotalCount = x.Count(),
331                CalculatingCount = x.Count(y => y.State == DA.TaskState.Calculating),
332                FinishedCount = x.Count(y => CompletedStates.Contains(y.State))
333              }).FirstOrDefault();
334            if (statistics != null) {
335              job.JobCount = statistics.TotalCount;
336              job.CalculatingCount = statistics.CalculatingCount;
337              job.FinishedCount = statistics.FinishedCount;
338            }
339            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
340            if (currentUserId == job.OwnerUserId) {
341              job.Permission = Permission.Full;
342            } else {
343              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
344              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
345            }
346          }
347          return job;
348        });
349      }
350    }
351
352    public IEnumerable<DT.Job> GetJobs() {
353      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
354      var pm = PersistenceManager;
355      using (new PerformanceLogger("GetJobs")) {
356        // TODO-JAN: optimization potential - avoid using too many joins in linq
357        var jobDao = pm.JobDao;
358        var jobPermissionDao = pm.JobPermissionDao;
359        var taskDao = pm.TaskDao;
360        var currentUserId = UserManager.CurrentUserId;
361        return pm.UseTransaction(() => {
362          var jobs = jobDao.GetAll()
363            .Where(x => x.OwnerUserId == currentUserId
364                     || x.JobPermissions.Count(y => y.Permission != DA.Permission.NotAllowed
365                                                 && y.GrantedUserId == currentUserId) > 0)
366            .Select(x => x.ToDto())
367            .ToList();
368          // calculate stats only for owned & permitted jobs; TODO: query only needed ones, not all
369          var statistics = taskDao.GetAll()
370              .Where(x => jobs.Select(y => y.Id).Contains(x.JobId))
371              .GroupBy(x => x.JobId)
372              .Select(x => new {
373                x.Key,
374                TotalCount = x.Count(),
375                CalculatingCount = x.Count(y => y.State == DA.TaskState.Calculating),
376                FinishedCount = x.Count(y => CompletedStates.Contains(y.State))
377              })
378              .ToList();
379          foreach (var job in jobs) {
380            var statistic = statistics.FirstOrDefault(x => x.Key == job.Id);
381            if (statistic != null) {
382              job.JobCount = statistic.TotalCount;
383              job.CalculatingCount = statistic.CalculatingCount;
384              job.FinishedCount = statistic.FinishedCount;
385            }
386            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
387            if (currentUserId == job.OwnerUserId) {
388              job.Permission = Permission.Full;
389            } else {
390              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
391              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
392            }
393          }
394          return jobs;
395        });
396      }
397    }
398
399    [Obsolete]
400    public Guid AddJob(DT.Job jobDto) {
401      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
402      var pm = PersistenceManager;
403      using (new PerformanceLogger("AddJob")) {
404        var jobDao = pm.JobDao;
405        var userPriorityDao = pm.UserPriorityDao;
406        return pm.UseTransaction(() => {
407          jobDto.OwnerUserId = UserManager.CurrentUserId;
408          jobDto.DateCreated = DateTime.Now;
409          var job = jobDao.Save(jobDto.ToEntity());
410          if (userPriorityDao.GetById(jobDto.OwnerUserId) == null) {
411            userPriorityDao.Save(new DA.UserPriority {
412              UserId = jobDto.OwnerUserId,
413              DateEnqueued = jobDto.DateCreated
414            });
415          }
416          pm.SubmitChanges();
417          return job.JobId;
418        });
419      }
420    }
421
422    public Guid AddJob(DT.Job jobDto, IEnumerable<Guid> resourceIds) {
423      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
424      // check user - project
425      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, jobDto.ProjectId);
426      // check project - resources
427      AuthorizationManager.AuthorizeProjectForResourcesUse(jobDto.ProjectId, resourceIds);
428      var pm = PersistenceManager;
429      using (new PerformanceLogger("AddJob")) {
430        var jobDao = pm.JobDao;
431        var userPriorityDao = pm.UserPriorityDao;
432
433        return pm.UseTransaction(() => {
434          var newJob = jobDto.ToEntity();
435          newJob.OwnerUserId = UserManager.CurrentUserId;
436          newJob.DateCreated = DateTime.Now;
437
438          // add resource assignments
439          newJob.AssignedJobResources.AddRange(resourceIds.Select(
440            x => new DA.AssignedJobResource {
441              ResourceId = x
442            }));
443
444          var job = jobDao.Save(newJob);
445          if (userPriorityDao.GetById(jobDto.OwnerUserId) == null) {
446            userPriorityDao.Save(new DA.UserPriority {
447              UserId = jobDto.OwnerUserId,
448              DateEnqueued = jobDto.DateCreated
449            });
450          }
451          pm.SubmitChanges();
452          return job.JobId;
453        });
454      }
455    }
456
457    public void UpdateJob(DT.Job jobDto) {
458      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
459      AuthorizationManager.AuthorizeForJob(jobDto.Id, DT.Permission.Full);
460      var pm = PersistenceManager;
461      using (new PerformanceLogger("UpdateJob")) {
462        bool exists = true;
463        var jobDao = pm.JobDao;
464        pm.UseTransaction(() => {
465          var job = jobDao.GetById(jobDto.Id);
466          if (job == null) {
467            exists = false;
468            job = new DA.Job();
469          }
470          jobDto.CopyToEntity(job);
471          if (!exists) {
472            jobDao.Save(job);
473          }
474          pm.SubmitChanges();
475        });
476      }
477    }
478
479    public void UpdateJob(DT.Job jobDto, IEnumerable<Guid> resourceIds) {
480      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
481      AuthorizationManager.AuthorizeForJob(jobDto.Id, DT.Permission.Full);
482      // check user - project permission
483      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, jobDto.ProjectId);
484      // check project - resources permission
485      AuthorizationManager.AuthorizeProjectForResourcesUse(jobDto.ProjectId, resourceIds);
486
487      var pm = PersistenceManager;
488      using (new PerformanceLogger("UpdateJob")) {
489        bool exists = true;
490        var jobDao = pm.JobDao;
491        pm.UseTransaction(() => {
492          var job = jobDao.GetById(jobDto.Id);
493          if (job == null) {
494            exists = false;
495            job = new DA.Job();
496          }
497          jobDto.CopyToEntity(job);
498
499          // remove former resource assignments
500          job.AssignedJobResources.Clear();
501          // add resource assignments
502          job.AssignedJobResources.AddRange(resourceIds.Select(
503            x => new DA.AssignedJobResource {
504              ResourceId = x
505            }));
506
507          if (!exists) {
508            jobDao.Save(job);
509          }
510          pm.SubmitChanges();
511        });
512      }
513    }
514
515    public void DeleteJob(Guid jobId) {
516      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
517      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
518      var pm = PersistenceManager;
519      using (new PerformanceLogger("DeleteJob")) {
520        var jobDao = pm.JobDao;
521        pm.UseTransaction(() => {
522          // child tasks will be deleted by db-trigger
523          // entries in AssignedJobResource will be deleted by foreign key clause CASCADE ON DELETE
524          jobDao.Delete(jobId);
525          pm.SubmitChanges();
526        });
527      }
528    }
529    #endregion
530
531    #region JobPermission Methods
532    public void GrantPermission(Guid jobId, Guid grantedUserId, DT.Permission permission) {
533      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
534      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
535      var pm = PersistenceManager;
536      using (new PerformanceLogger("GrantPermission")) {
537        var jobPermissionDao = pm.JobPermissionDao;
538        var currentUserId = UserManager.CurrentUserId;
539        pm.UseTransaction(() => {
540          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, permission.ToEntity());
541          pm.SubmitChanges();
542        });
543      }
544    }
545
546    public void RevokePermission(Guid jobId, Guid grantedUserId) {
547      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
548      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
549      var pm = PersistenceManager;
550      using (new PerformanceLogger("RevokePermission")) {
551        var jobPermissionDao = pm.JobPermissionDao;
552        var currentUserId = UserManager.CurrentUserId;
553        pm.UseTransaction(() => {
554          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, DA.Permission.NotAllowed);
555          pm.SubmitChanges();
556        });
557      }
558    }
559
560    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
561      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
562      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
563      var pm = PersistenceManager;
564      using (new PerformanceLogger("GetJobPermissions")) {
565        var jobPermissionDao = pm.JobPermissionDao;
566        return pm.UseTransaction(() => jobPermissionDao.GetByJobId(jobId)
567          .Select(x => x.ToDto())
568          .ToList()
569        );
570      }
571    }
572
573    // BackwardsCompatibility3.3
574    #region Backwards compatible code, remove with 3.4
575    public bool IsAllowedPrivileged() {
576      return true;
577    }
578    #endregion
579    #endregion
580
581    #region Login Methods
582    public void Hello(DT.Slave slaveInfo) {
583      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
584      if (UserManager.CurrentUser.UserName != "hiveslave") {
585        slaveInfo.OwnerUserId = UserManager.CurrentUserId;
586      }
587      var pm = PersistenceManager;
588      using (new PerformanceLogger("Hello")) {
589        var slaveDao = pm.SlaveDao;
590        pm.UseTransaction(() => {
591          var slave = slaveDao.GetById(slaveInfo.Id);
592          if (slave == null) {
593            slaveDao.Save(slaveInfo.ToEntity());
594          } else {
595            bool oldIsAllowedToCalculate = slave.IsAllowedToCalculate;
596            Guid? oldParentResourceId = slave.ParentResourceId;
597            slaveInfo.CopyToEntity(slave);
598            slave.IsAllowedToCalculate = oldIsAllowedToCalculate;
599            slave.ParentResourceId = oldParentResourceId;
600            slave.LastHeartbeat = DateTime.Now;
601            slave.SlaveState = DA.SlaveState.Idle;
602          }
603          pm.SubmitChanges();
604        });
605      }
606    }
607
608    public void GoodBye(Guid slaveId) {
609      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
610      var pm = PersistenceManager;
611      using (new PerformanceLogger("GoodBye")) {
612        var slaveDao = pm.SlaveDao;
613        pm.UseTransaction(() => {
614          var slave = slaveDao.GetById(slaveId);
615          if (slave != null) {
616            slave.SlaveState = DA.SlaveState.Offline;
617            pm.SubmitChanges();
618          }
619        });
620      }
621    }
622    #endregion
623
624    #region Heartbeat Methods
625    public List<MessageContainer> Heartbeat(DT.Heartbeat heartbeat) {
626      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
627      List<MessageContainer> result = new List<MessageContainer>();
628      try {
629        using (new PerformanceLogger("ProcessHeartbeat")) {
630          result = HeartbeatManager.ProcessHeartbeat(heartbeat);
631        }
632      } catch (Exception ex) {
633        DA.LogFactory.GetLogger(this.GetType().Namespace).Log(string.Format("Exception processing Heartbeat: {0}", ex));
634      }
635      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
636        TriggerEventManager(false);
637      }
638      return result;
639    }
640    #endregion
641
642    #region Plugin Methods
643    public DT.Plugin GetPlugin(Guid pluginId) {
644      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
645      var pm = PersistenceManager;
646      using (new PerformanceLogger("GetPlugin")) {
647        var pluginDao = pm.PluginDao;
648        return pm.UseTransaction(() => pluginDao.GetById(pluginId).ToDto());
649      }
650    }
651
652    public Guid AddPlugin(DT.Plugin plugin, List<DT.PluginData> pluginData) {
653      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
654      var pm = PersistenceManager;
655      using (new PerformanceLogger("AddPlugin")) {
656        var pluginDao = pm.PluginDao;
657        plugin.UserId = UserManager.CurrentUserId;
658        plugin.DateCreated = DateTime.Now;
659        return pm.UseTransaction(() => {
660          var pluginEntity = pluginDao.GetByHash(plugin.Hash).SingleOrDefault();
661          if (pluginEntity != null) {
662            throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(pluginEntity.PluginId));
663          }
664          pluginEntity = plugin.ToEntity();
665          foreach (var data in pluginData) {
666            data.PluginId = default(Guid); // real id will be assigned from linq2sql
667            pluginEntity.PluginData.Add(data.ToEntity());
668          }
669          pluginDao.Save(pluginEntity);
670          pm.SubmitChanges();
671          return pluginEntity.PluginId;
672        });
673      }
674    }
675
676    public IEnumerable<DT.Plugin> GetPlugins() {
677      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
678      var pm = PersistenceManager;
679      using (new PerformanceLogger("GetPlugins")) {
680        var pluginDao = pm.PluginDao;
681        return pm.UseTransaction(() => pluginDao.GetAll()
682          .Where(x => x.Hash != null)
683          .Select(x => x.ToDto())
684          .ToList()
685        );
686      }
687    }
688
689    public IEnumerable<DT.PluginData> GetPluginDatas(List<Guid> pluginIds) {
690      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
691      var pm = PersistenceManager;
692      using (new PerformanceLogger("GetPluginDatas")) {
693        var pluginDataDao = pm.PluginDataDao;
694        return pm.UseTransaction(() => pluginDataDao.GetAll()
695            .Where(x => pluginIds.Contains(x.PluginId))
696            .Select(x => x.ToDto())
697            .ToList()
698        );
699      }
700    }
701    #endregion
702
703    #region Project Methods
704    public Guid AddProject(DT.Project projectDto) {
705      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
706      var pm = PersistenceManager;
707      using (new PerformanceLogger("AddProject")) {
708        var projectDao = pm.ProjectDao;
709        return pm.UseTransaction(() => {
710          var project = projectDao.Save(projectDto.ToEntity());
711          pm.SubmitChanges();
712          return project.ProjectId;
713        });
714      }
715    }
716
717    public void UpdateProject(DT.Project projectDto) {
718      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
719      var pm = PersistenceManager;
720      using (new PerformanceLogger("UpdateProject")) {
721        var projectDao = pm.ProjectDao;
722        pm.UseTransaction(() => {
723          var project = projectDao.GetById(projectDto.Id);
724          if (project != null) {
725            projectDto.CopyToEntity(project);
726          } else {
727            projectDao.Save(projectDto.ToEntity());
728          }
729          pm.SubmitChanges();
730        });
731      }
732    }
733
734    public void DeleteProject(Guid projectId) {
735      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
736      var pm = PersistenceManager;
737      using (new PerformanceLogger("DeleteProject")) {
738        var projectDao = pm.ProjectDao;
739        var assignedJobResourceDao = pm.AssignedJobResourceDao;
740        pm.UseTransaction(() => {
741          assignedJobResourceDao.DeleteByProjectId(projectId);
742          projectDao.Delete(projectId);
743          pm.SubmitChanges();
744        });
745      }
746    }
747
748    public DT.Project GetProject(Guid projectId) {
749      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
750      var pm = PersistenceManager;
751      using (new PerformanceLogger("GetProject")) {
752        var projectDao = pm.ProjectDao;
753        return pm.UseTransaction(() => projectDao.GetById(projectId).ToDto());
754      }
755    }
756
757    // query granted projects for use (i.e. to calculate on)
758    public IEnumerable<DT.Project> GetProjects() {
759      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
760      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
761      var pm = PersistenceManager;
762      using (new PerformanceLogger("GetProjects")) {
763        var projectDao = pm.ProjectDao;
764        var projectPermissionDao = pm.ProjectPermissionDao;
765        var currentUserId = UserManager.CurrentUserId;
766        return pm.UseTransaction(() => {
767          var userAndGroupIds = new List<Guid> { currentUserId };
768          userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
769          return projectDao.GetGrantedProjectsForUser(userAndGroupIds)
770            .Select(x => x.ToDto());
771          //var projectPermissions = projectPermissionDao.GetAll();
772          //return projectDao.GetAll().ToList()
773          //  .Where(x => isAdministrator
774          //    || x.OwnerUserId == currentUserId
775          //    || UserManager.VerifyUser(currentUserId, projectPermissions
776          //        .Where(y => y.ProjectId == x.ProjectId)
777          //        .Select(z => z.GrantedUserId)
778          //        .ToList())
779          //    )
780          //  .Select(x => x.ToDto())
781          //  .ToList();
782        });
783      }
784    }
785    #endregion
786
787    #region ProjectPermission Methods
788    public void GrantProjectPermissions(Guid projectId, Guid[] grantedUserIds, bool cascading) {
789      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
790      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
791      var pm = PersistenceManager;
792      using (new PerformanceLogger("GrantProjectPermissions")) {
793        var projectDao = pm.ProjectDao;
794
795        pm.UseTransaction(() => {
796          var project = projectDao.GetById(projectId);
797          var projectPermissions = project.ProjectPermissions.ToList();
798          foreach (var id in grantedUserIds) {
799            if (projectPermissions.All(x => x.GrantedUserId != id)) {
800              project.ProjectPermissions.Add(new DA.ProjectPermission {
801                GrantedUserId = id,
802                GrantedByUserId = UserManager.CurrentUserId
803              });
804            }
805          }
806          if (cascading) {
807            var childProjects = projectDao.GetChildProjectsById(projectId);
808            foreach (var p in childProjects) {
809              p.ProjectPermissions.Clear();
810              foreach (var id in grantedUserIds) {
811                p.ProjectPermissions.Add(new DA.ProjectPermission {
812                  GrantedUserId = id,
813                  GrantedByUserId = UserManager.CurrentUserId
814                });
815              }
816            }
817          }
818          pm.SubmitChanges();
819        });
820      }
821    }
822
823    public void RevokeProjectPermissions(Guid projectId, Guid[] grantedUserIds, bool cascading) {
824      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
825      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
826      var pm = PersistenceManager;
827      using (new PerformanceLogger("RevokeProjectPermissions")) {
828        var projectPermissionDao = pm.ProjectPermissionDao;
829        var projectDao = pm.ProjectDao;
830        var assignedJobResourceDao = pm.AssignedJobResourceDao;
831        pm.UseTransaction(() => {
832          if (cascading) {
833            var childProjectIds = projectDao.GetChildProjectIdsById(projectId);
834            projectPermissionDao.DeleteByProjectIdsAndGrantedUserIds(childProjectIds, grantedUserIds);
835            assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, grantedUserIds);
836          }
837          projectPermissionDao.DeleteByProjectIdAndGrantedUserIds(projectId, grantedUserIds);
838          assignedJobResourceDao.DeleteByProjectIdAndUserIds(projectId, grantedUserIds);
839          pm.SubmitChanges();
840        });
841      }
842    }
843
844    public IEnumerable<DT.ProjectPermission> GetProjectPermissions(Guid projectId) {
845      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
846      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
847      var pm = PersistenceManager;
848      using (new PerformanceLogger("GetProjectPermissions")) {
849        var projectPermissionDao = pm.ProjectPermissionDao;
850        return pm.UseTransaction(() => projectPermissionDao.GetByProjectId(projectId)
851          .Select(x => x.ToDto())
852          .ToList()
853        );
854      }
855    }
856    #endregion
857
858    #region AssignedProjectResource Methods
859    public void AssignProjectResources(Guid projectId, Guid[] resourceIds, bool cascading) {
860      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
861      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
862      var pm = PersistenceManager;
863      using (new PerformanceLogger("AssignProjectResources")) {
864        var projectDao = pm.ProjectDao;
865        pm.UseTransaction(() => {
866          var project = projectDao.GetById(projectId);
867          var assignedProjectResources = project.AssignedProjectResources.ToList();
868
869          foreach (var id in resourceIds) {
870            if (assignedProjectResources.All(x => x.ResourceId != id)) {
871              project.AssignedProjectResources.Add(new DA.AssignedProjectResource {
872                ResourceId = id
873              });
874            }
875          }
876          if (cascading) {
877            var childProjects = projectDao.GetChildProjectsById(projectId);
878            foreach (var p in childProjects) {
879              p.AssignedProjectResources.Clear();
880              foreach (var id in resourceIds) {
881                p.AssignedProjectResources.Add(new DA.AssignedProjectResource {
882                  ResourceId = id
883                });
884              }
885            }
886          }
887          pm.SubmitChanges();
888        });
889      }
890    }
891
892    public void UnassignProjectResources(Guid projectId, Guid[] resourceIds, bool cascading) {
893      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
894      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
895      var pm = PersistenceManager;
896      using (new PerformanceLogger("UnassignProjectResources")) {
897        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
898        var assignedJobResourceDao = pm.AssignedJobResourceDao;
899        var projectDao = pm.ProjectDao;
900        pm.UseTransaction(() => {
901          if (cascading) {
902            var childProjectIds = projectDao.GetChildProjectIdsById(projectId);
903            assignedProjectResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
904            assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
905          }
906          assignedProjectResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
907          assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
908          pm.SubmitChanges();
909        });
910      }
911    }
912
913    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProject(Guid projectId) {
914      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
915      var pm = PersistenceManager;
916      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
917        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
918        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
919          .Select(x => x.ToDto())
920          .ToList()
921        );
922      }
923    }
924
925    #endregion
926
927    #region Slave Methods
928    public Guid AddSlave(DT.Slave slaveDto) {
929      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
930      var pm = PersistenceManager;
931      using (new PerformanceLogger("AddSlave")) {
932        var slaveDao = pm.SlaveDao;
933        return pm.UseTransaction(() => {
934          var slave = slaveDao.Save(slaveDto.ToEntity());
935          pm.SubmitChanges();
936          return slave.ResourceId;
937        });
938      }
939    }
940
941    public Guid AddSlaveGroup(DT.SlaveGroup slaveGroupDto) {
942      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
943      var pm = PersistenceManager;
944      using (new PerformanceLogger("AddSlaveGroup")) {
945        var slaveGroupDao = pm.SlaveGroupDao;
946        return pm.UseTransaction(() => {
947          if (slaveGroupDto.Id == Guid.Empty) {
948            slaveGroupDto.Id = Guid.NewGuid();
949          }
950          var slaveGroup = slaveGroupDao.Save(slaveGroupDto.ToEntity());
951          pm.SubmitChanges();
952          return slaveGroup.ResourceId;
953        });
954      }
955    }
956
957    public DT.Slave GetSlave(Guid slaveId) {
958      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
959      var pm = PersistenceManager;
960      using (new PerformanceLogger("GetSlave")) {
961        var slaveDao = pm.SlaveDao;
962        return pm.UseTransaction(() => slaveDao.GetById(slaveId).ToDto());
963      }
964    }
965
966    public IEnumerable<DT.Slave> GetSlaves() {
967      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
968      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
969      var pm = PersistenceManager;
970      using (new PerformanceLogger("GetSlaves")) {
971        var slaveDao = pm.SlaveDao;
972        var resourcePermissionDao = pm.ProjectPermissionDao;
973        var currentUserId = UserManager.CurrentUserId;
974        return pm.UseTransaction(() => {
975          var resourcePermissions = resourcePermissionDao.GetAll();
976          return slaveDao.GetAll().ToList()
977            .Where(x => isAdministrator
978              || x.OwnerUserId == null
979              || x.OwnerUserId == currentUserId
980              || UserManager.VerifyUser(currentUserId, resourcePermissions
981                  //.Where(y => y.ResourceId == x.ResourceId)
982                  .Select(z => z.GrantedUserId)
983                  .ToList())
984              )
985            .Select(x => x.ToDto())
986            .ToList();
987        });
988      }
989    }
990
991    public IEnumerable<DT.SlaveGroup> GetSlaveGroups() {
992      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
993      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
994      var pm = PersistenceManager;
995      using (new PerformanceLogger("GetSlaveGroups")) {
996        var slaveGroupDao = pm.SlaveGroupDao;
997        var resourcePermissionDao = pm.ProjectPermissionDao;
998        var currentUserId = UserManager.CurrentUserId;
999        return pm.UseTransaction(() => {
1000          var resourcePermissions = resourcePermissionDao.GetAll();
1001          return slaveGroupDao.GetAll().ToList()
1002            .Where(x => isAdministrator
1003              || x.OwnerUserId == null
1004              || x.OwnerUserId == currentUserId
1005              || UserManager.VerifyUser(currentUserId, resourcePermissions
1006                  //.Where(y => y.ResourceId == x.ResourceId)
1007                  .Select(z => z.GrantedUserId)
1008                  .ToList())
1009              )
1010            .Select(x => x.ToDto())
1011            .ToList();
1012        });
1013      }
1014    }
1015
1016    public void UpdateSlave(DT.Slave slaveDto) {
1017      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1018      var pm = PersistenceManager;
1019      using (new PerformanceLogger("UpdateSlave")) {
1020        var slaveDao = pm.SlaveDao;
1021        pm.UseTransaction(() => {
1022          var slave = slaveDao.GetById(slaveDto.Id);
1023          if (slave != null) {
1024            slaveDto.CopyToEntity(slave);
1025          } else {
1026            slaveDao.Save(slaveDto.ToEntity());
1027          }
1028          pm.SubmitChanges();
1029        });
1030      }
1031    }
1032
1033    public void UpdateSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1034      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1035      var pm = PersistenceManager;
1036      using (new PerformanceLogger("UpdateSlaveGroup")) {
1037        var slaveGroupDao = pm.SlaveGroupDao;
1038        pm.UseTransaction(() => {
1039          var slaveGroup = slaveGroupDao.GetById(slaveGroupDto.Id);
1040          if (slaveGroup != null) {
1041            slaveGroupDto.CopyToEntity(slaveGroup);
1042          } else {
1043            slaveGroupDao.Save(slaveGroupDto.ToEntity());
1044          }
1045          pm.SubmitChanges();
1046        });
1047      }
1048    }
1049
1050    public void DeleteSlave(Guid slaveId) {
1051      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1052      AuthorizationManager.AuthorizeForResourceAdministration(slaveId);
1053      var pm = PersistenceManager;
1054      using (new PerformanceLogger("DeleteSlave")) {
1055        var slaveDao = pm.SlaveDao;
1056        pm.UseTransaction(() => {
1057          slaveDao.Delete(slaveId);
1058          pm.SubmitChanges();
1059        });
1060      }
1061    }
1062
1063    public void DeleteSlaveGroup(Guid slaveGroupId) {
1064      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1065      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupId);
1066      var pm = PersistenceManager;
1067      using (new PerformanceLogger("DeleteSlaveGroup")) {
1068        var slaveGroupDao = pm.SlaveGroupDao;
1069        pm.UseTransaction(() => {
1070          slaveGroupDao.Delete(slaveGroupId);
1071          pm.SubmitChanges();
1072        });
1073      }
1074    }
1075
1076    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
1077      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1078      var pm = PersistenceManager;
1079      using (new PerformanceLogger("AddResourceToGroup")) {
1080        var resourceDao = pm.ResourceDao;
1081        pm.UseTransaction(() => {
1082          var resource = resourceDao.GetById(resourceId);
1083          resource.ParentResourceId = slaveGroupId;
1084          pm.SubmitChanges();
1085        });
1086      }
1087    }
1088
1089    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
1090      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1091      var pm = PersistenceManager;
1092      using (new PerformanceLogger("RemoveResourceFromGroup")) {
1093        var resourceDao = pm.ResourceDao;
1094        pm.UseTransaction(() => {
1095          var resource = resourceDao.GetById(resourceId);
1096          resource.ParentResourceId = null;
1097          pm.SubmitChanges();
1098        });
1099      }
1100    }
1101
1102    public Guid GetResourceId(string resourceName) {
1103      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1104      var pm = PersistenceManager;
1105      using (new PerformanceLogger("GetResourceId")) {
1106        var resourceDao = pm.ResourceDao;
1107        return pm.UseTransaction(() => {
1108          var resource = resourceDao.GetByName(resourceName);
1109          return resource != null ? resource.ResourceId : Guid.Empty;
1110        });
1111      }
1112    }
1113
1114    public void TriggerEventManager(bool force) {
1115      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1116      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
1117      bool cleanup;
1118      var pm = PersistenceManager;
1119      using (new PerformanceLogger("TriggerEventManager")) {
1120        cleanup = false;
1121        var lifecycleDao = pm.LifecycleDao;
1122        pm.UseTransaction(() => {
1123          var lastLifecycle = lifecycleDao.GetLastLifecycle();
1124          DateTime lastCleanup = lastLifecycle != null ? lastLifecycle.LastCleanup : DateTime.MinValue;
1125          if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
1126            lifecycleDao.UpdateLifecycle();
1127            cleanup = true;
1128            pm.SubmitChanges();
1129          }
1130        }, true);
1131      }
1132      if (cleanup) {
1133        EventManager.Cleanup();
1134      }
1135    }
1136
1137    public int GetNewHeartbeatInterval(Guid slaveId) {
1138      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
1139      var pm = PersistenceManager;
1140      using (new PerformanceLogger("GetNewHeartbeatInterval")) {
1141        var slaveDao = pm.SlaveDao;
1142        return pm.UseTransaction(() => {
1143          var slave = slaveDao.GetById(slaveId);
1144          if (slave != null) {
1145            return slave.HbInterval;
1146          }
1147          return -1;
1148        });
1149      }
1150    }
1151    #endregion
1152
1153    #region Downtime Methods
1154    public Guid AddDowntime(DT.Downtime downtimeDto) {
1155      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1156      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1157      var pm = PersistenceManager;
1158      using (new PerformanceLogger("AddDowntime")) {
1159        var downtimeDao = pm.DowntimeDao;
1160        return pm.UseTransaction(() => {
1161          var downtime = downtimeDao.Save(downtimeDto.ToEntity());
1162          pm.SubmitChanges();
1163          return downtime.ResourceId;
1164        });
1165      }
1166    }
1167
1168    public void DeleteDowntime(Guid downtimeId) {
1169      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1170      var pm = PersistenceManager;
1171      using (new PerformanceLogger("DeleteDowntime")) {
1172        var downtimeDao = pm.DowntimeDao;
1173        pm.UseTransaction(() => {
1174          downtimeDao.Delete(downtimeId);
1175          pm.SubmitChanges();
1176        });
1177      }
1178    }
1179
1180    public void UpdateDowntime(DT.Downtime downtimeDto) {
1181      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1182      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1183      var pm = PersistenceManager;
1184      using (new PerformanceLogger("UpdateDowntime")) {
1185        var downtimeDao = pm.DowntimeDao;
1186        pm.UseTransaction(() => {
1187          var downtime = downtimeDao.GetById(downtimeDto.Id);
1188          if (downtime != null) {
1189            downtimeDto.CopyToEntity(downtime);
1190          } else {
1191            downtimeDao.Save(downtimeDto.ToEntity());
1192          }
1193          pm.SubmitChanges();
1194        });
1195      }
1196    }
1197
1198    public IEnumerable<DT.Downtime> GetDowntimesForResource(Guid resourceId) {
1199      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1200      var pm = PersistenceManager;
1201      using (new PerformanceLogger("GetDowntimesForResource")) {
1202        var downtimeDao = pm.DowntimeDao;
1203        return pm.UseTransaction(() => downtimeDao.GetByResourceId(resourceId)
1204          .Select(x => x.ToDto())
1205          .ToList()
1206        );
1207      }
1208    }
1209    #endregion
1210
1211    #region User Methods
1212    public string GetUsernameByUserId(Guid userId) {
1213      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1214      var user = UserManager.GetUserById(userId);
1215      return user != null ? user.UserName : null;
1216    }
1217
1218    public Guid GetUserIdByUsername(string username) {
1219      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1220      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
1221      return user != null ? (Guid?)user.ProviderUserKey ?? Guid.Empty : Guid.Empty;
1222    }
1223    #endregion
1224
1225    #region UserPriorities Methods
1226    public IEnumerable<DT.UserPriority> GetUserPriorities() {
1227      var pm = PersistenceManager;
1228      using (new PerformanceLogger("GetUserPriorities")) {
1229        var userPriorityDao = pm.UserPriorityDao;
1230        return pm.UseTransaction(() => userPriorityDao.GetAll()
1231          .Select(x => x.ToDto())
1232          .ToList()
1233        );
1234      }
1235    }
1236    #endregion
1237
1238    #region Private Helper Methods
1239    private void UpdateTaskState(IPersistenceManager pm, DA.Task task, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
1240      var stateLogDao = pm.StateLogDao;
1241      var taskStateEntity = taskState.ToEntity();
1242
1243      if (task.State == DA.TaskState.Transferring && taskStateEntity == DA.TaskState.Paused && task.Command == null) {
1244        // slave paused and uploaded the task (no user-command) -> set waiting.
1245        taskStateEntity = DA.TaskState.Waiting;
1246      }
1247
1248      stateLogDao.Save(new DA.StateLog {
1249        State = taskStateEntity,
1250        DateTime = DateTime.Now,
1251        TaskId = task.TaskId,
1252        UserId = userId,
1253        SlaveId = slaveId,
1254        Exception = exception
1255      });
1256
1257      task.State = taskStateEntity;
1258
1259      if (task.Command == DA.Command.Pause && task.State == DA.TaskState.Paused
1260          || task.Command == DA.Command.Abort && task.State == DA.TaskState.Aborted
1261          || task.Command == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
1262        task.Command = null;
1263      }
1264    }
1265
1266    #endregion
1267  }
1268}
Note: See TracBrowser for help on using the repository browser.