Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9120 was 9035, checked in by ascheibe, 12 years ago

#1994 removed duplicate code

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