Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11019 was 9751, checked in by ascheibe, 11 years ago

#2087 fixed exception when adding tasks in Hive

File size: 31.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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  [HiveOperationContextBehavior]
40  public class HiveService : IHiveService {
41    private IHiveDao dao {
42      get { return ServiceLocator.Instance.HiveDao; }
43    }
44    private IOptimizedHiveDao optimizedDao {
45      get { return ServiceLocator.Instance.OptimizedHiveDao; }
46    }
47    private Access.IRoleVerifier authen {
48      get { return ServiceLocator.Instance.RoleVerifier; }
49    }
50    private IAuthorizationManager author {
51      get { return ServiceLocator.Instance.AuthorizationManager; }
52    }
53    private DataAccess.ITransactionManager trans {
54      get { return ServiceLocator.Instance.TransactionManager; }
55    }
56    private IEventManager eventManager {
57      get { return ServiceLocator.Instance.EventManager; }
58    }
59    private Access.IUserManager userManager {
60      get { return ServiceLocator.Instance.UserManager; }
61    }
62    private HeartbeatManager heartbeatManager {
63      get { return ServiceLocator.Instance.HeartbeatManager; }
64    }
65
66    #region Task Methods
67    public Guid AddTask(Task task, TaskData taskData, IEnumerable<Guid> resourceIds) {
68      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
69      return trans.UseTransaction(() => {
70        var t = DT.Convert.ToEntity(task);
71        t.RequiredPlugins.AddRange(task.PluginsNeededIds.Select(pluginId => new DA.RequiredPlugin { Task = t, PluginId = pluginId }));
72
73        t.JobData = DT.Convert.ToEntity(taskData);
74        t.JobData.LastUpdate = DateTime.Now;
75
76        optimizedDao.AddTask(t);
77
78        dao.AssignJobToResource(t.TaskId, resourceIds);
79
80        optimizedDao.UpdateTaskState(t.TaskId, DA.TaskState.Waiting, null, userManager.CurrentUserId, null);
81
82        return t.TaskId;
83      }, false, true);
84    }
85
86    public Guid AddChildTask(Guid parentTaskId, Task task, TaskData taskData) {
87      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
88      task.ParentTaskId = parentTaskId;
89      return AddTask(task, taskData, optimizedDao.GetAssignedResourceIds(parentTaskId).ToList());
90    }
91
92    public Task GetTask(Guid taskId) {
93      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
94      author.AuthorizeForTask(taskId, Permission.Read);
95
96      return trans.UseTransaction(() => {
97        return DT.Convert.ToDto(optimizedDao.GetTaskById(taskId));
98      }, false, false);
99    }
100
101    public IEnumerable<Task> GetTasks() {
102      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
103      return trans.UseTransaction(() => {
104        var tasks = dao.GetTasks(x => true);
105        foreach (var task in tasks)
106          author.AuthorizeForTask(task.Id, Permission.Read);
107        return tasks;
108      });
109    }
110
111    public IEnumerable<LightweightTask> GetLightweightTasks(IEnumerable<Guid> taskIds) {
112      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
113
114      return trans.UseTransaction(() => {
115        var tasks = dao.GetTasks(x => taskIds.Contains(x.TaskId)).Select(x => new LightweightTask(x)).ToArray();
116        foreach (var task in tasks)
117          author.AuthorizeForTask(task.Id, Permission.Read);
118        return tasks;
119      }, false, false);
120    }
121
122    public IEnumerable<LightweightTask> GetLightweightChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
123      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
124
125      return trans.UseTransaction(() => {
126        var tasks = GetChildTasks(parentTaskId, recursive, includeParent).Select(x => new LightweightTask(x)).ToArray();
127        foreach (var task in tasks)
128          author.AuthorizeForTask(task.Id, Permission.Read);
129        return tasks;
130      }, false, false);
131    }
132
133    public IEnumerable<LightweightTask> GetLightweightJobTasks(Guid jobId) {
134      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
135      author.AuthorizeForJob(jobId, Permission.Read);
136
137      return trans.UseTransaction(() => {
138        return optimizedDao.GetLightweightTasks(jobId).ToArray();
139      }, false, true);
140    }
141
142    public IEnumerable<LightweightTask> GetLightweightJobTasksWithoutStateLog(Guid jobId) {
143      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
144      author.AuthorizeForJob(jobId, Permission.Read);
145
146      return trans.UseTransaction(() => {
147        return dao.GetLightweightTasksWithoutStateLog(task => task.JobId == jobId).ToArray();
148      }, false, false);
149    }
150
151    public TaskData GetTaskData(Guid taskId) {
152      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
153      author.AuthorizeForTask(taskId, Permission.Read);
154
155      return trans.UseTransaction(() => {
156        return dao.GetTaskData(taskId);
157      });
158    }
159
160    public void UpdateTask(Task taskDto) {
161      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
162      author.AuthorizeForTask(taskDto.Id, Permission.Full);
163
164      trans.UseTransaction(() => {
165        var task = optimizedDao.GetTaskByDto(taskDto);
166        optimizedDao.UpdateTask(task);
167      });
168    }
169
170    public void UpdateTaskData(Task task, TaskData taskData) {
171      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
172      author.AuthorizeForTask(task.Id, Permission.Full);
173
174      trans.UseTransaction(() => {
175        var t = optimizedDao.GetTaskByDto(task);
176        optimizedDao.UpdateTask(t);
177      });
178
179      trans.UseTransaction(() => {
180        var data = optimizedDao.GetTaskDataByDto(taskData);
181        data.LastUpdate = DateTime.Now;
182        optimizedDao.UpdateTaskData(data);
183      });
184    }
185
186    public void DeleteTask(Guid taskId) {
187      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
188      author.AuthorizeForTask(taskId, Permission.Full);
189      trans.UseTransaction(() => {
190        dao.DeleteTask(taskId);
191      });
192    }
193
194    public void DeleteChildTasks(Guid parentTaskId) {
195      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
196      author.AuthorizeForTask(parentTaskId, Permission.Full);
197      trans.UseTransaction(() => {
198        var tasks = GetChildTasks(parentTaskId, true, false);
199        foreach (var task in tasks) {
200          dao.DeleteTask(task.Id);
201          dao.DeleteTaskData(task.Id);
202        };
203      });
204    }
205
206    public Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
207      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
208      author.AuthorizeForTask(taskId, Permission.Full);
209
210      return trans.UseTransaction(() => {
211        var task = optimizedDao.UpdateTaskState(taskId, DT.Convert.ToEntity(taskState), slaveId, userId, exception);
212
213        if (task.Command.HasValue && task.Command.Value == DA.Command.Pause && task.State == DA.TaskState.Paused) {
214          task.Command = null;
215        } else if (task.Command.HasValue && task.Command.Value == DA.Command.Abort && task.State == DA.TaskState.Aborted) {
216          task.Command = null;
217        } else if (task.Command.HasValue && task.Command.Value == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
218          task.Command = null;
219        } else if (taskState == TaskState.Paused && !task.Command.HasValue) {
220          // slave paused and uploaded the task (no user-command) -> set waiting.
221          task = optimizedDao.UpdateTaskState(taskId, DA.TaskState.Waiting, slaveId, userId, exception);
222        }
223
224        return DT.Convert.ToDto(task);
225      });
226    }
227
228    public IEnumerable<Task> GetTasksByResourceId(Guid resourceId) {
229      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
230      var tasks = trans.UseTransaction(() => dao.GetJobsByResourceId(resourceId));
231      foreach (var task in tasks)
232        author.AuthorizeForTask(task.Id, Permission.Read);
233      return tasks;
234    }
235    #endregion
236
237    #region Task Control Methods
238    public void StopTask(Guid taskId) {
239      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
240      author.AuthorizeForTask(taskId, Permission.Full);
241      trans.UseTransaction(() => {
242        var task = dao.GetTask(taskId);
243        if (task.State == TaskState.Calculating || task.State == TaskState.Transferring) {
244          task.Command = Command.Stop;
245          dao.UpdateTask(task);
246        } else {
247          if (task.State != TaskState.Aborted && task.State != TaskState.Finished && task.State != TaskState.Failed) {
248            task = UpdateTaskState(taskId, TaskState.Aborted, null, null, string.Empty);
249          }
250        }
251      });
252    }
253
254    public void PauseTask(Guid taskId) {
255      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
256      author.AuthorizeForTask(taskId, Permission.Full);
257      trans.UseTransaction(() => {
258        var job = dao.GetTask(taskId);
259        if (job.State == TaskState.Calculating || job.State == TaskState.Transferring) {
260          job.Command = Command.Pause;
261          dao.UpdateTask(job);
262        } else {
263          job = UpdateTaskState(taskId, TaskState.Paused, null, null, string.Empty);
264        }
265      });
266    }
267
268    public void RestartTask(Guid taskId) {
269      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
270      author.AuthorizeForTask(taskId, Permission.Full);
271      trans.UseTransaction(() => {
272        Task task = dao.UpdateTaskState(taskId, DA.TaskState.Waiting, null, userManager.CurrentUserId, string.Empty);
273        task.Command = null;
274        dao.UpdateTask(task);
275      });
276    }
277    #endregion
278
279    #region Job Methods
280    public Job GetJob(Guid id) {
281      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
282      author.AuthorizeForJob(id, Permission.Read);
283      return trans.UseTransaction(() => {
284        var job = dao.GetJobs(x =>
285              x.JobId == id
286              && (x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0)
287            ).FirstOrDefault();
288        if (job != null) {
289          job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
290          job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
291        }
292        return job;
293      });
294    }
295
296    public IEnumerable<Job> GetJobs() {
297      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
298      return trans.UseTransaction(() => {
299        var jobs = dao.GetJobs(x => x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0);
300        foreach (var job in jobs) {
301          author.AuthorizeForJob(job.Id, Permission.Read);
302          job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
303          job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
304        }
305        return jobs;
306      });
307    }
308
309    public IEnumerable<Job> GetAllJobs() {
310      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
311      return trans.UseTransaction(() => {
312        var jobs = dao.GetJobs(x => true);
313        foreach (var job in jobs) { // no authorization here, since this method is admin-only! (admin is allowed to read all task)
314          job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
315          job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
316        }
317        return jobs;
318      });
319    }
320
321    public Guid AddJob(Job jobDto) {
322      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
323      return trans.UseTransaction(() => {
324        jobDto.OwnerUserId = userManager.CurrentUserId;
325        jobDto.DateCreated = DateTime.Now;
326        return dao.AddJob(jobDto);
327      });
328    }
329
330    public void UpdateJob(Job jobDto) {
331      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
332      author.AuthorizeForJob(jobDto.Id, Permission.Full);
333      trans.UseTransaction(() => {
334        dao.UpdateJob(jobDto);
335      });
336    }
337
338    public void DeleteJob(Guid jobId) {
339      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
340      author.AuthorizeForJob(jobId, Permission.Full);
341      trans.UseTransaction(() => {
342        dao.DeleteJob(jobId); // child task will be deleted by db-trigger
343      });
344    }
345    #endregion
346
347    #region JobPermission Methods
348    public void GrantPermission(Guid jobId, Guid grantedUserId, Permission permission) {
349      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
350      trans.UseTransaction(() => {
351        Job job = dao.GetJob(jobId);
352        if (job == null) throw new FaultException<FaultReason>(new FaultReason("Could not find task with id " + jobId));
353        Permission perm = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
354        if (perm != Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
355        dao.SetJobPermission(jobId, userManager.CurrentUserId, grantedUserId, DT.Convert.ToEntity(permission));
356      });
357    }
358
359    public void RevokePermission(Guid jobId, Guid grantedUserId) {
360      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
361      trans.UseTransaction(() => {
362        Job job = dao.GetJob(jobId);
363        if (job == null) throw new FaultException<FaultReason>(new FaultReason("Could not find task with id " + jobId));
364        DA.Permission perm = dao.GetPermissionForJob(job.Id, userManager.CurrentUserId);
365        if (perm != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
366        dao.SetJobPermission(jobId, userManager.CurrentUserId, grantedUserId, DA.Permission.NotAllowed);
367      });
368    }
369
370    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
371      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
372      return trans.UseTransaction(() => {
373        DA.Permission currentUserPermission = dao.GetPermissionForJob(jobId, userManager.CurrentUserId);
374        if (currentUserPermission != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to list permissions for this experiment"));
375        return dao.GetJobPermissions(x => x.JobId == jobId);
376      });
377    }
378
379    public bool IsAllowedPrivileged() {
380      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
381      return authen.IsInRole(HiveRoles.IsAllowedPrivileged);
382    }
383    #endregion
384
385    #region Login Methods
386    public void Hello(Slave slaveInfo) {
387      authen.AuthenticateForAnyRole(HiveRoles.Slave);
388      if (userManager.CurrentUser.UserName != "hiveslave")
389        slaveInfo.OwnerUserId = userManager.CurrentUserId;
390
391      trans.UseTransaction(() => {
392        var slave = dao.GetSlave(slaveInfo.Id);
393
394        if (slave == null) {
395          dao.AddSlave(slaveInfo);
396        } else {
397          slave.Name = slaveInfo.Name;
398          slave.Description = slaveInfo.Description;
399          slave.OwnerUserId = slaveInfo.OwnerUserId;
400
401          slave.Cores = slaveInfo.Cores;
402          slave.CpuArchitecture = slaveInfo.CpuArchitecture;
403          slave.CpuSpeed = slaveInfo.CpuSpeed;
404          slave.FreeCores = slaveInfo.FreeCores;
405          slave.FreeMemory = slaveInfo.FreeMemory;
406          slave.Memory = slaveInfo.Memory;
407          slave.OperatingSystem = slaveInfo.OperatingSystem;
408
409          slave.LastHeartbeat = DateTime.Now;
410          slave.SlaveState = SlaveState.Idle;
411
412          // don't update those properties: dbSlave.IsAllowedToCalculate, dbSlave.ParentResourceId
413
414          dao.UpdateSlave(slave);
415        }
416      });
417    }
418
419    public void GoodBye(Guid slaveId) {
420      authen.AuthenticateForAnyRole(HiveRoles.Slave);
421      trans.UseTransaction(() => {
422        var slave = dao.GetSlave(slaveId);
423        if (slave != null) {
424          slave.SlaveState = SlaveState.Offline;
425          dao.UpdateSlave(slave);
426        }
427      });
428    }
429    #endregion
430
431    #region Heartbeat Methods
432    public List<MessageContainer> Heartbeat(Heartbeat heartbeat) {
433      authen.AuthenticateForAnyRole(HiveRoles.Slave);
434
435      List<MessageContainer> result = new List<MessageContainer>();
436      try {
437        result = heartbeatManager.ProcessHeartbeat(heartbeat);
438      }
439      catch (Exception ex) {
440        DA.LogFactory.GetLogger(this.GetType().Namespace).Log("Exception processing Heartbeat: " + ex.ToString());
441      }
442
443      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
444        TriggerEventManager(false);
445      }
446
447      return result;
448    }
449    #endregion
450
451    #region Plugin Methods
452    public Guid AddPlugin(Plugin plugin, List<PluginData> pluginDatas) {
453      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
454      return trans.UseTransaction(() => {
455        plugin.UserId = userManager.CurrentUserId;
456        plugin.DateCreated = DateTime.Now;
457
458        var existing = dao.GetPlugins(x => x.Hash != null).Where(x => x.Hash.SequenceEqual(plugin.Hash));
459        if (existing.Count() > 0) {
460          // a plugin already exists.
461          throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(existing.Single().Id));
462        }
463
464        Guid pluginId = dao.AddPlugin(plugin);
465        foreach (PluginData pluginData in pluginDatas) {
466          pluginData.PluginId = pluginId;
467          dao.AddPluginData(pluginData);
468        }
469        return pluginId;
470      });
471    }
472
473    public Plugin GetPlugin(Guid pluginId) {
474      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
475      return trans.UseTransaction(() => {
476        return DT.Convert.ToDto(optimizedDao.GetPluginById(pluginId));
477      });
478    }
479
480    public Plugin GetPluginByHash(byte[] hash) {
481      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
482      return trans.UseTransaction(() => {
483        return dao.GetPlugins(x => x.Hash == hash).FirstOrDefault();
484      });
485    }
486
487    // 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)
488    //       change so that only with GetPluginByHash it is possible to download plugins
489    public IEnumerable<Plugin> GetPlugins() {
490      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
491      return trans.UseTransaction(() => {
492        return dao.GetPlugins(x => x.Hash != null);
493      });
494    }
495
496    public IEnumerable<PluginData> GetPluginDatas(List<Guid> pluginIds) {
497      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
498      var pluginDatas = new List<PluginData>();
499      return trans.UseTransaction(() => {
500        foreach (Guid guid in pluginIds) {
501          pluginDatas.AddRange(dao.GetPluginDatas(x => x.PluginId == guid).ToList());
502        }
503        return pluginDatas;
504      });
505    }
506
507    public void DeletePlugin(Guid pluginId) {
508      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
509      trans.UseTransaction(() => {
510        dao.DeletePlugin(pluginId);
511      });
512    }
513    #endregion
514
515    #region ResourcePermission Methods
516    public void GrantResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
517      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
518      trans.UseTransaction(() => {
519        Resource resource = dao.GetResource(resourceId);
520        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
521        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permission for this resource"));
522        foreach (Guid id in grantedUserIds)
523          dao.AddResourcePermission(new ResourcePermission { ResourceId = resourceId, GrantedByUserId = userManager.CurrentUserId, GrantedUserId = id });
524      });
525    }
526
527    public void RevokeResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
528      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
529      trans.UseTransaction(() => {
530        Resource resource = dao.GetResource(resourceId);
531        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
532        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to revoke permission for this resource"));
533        foreach (Guid id in grantedUserIds)
534          dao.DeleteResourcePermission(resourceId, id);
535      });
536    }
537
538    public IEnumerable<ResourcePermission> GetResourcePermissions(Guid resourceId) {
539      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
540      return trans.UseTransaction(() => {
541        Resource resource = dao.GetResource(resourceId);
542        if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
543        return dao.GetResourcePermissions(x => x.ResourceId == resourceId);
544      });
545    }
546    #endregion
547
548    #region Resource Methods
549    public IEnumerable<Resource> GetChildResources(Guid resourceId) {
550      return trans.UseTransaction(() => { return dao.GetChildResources(resourceId); });
551    }
552    #endregion
553
554    #region Slave Methods
555    public int GetNewHeartbeatInterval(Guid slaveId) {
556      authen.AuthenticateForAnyRole(HiveRoles.Slave);
557
558      Slave s = trans.UseTransaction(() => { return dao.GetSlave(slaveId); });
559      if (s != null) {
560        return s.HbInterval;
561      } else {
562        return -1;
563      }
564    }
565
566    public Guid AddSlave(Slave slave) {
567      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
568      return trans.UseTransaction(() => dao.AddSlave(slave));
569    }
570
571    public Guid AddSlaveGroup(SlaveGroup slaveGroup) {
572      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
573      return trans.UseTransaction(() => dao.AddSlaveGroup(slaveGroup));
574    }
575
576    public Slave GetSlave(Guid slaveId) {
577      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
578      return trans.UseTransaction(() => { return dao.GetSlave(slaveId); });
579    }
580
581    public SlaveGroup GetSlaveGroup(Guid slaveGroupId) {
582      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
583      return trans.UseTransaction(() => { return dao.GetSlaveGroup(slaveGroupId); });
584    }
585
586    public IEnumerable<Slave> GetSlaves() {
587      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
588      return trans.UseTransaction(() => {
589        return dao.GetSlaves(x => true).Where(x => x.OwnerUserId == null
590                                           || x.OwnerUserId == userManager.CurrentUserId
591                                           || userManager.VerifyUser(userManager.CurrentUserId, GetResourcePermissions(x.Id).Select(y => y.GrantedUserId).ToList())
592                                           || authen.IsInRole(HiveRoles.Administrator)).ToArray();
593      });
594    }
595
596    public IEnumerable<SlaveGroup> GetSlaveGroups() {
597      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
598      return trans.UseTransaction(() => {
599        return dao.GetSlaveGroups(x => true).Where(x => x.OwnerUserId == null
600                                                || x.OwnerUserId == userManager.CurrentUserId
601                                                || userManager.VerifyUser(userManager.CurrentUserId, GetResourcePermissions(x.Id).Select(y => y.GrantedUserId).ToList())
602                                                || authen.IsInRole(HiveRoles.Administrator)).ToArray();
603      });
604    }
605
606    public void UpdateSlave(Slave slave) {
607      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
608      trans.UseTransaction(() => {
609        dao.UpdateSlave(slave);
610      });
611    }
612
613    public void UpdateSlaveGroup(SlaveGroup slaveGroup) {
614      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
615      trans.UseTransaction(() => {
616        dao.UpdateSlaveGroup(slaveGroup);
617      });
618    }
619
620    public void DeleteSlave(Guid slaveId) {
621      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
622      author.AuthorizeForResourceAdministration(slaveId);
623      trans.UseTransaction(() => {
624        dao.DeleteSlave(slaveId);
625      });
626    }
627
628    public void DeleteSlaveGroup(Guid slaveGroupId) {
629      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
630      author.AuthorizeForResourceAdministration(slaveGroupId);
631      trans.UseTransaction(() => {
632        dao.DeleteSlaveGroup(slaveGroupId);
633      });
634    }
635
636    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
637      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
638      trans.UseTransaction(() => {
639        var resource = dao.GetResource(resourceId);
640        resource.ParentResourceId = slaveGroupId;
641        dao.UpdateResource(resource);
642      });
643    }
644
645    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
646      authen.AuthenticateForAnyRole(HiveRoles.Administrator);
647      trans.UseTransaction(() => {
648        var resource = dao.GetResource(resourceId);
649        resource.ParentResourceId = null;
650        dao.UpdateResource(resource);
651      });
652    }
653
654    public Guid GetResourceId(string resourceName) {
655      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
656      return trans.UseTransaction(() => {
657        var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
658        if (resource != null) {
659          return resource.Id;
660        } else {
661          return Guid.Empty;
662        }
663      });
664    }
665
666    public void TriggerEventManager(bool force) {
667      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Slave);
668      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
669      bool cleanup = false;
670      trans.UseTransaction(() => {
671        DateTime lastCleanup = dao.GetLastCleanup();
672        if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
673          dao.SetLastCleanup(DateTime.Now);
674          cleanup = true;
675        }
676      }, true);
677
678      if (cleanup) {
679        eventManager.Cleanup();
680      }
681    }
682    #endregion
683
684    #region Downtime Methods
685    public Guid AddDowntime(Downtime downtime) {
686      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
687      author.AuthorizeForResourceAdministration(downtime.ResourceId);
688      return trans.UseTransaction(() => dao.AddDowntime(downtime));
689    }
690
691    public void DeleteDowntime(Guid downtimeId) {
692      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
693      // TODO: pass resource id
694      // author.AuthorizeForResource(resourceId);
695      trans.UseTransaction(() => {
696        dao.DeleteDowntime(downtimeId);
697      });
698    }
699
700    public void UpdateDowntime(Downtime downtime) {
701      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
702      author.AuthorizeForResourceAdministration(downtime.ResourceId);
703      trans.UseTransaction(() => {
704        dao.UpdateDowntime(downtime);
705      });
706    }
707
708    public IEnumerable<Downtime> GetDowntimesForResource(Guid resourceId) {
709      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
710      return trans.UseTransaction(() => dao.GetDowntimes(x => x.ResourceId == resourceId));
711    }
712    #endregion
713
714    #region User Methods
715    public string GetUsernameByUserId(Guid userId) {
716      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
717      var user = ServiceLocator.Instance.UserManager.GetUserById(userId);
718      if (user != null)
719        return user.UserName;
720      else
721        return null;
722    }
723
724    public Guid GetUserIdByUsername(string username) {
725      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
726      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
727      return user != null ? (Guid)user.ProviderUserKey : Guid.Empty;
728    }
729    #endregion
730
731    #region UserPriority Methods
732    public IEnumerable<UserPriority> GetUserPriorities() {
733      return trans.UseTransaction(() => dao.GetUserPriorities(x => true));
734    }
735    #endregion
736
737    #region Helper Methods
738    private IEnumerable<Task> GetChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
739      var tasks = new List<Task>(dao.GetTasks(x => parentTaskId == null ? !x.ParentTaskId.HasValue : x.ParentTaskId.Value == parentTaskId));
740
741      if (recursive) {
742        var childs = new List<Task>();
743        foreach (var task in tasks) {
744          childs.AddRange(GetChildTasks(task.Id, recursive, false));
745        }
746        tasks.AddRange(childs);
747      }
748
749      if (includeParent) tasks.Add(GetTask(parentTaskId.Value));
750      return tasks;
751    }
752    #endregion
753
754    #region Statistics Methods
755    public IEnumerable<Statistics> GetStatistics() {
756      return trans.UseTransaction(() => { return dao.GetStatistics(x => true); });
757    }
758    public IEnumerable<Statistics> GetStatisticsForTimePeriod(DateTime from, DateTime to) {
759      return trans.UseTransaction(() => { return dao.GetStatistics(x => x.Timestamp >= from && x.Timestamp <= to); });
760    }
761    #endregion
762  }
763}
Note: See TracBrowser for help on using the repository browser.