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

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

#2839

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