source: branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/HiveService.cs @ 12691

Last change on this file since 12691 was 12691, checked in by dglaser, 6 years ago

#2388:

HeuristicLab.Services.Access:
HeuristicLab.Services.Access.DataAccess:

  • Changed connection strings and certificates for local usage

HeuristicLab.Services.Hive.DataAccess:

  • Added compiled queries for frequently used queries
  • Integrated string queries from OptimizedHiveDao

HeuristicLab.Services.Hive:

  • Added NewHeartbeatManager.cs
  • Added NewRoundRobinTaskScheduler.cs
  • Added PerformanceLogger
  • Updated AuthoriziationManager
  • Updated NewHiveService
    • Added Regions
    • Implemented missing methods
    • Improved performance of several queries

HeuristicLab.Services.WebApp.Status:

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