Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6377 was 6174, checked in by ascheibe, 14 years ago

#831

  • completed SandboxManager
  • added SandboxApplicationManager for Hive
  • DefaultApplicationManager is now a subclass of the SandboxApplicationManager
  • ApplicationManager now instantiates the LightweightApplicationManager only if it is accessed to avoid calling InitializeLifetimeService(..) in a sandbox
File size: 15.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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      }
122      finally {
123        // unload plugins in reverse order
124        foreach (var plugin in loadedPlugins.Reverse<IPlugin>()) {
125          plugin.OnUnload();
126        }
127        foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(plugins.Where(x => x.PluginState != PluginState.Disabled))) {
128          desc.Unload();
129          OnPluginUnloaded(new PluginInfrastructureEventArgs(desc));
130        }
131      }
132    }
133
134    /// <summary>
135    /// Loads raw assemblies dynamically from a byte array
136    /// </summary>
137    /// <param name="assemblies">bytearray of all raw assemblies that should be loaded</param>
138    internal void LoadAssemblies(IEnumerable<byte[]> assemblies) {
139      foreach (byte[] asm in assemblies) {
140        Assembly loadedAsm = Assembly.Load(asm);
141        RegisterLoadedAssembly(loadedAsm);
142      }
143    }
144
145    // register assembly in the assembly cache for the AssemblyResolveEvent
146    private void RegisterLoadedAssembly(Assembly asm) {
147      if (loadedAssemblies.ContainsKey(asm.FullName) || loadedAssemblies.ContainsKey(asm.GetName().Name)) {
148        throw new ArgumentException("An assembly with the name " + asm.GetName().Name + " has been registered already.", "asm");
149      }
150      loadedAssemblies.Add(asm.FullName, asm);
151      loadedAssemblies.Add(asm.GetName().Name, asm); // add short name
152    }
153
154    /// <summary>
155    /// Creates an instance of all types that are subtypes or the same type of the specified type and declared in <paramref name="plugin"/>
156    /// </summary>
157    /// <typeparam name="T">Most general type.</typeparam>
158    /// <returns>Enumerable of the created instances.</returns>
159    internal static IEnumerable<T> GetInstances<T>(IPluginDescription plugin) where T : class {
160      List<T> instances = new List<T>();
161      foreach (Type t in GetTypes(typeof(T), plugin, true)) {
162        T instance = null;
163        try { instance = (T)Activator.CreateInstance(t); }
164        catch { }
165        if (instance != null) instances.Add(instance);
166      }
167      return instances;
168    }
169    /// <summary>
170    /// 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"/>.
171    /// </summary>
172    /// <typeparam name="T">Most general type.</typeparam>
173    /// <param name="asm">Declaring assembly.</param>
174    /// <returns>Enumerable of the created instances.</returns>
175    private static IEnumerable<T> GetInstances<T>(Assembly asm) where T : class {
176      List<T> instances = new List<T>();
177      foreach (Type t in GetTypes(typeof(T), asm, true)) {
178        T instance = null;
179        try { instance = (T)Activator.CreateInstance(t); }
180        catch { }
181        if (instance != null) instances.Add(instance);
182      }
183      return instances;
184    }
185    /// <summary>
186    /// Creates an instance of all types that are subtypes or the same type of the specified type
187    /// </summary>
188    /// <typeparam name="T">Most general type.</typeparam>
189    /// <returns>Enumerable of the created instances.</returns>
190    internal static IEnumerable<T> GetInstances<T>() where T : class {
191      return from i in GetInstances(typeof(T))
192             select (T)i;
193    }
194
195    /// <summary>
196    /// Creates an instance of all types that are subtypes or the same type of the specified type
197    /// </summary>
198    /// <param name="type">Most general type.</param>
199    /// <returns>Enumerable of the created instances.</returns>
200    internal static IEnumerable<object> GetInstances(Type type) {
201      List<object> instances = new List<object>();
202      foreach (Type t in GetTypes(type, true)) {
203        object instance = null;
204        try { instance = Activator.CreateInstance(t); }
205        catch { }
206        if (instance != null) instances.Add(instance);
207      }
208      return instances;
209    }
210
211    /// <summary>
212    /// Finds all types that are subtypes or equal to the specified type.
213    /// </summary>
214    /// <param name="type">Most general type for which to find matching types.</param>
215    /// <param name="onlyInstantiable">Return only types that are instantiable
216    /// (interfaces, abstract classes... are not returned)</param>
217    /// <returns>Enumerable of the discovered types.</returns>
218    internal static IEnumerable<Type> GetTypes(Type type, bool onlyInstantiable) {
219      return from asm in AppDomain.CurrentDomain.GetAssemblies()
220             from t in GetTypes(type, asm, onlyInstantiable)
221             select t;
222    }
223
224    internal static IEnumerable<Type> GetTypes(IEnumerable<Type> types, bool onlyInstantiable, bool assignableToAllTypes) {
225      IEnumerable<Type> result = GetTypes(types.First(), onlyInstantiable);
226      foreach (Type type in types.Skip(1)) {
227        IEnumerable<Type> discoveredTypes = GetTypes(type, onlyInstantiable);
228        if (assignableToAllTypes) result = result.Intersect(discoveredTypes);
229        else result = result.Union(discoveredTypes);
230      }
231      return result;
232    }
233
234    /// <summary>
235    /// Finds all types that are subtypes or equal to the specified type if they are part of the given
236    /// <paramref name="pluginDescription"/>.
237    /// </summary>
238    /// <param name="type">Most general type for which to find matching types.</param>
239    /// <param name="pluginDescription">The plugin the subtypes must be part of.</param>
240    /// <param name="onlyInstantiable">Return only types that are instantiable
241    /// (interfaces, abstract classes... are not returned)</param>
242    /// <returns>Enumerable of the discovered types.</returns>
243    internal static IEnumerable<Type> GetTypes(Type type, IPluginDescription pluginDescription, bool onlyInstantiable) {
244      PluginDescription pluginDesc = (PluginDescription)pluginDescription;
245      return from asm in AppDomain.CurrentDomain.GetAssemblies()
246             where !IsDynamicAssembly(asm)
247             where pluginDesc.AssemblyLocations.Any(location => location.Equals(Path.GetFullPath(asm.Location), StringComparison.CurrentCultureIgnoreCase))
248             from t in GetTypes(type, asm, onlyInstantiable)
249             select t;
250    }
251
252    internal static IEnumerable<Type> GetTypes(IEnumerable<Type> types, IPluginDescription pluginDescription, bool onlyInstantiable, bool assignableToAllTypes) {
253      IEnumerable<Type> result = GetTypes(types.First(), pluginDescription, onlyInstantiable);
254      foreach (Type type in types.Skip(1)) {
255        IEnumerable<Type> discoveredTypes = GetTypes(type, pluginDescription, onlyInstantiable);
256        if (assignableToAllTypes) result = result.Intersect(discoveredTypes);
257        else result = result.Union(discoveredTypes);
258      }
259      return result;
260    }
261
262    private static bool IsDynamicAssembly(Assembly asm) {
263      return (asm is System.Reflection.Emit.AssemblyBuilder) || string.IsNullOrEmpty(asm.Location);
264    }
265
266    /// <summary>
267    /// Gets types that are assignable (same of subtype) to the specified type only from the given assembly.
268    /// </summary>
269    /// <param name="type">Most general type we want to find.</param>
270    /// <param name="assembly">Assembly that should be searched for types.</param>
271    /// <param name="onlyInstantiable">Return only types that are instantiable
272    /// (interfaces, abstract classes...  are not returned)</param>
273    /// <returns>Enumerable of the discovered types.</returns>
274    private static IEnumerable<Type> GetTypes(Type type, Assembly assembly, bool onlyInstantiable) {
275      return from t in assembly.GetTypes()
276             where CheckTypeCompatibility(type, t)
277             where onlyInstantiable == false ||
278                (!t.IsAbstract && !t.IsInterface && !t.HasElementType)
279             where !IsNonDiscoverableType(t)
280             select BuildType(t, type);
281    }
282
283
284    private static bool IsNonDiscoverableType(Type t) {
285      return t.GetCustomAttributes(typeof(NonDiscoverableTypeAttribute), false).Any();
286    }
287
288    private static bool CheckTypeCompatibility(Type type, Type other) {
289      if (type.IsAssignableFrom(other))
290        return true;
291      if (type.IsGenericType && other.IsGenericType) {
292        try {
293          if (type.IsAssignableFrom(other.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArguments())))
294            return true;
295        }
296        catch (Exception) { }
297      }
298      return false;
299    }
300    private static Type BuildType(Type type, Type protoType) {
301      if (type.IsGenericType && protoType.IsGenericType)
302        return type.GetGenericTypeDefinition().MakeGenericType(protoType.GetGenericArguments());
303      else
304        return type;
305    }
306
307    private void OnPluginLoaded(PluginInfrastructureEventArgs e) {
308      if (PluginLoaded != null) PluginLoaded(this, e);
309    }
310
311    private void OnPluginUnloaded(PluginInfrastructureEventArgs e) {
312      if (PluginUnloaded != null) PluginUnloaded(this, e);
313    }
314
315    #region IApplicationManager Members
316
317    IEnumerable<T> IApplicationManager.GetInstances<T>() {
318      return GetInstances<T>();
319    }
320
321    IEnumerable<object> IApplicationManager.GetInstances(Type type) {
322      return GetInstances(type);
323    }
324
325    IEnumerable<Type> IApplicationManager.GetTypes(Type type, bool onlyInstantiable) {
326      return GetTypes(type, onlyInstantiable);
327    }
328    IEnumerable<Type> IApplicationManager.GetTypes(IEnumerable<Type> types, bool onlyInstantiable, bool assignableToAllTypes) {
329      return GetTypes(types, onlyInstantiable, assignableToAllTypes);
330    }
331
332    IEnumerable<Type> IApplicationManager.GetTypes(Type type, IPluginDescription plugin, bool onlyInstantiable) {
333      return GetTypes(type, plugin, onlyInstantiable);
334    }
335    IEnumerable<Type> IApplicationManager.GetTypes(IEnumerable<Type> types, IPluginDescription plugin, bool onlyInstantiable, bool assignableToAllTypes) {
336      return GetTypes(types, plugin, onlyInstantiable, assignableToAllTypes);
337    }
338
339    /// <summary>
340    /// Finds the plugin that declares the <paramref name="type">type</paramref>.
341    /// </summary>
342    /// <param name="type">The type of interest.</param>
343    /// <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>
344    public IPluginDescription GetDeclaringPlugin(Type type) {
345      if (type == null) throw new ArgumentNullException("type");
346      foreach (PluginDescription info in Plugins) {
347        if (info.AssemblyLocations.Contains(Path.GetFullPath(type.Assembly.Location))) return info;
348      }
349      return null;
350    }
351    #endregion
352  }
353}
Note: See TracBrowser for help on using the repository browser.