Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.PluginInfrastructure/3.3/SandboxApplicationManager.cs @ 12214

Last change on this file since 12214 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

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