Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveHiveEngine/HeuristicLab.Services.Hive/3.3/HiveDao.cs @ 10159

Last change on this file since 10159 was 7320, checked in by ascheibe, 13 years ago

#1744 fixed a bug in the job scheduler for hive engine tasks

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