Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1233 Review comments: renamed HiveEperiment to Job

File size: 25.1 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 AddJob(Task job, TaskData jobData, IEnumerable<Guid> resourceIds) {
64      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
65      return trans.UseTransaction(() => {
66        job.Id = dao.AddJob(job);
67        jobData.TaskId = job.Id;
68        jobData.LastUpdate = DateTime.Now;
69        foreach (Guid slaveGroupId in resourceIds) {
70          dao.AssignJobToResource(job.Id, slaveGroupId);
71        }
72        dao.AddJobData(jobData);
73        dao.UpdateJobState(job.Id, DA.TaskState.Waiting, null, userManager.CurrentUserId, null);
74        return jobData.TaskId;
75      }, false, true);
76    }
77
78    public Guid AddChildJob(Guid parentJobId, Task job, TaskData jobData) {
79      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
80      return trans.UseTransaction(() => {
81        job.ParentTaskId = parentJobId;
82        return AddJob(job, jobData, dao.GetAssignedResources(parentJobId).Select(x => x.Id));
83      }, false, true);
84    }
85
86    public Task GetJob(Guid jobId) {
87      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
88      author.AuthorizeForJob(jobId, Permission.Read);
89      return dao.GetJob(jobId);
90    }
91
92    public IEnumerable<Task> GetJobs() {
93      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
94      var jobs = dao.GetJobs(x => true);
95      foreach (var job in jobs)
96        author.AuthorizeForJob(job.Id, Permission.Read);
97      return jobs;
98    }
99
100    public IEnumerable<LightweightTask> GetLightweightJobs(IEnumerable<Guid> jobIds) {
101      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
102      var jobs = dao.GetJobs(x => jobIds.Contains(x.TaskId)).Select(x => new LightweightTask(x)).ToArray();
103      foreach (var job in jobs)
104        author.AuthorizeForJob(job.Id, Permission.Read);
105      return jobs;
106    }
107
108    public IEnumerable<LightweightTask> GetLightweightChildJobs(Guid? parentJobId, bool recursive, bool includeParent) {
109      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
110      var jobs = GetChildJobs(parentJobId, recursive, includeParent).Select(x => new LightweightTask(x)).ToArray();
111      foreach (var job in jobs)
112        author.AuthorizeForJob(job.Id, Permission.Read);
113      return jobs;
114    }
115
116    public IEnumerable<LightweightTask> GetLightweightExperimentJobs(Guid experimentId) {
117      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
118      author.AuthorizeForExperiment(experimentId, Permission.Read);
119      return dao.GetJobs(x => x.JobId == experimentId).Select(x => new LightweightTask(x)).ToArray();
120    }
121
122    public TaskData GetJobData(Guid jobId) {
123      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
124      author.AuthorizeForJob(jobId, Permission.Read);
125      return dao.GetJobData(jobId);
126    }
127
128    public void UpdateJob(Task job) {
129      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
130      author.AuthorizeForJob(job.Id, Permission.Full);
131      trans.UseTransaction(() => {
132        dao.UpdateJob(job);
133      });
134    }
135
136    public void UpdateJobData(Task job, TaskData jobData) {
137      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
138      author.AuthorizeForJob(job.Id, Permission.Full);
139      author.AuthorizeForJob(jobData.TaskId, Permission.Full);
140      //trans.UseTransaction(() => { // cneumuel: try without transaction
141      jobData.LastUpdate = DateTime.Now;
142      dao.UpdateJob(job);
143      dao.UpdateJobData(jobData);
144      //}, false, true);
145    }
146
147    public void DeleteJob(Guid jobId) {
148      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
149      author.AuthorizeForJob(jobId, Permission.Full);
150      trans.UseTransaction(() => {
151        dao.DeleteJob(jobId);
152      });
153    }
154
155    public void DeleteChildJobs(Guid parentJobId) {
156      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
157      author.AuthorizeForJob(parentJobId, Permission.Full);
158      trans.UseTransaction(() => {
159        var jobs = GetChildJobs(parentJobId, true, false);
160        foreach (var job in jobs) {
161          dao.DeleteJob(job.Id);
162          dao.DeleteJobData(job.Id);
163        };
164      });
165    }
166
167    public Task UpdateJobState(Guid jobId, TaskState jobState, Guid? slaveId, Guid? userId, string exception) {
168      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
169      author.AuthorizeForJob(jobId, Permission.Full);
170      return trans.UseTransaction(() => {
171        Task job = dao.UpdateJobState(jobId, DataTransfer.Convert.ToEntity(jobState), slaveId, userId, exception);
172
173        if (job.Command.HasValue && job.Command.Value == Command.Pause && job.State == TaskState.Paused) {
174          job.Command = null;
175        } else if (job.Command.HasValue && job.Command.Value == Command.Abort && job.State == TaskState.Aborted) {
176          job.Command = null;
177        } else if (job.Command.HasValue && job.Command.Value == Command.Stop && job.State == TaskState.Aborted) {
178          job.Command = null;
179        } else if (jobState == TaskState.Paused && !job.Command.HasValue) {
180          // slave paused and uploaded the job (no user-command) -> set waiting.
181          job = dao.UpdateJobState(jobId, DataTransfer.Convert.ToEntity(TaskState.Waiting), slaveId, userId, exception);
182        }
183
184        dao.UpdateJob(job);
185        return job;
186      });
187    }
188
189    public IEnumerable<Task> GetJobsByResourceId(Guid resourceId) {
190      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
191      var jobs = trans.UseTransaction(() => dao.GetJobsByResourceId(resourceId));
192      foreach (var job in jobs)
193        author.AuthorizeForJob(job.Id, Permission.Read);
194      return jobs;
195    }
196    #endregion
197
198    #region Job Control Methods
199    public void StopJob(Guid jobId) {
200      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
201      author.AuthorizeForJob(jobId, Permission.Full);
202      trans.UseTransaction(() => {
203        var job = dao.GetJob(jobId);
204        if (job.State == TaskState.Calculating || job.State == TaskState.Transferring) {
205          job.Command = Command.Stop;
206          dao.UpdateJob(job);
207        } else {
208          if (job.State != TaskState.Aborted && job.State != TaskState.Finished && job.State != TaskState.Failed) {
209            job = UpdateJobState(jobId, TaskState.Aborted, null, null, string.Empty);
210          }
211        }
212      });
213    }
214
215    public void PauseJob(Guid jobId) {
216      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
217      author.AuthorizeForJob(jobId, Permission.Full);
218      trans.UseTransaction(() => {
219        var job = dao.GetJob(jobId);
220        if (job.State == TaskState.Calculating || job.State == TaskState.Transferring) {
221          job.Command = Command.Pause;
222          dao.UpdateJob(job);
223        } else {
224          job = UpdateJobState(jobId, TaskState.Paused, null, null, string.Empty);
225        }
226      });
227    }
228
229    public void RestartJob(Guid jobId) {
230      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
231      author.AuthorizeForJob(jobId, Permission.Full);
232      trans.UseTransaction(() => {
233        Task job = dao.UpdateJobState(jobId, DA.TaskState.Waiting, null, userManager.CurrentUserId, string.Empty);
234        job.Command = null;
235        dao.UpdateJob(job);
236      });
237    }
238    #endregion
239
240    #region HiveExperiment Methods
241    public Job GetHiveExperiment(Guid id) {
242      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
243      author.AuthorizeForExperiment(id, Permission.Read);
244      var hiveExperiment = dao.GetHiveExperiments(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 (hiveExperiment != null) {
249        hiveExperiment.Permission = DT.Convert.ToDto(dao.GetPermissionForExperiment(hiveExperiment.Id, userManager.CurrentUserId));
250        hiveExperiment.OwnerUsername = userManager.GetUserById(hiveExperiment.OwnerUserId).UserName;
251      }
252      return hiveExperiment;
253    }
254
255    public IEnumerable<Job> GetHiveExperiments() {
256      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
257      var hiveExperiments = dao.GetHiveExperiments(x => x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0);
258      foreach (var he in hiveExperiments) {
259        author.AuthorizeForExperiment(he.Id, Permission.Read);
260        he.Permission = DT.Convert.ToDto(dao.GetPermissionForExperiment(he.Id, userManager.CurrentUserId));
261        he.OwnerUsername = userManager.GetUserById(he.OwnerUserId).UserName;
262      }
263      return hiveExperiments;
264    }
265
266    public IEnumerable<Job> GetAllHiveExperiments() {
267      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
268      var hiveExperiments = dao.GetHiveExperiments(x => true);
269      foreach (var he in hiveExperiments) { // no authorization here, since this method is admin-only! (admin is allowed to read all jobs)
270        he.Permission = DT.Convert.ToDto(dao.GetPermissionForExperiment(he.Id, userManager.CurrentUserId));
271        he.OwnerUsername = userManager.GetUserById(he.OwnerUserId).UserName;
272      }
273      return hiveExperiments;
274    }
275
276    public Guid AddHiveExperiment(Job hiveExperimentDto) {
277      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
278      return trans.UseTransaction(() => {
279        hiveExperimentDto.OwnerUserId = userManager.CurrentUserId;
280        hiveExperimentDto.DateCreated = DateTime.Now;
281        return dao.AddHiveExperiment(hiveExperimentDto);
282      });
283    }
284
285    public void UpdateHiveExperiment(Job hiveExperimentDto) {
286      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
287      author.AuthorizeForExperiment(hiveExperimentDto.Id, Permission.Full);
288      trans.UseTransaction(() => {
289        dao.UpdateHiveExperiment(hiveExperimentDto);
290      });
291    }
292
293    public void DeleteHiveExperiment(Guid hiveExperimentId) {
294      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
295      author.AuthorizeForExperiment(hiveExperimentId, Permission.Full);
296      trans.UseTransaction(() => {
297        dao.DeleteHiveExperiment(hiveExperimentId); // child jobs will be deleted by db-trigger
298      });
299    }
300    #endregion
301
302    #region HiveExperimentPermission Methods
303    public void GrantPermission(Guid hiveExperimentId, Guid grantedUserId, Permission permission) {
304      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
305      trans.UseTransaction(() => {
306        Job he = dao.GetHiveExperiment(hiveExperimentId);
307        if (he == null) throw new FaultException<FaultReason>(new FaultReason("Could not find hiveExperiment with id " + hiveExperimentId));
308        Permission perm = DT.Convert.ToDto(dao.GetPermissionForExperiment(he.Id, userManager.CurrentUserId));
309        if (perm != Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
310        dao.SetHiveExperimentPermission(hiveExperimentId, userManager.CurrentUserId, grantedUserId, DT.Convert.ToEntity(permission));
311      });
312    }
313
314    public void RevokePermission(Guid hiveExperimentId, Guid grantedUserId) {
315      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
316      trans.UseTransaction(() => {
317        Job he = dao.GetHiveExperiment(hiveExperimentId);
318        if (he == null) throw new FaultException<FaultReason>(new FaultReason("Could not find hiveExperiment with id " + hiveExperimentId));
319        DA.Permission perm = dao.GetPermissionForExperiment(he.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.SetHiveExperimentPermission(hiveExperimentId, userManager.CurrentUserId, grantedUserId, DA.Permission.NotAllowed);
322      });
323    }
324    public IEnumerable<JobPermission> GetHiveExperimentPermissions(Guid hiveExperimentId) {
325      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
326      return trans.UseTransaction(() => {
327        DA.Permission currentUserPermission = dao.GetPermissionForExperiment(hiveExperimentId, 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.GetHiveExperimentPermissions(x => x.JobId == hiveExperimentId);
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> GetChildJobs(Guid? parentJobId, bool recursive, bool includeParent) {
594      var jobs = new List<Task>(dao.GetJobs(x => parentJobId == null ? !x.ParentTaskId.HasValue : x.ParentTaskId.Value == parentJobId));
595
596      if (recursive) {
597        var childs = new List<Task>();
598        foreach (var job in jobs) {
599          childs.AddRange(GetChildJobs(job.Id, recursive, false));
600        }
601        jobs.AddRange(childs);
602      }
603
604      if (includeParent) jobs.Add(GetJob(parentJobId.Value));
605      return jobs;
606    }
607    #endregion
608  }
609}
Note: See TracBrowser for help on using the repository browser.