source: trunk/sources/HeuristicLab.PluginInfrastructure/3.3/SandboxApplicationManager.cs @ 7520

Last change on this file since 7520 was 7520, checked in by abeham, 8 years ago

#1774:

  • improved performance of type discovery by moving compatibility check further up the chain (deep cloneable unit test time reduced from 32s to 18s)
File size: 17.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.IO;
25using System.Linq;
26using System.Reflection;
27using HeuristicLab.PluginInfrastructure.Manager;
28
29namespace HeuristicLab.PluginInfrastructure {
30
31  /// <summary>
32  /// The SandboxApplicationManager provides properties to retrieve the list of available plugins and applications.
33  /// It also provides methods for type discovery and instantiation for types declared in plugins.
34  /// The SandboxApplicationManager is used in sandboxed Application Domains where permissions are restricted and
35  /// only partially-trusted code can be executed.
36  /// </summary>
37  internal class SandboxApplicationManager : MarshalByRefObject, IApplicationManager {
38    /// <summary>
39    /// Fired when a plugin is loaded.
40    /// </summary>
41    internal event EventHandler<PluginInfrastructureEventArgs> PluginLoaded;
42    /// <summary>
43    /// Fired when a plugin is unloaded (when the application terminates).
44    /// </summary>
45    internal event EventHandler<PluginInfrastructureEventArgs> PluginUnloaded;
46
47    // cache for the AssemblyResolveEvent
48    // which must be handled when assemblies are loaded dynamically after the application start
49    protected internal Dictionary<string, Assembly> loadedAssemblies;
50
51    private List<IPlugin> loadedPlugins;
52
53    private List<PluginDescription> plugins;
54    /// <summary>
55    /// Gets all plugins.
56    /// </summary>
57    public IEnumerable<IPluginDescription> Plugins {
58      get { return plugins.Cast<IPluginDescription>(); }
59    }
60
61    private List<ApplicationDescription> applications;
62    /// <summary>
63    /// Gets all installed applications.
64    /// </summary>
65    public IEnumerable<IApplicationDescription> Applications {
66      get { return applications.Cast<IApplicationDescription>(); }
67    }
68
69    internal SandboxApplicationManager()
70      : base() {
71      loadedAssemblies = new Dictionary<string, Assembly>();
72      loadedPlugins = new List<IPlugin>();
73    }
74
75    /// <summary>
76    /// Prepares the application domain for the execution of an HL application.
77    /// Pre-loads all <paramref name="plugins"/>.
78    /// </summary>
79    /// <param name="apps">Enumerable of available HL applications.</param>
80    /// <param name="plugins">Enumerable of plugins that should be pre-loaded.</param> 
81    internal void PrepareApplicationDomain(IEnumerable<ApplicationDescription> apps, IEnumerable<PluginDescription> plugins) {
82      this.plugins = new List<PluginDescription>(plugins);
83      this.applications = new List<ApplicationDescription>(apps);
84      ApplicationManager.RegisterApplicationManager(this);
85      LoadPlugins(plugins);
86    }
87
88    /// <summary>
89    /// Loads the <paramref name="plugins"/> into this application domain.
90    /// </summary>
91    /// <param name="plugins">Enumerable of plugins that should be loaded.</param>
92    private void LoadPlugins(IEnumerable<PluginDescription> plugins) {
93      // load all loadable plugins (all dependencies available) into the execution context
94      foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(plugins.Where(x => x.PluginState != PluginState.Disabled))) {
95        foreach (string fileName in desc.AssemblyLocations) {
96          // load assembly reflection only first to get the full assembly name
97          var reflectionOnlyAssembly = Assembly.ReflectionOnlyLoadFrom(fileName);
98          // load the assembly into execution context using full assembly name
99          var asm = Assembly.Load(reflectionOnlyAssembly.FullName);
100          RegisterLoadedAssembly(asm);
101          // instantiate and load all plugins in this assembly
102          foreach (var plugin in GetInstances<IPlugin>(asm)) {
103            plugin.OnLoad();
104            loadedPlugins.Add(plugin);
105          }
106        }
107        OnPluginLoaded(new PluginInfrastructureEventArgs(desc));
108        desc.Load();
109      }
110    }
111
112    /// <summary>
113    /// Runs the application declared in <paramref name="appInfo"/>.
114    /// This is a synchronous call. When the application is terminated all plugins are unloaded.
115    /// </summary>
116    /// <param name="appInfo">Description of the application to run</param>
117    internal void Run(ApplicationDescription appInfo) {
118      IApplication runnablePlugin = (IApplication)Activator.CreateInstance(appInfo.DeclaringAssemblyName, appInfo.DeclaringTypeName).Unwrap();
119      try {
120        runnablePlugin.Run();
121      } finally {
122        // unload plugins in reverse order
123        foreach (var plugin in loadedPlugins.Reverse<IPlugin>()) {
124          plugin.OnUnload();
125        }
126        foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(plugins.Where(x => x.PluginState != PluginState.Disabled))) {
127          desc.Unload();
128          OnPluginUnloaded(new PluginInfrastructureEventArgs(desc));
129        }
130      }
131    }
132
133    // register assembly in the assembly cache for the AssemblyResolveEvent
134    private void RegisterLoadedAssembly(Assembly asm) {
135      if (loadedAssemblies.ContainsKey(asm.FullName) || loadedAssemblies.ContainsKey(asm.GetName().Name)) {
136        throw new ArgumentException("An assembly with the name " + asm.GetName().Name + " has been registered already.", "asm");
137      }
138      loadedAssemblies.Add(asm.FullName, asm);
139      loadedAssemblies.Add(asm.GetName().Name, asm); // add short name
140    }
141
142    /// <summary>
143    /// Creates an instance of all types that are subtypes or the same type of the specified type and declared in <paramref name="plugin"/>
144    /// </summary>
145    /// <typeparam name="T">Most general type.</typeparam>
146    /// <returns>Enumerable of the created instances.</returns>
147    internal static IEnumerable<T> GetInstances<T>(IPluginDescription plugin) where T : class {
148      List<T> instances = new List<T>();
149      foreach (Type t in GetTypes(typeof(T), plugin, onlyInstantiable: true, includeGenericTypeDefinitions: false)) {
150        T instance = null;
151        try { instance = (T)Activator.CreateInstance(t); } catch { }
152        if (instance != null) instances.Add(instance);
153      }
154      return instances;
155    }
156    /// <summary>
157    /// Creates an instance of all types declared in assembly <paramref name="asm"/> that are subtypes or the same type of the specified <typeparamref name="type"/>.
158    /// </summary>
159    /// <typeparam name="T">Most general type.</typeparam>
160    /// <param name="asm">Declaring assembly.</param>
161    /// <returns>Enumerable of the created instances.</returns>
162    private static IEnumerable<T> GetInstances<T>(Assembly asm) where T : class {
163      List<T> instances = new List<T>();
164      foreach (Type t in GetTypes(typeof(T), asm, onlyInstantiable: true, includeGenericTypeDefinitions: false)) {
165        T instance = null;
166        try { instance = (T)Activator.CreateInstance(t); } catch { }
167        if (instance != null) instances.Add(instance);
168      }
169      return instances;
170    }
171    /// <summary>
172    /// Creates an instance of all types that are subtypes or the same type of the specified type
173    /// </summary>
174    /// <typeparam name="T">Most general type.</typeparam>
175    /// <returns>Enumerable of the created instances.</returns>
176    internal static IEnumerable<T> GetInstances<T>() where T : class {
177      return from i in GetInstances(typeof(T))
178             select (T)i;
179    }
180
181    /// <summary>
182    /// Creates an instance of all types that are subtypes or the same type of the specified type
183    /// </summary>
184    /// <param name="type">Most general type.</param>
185    /// <returns>Enumerable of the created instances.</returns>
186    internal static IEnumerable<object> GetInstances(Type type) {
187      List<object> instances = new List<object>();
188      foreach (Type t in GetTypes(type, onlyInstantiable: true, includeGenericTypeDefinitions: false)) {
189        object instance = null;
190        try { instance = Activator.CreateInstance(t); } catch { }
191        if (instance != null) instances.Add(instance);
192      }
193      return instances;
194    }
195
196    /// <summary>
197    /// Finds all types that are subtypes or equal to the specified type.
198    /// </summary>
199    /// <param name="type">Most general type for which to find matching types.</param>
200    /// <param name="onlyInstantiable">Return only types that are instantiable
201    /// <param name="includeGenericTypeDefinitions">Specifies if generic type definitions shall be included</param>
202    /// (interfaces, abstract classes... are not returned)</param>
203    /// <returns>Enumerable of the discovered types.</returns>
204    internal static IEnumerable<Type> GetTypes(Type type, bool onlyInstantiable, bool includeGenericTypeDefinitions) {
205      return from asm in AppDomain.CurrentDomain.GetAssemblies()
206             from t in GetTypes(type, asm, onlyInstantiable, includeGenericTypeDefinitions)
207             select t;
208    }
209
210    internal static IEnumerable<Type> GetTypes(IEnumerable<Type> types, bool onlyInstantiable, bool includeGenericTypeDefinitions, bool assignableToAllTypes) {
211      IEnumerable<Type> result = GetTypes(types.First(), onlyInstantiable, includeGenericTypeDefinitions);
212      foreach (Type type in types.Skip(1)) {
213        IEnumerable<Type> discoveredTypes = GetTypes(type, onlyInstantiable, includeGenericTypeDefinitions);
214        if (assignableToAllTypes) result = result.Intersect(discoveredTypes);
215        else result = result.Union(discoveredTypes);
216      }
217      return result;
218    }
219
220    /// <summary>
221    /// Finds all types that are subtypes or equal to the specified type if they are part of the given
222    /// <paramref name="pluginDescription"/>.
223    /// </summary>
224    /// <param name="type">Most general type for which to find matching types.</param>
225    /// <param name="pluginDescription">The plugin the subtypes must be part of.</param>
226    /// <param name="onlyInstantiable">Return only types that are instantiable
227    /// <param name="includeGenericTypeDefinitions">Specifies if generic type definitions shall be included</param>
228    /// (interfaces, abstract classes... are not returned)</param>
229    /// <returns>Enumerable of the discovered types.</returns>
230    internal static IEnumerable<Type> GetTypes(Type type, IPluginDescription pluginDescription, bool onlyInstantiable, bool includeGenericTypeDefinitions) {
231      PluginDescription pluginDesc = (PluginDescription)pluginDescription;
232      return from asm in AppDomain.CurrentDomain.GetAssemblies()
233             where !asm.IsDynamic
234             where pluginDesc.AssemblyLocations.Any(location => location.Equals(Path.GetFullPath(asm.Location), StringComparison.CurrentCultureIgnoreCase))
235             from t in GetTypes(type, asm, onlyInstantiable, includeGenericTypeDefinitions)
236             select t;
237    }
238
239    internal static IEnumerable<Type> GetTypes(IEnumerable<Type> types, IPluginDescription pluginDescription, bool onlyInstantiable, bool includeGenericTypeDefinitions, bool assignableToAllTypes) {
240      IEnumerable<Type> result = GetTypes(types.First(), pluginDescription, onlyInstantiable, includeGenericTypeDefinitions);
241      foreach (Type type in types.Skip(1)) {
242        IEnumerable<Type> discoveredTypes = GetTypes(type, pluginDescription, onlyInstantiable, includeGenericTypeDefinitions);
243        if (assignableToAllTypes) result = result.Intersect(discoveredTypes);
244        else result = result.Union(discoveredTypes);
245      }
246      return result;
247    }
248
249    /// <summary>
250    /// Gets types that are assignable (same of subtype) to the specified type only from the given assembly.
251    /// </summary>
252    /// <param name="type">Most general type we want to find.</param>
253    /// <param name="assembly">Assembly that should be searched for types.</param>
254    /// <param name="onlyInstantiable">Return only types that are instantiable
255    /// (interfaces, abstract classes...  are not returned)</param>
256    /// <param name="includeGenericTypeDefinitions">Specifies if generic type definitions shall be included</param>
257    /// <returns>Enumerable of the discovered types.</returns>
258    private static IEnumerable<Type> GetTypes(Type type, Assembly assembly, bool onlyInstantiable, bool includeGenericTypeDefinitions) {
259      var buildTypes = from t in assembly.GetTypes()
260                       where CheckTypeCompatibility(type, t)
261                       where !IsNonDiscoverableType(t)
262                       where onlyInstantiable == false ||
263                             (!t.IsAbstract && !t.IsInterface && !t.HasElementType)
264                       select BuildType(t, type);
265
266      return from t in buildTypes
267             where includeGenericTypeDefinitions || !t.IsGenericTypeDefinition
268             select t;
269    }
270
271
272    private static bool IsNonDiscoverableType(Type t) {
273      return t.GetCustomAttributes(typeof(NonDiscoverableTypeAttribute), false).Any();
274    }
275
276    private static bool CheckTypeCompatibility(Type type, Type other) {
277      if (type.IsAssignableFrom(other))
278        return true;
279      if (type.IsGenericType && other.IsGenericType) {
280        var otherGenericArguments = other.GetGenericArguments();
281        var typeGenericArguments = type.GetGenericArguments();
282
283        //check type arguments count
284        if (otherGenericArguments.Length != typeGenericArguments.Length)
285          return false;
286
287        //check type arguments & constraints
288        int i = 0;
289        foreach (var genericArgument in typeGenericArguments) {
290          if (otherGenericArguments[i].IsGenericParameter) {
291            foreach (var constraint in otherGenericArguments[i].GetGenericParameterConstraints())
292              if (!constraint.IsAssignableFrom(genericArgument)) return false;
293          } else if (genericArgument != otherGenericArguments[i]) return false;
294          i++;
295        }
296        //check types
297        try {
298          var otherGenericTypeDefinition = other.GetGenericTypeDefinition();
299          if (type.IsAssignableFrom(otherGenericTypeDefinition.MakeGenericType(typeGenericArguments)))
300            return true;
301        } catch (Exception) { }
302      }
303      return false;
304    }
305    private static Type BuildType(Type type, Type protoType) {
306      if (type.IsGenericType && protoType.IsGenericType)
307        return type.GetGenericTypeDefinition().MakeGenericType(protoType.GetGenericArguments());
308      else
309        return type;
310    }
311
312    private void OnPluginLoaded(PluginInfrastructureEventArgs e) {
313      if (PluginLoaded != null) PluginLoaded(this, e);
314    }
315
316    private void OnPluginUnloaded(PluginInfrastructureEventArgs e) {
317      if (PluginUnloaded != null) PluginUnloaded(this, e);
318    }
319
320    #region IApplicationManager Members
321
322    IEnumerable<T> IApplicationManager.GetInstances<T>() {
323      return GetInstances<T>();
324    }
325
326    IEnumerable<object> IApplicationManager.GetInstances(Type type) {
327      return GetInstances(type);
328    }
329
330    IEnumerable<Type> IApplicationManager.GetTypes(Type type, bool onlyInstantiable, bool includeGenericTypeDefinitions) {
331      return GetTypes(type, onlyInstantiable, includeGenericTypeDefinitions);
332    }
333    IEnumerable<Type> IApplicationManager.GetTypes(IEnumerable<Type> types, bool onlyInstantiable, bool includeGenericTypeDefinitions, bool assignableToAllTypes) {
334      return GetTypes(types, onlyInstantiable, includeGenericTypeDefinitions, assignableToAllTypes);
335    }
336
337    IEnumerable<Type> IApplicationManager.GetTypes(Type type, IPluginDescription plugin, bool onlyInstantiable, bool includeGenericTypeDefinitions) {
338      return GetTypes(type, plugin, onlyInstantiable, includeGenericTypeDefinitions);
339    }
340    IEnumerable<Type> IApplicationManager.GetTypes(IEnumerable<Type> types, IPluginDescription plugin, bool onlyInstantiable, bool includeGenericTypeDefinitions, bool assignableToAllTypes) {
341      return GetTypes(types, plugin, onlyInstantiable, includeGenericTypeDefinitions, assignableToAllTypes);
342    }
343
344    /// <summary>
345    /// Finds the plugin that declares the <paramref name="type">type</paramref>.
346    /// </summary>
347    /// <param name="type">The type of interest.</param>
348    /// <returns>The description of the plugin that declares the given type or null if the type has not been declared by a known plugin.</returns>
349    public IPluginDescription GetDeclaringPlugin(Type type) {
350      if (type == null) throw new ArgumentNullException("type");
351      foreach (PluginDescription info in Plugins) {
352        if (info.AssemblyLocations.Contains(Path.GetFullPath(type.Assembly.Location))) return info;
353      }
354      return null;
355    }
356    #endregion
357  }
358}
Note: See TracBrowser for help on using the repository browser.