Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7403 was 7259, checked in by swagner, 13 years ago

Updated year of copyrights to 2012 (#1716)

File size: 25.5 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    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
337      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
338      return trans.UseTransaction(() => {
339        DA.Permission currentUserPermission = dao.GetPermissionForJob(jobId, userManager.CurrentUserId);
340        if (currentUserPermission != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to list permissions for this experiment"));
341        return dao.GetJobPermissions(x => x.JobId == jobId);
342      });
343    }
344
345    public bool IsAllowedPrivileged() {
346      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
347      return authen.IsInRole(HiveRoles.IsAllowedPrivileged);
348    }
349    #endregion
350
351    #region Login Methods
352    public void Hello(Slave slaveInfo) {
353      authen.AuthenticateForAnyRole(HiveRoles.Slave);
354      trans.UseTransaction(() => {
355        var slave = dao.GetSlave(slaveInfo.Id);
356
357        if (slave == null) {
358          dao.AddSlave(slaveInfo);
359        } else {
360          var dbSlave = dao.GetSlave(slaveInfo.Id);
361
362          dbSlave.Name = slaveInfo.Name;
363          dbSlave.Description = slaveInfo.Description;
364
365          dbSlave.Cores = slaveInfo.Cores;
366          dbSlave.CpuArchitecture = slaveInfo.CpuArchitecture;
367          dbSlave.CpuSpeed = slaveInfo.CpuSpeed;
368          dbSlave.FreeCores = slaveInfo.FreeCores;
369          dbSlave.FreeMemory = slaveInfo.FreeMemory;
370          dbSlave.Memory = slaveInfo.Memory;
371          dbSlave.OperatingSystem = slaveInfo.OperatingSystem;
372
373          dbSlave.LastHeartbeat = DateTime.Now;
374          dbSlave.SlaveState = SlaveState.Idle;
375
376          // don't update those properties: dbSlave.IsAllowedToCalculate, dbSlave.ParentResourceId
377
378          dao.UpdateSlave(dbSlave);
379        }
380      });
381    }
382
383    public void GoodBye(Guid slaveId) {
384      authen.AuthenticateForAnyRole(HiveRoles.Slave);
385      trans.UseTransaction(() => {
386        var slave = dao.GetSlave(slaveId);
387        if (slave != null) {
388          slave.SlaveState = SlaveState.Offline;
389          dao.UpdateSlave(slave);
390        }
391      });
392    }
393    #endregion
394
395    #region Heartbeat Methods
396    public List<MessageContainer> Heartbeat(Heartbeat heartbeat) {
397      authen.AuthenticateForAnyRole(HiveRoles.Slave);
398
399      List<MessageContainer> result = trans.UseTransaction(() => heartbeatManager.ProcessHeartbeat(heartbeat));
400
401      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
402        TriggerEventManager(false);
403      }
404
405      return result;
406    }
407    #endregion
408
409    #region Plugin Methods
410    public Guid AddPlugin(Plugin plugin, List<PluginData> pluginDatas) {
411      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
412      return trans.UseTransaction(() => {
413        plugin.UserId = userManager.CurrentUserId;
414        plugin.DateCreated = DateTime.Now;
415
416        var existing = dao.GetPlugins(x => x.Hash != null).Where(x => x.Hash.SequenceEqual(plugin.Hash));
417        if (existing.Count() > 0) {
418          // a plugin already exists.
419          throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(existing.Single().Id));
420        }
421
422        Guid pluginId = dao.AddPlugin(plugin);
423        foreach (PluginData pluginData in pluginDatas) {
424          pluginData.PluginId = pluginId;
425          dao.AddPluginData(pluginData);
426        }
427        return pluginId;
428      });
429    }
430
431    public Plugin GetPlugin(Guid pluginId) {
432      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
433      return dao.GetPlugin(pluginId);
434    }
435
436    public Plugin GetPluginByHash(byte[] hash) {
437      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
438      return dao.GetPlugins(x => x.Hash == hash).FirstOrDefault();
439    }
440
441    // 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)
442    //       change so that only with GetPluginByHash it is possible to download plugins
443    public IEnumerable<Plugin> GetPlugins() {
444      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
445      return dao.GetPlugins(x => x.Hash != null);
446    }
447
448    public IEnumerable<PluginData> GetPluginDatas(List<Guid> pluginIds) {
449      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
450      var pluginDatas = new List<PluginData>();
451      return trans.UseTransaction(() => {
452        foreach (Guid guid in pluginIds) {
453          pluginDatas.AddRange(dao.GetPluginDatas(x => x.PluginId == guid).ToList());
454        }
455        return pluginDatas;
456      });
457    }
458
459    public void DeletePlugin(Guid pluginId) {
460      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
461      dao.DeletePlugin(pluginId);
462    }
463    #endregion
464
465    #region Slave Methods
466    public int GetNewHeartbeatInterval(Guid slaveId) {
467      authen.AuthenticateForAnyRole(HiveRoles.Slave);
468      Slave s = dao.GetSlave(slaveId);
469      if (s != null) {
470        return s.HbInterval;
471      } else {
472        return -1;
473      }
474    }
475
476    public Guid AddSlave(Slave slave) {
477      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
478      return trans.UseTransaction(() => dao.AddSlave(slave));
479    }
480
481    public Guid AddSlaveGroup(SlaveGroup slaveGroup) {
482      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
483      return trans.UseTransaction(() => dao.AddSlaveGroup(slaveGroup));
484    }
485
486    public Slave GetSlave(Guid slaveId) {
487      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
488      return dao.GetSlave(slaveId);
489    }
490
491    public SlaveGroup GetSlaveGroup(Guid slaveGroupId) {
492      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
493      return dao.GetSlaveGroup(slaveGroupId);
494    }
495
496    public IEnumerable<Slave> GetSlaves() {
497      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
498      return dao.GetSlaves(x => true);
499    }
500
501    public IEnumerable<SlaveGroup> GetSlaveGroups() {
502      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
503      return dao.GetSlaveGroups(x => true);
504    }
505
506    public void UpdateSlave(Slave slave) {
507      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
508      trans.UseTransaction(() => {
509        dao.UpdateSlave(slave);
510      });
511    }
512
513    public void UpdateSlaveGroup(SlaveGroup slaveGroup) {
514      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
515      trans.UseTransaction(() => {
516        dao.UpdateSlaveGroup(slaveGroup);
517      });
518    }
519
520    public void DeleteSlave(Guid slaveId) {
521      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
522      trans.UseTransaction(() => {
523        dao.DeleteSlave(slaveId);
524      });
525    }
526
527    public void DeleteSlaveGroup(Guid slaveGroupId) {
528      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
529      trans.UseTransaction(() => {
530        dao.DeleteSlaveGroup(slaveGroupId);
531      });
532    }
533
534    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
535      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
536      trans.UseTransaction(() => {
537        var resource = dao.GetResource(resourceId);
538        resource.ParentResourceId = slaveGroupId;
539        dao.UpdateResource(resource);
540      });
541    }
542
543    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
544      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
545      trans.UseTransaction(() => {
546        var resource = dao.GetResource(resourceId);
547        resource.ParentResourceId = null;
548        dao.UpdateResource(resource);
549      });
550    }
551
552    public Guid GetResourceId(string resourceName) {
553      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
554      return trans.UseTransaction(() => {
555        var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
556        if (resource != null) {
557          return resource.Id;
558        } else {
559          return Guid.Empty;
560        }
561      });
562    }
563
564    public void TriggerEventManager(bool force) {
565      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Slave);
566      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
567      bool cleanup = false;
568      trans.UseTransaction(() => {
569        DateTime lastCleanup = dao.GetLastCleanup();
570        if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
571          dao.SetLastCleanup(DateTime.Now);
572          cleanup = true;
573        }
574      }, true);
575
576      if (cleanup) {
577        eventManager.Cleanup();
578      }
579    }
580    #endregion
581
582    #region Downtime Methods
583    public Guid AddDowntime(Downtime downtime) {
584      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
585      return trans.UseTransaction(() => dao.AddDowntime(downtime));
586    }
587
588    public void DeleteDowntime(Guid downtimeId) {
589      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
590      trans.UseTransaction(() => {
591        dao.DeleteDowntime(downtimeId);
592      });
593    }
594
595    public void UpdateDowntime(Downtime downtime) {
596      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
597      trans.UseTransaction(() => {
598        dao.UpdateDowntime(downtime);
599      });
600    }
601
602    public IEnumerable<Downtime> GetDowntimesForResource(Guid resourceId) {
603      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
604      return trans.UseTransaction(() => dao.GetDowntimes(x => x.ResourceId == resourceId));
605    }
606    #endregion
607
608    #region User Methods
609    public string GetUsernameByUserId(Guid userId) {
610      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
611      var user = ServiceLocator.Instance.UserManager.GetUserById(userId);
612      if (user != null)
613        return user.UserName;
614      else
615        return null;
616    }
617
618    public Guid GetUserIdByUsername(string username) {
619      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
620      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
621      return user != null ? (Guid)user.ProviderUserKey : Guid.Empty;
622    }
623    #endregion
624
625    #region Helper Methods
626    private IEnumerable<Task> GetChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
627      var tasks = new List<Task>(dao.GetTasks(x => parentTaskId == null ? !x.ParentTaskId.HasValue : x.ParentTaskId.Value == parentTaskId));
628
629      if (recursive) {
630        var childs = new List<Task>();
631        foreach (var task in tasks) {
632          childs.AddRange(GetChildTasks(task.Id, recursive, false));
633        }
634        tasks.AddRange(childs);
635      }
636
637      if (includeParent) tasks.Add(GetTask(parentTaskId.Value));
638      return tasks;
639    }
640    #endregion
641  }
642}
Note: See TracBrowser for help on using the repository browser.