Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveDao.cs @ 9215

Last change on this file since 9215 was 9215, checked in by fschoepp, 11 years ago

#1888:

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