Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.PluginInfrastructure/3.3/DefaultApplicationManager.cs @ 5924

Last change on this file since 5924 was 5903, checked in by gkronber, 14 years ago

#1454: renamed parameter and minor changes.

File size: 15.9 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 DefaultApplicationManager 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 DefaultApplicationManager is registered as ApplicationManager.Manager singleton for each HL application
35  /// started via the plugin infrastructure.
36  /// </summary>
37  internal sealed class DefaultApplicationManager : 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    private 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 DefaultApplicationManager()
70      : base() {
71      loadedAssemblies = new Dictionary<string, Assembly>();
72      loadedPlugins = new List<IPlugin>();
73      AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => {
74        if (loadedAssemblies.ContainsKey(args.Name)) {
75          return loadedAssemblies[args.Name];
76        }
77        return null;
78      };
79    }
80
81    /// <summary>
82    /// Prepares the application domain for the execution of an HL application.
83    /// Pre-loads all <paramref name="plugins"/>.
84    /// </summary>
85    /// <param name="apps">Enumerable of available HL applications.</param>
86    /// <param name="plugins">Enumerable of plugins that should be pre-loaded.</param>
87    internal void PrepareApplicationDomain(IEnumerable<ApplicationDescription> apps, IEnumerable<PluginDescription> plugins) {
88      this.plugins = new List<PluginDescription>(plugins);
89      this.applications = new List<ApplicationDescription>(apps);
90      ApplicationManager.RegisterApplicationManager(this);
91      LoadPlugins(plugins);
92    }
93
94    /// <summary>
95    /// Loads the <paramref name="plugins"/> into this application domain.
96    /// </summary>
97    /// <param name="plugins">Enumerable of plugins that should be loaded.</param>
98    private void LoadPlugins(IEnumerable<PluginDescription> plugins) {
99      // load all loadable plugins (all dependencies available) into the execution context
100      foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(plugins.Where(x => x.PluginState != PluginState.Disabled))) {
101        foreach (string fileName in desc.AssemblyLocations) {
102          // load assembly reflection only first to get the full assembly name
103          var reflectionOnlyAssembly = Assembly.ReflectionOnlyLoadFrom(fileName);
104          // load the assembly into execution context using full assembly name
105          var asm = Assembly.Load(reflectionOnlyAssembly.FullName);
106          RegisterLoadedAssembly(asm);
107          // instantiate and load all plugins in this assembly
108          foreach (var plugin in GetInstances<IPlugin>(asm)) {
109            plugin.OnLoad();
110            loadedPlugins.Add(plugin);
111          }
112        }
113        OnPluginLoaded(new PluginInfrastructureEventArgs(desc));
114        desc.Load();
115      }
116    }
117
118    /// <summary>
119    /// Runs the application declared in <paramref name="appInfo"/>.
120    /// This is a synchronous call. When the application is terminated all plugins are unloaded.
121    /// </summary>
122    /// <param name="appInfo">Description of the application to run</param>
123    internal void Run(ApplicationDescription appInfo) {
124      IApplication runnablePlugin = (IApplication)Activator.CreateInstance(appInfo.DeclaringAssemblyName, appInfo.DeclaringTypeName).Unwrap();
125      try {
126        runnablePlugin.Run();
127      }
128      finally {
129        // unload plugins in reverse order
130        foreach (var plugin in loadedPlugins.Reverse<IPlugin>()) {
131          plugin.OnUnload();
132        }
133        foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(plugins.Where(x => x.PluginState != PluginState.Disabled))) {
134          desc.Unload();
135          OnPluginUnloaded(new PluginInfrastructureEventArgs(desc));
136        }
137      }
138    }
139
140    /// <summary>
141    /// Loads raw assemblies dynamically from a byte array
142    /// </summary>
143    /// <param name="assemblies">bytearray of all raw assemblies that should be loaded</param>
144    internal void LoadAssemblies(IEnumerable<byte[]> assemblies) {
145      foreach (byte[] asm in assemblies) {
146        Assembly loadedAsm = Assembly.Load(asm);
147        RegisterLoadedAssembly(loadedAsm);
148      }
149    }
150
151    // register assembly in the assembly cache for the AssemblyResolveEvent
152    private void RegisterLoadedAssembly(Assembly asm) {
153      loadedAssemblies.Add(asm.FullName, asm);
154      loadedAssemblies.Add(asm.GetName().Name, asm); // add short name
155    }
156
157    /// <summary>
158    /// Creates an instance of all types that are subtypes or the same type of the specified type and declared in <paramref name="plugin"/>
159    /// </summary>
160    /// <typeparam name="T">Most general type.</typeparam>
161    /// <returns>Enumerable of the created instances.</returns>
162    internal static IEnumerable<T> GetInstances<T>(IPluginDescription plugin) where T : class {
163      List<T> instances = new List<T>();
164      foreach (Type t in GetTypes(typeof(T), plugin, true)) {
165        T instance = null;
166        try { instance = (T)Activator.CreateInstance(t); }
167        catch { }
168        if (instance != null) instances.Add(instance);
169      }
170      return instances;
171    }
172    /// <summary>
173    /// 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"/>.
174    /// </summary>
175    /// <typeparam name="T">Most general type.</typeparam>
176    /// <param name="asm">Declaring assembly.</param>
177    /// <returns>Enumerable of the created instances.</returns>
178    private static IEnumerable<T> GetInstances<T>(Assembly asm) where T : class {
179      List<T> instances = new List<T>();
180      foreach (Type t in GetTypes(typeof(T), asm, true)) {
181        T instance = null;
182        try { instance = (T)Activator.CreateInstance(t); }
183        catch { }
184        if (instance != null) instances.Add(instance);
185      }
186      return instances;
187    }
188    /// <summary>
189    /// Creates an instance of all types that are subtypes or the same type of the specified type
190    /// </summary>
191    /// <typeparam name="T">Most general type.</typeparam>
192    /// <returns>Enumerable of the created instances.</returns>
193    internal static IEnumerable<T> GetInstances<T>() where T : class {
194      return from i in GetInstances(typeof(T))
195             select (T)i;
196    }
197
198    /// <summary>
199    /// Creates an instance of all types that are subtypes or the same type of the specified type
200    /// </summary>
201    /// <param name="type">Most general type.</param>
202    /// <returns>Enumerable of the created instances.</returns>
203    internal static IEnumerable<object> GetInstances(Type type) {
204      List<object> instances = new List<object>();
205      foreach (Type t in GetTypes(type, true)) {
206        object instance = null;
207        try { instance = Activator.CreateInstance(t); }
208        catch { }
209        if (instance != null) instances.Add(instance);
210      }
211      return instances;
212    }
213
214    /// <summary>
215    /// Finds all types that are subtypes or equal to the specified type.
216    /// </summary>
217    /// <param name="type">Most general type for which to find matching types.</param>
218    /// <param name="onlyInstantiable">Return only types that are instantiable
219    /// (interfaces, abstract classes... are not returned)</param>
220    /// <returns>Enumerable of the discovered types.</returns>
221    internal static IEnumerable<Type> GetTypes(Type type, bool onlyInstantiable) {
222      return from asm in AppDomain.CurrentDomain.GetAssemblies()
223             from t in GetTypes(type, asm, onlyInstantiable)
224             select t;
225    }
226
227    internal static IEnumerable<Type> GetTypes(IEnumerable<Type> types, bool onlyInstantiable, bool assignableToAllTypes) {
228      IEnumerable<Type> result = GetTypes(types.First(), onlyInstantiable);
229      foreach (Type type in types.Skip(1)) {
230        IEnumerable<Type> discoveredTypes = GetTypes(type, onlyInstantiable);
231        if (assignableToAllTypes) result = result.Intersect(discoveredTypes);
232        else result = result.Union(discoveredTypes);
233      }
234      return result;
235    }
236
237    /// <summary>
238    /// Finds all types that are subtypes or equal to the specified type if they are part of the given
239    /// <paramref name="pluginDescription"/>.
240    /// </summary>
241    /// <param name="type">Most general type for which to find matching types.</param>
242    /// <param name="pluginDescription">The plugin the subtypes must be part of.</param>
243    /// <param name="onlyInstantiable">Return only types that are instantiable
244    /// (interfaces, abstract classes... are not returned)</param>
245    /// <returns>Enumerable of the discovered types.</returns>
246    internal static IEnumerable<Type> GetTypes(Type type, IPluginDescription pluginDescription, bool onlyInstantiable) {
247      PluginDescription pluginDesc = (PluginDescription)pluginDescription;
248      return from asm in AppDomain.CurrentDomain.GetAssemblies()
249             where !IsDynamicAssembly(asm)
250             where pluginDesc.AssemblyLocations.Any(location => location.Equals(Path.GetFullPath(asm.Location), StringComparison.CurrentCultureIgnoreCase))
251             from t in GetTypes(type, asm, onlyInstantiable)
252             select t;
253    }
254
255    internal static IEnumerable<Type> GetTypes(IEnumerable<Type> types, IPluginDescription pluginDescription, bool onlyInstantiable, bool assignableToAllTypes) {
256      IEnumerable<Type> result = GetTypes(types.First(), pluginDescription, onlyInstantiable);
257      foreach (Type type in types.Skip(1)) {
258        IEnumerable<Type> discoveredTypes = GetTypes(type, pluginDescription, onlyInstantiable);
259        if (assignableToAllTypes) result = result.Intersect(discoveredTypes);
260        else result = result.Union(discoveredTypes);
261      }
262      return result;
263    }
264
265    private static bool IsDynamicAssembly(Assembly asm) {
266      return (asm is System.Reflection.Emit.AssemblyBuilder) || string.IsNullOrEmpty(asm.Location);
267    }
268
269    /// <summary>
270    /// Gets types that are assignable (same of subtype) to the specified type only from the given assembly.
271    /// </summary>
272    /// <param name="type">Most general type we want to find.</param>
273    /// <param name="assembly">Assembly that should be searched for types.</param>
274    /// <param name="onlyInstantiable">Return only types that are instantiable
275    /// (interfaces, abstract classes...  are not returned)</param>
276    /// <returns>Enumerable of the discovered types.</returns>
277    private static IEnumerable<Type> GetTypes(Type type, Assembly assembly, bool onlyInstantiable) {
278      return from t in assembly.GetTypes()
279             where CheckTypeCompatibility(type, t)
280             where onlyInstantiable == false ||
281                (!t.IsAbstract && !t.IsInterface && !t.HasElementType)
282             where !IsNonDiscoverableType(t)
283             select BuildType(t, type);
284    }
285
286    private static bool IsNonDiscoverableType(Type t) {
287      return t.GetCustomAttributes(typeof(NonDiscoverableTypeAttribute), false).Any();
288    }
289
290    private static bool CheckTypeCompatibility(Type type, Type other) {
291      if (type.IsAssignableFrom(other))
292        return true;
293      if (type.IsGenericType && other.IsGenericType) {
294        try {
295          if (type.IsAssignableFrom(other.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArguments())))
296            return true;
297        }
298        catch (Exception) { }
299      }
300      return false;
301    }
302    private static Type BuildType(Type type, Type protoType) {
303      if (type.IsGenericType && protoType.IsGenericType)
304        return type.GetGenericTypeDefinition().MakeGenericType(protoType.GetGenericArguments());
305      else
306        return type;
307    }
308
309    private void OnPluginLoaded(PluginInfrastructureEventArgs e) {
310      if (PluginLoaded != null) PluginLoaded(this, e);
311    }
312
313    private void OnPluginUnloaded(PluginInfrastructureEventArgs e) {
314      if (PluginUnloaded != null) PluginUnloaded(this, e);
315    }
316
317    // infinite lease time
318    /// <summary>
319    /// Initializes the life time service with infinite lease time.
320    /// </summary>
321    /// <returns><c>null</c>.</returns>
322    public override object InitializeLifetimeService() {
323      return null;
324    }
325
326    #region IApplicationManager Members
327
328    IEnumerable<T> IApplicationManager.GetInstances<T>() {
329      return GetInstances<T>();
330    }
331
332    IEnumerable<object> IApplicationManager.GetInstances(Type type) {
333      return GetInstances(type);
334    }
335
336    IEnumerable<Type> IApplicationManager.GetTypes(Type type, bool onlyInstantiable) {
337      return GetTypes(type, onlyInstantiable);
338    }
339    IEnumerable<Type> IApplicationManager.GetTypes(IEnumerable<Type> types, bool onlyInstantiable, bool assignableToAllTypes) {
340      return GetTypes(types, onlyInstantiable, assignableToAllTypes);
341    }
342
343    IEnumerable<Type> IApplicationManager.GetTypes(Type type, IPluginDescription plugin, bool onlyInstantiable) {
344      return GetTypes(type, plugin, onlyInstantiable);
345    }
346    IEnumerable<Type> IApplicationManager.GetTypes(IEnumerable<Type> types, IPluginDescription plugin, bool onlyInstantiable, bool assignableToAllTypes) {
347      return GetTypes(types, plugin, onlyInstantiable, assignableToAllTypes);
348    }
349
350
351    /// <summary>
352    /// Finds the plugin that declares the <paramref name="type">type</paramref>.
353    /// </summary>
354    /// <param name="type">The type of interest.</param>
355    /// <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>
356    public IPluginDescription GetDeclaringPlugin(Type type) {
357      if (type == null) throw new ArgumentNullException("type");
358      foreach (PluginDescription info in Plugins) {
359        if (info.AssemblyLocations.Contains(Path.GetFullPath(type.Assembly.Location))) return info;
360      }
361      return null;
362    }
363    #endregion
364  }
365}
Note: See TracBrowser for help on using the repository browser.