Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 8266

Last change on this file since 8266 was 8266, checked in by spimming, 12 years ago

#1888:

  • disabled some transactions since dtc is not supported in sql azure
  • settings in dataaccess updated
File size: 29.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.ServiceModel;
26using HeuristicLab.Services.Hive.DataTransfer;
27using HeuristicLab.Services.Hive.ServiceContracts;
28using DA = HeuristicLab.Services.Hive.DataAccess;
29using DT = HeuristicLab.Services.Hive.DataTransfer;
30
31
32namespace HeuristicLab.Services.Hive {
33
34  /// <summary>
35  /// Implementation of the Hive service (interface <see cref="IHiveService"/>).
36  /// We need 'IgnoreExtensionDataObject' Attribute for the slave to work.
37  /// </summary>
38  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, IgnoreExtensionDataObject = true)]
39  public class HiveService : IHiveService {
40    private IHiveDao dao {
41      get { return ServiceLocator.Instance.HiveDao; }
42    }
43    private Access.IRoleVerifier authen {
44      get { return ServiceLocator.Instance.RoleVerifier; }
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 Access.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      return dao.GetTask(taskId);
95
96    }
97
98    public IEnumerable<Task> GetTasks() {
99      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
100      var tasks = dao.GetTasks(x => true);
101      foreach (var task in tasks)
102        author.AuthorizeForTask(task.Id, Permission.Read);
103      return tasks;
104    }
105
106    public IEnumerable<LightweightTask> GetLightweightTasks(IEnumerable<Guid> taskIds) {
107      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
108
109      return trans.UseTransaction(() => {
110        var tasks = dao.GetTasks(x => taskIds.Contains(x.TaskId)).Select(x => new LightweightTask(x)).ToArray();
111        foreach (var task in tasks)
112          author.AuthorizeForTask(task.Id, Permission.Read);
113        return tasks;
114      }, false, false);
115    }
116
117    public IEnumerable<LightweightTask> GetLightweightChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
118      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
119
120      return trans.UseTransaction(() => {
121        var tasks = GetChildTasks(parentTaskId, recursive, includeParent).Select(x => new LightweightTask(x)).ToArray();
122        foreach (var task in tasks)
123          author.AuthorizeForTask(task.Id, Permission.Read);
124        return tasks;
125      }, false, false);
126    }
127
128    public IEnumerable<LightweightTask> GetLightweightJobTasks(Guid jobId) {
129      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
130      author.AuthorizeForJob(jobId, Permission.Read);
131
132      return trans.UseTransaction(() => {
133        return dao.GetTasks(x => x.JobId == jobId).Select(x => new LightweightTask(x)).ToArray();
134      }, false, false);
135    }
136
137    public TaskData GetTaskData(Guid taskId) {
138      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
139      author.AuthorizeForTask(taskId, Permission.Read);
140      return dao.GetTaskData(taskId);
141    }
142
143    public void UpdateTask(Task taskDto) {
144      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
145      author.AuthorizeForTask(taskDto.Id, Permission.Full);
146      trans.UseTransaction(() => {
147        dao.UpdateTask(taskDto);
148      });
149    }
150
151    public void UpdateTaskData(Task task, TaskData taskData) {
152      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
153      author.AuthorizeForTask(task.Id, Permission.Full);
154      author.AuthorizeForTask(taskData.TaskId, Permission.Full);
155      //trans.UseTransaction(() => { // cneumuel: try without transaction
156      taskData.LastUpdate = DateTime.Now;
157      dao.UpdateTask(task);
158      dao.UpdateTaskData(taskData);
159      //}, false, true);
160    }
161
162    public void DeleteTask(Guid taskId) {
163      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
164      author.AuthorizeForTask(taskId, Permission.Full);
165      trans.UseTransaction(() => {
166        dao.DeleteTask(taskId);
167      });
168    }
169
170    public void DeleteChildTasks(Guid parentTaskId) {
171      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
172      author.AuthorizeForTask(parentTaskId, Permission.Full);
173      trans.UseTransaction(() => {
174        var tasks = GetChildTasks(parentTaskId, true, false);
175        foreach (var task in tasks) {
176          dao.DeleteTask(task.Id);
177          dao.DeleteTaskData(task.Id);
178        };
179      });
180    }
181
182    public Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
183      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
184      author.AuthorizeForTask(taskId, Permission.Full);
185      return trans.UseTransaction(() => {
186        Task task = dao.UpdateTaskState(taskId, DataTransfer.Convert.ToEntity(taskState), slaveId, userId, exception);
187
188        if (task.Command.HasValue && task.Command.Value == Command.Pause && task.State == TaskState.Paused) {
189          task.Command = null;
190        } else if (task.Command.HasValue && task.Command.Value == Command.Abort && task.State == TaskState.Aborted) {
191          task.Command = null;
192        } else if (task.Command.HasValue && task.Command.Value == Command.Stop && task.State == TaskState.Aborted) {
193          task.Command = null;
194        } else if (taskState == TaskState.Paused && !task.Command.HasValue) {
195          // slave paused and uploaded the task (no user-command) -> set waiting.
196          task = dao.UpdateTaskState(taskId, DataTransfer.Convert.ToEntity(TaskState.Waiting), slaveId, userId, exception);
197        }
198
199        dao.UpdateTask(task);
200        return task;
201      });
202    }
203
204    public IEnumerable<Task> GetTasksByResourceId(Guid resourceId) {
205      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
206      var tasks = trans.UseTransaction(() => dao.GetJobsByResourceId(resourceId));
207      foreach (var task in tasks)
208        author.AuthorizeForTask(task.Id, Permission.Read);
209      return tasks;
210    }
211    #endregion
212
213    #region Task Control Methods
214    public void StopTask(Guid taskId) {
215      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
216      author.AuthorizeForTask(taskId, Permission.Full);
217      trans.UseTransaction(() => {
218        var task = dao.GetTask(taskId);
219        if (task.State == TaskState.Calculating || task.State == TaskState.Transferring) {
220          task.Command = Command.Stop;
221          dao.UpdateTask(task);
222        } else {
223          if (task.State != TaskState.Aborted && task.State != TaskState.Finished && task.State != TaskState.Failed) {
224            task = UpdateTaskState(taskId, TaskState.Aborted, null, null, string.Empty);
225          }
226        }
227      });
228    }
229
230    public void PauseTask(Guid taskId) {
231      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
232      author.AuthorizeForTask(taskId, Permission.Full);
233      trans.UseTransaction(() => {
234        var job = dao.GetTask(taskId);
235        if (job.State == TaskState.Calculating || job.State == TaskState.Transferring) {
236          job.Command = Command.Pause;
237          dao.UpdateTask(job);
238        } else {
239          job = UpdateTaskState(taskId, TaskState.Paused, null, null, string.Empty);
240        }
241      });
242    }
243
244    public void RestartTask(Guid taskId) {
245      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
246      author.AuthorizeForTask(taskId, Permission.Full);
247      trans.UseTransaction(() => {
248        Task task = dao.UpdateTaskState(taskId, DA.TaskState.Waiting, null, userManager.CurrentUserId, string.Empty);
249        task.Command = null;
250        dao.UpdateTask(task);
251      });
252    }
253    #endregion
254
255    #region Job Methods
256    public Job GetJob(Guid id) {
257      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
258      author.AuthorizeForJob(id, Permission.Read);
259      var job = dao.GetJobs(x =>
260            x.JobId == id
261            && (x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0)
262          ).FirstOrDefault();
263      if (job != null) {
264        job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
265        job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
266      }
267      return job;
268    }
269
270    public IEnumerable<Job> GetJobs() {
271      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
272      var jobs = dao.GetJobs(x => x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0);
273      foreach (var job in jobs) {
274        author.AuthorizeForJob(job.Id, Permission.Read);
275        job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
276        job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
277      }
278      return jobs;
279    }
280
281    public IEnumerable<Job> GetAllJobs() {
282      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
283      var jobs = dao.GetJobs(x => true);
284      foreach (var job in jobs) { // no authorization here, since this method is admin-only! (admin is allowed to read all task)
285        job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
286        job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
287      }
288      return jobs;
289    }
290
291    public Guid AddJob(Job jobDto) {
292      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
293      Guid id = userManager.CurrentUserId;
294
295      return trans.UseTransaction(() => {
296        jobDto.OwnerUserId = id;
297        jobDto.DateCreated = DateTime.Now;
298        return dao.AddJob(jobDto);
299      });
300    }
301
302    public void UpdateJob(Job jobDto) {
303      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
304      author.AuthorizeForJob(jobDto.Id, Permission.Full);
305      trans.UseTransaction(() => {
306        dao.UpdateJob(jobDto);
307      });
308    }
309
310    public void DeleteJob(Guid jobId) {
311      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
312      author.AuthorizeForJob(jobId, Permission.Full);
313      trans.UseTransaction(() => {
314        dao.DeleteJob(jobId); // child task will be deleted by db-trigger
315      });
316    }
317    #endregion
318
319    #region JobPermission Methods
320    public void GrantPermission(Guid jobId, Guid grantedUserId, Permission permission) {
321      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
322      trans.UseTransaction(() => {
323        Job job = dao.GetJob(jobId);
324        if (job == null) throw new FaultException<FaultReason>(new FaultReason("Could not find task with id " + jobId));
325        Permission perm = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
326        if (perm != Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
327        dao.SetJobPermission(jobId, userManager.CurrentUserId, grantedUserId, DT.Convert.ToEntity(permission));
328      });
329    }
330
331    public void RevokePermission(Guid jobId, Guid grantedUserId) {
332      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
333      trans.UseTransaction(() => {
334        Job job = dao.GetJob(jobId);
335        if (job == null) throw new FaultException<FaultReason>(new FaultReason("Could not find task with id " + jobId));
336        DA.Permission perm = dao.GetPermissionForJob(job.Id, userManager.CurrentUserId);
337        if (perm != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
338        dao.SetJobPermission(jobId, userManager.CurrentUserId, grantedUserId, DA.Permission.NotAllowed);
339      });
340    }
341
342    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
343      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
344      return trans.UseTransaction(() => {
345        DA.Permission currentUserPermission = dao.GetPermissionForJob(jobId, userManager.CurrentUserId);
346        if (currentUserPermission != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to list permissions for this experiment"));
347        return dao.GetJobPermissions(x => x.JobId == jobId);
348      });
349    }
350
351    public bool IsAllowedPrivileged() {
352      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
353      return authen.IsInRole(HiveRoles.IsAllowedPrivileged);
354    }
355    #endregion
356
357    #region Login Methods
358    public void Hello(Slave slaveInfo) {
359      authen.AuthenticateForAnyRole(HiveRoles.Slave);
360      if (userManager.CurrentUser.UserName != "hiveslave")
361        slaveInfo.OwnerUserId = userManager.CurrentUserId;
362
363      Slave slave = null;
364      trans.UseTransaction(() => { slave = dao.GetSlave(slaveInfo.Id); });
365      trans.UseTransaction(() => {
366        if (slave == null) {
367          dao.AddSlave(slaveInfo);
368        } else {
369          slave.Name = slaveInfo.Name;
370          slave.Description = slaveInfo.Description;
371          slave.OwnerUserId = slaveInfo.OwnerUserId;
372
373          slave.Cores = slaveInfo.Cores;
374          slave.CpuArchitecture = slaveInfo.CpuArchitecture;
375          slave.CpuSpeed = slaveInfo.CpuSpeed;
376          slave.FreeCores = slaveInfo.FreeCores;
377          slave.FreeMemory = slaveInfo.FreeMemory;
378          slave.Memory = slaveInfo.Memory;
379          slave.OperatingSystem = slaveInfo.OperatingSystem;
380
381          slave.LastHeartbeat = DateTime.Now;
382          slave.SlaveState = SlaveState.Idle;
383
384          // don't update those properties: dbSlave.IsAllowedToCalculate, dbSlave.ParentResourceId
385
386          dao.UpdateSlave(slave);
387        }
388      });
389    }
390
391    public void GoodBye(Guid slaveId) {
392      authen.AuthenticateForAnyRole(HiveRoles.Slave);
393      trans.UseTransaction(() => {
394        var slave = dao.GetSlave(slaveId);
395        if (slave != null) {
396          slave.SlaveState = SlaveState.Offline;
397          dao.UpdateSlave(slave);
398        }
399      });
400    }
401    #endregion
402
403    #region Heartbeat Methods
404    public List<MessageContainer> Heartbeat(Heartbeat heartbeat) {
405      authen.AuthenticateForAnyRole(HiveRoles.Slave);
406
407      //TODO: enable transaction
408      //List<MessageContainer> result = trans.UseTransaction(() => heartbeatManager.ProcessHeartbeat(heartbeat));
409      List<MessageContainer> result = heartbeatManager.ProcessHeartbeat(heartbeat);
410
411      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
412        TriggerEventManager(false);
413      }
414
415      return result;
416    }
417    #endregion
418
419    #region Plugin Methods
420    public Guid AddPlugin(Plugin plugin, List<PluginData> pluginDatas) {
421      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
422      return trans.UseTransaction(() => {
423        plugin.UserId = userManager.CurrentUserId;
424        plugin.DateCreated = DateTime.Now;
425
426        var existing = dao.GetPlugins(x => x.Hash != null).Where(x => x.Hash.SequenceEqual(plugin.Hash));
427        if (existing.Count() > 0) {
428          // a plugin already exists.
429          throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(existing.Single().Id));
430        }
431
432        Guid pluginId = dao.AddPlugin(plugin);
433        foreach (PluginData pluginData in pluginDatas) {
434          pluginData.PluginId = pluginId;
435          dao.AddPluginData(pluginData);
436        }
437        return pluginId;
438      });
439    }
440
441    public Plugin GetPlugin(Guid pluginId) {
442      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
443      return dao.GetPlugin(pluginId);
444    }
445
446    public Plugin GetPluginByHash(byte[] hash) {
447      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
448      return dao.GetPlugins(x => x.Hash == hash).FirstOrDefault();
449    }
450
451    // 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)
452    //       change so that only with GetPluginByHash it is possible to download plugins
453    public IEnumerable<Plugin> GetPlugins() {
454      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
455      return dao.GetPlugins(x => x.Hash != null);
456    }
457
458    public IEnumerable<PluginData> GetPluginDatas(List<Guid> pluginIds) {
459      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
460      var pluginDatas = new List<PluginData>();
461      return trans.UseTransaction(() => {
462        foreach (Guid guid in pluginIds) {
463          pluginDatas.AddRange(dao.GetPluginDatas(x => x.PluginId == guid).ToList());
464        }
465        return pluginDatas;
466      });
467    }
468
469    public void DeletePlugin(Guid pluginId) {
470      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
471      dao.DeletePlugin(pluginId);
472    }
473    #endregion
474
475    #region ResourcePermission Methods
476    public void GrantResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
477      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
478      trans.UseTransaction(() => {
479        Resource resource = dao.GetResource(resourceId);
480        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
481        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permission for this resource"));
482        foreach (Guid id in grantedUserIds)
483          dao.AddResourcePermission(new ResourcePermission { ResourceId = resourceId, GrantedByUserId = userManager.CurrentUserId, GrantedUserId = id });
484      });
485    }
486
487    public void RevokeResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
488      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
489      trans.UseTransaction(() => {
490        Resource resource = dao.GetResource(resourceId);
491        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
492        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to revoke permission for this resource"));
493        foreach (Guid id in grantedUserIds)
494          dao.DeleteResourcePermission(resourceId, id);
495      });
496    }
497
498    public IEnumerable<ResourcePermission> GetResourcePermissions(Guid resourceId) {
499      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
500      return trans.UseTransaction(() => {
501        Resource resource = dao.GetResource(resourceId);
502        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
503        return dao.GetResourcePermissions(x => x.ResourceId == resourceId);
504      });
505    }
506    #endregion
507
508    #region Slave Methods
509    public int GetNewHeartbeatInterval(Guid slaveId) {
510      authen.AuthenticateForAnyRole(HiveRoles.Slave);
511      Slave s = dao.GetSlave(slaveId);
512      if (s != null) {
513        return s.HbInterval;
514      } else {
515        return -1;
516      }
517    }
518
519    public Guid AddSlave(Slave slave) {
520      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
521      return trans.UseTransaction(() => dao.AddSlave(slave));
522    }
523
524    public Guid AddSlaveGroup(SlaveGroup slaveGroup) {
525      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
526      return trans.UseTransaction(() => dao.AddSlaveGroup(slaveGroup));
527    }
528
529    public Slave GetSlave(Guid slaveId) {
530      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
531      return dao.GetSlave(slaveId);
532    }
533
534    public SlaveGroup GetSlaveGroup(Guid slaveGroupId) {
535      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
536      return dao.GetSlaveGroup(slaveGroupId);
537    }
538
539    public IEnumerable<Slave> GetSlaves() {
540      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
541      return dao.GetSlaves(x => true).Where(x => x.OwnerUserId == null
542                                         || x.OwnerUserId == userManager.CurrentUserId
543                                         || userManager.VerifyUser(userManager.CurrentUserId, GetResourcePermissions(x.Id).Select(y => y.GrantedUserId).ToList())
544                                         || authen.IsInRole(HiveRoles.Administrator)).ToArray();
545    }
546
547    public IEnumerable<SlaveGroup> GetSlaveGroups() {
548      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
549      return dao.GetSlaveGroups(x => true).Where(x => x.OwnerUserId == null
550                                              || x.OwnerUserId == userManager.CurrentUserId
551                                              || userManager.VerifyUser(userManager.CurrentUserId, GetResourcePermissions(x.Id).Select(y => y.GrantedUserId).ToList())
552                                              || authen.IsInRole(HiveRoles.Administrator)).ToArray();
553    }
554
555    public void UpdateSlave(Slave slave) {
556      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
557      trans.UseTransaction(() => {
558        dao.UpdateSlave(slave);
559      });
560    }
561
562    public void UpdateSlaveGroup(SlaveGroup slaveGroup) {
563      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
564      trans.UseTransaction(() => {
565        dao.UpdateSlaveGroup(slaveGroup);
566      });
567    }
568
569    public void DeleteSlave(Guid slaveId) {
570      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
571      author.AuthorizeForResourceAdministration(slaveId);
572      trans.UseTransaction(() => {
573        dao.DeleteSlave(slaveId);
574      });
575    }
576
577    public void DeleteSlaveGroup(Guid slaveGroupId) {
578      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
579      author.AuthorizeForResourceAdministration(slaveGroupId);
580      trans.UseTransaction(() => {
581        dao.DeleteSlaveGroup(slaveGroupId);
582      });
583    }
584
585    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
586      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
587      trans.UseTransaction(() => {
588        var resource = dao.GetResource(resourceId);
589        resource.ParentResourceId = slaveGroupId;
590        dao.UpdateResource(resource);
591      });
592    }
593
594    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
595      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
596      trans.UseTransaction(() => {
597        var resource = dao.GetResource(resourceId);
598        resource.ParentResourceId = null;
599        dao.UpdateResource(resource);
600      });
601    }
602
603    public Guid GetResourceId(string resourceName) {
604      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
605      return trans.UseTransaction(() => {
606        var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
607        if (resource != null) {
608          return resource.Id;
609        } else {
610          return Guid.Empty;
611        }
612      });
613    }
614
615    public void TriggerEventManager(bool force) {
616      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Slave);
617      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
618      bool cleanup = false;
619      trans.UseTransaction(() => {
620        DateTime lastCleanup = dao.GetLastCleanup();
621        if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
622          dao.SetLastCleanup(DateTime.Now);
623          cleanup = true;
624        }
625      }, true);
626
627      if (cleanup) {
628        eventManager.Cleanup();
629      }
630    }
631    #endregion
632
633    #region Downtime Methods
634    public Guid AddDowntime(Downtime downtime) {
635      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
636      author.AuthorizeForResourceAdministration(downtime.ResourceId);
637      return trans.UseTransaction(() => dao.AddDowntime(downtime));
638    }
639
640    public void DeleteDowntime(Guid downtimeId) {
641      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
642      // TODO: pass resource id
643      // author.AuthorizeForResource(resourceId);
644      trans.UseTransaction(() => {
645        dao.DeleteDowntime(downtimeId);
646      });
647    }
648
649    public void UpdateDowntime(Downtime downtime) {
650      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
651      author.AuthorizeForResourceAdministration(downtime.ResourceId);
652      trans.UseTransaction(() => {
653        dao.UpdateDowntime(downtime);
654      });
655    }
656
657    public IEnumerable<Downtime> GetDowntimesForResource(Guid resourceId) {
658      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
659      return trans.UseTransaction(() => dao.GetDowntimes(x => x.ResourceId == resourceId));
660    }
661    #endregion
662
663    #region User Methods
664    public string GetUsernameByUserId(Guid userId) {
665      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
666      var user = ServiceLocator.Instance.UserManager.GetUserById(userId);
667      if (user != null)
668        return user.UserName;
669      else
670        return null;
671    }
672
673    public Guid GetUserIdByUsername(string username) {
674      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
675      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
676      return user != null ? (Guid)user.ProviderUserKey : Guid.Empty;
677    }
678    #endregion
679
680    #region Helper Methods
681    private IEnumerable<Task> GetChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
682      var tasks = new List<Task>(dao.GetTasks(x => parentTaskId == null ? !x.ParentTaskId.HasValue : x.ParentTaskId.Value == parentTaskId));
683
684      if (recursive) {
685        var childs = new List<Task>();
686        foreach (var task in tasks) {
687          childs.AddRange(GetChildTasks(task.Id, recursive, false));
688        }
689        tasks.AddRange(childs);
690      }
691
692      if (includeParent) tasks.Add(GetTask(parentTaskId.Value));
693      return tasks;
694    }
695    #endregion
696  }
697}
Note: See TracBrowser for help on using the repository browser.