Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 9420

Last change on this file since 9420 was 9257, checked in by ascheibe, 12 years ago

#2019

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