Free cookie consent management tool by TermsFeed Policy Generator

Changeset 16993


Ignore:
Timestamp:
05/29/19 12:16:15 (4 years ago)
Author:
dpiringe
Message:

#2924:

  • added IEnumerable<T> GetInstances<T>(params object[] args) where T: class and IEnumerable<object> GetInstances(Type type, params object[] args) method to IApplicationManager and implemented them in LightweightApplicationManager -> to instantiate types with specific constructor arguments
  • added RunnerState State { get; } property in IRunnerHost, was already in RunnerHost
  • added user authentication for NativeRunnerHost
  • added optional check for a running docker daemon and available image for type DockerRunnerHost + Exception DockerException
  • added caching of the saved IApplication in ApplicationRunner to prevent a new instance every get call
  • removed System.ServiceModel.Primitives NuGet package
  • lots of formatting
Location:
branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3
Files:
1 added
12 edited

Legend:

Unmodified
Added
Removed
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/ApplicationBase.cs

    r16984 r16993  
    3636    private ApplicationAttribute ApplicationAttribute {
    3737      get {
    38         object[] appAttributes = this.GetType().GetCustomAttributes(typeof(ApplicationAttribute), false);
     38        object[] appAttributes = GetType().GetCustomAttributes(typeof(ApplicationAttribute), false);
    3939
    4040        // exactly one attribute of the type ClassInfoAttribute must be given
    4141        if (appAttributes.Length == 0) {
    42           throw new InvalidPluginException("ApplicationAttribute on type " + this.GetType() + " is missing.");
     42          throw new InvalidPluginException("ApplicationAttribute on type " + GetType() + " is missing.");
    4343        } else if (appAttributes.Length > 1) {
    44           throw new InvalidPluginException("Found multiple ApplicationAttributes on type " + this.GetType());
     44          throw new InvalidPluginException("Found multiple ApplicationAttributes on type " + GetType());
    4545        }
    4646
     
    5050
    5151    #region IApplication Members
    52 
    5352    /// <summary>
    5453    /// Gets the name of the application.
    5554    /// </summary>
    56     public string Name {
    57       get { return ApplicationAttribute.Name; }
    58     }
     55    public string Name => ApplicationAttribute.Name;
    5956
    6057    /// <summary>
    6158    /// Gets the description of the application.
    6259    /// </summary>
    63     public string Description {
    64       get {
    65         return ApplicationAttribute.Description;
    66       }
    67     }
     60    public string Description => ApplicationAttribute.Description;
    6861
    6962    /// <summary>
     
    7265    public abstract void Run(ICommandLineArgument[] args);
    7366
    74     public virtual void OnCancel() { Console.WriteLine("OnCancellation"); }
    75     public virtual void OnPause() { Console.WriteLine("OnPause"); }
    76     public virtual void OnResume() { Console.WriteLine("OnResume"); }
    77 
     67    public virtual void OnCancel() { }
     68    public virtual void OnPause() { }
     69    public virtual void OnResume() { }
    7870    #endregion
    7971  }
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/HeuristicLab.PluginInfrastructure-3.3.csproj

    r16984 r16993  
    2121    <PackageReference Include="System.Runtime.Loader" Version="4.3.0" />
    2222    <PackageReference Include="System.Security.Cryptography.ProtectedData" Version="4.5.0" />
    23     <PackageReference Include="System.ServiceModel.Primitives" Version="4.5.3" />
    2423    <PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />
    2524    <PackageReference Include="System.Security.Cryptography.Primitives" Version="4.3.0" />
    2625  </ItemGroup>
    27   <ItemGroup>
    28     <Folder Include="Exceptions\" />
    29   </ItemGroup>
    3026</Project>
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Interfaces/IApplicationManager.cs

    r16984 r16993  
    4747
    4848    /// <summary>
     49    /// Discovers and creates instances of <typeparamref name="T"/> and all types implementing or inheriting <typeparamref name="T"/> (directly and indirectly).
     50    /// </summary>
     51    /// <typeparam name="T">The type or super-type to discover.</typeparam>
     52    /// <param name="args">Constructor arguments.</param>
     53    /// <returns>An enumerable of instances of the discovered types.</returns>
     54    IEnumerable<T> GetInstances<T>(params object[] args) where T : class;
     55
     56    /// <summary>
    4957    /// Discovers and creates instances of <paramref name="type"/> and all types implementing or inheriting <paramref name="type"/> (directly and indirectly).
    5058    /// </summary>
     
    5260    /// <returns>An enumerable of instances of the discovered types.</returns>
    5361    IEnumerable<object> GetInstances(Type type);
     62
     63    /// <summary>
     64    /// Discovers and creates instances of <paramref name="type"/> and all types implementing or inheriting <paramref name="type"/> (directly and indirectly).
     65    /// </summary>
     66    /// <param name="type">The type or super-type to discover.</param>
     67    /// <param name="args">Constructor arguments.</param>
     68    /// <returns>An enumerable of instances of the discovered types.</returns>
     69    IEnumerable<object> GetInstances(Type type, params object[] args);
    5470
    5571    /// <summary>
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Interfaces/IRunner.cs

    r16984 r16993  
    1 using System;
    2 using System.Collections.Generic;
    3 using System.IO;
    4 using System.Text;
     1using System.Collections.Generic;
    52
    63namespace HeuristicLab.PluginInfrastructure {
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Interfaces/IRunnerHost.cs

    r16985 r16993  
    88  /// </summary>
    99  public interface IRunnerHost {
     10    /// <summary>
     11    /// The runner state.
     12    /// </summary>
     13    RunnerState State { get; }
    1014
    1115    /// <summary>
     
    3236    /// </summary>
    3337    void Resume();
    34 
    3538  }
    3639}
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Isolation/ApplicationRunner.cs

    r16984 r16993  
    11using System;
    2 using System.Collections.Generic;
    32using System.IO;
    4 using System.Text;
    53
    64namespace HeuristicLab.PluginInfrastructure {
     
    1715    public IApplication StartApplication {
    1816      get {
    19         using (var memStream = new MemoryStream(serializedStartApplication)) {
    20           return (IApplication)formatter.Deserialize(memStream);
     17        if (application == null) {
     18          using (var memStream = new MemoryStream(serializedStartApplication)) {
     19            application = (IApplication)formatter.Deserialize(memStream);
     20          }
    2121        }
     22        return application;
    2223      }
    2324      set {
     
    3132    // instantly deserialize the application, before all assemblies are loaded.
    3233    private byte[] serializedStartApplication = new byte[0];
     34    // cache application to prevent new instances every get call of StartApplication
     35    private IApplication application;
    3336
    3437    protected override void Execute() {
     
    3942      switch (runnerJob) {
    4043        case RunnerJob.Cancel: StartApplication.OnCancel(); break;
    41         case RunnerJob.Pause:  StartApplication.OnPause (); break;
     44        case RunnerJob.Pause: StartApplication.OnPause(); break;
    4245        case RunnerJob.Resume: StartApplication.OnResume(); break;
    4346      }
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Isolation/AssemblyLoader.cs

    r16984 r16993  
    120120    #endregion
    121121
    122 
    123122    private void LoadTypes(IEnumerable<Assembly> assemblies) {
    124123      foreach (Assembly asm in assemblies) {
     
    136135            }
    137136          } catch (BadImageFormatException) { }
    138         } catch (Exception e) { // to catch every other exception
     137        } catch (Exception) { // to catch every other exception
    139138          //Tracing.Logger.Error(
    140139          //  $"Exception occured while loading types of assembly {asm.FullName}! \n " +
     
    147146      foreach (string path in GetAssembliesFromBasePath(basePath))
    148147        LoadAssemblyFromPath(path);
    149      
     148
    150149      LoadTypes(this.Assemblies);
    151150      return this.Assemblies;
     
    155154      foreach (var info in assemblyInfos)
    156155        LoadAssemblyFromPath(info.Path.ToString());
    157      
     156
    158157      LoadTypes(this.Assemblies);
    159158      return this.Assemblies;
     
    167166        } // else
    168167          //Tracing.Logger.Error($"Unnable to load assembly with path {path}!");
    169       } catch (Exception e) { // to catch every exception occured by assembly loading.
     168      } catch (Exception) { // to catch every exception occured by assembly loading.
    170169        //Tracing.Logger.Error(
    171170        //  $"Exception occured while loading assembly from path {path}! \n " +
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Isolation/DockerRunnerHost.cs

    r16985 r16993  
    1 namespace HeuristicLab.PluginInfrastructure {
     1using System.Diagnostics;
     2using HeuristicLab.PluginInfrastructure.Exceptions;
     3
     4namespace HeuristicLab.PluginInfrastructure {
    25  /// <summary>
    36  /// IRunner for isolation with docker.
    47  /// </summary>
    58  public class DockerRunnerHost : RunnerHost {
    6     public DockerRunnerHost()
    7       : base("docker", "run -i --rm --mount type=bind,source=/c/Users/,target=/Users heuristiclab33", null, null, null) {
     9    #region Constants
     10    private const string Docker = "docker";
     11    private const string ContainerStartup = "container run -i --rm ";
     12    private const string Mounting = @"--mount type=bind,source=/c/Users/,target=/Users ";
     13    private const string Image = "heuristiclab33:latest";
     14    private const string DockerExceptionMessage = "Docker is not running or image '" + Image + "' does not exists!";
     15    #endregion
     16
     17    #region Constructors
     18    public DockerRunnerHost(bool doDockerAvailableCheck = true)
     19      : base(Docker, ContainerStartup + Mounting + Image, null, null, null) {
     20      if (doDockerAvailableCheck && !IsDockerAvailable())
     21        throw new DockerException(DockerExceptionMessage);
    822    }
     23    #endregion
     24
     25    #region Helper
     26    private bool IsDockerAvailable() {
     27      var process = new Process {
     28        StartInfo = new ProcessStartInfo {
     29          FileName = Docker,
     30          Arguments = "image inspect " + Image,
     31          UseShellExecute = false,
     32          RedirectStandardOutput = true,
     33          RedirectStandardInput = false,
     34          RedirectStandardError = true,
     35          CreateNoWindow = false
     36        },
     37        EnableRaisingEvents = false
     38      };
     39
     40      process.Start();
     41      process.BeginOutputReadLine();
     42      process.BeginErrorReadLine();
     43      process.WaitForExit();
     44      return process.ExitCode == 0;
     45    }
     46    #endregion
    947  }
    1048}
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Isolation/NativeRunnerHost.cs

    r16985 r16993  
    66  /// </summary>
    77  public class NativeRunnerHost : RunnerHost {
    8     public NativeRunnerHost()
    9       : base($"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}HeuristicLab-3.3.exe", "", null, null, null) {
     8    #region Constructors
     9    public NativeRunnerHost() : this(null, null, null) {
    1010    }
     11
     12    public NativeRunnerHost(string userName, string password, string domain)
     13      : base($"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}HeuristicLab-3.3.exe", "", userName, password, domain) {
     14    }
     15    #endregion
    1116  }
    1217}
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Isolation/Runner.cs

    r16984 r16993  
    44using System.Runtime.Serialization;
    55using System.Runtime.Serialization.Formatters.Binary;
    6 using System.Text;
    76using System.Threading;
    87
     
    1110  public abstract class Runner : IRunner {
    1211
     12    #region Vars
    1313    [NonSerialized]
    1414    private Thread listener;
     
    1919    [NonSerialized]
    2020    protected static IFormatter formatter = new BinaryFormatter();
    21    
     21    #endregion
     22
     23    #region Properties
    2224    public bool QuietMode { get; set; }
    23      
     25
    2426    public IEnumerable<AssemblyInfo> AssembliesToLoad { get; set; }
     27    #endregion
     28
    2529
    2630    public static void Serialize(IRunner runner, Stream stream) => formatter.Serialize(stream, runner);
     
    4145    protected abstract void OnRunnerJob(RunnerJob runnerJob);
    4246
     47    #region Helper
    4348    private void StartExecutor() {
    4449      executor = new Thread(Execute);
     
    4651      executor.Start();
    4752    }
     53
    4854    private void StartListener() {
    4955      listener = new Thread(() => {
    5056        Stream stdin = Console.OpenStandardInput();
    51         while (executor.IsAlive) 
     57        while (executor.IsAlive)
    5258          OnRunnerJob((RunnerJob)formatter.Deserialize(stdin));
    5359      });
     
    5561      listener.Start();
    5662    }
    57 
     63    #endregion
    5864  }
    5965}
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/Isolation/RunnerHost.cs

    r16984 r16993  
    7474          UserName = string.IsNullOrEmpty(UserName) ? null : UserName,
    7575          PasswordInClearText = string.IsNullOrEmpty(Password) ? null : Password,
    76           Domain = string.IsNullOrEmpty(Domain) ? null: Domain,
     76          Domain = string.IsNullOrEmpty(Domain) ? null : Domain,
    7777          WorkingDirectory = Directory.GetCurrentDirectory()
    7878        },
     
    8686      Runner.Serialize(runner, process.StandardInput.BaseStream);
    8787
     88      process.BeginOutputReadLine();
     89      process.BeginErrorReadLine();
     90
    8891      if (!runner.QuietMode) {
    89         process.BeginOutputReadLine();
    90         process.BeginErrorReadLine();
    9192        process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
    9293        process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
     
    124125    /// When the child process gets finished without requested cancellation, the linked token gets cancelled and a result set.
    125126    /// </summary>
    126     /// <param name="token"></param>
    127     /// <returns></returns>
    128127    private Task<bool> RegisterCancellation(CancellationToken token) {
    129128      if (process != null && State == RunnerState.Starting) {
  • branches/2924_DotNetCoreMigration/HeuristicLab.PluginInfrastructure/3.3/LightweightApplicationManager.cs

    r16984 r16993  
    3737    }
    3838
    39     Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
    40       return null;
    41     }
     39    Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) => null;
    4240
    4341
     
    4644    /// Gets an empty list of plugins. (LightweightApplicationManager doesn't support plugin discovery)
    4745    /// </summary>
    48     public IEnumerable<IPluginDescription> Plugins {
    49       get { return new IPluginDescription[0]; }
    50     }
     46    public IEnumerable<IPluginDescription> Plugins => new IPluginDescription[0];
    5147
    5248    /// <summary>
    5349    /// Gets an empty list of applications. (LightweightApplicationManager doesn't support application discovery)
    5450    /// </summary>
    55     public IEnumerable<IApplicationDescription> Applications {
    56       get { return new IApplicationDescription[0]; }
    57     }
     51    public IEnumerable<IApplicationDescription> Applications => new IApplicationDescription[0];
    5852
    5953    /// <summary>
     
    6256    /// <typeparam name="T">Most general type.</typeparam>
    6357    /// <returns>Enumerable of the created instances.</returns>
    64     public IEnumerable<T> GetInstances<T>() where T : class {
    65       return GetInstances(typeof(T)).Cast<T>();
    66     }
     58    public IEnumerable<T> GetInstances<T>() where T : class => GetInstances(typeof(T)).Cast<T>();
     59
     60    /// <summary>
     61    /// Creates an instance of all types that are subtypes or the same type of the specified type
     62    /// </summary>
     63    /// <typeparam name="T">Most general type.</typeparam>
     64    /// <param name="args">Constructor arguments.</param>
     65    /// <returns>Enumerable of the created instances.</returns>
     66    public IEnumerable<T> GetInstances<T>(params object[] args) where T : class => GetInstances(typeof(T), args).Cast<T>();
    6767
    6868    /// <summary>
     
    7171    /// <param name="type">Most general type.</param>
    7272    /// <returns>Enumerable of the created instances.</returns>
    73     public IEnumerable<object> GetInstances(Type type) {
     73    public IEnumerable<object> GetInstances(Type type) => GetInstances(type, null);
     74
     75    /// <summary>
     76    /// Creates an instance of all types that are subtypes or the same type of the specified type
     77    /// </summary>
     78    /// <param name="type">Most general type.</param>
     79    /// <param name="args">Constructor arguments.</param>
     80    /// <returns>Enumerable of the created instances.</returns>
     81    public IEnumerable<object> GetInstances(Type type, params object[] args) {
    7482      List<object> instances = new List<object>();
    7583      foreach (Type t in GetTypes(type)) {
    7684        object instance = null;
    77         try { instance = Activator.CreateInstance(t); } catch { }
     85        try { instance = Activator.CreateInstance(t, args); } catch { }
    7886        if (instance != null) instances.Add(instance);
    7987      }
     
    8189    }
    8290
     91    /// <summary>
     92    /// Discovers a specific type by its name.
     93    /// </summary>
     94    /// <param name="typeName">Full name of the type.</param>
     95    /// <returns>A type or null, if nothing was found.</returns>
    8396    public Type GetType(string typeName) {
    8497      foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
     
    217230      throw new NotSupportedException("LightweightApplicationManager doesn't support type discovery for plugins.");
    218231    }
    219 
    220232    #endregion
    221233  }
Note: See TracChangeset for help on using the changeset viewer.