Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9280 was 9266, checked in by ascheibe, 12 years ago

#2019 disable lazy loading in some methods to avoid deadlocks

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