Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 9779

Last change on this file since 9779 was 8085, checked in by gkronber, 13 years ago

#1847: merged trunk changes r7800:HEAD into gp move operators branch

File size: 28.9 KB
RevLine 
[6983]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6983]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    }
[8085]43    private Access.IRoleVerifier authen {
44      get { return ServiceLocator.Instance.RoleVerifier; }
[6983]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    }
[8085]55    private Access.IUserManager userManager {
[6983]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);
[7045]89
90      return trans.UseTransaction(() => {
91        return dao.GetTask(taskId);
92      }, false, false);
[6983]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);
[7045]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);
[6983]112    }
113
114    public IEnumerable<LightweightTask> GetLightweightChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
115      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[7045]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);
[6983]123    }
124
125    public IEnumerable<LightweightTask> GetLightweightJobTasks(Guid jobId) {
126      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
127      author.AuthorizeForJob(jobId, Permission.Read);
[7045]128
129      return trans.UseTransaction(() => {
130        return dao.GetTasks(x => x.JobId == jobId).Select(x => new LightweightTask(x)).ToArray();
131      }, false, false);
[6983]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    }
[8085]336
[6983]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);
[8085]355      if (userManager.CurrentUser.UserName != "hiveslave")
356        slaveInfo.OwnerUserId = userManager.CurrentUserId;
357
[6983]358      trans.UseTransaction(() => {
359        var slave = dao.GetSlave(slaveInfo.Id);
360
361        if (slave == null) {
362          dao.AddSlave(slaveInfo);
363        } else {
[8085]364          slave.Name = slaveInfo.Name;
365          slave.Description = slaveInfo.Description;
366          slave.OwnerUserId = slaveInfo.OwnerUserId;
[6983]367
[8085]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;
[6983]375
[8085]376          slave.LastHeartbeat = DateTime.Now;
377          slave.SlaveState = SlaveState.Idle;
[6983]378
379          // don't update those properties: dbSlave.IsAllowedToCalculate, dbSlave.ParentResourceId
380
[8085]381          dao.UpdateSlave(slave);
[6983]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);
[7189]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;
[6983]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
[8085]468    #region ResourcePermission Methods
469    public void GrantResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
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 && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permission for this resource"));
475        foreach (Guid id in grantedUserIds)
476          dao.AddResourcePermission(new ResourcePermission { ResourceId = resourceId, GrantedByUserId = userManager.CurrentUserId, GrantedUserId = id });
477      });
478    }
479
480    public void RevokeResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
481      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
482      trans.UseTransaction(() => {
483        Resource resource = dao.GetResource(resourceId);
484        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
485        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to revoke permission for this resource"));
486        foreach (Guid id in grantedUserIds)
487          dao.DeleteResourcePermission(resourceId, id);
488      });
489    }
490
491    public IEnumerable<ResourcePermission> GetResourcePermissions(Guid resourceId) {
492      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
493      return trans.UseTransaction(() => {
494        Resource resource = dao.GetResource(resourceId);
495        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
496        return dao.GetResourcePermissions(x => x.ResourceId == resourceId);
497      });
498    }
499    #endregion
500
[6983]501    #region Slave Methods
502    public int GetNewHeartbeatInterval(Guid slaveId) {
503      authen.AuthenticateForAnyRole(HiveRoles.Slave);
504      Slave s = dao.GetSlave(slaveId);
505      if (s != null) {
506        return s.HbInterval;
507      } else {
508        return -1;
509      }
510    }
511
512    public Guid AddSlave(Slave slave) {
513      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
514      return trans.UseTransaction(() => dao.AddSlave(slave));
515    }
516
517    public Guid AddSlaveGroup(SlaveGroup slaveGroup) {
[8085]518      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[6983]519      return trans.UseTransaction(() => dao.AddSlaveGroup(slaveGroup));
520    }
521
522    public Slave GetSlave(Guid slaveId) {
523      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
524      return dao.GetSlave(slaveId);
525    }
526
527    public SlaveGroup GetSlaveGroup(Guid slaveGroupId) {
528      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
529      return dao.GetSlaveGroup(slaveGroupId);
530    }
531
532    public IEnumerable<Slave> GetSlaves() {
[8085]533      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
534      return dao.GetSlaves(x => true).Where(x => x.OwnerUserId == null
535                                         || x.OwnerUserId == userManager.CurrentUserId
536                                         || userManager.VerifyUser(userManager.CurrentUserId, GetResourcePermissions(x.Id).Select(y => y.GrantedUserId).ToList())
537                                         || authen.IsInRole(HiveRoles.Administrator)).ToArray();
[6983]538    }
539
540    public IEnumerable<SlaveGroup> GetSlaveGroups() {
[8085]541      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
542      return dao.GetSlaveGroups(x => true).Where(x => x.OwnerUserId == null
543                                              || x.OwnerUserId == userManager.CurrentUserId
544                                              || userManager.VerifyUser(userManager.CurrentUserId, GetResourcePermissions(x.Id).Select(y => y.GrantedUserId).ToList())
545                                              || authen.IsInRole(HiveRoles.Administrator)).ToArray();
[6983]546    }
547
548    public void UpdateSlave(Slave slave) {
[8085]549      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[6983]550      trans.UseTransaction(() => {
551        dao.UpdateSlave(slave);
552      });
553    }
554
555    public void UpdateSlaveGroup(SlaveGroup slaveGroup) {
[8085]556      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[6983]557      trans.UseTransaction(() => {
558        dao.UpdateSlaveGroup(slaveGroup);
559      });
560    }
561
562    public void DeleteSlave(Guid slaveId) {
[8085]563      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
564      author.AuthorizeForResourceAdministration(slaveId);
[6983]565      trans.UseTransaction(() => {
566        dao.DeleteSlave(slaveId);
567      });
568    }
569
570    public void DeleteSlaveGroup(Guid slaveGroupId) {
[8085]571      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
572      author.AuthorizeForResourceAdministration(slaveGroupId);
[6983]573      trans.UseTransaction(() => {
574        dao.DeleteSlaveGroup(slaveGroupId);
575      });
576    }
577
578    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
579      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
580      trans.UseTransaction(() => {
581        var resource = dao.GetResource(resourceId);
582        resource.ParentResourceId = slaveGroupId;
583        dao.UpdateResource(resource);
584      });
585    }
586
587    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
588      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
589      trans.UseTransaction(() => {
590        var resource = dao.GetResource(resourceId);
591        resource.ParentResourceId = null;
592        dao.UpdateResource(resource);
593      });
594    }
595
596    public Guid GetResourceId(string resourceName) {
597      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
598      return trans.UseTransaction(() => {
599        var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
600        if (resource != null) {
601          return resource.Id;
602        } else {
603          return Guid.Empty;
604        }
605      });
606    }
607
608    public void TriggerEventManager(bool force) {
609      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Slave);
610      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
[7187]611      bool cleanup = false;
[6983]612      trans.UseTransaction(() => {
613        DateTime lastCleanup = dao.GetLastCleanup();
[7189]614        if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
[6983]615          dao.SetLastCleanup(DateTime.Now);
[7187]616          cleanup = true;
[6983]617        }
618      }, true);
[7187]619
620      if (cleanup) {
621        eventManager.Cleanup();
622      }
[6983]623    }
624    #endregion
625
626    #region Downtime Methods
627    public Guid AddDowntime(Downtime downtime) {
[8085]628      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
629      author.AuthorizeForResourceAdministration(downtime.ResourceId);
[6983]630      return trans.UseTransaction(() => dao.AddDowntime(downtime));
631    }
632
633    public void DeleteDowntime(Guid downtimeId) {
[8085]634      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
635      // TODO: pass resource id
636      // author.AuthorizeForResource(resourceId);
[6983]637      trans.UseTransaction(() => {
638        dao.DeleteDowntime(downtimeId);
639      });
640    }
641
642    public void UpdateDowntime(Downtime downtime) {
[8085]643      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
644      author.AuthorizeForResourceAdministration(downtime.ResourceId);
[6983]645      trans.UseTransaction(() => {
646        dao.UpdateDowntime(downtime);
647      });
648    }
649
650    public IEnumerable<Downtime> GetDowntimesForResource(Guid resourceId) {
[8085]651      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
[6983]652      return trans.UseTransaction(() => dao.GetDowntimes(x => x.ResourceId == resourceId));
653    }
654    #endregion
655
656    #region User Methods
657    public string GetUsernameByUserId(Guid userId) {
658      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
659      var user = ServiceLocator.Instance.UserManager.GetUserById(userId);
660      if (user != null)
661        return user.UserName;
662      else
663        return null;
664    }
665
666    public Guid GetUserIdByUsername(string username) {
667      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
668      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
669      return user != null ? (Guid)user.ProviderUserKey : Guid.Empty;
670    }
671    #endregion
672
673    #region Helper Methods
674    private IEnumerable<Task> GetChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
675      var tasks = new List<Task>(dao.GetTasks(x => parentTaskId == null ? !x.ParentTaskId.HasValue : x.ParentTaskId.Value == parentTaskId));
676
677      if (recursive) {
678        var childs = new List<Task>();
679        foreach (var task in tasks) {
680          childs.AddRange(GetChildTasks(task.Id, recursive, false));
681        }
682        tasks.AddRange(childs);
683      }
684
685      if (includeParent) tasks.Add(GetTask(parentTaskId.Value));
686      return tasks;
687    }
688    #endregion
689  }
690}
Note: See TracBrowser for help on using the repository browser.