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

Last change on this file since 15737 was 15737, checked in by jzenisek, 2 years ago

#2839

  • updated sql scripts (necessary foreign key option alterations & introduction of statistic tables)
  • updated HiveService according to changed client side (deletion-routine, permission checking,...)
File size: 62.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Security;
26using System.ServiceModel;
27using HeuristicLab.Services.Access;
28using HeuristicLab.Services.Hive.DataAccess.Interfaces;
29using HeuristicLab.Services.Hive.DataTransfer;
30using HeuristicLab.Services.Hive.Manager;
31using HeuristicLab.Services.Hive.ServiceContracts;
32using DA = HeuristicLab.Services.Hive.DataAccess;
33using DT = HeuristicLab.Services.Hive.DataTransfer;
34
35namespace HeuristicLab.Services.Hive {
36  /// <summary>
37  /// Implementation of the Hive service (interface <see cref="IHiveService"/>).
38  /// We need 'IgnoreExtensionDataObject' Attribute for the slave to work.
39  /// </summary>
40  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, IgnoreExtensionDataObject = true)]
41  [HiveOperationContextBehavior]
42  public class HiveService : IHiveService {
43    private const string NOT_AUTHORIZED_PROJECTRESOURCE = "Selected project is not authorized to access the requested resource";
44    private const string NOT_AUTHORIZED_USERPROJECT = "Current user is not authorized to access the requested project";
45
46    private static readonly DA.TaskState[] CompletedStates = { DA.TaskState.Finished, DA.TaskState.Aborted, DA.TaskState.Failed };
47
48    private IPersistenceManager PersistenceManager {
49      get { return ServiceLocator.Instance.PersistenceManager; }
50    }
51
52    private IUserManager UserManager {
53      get { return ServiceLocator.Instance.UserManager; }
54    }
55
56    private IRoleVerifier RoleVerifier {
57      get { return ServiceLocator.Instance.RoleVerifier; }
58    }
59
60    private IAuthorizationManager AuthorizationManager {
61      get { return ServiceLocator.Instance.AuthorizationManager; }
62    }
63    private IEventManager EventManager {
64      get { return ServiceLocator.Instance.EventManager; }
65    }
66    private HeartbeatManager HeartbeatManager {
67      get { return ServiceLocator.Instance.HeartbeatManager; }
68    }
69
70    #region Task Methods
71
72    public Guid AddTask(DT.Task task, DT.TaskData taskData) {
73      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
74      AuthorizationManager.AuthorizeForJob(task.JobId, DT.Permission.Full);
75      var pm = PersistenceManager;
76      using (new PerformanceLogger("AddTask")) {
77        var taskDao = pm.TaskDao;
78        var stateLogDao = pm.StateLogDao;
79        var newTask = task.ToEntity();
80        newTask.JobData = taskData.ToEntity();
81        newTask.JobData.LastUpdate = DateTime.Now;
82        newTask.State = DA.TaskState.Waiting;
83        return pm.UseTransaction(() => {
84          taskDao.Save(newTask);
85          pm.SubmitChanges();
86          stateLogDao.Save(new DA.StateLog {
87            State = DA.TaskState.Waiting,
88            DateTime = DateTime.Now,
89            TaskId = newTask.TaskId,
90            UserId = UserManager.CurrentUserId,
91            SlaveId = null,
92            Exception = null
93          });
94          pm.SubmitChanges();
95          return newTask.TaskId;
96        }, false, true);
97      }
98    }
99
100    public Guid AddChildTask(Guid parentTaskId, DT.Task task, DT.TaskData taskData) {
101      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
102      task.ParentTaskId = parentTaskId;
103      return AddTask(task, taskData);
104    }
105
106    public DT.Task GetTask(Guid taskId) {
107      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
108      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
109      var pm = PersistenceManager;
110      using (new PerformanceLogger("GetTask")) {
111        var taskDao = pm.TaskDao;
112        return pm.UseTransaction(() => {
113          var task = taskDao.GetById(taskId);
114          return task.ToDto();
115        });
116      }
117    }
118
119    public IEnumerable<DT.LightweightTask> GetLightweightJobTasks(Guid jobId) {
120      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
121      AuthorizationManager.AuthorizeForJob(jobId, Permission.Read);
122      var pm = PersistenceManager;
123      using (new PerformanceLogger("GetLightweightJobTasks")) {
124        var taskDao = pm.TaskDao;
125        return pm.UseTransaction(() => {
126          return taskDao.GetByJobId(jobId)
127            .ToList()
128            .Select(x => new DT.LightweightTask {
129              Id = x.TaskId,
130              ExecutionTime = TimeSpan.FromMilliseconds(x.ExecutionTimeMs),
131              ParentTaskId = x.ParentTaskId,
132              StateLog = x.StateLogs.OrderBy(y => y.DateTime)
133                                    .Select(z => z.ToDto())
134                                    .ToList(),
135              State = x.State.ToDto(),
136              Command = x.Command.ToDto(),
137              LastTaskDataUpdate = x.JobData.LastUpdate
138            })
139            .ToList();
140        }, false, true);
141      }
142    }
143
144    public IEnumerable<DT.LightweightTask> GetLightweightJobTasksWithoutStateLog(Guid jobId) {
145      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
146      AuthorizationManager.AuthorizeForJob(jobId, Permission.Read);
147      var pm = PersistenceManager;
148      using (new PerformanceLogger("GetLightweightJobTasksWithoutStateLog")) {
149        var taskDao = pm.TaskDao;
150        return pm.UseTransaction(() => {
151          return taskDao.GetByJobId(jobId)
152            .ToList()
153            .Select(x => new DT.LightweightTask {
154              Id = x.TaskId,
155              ExecutionTime = TimeSpan.FromMilliseconds(x.ExecutionTimeMs),
156              ParentTaskId = x.ParentTaskId,
157              StateLog = new List<DT.StateLog>(),
158              State = x.State.ToDto(),
159              Command = x.Command.ToDto(),
160              LastTaskDataUpdate = x.JobData.LastUpdate
161            })
162            .ToList();
163        }, false, true);
164      }
165    }
166
167    public DT.TaskData GetTaskData(Guid taskId) {
168      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
169      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
170      var pm = PersistenceManager;
171      using (new PerformanceLogger("GetTaskData")) {
172        var taskDataDao = pm.TaskDataDao;
173        return pm.UseTransaction(() => taskDataDao.GetById(taskId).ToDto());
174      }
175    }
176
177    public void UpdateTask(DT.Task taskDto) {
178      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
179      AuthorizationManager.AuthorizeForTask(taskDto.Id, Permission.Full);
180      var pm = PersistenceManager;
181      using (new PerformanceLogger("UpdateTask")) {
182        var taskDao = pm.TaskDao;
183        pm.UseTransaction(() => {
184          var task = taskDao.GetById(taskDto.Id);
185          taskDto.CopyToEntity(task);
186          pm.SubmitChanges();
187        });
188      }
189    }
190
191    public void UpdateTaskData(DT.Task taskDto, DT.TaskData taskDataDto) {
192      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
193      AuthorizationManager.AuthorizeForTask(taskDto.Id, Permission.Full);
194      var pm = PersistenceManager;
195      using (new PerformanceLogger("UpdateTaskData")) {
196        var taskDao = pm.TaskDao;
197        var taskDataDao = pm.TaskDataDao;
198        pm.UseTransaction(() => {
199          var task = taskDao.GetById(taskDto.Id);
200          var taskData = taskDataDao.GetById(taskDataDto.TaskId);
201          taskDto.CopyToEntity(task);
202          taskDataDto.CopyToEntity(taskData);
203          taskData.LastUpdate = DateTime.Now;
204          pm.SubmitChanges();
205        });
206      }
207    }
208
209    public DT.Task UpdateTaskState(Guid taskId, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
210      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
211      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
212      var pm = PersistenceManager;
213      using (new PerformanceLogger("UpdateTaskState")) {
214        var taskDao = pm.TaskDao;
215        return pm.UseTransaction(() => {
216          var task = taskDao.GetById(taskId);
217          UpdateTaskState(pm, task, taskState, slaveId, userId, exception);
218          pm.SubmitChanges();
219          return task.ToDto();
220        });
221      }
222    }
223    #endregion
224
225    #region Task Control Methods
226    public void StopTask(Guid taskId) {
227      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
228      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
229      var pm = PersistenceManager;
230      using (new PerformanceLogger("StopTask")) {
231        var taskDao = pm.TaskDao;
232        pm.UseTransaction(() => {
233          var task = taskDao.GetById(taskId);
234          if (task.State == DA.TaskState.Calculating || task.State == DA.TaskState.Transferring) {
235            task.Command = DA.Command.Stop;
236          } else if (task.State != DA.TaskState.Aborted
237                     && task.State != DA.TaskState.Finished
238                     && task.State != DA.TaskState.Failed) {
239            UpdateTaskState(pm, task, DT.TaskState.Aborted, null, null, string.Empty);
240          }
241          pm.SubmitChanges();
242        });
243      }
244    }
245
246    public void PauseTask(Guid taskId) {
247      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
248      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
249      var pm = PersistenceManager;
250      using (new PerformanceLogger("PauseTask")) {
251        var taskDao = pm.TaskDao;
252        pm.UseTransaction(() => {
253          var task = taskDao.GetById(taskId);
254          if (task.State == DA.TaskState.Calculating || task.State == DA.TaskState.Transferring) {
255            task.Command = DA.Command.Pause;
256          } else if (task.State != DA.TaskState.Paused
257                     && task.State != DA.TaskState.Aborted
258                     && task.State != DA.TaskState.Finished
259                     && task.State != DA.TaskState.Failed) {
260            UpdateTaskState(pm, task, DT.TaskState.Paused, null, null, string.Empty);
261          }
262          pm.SubmitChanges();
263        });
264      }
265    }
266
267    public void RestartTask(Guid taskId) {
268      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
269      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
270      var pm = PersistenceManager;
271      using (new PerformanceLogger("RestartTask")) {
272        var taskDao = pm.TaskDao;
273        pm.UseTransaction(() => {
274          var task = taskDao.GetById(taskId);
275          task.Command = null;
276          UpdateTaskState(pm, task, DT.TaskState.Waiting, null, UserManager.CurrentUserId, string.Empty);
277          pm.SubmitChanges();
278        });
279      }
280    }
281    #endregion
282
283    #region Job Methods
284    public DT.Job GetJob(Guid id) {
285      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
286      AuthorizationManager.AuthorizeForJob(id, DT.Permission.Read);
287      var pm = PersistenceManager;
288      using (new PerformanceLogger("GetJob")) {
289        var jobDao = pm.JobDao;
290        var jobPermissionDao = pm.JobPermissionDao;
291        var taskDao = pm.TaskDao;
292        var currentUserId = UserManager.CurrentUserId;
293        return pm.UseTransaction(() => {
294          var job = jobDao.GetById(id).ToDto();
295          if (job != null) {
296            var statistics = taskDao.GetByJobId(job.Id)
297              .GroupBy(x => x.JobId)
298              .Select(x => new {
299                TotalCount = x.Count(),
300                CalculatingCount = x.Count(y => y.State == DA.TaskState.Calculating),
301                FinishedCount = x.Count(y => CompletedStates.Contains(y.State))
302              }).FirstOrDefault();
303            if (statistics != null) {
304              job.JobCount = statistics.TotalCount;
305              job.CalculatingCount = statistics.CalculatingCount;
306              job.FinishedCount = statistics.FinishedCount;
307            }
308            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
309            if (currentUserId == job.OwnerUserId) {
310              job.Permission = Permission.Full;
311            } else {
312              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
313              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
314            }
315          }
316          return job;
317        });
318      }
319    }
320
321    public IEnumerable<DT.Job> GetJobs() {
322      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
323      var pm = PersistenceManager;
324      using (new PerformanceLogger("GetJobs")) {
325        var jobDao = pm.JobDao;
326        var jobPermissionDao = pm.JobPermissionDao;
327        var taskDao = pm.TaskDao;
328        var currentUserId = UserManager.CurrentUserId;
329        return pm.UseTransaction(() => {
330          var jobs = jobDao.GetAll()
331            .Where(x => x.State == DA.JobState.Online
332                          && (x.OwnerUserId == currentUserId
333                            || x.JobPermissions.Count(y => y.Permission != DA.Permission.NotAllowed
334                              && y.GrantedUserId == currentUserId) > 0)
335                          )
336            .Select(x => x.ToDto())
337            .ToList();
338          var statistics = taskDao.GetAll()
339              .Where(x => jobs.Select(y => y.Id).Contains(x.JobId))
340              .GroupBy(x => x.JobId)
341              .Select(x => new {
342                x.Key,
343                TotalCount = x.Count(),
344                CalculatingCount = x.Count(y => y.State == DA.TaskState.Calculating),
345                FinishedCount = x.Count(y => CompletedStates.Contains(y.State))
346              })
347              .ToList();
348          foreach (var job in jobs) {
349            var statistic = statistics.FirstOrDefault(x => x.Key == job.Id);
350            if (statistic != null) {
351              job.JobCount = statistic.TotalCount;
352              job.CalculatingCount = statistic.CalculatingCount;
353              job.FinishedCount = statistic.FinishedCount;
354            }
355            job.OwnerUsername = UserManager.GetUserNameById(job.OwnerUserId);
356            if (currentUserId == job.OwnerUserId) {
357              job.Permission = Permission.Full;
358            } else {
359              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
360              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
361            }
362          }
363          return jobs;
364        });
365      }
366    }
367
368    public Guid AddJob(DT.Job jobDto, IEnumerable<Guid> resourceIds) {
369      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
370      // check user - project
371      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, jobDto.ProjectId);
372      // check project - resources
373      AuthorizationManager.AuthorizeProjectForResourcesUse(jobDto.ProjectId, resourceIds);
374      var pm = PersistenceManager;
375      using (new PerformanceLogger("AddJob")) {
376        var jobDao = pm.JobDao;
377        var userPriorityDao = pm.UserPriorityDao;
378
379        return pm.UseTransaction(() => {
380          var newJob = jobDto.ToEntity();
381          newJob.OwnerUserId = UserManager.CurrentUserId;
382          newJob.DateCreated = DateTime.Now;
383
384          // add resource assignments
385          if (resourceIds != null && resourceIds.Any()) {           
386            newJob.AssignedJobResources.AddRange(resourceIds.Select(
387              x => new DA.AssignedJobResource {
388                ResourceId = x
389              }));
390          }
391
392          var job = jobDao.Save(newJob);
393          if (userPriorityDao.GetById(jobDto.OwnerUserId) == null) {
394            userPriorityDao.Save(new DA.UserPriority {
395              UserId = jobDto.OwnerUserId,
396              DateEnqueued = jobDto.DateCreated
397            });
398          }
399          pm.SubmitChanges();
400          return job.JobId;
401        });
402      }
403    }
404
405    public void UpdateJob(DT.Job jobDto, IEnumerable<Guid> resourceIds) {
406      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
407      AuthorizationManager.AuthorizeForJob(jobDto.Id, DT.Permission.Full);
408      // check user - project permission
409      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, jobDto.ProjectId);
410      // check project - resources permission
411      AuthorizationManager.AuthorizeProjectForResourcesUse(jobDto.ProjectId, resourceIds);
412
413      var pm = PersistenceManager;
414      using (new PerformanceLogger("UpdateJob")) {
415        bool exists = true;
416        var jobDao = pm.JobDao;
417        pm.UseTransaction(() => {
418          var job = jobDao.GetById(jobDto.Id);
419          if (job == null) {
420            exists = false;
421            job = new DA.Job();
422          }
423          jobDto.CopyToEntity(job);
424
425          if (!exists) {
426            // add resource assignments
427            if (resourceIds != null && resourceIds.Any()) {
428              job.AssignedJobResources.AddRange(resourceIds.Select(
429                x => new DA.AssignedJobResource {
430                  ResourceId = x
431              }));
432            }
433            jobDao.Save(job);
434          } else if(resourceIds != null) {
435            var addedJobResourceIds = resourceIds.Except(job.AssignedJobResources.Select(x => x.ResourceId));
436            var removedJobResourceIds = job.AssignedJobResources
437              .Select(x => x.ResourceId)
438              .Except(resourceIds)
439              .ToArray();
440           
441            // remove resource assignments
442            foreach(var rid in removedJobResourceIds) {
443              var ajr = job.AssignedJobResources.Where(x => x.ResourceId == rid).SingleOrDefault();
444              if (ajr != null) job.AssignedJobResources.Remove(ajr);
445            }
446
447            // add resource assignments
448            job.AssignedJobResources.AddRange(addedJobResourceIds.Select(
449              x => new DA.AssignedJobResource {
450                ResourceId = x
451              }));
452          }
453          pm.SubmitChanges();
454        });
455      }
456    }
457
458    public void UpdateJobState(Guid jobId, DT.JobState jobState) {
459      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
460      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
461      var pm = PersistenceManager;
462      using (new PerformanceLogger("UpdateJobState")) {
463        var jobDao = pm.JobDao;
464        pm.UseTransaction(() => {
465          var job = jobDao.GetById(jobId);
466          if(job != null) {
467            var jobStateEntity = jobState.ToEntity();
468            // note: allow solely state changes from "Online" to "StatisticsPending"
469            // and from "StatisticsPending" to "DeletionPending"
470            if (job.State == DA.JobState.Online && jobStateEntity == DA.JobState.StatisticsPending) {
471              job.State = jobStateEntity;
472              foreach(var task in job.Tasks
473              .Where(x => x.State == DA.TaskState.Waiting
474                || x.State == DA.TaskState.Paused
475                || x.State == DA.TaskState.Offline)) {
476                task.State = DA.TaskState.Aborted;
477              }
478              pm.SubmitChanges();
479            } else if(job.State == DA.JobState.StatisticsPending && jobStateEntity == DA.JobState.DeletionPending) {
480              job.State = jobStateEntity;
481              pm.SubmitChanges();
482            }
483          }
484        });
485      }
486    }
487
488    public IEnumerable<DT.AssignedJobResource> GetAssignedResourcesForJob(Guid jobId) {
489      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
490      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
491      var pm = PersistenceManager;
492      var assignedJobResourceDao = pm.AssignedJobResourceDao;
493      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
494        return pm.UseTransaction(() =>
495          assignedJobResourceDao.GetByJobId(jobId)
496          .Select(x => x.ToDto())
497          .ToList()
498        );
499      }
500    }
501    #endregion
502
503    #region JobPermission Methods
504    public void GrantPermission(Guid jobId, Guid grantedUserId, DT.Permission permission) {
505      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
506      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
507      var pm = PersistenceManager;
508      using (new PerformanceLogger("GrantPermission")) {
509        var jobPermissionDao = pm.JobPermissionDao;
510        var currentUserId = UserManager.CurrentUserId;
511        pm.UseTransaction(() => {
512          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, permission.ToEntity());
513          pm.SubmitChanges();
514        });
515      }
516    }
517
518    public void RevokePermission(Guid jobId, Guid grantedUserId) {
519      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
520      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
521      var pm = PersistenceManager;
522      using (new PerformanceLogger("RevokePermission")) {
523        var jobPermissionDao = pm.JobPermissionDao;
524        var currentUserId = UserManager.CurrentUserId;
525        pm.UseTransaction(() => {
526          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, DA.Permission.NotAllowed);
527          pm.SubmitChanges();
528        });
529      }
530    }
531
532    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
533      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
534      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
535      var pm = PersistenceManager;
536      using (new PerformanceLogger("GetJobPermissions")) {
537        var jobPermissionDao = pm.JobPermissionDao;
538        return pm.UseTransaction(() => jobPermissionDao.GetByJobId(jobId)
539          .Select(x => x.ToDto())
540          .ToList()
541        );
542      }
543    }
544
545    // BackwardsCompatibility3.3
546    #region Backwards compatible code, remove with 3.4
547    public bool IsAllowedPrivileged() {
548      return true;
549    }
550    #endregion
551    #endregion
552
553    #region Login Methods
554    public void Hello(DT.Slave slaveInfo) {
555      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
556      if (UserManager.CurrentUser.UserName != "hiveslave") {
557        slaveInfo.OwnerUserId = UserManager.CurrentUserId;
558      }
559      var pm = PersistenceManager;
560      using (new PerformanceLogger("Hello")) {
561        var slaveDao = pm.SlaveDao;
562        pm.UseTransaction(() => {
563          var slave = slaveDao.GetById(slaveInfo.Id);
564          if (slave == null) {
565            slaveDao.Save(slaveInfo.ToEntity());
566          } else {
567            bool oldIsAllowedToCalculate = slave.IsAllowedToCalculate;
568            Guid? oldParentResourceId = slave.ParentResourceId;
569            slaveInfo.CopyToEntity(slave);
570            slave.IsAllowedToCalculate = oldIsAllowedToCalculate;
571            slave.ParentResourceId = oldParentResourceId;
572            slave.LastHeartbeat = DateTime.Now;
573            slave.SlaveState = DA.SlaveState.Idle;
574          }
575          pm.SubmitChanges();
576        });
577      }
578    }
579
580    public void GoodBye(Guid slaveId) {
581      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
582      var pm = PersistenceManager;
583      using (new PerformanceLogger("GoodBye")) {
584        var slaveDao = pm.SlaveDao;
585        pm.UseTransaction(() => {
586          var slave = slaveDao.GetById(slaveId);
587          if (slave != null) {
588            slave.SlaveState = DA.SlaveState.Offline;
589            pm.SubmitChanges();
590          }
591        });
592      }
593    }
594    #endregion
595
596    #region Heartbeat Methods
597    public List<MessageContainer> Heartbeat(DT.Heartbeat heartbeat) {
598      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
599      List<MessageContainer> result = new List<MessageContainer>();
600      try {
601        using (new PerformanceLogger("ProcessHeartbeat")) {
602          result = HeartbeatManager.ProcessHeartbeat(heartbeat);
603        }
604      } catch (Exception ex) {
605        DA.LogFactory.GetLogger(this.GetType().Namespace).Log(string.Format("Exception processing Heartbeat: {0}", ex));
606      }
607      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
608        TriggerEventManager(false);
609      }
610      return result;
611    }
612    #endregion
613
614    #region Plugin Methods
615    public DT.Plugin GetPlugin(Guid pluginId) {
616      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
617      var pm = PersistenceManager;
618      using (new PerformanceLogger("GetPlugin")) {
619        var pluginDao = pm.PluginDao;
620        return pm.UseTransaction(() => pluginDao.GetById(pluginId).ToDto());
621      }
622    }
623
624    public Guid AddPlugin(DT.Plugin plugin, List<DT.PluginData> pluginData) {
625      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
626      var pm = PersistenceManager;
627      using (new PerformanceLogger("AddPlugin")) {
628        var pluginDao = pm.PluginDao;
629        plugin.UserId = UserManager.CurrentUserId;
630        plugin.DateCreated = DateTime.Now;
631        return pm.UseTransaction(() => {
632          var pluginEntity = pluginDao.GetByHash(plugin.Hash).SingleOrDefault();
633          if (pluginEntity != null) {
634            throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(pluginEntity.PluginId));
635          }
636          pluginEntity = plugin.ToEntity();
637          foreach (var data in pluginData) {
638            data.PluginId = default(Guid); // real id will be assigned from linq2sql
639            pluginEntity.PluginData.Add(data.ToEntity());
640          }
641          pluginDao.Save(pluginEntity);
642          pm.SubmitChanges();
643          return pluginEntity.PluginId;
644        });
645      }
646    }
647
648    public IEnumerable<DT.Plugin> GetPlugins() {
649      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
650      var pm = PersistenceManager;
651      using (new PerformanceLogger("GetPlugins")) {
652        var pluginDao = pm.PluginDao;
653        return pm.UseTransaction(() => pluginDao.GetAll()
654          .Where(x => x.Hash != null)
655          .Select(x => x.ToDto())
656          .ToList()
657        );
658      }
659    }
660
661    public IEnumerable<DT.PluginData> GetPluginDatas(List<Guid> pluginIds) {
662      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
663      var pm = PersistenceManager;
664      using (new PerformanceLogger("GetPluginDatas")) {
665        var pluginDataDao = pm.PluginDataDao;
666        return pm.UseTransaction(() => pluginDataDao.GetAll()
667            .Where(x => pluginIds.Contains(x.PluginId))
668            .Select(x => x.ToDto())
669            .ToList()
670        );
671      }
672    }
673    #endregion
674
675    #region Project Methods
676    public Guid AddProject(DT.Project projectDto) {
677      if (projectDto == null) return Guid.Empty;
678      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
679      // check if current (non-admin) user is owner of one of projectDto's-parents
680      if (!RoleVerifier.IsInRole(HiveRoles.Administrator)) {
681        if(projectDto.ParentProjectId.HasValue) {
682          AuthorizationManager.AuthorizeForProjectAdministration(projectDto.ParentProjectId.Value, false);
683        } else {
684          throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
685        }
686      }
687     
688      var pm = PersistenceManager;
689      using (new PerformanceLogger("AddProject")) {
690        var projectDao = pm.ProjectDao;
691        return pm.UseTransaction(() => {
692          var project = projectDao.Save(projectDto.ToEntity());
693          pm.SubmitChanges();
694          return project.ProjectId;
695        });
696      }
697    }
698
699    public void UpdateProject(DT.Project projectDto) {
700      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
701      // check if current (non-admin) user is owner of the project or the projectDto's-parents
702      if (!RoleVerifier.IsInRole(HiveRoles.Administrator)) {
703        AuthorizationManager.AuthorizeForProjectAdministration(projectDto.Id, false);
704      }
705
706      var pm = PersistenceManager;
707      using (new PerformanceLogger("UpdateProject")) {
708        var projectDao = pm.ProjectDao;
709        pm.UseTransaction(() => {
710          var project = projectDao.GetById(projectDto.Id);
711          if (project != null) {
712            projectDto.CopyToEntity(project);
713          } else {
714            projectDao.Save(projectDto.ToEntity());
715          }
716          pm.SubmitChanges();
717        });
718      }
719    }
720
721    public void DeleteProject(Guid projectId) {
722      if (projectId == Guid.Empty) return;
723      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
724      // check if current (non-admin) user is owner of one of the projectDto's-parents
725      if (!RoleVerifier.IsInRole(HiveRoles.Administrator)) {
726        AuthorizationManager.AuthorizeForProjectAdministration(projectId, true);
727      }
728
729      var pm = PersistenceManager;
730      using (new PerformanceLogger("DeleteProject")) {
731        var projectDao = pm.ProjectDao;
732        var assignedJobResourceDao = pm.AssignedJobResourceDao;
733        pm.UseTransaction(() => {
734          var projectIds = new HashSet<Guid> { projectId };
735          projectIds.Union(projectDao.GetChildProjectIdsById(projectId));
736
737          assignedJobResourceDao.DeleteByProjectIds(projectIds);
738          projectDao.DeleteByIds(projectIds);
739          pm.SubmitChanges();
740        });
741      }
742    }
743
744    // query granted project for use (i.e. to calculate on)
745    public DT.Project GetProject(Guid projectId) {
746      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
747      var pm = PersistenceManager;
748      using (new PerformanceLogger("GetProject")) {
749        var projectDao = pm.ProjectDao;
750        var currentUserId = UserManager.CurrentUserId;
751        var userAndGroupIds = new List<Guid> { currentUserId };
752        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
753        return pm.UseTransaction(() => {
754          return projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
755          .Where(x => x.ProjectId == projectId)
756          .Select(x => x.ToDto())
757          .SingleOrDefault();
758        });
759      }
760    }
761
762    // query granted projects for use (i.e. to calculate on)
763    public IEnumerable<DT.Project> GetProjects() {
764      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
765      var pm = PersistenceManager;
766      using (new PerformanceLogger("GetProjects")) {
767        var projectDao = pm.ProjectDao;
768        var currentUserId = UserManager.CurrentUserId;
769        var userAndGroupIds = new List<Guid> { currentUserId };
770        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
771        return pm.UseTransaction(() => {
772          return projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
773            .Select(x => x.ToDto()).ToList();
774        });
775      }
776    }
777
778    public IEnumerable<DT.Project> GetProjectsForAdministration() {
779      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
780      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
781      var pm = PersistenceManager;
782      using (new PerformanceLogger("GetProjectsForAdministration")) {
783        var projectDao = pm.ProjectDao;
784       
785        return pm.UseTransaction(() => {
786          if(isAdministrator) {
787            return projectDao.GetAll().Select(x => x.ToDto()).ToList();
788          } else {
789            var currentUserId = UserManager.CurrentUserId;
790            return projectDao.GetAdministrationGrantedProjectsForUser(currentUserId)
791              .Select(x => x.ToDto()).ToList();
792
793          }
794        });
795      }
796    }
797    #endregion
798
799    #region ProjectPermission Methods
800    public void SaveProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool reassign, bool cascading, bool reassignCascading) {
801      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
802      if (projectId == null || grantedUserIds == null) return;
803      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
804      var pm = PersistenceManager;
805      using (new PerformanceLogger("SaveProjectPermissions")) {
806        var projectDao = pm.ProjectDao;
807        var projectPermissionDao = pm.ProjectPermissionDao;
808        var assignedJobResourceDao = pm.AssignedJobResourceDao;
809
810        pm.UseTransaction(() => {
811          var project = projectDao.GetById(projectId);
812          if (project == null) return;
813          var projectPermissions = project.ProjectPermissions.Select(x => x.GrantedUserId).ToArray();
814          //var addedPermissions = grantedUserIds.Except(projectPermissions);
815          var removedPermissions = projectPermissions.Except(grantedUserIds);
816
817          // remove job assignments and project permissions
818          if (reassign) {
819            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
820            project.ProjectPermissions.Clear();
821          } else {
822            assignedJobResourceDao.DeleteByProjectIdAndUserIds(project.ProjectId, removedPermissions);
823            foreach(var item in project.ProjectPermissions
824              .Where(x => removedPermissions.Contains(x.GrantedUserId))
825              .ToList()) {
826              project.ProjectPermissions.Remove(item);
827            }
828          }
829          pm.SubmitChanges();
830
831          // add project permissions
832          foreach (var id in grantedUserIds) {
833            if(project.ProjectPermissions.All(x => x.GrantedUserId != id)) {
834              project.ProjectPermissions.Add(new DA.ProjectPermission {
835                GrantedUserId = id,
836                GrantedByUserId = UserManager.CurrentUserId
837              });
838            }
839          }
840          pm.SubmitChanges();
841
842          if (cascading) {
843            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
844            var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
845
846            // remove job assignments
847            if (reassignCascading) {
848              assignedJobResourceDao.DeleteByProjectIds(childProjectIds);
849            } else {
850              assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, removedPermissions);
851            }
852
853            foreach(var p in childProjects) {
854              // remove project permissions
855              if(reassignCascading) {
856                p.ProjectPermissions.Clear();
857              } else {
858                foreach(var item in p.ProjectPermissions
859                  .Where(x => removedPermissions.Contains(x.GrantedUserId))
860                  .ToList()) {
861                  p.ProjectPermissions.Remove(item);
862                }
863              }
864              pm.SubmitChanges();
865
866              // add project permissions
867              foreach (var id in grantedUserIds) {
868                if (p.ProjectPermissions.All(x => x.GrantedUserId != id)) {
869                  p.ProjectPermissions.Add(new DA.ProjectPermission {
870                    GrantedUserId = id,
871                    GrantedByUserId = UserManager.CurrentUserId
872                  });
873                }
874              }
875            }
876          }
877          pm.SubmitChanges();
878        });
879      }
880    }
881
882    private void GrantProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
883      throw new NotImplementedException();
884    }
885
886    private void RevokeProjectPermissions(Guid projectId, List<Guid> grantedUserIds, bool cascading) {
887      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
888      if (projectId == null || grantedUserIds == null || !grantedUserIds.Any()) return;
889      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
890      var pm = PersistenceManager;
891      using (new PerformanceLogger("RevokeProjectPermissions")) {
892        var projectPermissionDao = pm.ProjectPermissionDao;
893        var projectDao = pm.ProjectDao;
894        var assignedJobResourceDao = pm.AssignedJobResourceDao;
895        pm.UseTransaction(() => {
896          if (cascading) {
897            var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
898            projectPermissionDao.DeleteByProjectIdsAndGrantedUserIds(childProjectIds, grantedUserIds);
899            assignedJobResourceDao.DeleteByProjectIdsAndUserIds(childProjectIds, grantedUserIds);
900          }
901          projectPermissionDao.DeleteByProjectIdAndGrantedUserIds(projectId, grantedUserIds);
902          assignedJobResourceDao.DeleteByProjectIdAndUserIds(projectId, grantedUserIds);
903          pm.SubmitChanges();
904        });
905      }
906    }
907
908    public IEnumerable<DT.ProjectPermission> GetProjectPermissions(Guid projectId) {
909      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
910      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
911      var pm = PersistenceManager;
912      using (new PerformanceLogger("GetProjectPermissions")) {
913        var projectPermissionDao = pm.ProjectPermissionDao;
914        return pm.UseTransaction(() => projectPermissionDao.GetByProjectId(projectId)
915          .Select(x => x.ToDto())
916          .ToList()
917        );
918      }
919    }
920    #endregion
921
922    #region AssignedProjectResource Methods
923    // basic: remove and add assignments (resourceIds) to projectId and its depending jobs
924    // reassign: clear all assignments from project and its depending jobs, before adding new ones (resourceIds)
925    // cascading: "basic" mode for child-projects
926    // reassignCascading: "reassign" mode for child-projects
927    public void SaveProjectResourceAssignments(Guid projectId, List<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
928      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
929      if (projectId == null || resourceIds == null) return;
930      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
931      var pm = PersistenceManager;
932      using (new PerformanceLogger("SaveProjectResourceAssignments")) {
933        var projectDao = pm.ProjectDao;
934        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
935        var assignedJobResourceDao = pm.AssignedJobResourceDao;
936        pm.UseTransaction(() => {
937          var project = projectDao.GetById(projectId);
938          var assignedResources = project.AssignedProjectResources.Select(x => x.ResourceId).ToArray();
939          var removedAssignments = assignedResources.Except(resourceIds);
940
941          // remove job and project assignments
942          if (reassign) {
943            assignedJobResourceDao.DeleteByProjectId(project.ProjectId);
944            project.AssignedProjectResources.Clear();
945          } else {
946            assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, removedAssignments);
947            foreach (var item in project.AssignedProjectResources
948              .Where(x => removedAssignments.Contains(x.ResourceId))
949              .ToList()) {
950              project.AssignedProjectResources.Remove(item);
951            }
952          }
953          pm.SubmitChanges();
954
955          // add project assignments
956          foreach (var id in resourceIds) {
957            if (project.AssignedProjectResources.All(x => x.ResourceId != id)) {
958              project.AssignedProjectResources.Add(new DA.AssignedProjectResource {
959                ResourceId = id
960              });
961            }
962          }
963          pm.SubmitChanges();
964
965          if (cascading) {
966            var childProjects = projectDao.GetChildProjectsById(projectId).ToList();
967
968            // remove job assignments
969            if (reassignCascading) {
970              assignedJobResourceDao.DeleteByProjectIds(childProjects.Select(x => x.ProjectId).ToList());
971            } else {
972              var childProjectIds = childProjects.Select(x => x.ProjectId).ToList();
973              assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, removedAssignments);
974            }
975            foreach (var p in childProjects) {
976              // remove project assignments
977              if (reassignCascading) {
978                p.AssignedProjectResources.Clear();
979              } else {
980                foreach (var item in p.AssignedProjectResources
981                  .Where(x => removedAssignments.Contains(x.ResourceId))
982                  .ToList()) {
983                  p.AssignedProjectResources.Remove(item);
984                }
985              }
986              pm.SubmitChanges();
987
988              // add project assignments
989              foreach (var id in resourceIds) {
990                if(p.AssignedProjectResources.All(x => x.ResourceId != id)) {
991                  p.AssignedProjectResources.Add(new DA.AssignedProjectResource {
992                    ResourceId = id
993                  });
994                }
995              }
996            }
997          }
998          pm.SubmitChanges();
999        });
1000      }
1001    }
1002
1003    private void AssignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
1004      throw new NotImplementedException();
1005    }
1006
1007    // basic: unassign resourceIds from project and depending jobs
1008    // cascading: unassign resourceIds from all child-projects and their depending jobs
1009    private void UnassignProjectResources(Guid projectId, List<Guid> resourceIds, bool cascading) {
1010      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1011      if (projectId == null || resourceIds == null || !resourceIds.Any()) return;
1012      AuthorizationManager.AuthorizeForProjectResourceAdministration(projectId, resourceIds);
1013      var pm = PersistenceManager;
1014      using (new PerformanceLogger("UnassignProjectResources")) {
1015        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1016        var assignedJobResourceDao = pm.AssignedJobResourceDao;
1017        var projectDao = pm.ProjectDao;
1018        pm.UseTransaction(() => {
1019          if (cascading) {
1020            var childProjectIds = projectDao.GetChildProjectIdsById(projectId).ToList();
1021            assignedProjectResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
1022            assignedJobResourceDao.DeleteByProjectIdsAndResourceIds(childProjectIds, resourceIds);
1023          }
1024          assignedProjectResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
1025          assignedJobResourceDao.DeleteByProjectIdAndResourceIds(projectId, resourceIds);
1026          pm.SubmitChanges();
1027        });
1028      }
1029    }
1030
1031    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProject(Guid projectId) {
1032      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1033      AuthorizationManager.AuthorizeUserForProjectUse(UserManager.CurrentUserId, projectId);
1034      var pm = PersistenceManager;
1035      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1036        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1037        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1038          .Select(x => x.ToDto())
1039          .ToList()
1040        );
1041      }
1042    }
1043
1044    public IEnumerable<DT.AssignedProjectResource> GetAssignedResourcesForProjectAdministration(Guid projectId) {
1045      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1046      AuthorizationManager.AuthorizeForProjectAdministration(projectId, false);
1047      var pm = PersistenceManager;
1048      using (new PerformanceLogger("GetAssignedResourcesForProject")) {
1049        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1050        return pm.UseTransaction(() => assignedProjectResourceDao.GetByProjectId(projectId)
1051          .Select(x => x.ToDto())
1052          .ToList()
1053        );
1054      }
1055    }
1056
1057    #endregion
1058
1059    #region Slave Methods
1060    public Guid AddSlave(DT.Slave slaveDto) {
1061      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1062      var pm = PersistenceManager;
1063      using (new PerformanceLogger("AddSlave")) {
1064        var slaveDao = pm.SlaveDao;
1065        return pm.UseTransaction(() => {
1066          var slave = slaveDao.Save(slaveDto.ToEntity());
1067          pm.SubmitChanges();
1068          return slave.ResourceId;
1069        });
1070      }
1071    }
1072
1073    public Guid AddSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1074      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1075      var pm = PersistenceManager;
1076      using (new PerformanceLogger("AddSlaveGroup")) {
1077        var slaveGroupDao = pm.SlaveGroupDao;
1078        return pm.UseTransaction(() => {
1079          if (slaveGroupDto.Id == Guid.Empty) {
1080            slaveGroupDto.Id = Guid.NewGuid();
1081          }
1082          var slaveGroup = slaveGroupDao.Save(slaveGroupDto.ToEntity());
1083          pm.SubmitChanges();
1084          return slaveGroup.ResourceId;
1085        });
1086      }
1087    }
1088
1089    public DT.Slave GetSlave(Guid slaveId) {
1090      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1091      var pm = PersistenceManager;
1092      using (new PerformanceLogger("GetSlave")) {
1093        var slaveDao = pm.SlaveDao;
1094        return pm.UseTransaction(() => slaveDao.GetById(slaveId).ToDto());
1095      }
1096    }
1097
1098    // query granted slaves for use (i.e. to calculate on)
1099    public IEnumerable<DT.Slave> GetSlaves() {
1100      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1101      var pm = PersistenceManager;
1102      using (new PerformanceLogger("GetSlaves")) {
1103        var slaveDao = pm.SlaveDao;
1104        var projectDao = pm.ProjectDao;
1105        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1106
1107        // collect user information
1108        var currentUserId = UserManager.CurrentUserId;
1109        var userAndGroupIds = new List<Guid> { currentUserId };
1110        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
1111
1112        return pm.UseTransaction(() => {
1113          var slaves = slaveDao.GetAll()
1114            .Select(x => x.ToDto())
1115            .ToList();
1116          var grantedProjectIds = projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
1117            .Select(x => x.ProjectId)
1118            .ToList();
1119          var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourcesByProjectIds(grantedProjectIds)
1120            .Select(x => x.ResourceId)
1121            .ToList();
1122
1123          return slaves
1124            .Where(x => grantedResourceIds.Contains(x.Id))
1125            .ToList();
1126        });
1127      }
1128    }
1129
1130    // query granted slave groups for use (i.e. to calculate on)
1131    public IEnumerable<DT.SlaveGroup> GetSlaveGroups() {
1132      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1133      var pm = PersistenceManager;
1134      using (new PerformanceLogger("GetSlaveGroups")) {
1135        var slaveGroupDao = pm.SlaveGroupDao;
1136        var projectDao = pm.ProjectDao;
1137        var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1138
1139        // collect user information
1140        var currentUserId = UserManager.CurrentUserId;
1141        var userAndGroupIds = new List<Guid> { currentUserId };
1142        userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(currentUserId));
1143
1144        return pm.UseTransaction(() => {
1145          var slaveGroups = slaveGroupDao.GetAll()
1146            .Select(x => x.ToDto())
1147            .ToList();
1148          var grantedProjectIds = projectDao.GetUsageGrantedProjectsForUser(userAndGroupIds)
1149            .Select(x => x.ProjectId)
1150            .ToList();
1151          var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourcesByProjectIds(grantedProjectIds)
1152            .Select(x => x.ResourceId)
1153            .ToList();
1154
1155          return slaveGroups
1156            .Where(x => grantedResourceIds.Contains(x.Id))
1157            .ToList();
1158        });
1159      }
1160    }
1161
1162    // query granted slaves for resource administration
1163    public IEnumerable<DT.Slave> GetSlavesForAdministration() {
1164      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1165      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1166      var pm = PersistenceManager;
1167      using (new PerformanceLogger("GetSlavesForAdministration")) {
1168        var slaveDao = pm.SlaveDao;
1169        var currentUserId = UserManager.CurrentUserId;
1170
1171        if (isAdministrator) {
1172          return pm.UseTransaction(() => {
1173            return slaveDao.GetAll()
1174              .Select(x => x.ToDto())
1175              .ToList();
1176          });
1177        } else {
1178          var slaves = slaveDao.GetAll()
1179            .Select(x => x.ToDto())
1180            .ToList();
1181          var projectDao = pm.ProjectDao;
1182          var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1183          var projects = projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).ToList();
1184          var resourceIds = assignedProjectResourceDao
1185            .GetAllGrantedResourcesByProjectIds(projects.Select(x => x.ProjectId).ToList())
1186            .Select(x => x.ResourceId)
1187            .ToList();
1188
1189          return slaves
1190            .Where(x => resourceIds.Contains(x.Id))
1191            .ToList();
1192        }
1193      }
1194    }
1195
1196    // query granted slave groups for resource administration
1197    public IEnumerable<DT.SlaveGroup> GetSlaveGroupsForAdministration() {
1198      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1199      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1200      var pm = PersistenceManager;
1201      using (new PerformanceLogger("GetSlaveGroupsForAdministration")) {
1202        var slaveGroupDao = pm.SlaveGroupDao;
1203        var currentUserId = UserManager.CurrentUserId;
1204
1205        if (isAdministrator) {
1206          return pm.UseTransaction(() => {
1207            return slaveGroupDao.GetAll()
1208              .Select(x => x.ToDto())
1209              .ToList();
1210          });
1211        } else {
1212          var slaveGroups = slaveGroupDao.GetAll()
1213            .Select(x => x.ToDto())
1214            .ToList();
1215          var projectDao = pm.ProjectDao;
1216          var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
1217          var projects = projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).ToList();
1218          var resourceIds = assignedProjectResourceDao
1219            .GetAllGrantedResourcesByProjectIds(projects.Select(x => x.ProjectId).ToList())
1220            .Select(x => x.ResourceId)
1221            .ToList();
1222
1223          return slaveGroups
1224            .Where(x => resourceIds.Contains(x.Id))
1225            .ToList();
1226        }
1227      }
1228    }
1229
1230    public void UpdateSlave(DT.Slave slaveDto) {
1231      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1232      if (slaveDto == null) return;
1233      AuthorizationManager.AuthorizeForResourceAdministration(slaveDto.Id);
1234      var pm = PersistenceManager;
1235      using (new PerformanceLogger("UpdateSlave")) {
1236        var slaveDao = pm.SlaveDao;
1237        pm.UseTransaction(() => {
1238          var slave = slaveDao.GetById(slaveDto.Id);
1239          if (slave != null) {
1240            slaveDto.CopyToEntity(slave);
1241          } else {
1242            slaveDao.Save(slaveDto.ToEntity());
1243          }
1244          pm.SubmitChanges();
1245        });
1246      }
1247    }
1248
1249    public void UpdateSlaveGroup(DT.SlaveGroup slaveGroupDto) {
1250      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1251      if (slaveGroupDto == null) return;
1252      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupDto.Id);
1253      var pm = PersistenceManager;
1254      using (new PerformanceLogger("UpdateSlaveGroup")) {
1255        var slaveGroupDao = pm.SlaveGroupDao;
1256        pm.UseTransaction(() => {
1257          var slaveGroup = slaveGroupDao.GetById(slaveGroupDto.Id);
1258          if (slaveGroup != null) {
1259            slaveGroupDto.CopyToEntity(slaveGroup);
1260          } else {
1261            slaveGroupDao.Save(slaveGroupDto.ToEntity());
1262          }
1263          pm.SubmitChanges();
1264        });
1265      }
1266    }
1267
1268    public void DeleteSlave(Guid slaveId) {
1269      if (slaveId == Guid.Empty) return;
1270      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1271      AuthorizationManager.AuthorizeForResourceAdministration(slaveId);
1272      var pm = PersistenceManager;
1273      using (new PerformanceLogger("DeleteSlave")) {
1274        var slaveDao = pm.SlaveDao;
1275        pm.UseTransaction(() => {
1276          slaveDao.Delete(slaveId);
1277          pm.SubmitChanges();
1278        });
1279      }
1280    }
1281
1282    public void DeleteSlaveGroup(Guid slaveGroupId) {
1283      if (slaveGroupId == Guid.Empty) return;
1284      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1285      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupId);
1286      var pm = PersistenceManager;
1287      using (new PerformanceLogger("DeleteSlaveGroup")) {
1288        var resourceDao = pm.ResourceDao;
1289        pm.UseTransaction(() => {
1290          var resourceIds = new HashSet<Guid> { slaveGroupId };
1291          resourceIds.Union(resourceDao.GetChildResourceIdsById(slaveGroupId));
1292          resourceDao.DeleteByIds(resourceIds);
1293          pm.SubmitChanges();
1294        });
1295      }
1296    }
1297
1298    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
1299      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1300      var pm = PersistenceManager;
1301      using (new PerformanceLogger("AddResourceToGroup")) {
1302        var resourceDao = pm.ResourceDao;
1303        pm.UseTransaction(() => {
1304          var resource = resourceDao.GetById(resourceId);
1305          resource.ParentResourceId = slaveGroupId;
1306          pm.SubmitChanges();
1307        });
1308      }
1309    }
1310
1311    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
1312      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1313      var pm = PersistenceManager;
1314      using (new PerformanceLogger("RemoveResourceFromGroup")) {
1315        var resourceDao = pm.ResourceDao;
1316        pm.UseTransaction(() => {
1317          var resource = resourceDao.GetById(resourceId);
1318          resource.ParentResourceId = null;
1319          pm.SubmitChanges();
1320        });
1321      }
1322    }
1323
1324    public Guid GetResourceId(string resourceName) {
1325      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1326      var pm = PersistenceManager;
1327      using (new PerformanceLogger("GetResourceId")) {
1328        var resourceDao = pm.ResourceDao;
1329        return pm.UseTransaction(() => {
1330          var resource = resourceDao.GetByName(resourceName);
1331          return resource != null ? resource.ResourceId : Guid.Empty;
1332        });
1333      }
1334    }
1335
1336    public void TriggerEventManager(bool force) {
1337      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
1338      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
1339      bool cleanup;
1340      var pm = PersistenceManager;
1341      using (new PerformanceLogger("TriggerEventManager")) {
1342        cleanup = false;
1343        var lifecycleDao = pm.LifecycleDao;
1344        pm.UseTransaction(() => {
1345          var lastLifecycle = lifecycleDao.GetLastLifecycle();
1346          DateTime lastCleanup = lastLifecycle != null ? lastLifecycle.LastCleanup : DateTime.MinValue;
1347          if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
1348            lifecycleDao.UpdateLifecycle();
1349            cleanup = true;
1350            pm.SubmitChanges();
1351          }
1352        }, true);
1353      }
1354      if (cleanup) {
1355        EventManager.Cleanup();
1356      }
1357    }
1358
1359    public int GetNewHeartbeatInterval(Guid slaveId) {
1360      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
1361      var pm = PersistenceManager;
1362      using (new PerformanceLogger("GetNewHeartbeatInterval")) {
1363        var slaveDao = pm.SlaveDao;
1364        return pm.UseTransaction(() => {
1365          var slave = slaveDao.GetById(slaveId);
1366          if (slave != null) {
1367            return slave.HbInterval;
1368          }
1369          return -1;
1370        });
1371      }
1372    }
1373    #endregion
1374
1375    #region Downtime Methods
1376    public Guid AddDowntime(DT.Downtime downtimeDto) {
1377      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1378      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1379      var pm = PersistenceManager;
1380      using (new PerformanceLogger("AddDowntime")) {
1381        var downtimeDao = pm.DowntimeDao;
1382        return pm.UseTransaction(() => {
1383          var downtime = downtimeDao.Save(downtimeDto.ToEntity());
1384          pm.SubmitChanges();
1385          return downtime.ResourceId;
1386        });
1387      }
1388    }
1389
1390    public void DeleteDowntime(Guid downtimeId) {
1391      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1392      var pm = PersistenceManager;
1393      using (new PerformanceLogger("DeleteDowntime")) {
1394        var downtimeDao = pm.DowntimeDao;
1395        pm.UseTransaction(() => {
1396          downtimeDao.Delete(downtimeId);
1397          pm.SubmitChanges();
1398        });
1399      }
1400    }
1401
1402    public void UpdateDowntime(DT.Downtime downtimeDto) {
1403      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1404      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
1405      var pm = PersistenceManager;
1406      using (new PerformanceLogger("UpdateDowntime")) {
1407        var downtimeDao = pm.DowntimeDao;
1408        pm.UseTransaction(() => {
1409          var downtime = downtimeDao.GetById(downtimeDto.Id);
1410          if (downtime != null) {
1411            downtimeDto.CopyToEntity(downtime);
1412          } else {
1413            downtimeDao.Save(downtimeDto.ToEntity());
1414          }
1415          pm.SubmitChanges();
1416        });
1417      }
1418    }
1419
1420    public IEnumerable<DT.Downtime> GetDowntimesForResource(Guid resourceId) {
1421      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1422      var pm = PersistenceManager;
1423      using (new PerformanceLogger("GetDowntimesForResource")) {
1424        var downtimeDao = pm.DowntimeDao;
1425        return pm.UseTransaction(() => downtimeDao.GetByResourceId(resourceId)
1426          .Select(x => x.ToDto())
1427          .ToList()
1428        );
1429      }
1430    }
1431    #endregion
1432
1433    #region User Methods
1434    public string GetUsernameByUserId(Guid userId) {
1435      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1436      var user = UserManager.GetUserById(userId);
1437      return user != null ? user.UserName : null;
1438    }
1439
1440    public Guid GetUserIdByUsername(string username) {
1441      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1442      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
1443      return user != null ? (Guid?)user.ProviderUserKey ?? Guid.Empty : Guid.Empty;
1444    }
1445   
1446    public Dictionary<Guid, HashSet<Guid>> GetUserGroupTree() {
1447      var userGroupTree = new Dictionary<Guid, HashSet<Guid>>();
1448      var userGroupMapping = UserManager.GetUserGroupMapping();
1449
1450      foreach(var ugm in userGroupMapping) {
1451        if (ugm.Parent == null || ugm.Child == null) continue;
1452
1453        if (!userGroupTree.ContainsKey(ugm.Parent)) {
1454          userGroupTree.Add(ugm.Parent, new HashSet<Guid>());
1455        }
1456        userGroupTree[ugm.Parent].Add(ugm.Child);
1457      }
1458
1459      return userGroupTree;
1460    }
1461
1462    public bool CheckAccessToAdminAreaGranted() {
1463      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
1464      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
1465      var pm = PersistenceManager;
1466      using(new PerformanceLogger("CheckAccessToAdminAreaGranted")) {
1467        if (isAdministrator) {
1468          return true;
1469        } else {
1470          var projectDao = pm.ProjectDao;
1471          var currentUserId = UserManager.CurrentUserId;
1472          return projectDao.GetAdministrationGrantedProjectsForUser(currentUserId).Any();
1473        }
1474      }
1475    }
1476    #endregion
1477
1478    #region UserPriorities Methods
1479    public IEnumerable<DT.UserPriority> GetUserPriorities() {
1480      var pm = PersistenceManager;
1481      using (new PerformanceLogger("GetUserPriorities")) {
1482        var userPriorityDao = pm.UserPriorityDao;
1483        return pm.UseTransaction(() => userPriorityDao.GetAll()
1484          .Select(x => x.ToDto())
1485          .ToList()
1486        );
1487      }
1488    }
1489    #endregion
1490
1491    #region Private Helper Methods
1492    private void UpdateTaskState(IPersistenceManager pm, DA.Task task, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
1493      var stateLogDao = pm.StateLogDao;
1494      var taskStateEntity = taskState.ToEntity();
1495
1496      if (task.State == DA.TaskState.Transferring && taskStateEntity == DA.TaskState.Paused && task.Command == null) {
1497        // slave paused and uploaded the task (no user-command) -> set waiting.
1498        taskStateEntity = DA.TaskState.Waiting;
1499      }
1500
1501      stateLogDao.Save(new DA.StateLog {
1502        State = taskStateEntity,
1503        DateTime = DateTime.Now,
1504        TaskId = task.TaskId,
1505        UserId = userId,
1506        SlaveId = slaveId,
1507        Exception = exception
1508      });
1509
1510      task.State = taskStateEntity;
1511
1512      if (task.Command == DA.Command.Pause && task.State == DA.TaskState.Paused
1513          || task.Command == DA.Command.Abort && task.State == DA.TaskState.Aborted
1514          || task.Command == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
1515        task.Command = null;
1516      }
1517    }
1518
1519    #endregion
1520  }
1521}
Note: See TracBrowser for help on using the repository browser.