Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Services.Hive/3.3/HiveDao.cs @ 9022

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

#1994 added a dao method which loads lightweight tasks instead of tasks. Therefore the task datas are not loaded which reduces memory consumption and improves performance when

  • downloading tasks
  • refresh automatically is checked in the Hive Job Manager
  • loading the Hive Status page.

The Hive Status page now shows which users are currently calculating how many tasks.

File size: 38.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Linq.Expressions;
26using DT = HeuristicLab.Services.Hive.DataTransfer;
27
28namespace HeuristicLab.Services.Hive.DataAccess {
29  public class HiveDao : IHiveDao {
30    public static HiveDataContext CreateContext(bool longRunning = false) {
31      var context = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
32      if (longRunning) context.CommandTimeout = (int)Settings.Default.LongRunningDatabaseCommandTimeout.TotalSeconds;
33      return context;
34    }
35
36    public HiveDao() { }
37
38    #region Task Methods
39    public DT.Task GetTask(Guid id) {
40      using (var db = CreateContext()) {
41        return DT.Convert.ToDto(db.Tasks.SingleOrDefault(x => x.TaskId == id));
42      }
43    }
44
45    public IEnumerable<DT.Task> GetTasks(Expression<Func<Task, bool>> predicate) {
46      using (var db = CreateContext()) {
47        return db.Tasks.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
48      }
49    }
50
51    public IEnumerable<DT.LightweightTask> GetLightweightTasksForJob(Guid jobId) {
52      List<DT.LightweightTask> tasks = new List<DT.LightweightTask>();
53
54      using (var db = CreateContext()) {
55        var tasksQuery = from task in db.Tasks
56                         where task.JobId == jobId
57                         select new { task.TaskId, task.ExecutionTimeMs, task.ParentTaskId, task.StateLogs, task.State, task.Command };
58
59        var taskDatasQuery = from task in db.Tasks
60                             where task.JobId == jobId && task.JobData != null
61                             select new { task.TaskId, task.JobData.LastUpdate };
62
63        foreach (var task in tasksQuery) {
64          DT.LightweightTask t = new DT.LightweightTask();
65          t.Id = task.TaskId;
66          t.ExecutionTime = TimeSpan.FromMilliseconds(task.ExecutionTimeMs);
67          t.ParentTaskId = task.ParentTaskId;
68          t.StateLog = task.StateLogs == null ? new List<DT.StateLog>() : task.StateLogs.Select(x => DataTransfer.Convert.ToDto(x)).OrderBy(x => x.DateTime).ToList();
69          t.State = DataTransfer.Convert.ToDto(task.State);
70          t.Command = DataTransfer.Convert.ToDto(task.Command);
71          t.LastTaskDataUpdate = taskDatasQuery.Where(x => x.TaskId == task.TaskId).Count() > 0 ? taskDatasQuery.Select(x => x.LastUpdate).First() : DateTime.MinValue;
72          tasks.Add(t);
73        }
74      }
75      return tasks;
76    }
77
78    public IEnumerable<DT.LightweightTask> GetLightweightTasks(Expression<Func<Task, bool>> predicate) {
79      List<DT.LightweightTask> tasks = new List<DT.LightweightTask>();
80
81      using (var db = CreateContext()) {
82        var tasksQuery = db.Tasks.Where(predicate).Select(task => new { task.TaskId, task.ExecutionTimeMs, task.ParentTaskId, task.StateLogs, task.State, task.Command });
83        var taskDatasQuery = db.Tasks.Where(predicate).Where(task => task.JobData != null).Select(task => new { task.TaskId, task.JobData.LastUpdate });
84
85        foreach (var task in tasksQuery) {
86          DT.LightweightTask t = new DT.LightweightTask();
87          t.Id = task.TaskId;
88          t.ExecutionTime = TimeSpan.FromMilliseconds(task.ExecutionTimeMs);
89          t.ParentTaskId = task.ParentTaskId;
90          t.StateLog = task.StateLogs == null ? new List<DT.StateLog>() : task.StateLogs.Select(x => DataTransfer.Convert.ToDto(x)).OrderBy(x => x.DateTime).ToList();
91          t.State = DataTransfer.Convert.ToDto(task.State);
92          t.Command = DataTransfer.Convert.ToDto(task.Command);
93          t.LastTaskDataUpdate = taskDatasQuery.Where(x => x.TaskId == task.TaskId).Count() > 0 ? taskDatasQuery.Select(x => x.LastUpdate).First() : DateTime.MinValue;
94          tasks.Add(t);
95        }
96      }
97      return tasks;
98    }
99
100    public Guid AddTask(DT.Task dto) {
101      using (var db = CreateContext()) {
102        var entity = DT.Convert.ToEntity(dto);
103        db.Tasks.InsertOnSubmit(entity);
104        db.SubmitChanges();
105        foreach (Guid pluginId in dto.PluginsNeededIds) {
106          db.RequiredPlugins.InsertOnSubmit(new RequiredPlugin() { TaskId = entity.TaskId, PluginId = pluginId });
107        }
108        db.SubmitChanges();
109        return entity.TaskId;
110      }
111    }
112
113    public void UpdateTask(DT.Task dto) {
114      using (var db = CreateContext()) {
115        var entity = db.Tasks.FirstOrDefault(x => x.TaskId == dto.Id);
116        if (entity == null) db.Tasks.InsertOnSubmit(DT.Convert.ToEntity(dto));
117        else DT.Convert.ToEntity(dto, entity);
118        foreach (Guid pluginId in dto.PluginsNeededIds) {
119          if (db.RequiredPlugins.Count(p => p.PluginId == pluginId) == 0) {
120            db.RequiredPlugins.InsertOnSubmit(new RequiredPlugin() { TaskId = entity.TaskId, PluginId = pluginId });
121          }
122        }
123        db.SubmitChanges();
124      }
125    }
126
127    public void DeleteTask(Guid id) {
128      using (var db = CreateContext()) {
129        var entity = db.Tasks.FirstOrDefault(x => x.TaskId == id);
130        if (entity != null) db.Tasks.DeleteOnSubmit(entity);
131        db.SubmitChanges(); // taskData and child tasks are deleted by db-trigger
132      }
133    }
134
135    /// <summary>
136    /// returns all parent tasks which are waiting for their child tasks to finish
137    /// </summary>
138    /// <param name="resourceIds">list of resourceids which for which the task should be valid</param>
139    /// <param name="count">maximum number of task to return</param>
140    /// <param name="finished">if true, all parent task which have FinishWhenChildJobsFinished=true are returned, otherwise only FinishWhenChildJobsFinished=false are returned</param>
141    /// <returns></returns>
142    public IEnumerable<DT.Task> GetParentTasks(IEnumerable<Guid> resourceIds, int count, bool finished) {
143      using (var db = CreateContext()) {
144        var query = from ar in db.AssignedResources
145                    where resourceIds.Contains(ar.ResourceId)
146                       && ar.Task.State == TaskState.Waiting
147                       && ar.Task.IsParentTask
148                       && (finished ? ar.Task.FinishWhenChildJobsFinished : !ar.Task.FinishWhenChildJobsFinished)
149                       && (from child in db.Tasks
150                           where child.ParentTaskId == ar.Task.TaskId
151                           select child.State == TaskState.Finished
152                               || child.State == TaskState.Aborted
153                               || child.State == TaskState.Failed).All(x => x)
154                       && (from child in db.Tasks // avoid returning WaitForChildTasks task where no child-task exist (yet)
155                           where child.ParentTaskId == ar.Task.TaskId
156                           select child).Count() > 0
157                    orderby ar.Task.Priority descending, db.Random()
158                    select DT.Convert.ToDto(ar.Task);
159        return count == 0 ? query.ToArray() : query.Take(count).ToArray();
160      }
161    }
162
163    public IEnumerable<DT.Task> GetWaitingTasks(DT.Slave slave, int count) {
164      using (var db = CreateContext()) {
165        var resourceIds = GetParentResources(slave.Id).Select(r => r.Id);
166        //Originally we checked here if there are parent tasks which should be calculated (with GetParentTasks(resourceIds, count, false);).
167        //Because there is at the moment no case where this makes sense (there don't exist parent tasks which need to be calculated),
168        //we skip this step because it's wasted runtime
169
170        var query = from ar in db.AssignedResources
171                    where resourceIds.Contains(ar.ResourceId)
172                       && !(ar.Task.IsParentTask && ar.Task.FinishWhenChildJobsFinished)
173                       && ar.Task.State == TaskState.Waiting
174                       && ar.Task.CoresNeeded <= slave.FreeCores
175                       && ar.Task.MemoryNeeded <= slave.FreeMemory
176                    orderby ar.Task.Priority descending, db.Random() // take random task to avoid the race condition that occurs when this method is called concurrently (the same task would be returned)
177                    select DT.Convert.ToDto(ar.Task);
178        var waitingTasks = (count == 0 ? query : query.Take(count)).ToArray();
179        return waitingTasks;
180      }
181    }
182
183    public DT.Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
184      using (var db = CreateContext()) {
185        var job = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
186        job.State = taskState;
187        db.StateLogs.InsertOnSubmit(new StateLog {
188          TaskId = taskId,
189          State = taskState,
190          SlaveId = slaveId,
191          UserId = userId,
192          Exception = exception,
193          DateTime = DateTime.Now
194        });
195        db.SubmitChanges();
196        job = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
197        return DT.Convert.ToDto(job);
198      }
199    }
200    #endregion
201
202    #region TaskData Methods
203    public DT.TaskData GetTaskData(Guid id) {
204      using (var db = CreateContext(true)) {
205        return DT.Convert.ToDto(db.TaskDatas.SingleOrDefault(x => x.TaskId == id));
206      }
207    }
208
209    public IEnumerable<DT.TaskData> GetTaskDatas(Expression<Func<TaskData, bool>> predicate) {
210      using (var db = CreateContext(true)) {
211        return db.TaskDatas.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
212      }
213    }
214
215    public Guid AddTaskData(DT.TaskData dto) {
216      using (var db = CreateContext(true)) {
217        var entity = DT.Convert.ToEntity(dto);
218        db.TaskDatas.InsertOnSubmit(entity);
219        db.SubmitChanges();
220        return entity.TaskId;
221      }
222    }
223
224    public void UpdateTaskData(DT.TaskData dto) {
225      using (var db = CreateContext(true)) {
226        var entity = db.TaskDatas.FirstOrDefault(x => x.TaskId == dto.TaskId);
227        if (entity == null) db.TaskDatas.InsertOnSubmit(DT.Convert.ToEntity(dto));
228        else DT.Convert.ToEntity(dto, entity);
229        db.SubmitChanges();
230      }
231    }
232
233    public void DeleteTaskData(Guid id) {
234      using (var db = CreateContext()) {
235        var entity = db.TaskDatas.FirstOrDefault(x => x.TaskId == id); // check if all the byte[] is loaded into memory here. otherwise work around to delete without loading it
236        if (entity != null) db.TaskDatas.DeleteOnSubmit(entity);
237        db.SubmitChanges();
238      }
239    }
240    #endregion
241
242    #region StateLog Methods
243    public DT.StateLog GetStateLog(Guid id) {
244      using (var db = CreateContext()) {
245        return DT.Convert.ToDto(db.StateLogs.SingleOrDefault(x => x.StateLogId == id));
246      }
247    }
248
249    public IEnumerable<DT.StateLog> GetStateLogs(Expression<Func<StateLog, bool>> predicate) {
250      using (var db = CreateContext()) {
251        return db.StateLogs.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
252      }
253    }
254
255    public Guid AddStateLog(DT.StateLog dto) {
256      using (var db = CreateContext()) {
257        var entity = DT.Convert.ToEntity(dto);
258        db.StateLogs.InsertOnSubmit(entity);
259        db.SubmitChanges();
260        return entity.StateLogId;
261      }
262    }
263
264    public void UpdateStateLog(DT.StateLog dto) {
265      using (var db = CreateContext()) {
266        var entity = db.StateLogs.FirstOrDefault(x => x.StateLogId == dto.Id);
267        if (entity == null) db.StateLogs.InsertOnSubmit(DT.Convert.ToEntity(dto));
268        else DT.Convert.ToEntity(dto, entity);
269        db.SubmitChanges();
270      }
271    }
272
273    public void DeleteStateLog(Guid id) {
274      using (var db = CreateContext()) {
275        var entity = db.StateLogs.FirstOrDefault(x => x.StateLogId == id);
276        if (entity != null) db.StateLogs.DeleteOnSubmit(entity);
277        db.SubmitChanges();
278      }
279    }
280    #endregion
281
282    #region Job Methods
283    public DT.Job GetJob(Guid id) {
284      using (var db = CreateContext()) {
285        return AddStatsToJob(db, DT.Convert.ToDto(db.Jobs.SingleOrDefault(x => x.JobId == id)));
286      }
287    }
288
289    private DT.Job AddStatsToJob(HiveDataContext db, DT.Job exp) {
290      if (exp == null)
291        return null;
292
293      var jobs = db.Tasks.Where(j => j.JobId == exp.Id);
294      exp.JobCount = jobs.Count();
295      exp.CalculatingCount = jobs.Count(j => j.State == TaskState.Calculating);
296      exp.FinishedCount = jobs.Count(j => j.State == TaskState.Finished);
297      return exp;
298    }
299
300    public IEnumerable<DT.Job> GetJobs(Expression<Func<Job, bool>> predicate) {
301      using (var db = CreateContext()) {
302        return db.Jobs.Where(predicate).Select(x => AddStatsToJob(db, DT.Convert.ToDto(x))).ToArray();
303      }
304    }
305
306    public Guid AddJob(DT.Job dto) {
307      using (var db = CreateContext()) {
308        var entity = DT.Convert.ToEntity(dto);
309        db.Jobs.InsertOnSubmit(entity);
310        db.SubmitChanges();
311        return entity.JobId;
312      }
313    }
314
315    public void UpdateJob(DT.Job dto) {
316      using (var db = CreateContext()) {
317        var entity = db.Jobs.FirstOrDefault(x => x.JobId == dto.Id);
318        if (entity == null) db.Jobs.InsertOnSubmit(DT.Convert.ToEntity(dto));
319        else DT.Convert.ToEntity(dto, entity);
320        db.SubmitChanges();
321      }
322    }
323
324    public void DeleteJob(Guid id) {
325      using (var db = CreateContext()) {
326        var entity = db.Jobs.FirstOrDefault(x => x.JobId == id);
327        if (entity != null) db.Jobs.DeleteOnSubmit(entity);
328        db.SubmitChanges();
329      }
330    }
331    #endregion
332
333    #region JobPermission Methods
334    public DT.JobPermission GetJobPermission(Guid jobId, Guid grantedUserId) {
335      using (var db = CreateContext()) {
336        return DT.Convert.ToDto(db.JobPermissions.SingleOrDefault(x => x.JobId == jobId && x.GrantedUserId == grantedUserId));
337      }
338    }
339
340    public IEnumerable<DT.JobPermission> GetJobPermissions(Expression<Func<JobPermission, bool>> predicate) {
341      using (var db = CreateContext()) {
342        return db.JobPermissions.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
343      }
344    }
345
346    public void AddJobPermission(DT.JobPermission dto) {
347      using (var db = CreateContext()) {
348        var entity = DT.Convert.ToEntity(dto);
349        db.JobPermissions.InsertOnSubmit(entity);
350        db.SubmitChanges();
351      }
352    }
353
354    public void UpdateJobPermission(DT.JobPermission dto) {
355      using (var db = CreateContext()) {
356        var entity = db.JobPermissions.FirstOrDefault(x => x.JobId == dto.JobId && x.GrantedUserId == dto.GrantedUserId);
357        if (entity == null) db.JobPermissions.InsertOnSubmit(DT.Convert.ToEntity(dto));
358        else DT.Convert.ToEntity(dto, entity);
359        db.SubmitChanges();
360      }
361    }
362
363    public void DeleteJobPermission(Guid jobId, Guid grantedUserId) {
364      using (var db = CreateContext()) {
365        var entity = db.JobPermissions.FirstOrDefault(x => x.JobId == jobId && x.GrantedUserId == grantedUserId);
366        if (entity != null) db.JobPermissions.DeleteOnSubmit(entity);
367        db.SubmitChanges();
368      }
369    }
370
371    /// <summary>
372    /// Sets the permissions for a experiment. makes sure that only one permission per user exists.
373    /// </summary>
374    public void SetJobPermission(Guid jobId, Guid grantedByUserId, Guid grantedUserId, Permission permission) {
375      using (var db = CreateContext()) {
376        JobPermission jobPermission = db.JobPermissions.SingleOrDefault(x => x.JobId == jobId && x.GrantedUserId == grantedUserId);
377        if (jobPermission != null) {
378          if (permission == Permission.NotAllowed) {
379            // not allowed, delete
380            db.JobPermissions.DeleteOnSubmit(jobPermission);
381          } else {
382            // update
383            jobPermission.Permission = permission;
384            jobPermission.GrantedByUserId = grantedByUserId; // update grantedByUserId, always the last "granter" is stored
385          }
386        } else {
387          // insert
388          if (permission != Permission.NotAllowed) {
389            jobPermission = new JobPermission() { JobId = jobId, GrantedByUserId = grantedByUserId, GrantedUserId = grantedUserId, Permission = permission };
390            db.JobPermissions.InsertOnSubmit(jobPermission);
391          }
392        }
393        db.SubmitChanges();
394      }
395    }
396    #endregion
397
398    #region Plugin Methods
399    public DT.Plugin GetPlugin(Guid id) {
400      using (var db = CreateContext()) {
401        return DT.Convert.ToDto(db.Plugins.SingleOrDefault(x => x.PluginId == id));
402      }
403    }
404
405    public IEnumerable<DT.Plugin> GetPlugins(Expression<Func<Plugin, bool>> predicate) {
406      using (var db = CreateContext()) {
407        return db.Plugins.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
408      }
409    }
410
411    public Guid AddPlugin(DT.Plugin dto) {
412      using (var db = CreateContext()) {
413        var entity = DT.Convert.ToEntity(dto);
414        db.Plugins.InsertOnSubmit(entity);
415        db.SubmitChanges();
416        return entity.PluginId;
417      }
418    }
419
420    public void UpdatePlugin(DT.Plugin dto) {
421      using (var db = CreateContext()) {
422        var entity = db.Plugins.FirstOrDefault(x => x.PluginId == dto.Id);
423        if (entity == null) db.Plugins.InsertOnSubmit(DT.Convert.ToEntity(dto));
424        else DT.Convert.ToEntity(dto, entity);
425        db.SubmitChanges();
426      }
427    }
428
429    public void DeletePlugin(Guid id) {
430      using (var db = CreateContext()) {
431        var entity = db.Plugins.FirstOrDefault(x => x.PluginId == id);
432        if (entity != null) db.Plugins.DeleteOnSubmit(entity);
433        db.SubmitChanges();
434      }
435    }
436    #endregion
437
438    #region PluginData Methods
439    public DT.PluginData GetPluginData(Guid id) {
440      using (var db = CreateContext()) {
441        return DT.Convert.ToDto(db.PluginDatas.SingleOrDefault(x => x.PluginDataId == id));
442      }
443    }
444
445    public IEnumerable<DT.PluginData> GetPluginDatas(Expression<Func<PluginData, bool>> predicate) {
446      using (var db = CreateContext()) {
447        return db.PluginDatas.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
448      }
449    }
450
451    public Guid AddPluginData(DT.PluginData dto) {
452      using (var db = CreateContext()) {
453        var entity = DT.Convert.ToEntity(dto);
454        db.PluginDatas.InsertOnSubmit(entity);
455        db.SubmitChanges();
456        return entity.PluginDataId;
457      }
458    }
459
460    public void UpdatePluginData(DT.PluginData dto) {
461      using (var db = CreateContext()) {
462        var entity = db.PluginDatas.FirstOrDefault(x => x.PluginId == dto.PluginId);
463        if (entity == null) db.PluginDatas.InsertOnSubmit(DT.Convert.ToEntity(dto));
464        else DT.Convert.ToEntity(dto, entity);
465        db.SubmitChanges();
466      }
467    }
468
469    public void DeletePluginData(Guid id) {
470      using (var db = CreateContext()) {
471        var entity = db.PluginDatas.FirstOrDefault(x => x.PluginDataId == id);
472        if (entity != null) db.PluginDatas.DeleteOnSubmit(entity);
473        db.SubmitChanges();
474      }
475    }
476    #endregion
477
478    #region Slave Methods
479    public DT.Slave GetSlave(Guid id) {
480      using (var db = CreateContext()) {
481        return DT.Convert.ToDto(db.Resources.OfType<Slave>().SingleOrDefault(x => x.ResourceId == id));
482      }
483    }
484
485    public IEnumerable<DT.Slave> GetSlaves(Expression<Func<Slave, bool>> predicate) {
486      using (var db = CreateContext()) {
487        return db.Resources.OfType<Slave>().Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
488      }
489    }
490
491    public Guid AddSlave(DT.Slave dto) {
492      using (var db = CreateContext()) {
493        var entity = DT.Convert.ToEntity(dto);
494        db.Resources.InsertOnSubmit(entity);
495        db.SubmitChanges();
496        return entity.ResourceId;
497      }
498    }
499
500    public void UpdateSlave(DT.Slave dto) {
501      using (var db = CreateContext()) {
502        var entity = db.Resources.OfType<Slave>().FirstOrDefault(x => x.ResourceId == dto.Id);
503        if (entity == null) db.Resources.InsertOnSubmit(DT.Convert.ToEntity(dto));
504        else DT.Convert.ToEntity(dto, entity);
505        db.SubmitChanges();
506      }
507    }
508
509    public void DeleteSlave(Guid id) {
510      using (var db = CreateContext()) {
511        var entity = db.Resources.OfType<Slave>().FirstOrDefault(x => x.ResourceId == id);
512        if (entity != null) db.Resources.DeleteOnSubmit(entity);
513        db.SubmitChanges();
514      }
515    }
516    #endregion
517
518    #region SlaveGroup Methods
519    public DT.SlaveGroup GetSlaveGroup(Guid id) {
520      using (var db = CreateContext()) {
521        return DT.Convert.ToDto(db.Resources.OfType<SlaveGroup>().SingleOrDefault(x => x.ResourceId == id));
522      }
523    }
524
525    public IEnumerable<DT.SlaveGroup> GetSlaveGroups(Expression<Func<SlaveGroup, bool>> predicate) {
526      using (var db = CreateContext()) {
527        return db.Resources.OfType<SlaveGroup>().Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
528      }
529    }
530
531    public Guid AddSlaveGroup(DT.SlaveGroup dto) {
532      using (var db = CreateContext()) {
533        if (dto.Id == Guid.Empty)
534          dto.Id = Guid.NewGuid();
535        var entity = DT.Convert.ToEntity(dto);
536        db.Resources.InsertOnSubmit(entity);
537        db.SubmitChanges();
538        return entity.ResourceId;
539      }
540    }
541
542    public void UpdateSlaveGroup(DT.SlaveGroup dto) {
543      using (var db = CreateContext()) {
544        var entity = db.Resources.OfType<SlaveGroup>().FirstOrDefault(x => x.ResourceId == dto.Id);
545        if (entity == null) db.Resources.InsertOnSubmit(DT.Convert.ToEntity(dto));
546        else DT.Convert.ToEntity(dto, entity);
547        db.SubmitChanges();
548      }
549    }
550
551    public void DeleteSlaveGroup(Guid id) {
552      using (var db = CreateContext()) {
553        var entity = db.Resources.OfType<SlaveGroup>().FirstOrDefault(x => x.ResourceId == id);
554        if (entity != null) {
555          if (db.Resources.Where(r => r.ParentResourceId == id).Count() > 0) {
556            throw new InvalidOperationException("Cannot delete SlaveGroup as long as there are Slaves in the group");
557          }
558          db.Resources.DeleteOnSubmit(entity);
559        }
560        db.SubmitChanges();
561      }
562    }
563    #endregion
564
565    #region Resource Methods
566    public DT.Resource GetResource(Guid id) {
567      using (var db = CreateContext()) {
568        return DT.Convert.ToDto(db.Resources.SingleOrDefault(x => x.ResourceId == id));
569      }
570    }
571
572    public IEnumerable<DT.Resource> GetResources(Expression<Func<Resource, bool>> predicate) {
573      using (var db = CreateContext()) {
574        return db.Resources.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
575      }
576    }
577
578    public Guid AddResource(DT.Resource dto) {
579      using (var db = CreateContext()) {
580        var entity = DT.Convert.ToEntity(dto);
581        db.Resources.InsertOnSubmit(entity);
582        db.SubmitChanges();
583        return entity.ResourceId;
584      }
585    }
586
587    public void UpdateResource(DT.Resource dto) {
588      using (var db = CreateContext()) {
589        var entity = db.Resources.FirstOrDefault(x => x.ResourceId == dto.Id);
590        if (entity == null) db.Resources.InsertOnSubmit(DT.Convert.ToEntity(dto));
591        else DT.Convert.ToEntity(dto, entity);
592        db.SubmitChanges();
593      }
594    }
595
596    public void DeleteResource(Guid id) {
597      using (var db = CreateContext()) {
598        var entity = db.Resources.FirstOrDefault(x => x.ResourceId == id);
599        if (entity != null) db.Resources.DeleteOnSubmit(entity);
600        db.SubmitChanges();
601      }
602    }
603
604    public void AssignJobToResource(Guid jobId, Guid resourceId) {
605      using (var db = CreateContext()) {
606        var job = db.Tasks.Where(x => x.TaskId == jobId).Single();
607        job.AssignedResources.Add(new AssignedResource() { TaskId = jobId, ResourceId = resourceId });
608        db.SubmitChanges();
609      }
610    }
611
612    public IEnumerable<DT.Resource> GetAssignedResources(Guid jobId) {
613      using (var db = CreateContext()) {
614        var job = db.Tasks.Where(x => x.TaskId == jobId).Single();
615        return job.AssignedResources.Select(x => DT.Convert.ToDto(x.Resource)).ToArray();
616      }
617    }
618
619    /// <summary>
620    /// Returns all parent resources of a resource (the given resource is also added)
621    /// </summary>
622    public IEnumerable<DT.Resource> GetParentResources(Guid resourceId) {
623      using (var db = CreateContext()) {
624        var resources = new List<Resource>();
625        CollectParentResources(resources, db.Resources.Where(r => r.ResourceId == resourceId).Single());
626        return resources.Select(r => DT.Convert.ToDto(r)).ToArray();
627      }
628    }
629
630    private void CollectParentResources(List<Resource> resources, Resource resource) {
631      if (resource == null) return;
632      resources.Add(resource);
633      CollectParentResources(resources, resource.ParentResource);
634    }
635
636    /// <summary>
637    /// Returns all child resources of a resource (without the given resource)
638    /// </summary>
639    public IEnumerable<DT.Resource> GetChildResources(Guid resourceId) {
640      using (var db = CreateContext()) {
641        var childs = new List<DT.Resource>();
642        foreach (var child in db.Resources.Where(x => x.ParentResourceId == resourceId)) {
643          childs.Add(DT.Convert.ToDto(child));
644          childs.AddRange(GetChildResources(child.ResourceId));
645        }
646        return childs;
647      }
648    }
649
650    public IEnumerable<DT.Task> GetJobsByResourceId(Guid resourceId) {
651      using (var db = CreateContext()) {
652        var resources = GetChildResources(resourceId).Select(x => x.Id).ToList();
653        resources.Add(resourceId);
654
655        var jobs = db.Tasks.Where(j =>
656          j.State == TaskState.Calculating &&
657          j.StateLogs.OrderByDescending(x => x.DateTime).First().SlaveId.HasValue &&
658          resources.Contains(j.StateLogs.OrderByDescending(x => x.DateTime).First().SlaveId.Value));
659        return jobs.Select(j => DT.Convert.ToDto(j)).ToArray();
660      }
661    }
662    #endregion
663
664    #region ResourcePermission Methods
665    public DT.ResourcePermission GetResourcePermission(Guid resourceId, Guid grantedUserId) {
666      using (var db = CreateContext()) {
667        return DT.Convert.ToDto(db.ResourcePermissions.SingleOrDefault(x => x.ResourceId == resourceId && x.GrantedUserId == grantedUserId));
668      }
669    }
670
671    public IEnumerable<DT.ResourcePermission> GetResourcePermissions(Expression<Func<ResourcePermission, bool>> predicate) {
672      using (var db = CreateContext()) {
673        return db.ResourcePermissions.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
674      }
675    }
676
677    public void AddResourcePermission(DT.ResourcePermission dto) {
678      using (var db = CreateContext()) {
679        var entity = db.ResourcePermissions.SingleOrDefault(x => x.ResourceId == dto.ResourceId && x.GrantedUserId == dto.GrantedUserId);
680        if (entity == null) { db.ResourcePermissions.InsertOnSubmit(DT.Convert.ToEntity(dto)); db.SubmitChanges(); }
681      }
682    }
683
684    public void UpdateResourcePermission(DT.ResourcePermission dto) {
685      using (var db = CreateContext()) {
686        var entity = db.ResourcePermissions.FirstOrDefault(x => x.ResourceId == dto.ResourceId && x.GrantedUserId == dto.GrantedUserId);
687        if (entity == null) db.ResourcePermissions.InsertOnSubmit(DT.Convert.ToEntity(dto));
688        else DT.Convert.ToEntity(dto, entity);
689        db.SubmitChanges();
690      }
691    }
692
693    public void DeleteResourcePermission(Guid resourceId, Guid grantedUserId) {
694      using (var db = CreateContext()) {
695        var entity = db.ResourcePermissions.FirstOrDefault(x => x.ResourceId == resourceId && x.GrantedUserId == grantedUserId);
696        if (entity != null) db.ResourcePermissions.DeleteOnSubmit(entity);
697        db.SubmitChanges();
698      }
699    }
700    #endregion
701
702    #region Authorization Methods
703    public Permission GetPermissionForTask(Guid taskId, Guid userId) {
704      using (var db = CreateContext()) {
705        return GetPermissionForJob(GetJobForTask(taskId), userId);
706      }
707    }
708
709    public Permission GetPermissionForJob(Guid jobId, Guid userId) {
710      using (var db = CreateContext()) {
711        Job job = db.Jobs.SingleOrDefault(x => x.JobId == jobId);
712        if (job == null) return Permission.NotAllowed;
713        if (job.OwnerUserId == userId) return Permission.Full;
714        JobPermission permission = db.JobPermissions.SingleOrDefault(p => p.JobId == jobId && p.GrantedUserId == userId);
715        return permission != null ? permission.Permission : Permission.NotAllowed;
716      }
717    }
718
719    public Guid GetJobForTask(Guid taskId) {
720      using (var db = CreateContext()) {
721        return db.Tasks.Single(j => j.TaskId == taskId).JobId;
722      }
723    }
724    #endregion
725
726    #region Lifecycle Methods
727    public DateTime GetLastCleanup() {
728      using (var db = CreateContext()) {
729        var entity = db.Lifecycles.SingleOrDefault();
730        return entity != null ? entity.LastCleanup : DateTime.MinValue;
731      }
732    }
733
734    public void SetLastCleanup(DateTime datetime) {
735      using (var db = CreateContext()) {
736        var entity = db.Lifecycles.SingleOrDefault();
737        if (entity != null) {
738          entity.LastCleanup = datetime;
739        } else {
740          entity = new Lifecycle();
741          entity.LifecycleId = 0; // always only one entry with ID:0
742          entity.LastCleanup = datetime;
743          db.Lifecycles.InsertOnSubmit(entity);
744        }
745        db.SubmitChanges();
746      }
747    }
748    #endregion
749
750    #region Downtime Methods
751    public DT.Downtime GetDowntime(Guid id) {
752      using (var db = CreateContext()) {
753        return DT.Convert.ToDto(db.Downtimes.SingleOrDefault(x => x.DowntimeId == id));
754      }
755    }
756
757    public IEnumerable<DT.Downtime> GetDowntimes(Expression<Func<Downtime, bool>> predicate) {
758      using (var db = CreateContext()) {
759        return db.Downtimes.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
760      }
761    }
762
763    public Guid AddDowntime(DT.Downtime dto) {
764      using (var db = CreateContext()) {
765        var entity = DT.Convert.ToEntity(dto);
766        db.Downtimes.InsertOnSubmit(entity);
767        db.SubmitChanges();
768        return entity.DowntimeId;
769      }
770    }
771
772    public void UpdateDowntime(DT.Downtime dto) {
773      using (var db = CreateContext()) {
774        var entity = db.Downtimes.FirstOrDefault(x => x.DowntimeId == dto.Id);
775        if (entity == null) db.Downtimes.InsertOnSubmit(DT.Convert.ToEntity(dto));
776        else DT.Convert.ToEntity(dto, entity);
777        db.SubmitChanges();
778      }
779    }
780
781    public void DeleteDowntime(Guid id) {
782      using (var db = CreateContext()) {
783        var entity = db.Downtimes.FirstOrDefault(x => x.DowntimeId == id);
784        if (entity != null) db.Downtimes.DeleteOnSubmit(entity);
785        db.SubmitChanges();
786      }
787    }
788    #endregion
789
790    #region Statistics Methods
791    public DT.Statistics GetStatistic(Guid id) {
792      using (var db = CreateContext()) {
793        return DT.Convert.ToDto(db.Statistics.SingleOrDefault(x => x.StatisticsId == id));
794      }
795    }
796
797    public IEnumerable<DT.Statistics> GetStatistics(Expression<Func<Statistics, bool>> predicate) {
798      using (var db = CreateContext()) {
799        return db.Statistics.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
800      }
801    }
802
803    public Guid AddStatistics(DT.Statistics dto) {
804      using (var db = CreateContext()) {
805        var entity = DT.Convert.ToEntity(dto);
806        db.Statistics.InsertOnSubmit(entity);
807        db.SubmitChanges();
808        foreach (var slaveStat in dto.SlaveStatistics) {
809          slaveStat.Id = entity.StatisticsId;
810          db.SlaveStatistics.InsertOnSubmit(DT.Convert.ToEntity(slaveStat));
811        }
812        if (dto.UserStatistics != null) {
813          foreach (var userStat in dto.UserStatistics) {
814            userStat.Id = entity.StatisticsId;
815            db.UserStatistics.InsertOnSubmit(DT.Convert.ToEntity(userStat));
816          }
817        }
818        db.SubmitChanges();
819        return entity.StatisticsId;
820      }
821    }
822
823    public void DeleteStatistics(Guid id) {
824      using (var db = CreateContext()) {
825        var entity = db.Statistics.FirstOrDefault(x => x.StatisticsId == id);
826        if (entity != null) db.Statistics.DeleteOnSubmit(entity);
827        db.SubmitChanges();
828      }
829    }
830
831    public Dictionary<Guid, int> GetWaitingTasksByUser() {
832      using (var db = CreateContext()) {
833        var waitingTasksByUser = from task in db.Tasks
834                                 where task.State == TaskState.Waiting
835                                 group task by task.Job.OwnerUserId into g
836                                 select new { UserId = g.Key, UsedCores = g.Count() };
837        return waitingTasksByUser.ToDictionary(x => x.UserId, x => x.UsedCores);
838      }
839    }
840
841    public Dictionary<Guid, int> GetCalculatingTasksByUser() {
842      using (var db = CreateContext()) {
843        var calculatingTasksByUser = from task in db.Tasks
844                              where task.State == TaskState.Calculating
845                              group task by task.Job.OwnerUserId into g
846                              select new { UserId = g.Key, UsedCores = g.Count() };
847        return calculatingTasksByUser.ToDictionary(x => x.UserId, x => x.UsedCores);
848      }
849    }
850
851    public List<DT.UserStatistics> GetUserStatistics() {
852      using (var db = CreateContext()) {
853        var userStats = new Dictionary<Guid, DT.UserStatistics>();
854
855        var usedCoresByUser = from job in db.Tasks
856                              where job.State == TaskState.Calculating
857                              group job by job.Job.OwnerUserId into g
858                              select new { UserId = g.Key, UsedCores = g.Count() };
859
860        foreach (var item in usedCoresByUser) {
861          if (!userStats.ContainsKey(item.UserId)) {
862            userStats.Add(item.UserId, new DT.UserStatistics() { UserId = item.UserId });
863          }
864          userStats[item.UserId].UsedCores += item.UsedCores;
865        }
866
867        var executionTimesByUser = from task in db.Tasks
868                                   group task by task.Job.OwnerUserId into g
869                                   select new { UserId = g.Key, ExecutionTime = TimeSpan.FromMilliseconds(g.Select(x => x.ExecutionTimeMs).Sum()) };
870        foreach (var item in executionTimesByUser) {
871          if (!userStats.ContainsKey(item.UserId)) {
872            userStats.Add(item.UserId, new DT.UserStatistics() { UserId = item.UserId });
873          }
874          userStats[item.UserId].ExecutionTime += item.ExecutionTime;
875        }
876
877        // execution times only of finished task - necessary to compute efficieny
878        var executionTimesFinishedJobs = from job in db.Tasks
879                                         where job.State == TaskState.Finished
880                                         group job by job.Job.OwnerUserId into g
881                                         select new { UserId = g.Key, ExecutionTimeFinishedJobs = TimeSpan.FromMilliseconds(g.Select(x => x.ExecutionTimeMs).Sum()) };
882
883        foreach (var item in executionTimesFinishedJobs) {
884          if (!userStats.ContainsKey(item.UserId)) {
885            userStats.Add(item.UserId, new DT.UserStatistics() { UserId = item.UserId });
886          }
887          userStats[item.UserId].ExecutionTimeFinishedJobs += item.ExecutionTimeFinishedJobs;
888        }
889
890        // start to end times only of finished task - necessary to compute efficiency
891        var startToEndTimesFinishedJobs = from job in db.Tasks
892                                          where job.State == TaskState.Finished
893                                          group job by job.Job.OwnerUserId into g
894                                          select new {
895                                            UserId = g.Key,
896                                            StartToEndTime = new TimeSpan(g.Select(x => x.StateLogs.OrderByDescending(sl => sl.DateTime).First().DateTime - x.StateLogs.OrderBy(sl => sl.DateTime).First().DateTime).Sum(ts => ts.Ticks))
897                                          };
898        foreach (var item in startToEndTimesFinishedJobs) {
899          if (!userStats.ContainsKey(item.UserId)) {
900            userStats.Add(item.UserId, new DT.UserStatistics() { UserId = item.UserId });
901          }
902          userStats[item.UserId].StartToEndTime += item.StartToEndTime;
903        }
904
905        // also consider executiontimes of DeletedJobStats
906        var deletedJobsExecutionTimesByUsers = from del in db.DeletedJobStatistics
907                                               group del by del.UserId into g
908                                               select new {
909                                                 UserId = g.Key,
910                                                 ExecutionTime = TimeSpan.FromSeconds(g.Select(x => x.ExecutionTimeS).Sum()),
911                                                 ExecutionTimeFinishedJobs = TimeSpan.FromSeconds(g.Select(x => x.ExecutionTimeSFinishedJobs).Sum()),
912                                                 StartToEndTime = TimeSpan.FromSeconds(g.Select(x => x.StartToEndTimeS).Sum())
913                                               };
914        foreach (var item in deletedJobsExecutionTimesByUsers) {
915          if (!userStats.ContainsKey(item.UserId)) {
916            userStats.Add(item.UserId, new DT.UserStatistics() { UserId = item.UserId });
917          }
918          userStats[item.UserId].ExecutionTime += item.ExecutionTime;
919          userStats[item.UserId].ExecutionTimeFinishedJobs += item.ExecutionTimeFinishedJobs;
920          userStats[item.UserId].StartToEndTime += item.StartToEndTime;
921        }
922
923        return userStats.Values.ToList();
924      }
925    }
926    #endregion
927
928    #region Helpers
929    private void CollectChildTasks(HiveDataContext db, Guid parentTaskId, List<Task> collection) {
930      var tasks = db.Tasks.Where(j => j.ParentTaskId == parentTaskId);
931      foreach (var task in tasks) {
932        collection.Add(task);
933        if (task.IsParentTask)
934          CollectChildTasks(db, task.TaskId, collection);
935      }
936    }
937    #endregion
938  }
939}
Note: See TracBrowser for help on using the repository browser.