Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 6743

Last change on this file since 6743 was 6743, checked in by ascheibe, 13 years ago

#1233

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