Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HivePerformance/sources/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 9426

Last change on this file since 9426 was 9399, checked in by pfleck, 12 years ago

#2030
Removed unnecessary UpdatePlugins in UpdateTask.
Optimized GetTask and GetPlugin with compiled queries.

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