Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2839 worked on resource permission checks (v2 = accelerated verison)

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