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

Last change on this file since 15643 was 15643, checked in by jzenisek, 3 years ago

#2839

  • worked on UpdateJob(..)
  • adapted permission and assignment handling methods
  • adpated dbml of HiveDataContext using the designer (added delete rules and onNull-handling)
File size: 60.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   
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.State == DA.JobState.Online
364                          && (x.OwnerUserId == currentUserId
365                            || x.JobPermissions.Count(y => y.Permission != DA.Permission.NotAllowed
366                              && y.GrantedUserId == currentUserId) > 0)
367                          )
368            .Select(x => x.ToDto())
369            .ToList();
370          // calculate stats only for owned & permitted jobs; TODO: query only needed ones, not all
371          var statistics = taskDao.GetAll()
372              .Where(x => jobs.Select(y => y.Id).Contains(x.JobId))
373              .GroupBy(x => x.JobId)
374              .Select(x => new {
375                x.Key,
376                TotalCount = x.Count(),
377                CalculatingCount = x.Count(y => y.State == DA.TaskState.Calculating),
378                FinishedCount = x.Count(y => CompletedStates.Contains(y.State))
379              })
380              .ToList();
381          foreach (var job in jobs) {
382            var statistic = statistics.FirstOrDefault(x => x.Key == job.Id);
383            if (statistic != null) {
384              job.JobCount = statistic.TotalCount;
385              job.CalculatingCount = statistic.CalculatingCount;
386              job.FinishedCount = statistic.FinishedCount;
387            }
388            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
389            if (currentUserId == job.OwnerUserId) {
390              job.Permission = Permission.Full;
391            } else {
392              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
393              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
394            }
395          }
396          return jobs;
397        });
398      }
399    }
400
401    public Guid AddJob(DT.Job jobDto) {
402      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
403      var pm = PersistenceManager;
404      using (new PerformanceLogger("AddJob")) {
405        var jobDao = pm.JobDao;
406        var userPriorityDao = pm.UserPriorityDao;
407        return pm.UseTransaction(() => {
408          jobDto.OwnerUserId = UserManager.CurrentUserId;
409          jobDto.DateCreated = DateTime.Now;
410          var job = jobDao.Save(jobDto.ToEntity());
411          if (userPriorityDao.GetById(jobDto.OwnerUserId) == null) {
412            userPriorityDao.Save(new DA.UserPriority {
413              UserId = jobDto.OwnerUserId,
414              DateEnqueued = jobDto.DateCreated
415            });
416          }
417          pm.SubmitChanges();
418          return job.JobId;
419        });
420      }
421    }
422
423    public Guid AddJob(DT.Job jobDto, IEnumerable<Guid> resourceIds) {
424      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
425      // check user - project
426      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, jobDto.ProjectId);
427      // check project - resources
428      AuthorizationManager.AuthorizeProjectForResourcesUse(jobDto.ProjectId, resourceIds);
429      var pm = PersistenceManager;
430      using (new PerformanceLogger("AddJob")) {
431        var jobDao = pm.JobDao;
432        var userPriorityDao = pm.UserPriorityDao;
433
434        return pm.UseTransaction(() => {
435          var newJob = jobDto.ToEntity();
436          newJob.OwnerUserId = UserManager.CurrentUserId;
437          newJob.DateCreated = DateTime.Now;
438
439          // add resource assignments
440          newJob.AssignedJobResources.AddRange(resourceIds.Select(
441            x => new DA.AssignedJobResource {
442              ResourceId = x
443            }));
444
445          var job = jobDao.Save(newJob);
446          if (userPriorityDao.GetById(jobDto.OwnerUserId) == null) {
447            userPriorityDao.Save(new DA.UserPriority {
448              UserId = jobDto.OwnerUserId,
449              DateEnqueued = jobDto.DateCreated
450            });
451          }
452          pm.SubmitChanges();
453          return job.JobId;
454        });
455      }
456    }
457
458    public void UpdateJob(DT.Job jobDto) {
459      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
460      AuthorizationManager.AuthorizeForJob(jobDto.Id, DT.Permission.Full);
461      var pm = PersistenceManager;
462      using (new PerformanceLogger("UpdateJob")) {
463        bool exists = true;
464        var jobDao = pm.JobDao;
465        pm.UseTransaction(() => {
466          var job = jobDao.GetById(jobDto.Id);
467          if (job == null) {
468            exists = false;
469            job = new DA.Job();
470          }
471          jobDto.CopyToEntity(job);
472          if (!exists) {
473            jobDao.Save(job);
474          }
475          pm.SubmitChanges();
476        });
477      }
478    }
479
480    public void UpdateJob(DT.Job jobDto, IEnumerable<Guid> resourceIds) {
481      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
482      AuthorizationManager.AuthorizeForJob(jobDto.Id, DT.Permission.Full);
483      // check user - project permission
484      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, jobDto.ProjectId);
485      // check project - resources permission
486      AuthorizationManager.AuthorizeProjectForResourcesUse(jobDto.ProjectId, resourceIds);
487
488      var pm = PersistenceManager;
489      using (new PerformanceLogger("UpdateJob")) {
490        bool exists = true;
491        var jobDao = pm.JobDao;
492        pm.UseTransaction(() => {
493          var job = jobDao.GetById(jobDto.Id);
494          if (job == null) {
495            exists = false;
496            job = new DA.Job();
497          }
498          jobDto.CopyToEntity(job);
499
500          if (!exists) {
501            // add resource assignments
502            job.AssignedJobResources.AddRange(resourceIds.Select(
503              x => new DA.AssignedJobResource {
504                ResourceId = x
505              }));
506            jobDao.Save(job);
507          } else {
508            var addedJobResourceIds = resourceIds.Except(job.AssignedJobResources.Select(x => x.ResourceId));
509            var removedJobResourceIds = job.AssignedJobResources
510              .Select(x => x.ResourceId)
511              .Except(resourceIds)
512              .ToArray();
513           
514            // remove resource assignments
515            foreach(var rid in removedJobResourceIds) {
516              var ajr = job.AssignedJobResources.Where(x => x.ResourceId == rid).SingleOrDefault();
517              if (ajr != null) job.AssignedJobResources.Remove(ajr);
518            }
519
520            // add resource assignments
521            job.AssignedJobResources.AddRange(addedJobResourceIds.Select(
522              x => new DA.AssignedJobResource {
523                ResourceId = x
524              }));
525          }
526          pm.SubmitChanges();
527        });
528      }
529    }
530
531    public void UpdateJobState(Guid jobId, DT.JobState jobState) {
532      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
533      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
534      var pm = PersistenceManager;
535      using (new PerformanceLogger("UpdateJobState")) {
536        var jobDao = pm.JobDao;
537        pm.UseTransaction(() => {
538          var job = jobDao.GetById(jobId);
539          if(job != null) {
540            var jobStateEntity = jobState.ToEntity();
541            // note: allow solely state changes from "Online" to "StatisticsPending"
542            // and from "StatisticsPending" to "DeletionPending"
543            if (job.State == DA.JobState.Online && jobStateEntity == DA.JobState.StatisticsPending) {
544              job.State = jobStateEntity;
545              foreach(var task in job.Tasks
546              .Where(x => x.State == DA.TaskState.Waiting
547                || x.State == DA.TaskState.Paused
548                || x.State == DA.TaskState.Offline)) {
549                task.State = DA.TaskState.Aborted;
550              }
551              pm.SubmitChanges();
552            } else if(job.State == DA.JobState.StatisticsPending && jobStateEntity == DA.JobState.DeletionPending) {
553              job.State = jobStateEntity;
554              pm.SubmitChanges();
555            }
556          }
557        });
558      }
559    }
560
561    public IEnumerable<DT.AssignedJobResource> GetAssignedResourcesForJob(Guid jobId) {
562      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
563      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
564      var pm = PersistenceManager;
565      var assignedJobResourceDao = pm.AssignedJobResourceDao;
566      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
567        return pm.UseTransaction(() =>
568          assignedJobResourceDao.GetByJobId(jobId)
569          .Select(x => x.ToDto())
570          .ToList()
571        );
572      }
573    }
574    #endregion
575
576    #region JobPermission Methods
577    public void GrantPermission(Guid jobId, Guid grantedUserId, DT.Permission permission) {
578      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
579      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
580      var pm = PersistenceManager;
581      using (new PerformanceLogger("GrantPermission")) {
582        var jobPermissionDao = pm.JobPermissionDao;
583        var currentUserId = UserManager.CurrentUserId;
584        pm.UseTransaction(() => {
585          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, permission.ToEntity());
586          pm.SubmitChanges();
587        });
588      }
589    }
590
591    public void RevokePermission(Guid jobId, Guid grantedUserId) {
592      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
593      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
594      var pm = PersistenceManager;
595      using (new PerformanceLogger("RevokePermission")) {
596        var jobPermissionDao = pm.JobPermissionDao;
597        var currentUserId = UserManager.CurrentUserId;
598        pm.UseTransaction(() => {
599          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, DA.Permission.NotAllowed);
600          pm.SubmitChanges();
601        });
602      }
603    }
604
605    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
606      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
607      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
608      var pm = PersistenceManager;
609      using (new PerformanceLogger("GetJobPermissions")) {
610        var jobPermissionDao = pm.JobPermissionDao;
611        return pm.UseTransaction(() => jobPermissionDao.GetByJobId(jobId)
612          .Select(x => x.ToDto())
613          .ToList()
614        );
615      }
616    }
617
618    // BackwardsCompatibility3.3
619    #region Backwards compatible code, remove with 3.4
620    public bool IsAllowedPrivileged() {
621      return true;
622    }
623    #endregion
624    #endregion
625
626    #region Login Methods
627    public void Hello(DT.Slave slaveInfo) {
628      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
629      if (UserManager.CurrentUser.UserName != "hiveslave") {
630        slaveInfo.OwnerUserId = UserManager.CurrentUserId;
631      }
632      var pm = PersistenceManager;
633      using (new PerformanceLogger("Hello")) {
634        var slaveDao = pm.SlaveDao;
635        pm.UseTransaction(() => {
636          var slave = slaveDao.GetById(slaveInfo.Id);
637          if (slave == null) {
638            slaveDao.Save(slaveInfo.ToEntity());
639          } else {
640            bool oldIsAllowedToCalculate = slave.IsAllowedToCalculate;
641            Guid? oldParentResourceId = slave.ParentResourceId;
642            slaveInfo.CopyToEntity(slave);
643            slave.IsAllowedToCalculate = oldIsAllowedToCalculate;
644            slave.ParentResourceId = oldParentResourceId;
645            slave.LastHeartbeat = DateTime.Now;
646            slave.SlaveState = DA.SlaveState.Idle;
647          }
648          pm.SubmitChanges();
649        });
650      }
651    }
652
653    public void GoodBye(Guid slaveId) {
654      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
655      var pm = PersistenceManager;
656      using (new PerformanceLogger("GoodBye")) {
657        var slaveDao = pm.SlaveDao;
658        pm.UseTransaction(() => {
659          var slave = slaveDao.GetById(slaveId);
660          if (slave != null) {
661            slave.SlaveState = DA.SlaveState.Offline;
662            pm.SubmitChanges();
663          }
664        });
665      }
666    }
667    #endregion
668
669    #region Heartbeat Methods
670    public List<MessageContainer> Heartbeat(DT.Heartbeat heartbeat) {
671      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
672      List<MessageContainer> result = new List<MessageContainer>();
673      try {
674        using (new PerformanceLogger("ProcessHeartbeat")) {
675          result = HeartbeatManager.ProcessHeartbeat(heartbeat);
676        }
677      } catch (Exception ex) {
678        DA.LogFactory.GetLogger(this.GetType().Namespace).Log(string.Format("Exception processing Heartbeat: {0}", ex));
679      }
680      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
681        TriggerEventManager(false);
682      }
683      return result;
684    }
685    #endregion
686
687    #region Plugin Methods
688    public DT.Plugin GetPlugin(Guid pluginId) {
689      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
690      var pm = PersistenceManager;
691      using (new PerformanceLogger("GetPlugin")) {
692        var pluginDao = pm.PluginDao;
693        return pm.UseTransaction(() => pluginDao.GetById(pluginId).ToDto());
694      }
695    }
696
697    public Guid AddPlugin(DT.Plugin plugin, List<DT.PluginData> pluginData) {
698      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
699      var pm = PersistenceManager;
700      using (new PerformanceLogger("AddPlugin")) {
701        var pluginDao = pm.PluginDao;
702        plugin.UserId = UserManager.CurrentUserId;
703        plugin.DateCreated = DateTime.Now;
704        return pm.UseTransaction(() => {
705          var pluginEntity = pluginDao.GetByHash(plugin.Hash).SingleOrDefault();
706          if (pluginEntity != null) {
707            throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(pluginEntity.PluginId));
708          }
709          pluginEntity = plugin.ToEntity();
710          foreach (var data in pluginData) {
711            data.PluginId = default(Guid); // real id will be assigned from linq2sql
712            pluginEntity.PluginData.Add(data.ToEntity());
713          }
714          pluginDao.Save(pluginEntity);
715          pm.SubmitChanges();
716          return pluginEntity.PluginId;
717        });
718      }
719    }
720
721    public IEnumerable<DT.Plugin> GetPlugins() {
722      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
723      var pm = PersistenceManager;
724      using (new PerformanceLogger("GetPlugins")) {
725        var pluginDao = pm.PluginDao;
726        return pm.UseTransaction(() => pluginDao.GetAll()
727          .Where(x => x.Hash != null)
728          .Select(x => x.ToDto())
729          .ToList()
730        );
731      }
732    }
733
734    public IEnumerable<DT.PluginData> GetPluginDatas(List<Guid> pluginIds) {
735      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
736      var pm = PersistenceManager;
737      using (new PerformanceLogger("GetPluginDatas")) {
738        var pluginDataDao = pm.PluginDataDao;
739        return pm.UseTransaction(() => pluginDataDao.GetAll()
740            .Where(x => pluginIds.Contains(x.PluginId))
741            .Select(x => x.ToDto())
742            .ToList()
743        );
744      }
745    }
746    #endregion
747
748    #region Project Methods
749    public Guid AddProject(DT.Project projectDto) {
750      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
751      var pm = PersistenceManager;
752      using (new PerformanceLogger("AddProject")) {
753        var projectDao = pm.ProjectDao;
754        return pm.UseTransaction(() => {
755          var project = projectDao.Save(projectDto.ToEntity());
756          pm.SubmitChanges();
757          return project.ProjectId;
758        });
759      }
760    }
761
762    public void UpdateProject(DT.Project projectDto) {
763      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
764      var pm = PersistenceManager;
765      using (new PerformanceLogger("UpdateProject")) {
766        var projectDao = pm.ProjectDao;
767        pm.UseTransaction(() => {
768          var project = projectDao.GetById(projectDto.Id);
769          if (project != null) {
770            projectDto.CopyToEntity(project);
771          } else {
772            projectDao.Save(projectDto.ToEntity());
773          }
774          pm.SubmitChanges();
775        });
776      }
777    }
778
779    public void DeleteProject(Guid projectId) {
780      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
781      var pm = PersistenceManager;
782      using (new PerformanceLogger("DeleteProject")) {
783        var projectDao = pm.ProjectDao;
784        var assignedJobResourceDao = pm.AssignedJobResourceDao;
785        pm.UseTransaction(() => {
786          assignedJobResourceDao.DeleteByProjectId(projectId);
787          projectDao.Delete(projectId);
788          pm.SubmitChanges();
789        });
790      }
791    }
792
793    public DT.Project GetProject(Guid projectId) {
794      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
795      var pm = PersistenceManager;
796      using (new PerformanceLogger("GetProject")) {
797        var projectDao = pm.ProjectDao;
798        return pm.UseTransaction(() => projectDao.GetById(projectId).ToDto());
799      }
800    }
801
802    // query granted projects for use (i.e. to calculate on)
803    public IEnumerable<DT.Project> GetProjects() {
804      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
805      //bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
806      var pm = PersistenceManager;
807      using (new PerformanceLogger("GetProjects")) {
808        var projectDao = pm.ProjectDao;
809        //var projectPermissionDao = pm.ProjectPermissionDao;
810        var currentUserId = UserManager.CurrentUserId;
811        var userAndGroupIds = new List<Guid> { currentUserId };
812        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
813        return pm.UseTransaction(() => {
814          return projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
815            .Select(x => x.ToDto()).ToList();
816        });
817      }
818    }
819
820    public IEnumerable<DT.Project> GetProjectsForAdministration() {
821      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
822      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
823      var pm = PersistenceManager;
824      using (new PerformanceLogger("GetProjectsForAdministration")) {
825        var projectDao = pm.ProjectDao;
826        //var projectPermissionDao = pm.ProjectPermissionDao;
827       
828        return pm.UseTransaction(() => {
829          if(isAdministrator) {
830            return projectDao.GetAll().Select(x => x.ToDto()).ToList();
831          } else {
832            var currentUserId = UserManager.CurrentUserId;
833            return projectDao.GetAdministrationGrantedProjectsForUser(currentUserId)
834              .Select(x => x.ToDto()).ToList();
835
836          }
837
838          //var projectPermissions = projectPermissionDao.GetAll();
839          //return projectDao.GetAll().ToList()
840          //  .Where(x => isAdministrator
841          //    || x.OwnerUserId == currentUserId
842          //    || UserManager.VerifyUser(currentUserId, projectPermissions
843          //        .Where(y => y.ProjectId == x.ProjectId)
844          //        .Select(z => z.GrantedUserId)
845          //        .ToList())
846          //    )
847          //  .Select(x => x.ToDto())
848          //  .ToList();
849        });
850      }
851    }
852    #endregion
853
854    #region ProjectPermission Methods
855    public void SaveProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool reassign, bool cascading, bool reassignCascading) {
856      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
857      if (projectId == null || grantedUserIds == null) return;
858      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
859      var pm = PersistenceManager;
860      using (new PerformanceLogger("SaveProjectPermissions")) {
861        var projectDao = pm.ProjectDao;
862        var projectPermissionDao = pm.ProjectPermissionDao;
863        var assignedJobResourceDao = pm.AssignedJobResourceDao;
864
865        pm.UseTransaction(() => {
866          var project = projectDao.GetById(projectId);
867          if (project == null) return;
868          var projectPermissions = project.ProjectPermissions.Select(x => x.GrantedUserId).ToArray();
869          //var addedPermissions = grantedUserIds.Except(projectPermissions);
870          var removedPermissions = projectPermissions.Except(grantedUserIds);
871
872          // remove job assignments and project permissions
873          if (reassign) {
874            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
875            project.ProjectPermissions.Clear();
876          } else {
877            assignedJobResourceDao.DeleteByProjectIdAndUserIds(project.ProjectId, removedPermissions);
878            foreach(var item in project.ProjectPermissions
879              .Where(x => removedPermissions.Contains(x.GrantedUserId))
880              .ToList()) {
881              project.ProjectPermissions.Remove(item);
882            }
883          }
884          pm.SubmitChanges();
885
886          // add project permissions
887          foreach (var id in grantedUserIds) {
888            if(project.ProjectPermissions.All(x => x.GrantedUserId != id)) {
889              project.ProjectPermissions.Add(new DA.ProjectPermission {
890                GrantedUserId = id,
891                GrantedByUserId = UserManager.CurrentUserId
892              });
893            }
894          }
895          pm.SubmitChanges();
896
897          if (cascading) {
898            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
899            var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
900
901            // remove job assignments
902            if (reassignCascading) {
903              assignedJobResourceDao.DeleteByProjectIds(childProjectIds);
904            } else {
905              assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, removedPermissions);
906            }
907
908            foreach(var p in childProjects) {
909              // remove project permissions
910              if(reassignCascading) {
911                p.ProjectPermissions.Clear();
912              } else {
913                foreach(var item in p.ProjectPermissions
914                  .Where(x => removedPermissions.Contains(x.GrantedUserId))
915                  .ToList()) {
916                  p.ProjectPermissions.Remove(item);
917                }
918              }
919              pm.SubmitChanges();
920
921              // add project permissions
922              foreach (var id in grantedUserIds) {
923                if (p.ProjectPermissions.All(x => x.GrantedUserId != id)) {
924                  p.ProjectPermissions.Add(new DA.ProjectPermission {
925                    GrantedUserId = id,
926                    GrantedByUserId = UserManager.CurrentUserId
927                  });
928                }
929              }
930            }
931          }
932          pm.SubmitChanges();
933        });
934      }
935    }
936
937    public void GrantProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
938      throw new NotImplementedException();
939    }
940
941    public void RevokeProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
942      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
943      if (projectId == null || grantedUserIds == null || !grantedUserIds.Any()) return;
944      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
945      var pm = PersistenceManager;
946      using (new PerformanceLogger("RevokeProjectPermissions")) {
947        var projectPermissionDao = pm.ProjectPermissionDao;
948        var projectDao = pm.ProjectDao;
949        var assignedJobResourceDao = pm.AssignedJobResourceDao;
950        pm.UseTransaction(() => {
951          if (cascading) {
952            var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
953            projectPermissionDao.DeleteByProjectIdsAndGrantedUserIds(childProjectIds, grantedUserIds);
954            assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, grantedUserIds);
955          }
956          projectPermissionDao.DeleteByProjectIdAndGrantedUserIds(projectId, grantedUserIds);
957          assignedJobResourceDao.DeleteByProjectIdAndUserIds(projectId, grantedUserIds);
958          pm.SubmitChanges();
959        });
960      }
961    }
962
963    public IEnumerable<DT.ProjectPermission> GetProjectPermissions(Guid projectId) {
964      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
965      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
966      var pm = PersistenceManager;
967      using (new PerformanceLogger("GetProjectPermissions")) {
968        var projectPermissionDao = pm.ProjectPermissionDao;
969        return pm.UseTransaction(() => projectPermissionDao.GetByProjectId(projectId)
970          .Select(x => x.ToDto())
971          .ToList()
972        );
973      }
974    }
975    #endregion
976
977    #region AssignedProjectResource Methods
978    // basic: remove and add assignments (resourceIds) to projectId and its depending jobs
979    // reassign: clear all assignments from project and its depending jobs, before adding new ones (resourceIds)
980    // cascading: "basic" mode for child-projects
981    // reassignCascading: "reassign" mode for child-projects
982    public void SaveProjectResourceAssignments(Guid projectId, List<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
983      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
984      if (projectId == null || resourceIds == null) return;
985      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
986      var pm = PersistenceManager;
987      using (new PerformanceLogger("SaveProjectResourceAssignments")) {
988        var projectDao = pm.ProjectDao;
989        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
990        var assignedJobResourceDao = pm.AssignedJobResourceDao;
991        pm.UseTransaction(() => {
992          var project = projectDao.GetById(projectId);
993          var assignedResources = project.AssignedProjectResources.Select(x => x.ResourceId).ToArray();
994          //var addedAssignments = resourceIds.Except(assignedResources);
995          var removedAssignments = assignedResources.Except(resourceIds);
996
997          // remove job and project assignments
998          if (reassign) {
999            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
1000            project.AssignedProjectResources.Clear();
1001          } else {
1002            assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, removedAssignments);
1003            foreach (var item in project.AssignedProjectResources
1004              .Where(x => removedAssignments.Contains(x.ResourceId))
1005              .ToList()) {
1006              project.AssignedProjectResources.Remove(item);
1007            }
1008          }
1009          pm.SubmitChanges();
1010
1011          // add project assignments
1012          foreach (var id in resourceIds) {
1013            if (project.AssignedProjectResources.All(x => x.ResourceId != id)) {
1014              project.AssignedProjectResources.Add(new DA.AssignedProjectResource {
1015                ResourceId = id
1016              });
1017            }
1018          }
1019          pm.SubmitChanges();
1020
1021          if (cascading) {
1022            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
1023
1024            // remove job assignments
1025            if (reassignCascading) {
1026              assignedJobResourceDao.DeleteByProjectIds(childProjects.Select(x => x.ProjectId).ToList());
1027            } else {
1028              var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
1029              assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, removedAssignments);
1030            }
1031            foreach (var p in childProjects) {
1032              // remove project assignments
1033              if (reassignCascading) {
1034                //assignedProjectResourceDao.DeleteByProjectIds(new List<Guid> { p.ProjectId });
1035                p.AssignedProjectResources.Clear();
1036              } else {
1037                //assignedProjectResourceDao.DeleteByProjectIdAndResourceIds(p.ProjectId, removedAssignments);
1038                //for(int i = p.AssignedProjectResources.Count -1; i >= 0; i--) {
1039                //  if(removedAssignments.Contains(p.AssignedProjectResources[i].ResourceId)) {
1040                //    p.AssignedProjectResources.RemoveAt(i);
1041                //  }
1042                //}
1043                foreach (var item in p.AssignedProjectResources
1044                  .Where(x => removedAssignments.Contains(x.ResourceId))
1045                  .ToList()) {
1046                  p.AssignedProjectResources.Remove(item);
1047                }
1048              }
1049              pm.SubmitChanges();
1050
1051              // add project assignments
1052              foreach (var id in resourceIds) {
1053                if(p.AssignedProjectResources.All(x => x.ResourceId != id)) {
1054                  p.AssignedProjectResources.Add(new DA.AssignedProjectResource {
1055                    ResourceId = id
1056                  });
1057                }
1058              }
1059            }
1060          }
1061          pm.SubmitChanges();
1062        });
1063      }
1064    }
1065
1066    public void AssignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
1067      throw new NotImplementedException();
1068    }
1069
1070    // basic: unassign resourceIds from project and depending jobs
1071    // cascading: unassign resourceIds from all child-projects and their depending jobs
1072    public void UnassignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
1073      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1074      if (projectId == null || resourceIds == null || !resourceIds.Any()) return;
1075      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
1076      var pm = PersistenceManager;
1077      using (new PerformanceLogger("UnassignProjectResources")) {
1078        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1079        var assignedJobResourceDao = pm.AssignedJobResourceDao;
1080        var projectDao = pm.ProjectDao;
1081        pm.UseTransaction(() => {
1082          if (cascading) {
1083            var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
1084            assignedProjectResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
1085            assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
1086          }
1087          assignedProjectResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
1088          assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
1089          pm.SubmitChanges();
1090        });
1091      }
1092    }
1093
1094    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProject(Guid projectId) {
1095      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1096      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, projectId);
1097      var pm = PersistenceManager;
1098      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1099        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1100        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1101          .Select(x => x.ToDto())
1102          .ToList()
1103        );
1104      }
1105    }
1106
1107    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProjectAdministration(Guid projectId) {
1108      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1109      AuthorizationManager.AuthorizeForProjectAdministration(projectId);
1110      var pm = PersistenceManager;
1111      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1112        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1113        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1114          .Select(x => x.ToDto())
1115          .ToList()
1116        );
1117      }
1118    }
1119
1120    #endregion
1121
1122    #region Slave Methods
1123    public Guid AddSlave(DT.Slave slaveDto) {
1124      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1125      var pm = PersistenceManager;
1126      using (new PerformanceLogger("AddSlave")) {
1127        var slaveDao = pm.SlaveDao;
1128        return pm.UseTransaction(() => {
1129          var slave = slaveDao.Save(slaveDto.ToEntity());
1130          pm.SubmitChanges();
1131          return slave.ResourceId;
1132        });
1133      }
1134    }
1135
1136    public Guid AddSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1137      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1138      var pm = PersistenceManager;
1139      using (new PerformanceLogger("AddSlaveGroup")) {
1140        var slaveGroupDao = pm.SlaveGroupDao;
1141        return pm.UseTransaction(() => {
1142          if (slaveGroupDto.Id == Guid.Empty) {
1143            slaveGroupDto.Id = Guid.NewGuid();
1144          }
1145          var slaveGroup = slaveGroupDao.Save(slaveGroupDto.ToEntity());
1146          pm.SubmitChanges();
1147          return slaveGroup.ResourceId;
1148        });
1149      }
1150    }
1151
1152    public DT.Slave GetSlave(Guid slaveId) {
1153      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1154      var pm = PersistenceManager;
1155      using (new PerformanceLogger("GetSlave")) {
1156        var slaveDao = pm.SlaveDao;
1157        return pm.UseTransaction(() => slaveDao.GetById(slaveId).ToDto());
1158      }
1159    }
1160
1161    public IEnumerable<DT.Slave> GetSlaves() {
1162      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1163      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1164      var pm = PersistenceManager;
1165      using (new PerformanceLogger("GetSlaves")) {
1166        var slaveDao = pm.SlaveDao;
1167        //var projectPermissionDao = pm.ProjectPermissionDao;
1168        var currentUserId = UserManager.CurrentUserId;
1169        return pm.UseTransaction(() => {
1170            return slaveDao.GetAll().ToList()
1171              .Where( x => isAdministrator
1172              || x.OwnerUserId == null
1173              || x.OwnerUserId == currentUserId)
1174              .Select(x => x.ToDto())
1175              .ToList();
1176          //var projectPermissions = projectPermissionDao.GetAll();
1177          //return slaveDao.GetAll().ToList()
1178          //  .Where(x => isAdministrator
1179          //    || x.OwnerUserId == null
1180          //    || x.OwnerUserId == currentUserId
1181          //    || UserManager.VerifyUser(currentUserId, projectPermissions
1182          //        //.Where(y => y.ResourceId == x.ResourceId)
1183          //        .Select(z => z.GrantedUserId)
1184          //        .ToList())
1185          //    )
1186          //  .Select(x => x.ToDto())
1187          //  .ToList();
1188        });
1189      }
1190    }
1191
1192    public IEnumerable<DT.SlaveGroup> GetSlaveGroups() {
1193      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1194      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1195      var pm = PersistenceManager;
1196      using (new PerformanceLogger("GetSlaveGroups")) {
1197        var slaveGroupDao = pm.SlaveGroupDao;
1198        var projectPermissionDao = pm.ProjectPermissionDao;
1199        var currentUserId = UserManager.CurrentUserId;
1200        return pm.UseTransaction(() => {
1201          //var projectPermissions = projectPermissionDao.GetAll();
1202          return slaveGroupDao.GetAll().ToList()
1203            .Where(x => isAdministrator
1204              || x.OwnerUserId == null
1205              || x.OwnerUserId == currentUserId
1206              //|| UserManager.VerifyUser(currentUserId, projectPermissions
1207              //    //.Where(y => y.ResourceId == x.ResourceId)
1208              //    .Select(z => z.GrantedUserId)
1209              //    .ToList())
1210             )
1211            .Select(x => x.ToDto())
1212            .ToList();
1213        });
1214      }
1215    }
1216
1217    public void UpdateSlave(DT.Slave slaveDto) {
1218      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1219      var pm = PersistenceManager;
1220      using (new PerformanceLogger("UpdateSlave")) {
1221        var slaveDao = pm.SlaveDao;
1222        pm.UseTransaction(() => {
1223          var slave = slaveDao.GetById(slaveDto.Id);
1224          if (slave != null) {
1225            slaveDto.CopyToEntity(slave);
1226          } else {
1227            slaveDao.Save(slaveDto.ToEntity());
1228          }
1229          pm.SubmitChanges();
1230        });
1231      }
1232    }
1233
1234    public void UpdateSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1235      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1236      var pm = PersistenceManager;
1237      using (new PerformanceLogger("UpdateSlaveGroup")) {
1238        var slaveGroupDao = pm.SlaveGroupDao;
1239        pm.UseTransaction(() => {
1240          var slaveGroup = slaveGroupDao.GetById(slaveGroupDto.Id);
1241          if (slaveGroup != null) {
1242            slaveGroupDto.CopyToEntity(slaveGroup);
1243          } else {
1244            slaveGroupDao.Save(slaveGroupDto.ToEntity());
1245          }
1246          pm.SubmitChanges();
1247        });
1248      }
1249    }
1250
1251    public void DeleteSlave(Guid slaveId) {
1252      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1253      AuthorizationManager.AuthorizeForResourceAdministration(slaveId);
1254      var pm = PersistenceManager;
1255      using (new PerformanceLogger("DeleteSlave")) {
1256        var slaveDao = pm.SlaveDao;
1257        pm.UseTransaction(() => {
1258          slaveDao.Delete(slaveId);
1259          pm.SubmitChanges();
1260        });
1261      }
1262    }
1263
1264    public void DeleteSlaveGroup(Guid slaveGroupId) {
1265      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1266      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupId);
1267      var pm = PersistenceManager;
1268      using (new PerformanceLogger("DeleteSlaveGroup")) {
1269        var slaveGroupDao = pm.SlaveGroupDao;
1270        pm.UseTransaction(() => {
1271          slaveGroupDao.Delete(slaveGroupId);
1272          pm.SubmitChanges();
1273        });
1274      }
1275    }
1276
1277    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
1278      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1279      var pm = PersistenceManager;
1280      using (new PerformanceLogger("AddResourceToGroup")) {
1281        var resourceDao = pm.ResourceDao;
1282        pm.UseTransaction(() => {
1283          var resource = resourceDao.GetById(resourceId);
1284          resource.ParentResourceId = slaveGroupId;
1285          pm.SubmitChanges();
1286        });
1287      }
1288    }
1289
1290    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
1291      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1292      var pm = PersistenceManager;
1293      using (new PerformanceLogger("RemoveResourceFromGroup")) {
1294        var resourceDao = pm.ResourceDao;
1295        pm.UseTransaction(() => {
1296          var resource = resourceDao.GetById(resourceId);
1297          resource.ParentResourceId = null;
1298          pm.SubmitChanges();
1299        });
1300      }
1301    }
1302
1303    public Guid GetResourceId(string resourceName) {
1304      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1305      var pm = PersistenceManager;
1306      using (new PerformanceLogger("GetResourceId")) {
1307        var resourceDao = pm.ResourceDao;
1308        return pm.UseTransaction(() => {
1309          var resource = resourceDao.GetByName(resourceName);
1310          return resource != null ? resource.ResourceId : Guid.Empty;
1311        });
1312      }
1313    }
1314
1315    public void TriggerEventManager(bool force) {
1316      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1317      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
1318      bool cleanup;
1319      var pm = PersistenceManager;
1320      using (new PerformanceLogger("TriggerEventManager")) {
1321        cleanup = false;
1322        var lifecycleDao = pm.LifecycleDao;
1323        pm.UseTransaction(() => {
1324          var lastLifecycle = lifecycleDao.GetLastLifecycle();
1325          DateTime lastCleanup = lastLifecycle != null ? lastLifecycle.LastCleanup : DateTime.MinValue;
1326          if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
1327            lifecycleDao.UpdateLifecycle();
1328            cleanup = true;
1329            pm.SubmitChanges();
1330          }
1331        }, true);
1332      }
1333      if (cleanup) {
1334        EventManager.Cleanup();
1335      }
1336    }
1337
1338    public int GetNewHeartbeatInterval(Guid slaveId) {
1339      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
1340      var pm = PersistenceManager;
1341      using (new PerformanceLogger("GetNewHeartbeatInterval")) {
1342        var slaveDao = pm.SlaveDao;
1343        return pm.UseTransaction(() => {
1344          var slave = slaveDao.GetById(slaveId);
1345          if (slave != null) {
1346            return slave.HbInterval;
1347          }
1348          return -1;
1349        });
1350      }
1351    }
1352    #endregion
1353
1354    #region Downtime Methods
1355    public Guid AddDowntime(DT.Downtime downtimeDto) {
1356      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1357      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1358      var pm = PersistenceManager;
1359      using (new PerformanceLogger("AddDowntime")) {
1360        var downtimeDao = pm.DowntimeDao;
1361        return pm.UseTransaction(() => {
1362          var downtime = downtimeDao.Save(downtimeDto.ToEntity());
1363          pm.SubmitChanges();
1364          return downtime.ResourceId;
1365        });
1366      }
1367    }
1368
1369    public void DeleteDowntime(Guid downtimeId) {
1370      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1371      var pm = PersistenceManager;
1372      using (new PerformanceLogger("DeleteDowntime")) {
1373        var downtimeDao = pm.DowntimeDao;
1374        pm.UseTransaction(() => {
1375          downtimeDao.Delete(downtimeId);
1376          pm.SubmitChanges();
1377        });
1378      }
1379    }
1380
1381    public void UpdateDowntime(DT.Downtime downtimeDto) {
1382      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1383      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1384      var pm = PersistenceManager;
1385      using (new PerformanceLogger("UpdateDowntime")) {
1386        var downtimeDao = pm.DowntimeDao;
1387        pm.UseTransaction(() => {
1388          var downtime = downtimeDao.GetById(downtimeDto.Id);
1389          if (downtime != null) {
1390            downtimeDto.CopyToEntity(downtime);
1391          } else {
1392            downtimeDao.Save(downtimeDto.ToEntity());
1393          }
1394          pm.SubmitChanges();
1395        });
1396      }
1397    }
1398
1399    public IEnumerable<DT.Downtime> GetDowntimesForResource(Guid resourceId) {
1400      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1401      var pm = PersistenceManager;
1402      using (new PerformanceLogger("GetDowntimesForResource")) {
1403        var downtimeDao = pm.DowntimeDao;
1404        return pm.UseTransaction(() => downtimeDao.GetByResourceId(resourceId)
1405          .Select(x => x.ToDto())
1406          .ToList()
1407        );
1408      }
1409    }
1410    #endregion
1411
1412    #region User Methods
1413    public string GetUsernameByUserId(Guid userId) {
1414      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1415      var user = UserManager.GetUserById(userId);
1416      return user != null ? user.UserName : null;
1417    }
1418
1419    public Guid GetUserIdByUsername(string username) {
1420      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1421      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
1422      return user != null ? (Guid?)user.ProviderUserKey ?? Guid.Empty : Guid.Empty;
1423    }
1424   
1425    public Dictionary<Guid, HashSet<Guid>> GetUserGroupTree() {
1426      var userGroupTree = new Dictionary<Guid, HashSet<Guid>>();
1427      var userGroupMapping = UserManager.GetUserGroupMapping();
1428
1429      foreach(var ugm in userGroupMapping) {
1430        if (ugm.Parent == null || ugm.Child == null) continue;
1431
1432        if (!userGroupTree.ContainsKey(ugm.Parent)) {
1433          userGroupTree.Add(ugm.Parent, new HashSet<Guid>());
1434        }
1435        userGroupTree[ugm.Parent].Add(ugm.Child);
1436      }
1437
1438      return userGroupTree;
1439    }
1440    #endregion
1441
1442    #region UserPriorities Methods
1443    public IEnumerable<DT.UserPriority> GetUserPriorities() {
1444      var pm = PersistenceManager;
1445      using (new PerformanceLogger("GetUserPriorities")) {
1446        var userPriorityDao = pm.UserPriorityDao;
1447        return pm.UseTransaction(() => userPriorityDao.GetAll()
1448          .Select(x => x.ToDto())
1449          .ToList()
1450        );
1451      }
1452    }
1453    #endregion
1454
1455    #region Private Helper Methods
1456    private void UpdateTaskState(IPersistenceManager pm, DA.Task task, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
1457      var stateLogDao = pm.StateLogDao;
1458      var taskStateEntity = taskState.ToEntity();
1459
1460      if (task.State == DA.TaskState.Transferring && taskStateEntity == DA.TaskState.Paused && task.Command == null) {
1461        // slave paused and uploaded the task (no user-command) -> set waiting.
1462        taskStateEntity = DA.TaskState.Waiting;
1463      }
1464
1465      stateLogDao.Save(new DA.StateLog {
1466        State = taskStateEntity,
1467        DateTime = DateTime.Now,
1468        TaskId = task.TaskId,
1469        UserId = userId,
1470        SlaveId = slaveId,
1471        Exception = exception
1472      });
1473
1474      task.State = taskStateEntity;
1475
1476      if (task.Command == DA.Command.Pause && task.State == DA.TaskState.Paused
1477          || task.Command == DA.Command.Abort && task.State == DA.TaskState.Aborted
1478          || task.Command == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
1479        task.Command = null;
1480      }
1481    }
1482
1483    #endregion
1484  }
1485}
Note: See TracBrowser for help on using the repository browser.