Free cookie consent management tool by TermsFeed Policy Generator

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

#1888:

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

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/Convert.cs

    r7916 r9363  
    7979      }
    8080    }
     81
     82    public static void ToEntityTaskOnly(DT.Task source, DB.Task target) {
     83      if ((source != null) && (target != null)) {
     84        target.TaskId = source.Id;
     85        target.CoresNeeded = source.CoresNeeded;
     86        target.ExecutionTimeMs = source.ExecutionTime.TotalMilliseconds;
     87        target.MemoryNeeded = source.MemoryNeeded;
     88        target.ParentTaskId = source.ParentTaskId;
     89        target.Priority = source.Priority;
     90        target.LastHeartbeat = source.LastHeartbeat;
     91        target.State = Convert.ToEntity(source.State);
     92        target.IsParentTask = source.IsParentTask;
     93        target.FinishWhenChildJobsFinished = source.FinishWhenChildJobsFinished;
     94        target.Command = Convert.ToEntity(source.Command);
     95        // RequiredPlugins are added by Dao
     96        target.JobId = source.JobId;
     97        target.IsPrivileged = source.IsPrivileged;
     98      }
     99    }
    81100    #endregion
    82101
     
    118137    public static DT.Downtime ToDto(DB.Downtime source) {
    119138      if (source == null) return null;
    120       return new DT.Downtime { Id = source.DowntimeId, AllDayEvent = source.AllDayEvent, EndDate = source.EndDate, Recurring = source.Recurring, RecurringId = source.RecurringId, ResourceId = source.ResourceId, StartDate = source.StartDate };
     139      return new DT.Downtime { Id = source.DowntimeId, AllDayEvent = source.AllDayEvent, EndDate = source.EndDate, Recurring = source.Recurring, RecurringId = source.RecurringId, ResourceId = source.ResourceId, StartDate = source.StartDate, DowntimeType = source.DowntimeType };
    121140    }
    122141    public static DB.Downtime ToEntity(DT.Downtime source) {
     
    127146    public static void ToEntity(DT.Downtime source, DB.Downtime target) {
    128147      if ((source != null) && (target != null)) {
    129         target.DowntimeId = source.Id; target.AllDayEvent = source.AllDayEvent; target.EndDate = source.EndDate; target.Recurring = source.Recurring; target.RecurringId = source.RecurringId; target.ResourceId = source.ResourceId; target.StartDate = source.StartDate;
     148        target.DowntimeId = source.Id; target.AllDayEvent = source.AllDayEvent; target.EndDate = source.EndDate; target.Recurring = source.Recurring; target.RecurringId = source.RecurringId; target.ResourceId = source.ResourceId; target.StartDate = source.StartDate; target.DowntimeType = source.DowntimeType;
    130149      }
    131150    }
     
    527546    }
    528547    #endregion
     548
     549    #region UserPriority
     550    public static DT.UserPriority ToDto(DB.UserPriority source) {
     551      if (source == null) return null;
     552      return new DT.UserPriority() { Id = source.UserId, DateEnqueued = source.DateEnqueued };
     553    }
     554    public static DB.UserPriority ToEntity(DT.UserPriority source) {
     555      if (source == null) return null;
     556      var entity = new DB.UserPriority(); ToEntity(source, entity);
     557      return entity;
     558    }
     559    public static void ToEntity(DT.UserPriority source, DB.UserPriority target) {
     560      if ((source != null) && (target != null)) {
     561        target.UserId = source.Id;
     562        target.DateEnqueued = source.DateEnqueued;
     563      }
     564    }
     565    #endregion
    529566  }
    530567}
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/DataTransfer/Downtime.cs

    r7259 r9363  
    2222using System;
    2323using System.Runtime.Serialization;
     24using HeuristicLab.Services.Hive.DataAccess;
    2425
    2526namespace HeuristicLab.Services.Hive.DataTransfer {
     
    3839    [DataMember]
    3940    public Guid ResourceId { get; set; }
     41    [DataMember]
     42    public DowntimeType DowntimeType { get; set; }
    4043  }
    4144}
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/HeuristicLab.Services.Hive-3.3.csproj

    r8326 r9363  
    116116    <Compile Include="Convert.cs" />
    117117    <Compile Include="DataTransfer\Command.cs" />
     118    <Compile Include="DataTransfer\UserPriority.cs" />
    118119    <Compile Include="DataTransfer\ResourcePermission.cs" />
    119120    <Compile Include="DataTransfer\Downtime.cs" />
     
    142143    <Compile Include="Interfaces\IConnectionProvider.cs" />
    143144    <Compile Include="Interfaces\IHiveDao.cs" />
     145    <Compile Include="Interfaces\ITaskScheduler.cs" />
     146    <Compile Include="Scheduler\TaskInfoForScheduler.cs" />
     147    <Compile Include="Scheduler\JobInfoForScheduler.cs" />
     148    <Compile Include="Scheduler\RoundRobinTaskScheduler.cs" />
    144149    <Compile Include="Settings.cs" />
    145150    <None Include="app.config" />
     
    199204  </PropertyGroup>
    200205  <PropertyGroup>
    201     <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
     206    <PreBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
    202207set ProjectDir=$(ProjectDir)
    203208set SolutionDir=$(SolutionDir)
     
    205210
    206211call PreBuildEvent.cmd</PreBuildEvent>
     212    <PreBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
     213export ProjectDir=$(ProjectDir)
     214export SolutionDir=$(SolutionDir)
     215
     216$SolutionDir/PreBuildEvent.sh
     217</PreBuildEvent>
    207218  </PropertyGroup>
    208219  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
  • 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) {
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveService.cs

    r8506 r9363  
    2424using System.Linq;
    2525using System.ServiceModel;
     26using System.Transactions;
    2627using HeuristicLab.Services.Hive.DataTransfer;
    2728using HeuristicLab.Services.Hive.ServiceContracts;
    2829using DA = HeuristicLab.Services.Hive.DataAccess;
    2930using DT = HeuristicLab.Services.Hive.DataTransfer;
    30 using System.Transactions;
    3131
    3232
     
    6969        taskData.TaskId = task.Id;
    7070        taskData.LastUpdate = DateTime.Now;
    71         foreach (Guid slaveGroupId in resourceIds) {
    72           dao.AssignJobToResource(task.Id, slaveGroupId);
    73         }
     71        dao.AssignJobToResource(task.Id, resourceIds);
    7472        dao.AddTaskData(taskData);
    7573        dao.UpdateTaskState(task.Id, DA.TaskState.Waiting, null, currentUserId, null);
     
    8280      var assignedResources = dao.GetAssignedResources(parentTaskId).Select(x => x.Id);
    8381      task.ParentTaskId = parentTaskId;
    84       return AddTask(task, taskData, assignedResources);     
     82      return AddTask(task, taskData, assignedResources);
    8583    }
    8684
     
    132130
    133131      return trans.UseTransaction(() => {
    134         return dao.GetTasks(x => x.JobId == jobId).Select(x => new LightweightTask(x)).ToArray();
     132        return dao.GetLightweightTasks(task => task.JobId == jobId).ToArray();
     133      }, false, true);
     134    }
     135
     136    public IEnumerable<LightweightTask> GetLightweightJobTasksWithoutStateLog(Guid jobId) {
     137      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     138      author.AuthorizeForJob(jobId, Permission.Read);
     139
     140      return trans.UseTransaction(() => {
     141        return dao.GetLightweightTasksWithoutStateLog(task => task.JobId == jobId).ToArray();
    135142      }, false, false);
    136143    }
     
    145152      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    146153      author.AuthorizeForTask(taskDto.Id, Permission.Full);
    147       trans.UseTransaction(() => {
    148         dao.UpdateTask(taskDto);
     154
     155      trans.UseTransaction(() => {
     156        dao.UpdateTaskAndPlugins(taskDto);
    149157      });
    150158    }
     
    153161      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    154162      author.AuthorizeForTask(task.Id, Permission.Full);
    155       author.AuthorizeForTask(taskData.TaskId, Permission.Full);
    156       //trans.UseTransaction(() => { // cneumuel: try without transaction
     163      dao.UpdateTaskAndPlugins(task);
    157164      taskData.LastUpdate = DateTime.Now;
    158       dao.UpdateTask(task);
    159165      dao.UpdateTaskData(taskData);
    160       //}, false, true);
    161166    }
    162167
     
    200205        }
    201206
    202         dao.UpdateTask(task);
     207        dao.UpdateTaskAndPlugins(task);
    203208        return task;
    204209      });
     
    412417      authen.AuthenticateForAnyRole(HiveRoles.Slave);
    413418
    414       //TODO: enable transaction
    415       //List<MessageContainer> result = trans.UseTransaction(() => heartbeatManager.ProcessHeartbeat(heartbeat));
    416       List<MessageContainer> result = heartbeatManager.ProcessHeartbeat(heartbeat);
     419      List<MessageContainer> result = new List<MessageContainer>();
     420      try {
     421        result = heartbeatManager.ProcessHeartbeat(heartbeat);
     422      }
     423      catch (Exception ex) {
     424        DA.LogFactory.GetLogger(this.GetType().Namespace).Log("Exception processing Heartbeat: " + ex.ToString());
     425      }
    417426
    418427      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
     
    517526    #endregion
    518527
     528    #region Resource Methods
     529    public IEnumerable<Resource> GetChildResources(Guid resourceId) {
     530      return trans.UseTransaction(() => { return dao.GetChildResources(resourceId); });
     531    }
     532    #endregion
     533
    519534    #region Slave Methods
    520535    public int GetNewHeartbeatInterval(Guid slaveId) {
    521536      authen.AuthenticateForAnyRole(HiveRoles.Slave);
    522       Slave s = dao.GetSlave(slaveId);
     537
     538      Slave s = trans.UseTransaction(() => { return dao.GetSlave(slaveId); });
    523539      if (s != null) {
    524540        return s.HbInterval;
     
    689705    #endregion
    690706
     707    #region UserPriority Methods
     708    public IEnumerable<UserPriority> GetUserPriorities() {
     709      return trans.UseTransaction(() => dao.GetUserPriorities(x => true));
     710    }
     711    #endregion
     712
    691713    #region Helper Methods
    692714    private IEnumerable<Task> GetChildTasks(Guid? parentTaskId, bool recursive, bool includeParent) {
     
    705727    }
    706728    #endregion
     729
     730    #region Statistics Methods
     731    public IEnumerable<Statistics> GetStatistics() {
     732      return trans.UseTransaction(() => { return dao.GetStatistics(x => true); });
     733    }
     734    public IEnumerable<Statistics> GetStatisticsForTimePeriod(DateTime from, DateTime to) {
     735      return trans.UseTransaction(() => { return dao.GetStatistics(x => x.Timestamp >= from && x.Timestamp <= to); });
     736    }
     737    #endregion
    707738  }
    708739}
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/Interfaces/IHiveDao.cs

    r7916 r9363  
    3131    DT.Task GetTask(Guid id);
    3232    IEnumerable<DT.Task> GetTasks(Expression<Func<Task, bool>> predicate);
     33    IEnumerable<DT.LightweightTask> GetLightweightTasks(Expression<Func<Task, bool>> predicate);
     34    IEnumerable<DT.LightweightTask> GetLightweightTasksWithoutStateLog(Expression<Func<Task, bool>> predicate);
    3335    Guid AddTask(DT.Task dto);
     36    void UpdateTaskAndPlugins(DT.Task dto);
     37    void UpdateTaskAndStateLogs(DT.Task dto);
    3438    void UpdateTask(DT.Task dto);
    3539    void DeleteTask(Guid id);
    36     IEnumerable<DT.Task> GetWaitingTasks(DT.Slave slave, int count);
     40    IEnumerable<TaskInfoForScheduler> GetWaitingTasks(DT.Slave slave);
    3741    IEnumerable<DT.Task> GetParentTasks(IEnumerable<Guid> resourceIds, int count, bool finished);
    3842    DT.Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception);
     
    5862    DT.Job GetJob(Guid id);
    5963    IEnumerable<DT.Job> GetJobs(Expression<Func<Job, bool>> predicate);
     64    IEnumerable<JobInfoForScheduler> GetJobInfoForScheduler(Expression<Func<Job, bool>> predicate);
    6065    Guid AddJob(DT.Job dto);
    6166    void UpdateJob(DT.Job dto);
     
    110115    void UpdateResource(DT.Resource dto);
    111116    void DeleteResource(Guid id);
    112     void AssignJobToResource(Guid jobId, Guid resourceId);
     117    void AssignJobToResource(Guid taskId, IEnumerable<Guid> resourceIds);
    113118    IEnumerable<DT.Resource> GetAssignedResources(Guid jobId);
    114119    IEnumerable<DT.Resource> GetParentResources(Guid resourceId);
     
    145150
    146151    #region Statistics Methods
     152    Dictionary<Guid, int> GetWaitingTasksByUser();
     153    Dictionary<Guid, int> GetWaitingTasksByUserForResources(List<Guid> resourceIds);
     154    Dictionary<Guid, int> GetCalculatingTasksByUser();
     155    Dictionary<Guid, int> GetCalculatingTasksByUserForResources(List<Guid> resourceIds);
    147156    DT.Statistics GetStatistic(Guid id);
    148157    IEnumerable<DT.Statistics> GetStatistics(Expression<Func<Statistics, bool>> predicate);
     
    151160    List<DT.UserStatistics> GetUserStatistics();
    152161    #endregion
     162
     163    #region UserPriority Methods
     164    IEnumerable<DT.UserPriority> GetUserPriorities(Expression<Func<UserPriority, bool>> predicate);
     165    void EnqueueUserPriority(DT.UserPriority userPriority);
     166    #endregion
    153167  }
    154168}
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/Interfaces/IServiceLocator.cs

    r8051 r9363  
    3131    Access.IUserManager UserManager { get; }
    3232    HeartbeatManager HeartbeatManager { get; }
     33    ITaskScheduler TaskScheduler { get; }
    3334  }
    3435}
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/Manager/HeartbeatManager.cs

    r7723 r9363  
    2323using System.Collections.Generic;
    2424using System.Linq;
     25using System.Threading;
    2526using HeuristicLab.Services.Hive.DataTransfer;
    2627using DA = HeuristicLab.Services.Hive.DataAccess;
     
    2829namespace HeuristicLab.Services.Hive {
    2930  public class HeartbeatManager {
     31    private const string MutexName = "HiveTaskSchedulingMutex";
     32
    3033    private IHiveDao dao {
    3134      get { return ServiceLocator.Instance.HiveDao; }
    3235    }
    33     private IAuthorizationManager auth {
    34       get { return ServiceLocator.Instance.AuthorizationManager; }
     36    private ITaskScheduler taskScheduler {
     37      get { return ServiceLocator.Instance.TaskScheduler; }
     38    }
     39    private DataAccess.ITransactionManager trans {
     40      get { return ServiceLocator.Instance.TransactionManager; }
    3541    }
    3642
     
    4147    public List<MessageContainer> ProcessHeartbeat(Heartbeat heartbeat) {
    4248      List<MessageContainer> actions = new List<MessageContainer>();
    43       Slave slave = dao.GetSlave(heartbeat.SlaveId);
     49      Slave slave = null;
     50      slave = trans.UseTransaction(() => { return dao.GetSlave(heartbeat.SlaveId); });
     51
    4452      if (slave == null) {
    4553        actions.Add(new MessageContainer(MessageContainer.MessageType.SayHello));
     
    4755        if (heartbeat.HbInterval != slave.HbInterval) {
    4856          actions.Add(new MessageContainer(MessageContainer.MessageType.NewHBInterval));
     57        }
     58        if (ShutdownSlaveComputer(slave.Id)) {
     59          actions.Add(new MessageContainer(MessageContainer.MessageType.ShutdownComputer));
    4960        }
    5061
     
    5667        slave.SlaveState = (heartbeat.JobProgress != null && heartbeat.JobProgress.Count > 0) ? SlaveState.Calculating : SlaveState.Idle;
    5768        slave.LastHeartbeat = DateTime.Now;
    58         dao.UpdateSlave(slave);
     69
     70        trans.UseTransaction(() => { dao.UpdateSlave(slave); });
    5971
    6072        // update task data
     
    6375        // assign new task
    6476        if (heartbeat.AssignJob && slave.IsAllowedToCalculate && heartbeat.FreeCores > 0) {
    65           var availableJobs = dao.GetWaitingTasks(slave, 1);
    66           if (availableJobs.Count() > 0) {
    67             var job = availableJobs.First();
    68             if (AssignJob(slave, job))
    69               actions.Add(new MessageContainer(MessageContainer.MessageType.CalculateTask, job.Id));
     77          bool mutexAquired = false;
     78          var mutex = new Mutex(false, MutexName);
     79          try {
     80            mutexAquired = mutex.WaitOne(Properties.Settings.Default.SchedulingPatience);
     81            if (!mutexAquired)
     82              DA.LogFactory.GetLogger(this.GetType().Namespace).Log("HeartbeatManager: The mutex used for scheduling could not be aquired.");
     83            else {
     84              IEnumerable<TaskInfoForScheduler> availableTasks = null;
     85              availableTasks = trans.UseTransaction(() => { return taskScheduler.Schedule(dao.GetWaitingTasks(slave)); });
     86              if (availableTasks.Any()) {
     87                var task = availableTasks.First();
     88                AssignJob(slave, task.TaskId);
     89                actions.Add(new MessageContainer(MessageContainer.MessageType.CalculateTask, task.TaskId));
     90              }
     91            }
     92          }
     93          catch (AbandonedMutexException) {
     94            DA.LogFactory.GetLogger(this.GetType().Namespace).Log("HeartbeatManager: The mutex used for scheduling has been abandoned.");
     95          }
     96          catch (Exception ex) {
     97            DA.LogFactory.GetLogger(this.GetType().Namespace).Log("HeartbeatManager threw an exception in ProcessHeartbeat: " + ex.ToString());
     98          }
     99          finally {
     100            if (mutexAquired) mutex.ReleaseMutex();
    70101          }
    71102        }
     
    74105    }
    75106
    76     // returns true if assignment was successful
    77     private bool AssignJob(Slave slave, Task task) {
    78       // load task again and check if it is still available (this is an attempt to reduce the race condition which causes multiple heartbeats to get the same task assigned)
    79       if (dao.GetTask(task.Id).State != TaskState.Waiting) return false;
     107    private void AssignJob(Slave slave, Guid taskId) {
     108      trans.UseTransaction(() => {
     109        var task = dao.UpdateTaskState(taskId, DataAccess.TaskState.Transferring, slave.Id, null, null);
    80110
    81       task = dao.UpdateTaskState(task.Id, DataAccess.TaskState.Transferring, slave.Id, null, null);
    82 
    83       // from now on the task has some time to send the next heartbeat (ApplicationConstants.TransferringJobHeartbeatTimeout)
    84       task.LastHeartbeat = DateTime.Now;
    85       dao.UpdateTask(task);
    86       return true;
     111        // from now on the task has some time to send the next heartbeat (ApplicationConstants.TransferringJobHeartbeatTimeout)
     112        task.LastHeartbeat = DateTime.Now;
     113        dao.UpdateTask(task);
     114      });
    87115    }
    88116
     
    102130        // process the jobProgresses
    103131        foreach (var jobProgress in heartbeat.JobProgress) {
    104           Task curTask = dao.GetTask(jobProgress.Key);
     132          Task curTask = null;
     133          curTask = trans.UseTransaction(() => { return dao.GetTask(jobProgress.Key); });
    105134          if (curTask == null) {
    106135            // task does not exist in db
     
    131160                  break;
    132161              }
    133               dao.UpdateTask(curTask);
     162              trans.UseTransaction(() => { dao.UpdateTask(curTask); });
    134163            }
    135164          }
     
    140169
    141170    private bool TaskIsAllowedToBeCalculatedBySlave(Guid slaveId, Task curTask) {
    142       var assignedResourceIds = dao.GetAssignedResources(curTask.Id).Select(x => x.Id);
    143       var slaveResourceIds = dao.GetParentResources(slaveId).Select(x => x.Id);
    144       return assignedResourceIds.Any(x => slaveResourceIds.Contains(x));
     171      return trans.UseTransaction(() => {
     172        var assignedResourceIds = dao.GetAssignedResources(curTask.Id).Select(x => x.Id);
     173        var slaveResourceIds = dao.GetParentResources(slaveId).Select(x => x.Id);
     174        return assignedResourceIds.Any(x => slaveResourceIds.Contains(x));
     175      });
    145176    }
    146177
    147178    private bool SlaveIsAllowedToCalculate(Guid slaveId) {
    148179      // the slave may only calculate if there is no downtime right now. this needs to be checked for every parent resource also
    149       return dao.GetParentResources(slaveId).All(r => dao.GetDowntimes(x => x.ResourceId == r.Id && (DateTime.Now >= x.StartDate) && (DateTime.Now <= x.EndDate)).Count() == 0);
     180      return trans.UseTransaction(() => { return dao.GetParentResources(slaveId).All(r => dao.GetDowntimes(x => x.ResourceId == r.Id && x.DowntimeType == DA.DowntimeType.Offline && (DateTime.Now >= x.StartDate) && (DateTime.Now <= x.EndDate)).Count() == 0); });
     181    }
     182
     183    private bool ShutdownSlaveComputer(Guid slaveId) {
     184      return trans.UseTransaction(() => { return dao.GetParentResources(slaveId).Any(r => dao.GetDowntimes(x => x.ResourceId == r.Id && x.DowntimeType == DA.DowntimeType.Shutdown && (DateTime.Now >= x.StartDate) && (DateTime.Now <= x.EndDate)).Count() != 0); });
    150185    }
    151186  }
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/MessageContainer.cs

    r7259 r9363  
    4848      ShutdownSlave,  // slave should shutdown immediately without submitting results
    4949      SayHello,  // Slave should say hello, because job is unknown to the server
    50       NewHBInterval,
     50      NewHBInterval, // change the polling to a new interval
     51      ShutdownComputer, // shutdown the computer the slave runs on
    5152    };
    5253
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/Plugin.cs.frame

    r8051 r9363  
    2727
    2828namespace HeuristicLab.Services.Hive.Server {
    29   [Plugin("HeuristicLab.Services.Hive", "3.3.6.$WCREV$")]
     29  [Plugin("HeuristicLab.Services.Hive", "3.3.7.$WCREV$")]
    3030  [PluginFile("HeuristicLab.Services.Hive-3.3.dll", PluginFileType.Assembly)]
    3131  [PluginDependency("HeuristicLab.Common", "3.3")]
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/Properties/AssemblyInfo.cs.frame

    r7259 r9363  
    5555// [assembly: AssemblyVersion("1.0.*")]
    5656[assembly: AssemblyVersion("3.3.0.0")]
    57 [assembly: AssemblyFileVersion("3.3.6.$WCREV$")]
     57[assembly: AssemblyFileVersion("3.3.7.$WCREV$")]
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/Properties/Settings.Designer.cs

    r7857 r9363  
    22// <auto-generated>
    33//     This code was generated by a tool.
    4 //     Runtime Version:4.0.30319.269
     4//     Runtime Version:4.0.30319.17929
    55//
    66//     Changes to this file may cause incorrect behavior and will be lost if
     
    1313   
    1414    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    15     [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
     15    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
    1616    public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
    1717       
     
    7777            }
    7878        }
     79       
     80        [global::System.Configuration.ApplicationScopedSettingAttribute()]
     81        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
     82        [global::System.Configuration.DefaultSettingValueAttribute("00:00:20")]
     83        public global::System.TimeSpan SchedulingPatience {
     84            get {
     85                return ((global::System.TimeSpan)(this["SchedulingPatience"]));
     86            }
     87        }
    7988    }
    8089}
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/Properties/Settings.settings

    r7857 r9363  
    2121      <Value Profile="(Default)">3.00:00:00</Value>
    2222    </Setting>
     23    <Setting Name="SchedulingPatience" Type="System.TimeSpan" Scope="Application">
     24      <Value Profile="(Default)">00:00:20</Value>
     25    </Setting>
    2326  </Settings>
    2427</SettingsFile>
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/ServiceContracts/IHiveService.cs

    r8071 r9363  
    5353
    5454    [OperationContract]
     55    IEnumerable<LightweightTask> GetLightweightJobTasksWithoutStateLog(Guid jobId);
     56
     57    [OperationContract]
    5558    TaskData GetTaskData(Guid taskId);
    5659
     
    168171    #endregion
    169172
     173    #region Resource Methods
     174    [OperationContract]
     175    IEnumerable<Resource> GetChildResources(Guid resourceId);
     176    #endregion
     177
    170178    #region Slave Methods
    171179    [OperationContract]
     
    238246    [OperationContract]
    239247    Guid GetUserIdByUsername(string username);
     248    #endregion
     249
     250    #region UserPriorities Methods
     251    [OperationContract]
     252    IEnumerable<UserPriority> GetUserPriorities();
     253    #endregion
     254
     255    #region Statistics Methods
     256    [OperationContract]
     257    IEnumerable<Statistics> GetStatistics();
     258    [OperationContract]
     259    IEnumerable<Statistics> GetStatisticsForTimePeriod(DateTime from, DateTime to);
    240260    #endregion
    241261  }
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/ServiceLocator.cs

    r8326 r9363  
    9898      }
    9999    }
     100
     101    private ITaskScheduler taskScheduler;
     102    public ITaskScheduler TaskScheduler {
     103      get {
     104        if (taskScheduler == null) taskScheduler = new RoundRobinTaskScheduler();
     105        return taskScheduler;
     106      }
     107    }
    100108  }
    101109}
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/Settings.cs

    r6983 r9363  
    1 namespace HeuristicLab.Services.Hive.Properties {
     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
     22namespace HeuristicLab.Services.Hive.Properties {
    223   
    324   
  • branches/OaaS/HeuristicLab.Services.Hive/3.3/app.config

    r7857 r9363  
    2626                <value>3.00:00:00</value>
    2727            </setting>
     28            <setting name="SchedulingPatience" serializeAs="String">
     29                <value>00:00:20</value>
     30            </setting>
    2831        </HeuristicLab.Services.Hive.Properties.Settings>
    2932    </applicationSettings>
Note: See TracChangeset for help on using the changeset viewer.