Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
04/16/13 13:13:41 (12 years ago)
Author:
spimming
Message:

#1888:

  • Merged revisions from trunk
Location:
branches/OaaS
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • branches/OaaS

  • branches/OaaS/HeuristicLab.Services.Hive

    • Property svn:mergeinfo set to (toggle deleted branches)
      /trunk/sources/HeuristicLab.Services.Hivemergedeligible
      /branches/Algorithms.GradientDescent/HeuristicLab.Services.Hive5516-5520
      /branches/Benchmarking/sources/HeuristicLab.Services.Hive6917-7005
      /branches/CloningRefactoring/HeuristicLab.Services.Hive4656-4721
      /branches/DataAnalysis Refactoring/HeuristicLab.Services.Hive5471-5808
      /branches/DataAnalysis SolutionEnsembles/HeuristicLab.Services.Hive5815-6180
      /branches/DataAnalysis/HeuristicLab.Services.Hive4458-4459,​4462,​4464
      /branches/GP.Grammar.Editor/HeuristicLab.Services.Hive6284-6795
      /branches/GP.Symbols (TimeLag, Diff, Integral)/HeuristicLab.Services.Hive5060
      /branches/HiveTaskScheduler/HeuristicLab.Services.Hive8687-9106
      /branches/NET40/sources/HeuristicLab.Services.Hive5138-5162
      /branches/ParallelEngine/HeuristicLab.Services.Hive5175-5192
      /branches/ProblemInstancesRegressionAndClassification/HeuristicLab.Services.Hive7568-7810
      /branches/QAPAlgorithms/HeuristicLab.Services.Hive6350-6627
      /branches/Restructure trunk solution/HeuristicLab.Services.Hive6828
      /branches/RuntimeOptimizer/HeuristicLab.Services.Hive8943-9078
      /branches/ScatterSearch (trunk integration)/HeuristicLab.Services.Hive7787-8333
      /branches/SlaveShutdown/HeuristicLab.Services.Hive8944-8956
      /branches/SuccessProgressAnalysis/HeuristicLab.Services.Hive5370-5682
      /branches/Trunk/HeuristicLab.Services.Hive6829-6865
      /branches/UnloadJobs/HeuristicLab.Services.Hive9168-9215
      /branches/VNS/HeuristicLab.Services.Hive5594-5752
      /branches/histogram/HeuristicLab.Services.Hive5959-6341
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveDao.cs

    r9215 r9363  
    2222using System;
    2323using System.Collections.Generic;
     24using System.Configuration;
     25using System.Data.Common;
    2426using System.Linq;
    2527using System.Linq.Expressions;
     28using HeuristicLab.Services.Hive.Interfaces;
    2629using DT = HeuristicLab.Services.Hive.DataTransfer;
    27 using System.ServiceModel;
    28 using HeuristicLab.Services.Hive.Interfaces;
    29 using System.Data.Common;
    30 using System.Configuration;
    3130
    3231namespace HeuristicLab.Services.Hive.DataAccess {
    3332  public class HiveDao : IHiveDao {
    34    
     33
    3534    public HiveDataContext CreateContext(bool longRunning = false) {
    3635      //var context = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
     
    3837      if (ConfigurationManager.ConnectionStrings[Settings.Default.HiveConnectionStringName] == null) {
    3938        context = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
    40       }
    41       else {
     39      } else {
    4240        context = new HiveDataContext(provider.GetOpenConnection(Settings.Default.HiveConnectionStringName));
    4341      }
     
    9391    }
    9492
     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
    95137    public Guid AddTask(DT.Task dto) {
    96138      return ExecuteWithContext<Guid>((db) => {
     
    106148    }
    107149
    108     public void UpdateTask(DT.Task dto) {
     150    public void UpdateTaskAndPlugins(DT.Task dto) {
    109151      ExecuteWithContext((db) => {
    110152        var entity = db.Tasks.FirstOrDefault(x => x.TaskId == dto.Id);
     
    118160        db.SubmitChanges();
    119161      });
     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      }
    120182    }
    121183
     
    156218    }
    157219
    158     public IEnumerable<DT.Task> GetWaitingTasks(DT.Slave slave, int count) {
    159       return ExecuteWithContext<IEnumerable<DT.Task>>((db) => {
     220    public IEnumerable<TaskInfoForScheduler> GetWaitingTasks(DT.Slave slave) {
     221      return ExecuteWithContext<IEnumerable<TaskInfoForScheduler>>((db) => {
    160222        var resourceIds = GetParentResources(slave.Id).Select(r => r.Id);
    161223        //Originally we checked here if there are parent tasks which should be calculated (with GetParentTasks(resourceIds, count, false);).
     
    169231                       && ar.Task.CoresNeeded <= slave.FreeCores
    170232                       && ar.Task.MemoryNeeded <= slave.FreeMemory
    171                     orderby ar.Task.Priority descending, db.Random() // take random task to avoid the race condition that occurs when this method is called concurrently (the same task would be returned)
    172                     select DT.Convert.ToDto(ar.Task);
    173         var waitingTasks = (count == 0 ? query : query.Take(count)).ToArray();
     233                    select new TaskInfoForScheduler() { TaskId = ar.Task.TaskId, JobId = ar.Task.JobId, Priority = ar.Task.Priority };
     234        var waitingTasks = query.ToArray();
    174235        return waitingTasks;
    175236      });
     
    178239    public DT.Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
    179240      return ExecuteWithContext<DT.Task>((db) => {
    180         var job = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
    181         job.State = taskState;
     241        db.DeferredLoadingEnabled = false;
     242        var task = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
     243        task.State = taskState;
    182244        db.StateLogs.InsertOnSubmit(new StateLog {
    183245          TaskId = taskId,
     
    189251        });
    190252        db.SubmitChanges();
    191         job = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
    192         return DT.Convert.ToDto(job);
     253        task = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
     254        return DT.Convert.ToDto(task);
    193255      });
    194256    }
     
    299361    }
    300362
     363    public IEnumerable<JobInfoForScheduler> GetJobInfoForScheduler(Expression<Func<Job, bool>> predicate) {
     364      using (var db = CreateContext()) {
     365        return db.Jobs.Where(predicate).Select(x => new JobInfoForScheduler() { Id = x.JobId, DateCreated = x.DateCreated, OwnerUserId = x.OwnerUserId }).ToArray();
     366      }
     367    }
     368
    301369    public Guid AddJob(DT.Job dto) {
    302370      return ExecuteWithContext<Guid>((db) => {
    303371        var entity = DT.Convert.ToEntity(dto);
    304372        db.Jobs.InsertOnSubmit(entity);
     373        if (!db.UserPriorities.Any(x => x.UserId == dto.OwnerUserId))
     374          EnqueueUserPriority(new DT.UserPriority { Id = dto.OwnerUserId, DateEnqueued = dto.DateCreated });
    305375        db.SubmitChanges();
    306376        return entity.JobId;
     
    374444            // not allowed, delete
    375445            db.JobPermissions.DeleteOnSubmit(jobPermission);
    376           }
    377           else {
     446          } else {
    378447            // update
    379448            jobPermission.Permission = permission;
    380449            jobPermission.GrantedByUserId = grantedByUserId; // update grantedByUserId, always the last "granter" is stored
    381450          }
    382         }
    383         else {
     451        } else {
    384452          // insert
    385453          if (permission != Permission.NotAllowed) {
     
    441509
    442510    public IEnumerable<DT.PluginData> GetPluginDatas(Expression<Func<PluginData, bool>> predicate) {
    443       return ExecuteWithContext <IEnumerable<DT.PluginData>>((db) => {
     511      return ExecuteWithContext<IEnumerable<DT.PluginData>>((db) => {
    444512        return db.PluginDatas.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
    445513      });
     
    599667    }
    600668
    601     public void AssignJobToResource(Guid jobId, Guid resourceId) {
    602       ExecuteWithContext((db) => {
    603         var job = db.Tasks.Where(x => x.TaskId == jobId).Single();
    604         job.AssignedResources.Add(new AssignedResource() { TaskId = jobId, ResourceId = resourceId });
     669    public void AssignJobToResource(Guid taskId, IEnumerable<Guid> resourceIds) {
     670      ExecuteWithContext((db) => {
     671        db.DeferredLoadingEnabled = false;
     672
     673        List<AssignedResource> assignedResources = new List<AssignedResource>();
     674        foreach (Guid rId in resourceIds) {
     675          assignedResources.Add(new AssignedResource() { TaskId = taskId, ResourceId = rId });
     676        }
     677        db.AssignedResources.InsertAllOnSubmit(assignedResources);
    605678        db.SubmitChanges();
    606679      });
     
    608681
    609682    public IEnumerable<DT.Resource> GetAssignedResources(Guid jobId) {
    610       return ExecuteWithContext <IEnumerable<DT.Resource>>((db) => {
     683      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
    611684        var job = db.Tasks.Where(x => x.TaskId == jobId).Single();
    612685        return job.AssignedResources.Select(x => DT.Convert.ToDto(x.Resource)).ToArray();
     
    636709    public IEnumerable<DT.Resource> GetChildResources(Guid resourceId) {
    637710      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
    638         var childs = new List<DT.Resource>();
    639         foreach (var child in db.Resources.Where(x => x.ParentResourceId == resourceId)) {
    640           childs.Add(DT.Convert.ToDto(child));
    641           childs.AddRange(GetChildResources(child.ResourceId));
    642         }
    643         return childs;
    644       });
     711        return CollectChildResources(resourceId, db);
     712      });
     713    }
     714
     715    public IEnumerable<DT.Resource> CollectChildResources(Guid resourceId, HiveDataContext db) {
     716      var childs = new List<DT.Resource>();
     717      foreach (var child in db.Resources.Where(x => x.ParentResourceId == resourceId)) {
     718        childs.Add(DT.Convert.ToDto(child));
     719        childs.AddRange(CollectChildResources(child.ResourceId, db));
     720      }
     721      return childs;
    645722    }
    646723
     
    661738    #region ResourcePermission Methods
    662739    public DT.ResourcePermission GetResourcePermission(Guid resourceId, Guid grantedUserId) {
    663       return ExecuteWithContext <DT.ResourcePermission> ((db) => {
     740      return ExecuteWithContext<DT.ResourcePermission>((db) => {
    664741        return DT.Convert.ToDto(db.ResourcePermissions.SingleOrDefault(x => x.ResourceId == resourceId && x.GrantedUserId == grantedUserId));
    665742      });
     
    734811        if (entity != null) {
    735812          entity.LastCleanup = datetime;
    736         }
    737         else {
     813        } else {
    738814          entity = new Lifecycle();
    739815          entity.LifecycleId = 0; // always only one entry with ID:0
     
    825901        db.SubmitChanges();
    826902      });
     903    }
     904
     905    public Dictionary<Guid, int> GetWaitingTasksByUser() {
     906      using (var db = CreateContext()) {
     907        var waitingTasksByUser = from task in db.Tasks
     908                                 where task.State == TaskState.Waiting
     909                                 group task by task.Job.OwnerUserId into g
     910                                 select new { UserId = g.Key, UsedCores = g.Count() };
     911        return waitingTasksByUser.ToDictionary(x => x.UserId, x => x.UsedCores);
     912      }
     913    }
     914
     915    public Dictionary<Guid, int> GetWaitingTasksByUserForResources(List<Guid> resourceIds) {
     916      using (var db = CreateContext()) {
     917        var waitingTasksByUser = from task in db.Tasks
     918                                 where task.State == TaskState.Waiting && task.AssignedResources.Any(x => resourceIds.Contains(x.ResourceId))
     919                                 group task by task.Job.OwnerUserId into g
     920                                 select new { UserId = g.Key, UsedCores = g.Count() };
     921        return waitingTasksByUser.ToDictionary(x => x.UserId, x => x.UsedCores);
     922      }
     923    }
     924
     925    public Dictionary<Guid, int> GetCalculatingTasksByUser() {
     926      using (var db = CreateContext()) {
     927        var calculatingTasksByUser = from task in db.Tasks
     928                                     where task.State == TaskState.Calculating
     929                                     group task by task.Job.OwnerUserId into g
     930                                     select new { UserId = g.Key, UsedCores = g.Count() };
     931        return calculatingTasksByUser.ToDictionary(x => x.UserId, x => x.UsedCores);
     932      }
     933    }
     934
     935    public Dictionary<Guid, int> GetCalculatingTasksByUserForResources(List<Guid> resourceIds) {
     936      using (var db = CreateContext()) {
     937        var calculatingTasksByUser = from task in db.Tasks
     938                                     where task.State == TaskState.Calculating && task.AssignedResources.Any(x => resourceIds.Contains(x.ResourceId))
     939                                     group task by task.Job.OwnerUserId into g
     940                                     select new { UserId = g.Key, UsedCores = g.Count() };
     941        return calculatingTasksByUser.ToDictionary(x => x.UserId, x => x.UsedCores);
     942      }
    827943    }
    828944
     
    9041020    #endregion
    9051021
     1022    #region UserPriority Methods
     1023    public IEnumerable<DT.UserPriority> GetUserPriorities(Expression<Func<UserPriority, bool>> predicate) {
     1024      using (var db = CreateContext()) {
     1025        return db.UserPriorities.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
     1026      }
     1027    }
     1028
     1029    public void EnqueueUserPriority(DT.UserPriority dto) {
     1030      using (var db = CreateContext()) {
     1031        var entity = db.UserPriorities.FirstOrDefault(x => x.UserId == dto.Id);
     1032        if (entity == null) db.UserPriorities.InsertOnSubmit(DT.Convert.ToEntity(dto));
     1033        else DT.Convert.ToEntity(dto, entity);
     1034        db.SubmitChanges();
     1035      }
     1036    }
     1037    #endregion
     1038
    9061039    #region Helpers
    9071040    private void CollectChildTasks(HiveDataContext db, Guid parentTaskId, List<Task> collection) {
Note: See TracChangeset for help on using the changeset viewer.