Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1672

  • increased times between life cycles on the server
  • some smaller performance improvements on the server
File size: 25.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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      TriggerEventManager(false);
399      return trans.UseTransaction(() => heartbeatManager.ProcessHeartbeat(heartbeat));
400    }
401    #endregion
402
403    #region Plugin Methods
404    public Guid AddPlugin(Plugin plugin, List<PluginData> pluginDatas) {
405      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
406      return trans.UseTransaction(() => {
407        plugin.UserId = userManager.CurrentUserId;
408        plugin.DateCreated = DateTime.Now;
409
410        var existing = dao.GetPlugins(x => x.Hash != null).Where(x => x.Hash.SequenceEqual(plugin.Hash));
411        if (existing.Count() > 0) {
412          // a plugin already exists.
413          throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(existing.Single().Id));
414        }
415
416        Guid pluginId = dao.AddPlugin(plugin);
417        foreach (PluginData pluginData in pluginDatas) {
418          pluginData.PluginId = pluginId;
419          dao.AddPluginData(pluginData);
420        }
421        return pluginId;
422      });
423    }
424
425    public Plugin GetPlugin(Guid pluginId) {
426      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
427      return dao.GetPlugin(pluginId);
428    }
429
430    public Plugin GetPluginByHash(byte[] hash) {
431      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
432      return dao.GetPlugins(x => x.Hash == hash).FirstOrDefault();
433    }
434
435    // 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)
436    //       change so that only with GetPluginByHash it is possible to download plugins
437    public IEnumerable<Plugin> GetPlugins() {
438      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
439      return dao.GetPlugins(x => x.Hash != null);
440    }
441
442    public IEnumerable<PluginData> GetPluginDatas(List<Guid> pluginIds) {
443      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
444      var pluginDatas = new List<PluginData>();
445      return trans.UseTransaction(() => {
446        foreach (Guid guid in pluginIds) {
447          pluginDatas.AddRange(dao.GetPluginDatas(x => x.PluginId == guid).ToList());
448        }
449        return pluginDatas;
450      });
451    }
452
453    public void DeletePlugin(Guid pluginId) {
454      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
455      dao.DeletePlugin(pluginId);
456    }
457    #endregion
458
459    #region Slave Methods
460    public int GetNewHeartbeatInterval(Guid slaveId) {
461      authen.AuthenticateForAnyRole(HiveRoles.Slave);
462      Slave s = dao.GetSlave(slaveId);
463      if (s != null) {
464        return s.HbInterval;
465      } else {
466        return -1;
467      }
468    }
469
470    public Guid AddSlave(Slave slave) {
471      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
472      return trans.UseTransaction(() => dao.AddSlave(slave));
473    }
474
475    public Guid AddSlaveGroup(SlaveGroup slaveGroup) {
476      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
477      return trans.UseTransaction(() => dao.AddSlaveGroup(slaveGroup));
478    }
479
480    public Slave GetSlave(Guid slaveId) {
481      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
482      return dao.GetSlave(slaveId);
483    }
484
485    public SlaveGroup GetSlaveGroup(Guid slaveGroupId) {
486      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
487      return dao.GetSlaveGroup(slaveGroupId);
488    }
489
490    public IEnumerable<Slave> GetSlaves() {
491      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
492      return dao.GetSlaves(x => true);
493    }
494
495    public IEnumerable<SlaveGroup> GetSlaveGroups() {
496      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
497      return dao.GetSlaveGroups(x => true);
498    }
499
500    public void UpdateSlave(Slave slave) {
501      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
502      trans.UseTransaction(() => {
503        dao.UpdateSlave(slave);
504      });
505    }
506
507    public void UpdateSlaveGroup(SlaveGroup slaveGroup) {
508      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
509      trans.UseTransaction(() => {
510        dao.UpdateSlaveGroup(slaveGroup);
511      });
512    }
513
514    public void DeleteSlave(Guid slaveId) {
515      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
516      trans.UseTransaction(() => {
517        dao.DeleteSlave(slaveId);
518      });
519    }
520
521    public void DeleteSlaveGroup(Guid slaveGroupId) {
522      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
523      trans.UseTransaction(() => {
524        dao.DeleteSlaveGroup(slaveGroupId);
525      });
526    }
527
528    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
529      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
530      trans.UseTransaction(() => {
531        var resource = dao.GetResource(resourceId);
532        resource.ParentResourceId = slaveGroupId;
533        dao.UpdateResource(resource);
534      });
535    }
536
537    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
538      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
539      trans.UseTransaction(() => {
540        var resource = dao.GetResource(resourceId);
541        resource.ParentResourceId = null;
542        dao.UpdateResource(resource);
543      });
544    }
545
546    public Guid GetResourceId(string resourceName) {
547      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
548      return trans.UseTransaction(() => {
549        var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
550        if (resource != null) {
551          return resource.Id;
552        } else {
553          return Guid.Empty;
554        }
555      });
556    }
557
558    public void TriggerEventManager(bool force) {
559      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Slave);
560      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
561      bool cleanup = false;
562      trans.UseTransaction(() => {
563        DateTime lastCleanup = dao.GetLastCleanup();
564        if (force || DateTime.Now - lastCleanup > TimeSpan.FromSeconds(140)) {
565          dao.SetLastCleanup(DateTime.Now);
566          cleanup = true;
567        }
568      }, true);
569
570      if (cleanup) {
571        eventManager.Cleanup();
572      }
573    }
574    #endregion
575
576    #region Downtime Methods
577    public Guid AddDowntime(Downtime downtime) {
578      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
579      return trans.UseTransaction(() => dao.AddDowntime(downtime));
580    }
581
582    public void DeleteDowntime(Guid downtimeId) {
583      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
584      trans.UseTransaction(() => {
585        dao.DeleteDowntime(downtimeId);
586      });
587    }
588
589    public void UpdateDowntime(Downtime downtime) {
590      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
591      trans.UseTransaction(() => {
592        dao.UpdateDowntime(downtime);
593      });
594    }
595
596    public IEnumerable<Downtime> GetDowntimesForResource(Guid resourceId) {
597      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
598      return trans.UseTransaction(() => dao.GetDowntimes(x => x.ResourceId == resourceId));
599    }
600    #endregion
601
602    #region User Methods
603    public string GetUsernameByUserId(Guid userId) {
604      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
605      var user = ServiceLocator.Instance.UserManager.GetUserById(userId);
606      if (user != null)
607        return user.UserName;
608      else
609        return null;
610    }
611
612    public Guid GetUserIdByUsername(string username) {
613      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
614      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
615      return user != null ? (Guid)user.ProviderUserKey : Guid.Empty;
616    }
617    #endregion
618
619    #region Helper Methods
620    private IEnumerable<Task> GetChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
621      var tasks = new List<Task>(dao.GetTasks(x => parentTaskId == null ? !x.ParentTaskId.HasValue : x.ParentTaskId.Value == parentTaskId));
622
623      if (recursive) {
624        var childs = new List<Task>();
625        foreach (var task in tasks) {
626          childs.AddRange(GetChildTasks(task.Id, recursive, false));
627        }
628        tasks.AddRange(childs);
629      }
630
631      if (includeParent) tasks.Add(GetTask(parentTaskId.Value));
632      return tasks;
633    }
634    #endregion
635  }
636}
Note: See TracBrowser for help on using the repository browser.