Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.PluginInfrastructure/Manager/PluginValidator.cs @ 2648

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

fixed #849 (PluginInfrastructure attempts to disable a plugin multiple times if multiple dependencies are missing)

File size: 18.1 KB
RevLine 
[2]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Text;
25using System.Reflection;
26using System.IO;
27using System.Diagnostics;
[2481]28using System.Linq;
[2527]29using System.Security;
[2]30
[2481]31
32namespace HeuristicLab.PluginInfrastructure.Manager {
[2503]33  /// <summary>
34  /// Discovers all installed plugins in the plugin directory. Checks correctness of plugin meta-data and if
35  /// all plugin files are available and checks plugin dependencies.
36  /// </summary>
37  internal sealed class PluginValidator : MarshalByRefObject {
[2489]38    internal event EventHandler<PluginInfrastructureEventArgs> PluginLoaded;
[2]39
[2481]40    private Dictionary<PluginDescription, List<string>> pluginDependencies;
[2]41
[2481]42    private List<ApplicationDescription> applications;
43    internal IEnumerable<ApplicationDescription> Applications {
[2]44      get {
[2503]45        if (string.IsNullOrEmpty(PluginDir)) throw new InvalidOperationException("PluginDir is not set.");
[2497]46        if (applications == null) DiscoverAndCheckPlugins();
[2481]47        return applications;
[2]48      }
49    }
50
[2481]51    private IEnumerable<PluginDescription> plugins;
52    internal IEnumerable<PluginDescription> Plugins {
[2]53      get {
[2503]54        if (string.IsNullOrEmpty(PluginDir)) throw new InvalidOperationException("PluginDir is not set.");
[2497]55        if (plugins == null) DiscoverAndCheckPlugins();
[2481]56        return plugins;
[29]57      }
58    }
59
[2504]60    internal string PluginDir { get; set; }
[2]61
[2504]62    internal PluginValidator() {
[2481]63      this.pluginDependencies = new Dictionary<PluginDescription, List<string>>();
[2488]64
[2497]65      // ReflectionOnlyAssemblyResolveEvent must be handled because we load assemblies from the plugin path
66      // (which is not listed in the default assembly lookup locations)
[2488]67      AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionOnlyAssemblyResolveEventHandler;
[2]68    }
69
[2488]70    private Assembly ReflectionOnlyAssemblyResolveEventHandler(object sender, ResolveEventArgs args) {
71      return Assembly.ReflectionOnlyLoad(args.Name);
72    }
[2]73
[2488]74
[2]75    /// <summary>
76    /// Init first clears all internal datastructures (including plugin lists)
77    /// 1. All assemblies in the plugins directory are loaded into the reflection only context.
[2503]78    /// 2. The validator checks if all necessary files for each plugin are available.
[2536]79    /// 3. The validator checks if all declared plugin assemblies can be loaded.
80    /// 4. The validator builds the tree of plugin descriptions (dependencies)
81    /// 5. The validator checks if there are any cycles in the plugin dependency graph and disables plugin with circular dependencies
82    /// 6. The validator checks for each plugin if any dependency is disabled.
83    /// 7. All plugins that are not disabled are loaded into the execution context.
84    /// 8. Each loaded plugin (all assemblies) is searched for a types that implement IPlugin
[2481]85    ///    then one instance of each IPlugin type is activated and the OnLoad hook is called.
[2536]86    /// 9. All types implementing IApplication are discovered
[2]87    /// </summary>
[2503]88    internal void DiscoverAndCheckPlugins() {
[2]89      pluginDependencies.Clear();
90
[2527]91      IEnumerable<Assembly> reflectionOnlyAssemblies = ReflectionOnlyLoadDlls(PluginDir);
[2481]92      IEnumerable<PluginDescription> pluginDescriptions = GatherPluginDescriptions(reflectionOnlyAssemblies);
93      CheckPluginFiles(pluginDescriptions);
[2]94
[2536]95      // check if all plugin assemblies can be loaded
[2527]96      CheckPluginAssemblies(pluginDescriptions);
97
[2481]98      // a full list of plugin descriptions is available now we can build the dependency tree
99      BuildDependencyTree(pluginDescriptions);
100
[2536]101      // check for dependency cycles
102      CheckPluginDependencyCycles(pluginDescriptions);
103
[2481]104      // recursively check if all necessary plugins are available and not disabled
105      // disable plugins with missing or disabled dependencies
106      CheckPluginDependencies(pluginDescriptions);
107
[2536]108      // mark all plugins as enabled that were not disabled in CheckPluginFiles, CheckPluginAssemblies,
109      // CheckCircularDependencies, or CheckPluginDependencies
[2488]110      foreach (var desc in pluginDescriptions)
111        if (desc.PluginState != PluginState.Disabled)
112          desc.Enable();
113
[2481]114      // test full loading (in contrast to reflection only loading) of plugins
115      // disables plugins that are not loaded correctly
116      LoadPlugins(pluginDescriptions);
117
118      plugins = pluginDescriptions;
119      DiscoverApplications();
120    }
121
122    private void DiscoverApplications() {
123      applications = new List<ApplicationDescription>();
[2]124
[2488]125      foreach (IApplication application in GetApplications()) {
[2504]126        Type appType = application.GetType();
127        ApplicationAttribute attr = (from x in appType.GetCustomAttributes(typeof(ApplicationAttribute), false)
128                                     select (ApplicationAttribute)x).Single();
[2481]129        ApplicationDescription info = new ApplicationDescription();
[2]130        info.Name = application.Name;
[2504]131        info.Version = appType.Assembly.GetName().Version;
[2]132        info.Description = application.Description;
[2504]133        info.AutoRestart = attr.RestartOnErrors;
134        info.DeclaringAssemblyName = appType.Assembly.GetName().Name;
135        info.DeclaringTypeName = appType.Namespace + "." + application.GetType().Name;
[2]136
[29]137        applications.Add(info);
[2]138      }
139    }
140
[2504]141    private static IEnumerable<IApplication> GetApplications() {
[2488]142      return from asm in AppDomain.CurrentDomain.GetAssemblies()
143             from t in asm.GetTypes()
144             where typeof(IApplication).IsAssignableFrom(t) &&
145               !t.IsAbstract && !t.IsInterface && !t.HasElementType
146             select (IApplication)Activator.CreateInstance(t);
147    }
148
[2527]149    private static IEnumerable<Assembly> ReflectionOnlyLoadDlls(string baseDir) {
[2]150      List<Assembly> assemblies = new List<Assembly>();
[2527]151      // recursively load .dll files in subdirectories
152      foreach (string dirName in Directory.GetDirectories(baseDir)) {
153        assemblies.AddRange(ReflectionOnlyLoadDlls(dirName));
154      }
[2481]155      // try to load each .dll file in the plugin directory into the reflection only context
[2527]156      foreach (string filename in Directory.GetFiles(baseDir, "*.dll")) {
[535]157        try {
[2481]158          assemblies.Add(Assembly.ReflectionOnlyLoadFrom(filename));
[1229]159        }
[2503]160        catch (BadImageFormatException) { } // just ignore the case that the .dll file is not a CLR assembly (e.g. a native dll)
[2527]161        catch (FileLoadException) { }
162        catch (SecurityException) { }
[2]163      }
164      return assemblies;
165    }
166
[2527]167    /// <summary>
168    /// Checks if all plugin assemblies can be loaded. If an assembly can't be loaded the plugin is disabled.
169    /// </summary>
170    /// <param name="pluginDescriptions"></param>
171    private void CheckPluginAssemblies(IEnumerable<PluginDescription> pluginDescriptions) {
172      foreach (var desc in pluginDescriptions.Where(x => x.PluginState != PluginState.Disabled)) {
173        try {
174          foreach (var asm in desc.Assemblies) {
175            Assembly.ReflectionOnlyLoadFrom(asm);
176          }
177        }
178        catch (BadImageFormatException) {
179          // disable the plugin
180          desc.Disable();
181        }
182        catch (FileNotFoundException) {
183          // disable the plugin
184          desc.Disable();
185        }
186        catch (FileLoadException) {
187          // disable the plugin
188          desc.Disable();
189        }
190        catch (ArgumentException) {
191          // disable the plugin
192          desc.Disable();
193        }
194        catch (SecurityException) {
195          // disable the plugin
196          desc.Disable();
197        }
198      }
199    }
200
201
[2481]202    // find all types implementing IPlugin in the reflectionOnlyAssemblies and create a list of plugin descriptions
203    // the dependencies in the plugin descriptions are not yet set correctly because we need to create
204    // the full list of all plugin descriptions first
205    private IEnumerable<PluginDescription> GatherPluginDescriptions(IEnumerable<Assembly> assemblies) {
206      List<PluginDescription> pluginDescriptions = new List<PluginDescription>();
[1229]207      foreach (Assembly assembly in assemblies) {
[2]208        // GetExportedTypes throws FileNotFoundException when a referenced assembly
209        // of the current assembly is missing.
210        try {
[2527]211          // if there is a type that implements IPlugin
212          // use AssemblyQualifiedName to compare the types because we can't directly
213          // compare ReflectionOnly types and execution types
214          var assemblyPluginDescriptions = from t in assembly.GetExportedTypes()
215                                           where !t.IsAbstract && t.GetInterfaces().Any(x => x.AssemblyQualifiedName == typeof(IPlugin).AssemblyQualifiedName)
216                                           select GetPluginDescription(t);
217          pluginDescriptions.AddRange(assemblyPluginDescriptions);
[1229]218        }
[2497]219        // ignore exceptions. Just don't yield a plugin description when an exception is thrown
[2489]220        catch (FileNotFoundException) {
[1229]221        }
[2489]222        catch (FileLoadException) {
[2]223        }
[2489]224        catch (InvalidPluginException) {
[1395]225        }
[2]226      }
[2481]227      return pluginDescriptions;
[2]228    }
229
230    /// <summary>
231    /// Extracts plugin information for this type.
232    /// Reads plugin name, list and type of files and dependencies of the plugin. This information is necessary for
233    /// plugin dependency checking before plugin activation.
234    /// </summary>
235    /// <param name="t"></param>
[2481]236    private PluginDescription GetPluginDescription(Type pluginType) {
[2]237      // get all attributes of that type
[2481]238      IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(pluginType);
[2]239      List<string> pluginAssemblies = new List<string>();
240      List<string> pluginDependencies = new List<string>();
[29]241      List<string> pluginFiles = new List<string>();
[2481]242      string pluginName = null;
[2513]243      string pluginDescription = null;
[2481]244      // iterate through all custom attributes and search for attributed that we are interested in
[1229]245      foreach (CustomAttributeData attributeData in attributes) {
[2488]246        if (IsAttributeDataForType(attributeData, typeof(PluginAttribute))) {
[2481]247          pluginName = (string)attributeData.ConstructorArguments[0].Value;
[2513]248          if (attributeData.ConstructorArguments.Count() == 2) {
249            pluginDescription = (string)attributeData.ConstructorArguments[1].Value;
250          } else pluginDescription = pluginName;
[2481]251        } else if (IsAttributeDataForType(attributeData, typeof(PluginDependencyAttribute))) {
252          pluginDependencies.Add((string)attributeData.ConstructorArguments[0].Value);
253        } else if (IsAttributeDataForType(attributeData, typeof(PluginFileAttribute))) {
254          string pluginFileName = (string)attributeData.ConstructorArguments[0].Value;
255          PluginFileType fileType = (PluginFileType)attributeData.ConstructorArguments[1].Value;
[2527]256          pluginFiles.Add(Path.GetFullPath(Path.Combine(PluginDir, pluginFileName)));
[2481]257          if (fileType == PluginFileType.Assembly) {
[2527]258            pluginAssemblies.Add(Path.GetFullPath(Path.Combine(PluginDir, pluginFileName)));
[2]259          }
260        }
261      }
262
[2504]263      var buildDates = from attr in CustomAttributeData.GetCustomAttributes(pluginType.Assembly)
264                       where IsAttributeDataForType(attr, typeof(AssemblyBuildDateAttribute))
265                       select (string)attr.ConstructorArguments[0].Value;
266
[29]267      // minimal sanity check of the attribute values
[2517]268      if (!string.IsNullOrEmpty(pluginName) &&
[2481]269          pluginFiles.Count > 0 &&
[2504]270          pluginAssemblies.Count > 0 &&
271          buildDates.Count() == 1) {
[2481]272        // create a temporary PluginDescription that contains the attribute values
273        PluginDescription info = new PluginDescription();
[29]274        info.Name = pluginName;
[2513]275        info.Description = pluginDescription;
[2481]276        info.Version = pluginType.Assembly.GetName().Version;
[2504]277        info.BuildDate = DateTime.Parse(buildDates.Single(), System.Globalization.CultureInfo.InvariantCulture);
[2481]278        info.AddAssemblies(pluginAssemblies);
279        info.AddFiles(pluginFiles);
280
[29]281        this.pluginDependencies[info] = pluginDependencies;
[2481]282        return info;
[2]283      } else {
[2481]284        throw new InvalidPluginException("Invalid metadata in plugin " + pluginType.ToString());
[2]285      }
286    }
287
[2504]288    private static bool IsAttributeDataForType(CustomAttributeData attributeData, Type attributeType) {
[2481]289      return attributeData.Constructor.DeclaringType.AssemblyQualifiedName == attributeType.AssemblyQualifiedName;
290    }
291
292    // builds a dependency tree of all plugin descriptions
293    // searches matching plugin descriptions based on the list of dependency names for each plugin
294    // and sets the dependencies in the plugin descriptions
295    private void BuildDependencyTree(IEnumerable<PluginDescription> pluginDescriptions) {
296      foreach (var desc in pluginDescriptions) {
297        foreach (string pluginName in pluginDependencies[desc]) {
298          var matchingDescriptions = pluginDescriptions.Where(x => x.Name == pluginName);
299          if (matchingDescriptions.Count() > 0) {
[2517]300            desc.AddDependency(matchingDescriptions.Single());
[2481]301          } else {
302            // no plugin description that matches the dependency name is available => plugin is disabled
[2648]303            desc.Disable(); break;
[2481]304          }
[29]305        }
[2481]306      }
307    }
[37]308
[2536]309    private void CheckPluginDependencyCycles(IEnumerable<PluginDescription> pluginDescriptions) {
310      foreach (var plugin in pluginDescriptions) {
311        // if the plugin is not disabled anyway check if there are cycles
312        if (plugin.PluginState != PluginState.Disabled && HasCycleInDependencies(plugin, plugin.Dependencies)) {
313          plugin.Disable();
314        }
315      }
316    }
317
318    private bool HasCycleInDependencies(PluginDescription plugin, IEnumerable<PluginDescription> pluginDependencies) {
319      foreach (var dep in pluginDependencies) {
320        // if one of the dependencies is the original plugin we found a cycle and can return
321        // if the dependency is already disabled we can ignore the cycle detection because we will disable the plugin anyway
322        // if following one of the dependencies recursively leads to a cycle then we also return
323        if (dep == plugin || dep.PluginState == PluginState.Disabled || HasCycleInDependencies(plugin, dep.Dependencies)) return true;
324      }
325      // no cycle found and none of the direct and indirect dependencies is disabled
326      return false;
327    }
328
[2481]329    private void CheckPluginDependencies(IEnumerable<PluginDescription> pluginDescriptions) {
330      foreach (PluginDescription pluginDescription in pluginDescriptions.Where(x => x.PluginState != PluginState.Disabled)) {
331        if (IsAnyDependencyDisabled(pluginDescription)) {
[2488]332          pluginDescription.Disable();
[29]333        }
334      }
335    }
336
337
[2481]338    private bool IsAnyDependencyDisabled(PluginDescription descr) {
339      if (descr.PluginState == PluginState.Disabled) return true;
340      foreach (PluginDescription dependency in descr.Dependencies) {
341        if (IsAnyDependencyDisabled(dependency)) return true;
[2]342      }
[2481]343      return false;
[2]344    }
345
[2481]346    private void LoadPlugins(IEnumerable<PluginDescription> pluginDescriptions) {
[2]347      // load all loadable plugins (all dependencies available) into the execution context
[2517]348      foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(pluginDescriptions
[2488]349                                                                                .Where(x => x.PluginState != PluginState.Disabled))) {
[2481]350        List<Type> types = new List<Type>();
351        foreach (string assembly in desc.Assemblies) {
352          var asm = Assembly.LoadFrom(assembly);
353          foreach (Type t in asm.GetTypes()) {
354            if (typeof(IPlugin).IsAssignableFrom(t)) {
355              types.Add(t);
356            }
[2]357          }
358        }
359
[2481]360        foreach (Type pluginType in types) {
[1229]361          if (!pluginType.IsAbstract && !pluginType.IsInterface && !pluginType.HasElementType) {
[2]362            IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);
[2481]363            plugin.OnLoad();
[2503]364            OnPluginLoaded(new PluginInfrastructureEventArgs("Plugin loaded", plugin.Name));
[2]365          }
366        }
[2489]367        desc.Load();
[2]368      }
369    }
[91]370
[2481]371    // checks if all declared plugin files are actually available and disables plugins with missing files
[2527]372    private void CheckPluginFiles(IEnumerable<PluginDescription> pluginDescriptions) {
[2481]373      foreach (PluginDescription desc in pluginDescriptions) {
374        if (!CheckPluginFiles(desc)) {
[2488]375          desc.Disable();
[29]376        }
[2]377      }
378    }
379
[2527]380    private bool CheckPluginFiles(PluginDescription pluginDescription) {
[2504]381      foreach (string filename in pluginDescription.Files) {
[2527]382        if (!FileLiesInDirectory(PluginDir, filename) ||
383          !File.Exists(filename)) {
[2]384          return false;
385        }
386      }
387      return true;
388    }
389
[2527]390    private static bool FileLiesInDirectory(string dir, string fileName) {
391      var basePath = Path.GetFullPath(dir);
392      return Path.GetFullPath(fileName).StartsWith(basePath);
393    }
394
[2503]395    internal void OnPluginLoaded(PluginInfrastructureEventArgs e) {
[2489]396      if (PluginLoaded != null)
[2503]397        PluginLoaded(this, e);
[2489]398    }
399
[1189]400    /// <summary>
[2497]401    /// Initializes the life time service with an infinite lease time.
[1189]402    /// </summary>
403    /// <returns><c>null</c>.</returns>
[2]404    public override object InitializeLifetimeService() {
405      return null;
406    }
407  }
408}
Note: See TracBrowser for help on using the repository browser.