Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15866 was 9365, checked in by fschoepp, 12 years ago

#1888:

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