Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15503 was 15503, checked in by jzenisek, 5 years ago

#2839 added ResourcePermission handling (still in progress)

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