Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive.Azure/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 6988

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

#1672

  • added the Hive Services and Slave projects
  • added missing svn ignores
File size: 24.9 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      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 int GetNewHeartbeatInterval(Guid slaveId) {
449      authen.AuthenticateForAnyRole(HiveRoles.Slave);
450      Slave s = dao.GetSlave(slaveId);
451      if (s != null) {
452        return s.HbInterval;
453      } else {
454        return -1;
455      }
456    }
457
458    public Guid AddSlave(Slave slave) {
459      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
460      return trans.UseTransaction(() => dao.AddSlave(slave));
461    }
462
463    public Guid AddSlaveGroup(SlaveGroup slaveGroup) {
464      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
465      return trans.UseTransaction(() => dao.AddSlaveGroup(slaveGroup));
466    }
467
468    public Slave GetSlave(Guid slaveId) {
469      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
470      return dao.GetSlave(slaveId);
471    }
472
473    public SlaveGroup GetSlaveGroup(Guid slaveGroupId) {
474      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
475      return dao.GetSlaveGroup(slaveGroupId);
476    }
477
478    public IEnumerable<Slave> GetSlaves() {
479      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
480      return dao.GetSlaves(x => true);
481    }
482
483    public IEnumerable<SlaveGroup> GetSlaveGroups() {
484      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
485      return dao.GetSlaveGroups(x => true);
486    }
487
488    public void UpdateSlave(Slave slave) {
489      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
490      trans.UseTransaction(() => {
491        dao.UpdateSlave(slave);
492      });
493    }
494
495    public void UpdateSlaveGroup(SlaveGroup slaveGroup) {
496      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
497      trans.UseTransaction(() => {
498        dao.UpdateSlaveGroup(slaveGroup);
499      });
500    }
501
502    public void DeleteSlave(Guid slaveId) {
503      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
504      trans.UseTransaction(() => {
505        dao.DeleteSlave(slaveId);
506      });
507    }
508
509    public void DeleteSlaveGroup(Guid slaveGroupId) {
510      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
511      trans.UseTransaction(() => {
512        dao.DeleteSlaveGroup(slaveGroupId);
513      });
514    }
515
516    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
517      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
518      trans.UseTransaction(() => {
519        var resource = dao.GetResource(resourceId);
520        resource.ParentResourceId = slaveGroupId;
521        dao.UpdateResource(resource);
522      });
523    }
524
525    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
526      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
527      trans.UseTransaction(() => {
528        var resource = dao.GetResource(resourceId);
529        resource.ParentResourceId = null;
530        dao.UpdateResource(resource);
531      });
532    }
533
534    public Guid GetResourceId(string resourceName) {
535      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
536      return trans.UseTransaction(() => {
537        var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
538        if (resource != null) {
539          return resource.Id;
540        } else {
541          return Guid.Empty;
542        }
543      });
544    }
545
546    public void TriggerEventManager(bool force) {
547      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Slave);
548      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
549      trans.UseTransaction(() => {
550        DateTime lastCleanup = dao.GetLastCleanup();
551        if (force || DateTime.Now - lastCleanup > TimeSpan.FromSeconds(59)) {
552          dao.SetLastCleanup(DateTime.Now);
553          eventManager.Cleanup();
554        }
555      }, true);
556    }
557    #endregion
558
559    #region Downtime Methods
560    public Guid AddDowntime(Downtime downtime) {
561      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
562      return trans.UseTransaction(() => dao.AddDowntime(downtime));
563    }
564
565    public void DeleteDowntime(Guid downtimeId) {
566      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
567      trans.UseTransaction(() => {
568        dao.DeleteDowntime(downtimeId);
569      });
570    }
571
572    public void UpdateDowntime(Downtime downtime) {
573      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
574      trans.UseTransaction(() => {
575        dao.UpdateDowntime(downtime);
576      });
577    }
578
579    public IEnumerable<Downtime> GetDowntimesForResource(Guid resourceId) {
580      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
581      return trans.UseTransaction(() => dao.GetDowntimes(x => x.ResourceId == resourceId));
582    }
583    #endregion
584
585    #region User Methods
586    public string GetUsernameByUserId(Guid userId) {
587      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
588      var user = ServiceLocator.Instance.UserManager.GetUserById(userId);
589      if (user != null)
590        return user.UserName;
591      else
592        return null;
593    }
594
595    public Guid GetUserIdByUsername(string username) {
596      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
597      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
598      return user != null ? (Guid)user.ProviderUserKey : Guid.Empty;
599    }
600    #endregion
601
602    #region Helper Methods
603    private IEnumerable<Task> GetChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
604      var tasks = new List<Task>(dao.GetTasks(x => parentTaskId == null ? !x.ParentTaskId.HasValue : x.ParentTaskId.Value == parentTaskId));
605
606      if (recursive) {
607        var childs = new List<Task>();
608        foreach (var task in tasks) {
609          childs.AddRange(GetChildTasks(task.Id, recursive, false));
610        }
611        tasks.AddRange(childs);
612      }
613
614      if (includeParent) tasks.Add(GetTask(parentTaskId.Value));
615      return tasks;
616    }
617    #endregion
618  }
619}
Note: See TracBrowser for help on using the repository browser.