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

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

#1860:

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