Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15287 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
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;
[9363]24using System.Configuration;
25using System.Data.Common;
[6983]26using System.Linq;
27using System.Linq.Expressions;
[9363]28using HeuristicLab.Services.Hive.Interfaces;
[6983]29using DT = HeuristicLab.Services.Hive.DataTransfer;
30
31namespace HeuristicLab.Services.Hive.DataAccess {
32  public class HiveDao : IHiveDao {
[9363]33
[8326]34    public HiveDataContext CreateContext(bool longRunning = false) {
35      //var context = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
[9215]36      HiveDataContext context;
37      if (ConfigurationManager.ConnectionStrings[Settings.Default.HiveConnectionStringName] == null) {
38        context = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
[9363]39      } else {
[9215]40        context = new HiveDataContext(provider.GetOpenConnection(Settings.Default.HiveConnectionStringName));
41      }
[6983]42      if (longRunning) context.CommandTimeout = (int)Settings.Default.LongRunningDatabaseCommandTimeout.TotalSeconds;
43      return context;
44    }
45
[8326]46    private IConnectionProvider provider;
[6983]47
[8326]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
[6983]80    #region Task Methods
81    public DT.Task GetTask(Guid id) {
[8326]82      return ExecuteWithContext<DT.Task>((db) => {
[6983]83        return DT.Convert.ToDto(db.Tasks.SingleOrDefault(x => x.TaskId == id));
[8326]84      });
[6983]85    }
86
87    public IEnumerable<DT.Task> GetTasks(Expression<Func<Task, bool>> predicate) {
[8326]88      return ExecuteWithContext<IEnumerable<DT.Task>>((db) => {
[6983]89        return db.Tasks.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]90      });
[6983]91    }
92
[9363]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
[6983]137    public Guid AddTask(DT.Task dto) {
[8326]138      return ExecuteWithContext<Guid>((db) => {
[6983]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;
[8326]147      });
[6983]148    }
149
[9363]150    public void UpdateTaskAndPlugins(DT.Task dto) {
[8326]151      ExecuteWithContext((db) => {
[6983]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();
[8326]161      });
[6983]162    }
163
[9363]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
[6983]184    public void DeleteTask(Guid id) {
[8326]185      ExecuteWithContext((db) => {
[6983]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
[8326]189      });
[6983]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) {
[8326]200      return ExecuteWithContext<IEnumerable<DT.Task>>((db) => {
[6983]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();
[8326]217      });
[6983]218    }
219
[9363]220    public IEnumerable<TaskInfoForScheduler> GetWaitingTasks(DT.Slave slave) {
221      return ExecuteWithContext<IEnumerable<TaskInfoForScheduler>>((db) => {
[6983]222        var resourceIds = GetParentResources(slave.Id).Select(r => r.Id);
[7178]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
[6983]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
[9363]233                    select new TaskInfoForScheduler() { TaskId = ar.Task.TaskId, JobId = ar.Task.JobId, Priority = ar.Task.Priority };
234        var waitingTasks = query.ToArray();
[7178]235        return waitingTasks;
[8326]236      });
[6983]237    }
238
239    public DT.Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
[8326]240      return ExecuteWithContext<DT.Task>((db) => {
[9363]241        var task = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
242        task.State = taskState;
[6983]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();
[9363]252        task = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
253        return DT.Convert.ToDto(task);
[8326]254      });
[6983]255    }
256    #endregion
257
258    #region TaskData Methods
259    public DT.TaskData GetTaskData(Guid id) {
[8326]260      return ExecuteWithContext<DT.TaskData>((db) => {
[6983]261        return DT.Convert.ToDto(db.TaskDatas.SingleOrDefault(x => x.TaskId == id));
[8326]262      });
[6983]263    }
264
265    public IEnumerable<DT.TaskData> GetTaskDatas(Expression<Func<TaskData, bool>> predicate) {
[8326]266      return ExecuteWithContext<IEnumerable<DT.TaskData>>((db) => {
[6983]267        return db.TaskDatas.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]268      });
[6983]269    }
270
271    public Guid AddTaskData(DT.TaskData dto) {
[8326]272      return ExecuteWithContext<Guid>((db) => {
[6983]273        var entity = DT.Convert.ToEntity(dto);
274        db.TaskDatas.InsertOnSubmit(entity);
275        db.SubmitChanges();
276        return entity.TaskId;
[8326]277      });
[6983]278    }
279
280    public void UpdateTaskData(DT.TaskData dto) {
[8326]281      ExecuteWithContext((db) => {
[6983]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();
[8326]286      });
[6983]287    }
288
289    public void DeleteTaskData(Guid id) {
[8326]290      ExecuteWithContext((db) => {
[6983]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();
[8326]294      });
[6983]295    }
296    #endregion
297
298    #region StateLog Methods
299    public DT.StateLog GetStateLog(Guid id) {
[8326]300      return ExecuteWithContext<DT.StateLog>((db) => {
[6983]301        return DT.Convert.ToDto(db.StateLogs.SingleOrDefault(x => x.StateLogId == id));
[8326]302      });
[6983]303    }
304
305    public IEnumerable<DT.StateLog> GetStateLogs(Expression<Func<StateLog, bool>> predicate) {
[8326]306      return ExecuteWithContext<IEnumerable<DT.StateLog>>((db) => {
[6983]307        return db.StateLogs.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]308      });
[6983]309    }
310
311    public Guid AddStateLog(DT.StateLog dto) {
[8326]312      return ExecuteWithContext<Guid>((db) => {
[6983]313        var entity = DT.Convert.ToEntity(dto);
314        db.StateLogs.InsertOnSubmit(entity);
315        db.SubmitChanges();
316        return entity.StateLogId;
[8326]317      });
[6983]318    }
319
320    public void UpdateStateLog(DT.StateLog dto) {
[8326]321      ExecuteWithContext((db) => {
[6983]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();
[8326]326      });
[6983]327    }
328
329    public void DeleteStateLog(Guid id) {
[8326]330      ExecuteWithContext((db) => {
[6983]331        var entity = db.StateLogs.FirstOrDefault(x => x.StateLogId == id);
332        if (entity != null) db.StateLogs.DeleteOnSubmit(entity);
333        db.SubmitChanges();
[8326]334      });
[6983]335    }
336    #endregion
337
338    #region Job Methods
339    public DT.Job GetJob(Guid id) {
[8326]340      return ExecuteWithContext<DT.Job>((db) => {
[6983]341        return AddStatsToJob(db, DT.Convert.ToDto(db.Jobs.SingleOrDefault(x => x.JobId == id)));
[8326]342      });
[6983]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) {
[8326]357      return ExecuteWithContext<IEnumerable<DT.Job>>((db) => {
[6983]358        return db.Jobs.Where(predicate).Select(x => AddStatsToJob(db, DT.Convert.ToDto(x))).ToArray();
[8326]359      });
[6983]360    }
361
[9363]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
[6983]368    public Guid AddJob(DT.Job dto) {
[8326]369      return ExecuteWithContext<Guid>((db) => {
[6983]370        var entity = DT.Convert.ToEntity(dto);
371        db.Jobs.InsertOnSubmit(entity);
[9363]372        if (!db.UserPriorities.Any(x => x.UserId == dto.OwnerUserId))
373          EnqueueUserPriority(new DT.UserPriority { Id = dto.OwnerUserId, DateEnqueued = dto.DateCreated });
[6983]374        db.SubmitChanges();
375        return entity.JobId;
[8326]376      });
[6983]377    }
378
379    public void UpdateJob(DT.Job dto) {
[8326]380      ExecuteWithContext((db) => {
[6983]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();
[8326]385      });
[6983]386    }
387
388    public void DeleteJob(Guid id) {
[8326]389      ExecuteWithContext((db) => {
[6983]390        var entity = db.Jobs.FirstOrDefault(x => x.JobId == id);
391        if (entity != null) db.Jobs.DeleteOnSubmit(entity);
392        db.SubmitChanges();
[8326]393      });
[6983]394    }
395    #endregion
396
397    #region JobPermission Methods
398    public DT.JobPermission GetJobPermission(Guid jobId, Guid grantedUserId) {
[8326]399      return ExecuteWithContext<DT.JobPermission>((db) => {
[6983]400        return DT.Convert.ToDto(db.JobPermissions.SingleOrDefault(x => x.JobId == jobId && x.GrantedUserId == grantedUserId));
[8326]401      });
[6983]402    }
403
404    public IEnumerable<DT.JobPermission> GetJobPermissions(Expression<Func<JobPermission, bool>> predicate) {
[8326]405      return ExecuteWithContext<IEnumerable<DT.JobPermission>>((db) => {
[6983]406        return db.JobPermissions.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]407      });
[6983]408    }
409
410    public void AddJobPermission(DT.JobPermission dto) {
[8326]411      ExecuteWithContext((db) => {
[6983]412        var entity = DT.Convert.ToEntity(dto);
413        db.JobPermissions.InsertOnSubmit(entity);
414        db.SubmitChanges();
[8326]415      });
[6983]416    }
417
418    public void UpdateJobPermission(DT.JobPermission dto) {
[8326]419      ExecuteWithContext((db) => {
[6983]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();
[8326]424      });
[6983]425    }
426
427    public void DeleteJobPermission(Guid jobId, Guid grantedUserId) {
[8326]428      ExecuteWithContext((db) => {
[6983]429        var entity = db.JobPermissions.FirstOrDefault(x => x.JobId == jobId && x.GrantedUserId == grantedUserId);
430        if (entity != null) db.JobPermissions.DeleteOnSubmit(entity);
431        db.SubmitChanges();
[8326]432      });
[6983]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) {
[8326]439      ExecuteWithContext((db) => {
[6983]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);
[9363]445          } else {
[6983]446            // update
447            jobPermission.Permission = permission;
448            jobPermission.GrantedByUserId = grantedByUserId; // update grantedByUserId, always the last "granter" is stored
449          }
[9363]450        } else {
[6983]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();
[8326]458      });
[6983]459    }
460    #endregion
461
462    #region Plugin Methods
463    public DT.Plugin GetPlugin(Guid id) {
[8326]464      return ExecuteWithContext<DT.Plugin>((db) => {
[6983]465        return DT.Convert.ToDto(db.Plugins.SingleOrDefault(x => x.PluginId == id));
[8326]466      });
[6983]467    }
468
469    public IEnumerable<DT.Plugin> GetPlugins(Expression<Func<Plugin, bool>> predicate) {
[8326]470      return ExecuteWithContext<IEnumerable<DT.Plugin>>((db) => {
[6983]471        return db.Plugins.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]472      });
[6983]473    }
474
475    public Guid AddPlugin(DT.Plugin dto) {
[8326]476      return ExecuteWithContext<Guid>((db) => {
[6983]477        var entity = DT.Convert.ToEntity(dto);
478        db.Plugins.InsertOnSubmit(entity);
479        db.SubmitChanges();
480        return entity.PluginId;
[8326]481      });
[6983]482    }
483
484    public void UpdatePlugin(DT.Plugin dto) {
[8326]485      ExecuteWithContext((db) => {
[6983]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();
[8326]490      });
[6983]491    }
492
493    public void DeletePlugin(Guid id) {
[8326]494      ExecuteWithContext((db) => {
[6983]495        var entity = db.Plugins.FirstOrDefault(x => x.PluginId == id);
496        if (entity != null) db.Plugins.DeleteOnSubmit(entity);
497        db.SubmitChanges();
[8326]498      });
[6983]499    }
500    #endregion
501
502    #region PluginData Methods
503    public DT.PluginData GetPluginData(Guid id) {
[8326]504      return ExecuteWithContext<DT.PluginData>((db) => {
[6983]505        return DT.Convert.ToDto(db.PluginDatas.SingleOrDefault(x => x.PluginDataId == id));
[8326]506      });
[6983]507    }
508
509    public IEnumerable<DT.PluginData> GetPluginDatas(Expression<Func<PluginData, bool>> predicate) {
[9363]510      return ExecuteWithContext<IEnumerable<DT.PluginData>>((db) => {
[6983]511        return db.PluginDatas.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]512      });
[6983]513    }
514
515    public Guid AddPluginData(DT.PluginData dto) {
[8326]516      return ExecuteWithContext<Guid>((db) => {
[6983]517        var entity = DT.Convert.ToEntity(dto);
518        db.PluginDatas.InsertOnSubmit(entity);
519        db.SubmitChanges();
520        return entity.PluginDataId;
[8326]521      });
[6983]522    }
523
524    public void UpdatePluginData(DT.PluginData dto) {
[8326]525      ExecuteWithContext((db) => {
[6983]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();
[8326]530      });
[6983]531    }
532
533    public void DeletePluginData(Guid id) {
[8326]534      ExecuteWithContext((db) => {
[6983]535        var entity = db.PluginDatas.FirstOrDefault(x => x.PluginDataId == id);
536        if (entity != null) db.PluginDatas.DeleteOnSubmit(entity);
537        db.SubmitChanges();
[8326]538      });
[6983]539    }
540    #endregion
541
542    #region Slave Methods
543    public DT.Slave GetSlave(Guid id) {
[8326]544      return ExecuteWithContext<DT.Slave>((db) => {
[6983]545        return DT.Convert.ToDto(db.Resources.OfType<Slave>().SingleOrDefault(x => x.ResourceId == id));
[8326]546      });
[6983]547    }
548
549    public IEnumerable<DT.Slave> GetSlaves(Expression<Func<Slave, bool>> predicate) {
[8326]550      return ExecuteWithContext<IEnumerable<DT.Slave>>((db) => {
[6983]551        return db.Resources.OfType<Slave>().Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]552      });
[6983]553    }
554
555    public Guid AddSlave(DT.Slave dto) {
[8326]556      return ExecuteWithContext<Guid>((db) => {
[6983]557        var entity = DT.Convert.ToEntity(dto);
558        db.Resources.InsertOnSubmit(entity);
559        db.SubmitChanges();
560        return entity.ResourceId;
[8326]561      });
[6983]562    }
563
564    public void UpdateSlave(DT.Slave dto) {
[8326]565      ExecuteWithContext((db) => {
[6983]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();
[8326]570      });
[6983]571    }
572
573    public void DeleteSlave(Guid id) {
[8326]574      ExecuteWithContext((db) => {
[6983]575        var entity = db.Resources.OfType<Slave>().FirstOrDefault(x => x.ResourceId == id);
576        if (entity != null) db.Resources.DeleteOnSubmit(entity);
577        db.SubmitChanges();
[8326]578      });
[6983]579    }
580    #endregion
581
582    #region SlaveGroup Methods
583    public DT.SlaveGroup GetSlaveGroup(Guid id) {
[8326]584      return ExecuteWithContext<DT.SlaveGroup>((db) => {
[6983]585        return DT.Convert.ToDto(db.Resources.OfType<SlaveGroup>().SingleOrDefault(x => x.ResourceId == id));
[8326]586      });
[6983]587    }
588
589    public IEnumerable<DT.SlaveGroup> GetSlaveGroups(Expression<Func<SlaveGroup, bool>> predicate) {
[8326]590      return ExecuteWithContext<IEnumerable<DT.SlaveGroup>>((db) => {
[6983]591        return db.Resources.OfType<SlaveGroup>().Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]592      });
[6983]593    }
594
595    public Guid AddSlaveGroup(DT.SlaveGroup dto) {
[8326]596      return ExecuteWithContext<Guid>((db) => {
[6983]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;
[8326]603      });
[6983]604    }
605
606    public void UpdateSlaveGroup(DT.SlaveGroup dto) {
[8326]607      ExecuteWithContext((db) => {
[6983]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();
[8326]612      });
[6983]613    }
614
615    public void DeleteSlaveGroup(Guid id) {
[8326]616      ExecuteWithContext((db) => {
[6983]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();
[8326]625      });
[6983]626    }
627    #endregion
628
629    #region Resource Methods
630    public DT.Resource GetResource(Guid id) {
[8326]631      return ExecuteWithContext<DT.Resource>((db) => {
[6983]632        return DT.Convert.ToDto(db.Resources.SingleOrDefault(x => x.ResourceId == id));
[8326]633      });
[6983]634    }
635
636    public IEnumerable<DT.Resource> GetResources(Expression<Func<Resource, bool>> predicate) {
[8326]637      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
[6983]638        return db.Resources.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]639      });
[6983]640    }
641
642    public Guid AddResource(DT.Resource dto) {
[8326]643      return ExecuteWithContext<Guid>((db) => {
[6983]644        var entity = DT.Convert.ToEntity(dto);
645        db.Resources.InsertOnSubmit(entity);
646        db.SubmitChanges();
647        return entity.ResourceId;
[8326]648      });
[6983]649    }
650
651    public void UpdateResource(DT.Resource dto) {
[8326]652      ExecuteWithContext((db) => {
[6983]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();
[8326]657      });
[6983]658    }
659
660    public void DeleteResource(Guid id) {
[8326]661      ExecuteWithContext((db) => {
[6983]662        var entity = db.Resources.FirstOrDefault(x => x.ResourceId == id);
663        if (entity != null) db.Resources.DeleteOnSubmit(entity);
664        db.SubmitChanges();
[8326]665      });
[6983]666    }
667
[9363]668    public void AssignJobToResource(Guid taskId, IEnumerable<Guid> resourceIds) {
[8326]669      ExecuteWithContext((db) => {
[9363]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);
[6983]677        db.SubmitChanges();
[8326]678      });
[6983]679    }
680
681    public IEnumerable<DT.Resource> GetAssignedResources(Guid jobId) {
[9363]682      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
[6983]683        var job = db.Tasks.Where(x => x.TaskId == jobId).Single();
684        return job.AssignedResources.Select(x => DT.Convert.ToDto(x.Resource)).ToArray();
[8326]685      });
[6983]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) {
[8326]692      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
[6983]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();
[8326]696      });
[6983]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) {
[8326]709      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
[9363]710        return CollectChildResources(resourceId, db);
[8326]711      });
[6983]712    }
713
[9363]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
[6983]723    public IEnumerable<DT.Task> GetJobsByResourceId(Guid resourceId) {
[8326]724      return ExecuteWithContext<IEnumerable<DT.Task>>((db) => {
[6983]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();
[8326]733      });
[6983]734    }
735    #endregion
736
[7916]737    #region ResourcePermission Methods
738    public DT.ResourcePermission GetResourcePermission(Guid resourceId, Guid grantedUserId) {
[9363]739      return ExecuteWithContext<DT.ResourcePermission>((db) => {
[7916]740        return DT.Convert.ToDto(db.ResourcePermissions.SingleOrDefault(x => x.ResourceId == resourceId && x.GrantedUserId == grantedUserId));
[8326]741      });
[7916]742    }
743
744    public IEnumerable<DT.ResourcePermission> GetResourcePermissions(Expression<Func<ResourcePermission, bool>> predicate) {
[8326]745      return ExecuteWithContext<IEnumerable<DT.ResourcePermission>>((db) => {
[7916]746        return db.ResourcePermissions.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]747      });
[7916]748    }
749
750    public void AddResourcePermission(DT.ResourcePermission dto) {
[8326]751      ExecuteWithContext((db) => {
[7916]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(); }
[8326]754      });
[7916]755    }
756
757    public void UpdateResourcePermission(DT.ResourcePermission dto) {
[8326]758      ExecuteWithContext((db) => {
[7916]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();
[8326]763      });
[7916]764    }
765
766    public void DeleteResourcePermission(Guid resourceId, Guid grantedUserId) {
[8326]767      ExecuteWithContext((db) => {
[7916]768        var entity = db.ResourcePermissions.FirstOrDefault(x => x.ResourceId == resourceId && x.GrantedUserId == grantedUserId);
769        if (entity != null) db.ResourcePermissions.DeleteOnSubmit(entity);
770        db.SubmitChanges();
[8326]771      });
[7916]772    }
773    #endregion
774
[6983]775    #region Authorization Methods
776    public Permission GetPermissionForTask(Guid taskId, Guid userId) {
[8326]777      return ExecuteWithContext<Permission>((db) => {
[6983]778        return GetPermissionForJob(GetJobForTask(taskId), userId);
[8326]779      });
[6983]780    }
781
782    public Permission GetPermissionForJob(Guid jobId, Guid userId) {
[8326]783      return ExecuteWithContext<Permission>((db) => {
[6983]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;
[8326]789      });
[6983]790    }
791
792    public Guid GetJobForTask(Guid taskId) {
[8326]793      return ExecuteWithContext<Guid>((db) => {
[6983]794        return db.Tasks.Single(j => j.TaskId == taskId).JobId;
[8326]795      });
[6983]796    }
797    #endregion
798
799    #region Lifecycle Methods
800    public DateTime GetLastCleanup() {
[8326]801      return ExecuteWithContext<DateTime>((db) => {
[6983]802        var entity = db.Lifecycles.SingleOrDefault();
803        return entity != null ? entity.LastCleanup : DateTime.MinValue;
[8326]804      });
[6983]805    }
806
807    public void SetLastCleanup(DateTime datetime) {
[8326]808      ExecuteWithContext((db) => {
[6983]809        var entity = db.Lifecycles.SingleOrDefault();
810        if (entity != null) {
811          entity.LastCleanup = datetime;
[9363]812        } else {
[6983]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();
[8326]819      });
[6983]820    }
821    #endregion
822
823    #region Downtime Methods
824    public DT.Downtime GetDowntime(Guid id) {
[8326]825      return ExecuteWithContext<DT.Downtime>((db) => {
[6983]826        return DT.Convert.ToDto(db.Downtimes.SingleOrDefault(x => x.DowntimeId == id));
[8326]827      });
[6983]828    }
829
830    public IEnumerable<DT.Downtime> GetDowntimes(Expression<Func<Downtime, bool>> predicate) {
[8326]831      return ExecuteWithContext<IEnumerable<DT.Downtime>>((db) => {
[6983]832        return db.Downtimes.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]833      });
[6983]834    }
835
836    public Guid AddDowntime(DT.Downtime dto) {
[8326]837      return ExecuteWithContext<Guid>((db) => {
[6983]838        var entity = DT.Convert.ToEntity(dto);
839        db.Downtimes.InsertOnSubmit(entity);
840        db.SubmitChanges();
841        return entity.DowntimeId;
[8326]842      });
[6983]843    }
844
845    public void UpdateDowntime(DT.Downtime dto) {
[8326]846      ExecuteWithContext((db) => {
[6983]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();
[8326]851      });
[6983]852    }
853
854    public void DeleteDowntime(Guid id) {
[8326]855      ExecuteWithContext((db) => {
[6983]856        var entity = db.Downtimes.FirstOrDefault(x => x.DowntimeId == id);
857        if (entity != null) db.Downtimes.DeleteOnSubmit(entity);
858        db.SubmitChanges();
[8326]859      });
[6983]860    }
861    #endregion
862
863    #region Statistics Methods
864    public DT.Statistics GetStatistic(Guid id) {
[8326]865      return ExecuteWithContext<DT.Statistics>((db) => {
[6983]866        return DT.Convert.ToDto(db.Statistics.SingleOrDefault(x => x.StatisticsId == id));
[8326]867      });
[6983]868    }
869
870    public IEnumerable<DT.Statistics> GetStatistics(Expression<Func<Statistics, bool>> predicate) {
[8326]871      return ExecuteWithContext<IEnumerable<DT.Statistics>>((db) => {
[6983]872        return db.Statistics.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
[8326]873      });
[6983]874    }
875
876    public Guid AddStatistics(DT.Statistics dto) {
[8326]877      return ExecuteWithContext<Guid>((db) => {
[6983]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;
[8326]893      });
[6983]894    }
895
896    public void DeleteStatistics(Guid id) {
[8326]897      ExecuteWithContext((db) => {
[6983]898        var entity = db.Statistics.FirstOrDefault(x => x.StatisticsId == id);
899        if (entity != null) db.Statistics.DeleteOnSubmit(entity);
900        db.SubmitChanges();
[8326]901      });
[6983]902    }
903
[9363]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
[6983]944    public List<DT.UserStatistics> GetUserStatistics() {
[8326]945      return ExecuteWithContext<List<DT.UserStatistics>>((db) => {
[6983]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();
[8326]1017      });
[6983]1018    }
1019    #endregion
1020
[9363]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
[6983]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.