Changeset 12691


Ignore:
Timestamp:
07/08/15 15:51:32 (7 years ago)
Author:
dglaser
Message:

#2388:

HeuristicLab.Services.Access:
HeuristicLab.Services.Access.DataAccess:

  • Changed connection strings and certificates for local usage

HeuristicLab.Services.Hive.DataAccess:

  • Added compiled queries for frequently used queries
  • Integrated string queries from OptimizedHiveDao

HeuristicLab.Services.Hive:

  • Added NewHeartbeatManager.cs
  • Added NewRoundRobinTaskScheduler.cs
  • Added PerformanceLogger
  • Updated AuthoriziationManager
  • Updated NewHiveService
    • Added Regions
    • Implemented missing methods
    • Improved performance of several queries

HeuristicLab.Services.WebApp.Status:

  • Fixed a bug which caused an error when calculating the average waiting time.
Location:
branches/HiveStatistics/sources
Files:
3 added
44 edited

Legend:

Unmodified
Added
Removed
  • branches/HiveStatistics/sources/HeuristicLab 3.3 Services.sln

    r12551 r12691  
    7070EndProject
    7171Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.Services.WebApp.Statistics-3.3", "HeuristicLab.Services.WebApp.Statistics\3.3\HeuristicLab.Services.WebApp.Statistics-3.3.csproj", "{1BC54353-7D4C-4734-BAA9-3D11B3242B59}"
     72EndProject
     73Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleServiceTest", "ConsoleServiceTest\ConsoleServiceTest.csproj", "{72EAF349-27C8-4CFE-B03B-47E2C5E124FD}"
    7274EndProject
    7375Global
     
    256258    {1BC54353-7D4C-4734-BAA9-3D11B3242B59}.Release|x86.ActiveCfg = Release|x86
    257259    {1BC54353-7D4C-4734-BAA9-3D11B3242B59}.Release|x86.Build.0 = Release|x86
     260    {72EAF349-27C8-4CFE-B03B-47E2C5E124FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
     261    {72EAF349-27C8-4CFE-B03B-47E2C5E124FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
     262    {72EAF349-27C8-4CFE-B03B-47E2C5E124FD}.Debug|x64.ActiveCfg = Debug|Any CPU
     263    {72EAF349-27C8-4CFE-B03B-47E2C5E124FD}.Debug|x86.ActiveCfg = Debug|Any CPU
     264    {72EAF349-27C8-4CFE-B03B-47E2C5E124FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
     265    {72EAF349-27C8-4CFE-B03B-47E2C5E124FD}.Release|Any CPU.Build.0 = Release|Any CPU
     266    {72EAF349-27C8-4CFE-B03B-47E2C5E124FD}.Release|x64.ActiveCfg = Release|Any CPU
     267    {72EAF349-27C8-4CFE-B03B-47E2C5E124FD}.Release|x86.ActiveCfg = Release|Any CPU
    258268  EndGlobalSection
    259269  GlobalSection(SolutionProperties) = preSolution
  • branches/HiveStatistics/sources/HeuristicLab.Services.Access.DataAccess/3.3/AccessService.dbml

    r8040 r12691  
    11<?xml version="1.0" encoding="utf-8"?><Database Name="HeuristicLab.ClientManagement" Class="AccessServiceDataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">
    2   <Connection Mode="AppSettings" ConnectionString="Data Source=.;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True" SettingsObjectName="HeuristicLab.Services.Access.DataAccess.Properties.Settings" SettingsPropertyName="HeuristicLab_ClientManagementConnectionString" Provider="System.Data.SqlClient" />
     2  <Connection Mode="AppSettings" ConnectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True" SettingsObjectName="HeuristicLab.Services.Access.DataAccess.Properties.Settings" SettingsPropertyName="HeuristicLab_ClientManagementConnectionString" Provider="System.Data.SqlClient" />
    33  <Table Name="dbo.Resource" Member="Resources">
    44    <Type Name="Resource" InheritanceCode="Resource" IsInheritanceDefault="true">
  • branches/HiveStatistics/sources/HeuristicLab.Services.Access.DataAccess/3.3/AccessService.designer.cs

    r11623 r12691  
    33// <auto-generated>
    44//     This code was generated by a tool.
    5 //     Runtime Version:4.0.30319.34014
     5//     Runtime Version:4.0.30319.34209
    66//
    77//     Changes to this file may cause incorrect behavior and will be lost if
  • branches/HiveStatistics/sources/HeuristicLab.Services.Access.DataAccess/3.3/Properties/Settings.Designer.cs

    r11623 r12691  
    22// <auto-generated>
    33//     This code was generated by a tool.
    4 //     Runtime Version:4.0.30319.34014
     4//     Runtime Version:4.0.30319.34209
    55//
    66//     Changes to this file may cause incorrect behavior and will be lost if
     
    2727        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    2828        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
    29         [global::System.Configuration.DefaultSettingValueAttribute("Data Source=.;Initial Catalog=HeuristicLab.Authentication;Integrated Security=Tru" +
    30             "e")]
    31         public string HeuristicLab_AuthenticationConnectionString {
     29        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=.\\SQLEXPRESS;Initial Catalog=HeuristicLab.AccessService;Integrated Se" +
     30            "curity=True")]
     31        public string HeuristicLab_ClientManagementConnectionString {
    3232            get {
    33                 return ((string)(this["HeuristicLab_AuthenticationConnectionString"]));
     33                return ((string)(this["HeuristicLab_ClientManagementConnectionString"]));
    3434            }
    3535        }
     
    3838        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    3939        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
    40         [global::System.Configuration.DefaultSettingValueAttribute("Data Source=.;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True" +
    41             "")]
    42         public string HeuristicLab_ClientManagementConnectionString {
     40        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=.\\SQLEXPRESS;Initial Catalog=HeuristicLab.Authentication;Integrated S" +
     41            "ecurity=True")]
     42        public string HeuristicLab_AuthenticationConnectionString {
    4343            get {
    44                 return ((string)(this["HeuristicLab_ClientManagementConnectionString"]));
     44                return ((string)(this["HeuristicLab_AuthenticationConnectionString"]));
    4545            }
    4646        }
  • branches/HiveStatistics/sources/HeuristicLab.Services.Access.DataAccess/3.3/Properties/Settings.settings

    r8040 r12691  
    33  <Profiles />
    44  <Settings>
     5    <Setting Name="HeuristicLab_ClientManagementConnectionString" Type="(Connection string)" Scope="Application">
     6      <DesignTimeValue Profile="(Default)">&lt;?xml version="1.0" encoding="utf-16"?&gt;
     7&lt;SerializableConnectionString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
     8  &lt;ConnectionString&gt;Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True&lt;/ConnectionString&gt;
     9  &lt;ProviderName&gt;System.Data.SqlClient&lt;/ProviderName&gt;
     10&lt;/SerializableConnectionString&gt;</DesignTimeValue>
     11      <Value Profile="(Default)">Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True</Value>
     12    </Setting>
    513    <Setting Name="HeuristicLab_AuthenticationConnectionString" Type="(Connection string)" Scope="Application">
    614      <DesignTimeValue Profile="(Default)">&lt;?xml version="1.0" encoding="utf-16"?&gt;
    715&lt;SerializableConnectionString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
    8   &lt;ConnectionString&gt;Data Source=.;Initial Catalog=HeuristicLab.Authentication;Integrated Security=True&lt;/ConnectionString&gt;
     16  &lt;ConnectionString&gt;Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.Authentication;Integrated Security=True&lt;/ConnectionString&gt;
    917  &lt;ProviderName&gt;System.Data.SqlClient&lt;/ProviderName&gt;
    1018&lt;/SerializableConnectionString&gt;</DesignTimeValue>
    11       <Value Profile="(Default)">Data Source=.;Initial Catalog=HeuristicLab.Authentication;Integrated Security=True</Value>
    12     </Setting>
    13     <Setting Name="HeuristicLab_ClientManagementConnectionString" Type="(Connection string)" Scope="Application">
    14       <DesignTimeValue Profile="(Default)">&lt;?xml version="1.0" encoding="utf-16"?&gt;
    15 &lt;SerializableConnectionString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
    16   &lt;ConnectionString&gt;Data Source=.;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True&lt;/ConnectionString&gt;
    17   &lt;ProviderName&gt;System.Data.SqlClient&lt;/ProviderName&gt;
    18 &lt;/SerializableConnectionString&gt;</DesignTimeValue>
    19       <Value Profile="(Default)">Data Source=.;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True</Value>
     19      <Value Profile="(Default)">Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.Authentication;Integrated Security=True</Value>
    2020    </Setting>
    2121  </Settings>
  • branches/HiveStatistics/sources/HeuristicLab.Services.Access.DataAccess/3.3/app.config

    r11623 r12691  
    33    <configSections>
    44    </configSections>
    5     <connectionStrings>       
    6         <add name="HeuristicLab.Services.Access.DataAccess.Properties.Settings.HeuristicLab_ClientManagementConnectionString" connectionString="Data Source=.;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True" providerName="System.Data.SqlClient"/>
    7         <add name="HeuristicLab.Services.Access.DataAccess.Properties.Settings.HeuristicLab_AuthenticationConnectionString" connectionString="Data Source=.;Initial Catalog=HeuristicLab.Authentication;Integrated Security=True" providerName="System.Data.SqlClient"/>
     5    <connectionStrings>
     6      <add name="HeuristicLab.Services.Access.DataAccess.Properties.Settings.HeuristicLab_ClientManagementConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.AccessService;Integrated Security=True" providerName="System.Data.SqlClient"/>
     7      <add name="HeuristicLab.Services.Access.DataAccess.Properties.Settings.HeuristicLab_AuthenticationConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.Authentication;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
    88    </connectionStrings>
    99<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>
  • branches/HiveStatistics/sources/HeuristicLab.Services.Access/3.3/App.config

    r11623 r12691  
    22<configuration>
    33  <connectionStrings>
    4     <add name="HeuristicLab.Authentication" connectionString="Data Source=.;Initial Catalog=HeuristicLab.Authentication;Integrated Security=True" providerName="System.Data.SqlClient"/>
     4    <add name="HeuristicLab.Authentication" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=HeuristicLab.Authentication"/>
     5    <add name="HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.Hive-3.3;Integrated Security=True;" providerName="System.Data.SqlClient"/>
    56  </connectionStrings>
    67  <system.web>
  • branches/HiveStatistics/sources/HeuristicLab.Services.Access/3.3/Web.config

    r12584 r12691  
    22<configuration>
    33  <connectionStrings>
    4   <add name="HeuristicLab.Authentication" connectionString="data source=localhost;Integrated Security=SSPI;Initial Catalog=HeuristicLab.Authentication"/>
     4    <add name="HeuristicLab.Authentication" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=HeuristicLab.Authentication"/>
     5    <add name="HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.Hive-3.3;Integrated Security=True;" providerName="System.Data.SqlClient"/>
    56  </connectionStrings>
    67  <system.web>
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/AssignedResourceDao.cs

    r12584 r12691  
    3535      return Table.Where(x => x.TaskId == taskId);
    3636    }
     37
     38    public bool TaskIsAllowedToBeCalculatedBySlave(Guid taskId, Guid slaveId) {
     39      return DataContext.ExecuteQuery<int>(TaskIsAllowedToBeCalculatedBySlaveQueryString, slaveId, taskId).First() > 0;
     40    }
     41
     42    #region String queries
     43    private const string TaskIsAllowedToBeCalculatedBySlaveQueryString = @"
     44      WITH pr AS (
     45        SELECT ResourceId, ParentResourceId
     46        FROM [Resource]
     47        WHERE ResourceId = {0}
     48        UNION ALL
     49        SELECT r.ResourceId, r.ParentResourceId
     50        FROM [Resource] r JOIN pr ON r.ResourceId = pr.ParentResourceId
     51      )
     52      SELECT COUNT(ar.TaskId)
     53      FROM pr JOIN AssignedResources ar ON pr.ResourceId = ar.ResourceId
     54      WHERE ar.TaskId = {1}
     55    ";
     56    #endregion
    3757  }
    3858}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/DowntimeDao.cs

    r12468 r12691  
    2929
    3030    public override Downtime GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.DowntimeId == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
     33
     34    public IQueryable<Downtime> GetByResourceId(Guid id) {
     35      return Table.Where(x => x.ResourceId == id);
     36    }
     37
     38    #region Compiled queries
     39    private static readonly Func<DataContext, Guid, Downtime> GetByIdQuery =
     40      CompiledQuery.Compile((DataContext db, Guid downtimeId) =>
     41        (from downtime in db.GetTable<Downtime>()
     42         where downtime.DowntimeId == downtimeId
     43         select downtime).SingleOrDefault());
     44    #endregion
    3345  }
    3446}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/GenericDao.cs

    r12484 r12691  
    109109
    110110    public bool Exists(T entity) {
    111       return Table.Contains(entity);
     111      return ExistsQuery(DataContext, entity);
    112112    }
    113113
     
    116116    }
    117117    #endregion
     118
     119    #region Compiled queries
     120    private static readonly Func<DataContext, T, bool> ExistsQuery =
     121      CompiledQuery.Compile((DataContext db, T entity) =>
     122        db.GetTable<T>().Contains(entity));
     123    #endregion
    118124  }
    119125}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/HiveStatistics/DimClientDao.cs

    r12516 r12691  
    2727namespace HeuristicLab.Services.Hive.DataAccess.Daos.HiveStatistics {
    2828  public class DimClientDao : GenericDao<Guid, DimClient> {
    29     private const string UpdateExpirationTimeQuery =
    30       @"UPDATE [statistics].[DimClient]
    31            SET ExpirationTime = {0}
    32          WHERE Id IN ({1});";
    33 
    3429    public DimClientDao(DataContext dataContext) : base(dataContext) { }
    3530
    3631    public override DimClient GetById(Guid id) {
    37       return Table.SingleOrDefault(x => x.Id == id);
     32      return GetByIdQuery(DataContext, id);
    3833    }
     34
    3935    public IQueryable<DimClient> GetActiveClients() {
    4036      return Table.Where(x => x.ExpirationTime == null);
     
    5349      return 0;
    5450    }
     51
     52    #region Compiled queries
     53    private static readonly Func<DataContext, Guid, DimClient> GetByIdQuery =
     54      CompiledQuery.Compile((DataContext db, Guid id) =>
     55        (from dimClient in db.GetTable<DimClient>()
     56         where dimClient.Id == id
     57         select dimClient).SingleOrDefault());
     58    #endregion
     59
     60    #region String queries
     61    private const string UpdateExpirationTimeQuery =
     62      @"UPDATE [statistics].[DimClient]
     63           SET ExpirationTime = {0}
     64         WHERE Id IN ({1});";
     65    #endregion
    5566  }
    5667}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/HiveStatistics/DimJobDao.cs

    r12516 r12691  
    2929
    3030    public override DimJob GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.JobId == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
    3333
     
    4343      return Table.Where(x => x.DateCompleted != null);
    4444    }
     45
     46    #region Compiled queries
     47    private static readonly Func<DataContext, Guid, DimJob> GetByIdQuery =
     48      CompiledQuery.Compile((DataContext db, Guid id) =>
     49        (from dimJob in db.GetTable<DimJob>()
     50         where dimJob.JobId == id
     51         select dimJob).SingleOrDefault());
     52    #endregion
    4553  }
    4654}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/HiveStatistics/DimTimeDao.cs

    r12468 r12691  
    2929
    3030    public override DimTime GetById(DateTime id) {
    31       return Table.SingleOrDefault(x => x.Time == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
    3333    public DimTime GetLastEntry() {
    34       return Table.OrderByDescending(x => x.Time).FirstOrDefault();
     34      return GetLastEntryQuery(DataContext);
    3535    }
     36
     37    #region Compiled queries
     38    private static readonly Func<DataContext, DateTime, DimTime> GetByIdQuery =
     39      CompiledQuery.Compile((DataContext db, DateTime id) =>
     40        (from dimTime in db.GetTable<DimTime>()
     41         where dimTime.Time == id
     42         select dimTime).SingleOrDefault());
     43
     44    private static readonly Func<DataContext, DimTime> GetLastEntryQuery =
     45      CompiledQuery.Compile((DataContext db) =>
     46        (from dimTime in db.GetTable<DimTime>()
     47         orderby dimTime.Time descending
     48         select dimTime).FirstOrDefault());
     49    #endregion
    3650  }
    3751}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/HiveStatistics/DimUserDao.cs

    r12468 r12691  
    2929
    3030    public override DimUser GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.UserId == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
     33
     34    #region Compiled queries
     35    private static readonly Func<DataContext, Guid, DimUser> GetByIdQuery =
     36      CompiledQuery.Compile((DataContext db, Guid id) =>
     37        (from dimUser in db.GetTable<DimUser>()
     38         where dimUser.UserId == id
     39         select dimUser).SingleOrDefault());
     40    #endregion
    3341  }
    3442}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/HiveStatistics/FactClientInfoDao.cs

    r12516 r12691  
    5353      return from cf in Table
    5454             join r in DimClientTable on cf.ClientId equals r.Id
    55              group cf by r.ResourceId into grpFacts
    56              select new LastUpdateTimestamp {
    57                ResourceId = grpFacts.Key,
    58                Timestamp = grpFacts.Max(x => x.Time),
    59              };
     55             group cf by r.ResourceId
     56               into grpFacts
     57               select new LastUpdateTimestamp {
     58                 ResourceId = grpFacts.Key,
     59                 Timestamp = grpFacts.Max(x => x.Time),
     60               };
    6061    }
    6162
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/HiveStatistics/FactTaskDao.cs

    r12551 r12691  
    3737    }
    3838
    39     private const string BatchDeleteQuery =
    40       @"DELETE FROM [statistics].[FactTask]
    41          WHERE TaskId IN ({0});";
    4239    public FactTaskDao(DataContext dataContext) : base(dataContext) { }
    4340
    4441    public override FactTask GetById(Guid id) {
    45       return Table.SingleOrDefault(x => x.TaskId == id);
     42      return GetByIdQuery(DataContext, id);
    4643    }
    4744
     
    5552
    5653    public DateTime? GetLastCompletedTaskFromJob(Guid id) {
    57       return Table.Where(x => x.JobId == id && x.EndTime != null).Max(x => x.EndTime);
     54      return GetLastCompletedTaskFromJobQuery(DataContext, id);
    5855    }
    5956
     
    9289    }
    9390
     91    #region Compiled queries
     92    private static readonly Func<DataContext, Guid, FactTask> GetByIdQuery =
     93      CompiledQuery.Compile((DataContext db, Guid id) =>
     94        (from factTask in db.GetTable<FactTask>()
     95         where factTask.TaskId == id
     96         select factTask).SingleOrDefault());
     97
     98
     99    private static readonly Func<DataContext, Guid, DateTime?> GetLastCompletedTaskFromJobQuery =
     100      CompiledQuery.Compile((DataContext db, Guid id) =>
     101        (from factTask in db.GetTable<FactTask>()
     102         where factTask.JobId == id && factTask.EndTime != null
     103         select factTask.EndTime).Max());
     104    #endregion
     105
     106    #region String queries
     107    private const string BatchDeleteQuery =
     108      @"DELETE FROM [statistics].[FactTask]
     109         WHERE TaskId IN ({0});";
     110    #endregion
    94111  }
    95112}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/JobDao.cs

    r12468 r12691  
    2929
    3030    public override Job GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.JobId == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
     33
     34    #region Compiled queries
     35    private static readonly Func<DataContext, Guid, Job> GetByIdQuery =
     36      CompiledQuery.Compile((DataContext db, Guid jobId) =>
     37        (from job in db.GetTable<Job>()
     38         where job.JobId == jobId
     39         select job).SingleOrDefault());
     40    #endregion
    3341  }
    3442}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/JobPermissionDao.cs

    r12584 r12691  
    3333
    3434    public JobPermission GetByJobAndUserId(Guid jobId, Guid userId) {
    35       return Table.SingleOrDefault(x => x.JobId == jobId && x.GrantedUserId == userId);
     35      return GetByJobAndUserIdQuery(DataContext, jobId, userId);
    3636    }
     37
     38    public IQueryable<JobPermission> GetByJobId(Guid jobId) {
     39      return Table.Where(x => x.JobId == jobId);
     40    }
     41
     42    public void SetJobPermission(Guid jobId, Guid grantedByUserId, Guid grantedUserId, Permission permission) {
     43      var jobPermission = GetByJobAndUserId(jobId, grantedUserId);
     44      if (jobPermission != null) {
     45        if (permission == Permission.NotAllowed) {
     46          Delete(jobPermission);
     47        } else {
     48          jobPermission.Permission = permission;
     49          jobPermission.GrantedByUserId = grantedByUserId;
     50        }
     51      } else {
     52        if (permission != Permission.NotAllowed) {
     53          Save(new JobPermission {
     54            JobId = jobId,
     55            GrantedByUserId = grantedByUserId,
     56            GrantedUserId = grantedUserId,
     57            Permission = permission
     58          });
     59        }
     60      }
     61    }
     62
     63    #region Compiled queries
     64    private static readonly Func<DataContext, Guid, Guid, JobPermission> GetByJobAndUserIdQuery =
     65      CompiledQuery.Compile((DataContext db, Guid jobId, Guid userId) =>
     66        (from jobPermission in db.GetTable<JobPermission>()
     67         where jobPermission.JobId == jobId && jobPermission.GrantedUserId == userId
     68         select jobPermission).SingleOrDefault());
     69    #endregion
    3770  }
    3871}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/LifecycleDao.cs

    r12468 r12691  
    2020#endregion
    2121
     22using System;
    2223using System.Data.Linq;
    2324using System.Linq;
     
    2829
    2930    public override Lifecycle GetById(int id) {
    30       return Table.SingleOrDefault(x => x.LifecycleId == id);
     31      return GetByIdQuery(DataContext, id);
    3132    }
     33
     34    public Lifecycle GetLastLifecycle() {
     35      return GetLastLifecycleQuery(DataContext);
     36    }
     37
     38    public void UpdateLifecycle() {
     39      var entity = GetLastLifecycle();
     40      if (entity != null) {
     41        entity.LastCleanup = DateTime.Now;
     42      } else {
     43        Save(new Lifecycle {
     44          LifecycleId = 0,
     45          LastCleanup = DateTime.Now
     46        });
     47      }
     48    }
     49
     50    #region Compiled queries
     51    private static readonly Func<DataContext, int, Lifecycle> GetByIdQuery =
     52     CompiledQuery.Compile((DataContext db, int lifecycleId) =>
     53       (from lifecycle in db.GetTable<Lifecycle>()
     54        where lifecycle.LifecycleId == lifecycleId
     55        select lifecycle).SingleOrDefault());
     56
     57    private static readonly Func<DataContext, Lifecycle> GetLastLifecycleQuery =
     58      CompiledQuery.Compile((DataContext db) =>
     59        (from lifecycle in db.GetTable<Lifecycle>()
     60         select lifecycle).SingleOrDefault());
     61    #endregion
    3262  }
    3363}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/PluginDao.cs

    r12468 r12691  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Data.Linq;
    2425using System.Linq;
     
    2930
    3031    public override Plugin GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.PluginId == id);
     32      return GetByIdQuery(DataContext, id);
    3233    }
     34
     35    public IEnumerable<Plugin> GetByHash(byte[] hash) {
     36      return GetByHashQuery(DataContext).Where(x => x.Hash.SequenceEqual(hash));
     37    }
     38
     39    #region Compiled queries
     40    private static readonly Func<DataContext, Guid, Plugin> GetByIdQuery =
     41      CompiledQuery.Compile((DataContext db, Guid pluginId) =>
     42        (from plugin in db.GetTable<Plugin>()
     43         where plugin.PluginId == pluginId
     44         select plugin).SingleOrDefault());
     45
     46    private static readonly Func<DataContext, IEnumerable<Plugin>> GetByHashQuery =
     47      CompiledQuery.Compile((DataContext db) =>
     48        (from plugin in db.GetTable<Plugin>()
     49         where plugin.Hash != null
     50         select plugin));
     51    #endregion
    3352  }
    3453}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/PluginDataDao.cs

    r12468 r12691  
    2929
    3030    public override PluginData GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.PluginDataId == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
     33
     34    #region Compiled queries
     35    private static readonly Func<DataContext, Guid, PluginData> GetByIdQuery =
     36      CompiledQuery.Compile((DataContext db, Guid pluginDataId) =>
     37        (from pluginData in db.GetTable<PluginData>()
     38         where pluginData.PluginDataId == pluginDataId
     39         select pluginData).SingleOrDefault());
     40    #endregion
    3341  }
    3442}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/RequiredPluginDao.cs

    r12468 r12691  
    2929
    3030    public override RequiredPlugin GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.RequiredPluginId == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
     33
     34    #region Compiled queries
     35    private static readonly Func<DataContext, Guid, RequiredPlugin> GetByIdQuery =
     36      CompiledQuery.Compile((DataContext db, Guid requiredPluginId) =>
     37        (from requiredPlugin in db.GetTable<RequiredPlugin>()
     38         where requiredPlugin.RequiredPluginId == requiredPluginId
     39         select requiredPlugin).SingleOrDefault());
     40    #endregion
    3341  }
    3442}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/ResourceDao.cs

    r12468 r12691  
    2929
    3030    public override Resource GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.ResourceId == id);
     31      return GetByIdQuery(DataContext, id);
     32    }
     33
     34    public Resource GetByName(string name) {
     35      return GetByNameQuery(DataContext, name);
    3236    }
    3337
     
    3539      return Table.Where(x => x.OwnerUserId != null);
    3640    }
     41
     42    #region Compiled queries
     43    private static readonly Func<DataContext, Guid, Resource> GetByIdQuery =
     44      CompiledQuery.Compile((DataContext db, Guid resourceId) =>
     45        (from resource in db.GetTable<Resource>()
     46         where resource.ResourceId == resourceId
     47         select resource).SingleOrDefault());
     48
     49    private static readonly Func<DataContext, string, Resource> GetByNameQuery =
     50     CompiledQuery.Compile((DataContext db, string name) =>
     51       (from resource in db.GetTable<Resource>()
     52        where resource.Name == name
     53        select resource).FirstOrDefault());
     54    #endregion
    3755  }
    3856}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/ResourcePermissionDao.cs

    r12468 r12691  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Data.Linq;
     25using System.Linq;
    2426
    2527namespace HeuristicLab.Services.Hive.DataAccess.Daos {
     
    3032      throw new NotImplementedException();
    3133    }
     34
     35    public IEnumerable<ResourcePermission> GetByResourceId(Guid id) {
     36      return GetByResourceIdGetByIdQuery(DataContext, id);
     37    }
     38
     39    public void DeleteByResourceAndGrantedUserId(Guid resourceId, IEnumerable<Guid> grantedUserId) {
     40      string paramIds = string.Join(",", grantedUserId.Select(x => string.Format("'{0}'", x)));
     41      if (!string.IsNullOrWhiteSpace(paramIds)) {
     42        string query = string.Format(DeleteByGrantedUserQuery, resourceId, paramIds);
     43        DataContext.ExecuteCommand(query);
     44      }
     45    }
     46
     47    #region Compiled queries
     48    private static readonly Func<DataContext, Guid, IEnumerable<ResourcePermission>> GetByResourceIdGetByIdQuery =
     49      CompiledQuery.Compile((DataContext db, Guid resourceId) =>
     50        from resourcePermission in db.GetTable<ResourcePermission>()
     51        where resourcePermission.ResourceId == resourceId
     52        select resourcePermission);
     53    #endregion
     54
     55    #region String queries
     56    private const string DeleteByGrantedUserQuery =
     57      @"DELETE FROM [ResourcePermission]
     58         WHERE ResourceId = '{0}'
     59           AND GrantedUserId IN ({1});";
     60    #endregion
    3261  }
    3362}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/SlaveDao.cs

    r12551 r12691  
    4646    #region IGenericDao<Guid,Slave> Members
    4747    public Slave GetById(Guid id) {
    48       return Entities.SingleOrDefault(x => x.ResourceId == id);
     48      return GetByIdQuery(dataContext, id);
    4949    }
    5050
     
    117117
    118118    public bool Exists(Slave entity) {
    119       return Table.Contains(entity);
     119      return ExistsQuery(dataContext, entity);
    120120    }
    121121
     
    124124    }
    125125    #endregion
     126
     127    public bool SlaveHasToShutdownComputer(Guid slaveId) {
     128      return dataContext.ExecuteQuery<int>(DowntimeQueryString, slaveId, DateTime.Now, DowntimeType.Shutdown.ToString()).FirstOrDefault() > 0;
     129    }
     130
     131    public bool SlaveIsAllowedToCalculate(Guid slaveId) {
     132      return dataContext.ExecuteQuery<int>(DowntimeQueryString, slaveId, DateTime.Now, DowntimeType.Offline.ToString()).FirstOrDefault() == 0;
     133    }
     134
     135    #region Compiled queries
     136    private static readonly Func<DataContext, Guid, Slave> GetByIdQuery =
     137      CompiledQuery.Compile((DataContext db, Guid slaveId) =>
     138        (from slave in db.GetTable<Resource>().OfType<Slave>()
     139         where slave.ResourceId == slaveId
     140         select slave).SingleOrDefault());
     141
     142    private static readonly Func<DataContext, Slave, bool> ExistsQuery =
     143      CompiledQuery.Compile((DataContext db, Slave entity) =>
     144        db.GetTable<Resource>().OfType<Slave>().Contains(entity));
     145    #endregion
     146
     147    #region String queries
     148    private const string DowntimeQueryString = @"
     149      WITH pr AS (
     150        SELECT ResourceId, ParentResourceId
     151        FROM [Resource]
     152        WHERE ResourceId = {0}
     153        UNION ALL
     154        SELECT r.ResourceId, r.ParentResourceId
     155        FROM [Resource] r JOIN pr ON r.ResourceId = pr.ParentResourceId
     156      )
     157      SELECT COUNT(dt.DowntimeId)
     158      FROM pr JOIN [Downtime] dt ON pr.ResourceId = dt.ResourceId
     159      WHERE {1} BETWEEN dt.StartDate AND dt.EndDate
     160        AND dt.DowntimeType = {2}
     161    ";
     162    #endregion
    126163  }
    127164}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/SlaveGroupDao.cs

    r12484 r12691  
    4545    #region IGenericDao<Guid,SlaveGroup> Members
    4646    public SlaveGroup GetById(Guid id) {
    47       return Entities.SingleOrDefault(x => x.ResourceId == id);
     47      return GetByIdQuery(dataContext, id);
    4848    }
    4949
     
    112112
    113113    public bool Exists(SlaveGroup entity) {
    114       return Table.Contains(entity);
     114      return ExistsQuery(dataContext, entity);
    115115    }
    116116
     
    119119    }
    120120    #endregion
     121
     122    #region Compiled queries
     123    private static readonly Func<DataContext, Guid, SlaveGroup> GetByIdQuery =
     124      CompiledQuery.Compile((DataContext db, Guid slaveGroupId) =>
     125        (from slaveGroup in db.GetTable<Resource>().OfType<SlaveGroup>()
     126         where slaveGroup.ResourceId == slaveGroupId
     127         select slaveGroup).SingleOrDefault());
     128
     129    private static readonly Func<DataContext, SlaveGroup, bool> ExistsQuery =
     130      CompiledQuery.Compile((DataContext db, SlaveGroup slaveGroup) =>
     131        db.GetTable<Resource>().OfType<SlaveGroup>().Contains(slaveGroup));
     132    #endregion
    121133  }
    122134}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/StateLogDao.cs

    r12584 r12691  
    2626namespace HeuristicLab.Services.Hive.DataAccess.Daos {
    2727  public class StateLogDao : GenericDao<Guid, StateLog> {
    28 
    2928    private Table<Task> TaskTable {
    3029      get { return DataContext.GetTable<Task>(); }
     
    3433
    3534    public override StateLog GetById(Guid id) {
    36       return Table.SingleOrDefault(x => x.StateLogId == id);
     35      return GetByIdQuery(DataContext, id);
    3736    }
    3837
    3938    public StateLog GetLastStateLogFromTask(Task task) {
    40       return Table
    41         .Where(x => x.TaskId == task.TaskId)
    42         .OrderByDescending(x => x.DateTime)
    43         .First(x => x.SlaveId != null);
     39      return GetLastStateLogFromTaskQuery(DataContext, task);
    4440    }
     41
     42    #region Compiled queries
     43    private static readonly Func<DataContext, Guid, StateLog> GetByIdQuery =
     44      CompiledQuery.Compile((DataContext db, Guid stateLogId) =>
     45        (from stateLog in db.GetTable<StateLog>()
     46         where stateLog.StateLogId == stateLogId
     47         select stateLog).SingleOrDefault());
     48
     49    private static readonly Func<DataContext, Task, StateLog> GetLastStateLogFromTaskQuery =
     50      CompiledQuery.Compile((DataContext db, Task task) =>
     51        (from stateLog in db.GetTable<StateLog>()
     52         where stateLog.TaskId == task.TaskId
     53         orderby stateLog.DateTime descending
     54         select stateLog).First(x => x.SlaveId != null));
     55    #endregion
    4556  }
    4657}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/TaskDao.cs

    r12584 r12691  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Data.Linq;
    2425using System.Linq;
     
    2930
    3031    public override Task GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.TaskId == id);
     32      return GetByIdQuery(DataContext, id);
    3233    }
    3334
     
    3940      return Table.Where(x => x.JobId == id);
    4041    }
     42    public class TaskPriorityInfo {
     43      public Guid JobId { get; set; }
     44      public Guid TaskId { get; set; }
     45      public int Priority { get; set; }
     46    }
     47
     48    public IEnumerable<TaskPriorityInfo> GetWaitingTasks(Slave slave) {
     49      //Originally we checked here if there are parent tasks which should be calculated (with GetParentTasks(resourceIds, count, false);).
     50      //Because there is at the moment no case where this makes sense (there don't exist parent tasks which need to be calculated),
     51      //we skip this step because it's wasted runtime
     52      return DataContext.ExecuteQuery<TaskPriorityInfo>(GetWaitingTasksQueryString, slave.ResourceId, Enum.GetName(typeof(TaskState), TaskState.Waiting), slave.FreeCores, slave.FreeMemory).ToList();
     53    }
     54
     55    public void UpdateExecutionTime(Guid taskId, double executionTime) {
     56      DataContext.ExecuteCommand(UpdateExecutionTimeQuery, executionTime, DateTime.Now, taskId);
     57    }
     58
     59    #region Compiled queries
     60    private static readonly Func<DataContext, Guid, Task> GetByIdQuery =
     61      CompiledQuery.Compile((DataContext db, Guid taskId) =>
     62        (from task in db.GetTable<Task>()
     63         where task.TaskId == taskId
     64         select task).SingleOrDefault());
     65    #endregion
     66
     67    #region String queries
     68    private const string GetWaitingTasksQueryString = @"
     69      WITH pr AS (
     70        SELECT ResourceId, ParentResourceId
     71        FROM [Resource]
     72        WHERE ResourceId = {0}
     73        UNION ALL
     74        SELECT r.ResourceId, r.ParentResourceId
     75        FROM [Resource] r JOIN pr ON r.ResourceId = pr.ParentResourceId
     76      )
     77      SELECT DISTINCT t.TaskId, t.JobId, t.Priority
     78      FROM pr JOIN AssignedResources ar ON ar.ResourceId = pr.ResourceId
     79          JOIN Task t ON t.TaskId = ar.TaskId
     80      WHERE NOT (t.IsParentTask = 1 AND t.FinishWhenChildJobsFinished = 1)
     81          AND t.TaskState = {1}
     82          AND t.CoresNeeded <= {2}
     83          AND t.MemoryNeeded <= {3}
     84    ";
     85
     86    private const string UpdateExecutionTimeQuery = @"
     87      UPDATE [Task]
     88         SET ExecutionTimeMs = {0},
     89             LastHeartbeat = {1}
     90       WHERE TaskId = {2}
     91    ";
     92    #endregion
    4193  }
    4294}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/TaskDataDao.cs

    r12468 r12691  
    2929
    3030    public override TaskData GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.TaskId == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
     33
     34    #region Compiled queries
     35    private static readonly Func<DataContext, Guid, TaskData> GetByIdQuery =
     36      CompiledQuery.Compile((DataContext db, Guid taskId) =>
     37        (from taskData in db.GetTable<TaskData>()
     38         where taskData.TaskId == taskId
     39         select taskData).SingleOrDefault());
     40    #endregion
    3341  }
    3442}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Daos/UserPriorityDao.cs

    r12468 r12691  
    2929
    3030    public override UserPriority GetById(Guid id) {
    31       return Table.SingleOrDefault(x => x.UserId == id);
     31      return GetByIdQuery(DataContext, id);
    3232    }
     33
     34    #region Compiled queries
     35    private static readonly Func<DataContext, Guid, UserPriority> GetByIdQuery =
     36      CompiledQuery.Compile((DataContext db, Guid userId) =>
     37        (from userPriority in db.GetTable<UserPriority>()
     38         where userPriority.UserId == userId
     39         select userPriority).SingleOrDefault());
     40    #endregion
    3341  }
    3442}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.DataAccess/3.3/Manager/PersistenceManager.cs

    r12468 r12691  
    3535
    3636    #region Hive daos
     37
     38    private AssignedResourceDao assignedResourceDao;
    3739    public AssignedResourceDao AssignedResourceDao {
    38       get { return new AssignedResourceDao(dataContext); }
    39     }
    40 
     40      get { return assignedResourceDao ?? (assignedResourceDao = new AssignedResourceDao(dataContext)); }
     41    }
     42
     43    private DowntimeDao downtimeDao;
    4144    public DowntimeDao DowntimeDao {
    42       get { return new DowntimeDao(dataContext); }
    43     }
    44 
     45      get { return downtimeDao ?? (downtimeDao = new DowntimeDao(dataContext)); }
     46    }
     47
     48    private JobDao jobDao;
    4549    public JobDao JobDao {
    46       get { return new JobDao(dataContext); }
    47     }
    48 
     50      get { return jobDao ?? (jobDao = new JobDao(dataContext)); }
     51    }
     52
     53    private JobPermissionDao jobPermissionDao;
    4954    public JobPermissionDao JobPermissionDao {
    50       get { return new JobPermissionDao(dataContext); }
    51     }
    52 
     55      get { return jobPermissionDao ?? (jobPermissionDao = new JobPermissionDao(dataContext)); }
     56    }
     57
     58    private LifecycleDao lifecycleDao;
    5359    public LifecycleDao LifecycleDao {
    54       get { return new LifecycleDao(dataContext); }
    55     }
    56 
     60      get { return lifecycleDao ?? (lifecycleDao = new LifecycleDao(dataContext)); }
     61    }
     62
     63    private PluginDao pluginDao;
    5764    public PluginDao PluginDao {
    58       get { return new PluginDao(dataContext); }
    59     }
    60 
     65      get { return pluginDao ?? (pluginDao = new PluginDao(dataContext)); }
     66    }
     67
     68    private PluginDataDao pluginDataDao;
    6169    public PluginDataDao PluginDataDao {
    62       get { return new PluginDataDao(dataContext); }
    63     }
    64 
     70      get { return pluginDataDao ?? (pluginDataDao = new PluginDataDao(dataContext)); }
     71    }
     72
     73    private RequiredPluginDao requiredPluginDao;
    6574    public RequiredPluginDao RequiredPluginDao {
    66       get { return new RequiredPluginDao(dataContext); }
    67     }
    68 
     75      get { return requiredPluginDao ?? (requiredPluginDao = new RequiredPluginDao(dataContext)); }
     76    }
     77
     78    private ResourceDao resourceDao;
    6979    public ResourceDao ResourceDao {
    70       get { return new ResourceDao(dataContext); }
    71     }
    72 
     80      get { return resourceDao ?? (resourceDao = new ResourceDao(dataContext)); }
     81    }
     82
     83    private ResourcePermissionDao resourcePermissionDao;
    7384    public ResourcePermissionDao ResourcePermissionDao {
    74       get { return new ResourcePermissionDao(dataContext); }
    75     }
    76 
     85      get { return resourcePermissionDao ?? (resourcePermissionDao = new ResourcePermissionDao(dataContext)); }
     86    }
     87
     88    private SlaveDao slaveDao;
    7789    public SlaveDao SlaveDao {
    78       get { return new SlaveDao(dataContext); }
    79     }
    80 
     90      get { return slaveDao ?? (slaveDao = new SlaveDao(dataContext)); }
     91    }
     92
     93    private SlaveGroupDao slaveGroupDao;
    8194    public SlaveGroupDao SlaveGroupDao {
    82       get { return new SlaveGroupDao(dataContext); }
    83     }
    84 
     95      get { return slaveGroupDao ?? (slaveGroupDao = new SlaveGroupDao(dataContext)); }
     96    }
     97
     98    private StateLogDao stateLogDao;
    8599    public StateLogDao StateLogDao {
    86       get { return new StateLogDao(dataContext); }
    87     }
    88 
     100      get { return stateLogDao ?? (stateLogDao = new StateLogDao(dataContext)); }
     101    }
     102
     103    private TaskDao taskDao;
    89104    public TaskDao TaskDao {
    90       get { return new TaskDao(dataContext); }
    91     }
    92 
     105      get { return taskDao ?? (taskDao = new TaskDao(dataContext)); }
     106    }
     107
     108    private TaskDataDao taskDataDao;
    93109    public TaskDataDao TaskDataDao {
    94       get { return new TaskDataDao(dataContext); }
    95     }
    96 
     110      get { return taskDataDao ?? (taskDataDao = new TaskDataDao(dataContext)); }
     111    }
     112
     113    private UserPriorityDao userPriorityDao;
    97114    public UserPriorityDao UserPriorityDao {
    98       get { return new UserPriorityDao(dataContext); }
     115      get { return userPriorityDao ?? (userPriorityDao = new UserPriorityDao(dataContext)); }
    99116    }
    100117    #endregion
    101118
    102119    #region HiveStatistics daos
     120
     121    private DimClientDao dimClientDao;
    103122    public DimClientDao DimClientDao {
    104       get { return new DimClientDao(dataContext); }
    105     }
    106 
     123      get { return dimClientDao ?? (dimClientDao = new DimClientDao(dataContext)); }
     124    }
     125
     126    private DimJobDao dimJobDao;
    107127    public DimJobDao DimJobDao {
    108       get { return new DimJobDao(dataContext); }
    109     }
    110 
     128      get { return dimJobDao ?? (dimJobDao = new DimJobDao(dataContext)); }
     129    }
     130
     131    private DimTimeDao dimTimeDao;
    111132    public DimTimeDao DimTimeDao {
    112       get { return new DimTimeDao(dataContext); }
    113     }
    114 
     133      get { return dimTimeDao ?? (dimTimeDao = new DimTimeDao(dataContext)); }
     134    }
     135
     136    private DimUserDao dimUserDao;
    115137    public DimUserDao DimUserDao {
    116       get { return new DimUserDao(dataContext); }
    117     }
    118 
     138      get { return dimUserDao ?? (dimUserDao = new DimUserDao(dataContext)); }
     139    }
     140
     141    private FactClientInfoDao factClientInfoDao;
    119142    public FactClientInfoDao FactClientInfoDao {
    120       get { return new FactClientInfoDao(dataContext); }
    121     }
    122 
     143      get { return factClientInfoDao ?? (factClientInfoDao = new FactClientInfoDao(dataContext)); }
     144    }
     145
     146    private FactTaskDao factTaskDao;
    123147    public FactTaskDao FactTaskDao {
    124       get { return new FactTaskDao(dataContext); }
     148      get { return factTaskDao ?? (factTaskDao = new FactTaskDao(dataContext)); }
    125149    }
    126150    #endregion
     
    130154      if (longRunning) context.CommandTimeout = (int)Settings.Default.LongRunningDatabaseCommandTimeout.TotalSeconds;
    131155      dataContext = context;
     156    }
     157
     158    public PersistenceManager(DataContext dataContext) {
     159      this.dataContext = dataContext;
    132160    }
    133161
     
    179207
    180208    public void Dispose() {
    181       if (dataContext != null) {
    182         dataContext.Dispose();
    183       }
     209      //if (dataContext != null) {
     210      //  dataContext.Dispose();
     211      //}
    184212    }
    185213  }
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.Web/Hive-3.3/HiveService.svc

    r6983 r12691  
    22  Language="C#"
    33  Debug="true"
    4   Service="HeuristicLab.Services.Hive.HiveService"
     4  Service="HeuristicLab.Services.Hive.NewHiveService"
    55  %>
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive.Web/Hive-3.3/Web.config

    r12584 r12691  
    100100    </behaviors>
    101101    <services>
    102       <service behaviorConfiguration="ServiceBehaviour_IHiveService" name="HeuristicLab.Services.Hive.HiveService">
     102      <service behaviorConfiguration="ServiceBehaviour_IHiveService" name="HeuristicLab.Services.Hive.NewHiveService">
    103103        <endpoint address="mexhttp" binding="mexHttpBinding" bindingConfiguration="" name="MexHttpEndpoint" contract="IMetadataExchange"/>
    104104        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="MexTcpEndpoint" contract="IMetadataExchange"/>
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/Converter.cs

    r12584 r12691  
    150150    #endregion
    151151
     152    #region Slave
     153    public static DT.Slave ToDto(this DA.Slave source) {
     154      if (source == null) return null;
     155      return new DT.Slave {
     156        Id = source.ResourceId,
     157        ParentResourceId = source.ParentResourceId,
     158        Cores = source.Cores,
     159        CpuSpeed = source.CpuSpeed,
     160        FreeCores = source.FreeCores,
     161        FreeMemory = source.FreeMemory,
     162        IsAllowedToCalculate = source.IsAllowedToCalculate,
     163        Memory = source.Memory,
     164        Name = source.Name,
     165        SlaveState = source.SlaveState.ToDto(),
     166        CpuArchitecture = source.CpuArchitecture.ToDto(),
     167        OperatingSystem = source.OperatingSystem,
     168        LastHeartbeat = source.LastHeartbeat,
     169        CpuUtilization = source.CpuUtilization,
     170        HbInterval = source.HbInterval,
     171        IsDisposable = source.IsDisposable,
     172        OwnerUserId = source.OwnerUserId
     173      };
     174    }
     175    public static DA.Slave ToEntity(this DT.Slave source) {
     176      if (source == null) return null;
     177      var result = new DA.Slave();
     178      source.CopyToEntity(result);
     179      return result;
     180    }
     181    public static void CopyToEntity(this DT.Slave source, DA.Slave target) {
     182      if ((source == null) || (target == null)) return;
     183      target.ResourceId = source.Id;
     184      target.ParentResourceId = source.ParentResourceId;
     185      target.Cores = source.Cores;
     186      target.CpuSpeed = source.CpuSpeed;
     187      target.FreeCores = source.FreeCores;
     188      target.FreeMemory = source.FreeMemory;
     189      target.IsAllowedToCalculate = source.IsAllowedToCalculate;
     190      target.Memory = source.Memory;
     191      target.Name = source.Name;
     192      target.SlaveState = source.SlaveState.ToEntity();
     193      target.CpuArchitecture = source.CpuArchitecture.ToEntity();
     194      target.OperatingSystem = source.OperatingSystem;
     195      target.LastHeartbeat = source.LastHeartbeat;
     196      target.CpuUtilization = source.CpuUtilization;
     197      target.HbInterval = source.HbInterval;
     198      target.IsDisposable = source.IsDisposable;
     199      target.OwnerUserId = source.OwnerUserId;
     200    }
     201    #endregion
     202
    152203    #region State
    153204    public static DT.TaskState ToDto(this DA.TaskState source) {
     
    206257    #endregion
    207258
     259    #region Plugin
     260    public static DT.Plugin ToDto(this DA.Plugin source) {
     261      if (source == null) return null;
     262      return new DT.Plugin {
     263        Id = source.PluginId,
     264        Name = source.Name,
     265        Version = new Version(source.Version),
     266        UserId = source.UserId,
     267        DateCreated = source.DateCreated,
     268        Hash = source.Hash
     269      };
     270    }
     271    public static DA.Plugin ToEntity(this DT.Plugin source) {
     272      if (source == null) return null;
     273      var result = new DA.Plugin();
     274      source.CopyToEntity(result);
     275      return result;
     276    }
     277    public static void CopyToEntity(this DT.Plugin source, DA.Plugin target) {
     278      if ((source == null) || (target == null)) return;
     279      target.PluginId = source.Id;
     280      target.Name = source.Name;
     281      target.Version = source.Version.ToString();
     282      target.UserId = source.UserId;
     283      target.DateCreated = source.DateCreated;
     284      target.Hash = source.Hash;
     285    }
     286    #endregion
     287
     288    #region PluginData
     289    public static DT.PluginData ToDto(this DA.PluginData source) {
     290      if (source == null) return null;
     291      return new DT.PluginData {
     292        Id = source.PluginDataId,
     293        PluginId = source.PluginId,
     294        Data = source.Data.ToArray(),
     295        FileName = source.FileName
     296      };
     297    }
     298
     299    public static DA.PluginData ToEntity(this DT.PluginData source) {
     300      if (source == null) return null;
     301      var result = new DA.PluginData();
     302      source.CopyToEntity(result);
     303      return result;
     304    }
     305
     306    public static void CopyToEntity(this DT.PluginData source, DA.PluginData target) {
     307      if ((source == null) || (target == null)) return;
     308      target.PluginDataId = source.Id;
     309      target.PluginId = source.PluginId;
     310      target.Data = source.Data;
     311      target.FileName = source.FileName;
     312    }
     313    #endregion
     314
     315    #region ResourcePermission
     316    public static DT.ResourcePermission ToDto(this DA.ResourcePermission source) {
     317      if (source == null) return null;
     318      return new DT.ResourcePermission {
     319        ResourceId = source.ResourceId,
     320        GrantedUserId = source.GrantedUserId,
     321        GrantedByUserId = source.GrantedByUserId
     322      };
     323    }
     324    public static DA.ResourcePermission ToEntity(this DT.ResourcePermission source) {
     325      if (source == null) return null;
     326      var result = new DA.ResourcePermission();
     327      source.CopyToEntity(result);
     328      return result;
     329    }
     330    public static void CopyToEntity(this DT.ResourcePermission source, DA.ResourcePermission target) {
     331      if ((source == null) || (target == null)) return;
     332      target.ResourceId = source.ResourceId;
     333      target.GrantedUserId = source.GrantedUserId;
     334      target.GrantedByUserId = source.GrantedByUserId;
     335    }
     336    #endregion
     337
     338    #region SlaveGroup
     339    public static DT.SlaveGroup ToDto(this DA.SlaveGroup source) {
     340      if (source == null) return null;
     341      return new DT.SlaveGroup {
     342        Id = source.ResourceId,
     343        Name = source.Name,
     344        ParentResourceId = source.ParentResourceId,
     345        HbInterval = source.HbInterval,
     346        OwnerUserId = source.OwnerUserId
     347      };
     348    }
     349
     350    public static DA.SlaveGroup ToEntity(this DT.SlaveGroup source) {
     351      if (source == null) return null;
     352      var result = new DA.SlaveGroup();
     353      source.CopyToEntity(result);
     354      return result;
     355    }
     356
     357    public static void CopyToEntity(this DT.SlaveGroup source, DA.SlaveGroup target) {
     358      if ((source == null) || (target == null)) return;
     359      target.ResourceId = source.Id;
     360      target.Name = source.Name;
     361      target.ParentResourceId = source.ParentResourceId;
     362      target.HbInterval = source.HbInterval;
     363      target.OwnerUserId = source.OwnerUserId;
     364    }
     365    #endregion
     366
     367    #region Downtimes
     368    public static DT.Downtime ToDto(this DA.Downtime source) {
     369      if (source == null) return null;
     370      return new DT.Downtime {
     371        Id = source.DowntimeId,
     372        AllDayEvent = source.AllDayEvent,
     373        EndDate = source.EndDate,
     374        Recurring = source.Recurring,
     375        RecurringId = source.RecurringId,
     376        ResourceId = source.ResourceId,
     377        StartDate = source.StartDate,
     378        DowntimeType = source.DowntimeType
     379      };
     380    }
     381    public static DA.Downtime ToEntity(this DT.Downtime source) {
     382      if (source == null) return null;
     383      var result = new DA.Downtime();
     384      source.CopyToEntity(result);
     385      return result;
     386    }
     387    public static void CopyToEntity(this DT.Downtime source, DA.Downtime target) {
     388      if ((source == null) || (target == null)) return;
     389      target.DowntimeId = source.Id;
     390      target.AllDayEvent = source.AllDayEvent;
     391      target.EndDate = source.EndDate;
     392      target.Recurring = source.Recurring;
     393      target.RecurringId = source.RecurringId;
     394      target.ResourceId = source.ResourceId;
     395      target.StartDate = source.StartDate;
     396      target.DowntimeType = source.DowntimeType;
     397    }
     398    #endregion
     399
     400
    208401    #region Command
    209402    public static DT.Command? ToDto(this DA.Command? source) {
     
    252445    #endregion
    253446
     447    #region CpuArchiteture
     448    public static DT.CpuArchitecture ToDto(this DA.CpuArchitecture source) {
     449      switch (source) {
     450        case DA.CpuArchitecture.x64: return DT.CpuArchitecture.x64;
     451        case DA.CpuArchitecture.x86: return DT.CpuArchitecture.x86;
     452        default: return DT.CpuArchitecture.x86;
     453      }
     454    }
     455
     456    public static DA.CpuArchitecture ToEntity(this DT.CpuArchitecture source) {
     457      switch (source) {
     458        case DT.CpuArchitecture.x64: return DA.CpuArchitecture.x64;
     459        case DT.CpuArchitecture.x86: return DA.CpuArchitecture.x86;
     460        default: return DA.CpuArchitecture.x86;
     461      }
     462    }
     463    #endregion
     464
     465    #region SlaveState
     466    public static DT.SlaveState ToDto(this DA.SlaveState source) {
     467      switch (source) {
     468        case DA.SlaveState.Calculating: return DT.SlaveState.Calculating;
     469        case DA.SlaveState.Idle: return DT.SlaveState.Idle;
     470        case DA.SlaveState.Offline: return DT.SlaveState.Offline;
     471        default: return DT.SlaveState.Offline;
     472      }
     473    }
     474
     475    public static DA.SlaveState ToEntity(this DT.SlaveState source) {
     476      switch (source) {
     477        case DT.SlaveState.Calculating: return DA.SlaveState.Calculating;
     478        case DT.SlaveState.Idle: return DA.SlaveState.Idle;
     479        case DT.SlaveState.Offline: return DA.SlaveState.Offline;
     480        default: return DA.SlaveState.Offline;
     481      }
     482    }
     483    #endregion
     484
     485    #region UserPriority
     486    public static DT.UserPriority ToDto(this DA.UserPriority source) {
     487      if (source == null) return null;
     488      return new DT.UserPriority() {
     489        Id = source.UserId,
     490        DateEnqueued = source.DateEnqueued
     491      };
     492    }
     493    public static DA.UserPriority ToEntity(this DT.UserPriority source) {
     494      if (source == null) return null;
     495      var result = new DA.UserPriority();
     496      source.CopyToEntity(result);
     497      return result;
     498    }
     499    public static void CopyToEntity(this DT.UserPriority source, DA.UserPriority target) {
     500      if ((source == null) || (target == null)) return;
     501      target.UserId = source.Id;
     502      target.DateEnqueued = source.DateEnqueued;
     503    }
     504    #endregion
     505
    254506  }
    255507}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/HeuristicLab.Services.Hive-3.3.csproj

    r12584 r12691  
    146146    <Compile Include="HiveStatisticsGenerator.cs" />
    147147    <Compile Include="Interfaces\IStatisticsGenerator.cs" />
     148    <Compile Include="Manager\NewHeartbeatManager.cs" />
    148149    <Compile Include="NewHiveService.cs" />
    149150    <Compile Include="OptimizedHiveDao.cs" />
     
    154155    <Compile Include="Interfaces\IHiveDao.cs" />
    155156    <Compile Include="Interfaces\ITaskScheduler.cs" />
     157    <Compile Include="PerformanceLogger.cs" />
     158    <Compile Include="Scheduler\NewRoundRobinTaskScheduler.cs" />
    156159    <Compile Include="Scheduler\TaskInfoForScheduler.cs" />
    157160    <Compile Include="Scheduler\JobInfoForScheduler.cs" />
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/HiveService.cs

    r12584 r12691  
    6868    public Guid AddTask(Task task, TaskData taskData, IEnumerable<Guid> resourceIds) {
    6969      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    70       return trans.UseTransaction(() => {
    71         var t = DT.Convert.ToEntity(task);
    72         t.RequiredPlugins.AddRange(task.PluginsNeededIds.Select(pluginId => new DA.RequiredPlugin { Task = t, PluginId = pluginId }));
    73 
    74         t.JobData = DT.Convert.ToEntity(taskData);
    75         t.JobData.LastUpdate = DateTime.Now;
    76 
    77         optimizedDao.AddTask(t);
    78 
    79         dao.AssignJobToResource(t.TaskId, resourceIds);
    80 
    81         optimizedDao.UpdateTaskState(t.TaskId, DA.TaskState.Waiting, null, userManager.CurrentUserId, null);
    82 
    83         return t.TaskId;
    84       }, false, true);
     70      using (new PerformanceLogger("Old_AddTask")) {
     71        return trans.UseTransaction(() => {
     72          var t = DT.Convert.ToEntity(task);
     73          t.RequiredPlugins.AddRange(task.PluginsNeededIds.Select(pluginId => new DA.RequiredPlugin { Task = t, PluginId = pluginId }));
     74
     75          t.JobData = DT.Convert.ToEntity(taskData);
     76          t.JobData.LastUpdate = DateTime.Now;
     77
     78          optimizedDao.AddTask(t);
     79
     80          dao.AssignJobToResource(t.TaskId, resourceIds);
     81
     82          optimizedDao.UpdateTaskState(t.TaskId, DA.TaskState.Waiting, null, userManager.CurrentUserId, null);
     83
     84          return t.TaskId;
     85        }, false, true);
     86      }
    8587    }
    8688
     
    8890      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    8991      task.ParentTaskId = parentTaskId;
    90       return AddTask(task, taskData, optimizedDao.GetAssignedResourceIds(parentTaskId).ToList());
     92      List<Guid> list = null;
     93      using (new PerformanceLogger("Old_AddChildTask")) {
     94        list = optimizedDao.GetAssignedResourceIds(parentTaskId).ToList();
     95      }
     96      return AddTask(task, taskData, list);
    9197    }
    9298
     
    94100      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    95101      author.AuthorizeForTask(taskId, Permission.Read);
    96       return trans.UseTransaction(() => {
    97         return DT.Convert.ToDto(optimizedDao.GetTaskById(taskId));
    98       }, false, false);
     102      using (new PerformanceLogger("Old_GetTask")) {
     103        return trans.UseTransaction(() => {
     104          return DT.Convert.ToDto(optimizedDao.GetTaskById(taskId));
     105        }, false, false);
     106      }
    99107    }
    100108
     
    134142      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    135143      author.AuthorizeForJob(jobId, Permission.Read);
    136 
    137       return trans.UseTransaction(() => {
    138         return optimizedDao.GetLightweightTasks(jobId).ToArray();
    139       }, false, true);
     144      using (new PerformanceLogger("Old_GetLightweightJobTasks")) {
     145        return trans.UseTransaction(() => {
     146          return optimizedDao.GetLightweightTasks(jobId).ToArray();
     147        }, false, true);
     148      }
    140149    }
    141150
     
    143152      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    144153      author.AuthorizeForJob(jobId, Permission.Read);
    145 
    146       return trans.UseTransaction(() => {
    147         return dao.GetLightweightTasksWithoutStateLog(task => task.JobId == jobId).ToArray();
    148       }, false, false);
     154      using (new PerformanceLogger("Old_GetLightweightJobTasksWithoutStateLog")) {
     155        return trans.UseTransaction(() => {
     156          return dao.GetLightweightTasksWithoutStateLog(task => task.JobId == jobId).ToArray();
     157        }, false, false);
     158      }
    149159    }
    150160
     
    153163      author.AuthorizeForTask(taskId, Permission.Read);
    154164
    155       return trans.UseTransaction(() => {
    156         return dao.GetTaskData(taskId);
    157       });
     165      using (new PerformanceLogger("Old_GetTaskData")) {
     166        return trans.UseTransaction(() => {
     167          return dao.GetTaskData(taskId);
     168        });
     169      }
    158170    }
    159171
     
    162174      author.AuthorizeForTask(taskDto.Id, Permission.Full);
    163175
    164       trans.UseTransaction(() => {
    165         var task = optimizedDao.GetTaskByDto(taskDto);
    166         optimizedDao.UpdateTask(task);
    167       });
     176      using (new PerformanceLogger("Old_UpdateTask")) {
     177        trans.UseTransaction(() => {
     178          var task = optimizedDao.GetTaskByDto(taskDto);
     179          optimizedDao.UpdateTask(task);
     180        });
     181      }
    168182    }
    169183
     
    172186      author.AuthorizeForTask(task.Id, Permission.Full);
    173187
    174       trans.UseTransaction(() => {
    175         var t = optimizedDao.GetTaskByDto(task);
    176         optimizedDao.UpdateTask(t);
    177       });
    178 
    179       trans.UseTransaction(() => {
    180         var data = optimizedDao.GetTaskDataByDto(taskData);
    181         data.LastUpdate = DateTime.Now;
    182         optimizedDao.UpdateTaskData(data);
    183       });
     188      using (new PerformanceLogger("Old_UpdateTaskData")) {
     189        trans.UseTransaction(() => {
     190          var t = optimizedDao.GetTaskByDto(task);
     191          optimizedDao.UpdateTask(t);
     192        });
     193
     194        trans.UseTransaction(() => {
     195          var data = optimizedDao.GetTaskDataByDto(taskData);
     196          data.LastUpdate = DateTime.Now;
     197          optimizedDao.UpdateTaskData(data);
     198        });
     199      }
    184200    }
    185201
     
    207223      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    208224      author.AuthorizeForTask(taskId, Permission.Full);
    209 
    210       return trans.UseTransaction(() => {
    211         var task = optimizedDao.UpdateTaskState(taskId, DT.Convert.ToEntity(taskState), slaveId, userId, exception);
    212 
    213         if (task.Command.HasValue && task.Command.Value == DA.Command.Pause && task.State == DA.TaskState.Paused) {
    214           task.Command = null;
    215         } else if (task.Command.HasValue && task.Command.Value == DA.Command.Abort && task.State == DA.TaskState.Aborted) {
    216           task.Command = null;
    217         } else if (task.Command.HasValue && task.Command.Value == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
    218           task.Command = null;
    219         } else if (taskState == TaskState.Paused && !task.Command.HasValue) {
    220           // slave paused and uploaded the task (no user-command) -> set waiting.
    221           task = optimizedDao.UpdateTaskState(taskId, DA.TaskState.Waiting, slaveId, userId, exception);
    222         }
    223 
    224         return DT.Convert.ToDto(task);
    225       });
     225      using (new PerformanceLogger("Old_UpdateTaskState")) {
     226        return trans.UseTransaction(() => {
     227          var task = optimizedDao.UpdateTaskState(taskId, DT.Convert.ToEntity(taskState), slaveId, userId, exception);
     228
     229          if (task.Command.HasValue && task.Command.Value == DA.Command.Pause && task.State == DA.TaskState.Paused) {
     230            task.Command = null;
     231          } else if (task.Command.HasValue && task.Command.Value == DA.Command.Abort && task.State == DA.TaskState.Aborted) {
     232            task.Command = null;
     233          } else if (task.Command.HasValue && task.Command.Value == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
     234            task.Command = null;
     235          } else if (taskState == TaskState.Paused && !task.Command.HasValue) {
     236            // slave paused and uploaded the task (no user-command) -> set waiting.
     237            task = optimizedDao.UpdateTaskState(taskId, DA.TaskState.Waiting, slaveId, userId, exception);
     238          }
     239
     240          return DT.Convert.ToDto(task);
     241        });
     242      }
    226243    }
    227244
     
    281298      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    282299      author.AuthorizeForJob(id, Permission.Read);
    283       return trans.UseTransaction(() => {
    284         var job = dao.GetJobs(x =>
    285               x.JobId == id
    286               && (x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0)
    287             ).FirstOrDefault();
    288         if (job != null) {
    289           job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
    290           job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
    291         }
    292         return job;
    293       });
     300      using (new PerformanceLogger("Old_GetJob")) {
     301        return trans.UseTransaction(() => {
     302          var job = dao.GetJobs(x =>
     303                x.JobId == id
     304                && (x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0)
     305              ).FirstOrDefault();
     306          if (job != null) {
     307            job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
     308            job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
     309          }
     310          return job;
     311        });
     312      }
    294313    }
    295314
    296315    public IEnumerable<Job> GetJobs() {
    297316      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    298       return trans.UseTransaction(() => {
    299         var jobs = dao.GetJobs(x => x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0);
    300         foreach (var job in jobs) {
    301           author.AuthorizeForJob(job.Id, Permission.Read);
    302           job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
    303           job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
    304         }
    305         return jobs;
    306       });
     317      using (new PerformanceLogger("Old_GetJobs")) {
     318        return trans.UseTransaction(() => {
     319          var jobs = dao.GetJobs(x => x.OwnerUserId == userManager.CurrentUserId || x.JobPermissions.Count(hep => hep.Permission != DA.Permission.NotAllowed && hep.GrantedUserId == userManager.CurrentUserId) > 0);
     320          foreach (var job in jobs) {
     321            author.AuthorizeForJob(job.Id, Permission.Read);
     322            job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
     323            job.OwnerUsername = userManager.GetUserById(job.OwnerUserId).UserName;
     324          }
     325          return jobs;
     326        });
     327      }
    307328    }
    308329
     
    321342    public Guid AddJob(Job jobDto) {
    322343      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    323       return trans.UseTransaction(() => {
    324         jobDto.OwnerUserId = userManager.CurrentUserId;
    325         jobDto.DateCreated = DateTime.Now;
    326         return dao.AddJob(jobDto);
    327       });
     344      using (new PerformanceLogger("Old_AddJob")) {
     345        return trans.UseTransaction(() => {
     346          jobDto.OwnerUserId = userManager.CurrentUserId;
     347          jobDto.DateCreated = DateTime.Now;
     348          return dao.AddJob(jobDto);
     349        });
     350      }
    328351    }
    329352
     
    370393    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
    371394      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    372       return trans.UseTransaction(() => {
    373         DA.Permission currentUserPermission = dao.GetPermissionForJob(jobId, userManager.CurrentUserId);
    374         if (currentUserPermission != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to list permissions for this experiment"));
    375         return dao.GetJobPermissions(x => x.JobId == jobId);
    376       });
     395      using (new PerformanceLogger("GetJobPermissions")) {
     396        return trans.UseTransaction(() => {
     397          DA.Permission currentUserPermission = dao.GetPermissionForJob(jobId, userManager.CurrentUserId);
     398          if (currentUserPermission != DA.Permission.Full)
     399            throw new FaultException<FaultReason>(new FaultReason("Not allowed to list permissions for this experiment"));
     400          return dao.GetJobPermissions(x => x.JobId == jobId);
     401        });
     402      }
    377403    }
    378404
     
    389415        slaveInfo.OwnerUserId = userManager.CurrentUserId;
    390416
    391       trans.UseTransaction(() => {
    392         var slave = dao.GetSlave(slaveInfo.Id);
    393 
    394         if (slave == null) {
    395           dao.AddSlave(slaveInfo);
    396         } else {
    397           slave.Name = slaveInfo.Name;
    398           slave.Description = slaveInfo.Description;
    399           slave.OwnerUserId = slaveInfo.OwnerUserId;
    400 
    401           slave.Cores = slaveInfo.Cores;
    402           slave.CpuArchitecture = slaveInfo.CpuArchitecture;
    403           slave.CpuSpeed = slaveInfo.CpuSpeed;
    404           slave.FreeCores = slaveInfo.FreeCores;
    405           slave.FreeMemory = slaveInfo.FreeMemory;
    406           slave.Memory = slaveInfo.Memory;
    407           slave.OperatingSystem = slaveInfo.OperatingSystem;
    408 
    409           slave.LastHeartbeat = DateTime.Now;
    410           slave.SlaveState = SlaveState.Idle;
    411 
    412           // don't update those properties: dbSlave.IsAllowedToCalculate, dbSlave.ParentResourceId
    413 
    414           dao.UpdateSlave(slave);
    415         }
    416       });
     417      using (new PerformanceLogger("Old_Hello")) {
     418        trans.UseTransaction(() => {
     419          var slave = dao.GetSlave(slaveInfo.Id);
     420
     421          if (slave == null) {
     422            dao.AddSlave(slaveInfo);
     423          } else {
     424            slave.Name = slaveInfo.Name;
     425            slave.Description = slaveInfo.Description;
     426            slave.OwnerUserId = slaveInfo.OwnerUserId;
     427
     428            slave.Cores = slaveInfo.Cores;
     429            slave.CpuArchitecture = slaveInfo.CpuArchitecture;
     430            slave.CpuSpeed = slaveInfo.CpuSpeed;
     431            slave.FreeCores = slaveInfo.FreeCores;
     432            slave.FreeMemory = slaveInfo.FreeMemory;
     433            slave.Memory = slaveInfo.Memory;
     434            slave.OperatingSystem = slaveInfo.OperatingSystem;
     435
     436            slave.LastHeartbeat = DateTime.Now;
     437            slave.SlaveState = SlaveState.Idle;
     438
     439            // don't update those properties: dbSlave.IsAllowedToCalculate, dbSlave.ParentResourceId
     440
     441            dao.UpdateSlave(slave);
     442          }
     443        });
     444      }
    417445    }
    418446
    419447    public void GoodBye(Guid slaveId) {
    420448      authen.AuthenticateForAnyRole(HiveRoles.Slave);
    421       trans.UseTransaction(() => {
    422         var slave = dao.GetSlave(slaveId);
    423         if (slave != null) {
    424           slave.SlaveState = SlaveState.Offline;
    425           dao.UpdateSlave(slave);
    426         }
    427       });
     449      using (new PerformanceLogger("Old_GoodBye")) {
     450        trans.UseTransaction(() => {
     451          var slave = dao.GetSlave(slaveId);
     452          if (slave != null) {
     453            slave.SlaveState = SlaveState.Offline;
     454            dao.UpdateSlave(slave);
     455          }
     456        });
     457      }
    428458    }
    429459    #endregion
     
    435465      List<MessageContainer> result = new List<MessageContainer>();
    436466      try {
    437         result = heartbeatManager.ProcessHeartbeat(heartbeat);
     467        using (new PerformanceLogger("Old_ProcessHeartbeat")) {
     468          result = heartbeatManager.ProcessHeartbeat(heartbeat);
     469        }
    438470      }
    439471      catch (Exception ex) {
    440472        DA.LogFactory.GetLogger(this.GetType().Namespace).Log("Exception processing Heartbeat: " + ex.ToString());
    441473      }
    442 
    443474      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
    444475        TriggerEventManager(false);
     
    489520    public IEnumerable<Plugin> GetPlugins() {
    490521      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    491       return trans.UseTransaction(() => {
    492         return dao.GetPlugins(x => x.Hash != null);
    493       });
     522      using (new PerformanceLogger("Old_GetPlugins")) {
     523        return trans.UseTransaction(() => {
     524          return dao.GetPlugins(x => x.Hash != null);
     525        });
     526      }
    494527    }
    495528
     
    497530      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    498531      var pluginDatas = new List<PluginData>();
    499       return trans.UseTransaction(() => {
    500         foreach (Guid guid in pluginIds) {
    501           pluginDatas.AddRange(dao.GetPluginDatas(x => x.PluginId == guid).ToList());
    502         }
    503         return pluginDatas;
    504       });
     532      using (new PerformanceLogger("Old_GetPluginData")) {
     533        return trans.UseTransaction(() => {
     534          foreach (Guid guid in pluginIds) {
     535            pluginDatas.AddRange(dao.GetPluginDatas(x => x.PluginId == guid).ToList());
     536          }
     537          return pluginDatas;
     538        });
     539      }
    505540    }
    506541
     
    654689    public Guid GetResourceId(string resourceName) {
    655690      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    656       return trans.UseTransaction(() => {
    657         var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
    658         if (resource != null) {
    659           return resource.Id;
    660         } else {
    661           return Guid.Empty;
    662         }
    663       });
     691      using (new PerformanceLogger("Old_GetResourceId")) {
     692        return trans.UseTransaction(() => {
     693          var resource = dao.GetResources(x => x.Name == resourceName).FirstOrDefault();
     694          if (resource != null) {
     695            return resource.Id;
     696          } else {
     697            return Guid.Empty;
     698          }
     699        });
     700      }
    664701    }
    665702
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/Interfaces/IServiceLocator.cs

    r12468 r12691  
    2020#endregion
    2121
    22 using HeuristicLab.Services.Hive.DataAccess;
    2322using HeuristicLab.Services.Hive.DataAccess.Interfaces;
     23using HeuristicLab.Services.Hive.Manager;
    2424
    2525namespace HeuristicLab.Services.Hive {
     
    3434    ITransactionManager TransactionManager { get; }
    3535    Access.IUserManager UserManager { get; }
     36    NewHeartbeatManager NewHeartbeatManager { get; }
    3637    HeartbeatManager HeartbeatManager { get; }
    3738    ITaskScheduler TaskScheduler { get; }
     39    ITaskScheduler NewTaskScheduler { get; }
    3840  }
    3941}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/Manager/AuthorizationManager.cs

    r12012 r12691  
    2222using System;
    2323using System.Security;
     24using HeuristicLab.Services.Access;
    2425using HeuristicLab.Services.Hive.DataAccess;
     26using HeuristicLab.Services.Hive.DataAccess.Interfaces;
     27using DA = HeuristicLab.Services.Hive.DataAccess;
    2528using DT = HeuristicLab.Services.Hive.DataTransfer;
    2629
     
    2831namespace HeuristicLab.Services.Hive {
    2932  public class AuthorizationManager : IAuthorizationManager {
     33
     34    private const string NOT_AUTHORIZED = "Current user is not authorized to access the requested resource";
     35    private IPersistenceManager PersistenceManager {
     36      get { return ServiceLocator.Instance.PersistenceManager; }
     37    }
     38
     39    private IUserManager UserManager {
     40      get { return ServiceLocator.Instance.UserManager; }
     41    }
     42
     43    private IRoleVerifier RoleVerifier {
     44      get { return ServiceLocator.Instance.RoleVerifier; }
     45    }
     46
    3047    public void Authorize(Guid userId) {
    3148      if (userId != ServiceLocator.Instance.UserManager.CurrentUserId)
    32         throw new SecurityException("Current user is not authorized to access object");
     49        throw new SecurityException(NOT_AUTHORIZED);
    3350    }
    3451
    3552    public void AuthorizeForTask(Guid taskId, DT.Permission requiredPermission) {
    3653      if (ServiceLocator.Instance.RoleVerifier.IsInRole(HiveRoles.Slave)) return; // slave-users can access all tasks
    37 
    38       Permission permission = ServiceLocator.Instance.HiveDao.GetPermissionForTask(taskId, ServiceLocator.Instance.UserManager.CurrentUserId);
    39       if (permission == Permission.NotAllowed || (permission != DT.Convert.ToEntity(requiredPermission) && DT.Convert.ToEntity(requiredPermission) == Permission.Full))
    40         throw new SecurityException("Current user is not authorized to access task");
     54      using (var pm = PersistenceManager) {
     55        var taskDao = pm.TaskDao;
     56        pm.UseTransaction(() => {
     57          var task = taskDao.GetById(taskId);
     58          if (task == null) throw new SecurityException(NOT_AUTHORIZED);
     59          AuthorizeJob(pm, task.JobId, requiredPermission);
     60        });
     61      }
    4162    }
    4263
    4364    public void AuthorizeForJob(Guid jobId, DT.Permission requiredPermission) {
    44       Permission permission = ServiceLocator.Instance.HiveDao.GetPermissionForJob(jobId, ServiceLocator.Instance.UserManager.CurrentUserId);
    45       if (permission == Permission.NotAllowed || (permission != DT.Convert.ToEntity(requiredPermission) && DT.Convert.ToEntity(requiredPermission) == Permission.Full))
    46         throw new SecurityException("Current user is not authorized to access task");
     65      using (var pm = PersistenceManager) {
     66        pm.UseTransaction(() => {
     67          AuthorizeJob(pm, jobId, requiredPermission);
     68        });
     69      }
    4770    }
    4871
    4972    public void AuthorizeForResourceAdministration(Guid resourceId) {
    50       Resource resource = DT.Convert.ToEntity(ServiceLocator.Instance.HiveDao.GetResource(resourceId));
    51       if (resource.OwnerUserId != ServiceLocator.Instance.UserManager.CurrentUserId && !ServiceLocator.Instance.RoleVerifier.IsInRole(HiveRoles.Administrator))
    52         throw new SecurityException("Current user is not authorized to access resource");
     73      using (var pm = PersistenceManager) {
     74        var resourceDao = pm.ResourceDao;
     75        pm.UseTransaction(() => {
     76          var resource = resourceDao.GetById(resourceId);
     77          if (resource == null) throw new SecurityException(NOT_AUTHORIZED);
     78          if (resource.OwnerUserId != UserManager.CurrentUserId
     79              && !RoleVerifier.IsInRole(HiveRoles.Administrator)) {
     80            throw new SecurityException(NOT_AUTHORIZED);
     81          }
     82        });
     83      }
     84    }
     85
     86    private DA.Permission GetPermissionForJob(IPersistenceManager pm, Guid jobId, Guid userId) {
     87      var jobDao = pm.JobDao;
     88      var jobPermissionDao = pm.JobPermissionDao;
     89      var job = jobDao.GetById(jobId);
     90      if (job == null) return DA.Permission.NotAllowed;
     91      if (job.OwnerUserId == userId) return DA.Permission.Full;
     92      var jobPermission = jobPermissionDao.GetByJobAndUserId(jobId, userId);
     93      if (jobPermission == null) return DA.Permission.NotAllowed;
     94      return jobPermission.Permission;
     95    }
     96
     97    private void AuthorizeJob(IPersistenceManager pm, Guid jobId, DT.Permission requiredPermission) {
     98      var requiredPermissionEntity = requiredPermission.ToEntity();
     99      DA.Permission permission = GetPermissionForJob(pm, jobId, UserManager.CurrentUserId);
     100      if (permission == Permission.NotAllowed
     101          || ((permission != requiredPermissionEntity) && requiredPermissionEntity == Permission.Full)) {
     102        throw new SecurityException(NOT_AUTHORIZED);
     103      }
    53104    }
    54105  }
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/Manager/HeartbeatManager.cs

    r12468 r12691  
    4747    /// <returns>a list of actions the slave should do</returns>
    4848    public List<MessageContainer> ProcessHeartbeat(Heartbeat heartbeat) {
     49
    4950      List<MessageContainer> actions = new List<MessageContainer>();
    50 
    5151      Slave slave = null;
    5252      trans.UseTransaction(() => {
     
    6262          actions.Add(new MessageContainer(MessageContainer.MessageType.ShutdownComputer));
    6363        }
    64 
    6564        // update slave data
    6665        slave.FreeCores = heartbeat.FreeCores;
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/NewHiveService.cs

    r12584 r12691  
    1 using System;
     1#region License Information
     2/* HeuristicLab
     3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     4 *
     5 * This file is part of HeuristicLab.
     6 *
     7 * HeuristicLab is free software: you can redistribute it and/or modify
     8 * it under the terms of the GNU General Public License as published by
     9 * the Free Software Foundation, either version 3 of the License, or
     10 * (at your option) any later version.
     11 *
     12 * HeuristicLab is distributed in the hope that it will be useful,
     13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
     14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15 * GNU General Public License for more details.
     16 *
     17 * You should have received a copy of the GNU General Public License
     18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
     19 */
     20#endregion
     21
     22using System;
    223using System.Collections.Generic;
     24using System.Diagnostics;
    325using System.Linq;
     26using System.Runtime.CompilerServices;
     27using System.Security;
     28using System.ServiceModel;
    429using HeuristicLab.Services.Access;
    530using HeuristicLab.Services.Hive.DataAccess.Interfaces;
    631using HeuristicLab.Services.Hive.DataTransfer;
     32using HeuristicLab.Services.Hive.Manager;
    733using HeuristicLab.Services.Hive.ServiceContracts;
    834using DA = HeuristicLab.Services.Hive.DataAccess;
     
    1036
    1137namespace HeuristicLab.Services.Hive {
     38  /// <summary>
     39  /// Implementation of the Hive service (interface <see cref="IHiveService"/>).
     40  /// We need 'IgnoreExtensionDataObject' Attribute for the slave to work.
     41  /// </summary>
     42  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, IgnoreExtensionDataObject = true)]
     43  [HiveOperationContextBehavior]
    1244  public class NewHiveService : IHiveService {
    1345    private static readonly DA.TaskState[] CompletedStates = { DA.TaskState.Finished, DA.TaskState.Aborted, DA.TaskState.Failed };
     
    2860      get { return ServiceLocator.Instance.AuthorizationManager; }
    2961    }
    30 
     62    private IEventManager EventManager {
     63      get { return ServiceLocator.Instance.EventManager; }
     64    }
     65    private NewHeartbeatManager HeartbeatManager {
     66      get { return ServiceLocator.Instance.NewHeartbeatManager; }
     67    }
     68
     69    #region Task Methods
    3170    public Guid AddTask(DT.Task task, DT.TaskData taskData, IEnumerable<Guid> resourceIds) {
    3271      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    33       using (var pm = PersistenceManager) {
     72      using (var pm = PersistenceManager)
     73      using (new PerformanceLogger("AddTask")) {
    3474        var taskDao = pm.TaskDao;
    3575        var stateLogDao = pm.StateLogDao;
     
    62102      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    63103      IEnumerable<Guid> resourceIds;
    64       using (var pm = PersistenceManager) {
     104      using (var pm = PersistenceManager)
     105      using (new PerformanceLogger("AddChildTask")) {
    65106        var assignedResourceDao = pm.AssignedResourceDao;
    66107        resourceIds = pm.UseTransaction(() => {
     
    77118      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    78119      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
    79       using (var pm = PersistenceManager) {
     120      using (var pm = PersistenceManager)
     121      using (new PerformanceLogger("GetTask")) {
    80122        var taskDao = pm.TaskDao;
    81123        return pm.UseTransaction(() => {
     
    104146      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    105147      AuthorizationManager.AuthorizeForJob(jobId, Permission.Read);
    106       using (var pm = PersistenceManager) {
     148      using (var pm = PersistenceManager)
     149      using (new PerformanceLogger("GetLightweightJobTasks")) {
    107150        var taskDao = pm.TaskDao;
    108151        return pm.UseTransaction(() => {
    109152          return taskDao.GetByJobId(jobId)
     153            .ToList()
    110154            .Select(x => new DT.LightweightTask {
    111155              Id = x.TaskId,
     
    118162              Command = x.Command.ToDto(),
    119163              LastTaskDataUpdate = x.JobData.LastUpdate
    120             });
     164            })
     165            .ToList();
    121166        }, false, true);
    122167      }
     
    126171      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    127172      AuthorizationManager.AuthorizeForJob(jobId, Permission.Read);
    128       using (var pm = PersistenceManager) {
     173      using (var pm = PersistenceManager)
     174      using (new PerformanceLogger("GetLightweightJobTasksWithoutStateLog")) {
    129175        var taskDao = pm.TaskDao;
    130176        return pm.UseTransaction(() => {
    131177          return taskDao.GetByJobId(jobId)
     178            .ToList()
    132179            .Select(x => new DT.LightweightTask {
    133180              Id = x.TaskId,
     
    138185              Command = x.Command.ToDto(),
    139186              LastTaskDataUpdate = x.JobData.LastUpdate
    140             });
     187            })
     188            .ToList();
    141189        }, false, true);
    142190      }
     
    146194      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    147195      AuthorizationManager.AuthorizeForTask(taskId, Permission.Read);
    148       using (var pm = PersistenceManager) {
     196      using (var pm = PersistenceManager)
     197      using (new PerformanceLogger("GetTaskData")) {
    149198        var taskDataDao = pm.TaskDataDao;
    150199        return pm.UseTransaction(() => taskDataDao.GetById(taskId).ToDto());
     
    155204      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    156205      AuthorizationManager.AuthorizeForTask(taskDto.Id, Permission.Full);
    157       using (var pm = PersistenceManager) {
     206      using (var pm = PersistenceManager)
     207      using (new PerformanceLogger("UpdateTask")) {
    158208        var taskDao = pm.TaskDao;
    159209        pm.UseTransaction(() => {
     
    168218      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    169219      AuthorizationManager.AuthorizeForTask(taskDto.Id, Permission.Full);
    170       using (var pm = PersistenceManager) {
     220      using (var pm = PersistenceManager)
     221      using (new PerformanceLogger("UpdateTaskData")) {
    171222        var taskDao = pm.TaskDao;
    172223        var taskDataDao = pm.TaskDataDao;
     
    195246      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    196247      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
    197       using (var pm = PersistenceManager) {
     248      using (var pm = PersistenceManager)
     249      using (new PerformanceLogger("UpdateTaskState")) {
    198250        var taskDao = pm.TaskDao;
    199251        var stateLogDao = pm.StateLogDao;
     
    206258      }
    207259    }
    208 
    209     private void UpdateTaskState(IPersistenceManager pm, DA.Task task, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
    210       var stateLogDao = pm.StateLogDao;
    211       var taskStateEntity = taskState.ToEntity();
    212       if (task.Command == DA.Command.Pause && task.State == DA.TaskState.Paused
    213           || task.Command == DA.Command.Abort && task.State == DA.TaskState.Aborted
    214           || task.Command == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
    215         task.Command = null;
    216       } else if (taskStateEntity == DA.TaskState.Paused) {
    217         taskStateEntity = DA.TaskState.Waiting;
    218       }
    219       stateLogDao.Save(new DA.StateLog {
    220         State = taskStateEntity,
    221         DateTime = DateTime.Now,
    222         TaskId = task.TaskId,
    223         UserId = userId,
    224         SlaveId = slaveId,
    225         Exception = exception
    226       });
    227       task.State = taskStateEntity;
    228     }
    229 
     260    #endregion
     261
     262    #region Task Control Methods
    230263    public void StopTask(Guid taskId) {
    231264      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    232265      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
    233       using (var pm = PersistenceManager) {
     266      using (var pm = PersistenceManager)
     267      using (new PerformanceLogger("StopTask")) {
    234268        var taskDao = pm.TaskDao;
    235269        pm.UseTransaction(() => {
     
    250284      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    251285      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
    252       using (var pm = PersistenceManager) {
     286      using (var pm = PersistenceManager)
     287      using (new PerformanceLogger("PauseTask")) {
    253288        var taskDao = pm.TaskDao;
    254289        pm.UseTransaction(() => {
     
    256291          if (task.State == DA.TaskState.Calculating || task.State == DA.TaskState.Transferring) {
    257292            task.Command = DA.Command.Pause;
    258           } else {
    259             UpdateTaskState(pm, task, DT.TaskState.Paused, null, null, string.Empty);
    260           }
     293          }
     294          UpdateTaskState(pm, task, DT.TaskState.Paused, null, null, string.Empty);
    261295          pm.SubmitChanges();
    262296        });
     
    267301      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
    268302      AuthorizationManager.AuthorizeForTask(taskId, Permission.Full);
    269       using (var pm = PersistenceManager) {
     303      using (var pm = PersistenceManager)
     304      using (new PerformanceLogger("RestartTask")) {
    270305        var taskDao = pm.TaskDao;
    271306        pm.UseTransaction(() => {
     
    277312      }
    278313    }
    279 
    280 
    281     public Job GetJob(Guid id) {
    282       RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
    283       AuthorizationManager.AuthorizeForJob(id, Permission.Read);
    284       using (var pm = PersistenceManager) {
     314    #endregion
     315
     316    #region Job Methods
     317    public DT.Job GetJob(Guid id) {
     318      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     319      AuthorizationManager.AuthorizeForJob(id, DT.Permission.Read);
     320      using (var pm = PersistenceManager)
     321      using (new PerformanceLogger("GetJob")) {
    285322        var jobDao = pm.JobDao;
    286323        var jobPermissionDao = pm.JobPermissionDao;
    287324        var taskDao = pm.TaskDao;
     325        var currentUserId = UserManager.CurrentUserId;
    288326        return pm.UseTransaction(() => {
    289327          var job = jobDao.GetById(id).ToDto();
     
    301339              job.FinishedCount = statistics.FinishedCount;
    302340            }
    303             // TODO
    304             //job.Permission = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
    305341            job.OwnerUsername = UserManager.GetUserById(job.OwnerUserId).UserName;
     342            if (currentUserId == job.OwnerUserId) {
     343              job.Permission = Permission.Full;
     344            } else {
     345              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
     346              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
     347            }
    306348          }
    307349          return job;
     
    310352    }
    311353
    312     public IEnumerable<Job> GetJobs() {
    313       throw new NotImplementedException();
     354    public IEnumerable<DT.Job> GetJobs() {
     355      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     356      using (var pm = PersistenceManager)
     357      using (new PerformanceLogger("GetJobs")) {
     358        var jobDao = pm.JobDao;
     359        var jobPermissionDao = pm.JobPermissionDao;
     360        var taskDao = pm.TaskDao;
     361        var currentUserId = UserManager.CurrentUserId;
     362        return pm.UseTransaction(() => {
     363          var jobs = jobDao.GetAll()
     364            .Where(x => x.OwnerUserId == currentUserId
     365                     || x.JobPermissions.Count(y => y.Permission != DA.Permission.NotAllowed
     366                                                 && y.GrantedUserId == currentUserId) > 0)
     367            .Select(x => x.ToDto())
     368            .ToList();
     369          var statistics = taskDao.GetAll()
     370              .GroupBy(x => x.JobId)
     371              .Select(x => new {
     372                x.Key,
     373                TotalCount = x.Count(),
     374                CalculatingCount = x.Count(y => y.State == DA.TaskState.Calculating),
     375                FinishedCount = x.Count(y => CompletedStates.Contains(y.State))
     376              })
     377              .ToList();
     378          foreach (var job in jobs) {
     379            // TODO: improve performance of authorization (batch authorization)
     380            AuthorizationManager.AuthorizeForJob(job.Id, DT.Permission.Read);
     381            var statistic = statistics.FirstOrDefault(x => x.Key == job.Id);
     382            if (statistic != null) {
     383              job.JobCount = statistic.TotalCount;
     384              job.CalculatingCount = statistic.CalculatingCount;
     385              job.FinishedCount = statistic.FinishedCount;
     386            }
     387            job.OwnerUsername = UserManager.GetUserById(job.OwnerUserId).UserName;
     388            if (currentUserId == job.OwnerUserId) {
     389              job.Permission = Permission.Full;
     390            } else {
     391              var jobPermission = jobPermissionDao.GetByJobAndUserId(job.Id, currentUserId);
     392              job.Permission = jobPermission == null ? Permission.NotAllowed : jobPermission.Permission.ToDto();
     393            }
     394          }
     395          return jobs;
     396        });
     397      }
    314398    }
    315399
     
    320404
    321405    public Guid AddJob(Job jobDto) {
    322       throw new NotImplementedException();
    323     }
    324 
    325     public void UpdateJob(Job jobDto) {
    326       throw new NotImplementedException();
    327     }
    328 
    329     public void DeleteJob(Guid JobId) {
    330       throw new NotImplementedException();
    331     }
    332 
    333     public void GrantPermission(Guid jobId, Guid grantedUserId, Permission permission) {
    334       throw new NotImplementedException();
    335     }
    336 
    337     public void RevokePermission(Guid hiveExperimentId, Guid grantedUserId) {
    338       throw new NotImplementedException();
     406      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     407      using (var pm = PersistenceManager)
     408      using (new PerformanceLogger("AddJob")) {
     409        var jobDao = pm.JobDao;
     410        return pm.UseTransaction(() => {
     411          jobDto.OwnerUserId = UserManager.CurrentUserId;
     412          jobDto.DateCreated = DateTime.Now;
     413          var job = jobDao.Save(jobDto.ToEntity());
     414          pm.SubmitChanges();
     415          return job.JobId;
     416        });
     417      }
     418    }
     419
     420    public void UpdateJob(DT.Job jobDto) {
     421      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     422      AuthorizationManager.AuthorizeForJob(jobDto.Id, DT.Permission.Full);
     423      using (var pm = PersistenceManager)
     424      using (new PerformanceLogger("UpdateJob")) {
     425        bool exists = true;
     426        var jobDao = pm.JobDao;
     427        pm.UseTransaction(() => {
     428          var job = jobDao.GetById(jobDto.Id);
     429          if (job == null) {
     430            exists = false;
     431            job = new DA.Job();
     432          }
     433          jobDto.CopyToEntity(job);
     434          if (!exists) {
     435            jobDao.Save(job);
     436          }
     437          pm.SubmitChanges();
     438        });
     439      }
     440    }
     441
     442    public void DeleteJob(Guid jobId) {
     443      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     444      AuthorizationManager.AuthorizeForJob(jobId, DT.Permission.Full);
     445      using (var pm = PersistenceManager)
     446      using (new PerformanceLogger("DeleteJob")) {
     447        var jobDao = pm.JobDao;
     448        pm.UseTransaction(() => {
     449          jobDao.Delete(jobId);
     450          pm.SubmitChanges();
     451        });
     452      }
     453    }
     454    #endregion
     455
     456    #region JobPermission Methods
     457    public void GrantPermission(Guid jobId, Guid grantedUserId, DT.Permission permission) {
     458      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     459      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
     460      using (var pm = PersistenceManager)
     461      using (new PerformanceLogger("GrantPermission")) {
     462        var jobPermissionDao = pm.JobPermissionDao;
     463        var currentUserId = UserManager.CurrentUserId;
     464        pm.UseTransaction(() => {
     465          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, permission.ToEntity());
     466          pm.SubmitChanges();
     467        });
     468      }
     469    }
     470
     471    public void RevokePermission(Guid jobId, Guid grantedUserId) {
     472      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     473      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
     474      using (var pm = PersistenceManager)
     475      using (new PerformanceLogger("RevokePermission")) {
     476        var jobPermissionDao = pm.JobPermissionDao;
     477        var currentUserId = UserManager.CurrentUserId;
     478        pm.UseTransaction(() => {
     479          jobPermissionDao.SetJobPermission(jobId, currentUserId, grantedUserId, DA.Permission.NotAllowed);
     480          pm.SubmitChanges();
     481        });
     482      }
    339483    }
    340484
    341485    public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
    342       throw new NotImplementedException();
     486      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     487      AuthorizationManager.AuthorizeForJob(jobId, Permission.Full);
     488      using (var pm = PersistenceManager)
     489      using (new PerformanceLogger("GetJobPermissions")) {
     490        var jobPermissionDao = pm.JobPermissionDao;
     491        return pm.UseTransaction(() => jobPermissionDao.GetByJobId(jobId)
     492          .Select(x => x.ToDto())
     493          .ToList()
     494        );
     495      }
    343496    }
    344497
    345498    public bool IsAllowedPrivileged() {
    346       throw new NotImplementedException();
    347     }
    348 
    349     public void Hello(Slave slave) {
    350       throw new NotImplementedException();
     499      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     500      return RoleVerifier.IsInRole(HiveRoles.IsAllowedPrivileged);
     501    }
     502    #endregion
     503
     504    #region Login Methods
     505    public void Hello(DT.Slave slaveInfo) {
     506      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
     507      if (UserManager.CurrentUser.UserName != "hiveslave") {
     508        slaveInfo.OwnerUserId = UserManager.CurrentUserId;
     509      }
     510      using (var pm = PersistenceManager)
     511      using (new PerformanceLogger("Hello")) {
     512        var slaveDao = pm.SlaveDao;
     513        pm.UseTransaction(() => {
     514          var slave = slaveDao.GetById(slaveInfo.Id);
     515          if (slave == null) {
     516            slaveDao.Save(slaveInfo.ToEntity());
     517          } else {
     518            bool oldIsAllowedToCalculate = slave.IsAllowedToCalculate;
     519            Guid? oldParentResourceId = slave.ParentResourceId;
     520            slaveInfo.CopyToEntity(slave);
     521            slave.IsAllowedToCalculate = oldIsAllowedToCalculate;
     522            slave.ParentResourceId = oldParentResourceId;
     523            slave.LastHeartbeat = DateTime.Now;
     524            slave.SlaveState = DA.SlaveState.Idle;
     525          }
     526          pm.SubmitChanges();
     527        });
     528      }
    351529    }
    352530
    353531    public void GoodBye(Guid slaveId) {
    354       throw new NotImplementedException();
    355     }
    356 
     532      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
     533      using (var pm = PersistenceManager)
     534      using (new PerformanceLogger("GoodBye")) {
     535        var slaveDao = pm.SlaveDao;
     536        pm.UseTransaction(() => {
     537          var slave = slaveDao.GetById(slaveId);
     538          if (slave != null) {
     539            slave.SlaveState = DA.SlaveState.Offline;
     540            pm.SubmitChanges();
     541          }
     542        });
     543      }
     544    }
     545    #endregion
     546
     547    #region Heartbeat Methods
    357548    public List<MessageContainer> Heartbeat(Heartbeat heartbeat) {
    358       throw new NotImplementedException();
    359     }
    360 
     549      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
     550      List<MessageContainer> result = new List<MessageContainer>();
     551      try {
     552        using (new PerformanceLogger("ProcessHeartbeat")) {
     553          result = HeartbeatManager.ProcessHeartbeat(heartbeat);
     554        }
     555      }
     556      catch (Exception ex) {
     557        DA.LogFactory.GetLogger(this.GetType().Namespace).Log(string.Format("Exception processing Heartbeat: {0}", ex));
     558      }
     559      if (HeuristicLab.Services.Hive.Properties.Settings.Default.TriggerEventManagerInHeartbeat) {
     560        TriggerEventManager(false);
     561      }
     562      return result;
     563    }
     564    #endregion
     565
     566    #region Plugin Methods
    361567    public Plugin GetPlugin(Guid pluginId) {
    362       throw new NotImplementedException();
     568      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
     569      using (var pm = PersistenceManager)
     570      using (new PerformanceLogger("GetPlugin")) {
     571        var pluginDao = pm.PluginDao;
     572        return pm.UseTransaction(() => pluginDao.GetById(pluginId).ToDto());
     573      }
    363574    }
    364575
     
    369580
    370581    public Guid AddPlugin(Plugin plugin, List<PluginData> pluginData) {
    371       throw new NotImplementedException();
     582      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     583      using (var pm = PersistenceManager)
     584      using (new PerformanceLogger("AddPlugin")) {
     585        var pluginDao = pm.PluginDao;
     586        plugin.UserId = UserManager.CurrentUserId;
     587        plugin.DateCreated = DateTime.Now;
     588        return pm.UseTransaction(() => {
     589          var pluginEntity = pluginDao.GetByHash(plugin.Hash).SingleOrDefault();
     590          if (pluginEntity != null) {
     591            throw new FaultException<PluginAlreadyExistsFault>(new PluginAlreadyExistsFault(pluginEntity.PluginId));
     592          }
     593          pluginEntity = plugin.ToEntity();
     594          foreach (var data in pluginData) {
     595            data.PluginId = default(Guid);
     596            pluginEntity.PluginData.Add(data.ToEntity());
     597          }
     598          pluginDao.Save(pluginEntity);
     599          pm.SubmitChanges();
     600          return pluginEntity.PluginId;
     601        });
     602      }
    372603    }
    373604
    374605    public IEnumerable<Plugin> GetPlugins() {
    375       throw new NotImplementedException();
     606      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
     607      using (var pm = PersistenceManager)
     608      using (new PerformanceLogger("GetPlugins")) {
     609        var pluginDao = pm.PluginDao;
     610        return pm.UseTransaction(() => pluginDao.GetAll()
     611          .Where(x => x.Hash != null)
     612          .Select(x => x.ToDto())
     613          .ToList()
     614        );
     615      }
    376616    }
    377617
    378618    public IEnumerable<PluginData> GetPluginDatas(List<Guid> pluginIds) {
    379       throw new NotImplementedException();
     619      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
     620      using (var pm = PersistenceManager)
     621      using (new PerformanceLogger("GetPluginDatas")) {
     622        var pluginDataDao = pm.PluginDataDao;
     623        return pm.UseTransaction(() => pluginDataDao.GetAll()
     624            .Where(x => pluginIds.Contains(x.PluginId))
     625            .Select(x => x.ToDto())
     626            .ToList()
     627        );
     628      }
    380629    }
    381630
     
    384633      throw new NotImplementedException();
    385634    }
    386 
     635    #endregion
     636
     637    #region ResourcePermission Methods
    387638    public void GrantResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
    388       throw new NotImplementedException();
     639      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     640      using (var pm = PersistenceManager)
     641      using (new PerformanceLogger("GrantResourcePermissions")) {
     642        pm.UseTransaction(() => {
     643          var resource = AuthorizeForResource(pm, resourceId);
     644          var resourcePermissions = resource.ResourcePermissions.ToList();
     645          foreach (var id in grantedUserIds) {
     646            if (resourcePermissions.All(x => x.GrantedUserId != id)) {
     647              resource.ResourcePermissions.Add(new DA.ResourcePermission {
     648                GrantedUserId = id,
     649                GrantedByUserId = UserManager.CurrentUserId
     650              });
     651            }
     652          }
     653          pm.SubmitChanges();
     654        });
     655      }
    389656    }
    390657
    391658    public void RevokeResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
    392       throw new NotImplementedException();
     659      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     660      using (var pm = PersistenceManager)
     661      using (new PerformanceLogger("RevokeResourcePermissions")) {
     662        var resourcePermissionDao = pm.ResourcePermissionDao;
     663        pm.UseTransaction(() => {
     664          AuthorizeForResource(pm, resourceId);
     665          resourcePermissionDao.DeleteByResourceAndGrantedUserId(resourceId, grantedUserIds);
     666        });
     667      }
    393668    }
    394669
    395670    public IEnumerable<ResourcePermission> GetResourcePermissions(Guid resourceId) {
    396       throw new NotImplementedException();
    397     }
    398 
     671      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     672      using (var pm = PersistenceManager)
     673      using (new PerformanceLogger("GetResourcePermissions")) {
     674        var resourcePermissionDao = pm.ResourcePermissionDao;
     675        return pm.UseTransaction(() => resourcePermissionDao.GetByResourceId(resourceId)
     676          .Select(x => x.ToDto())
     677          .ToList()
     678        );
     679      }
     680    }
     681    #endregion
     682
     683    #region Resource Methods
    399684    public IEnumerable<Resource> GetChildResources(Guid resourceId) {
    400685      // unused
    401686      throw new NotImplementedException();
    402687    }
    403 
    404     public Guid AddSlave(Slave slave) {
    405       throw new NotImplementedException();
    406     }
    407 
    408     public Guid AddSlaveGroup(SlaveGroup slaveGroup) {
    409       throw new NotImplementedException();
     688    #endregion
     689
     690    #region Slave Methods
     691    public Guid AddSlave(DT.Slave slaveDto) {
     692      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
     693      using (var pm = PersistenceManager)
     694      using (new PerformanceLogger("AddSlave")) {
     695        var slaveDao = pm.SlaveDao;
     696        return pm.UseTransaction(() => {
     697          var slave = slaveDao.Save(slaveDto.ToEntity());
     698          pm.SubmitChanges();
     699          return slave.ResourceId;
     700        });
     701      }
     702    }
     703
     704    public Guid AddSlaveGroup(DT.SlaveGroup slaveGroupDto) {
     705      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     706      using (var pm = PersistenceManager)
     707      using (new PerformanceLogger("AddSlaveGroup")) {
     708        var slaveGroupDao = pm.SlaveGroupDao;
     709        return pm.UseTransaction(() => {
     710          if (slaveGroupDto.Id == Guid.Empty) {
     711            slaveGroupDto.Id = Guid.NewGuid();
     712          }
     713          var slaveGroup = slaveGroupDao.Save(slaveGroupDto.ToEntity());
     714          pm.SubmitChanges();
     715          return slaveGroup.ResourceId;
     716        });
     717      }
    410718    }
    411719
    412720    public Slave GetSlave(Guid slaveId) {
    413       throw new NotImplementedException();
     721      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
     722      using (var pm = PersistenceManager)
     723      using (new PerformanceLogger("GetSlave")) {
     724        var slaveDao = pm.SlaveDao;
     725        return pm.UseTransaction(() => slaveDao.GetById(slaveId).ToDto());
     726      }
    414727    }
    415728
     
    420733
    421734    public IEnumerable<Slave> GetSlaves() {
    422       throw new NotImplementedException();
     735      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     736      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
     737      using (var pm = PersistenceManager)
     738      using (new PerformanceLogger("GetSlaves")) {
     739        var slaveDao = pm.SlaveDao;
     740        var resourcePermissionDao = pm.ResourcePermissionDao;
     741        var currentUserId = UserManager.CurrentUserId;
     742        return pm.UseTransaction(() => {
     743          var resourcePermissions = resourcePermissionDao.GetAll();
     744          return slaveDao.GetAll()
     745            .Where(x => isAdministrator
     746              || x.OwnerUserId == null
     747              || x.OwnerUserId == currentUserId
     748              || UserManager.VerifyUser(currentUserId, resourcePermissions
     749                  .Where(y => y.ResourceId == x.ResourceId)
     750                  .Select(z => z.GrantedUserId)
     751                  .ToList())
     752              )
     753            .Select(x => x.ToDto())
     754            .ToList();
     755        });
     756      }
    423757    }
    424758
    425759    public IEnumerable<SlaveGroup> GetSlaveGroups() {
    426       throw new NotImplementedException();
    427     }
    428 
    429     public void UpdateSlave(Slave slave) {
    430       throw new NotImplementedException();
    431     }
    432 
    433     public void UpdateSlaveGroup(SlaveGroup slaveGroup) {
    434       throw new NotImplementedException();
     760      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     761      bool isAdministrator = RoleVerifier.IsInRole(HiveRoles.Administrator);
     762      using (var pm = PersistenceManager)
     763      using (new PerformanceLogger("GetSlaveGroups")) {
     764        var slaveGroupDao = pm.SlaveGroupDao;
     765        var resourcePermissionDao = pm.ResourcePermissionDao;
     766        var currentUserId = UserManager.CurrentUserId;
     767        return pm.UseTransaction(() => {
     768          var resourcePermissions = resourcePermissionDao.GetAll();
     769          return slaveGroupDao.GetAll()
     770            .Where(x => isAdministrator
     771              || x.OwnerUserId == null
     772              || x.OwnerUserId == currentUserId
     773              || UserManager.VerifyUser(currentUserId, resourcePermissions
     774                  .Where(y => y.ResourceId == x.ResourceId)
     775                  .Select(z => z.GrantedUserId)
     776                  .ToList())
     777              )
     778            .Select(x => x.ToDto())
     779            .ToList();
     780        });
     781      }
     782    }
     783
     784    public void UpdateSlave(DT.Slave slaveDto) {
     785      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     786      using (var pm = PersistenceManager)
     787      using (new PerformanceLogger("UpdateSlave")) {
     788        var slaveDao = pm.SlaveDao;
     789        pm.UseTransaction(() => {
     790          var slave = slaveDao.GetById(slaveDto.Id);
     791          if (slave != null) {
     792            slaveDto.CopyToEntity(slave);
     793          } else {
     794            slaveDao.Save(slaveDto.ToEntity());
     795          }
     796          pm.SubmitChanges();
     797        });
     798      }
     799    }
     800
     801    public void UpdateSlaveGroup(DT.SlaveGroup slaveGroupDto) {
     802      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     803      using (var pm = PersistenceManager)
     804      using (new PerformanceLogger("UpdateSlaveGroup")) {
     805        var slaveGroupDao = pm.SlaveGroupDao;
     806        pm.UseTransaction(() => {
     807          var slaveGroup = slaveGroupDao.GetById(slaveGroupDto.Id);
     808          if (slaveGroup != null) {
     809            slaveGroupDto.CopyToEntity(slaveGroup);
     810          } else {
     811            slaveGroupDao.Save(slaveGroupDto.ToEntity());
     812          }
     813          pm.SubmitChanges();
     814        });
     815      }
    435816    }
    436817
    437818    public void DeleteSlave(Guid slaveId) {
    438       throw new NotImplementedException();
     819      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     820      AuthorizationManager.AuthorizeForResourceAdministration(slaveId);
     821      using (var pm = PersistenceManager)
     822      using (new PerformanceLogger("DeleteSlave")) {
     823        var slaveDao = pm.SlaveDao;
     824        pm.UseTransaction(() => {
     825          slaveDao.Delete(slaveId);
     826        });
     827      }
    439828    }
    440829
    441830    public void DeleteSlaveGroup(Guid slaveGroupId) {
    442       throw new NotImplementedException();
     831      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     832      AuthorizationManager.AuthorizeForResourceAdministration(slaveGroupId);
     833      using (var pm = PersistenceManager)
     834      using (new PerformanceLogger("DeleteSlaveGroup")) {
     835        var slaveGroupDao = pm.SlaveGroupDao;
     836        pm.UseTransaction(() => {
     837          slaveGroupDao.Delete(slaveGroupId);
     838        });
     839      }
    443840    }
    444841
    445842    public void AddResourceToGroup(Guid slaveGroupId, Guid resourceId) {
    446       throw new NotImplementedException();
     843      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
     844      using (var pm = PersistenceManager)
     845      using (new PerformanceLogger("AddResourceToGroup")) {
     846        var resourceDao = pm.ResourceDao;
     847        pm.UseTransaction(() => {
     848          var resource = resourceDao.GetById(resourceId);
     849          resource.ParentResourceId = slaveGroupId;
     850          pm.SubmitChanges();
     851        });
     852      }
    447853    }
    448854
    449855    public void RemoveResourceFromGroup(Guid slaveGroupId, Guid resourceId) {
    450       throw new NotImplementedException();
     856      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator);
     857      using (var pm = PersistenceManager)
     858      using (new PerformanceLogger("RemoveResourceFromGroup")) {
     859        var resourceDao = pm.ResourceDao;
     860        pm.UseTransaction(() => {
     861          var resource = resourceDao.GetById(resourceId);
     862          resource.ParentResourceId = null;
     863          pm.SubmitChanges();
     864        });
     865      }
    451866    }
    452867
    453868    public Guid GetResourceId(string resourceName) {
    454       throw new NotImplementedException();
     869      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     870      using (var pm = PersistenceManager)
     871      using (new PerformanceLogger("GetResourceId")) {
     872        var resourceDao = pm.ResourceDao;
     873        return pm.UseTransaction(() => {
     874          var resource = resourceDao.GetByName(resourceName);
     875          return resource != null ? resource.ResourceId : Guid.Empty;
     876        });
     877      }
    455878    }
    456879
     
    461884
    462885    public void TriggerEventManager(bool force) {
    463       // private method...
    464       throw new NotImplementedException();
     886      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Slave);
     887      // use a serializable transaction here to ensure not two threads execute this simultaniously (mutex-lock would not work since IIS may use multiple AppDomains)
     888      bool cleanup;
     889      using (var pm = PersistenceManager)
     890      using (new PerformanceLogger("TriggerEventManager")) {
     891        cleanup = false;
     892        var lifecycleDao = pm.LifecycleDao;
     893        pm.UseTransaction(() => {
     894          var lastLifecycle = lifecycleDao.GetLastLifecycle();
     895          DateTime lastCleanup = lastLifecycle != null ? lastLifecycle.LastCleanup : DateTime.MinValue;
     896          if (force || DateTime.Now - lastCleanup > HeuristicLab.Services.Hive.Properties.Settings.Default.CleanupInterval) {
     897            lifecycleDao.UpdateLifecycle();
     898            cleanup = true;
     899            pm.SubmitChanges();
     900          }
     901        }, true);
     902      }
     903      if (cleanup) {
     904        EventManager.Cleanup();
     905      }
    465906    }
    466907
    467908    public int GetNewHeartbeatInterval(Guid slaveId) {
    468       throw new NotImplementedException();
    469     }
    470 
    471     public Guid AddDowntime(Downtime downtime) {
    472       throw new NotImplementedException();
     909      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Slave);
     910      using (var pm = PersistenceManager)
     911      using (new PerformanceLogger("GetNewHeartbeatInterval")) {
     912        var slaveDao = pm.SlaveDao;
     913        return pm.UseTransaction(() => {
     914          var slave = slaveDao.GetById(slaveId);
     915          if (slave != null) {
     916            return slave.HbInterval;
     917          }
     918          return -1;
     919        });
     920      }
     921    }
     922    #endregion
     923
     924    #region Downtime Methods
     925    public Guid AddDowntime(DT.Downtime downtimeDto) {
     926      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     927      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
     928      using (var pm = PersistenceManager)
     929      using (new PerformanceLogger("AddDowntime")) {
     930        var downtimeDao = pm.DowntimeDao;
     931        return pm.UseTransaction(() => {
     932          var downtime = downtimeDao.Save(downtimeDto.ToEntity());
     933          pm.SubmitChanges();
     934          return downtime.ResourceId;
     935        });
     936      }
    473937    }
    474938
    475939    public void DeleteDowntime(Guid downtimeId) {
    476       throw new NotImplementedException();
    477     }
    478 
    479     public void UpdateDowntime(Downtime downtime) {
    480       throw new NotImplementedException();
     940      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     941      using (var pm = PersistenceManager)
     942      using (new PerformanceLogger("DeleteDowntime")) {
     943        var downtimeDao = pm.DowntimeDao;
     944        pm.UseTransaction(() => {
     945          downtimeDao.Delete(downtimeId);
     946          pm.SubmitChanges();
     947        });
     948      }
     949    }
     950
     951    public void UpdateDowntime(DT.Downtime downtimeDto) {
     952      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     953      AuthorizationManager.AuthorizeForResourceAdministration(downtimeDto.ResourceId);
     954      using (var pm = PersistenceManager)
     955      using (new PerformanceLogger("UpdateDowntime")) {
     956        var downtimeDao = pm.DowntimeDao;
     957        pm.UseTransaction(() => {
     958          var downtime = downtimeDao.GetById(downtimeDto.Id);
     959          if (downtime != null) {
     960            downtimeDto.CopyToEntity(downtime);
     961          } else {
     962            downtimeDao.Save(downtimeDto.ToEntity());
     963          }
     964          pm.SubmitChanges();
     965        });
     966      }
    481967    }
    482968
    483969    public IEnumerable<Downtime> GetDowntimesForResource(Guid resourceId) {
    484       throw new NotImplementedException();
    485     }
    486 
     970      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     971      using (var pm = PersistenceManager)
     972      using (new PerformanceLogger("GetDowntimesForResource")) {
     973        var downtimeDao = pm.DowntimeDao;
     974        return pm.UseTransaction(() => downtimeDao.GetByResourceId(resourceId)
     975          .Select(x => x.ToDto())
     976          .ToList()
     977        );
     978      }
     979    }
     980    #endregion
     981
     982    #region User Methods
    487983    public string GetUsernameByUserId(Guid userId) {
    488       throw new NotImplementedException();
     984      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     985      var user = UserManager.GetUserById(userId);
     986      return user != null ? user.UserName : null;
    489987    }
    490988
    491989    public Guid GetUserIdByUsername(string username) {
    492       throw new NotImplementedException();
    493     }
    494 
     990      RoleVerifier.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
     991      var user = ServiceLocator.Instance.UserManager.GetUserByName(username);
     992      return user != null ? (Guid?)user.ProviderUserKey ?? Guid.Empty : Guid.Empty;
     993    }
     994    #endregion
     995
     996    #region UserPriorities Methods
    495997    public IEnumerable<UserPriority> GetUserPriorities() {
    496       throw new NotImplementedException();
    497     }
    498 
     998      using (var pm = PersistenceManager)
     999      using (new PerformanceLogger("GetUserPriorities")) {
     1000        var userPriorityDao = pm.UserPriorityDao;
     1001        return pm.UseTransaction(() => userPriorityDao.GetAll()
     1002          .Select(x => x.ToDto())
     1003          .ToList()
     1004        );
     1005      }
     1006    }
     1007    #endregion
     1008
     1009    #region Statistics Methods
    4991010    public IEnumerable<Statistics> GetStatistics() {
    5001011      // unused
     
    5061017      throw new NotImplementedException();
    5071018    }
     1019    #endregion
     1020
     1021    #region Private Helper Methods
     1022    private void UpdateTaskState(IPersistenceManager pm, DA.Task task, DT.TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
     1023      var stateLogDao = pm.StateLogDao;
     1024      var taskStateEntity = taskState.ToEntity();
     1025      if (task.Command == DA.Command.Pause && task.State == DA.TaskState.Paused
     1026          || task.Command == DA.Command.Abort && task.State == DA.TaskState.Aborted
     1027          || task.Command == DA.Command.Stop && task.State == DA.TaskState.Aborted) {
     1028        task.Command = null;
     1029      } else if (taskStateEntity == DA.TaskState.Paused && task.Command != null) {
     1030        taskStateEntity = DA.TaskState.Waiting;
     1031      }
     1032      stateLogDao.Save(new DA.StateLog {
     1033        State = taskStateEntity,
     1034        DateTime = DateTime.Now,
     1035        TaskId = task.TaskId,
     1036        UserId = userId,
     1037        SlaveId = slaveId,
     1038        Exception = exception
     1039      });
     1040      task.State = taskStateEntity;
     1041    }
     1042
     1043    private DA.Resource AuthorizeForResource(IPersistenceManager pm, Guid resourceId) {
     1044      var resourceDao = pm.ResourceDao;
     1045      var resource = resourceDao.GetById(resourceId);
     1046      if (resource == null) throw new SecurityException("Not authorized");
     1047      if (resource.OwnerUserId != UserManager.CurrentUserId
     1048          && !RoleVerifier.IsInRole(HiveRoles.Administrator)) {
     1049        throw new SecurityException("Not authorized");
     1050      }
     1051      return resource;
     1052    }
     1053
     1054    [MethodImpl(MethodImplOptions.NoInlining)]
     1055    public string GetCurrentMethod() {
     1056      StackTrace st = new StackTrace();
     1057      StackFrame sf = st.GetFrame(1);
     1058      return sf.GetMethod().Name;
     1059    }
     1060    #endregion
    5081061  }
    5091062}
  • branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/ServiceLocator.cs

    r12468 r12691  
    2323using HeuristicLab.Services.Hive.DataAccess.Interfaces;
    2424using HeuristicLab.Services.Hive.DataAccess.Manager;
     25using HeuristicLab.Services.Hive.Manager;
    2526
    2627namespace HeuristicLab.Services.Hive {
     
    3738
    3839    public IPersistenceManager PersistenceManager {
    39       get { return new PersistenceManager(); }
     40      get {
     41        var dataContext = HiveOperationContext.Current != null
     42                            ? HiveOperationContext.Current.DataContext
     43                            : new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
     44        return new PersistenceManager(dataContext);
     45      }
    4046    }
    4147
     
    102108    }
    103109
     110    private NewHeartbeatManager newheartbeatManager;
     111    public NewHeartbeatManager NewHeartbeatManager {
     112      get {
     113        if (newheartbeatManager == null) newheartbeatManager = new NewHeartbeatManager();
     114        return newheartbeatManager;
     115      }
     116    }
     117
    104118    private HeartbeatManager heartbeatManager;
    105119    public HeartbeatManager HeartbeatManager {
     
    117131      }
    118132    }
     133    private ITaskScheduler newtaskScheduler;
     134    public ITaskScheduler NewTaskScheduler {
     135      get {
     136        if (newtaskScheduler == null) newtaskScheduler = new RoundRobinTaskScheduler();
     137        return newtaskScheduler;
     138      }
     139    }
    119140  }
    120141}
  • branches/HiveStatistics/sources/HeuristicLab.Services.WebApp.Status/3.3/WebApi/DataController.cs

    r12558 r12691  
    8585          }).FirstOrDefault();
    8686        var calculatingTasks = factTasks.Where(x => x.TaskState == TaskState.Calculating);
    87         int count = calculatingTasks.Count();
     87        int count = calculatingTasks.Count() / 3;
    8888        return new DT.TimeStatus {
    8989          MinCalculatingTime = lastCalculatingTimes != null ? lastCalculatingTimes.Min : 0,
    9090          MaxCalculatingTime = lastCalculatingTimes != null ? lastCalculatingTimes.Max : 0,
    91           AvgWaitingTime = count > 0 ? (long)calculatingTasks.OrderBy(x => x.StartTime).Take(count / 3).Average(x => x.InitialWaitingTime) : 0,
     91          AvgWaitingTime = count > 0 ? (long)calculatingTasks.OrderBy(x => x.StartTime).Take(count).Average(x => x.InitialWaitingTime) : 0,
    9292          AvgCalculatingTime = lastCalculatingTimes != null ? lastCalculatingTimes.Avg : 0,
    9393          TotalCpuTime = factTasks.Sum(x => x.CalculatingTime),
  • branches/HiveStatistics/sources/HeuristicLab.Services.WebApp.Status/3.3/WebApp/history/history.cshtml

    r12584 r12691  
    3333            <div class="btn-group" dropdown dropdown-append-to-body>
    3434                <button type="button" class="btn btn-default dropdown-toggle" dropdown-toggle style="width: 130px; text-align: left;">
    35                     {{curQuickSelection.name}} <span class="glyphicon glyphicon-chevron-down" style="margin-top: 3px; float:right"></span>
     35                    <span class="text-left" style="display: inline-block; width: 85px;">{{curQuickSelection.name}}</span>
     36                    <span class="glyphicon glyphicon-chevron-down" style="margin-top: 3px;"></span>
    3637                </button>
    3738                <ul class="dropdown-menu" role="menu">
Note: See TracChangeset for help on using the changeset viewer.