source: branches/HiveResourcePermissionManagement (trunk integration)/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 7950

Last change on this file since 7950 was 7950, checked in by jkarder, 9 years ago

#1860:

  • added ResourcePermission data transfer object
  • added resource permission management service methods
  • added authorization service method for resource administration
  • HiveService now uses AccessService infrastructure
File size: 29.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.ServiceModel;
26using HeuristicLab.Services.Hive.DataTransfer;
27using HeuristicLab.Services.Hive.ServiceContracts;
28using DA = HeuristicLab.Services.Hive.DataAccess;
29using DT = HeuristicLab.Services.Hive.DataTransfer;
30
31
32namespace HeuristicLab.Services.Hive {
33
34  /// <summary>
35  /// Implementation of the Hive service (interface <see cref="IHiveService"/>).
36  /// We need 'IgnoreExtensionDataObject' Attribute for the slave to work.
37  /// </summary>
38  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, IgnoreExtensionDataObject = true)]
39  public class HiveService : IHiveService {
40    private IHiveDao dao {
41      get { return ServiceLocator.Instance.HiveDao; }
42    }
43    private HeuristicLab.Services.Access.IRoleVerifier authen {
44      get { return ServiceLocator.Instance.AuthenticationManager; }
45    }
46    private IAuthorizationManager author {
47      get { return ServiceLocator.Instance.AuthorizationManager; }
48    }
49    private DataAccess.ITransactionManager trans {
50      get { return ServiceLocator.Instance.TransactionManager; }
51    }
52    private IEventManager eventManager {
53      get { return ServiceLocator.Instance.EventManager; }
54    }
55    private HeuristicLab.Services.Access.IUserManager userManager {
56      get { return ServiceLocator.Instance.UserManager; }
57    }
58    private HeartbeatManager heartbeatManager {
59      get { return ServiceLocator.Instance.HeartbeatManager; }
60    }
61
62    #region Authorization Methods
63    public bool AuthorizesForResourceAdministration(Guid resourceId) {
64      try {
65        author.AuthorizeForResourceAdministration(resourceId);
66        return true;
67      }
68      catch (System.Security.SecurityException) { return false; }
69    }
70    #endregion
71
72    #region Task Methods
73    public Guid AddTask(Task task, TaskData taskData, IEnumerable<Guid> resourceIds) {
74      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
75      return trans.UseTransaction(() => {
76        task.Id = dao.AddTask(task);
77        taskData.TaskId = task.Id;
78        taskData.LastUpdate = DateTime.Now;
79        foreach (Guid slaveGroupId in resourceIds) {
80          dao.AssignJobToResource(task.Id, slaveGroupId);
81        }
82        dao.AddTaskData(taskData);
83        dao.UpdateTaskState(task.Id, DA.TaskState.Waiting, null, userManager.CurrentUserId, null);
84        return taskData.TaskId;
85      }, false, true);
86    }
87
88    public Guid AddChildTask(Guid parentTaskId, Task task, TaskData taskData) {
89      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
90      return trans.UseTransaction(() => {
91        task.ParentTaskId = parentTaskId;
92        return AddTask(task, taskData, dao.GetAssignedResources(parentTaskId).Select(x => x.Id));
93      }, false, true);
94    }
95
96    public Task GetTask(Guid taskId) {
97      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
98      author.AuthorizeForTask(taskId, Permission.Read);
99
100      return trans.UseTransaction(() => {
101        return dao.GetTask(taskId);
102      }, false, false);
103    }
104
105    public IEnumerable<Task> GetTasks() {
106      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
107      var tasks = dao.GetTasks(x => true);
108      foreach (var task in tasks)
109        author.AuthorizeForTask(task.Id, Permission.Read);
110      return tasks;
111    }
112
113    public IEnumerable<LightweightTask> GetLightweightTasks(IEnumerable<Guid> taskIds) {
114      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
115
116      return trans.UseTransaction(() => {
117        var tasks = dao.GetTasks(x => taskIds.Contains(x.TaskId)).Select(x => new LightweightTask(x)).ToArray();
118        foreach (var task in tasks)
119          author.AuthorizeForTask(task.Id, Permission.Read);
120        return tasks;
121      }, false, false);
122    }
123
124    public IEnumerable<LightweightTask> GetLightweightChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
125      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
126
127      return trans.UseTransaction(() => {
128        var tasks = GetChildTasks(parentTaskId, recursive, includeParent).Select(x => new LightweightTask(x)).ToArray();
129        foreach (var task in tasks)
130          author.AuthorizeForTask(task.Id, Permission.Read);
131        return tasks;
132      }, false, false);
133    }
134
135    public IEnumerable<LightweightTask> GetLightweightJobTasks(Guid jobId) {
136      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
137      author.AuthorizeForJob(jobId, Permission.Read);
138
139      return trans.UseTransaction(() => {
140        return dao.GetTasks(x => x.JobId == jobId).Select(x => new LightweightTask(x)).ToArray();
141      }, false, false);
142    }
143
144    public TaskData GetTaskData(Guid taskId) {
145      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
146      author.AuthorizeForTask(taskId, Permission.Read);
147      return dao.GetTaskData(taskId);
148    }
149
150    public void UpdateTask(Task taskDto) {
151      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
152      author.AuthorizeForTask(taskDto.Id, Permission.Full);
153      trans.UseTransaction(() => {
154        dao.UpdateTask(taskDto);
155      });
156    }
157
158    public void UpdateTaskData(Task task, TaskData taskData) {
159      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
160      author.AuthorizeForTask(task.Id, Permission.Full);
161      author.AuthorizeForTask(taskData.TaskId, Permission.Full);
162      //trans.UseTransaction(() => { // cneumuel: try without transaction
163      taskData.LastUpdate = DateTime.Now;
164      dao.UpdateTask(task);
165      dao.UpdateTaskData(taskData);
166      //}, false, true);
167    }
168
169    public void DeleteTask(Guid taskId) {
170      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
171      author.AuthorizeForTask(taskId, Permission.Full);
172      trans.UseTransaction(() => {
173        dao.DeleteTask(taskId);
174      });
175    }
176
177    public void DeleteChildTasks(Guid parentTaskId) {
178      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
179      author.AuthorizeForTask(parentTaskId, Permission.Full);
180      trans.UseTransaction(() => {
181        var tasks = GetChildTasks(parentTaskId, true, false);
182        foreach (var task in tasks) {
183          dao.DeleteTask(task.Id);
184          dao.DeleteTaskData(task.Id);
185        };
186      });
187    }
188
189    public Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
190      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
191      author.AuthorizeForTask(taskId, Permission.Full);
192      return trans.UseTransaction(() => {
193        Task task = dao.UpdateTaskState(taskId, DataTransfer.Convert.ToEntity(taskState), slaveId, userId, exception);
194
195        if (task.Command.HasValue && task.Command.Value == Command.Pause && task.State == TaskState.Paused) {
196          task.Command = null;
197        } else if (task.Command.HasValue && task.Command.Value == Command.Abort && task.State == TaskState.Aborted) {
198          task.Command = null;
199        } else if (task.Command.HasValue && task.Command.Value == Command.Stop && task.State == TaskState.Aborted) {
200          task.Command = null;
201        } else if (taskState == TaskState.Paused && !task.Command.HasValue) {
202          // slave paused and uploaded the task (no user-command) -> set waiting.
203          task = dao.UpdateTaskState(taskId, DataTransfer.Convert.ToEntity(TaskState.Waiting), slaveId, userId, exception);
204        }
205
206        dao.UpdateTask(task);
207        return task;
208      });
209    }
210
211    public IEnumerable<Task> GetTasksByResourceId(Guid resourceId) {
212      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
213      var tasks = trans.UseTransaction(() => dao.GetJobsByResourceId(resourceId));
214      foreach (var task in tasks)
215        author.AuthorizeForTask(task.Id, Permission.Read);
216      return tasks;
217    }
218    #endregion
219
220    #region Task Control Methods
221    public void StopTask(Guid taskId) {
222      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
223      author.AuthorizeForTask(taskId, Permission.Full);
224      trans.UseTransaction(() => {
225        var task = dao.GetTask(taskId);
226        if (task.State == TaskState.Calculating || task.State == TaskState.Transferring) {
227          task.Command = Command.Stop;
228          dao.UpdateTask(task);
229        } else {
230          if (task.State != TaskState.Aborted && task.State != TaskState.Finished && task.State != TaskState.Failed) {
231            task = UpdateTaskState(taskId, TaskState.Aborted, null, null, string.Empty);
232          }
233        }
234      });
235    }
236
237    public void PauseTask(Guid taskId) {
238      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
239      author.AuthorizeForTask(taskId, Permission.Full);
240      trans.UseTransaction(() => {
241        var job = dao.GetTask(taskId);
242        if (job.State == TaskState.Calculating || job.State == TaskState.Transferring) {
243          job.Command = Command.Pause;
244          dao.UpdateTask(job);
245        } else {
246          job = UpdateTaskState(taskId, TaskState.Paused, null, null, string.Empty);
247        }
248      });
249    }
250
251    public void RestartTask(Guid taskId) {
252      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
253      author.AuthorizeForTask(taskId, Permission.Full);
254      trans.UseTransaction(() => {
255        Task task = dao.UpdateTaskState(taskId, DA.TaskState.Waiting, null, userManager.CurrentUserId, string.Empty);
256        task.Command = null;
257        dao.UpdateTask(task);
258      });
259    }
260    #endregion
261
262    #region Job Methods
263    public Job GetJob(Guid id) {
264      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
265      author.AuthorizeForJob(id, Permission.Read);
266      var job = dao.GetJobs(x =>
267            x.JobId == id
268            && (x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0)
269          ).FirstOrDefault();
270      if (job != null) {
271        job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
272        job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
273      }
274      return job;
275    }
276
277    public IEnumerable<Job> GetJobs() {
278      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
279      var jobs = dao.GetJobs(x => x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0);
280      foreach (var job in jobs) {
281        author.AuthorizeForJob(job.Id, Permission.Read);
282        job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
283        job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
284      }
285      return jobs;
286    }
287
288    public IEnumerable<Job> GetAllJobs() {
289      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
290      var jobs = dao.GetJobs(x => true);
291      foreach (var job in jobs) { // no authorization here, since this method is admin-only! (admin is allowed to read all task)
292        job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
293        job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
294      }
295      return jobs;
296    }
297
298    public Guid AddJob(Job jobDto) {
299      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
300      return trans.UseTransaction(() => {
301        jobDto.OwnerUserId = userManager.CurrentUserId;
302        jobDto.DateCreated = DateTime.Now;
303        return dao.AddJob(jobDto);
304      });
305    }
306
307    public void UpdateJob(Job jobDto) {
308      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
309      author.AuthorizeForJob(jobDto.Id, Permission.Full);
310      trans.UseTransaction(() => {
311        dao.UpdateJob(jobDto);
312      });
313    }
314
315    public void DeleteJob(Guid jobId) {
316      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
317      author.AuthorizeForJob(jobId, Permission.Full);
318      trans.UseTransaction(() => {
319        dao.DeleteJob(jobId); // child task will be deleted by db-trigger
320      });
321    }
322    #endregion
323
324    #region JobPermission Methods
325    public void GrantPermission(Guid jobId, Guid grantedUserId, Permission permission) {
326      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
327      trans.UseTransaction(() => {
328        Job job = dao.GetJob(jobId);
329        if (job == null) throw new FaultException<FaultReason>(new FaultReason("Could not find task with id " + jobId));
330        Permission perm = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
331        if (perm != Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
332        dao.SetJobPermission(jobId, userManager.CurrentUserId, grantedUserId, DT.Convert.ToEntity(permission));
333      });
334    }
335
336    public void RevokePermission(Guid jobId, Guid grantedUserId) {
337      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
338      trans.UseTransaction(() => {
339        Job job = dao.GetJob(jobId);
340        if (job == null) throw new FaultException<FaultReason>(new FaultReason("Could not find task with id " + jobId));
341        DA.Permission perm = dao.GetPermissionForJob(job.Id, userManager.CurrentUserId);
342        if (perm != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
343        dao.SetJobPermission(jobId, userManager.CurrentUserId, grantedUserId, DA.Permission.NotAllowed);
344      });
345    }
346
347    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
348      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
349      return trans.UseTransaction(() => {
350        DA.Permission currentUserPermission = dao.GetPermissionForJob(jobId, userManager.CurrentUserId);
351        if (currentUserPermission != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to list permissions for this experiment"));
352        return dao.GetJobPermissions(x => x.JobId == jobId);
353      });
354    }
355
356    public bool IsAllowedPrivileged() {
357      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
358      return authen.IsInRole(HiveRoles.IsAllowedPrivileged);
359    }
360    #endregion
361
362    #region Login Methods
363    public void Hello(Slave slaveInfo) {
364      authen.AuthenticateForAnyRole(HiveRoles.Slave);
365      if (userManager.CurrentUser.UserName != "hiveslave")
366        slaveInfo.OwnerUserId = userManager.CurrentUserId;
367
368      trans.UseTransaction(() => {
369        var slave = dao.GetSlave(slaveInfo.Id);
370
371        if (slave == null) {
372          dao.AddSlave(slaveInfo);
373        } else {
374          slave.Name = slaveInfo.Name;
375          slave.Description = slaveInfo.Description;
376          slave.OwnerUserId = slaveInfo.OwnerUserId;
377
378          slave.Cores = slaveInfo.Cores;
379          slave.CpuArchitecture = slaveInfo.CpuArchitecture;
380          slave.CpuSpeed = slaveInfo.CpuSpeed;
381          slave.FreeCores = slaveInfo.FreeCores;
382          slave.FreeMemory = slaveInfo.FreeMemory;
383          slave.Memory = slaveInfo.Memory;
384          slave.OperatingSystem = slaveInfo.OperatingSystem;
385
386          slave.LastHeartbeat = DateTime.Now;
387          slave.SlaveState = SlaveState.Idle;
388
389          // don't update those properties: dbSlave.IsAllowedToCalculate, dbSlave.ParentResourceId
390
391          dao.UpdateSlave(slave);
392        }
393      });
394    }
395
396    public void GoodBye(Guid slaveId) {
397      authen.AuthenticateForAnyRole(HiveRoles.Slave);
398      trans.UseTransaction(() => {
399        var slave = dao.GetSlave(slaveId);
400        if (slave != null) {
401          slave.SlaveState = SlaveState.Offline;
402          dao.UpdateSlave(slave);
403        }
404      });
405    }
406    #endregion
407
408    #region Heartbeat Methods
409    public List<MessageContainer> Heartbeat(Heartbeat heartbeat) {
410      authen.AuthenticateForAnyRole(HiveRoles.Slave);
411
412      List<MessageContainer> result = trans.UseTransaction(() => heartbeatManager.ProcessHeartbeat(heartbeat));
413
414      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
415        TriggerEventManager(false);
416      }
417
418      return result;
419    }
420    #endregion
421
422    #region Plugin Methods
423    public Guid AddPlugin(Plugin plugin, List<PluginData> pluginDatas) {
424      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
425      return trans.UseTransaction(() => {
426        plugin.UserId = userManager.CurrentUserId;
427        plugin.DateCreated = DateTime.Now;
428
429        var existing = dao.GetPlugins(x => x.Hash != null).Where(x => x.Hash.SequenceEqual(plugin.Hash));
430        if (existing.Count() > 0) {
431          // a plugin already exists.
432          throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(existing.Single().Id));
433        }
434
435        Guid pluginId = dao.AddPlugin(plugin);
436        foreach (PluginData pluginData in pluginDatas) {
437          pluginData.PluginId = pluginId;
438          dao.AddPluginData(pluginData);
439        }
440        return pluginId;
441      });
442    }
443
444    public Plugin GetPlugin(Guid pluginId) {
445      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
446      return dao.GetPlugin(pluginId);
447    }
448
449    public Plugin GetPluginByHash(byte[] hash) {
450      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
451      return dao.GetPlugins(x => x.Hash == hash).FirstOrDefault();
452    }
453
454    // note: this is a possible security problem, since a client is able to download all plugins, which may contain proprietary code (which can be disassembled)
455    //       change so that only with GetPluginByHash it is possible to download plugins
456    public IEnumerable<Plugin> GetPlugins() {
457      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
458      return dao.GetPlugins(x => x.Hash != null);
459    }
460
461    public IEnumerable<PluginData> GetPluginDatas(List<Guid> pluginIds) {
462      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
463      var pluginDatas = new List<PluginData>();
464      return trans.UseTransaction(() => {
465        foreach (Guid guid in pluginIds) {
466          pluginDatas.AddRange(dao.GetPluginDatas(x => x.PluginId == guid).ToList());
467        }
468        return pluginDatas;
469      });
470    }
471
472    public void DeletePlugin(Guid pluginId) {
473      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
474      dao.DeletePlugin(pluginId);
475    }
476    #endregion
477
478    #region ResourcePermission Methods
479    public void GrantResourcePermissions(Guid resourceId, params Guid[] grantedUserIds) {
480      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
481      trans.UseTransaction(() => {
482        Resource resource = dao.GetResource(resourceId);
483        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
484        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permission for this resource"));
485        foreach (Guid id in grantedUserIds)
486          dao.AddResourcePermission(new ResourcePermission { ResourceId = resourceId, GrantedByUserId = userManager.CurrentUserId, GrantedUserId = id });
487      });
488    }
489
490    public void RevokeResourcePermissions(Guid resourceId, params Guid[] grantedUserIds) {
491      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
492      trans.UseTransaction(() => {
493        Resource resource = dao.GetResource(resourceId);
494        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
495        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to revoke permission for this resource"));
496        foreach (Guid id in grantedUserIds)
497          dao.DeleteResourcePermission(resourceId, id);
498      });
499    }
500
501    public IEnumerable<ResourcePermission> GetResourcePermissions(Guid resourceId) {
502      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
503      return trans.UseTransaction(() => {
504        Resource resource = dao.GetResource(resourceId);
505        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
506        return dao.GetResourcePermissions(x => x.ResourceId == resourceId);
507      });
508    }
509    #endregion
510
511    #region Slave Methods
512    public int GetNewHeartbeatInterval(Guid slaveId) {
513      authen.AuthenticateForAnyRole(HiveRoles.Slave);
514      Slave s = dao.GetSlave(slaveId);
515      if (s != null) {
516        return s.HbInterval;
517      } else {
518        return -1;
519      }
520    }
521
522    public Guid AddSlave(Slave slave) {
523      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
524      return trans.UseTransaction(() => dao.AddSlave(slave));
525    }
526
527    public Guid AddSlaveGroup(SlaveGroup slaveGroup) {
528      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
529      return trans.UseTransaction(() => dao.AddSlaveGroup(slaveGroup));
530    }
531
532    public Slave GetSlave(Guid slaveId) {
533      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
534      return dao.GetSlave(slaveId);
535    }
536
537    public SlaveGroup GetSlaveGroup(Guid slaveGroupId) {
538      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
539      return dao.GetSlaveGroup(slaveGroupId);
540    }
541
542    public IEnumerable<Slave> GetSlaves() {
543      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
544      return dao.GetSlaves(x => true).Where(x => x.OwnerUserId == null
545                                         || x.OwnerUserId == userManager.CurrentUserId
546                                         || userManager.VerifyUser(userManager.CurrentUserId, GetResourcePermissions(x.Id).Select(y => y.GrantedUserId).ToList())
547                                         || authen.IsInRole(HiveRoles.Administrator)).ToArray();
548    }
549
550    public IEnumerable<SlaveGroup> GetSlaveGroups() {
551      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
552      return dao.GetSlaveGroups(x => true).Where(x => x.OwnerUserId == null
553                                              || x.OwnerUserId == userManager.CurrentUserId
554                                              || userManager.VerifyUser(userManager.CurrentUserId, GetResourcePermissions(x.Id).Select(y => y.GrantedUserId).ToList())
555                                              || authen.IsInRole(HiveRoles.Administrator)).ToArray();
556    }
557
558    public void UpdateSlave(Slave slave) {
559      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
560      trans.UseTransaction(() => {
561        dao.UpdateSlave(slave);
562      });
563    }
564
565    public void UpdateSlaveGroup(SlaveGroup slaveGroup) {
566      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
567      trans.UseTransaction(() => {
568        dao.UpdateSlaveGroup(slaveGroup);
569      });
570    }
571
572    public void DeleteSlave(Guid slaveId) {
573      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
574      author.AuthorizeForResourceAdministration(slaveId);
575      trans.UseTransaction(() => {
576        dao.DeleteSlave(slaveId);
577      });
578    }
579
580    public void DeleteSlaveGroup(Guid slaveGroupId) {
581      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
582      author.AuthorizeForResourceAdministration(slaveGroupId);
583      trans.UseTransaction(() => {
584        dao.DeleteSlaveGroup(slaveGroupId);
585      });
586    }
587
588    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
589      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
590      trans.UseTransaction(() => {
591        var resource = dao.GetResource(resourceId);
592        resource.ParentResourceId = slaveGroupId;
593        dao.UpdateResource(resource);
594      });
595    }
596
597    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
598      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
599      trans.UseTransaction(() => {
600        var resource = dao.GetResource(resourceId);
601        resource.ParentResourceId = null;
602        dao.UpdateResource(resource);
603      });
604    }
605
606    public Guid GetResourceId(string resourceName) {
607      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
608      return trans.UseTransaction(() => {
609        var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
610        if (resource != null) {
611          return resource.Id;
612        } else {
613          return Guid.Empty;
614        }
615      });
616    }
617
618    public void TriggerEventManager(bool force) {
619      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Slave);
620      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
621      bool cleanup = false;
622      trans.UseTransaction(() => {
623        DateTime lastCleanup = dao.GetLastCleanup();
624        if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
625          dao.SetLastCleanup(DateTime.Now);
626          cleanup = true;
627        }
628      }, true);
629
630      if (cleanup) {
631        eventManager.Cleanup();
632      }
633    }
634    #endregion
635
636    #region Downtime Methods
637    public Guid AddDowntime(Downtime downtime) {
638      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
639      author.AuthorizeForResourceAdministration(downtime.ResourceId);
640      return trans.UseTransaction(() => dao.AddDowntime(downtime));
641    }
642
643    public void DeleteDowntime(Guid downtimeId) {
644      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
645      // TODO: pass resource id
646      // author.AuthorizeForResource(resourceId);
647      trans.UseTransaction(() => {
648        dao.DeleteDowntime(downtimeId);
649      });
650    }
651
652    public void UpdateDowntime(Downtime downtime) {
653      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
654      author.AuthorizeForResourceAdministration(downtime.ResourceId);
655      trans.UseTransaction(() => {
656        dao.UpdateDowntime(downtime);
657      });
658    }
659
660    public IEnumerable<Downtime> GetDowntimesForResource(Guid resourceId) {
661      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
662      return trans.UseTransaction(() => dao.GetDowntimes(x => x.ResourceId == resourceId));
663    }
664    #endregion
665
666    #region User Methods
667    public string GetUsernameByUserId(Guid userId) {
668      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
669      var user = ServiceLocator.Instance.UserManager.GetUserById(userId);
670      if (user != null)
671        return user.UserName;
672      else
673        return null;
674    }
675
676    public Guid GetUserIdByUsername(string username) {
677      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
678      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
679      return user != null ? (Guid)user.ProviderUserKey : Guid.Empty;
680    }
681    #endregion
682
683    #region Helper Methods
684    private IEnumerable<Task> GetChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
685      var tasks = new List<Task>(dao.GetTasks(x => parentTaskId == null ? !x.ParentTaskId.HasValue : x.ParentTaskId.Value == parentTaskId));
686
687      if (recursive) {
688        var childs = new List<Task>();
689        foreach (var task in tasks) {
690          childs.AddRange(GetChildTasks(task.Id, recursive, false));
691        }
692        tasks.AddRange(childs);
693      }
694
695      if (includeParent) tasks.Add(GetTask(parentTaskId.Value));
696      return tasks;
697    }
698    #endregion
699  }
700}
Note: See TracBrowser for help on using the repository browser.