Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 2615 was 2536, checked in by gkronber, 15 years ago

Implemented cycle detection of plugin dependencies. #799

File size: 18.1 KB
Line 
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;
28using System.Linq;
29using System.Security;
30
31
32namespace HeuristicLab.PluginInfrastructure.Manager {
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 {
38    internal event EventHandler<PluginInfrastructureEventArgs> PluginLoaded;
39
40    private Dictionary<PluginDescription, List<string>> pluginDependencies;
41
42    private List<ApplicationDescription> applications;
43    internal IEnumerable<ApplicationDescription> Applications {
44      get {
45        if (string.IsNullOrEmpty(PluginDir)) throw new InvalidOperationException("PluginDir is not set.");
46        if (applications == null) DiscoverAndCheckPlugins();
47        return applications;
48      }
49    }
50
51    private IEnumerable<PluginDescription> plugins;
52    internal IEnumerable<PluginDescription> Plugins {
53      get {
54        if (string.IsNullOrEmpty(PluginDir)) throw new InvalidOperationException("PluginDir is not set.");
55        if (plugins == null) DiscoverAndCheckPlugins();
56        return plugins;
57      }
58    }
59
60    internal string PluginDir { get; set; }
61
62    internal PluginValidator() {
63      this.pluginDependencies = new Dictionary<PluginDescription, List<string>>();
64
65      // ReflectionOnlyAssemblyResolveEvent must be handled because we load assemblies from the plugin path
66      // (which is not listed in the default assembly lookup locations)
67      AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionOnlyAssemblyResolveEventHandler;
68    }
69
70    private Assembly ReflectionOnlyAssemblyResolveEventHandler(object sender, ResolveEventArgs args) {
71      return Assembly.ReflectionOnlyLoad(args.Name);
72    }
73
74
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.
78    /// 2. The validator checks if all necessary files for each plugin are available.
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
85    ///    then one instance of each IPlugin type is activated and the OnLoad hook is called.
86    /// 9. All types implementing IApplication are discovered
87    /// </summary>
88    internal void DiscoverAndCheckPlugins() {
89      pluginDependencies.Clear();
90
91      IEnumerable<Assembly> reflectionOnlyAssemblies = ReflectionOnlyLoadDlls(PluginDir);
92      IEnumerable<PluginDescription> pluginDescriptions = GatherPluginDescriptions(reflectionOnlyAssemblies);
93      CheckPluginFiles(pluginDescriptions);
94
95      // check if all plugin assemblies can be loaded
96      CheckPluginAssemblies(pluginDescriptions);
97
98      // a full list of plugin descriptions is available now we can build the dependency tree
99      BuildDependencyTree(pluginDescriptions);
100
101      // check for dependency cycles
102      CheckPluginDependencyCycles(pluginDescriptions);
103
104      // recursively check if all necessary plugins are available and not disabled
105      // disable plugins with missing or disabled dependencies
106      CheckPluginDependencies(pluginDescriptions);
107
108      // mark all plugins as enabled that were not disabled in CheckPluginFiles, CheckPluginAssemblies,
109      // CheckCircularDependencies, or CheckPluginDependencies
110      foreach (var desc in pluginDescriptions)
111        if (desc.PluginState != PluginState.Disabled)
112          desc.Enable();
113
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>();
124
125      foreach (IApplication application in GetApplications()) {
126        Type appType = application.GetType();
127        ApplicationAttribute attr = (from x in appType.GetCustomAttributes(typeof(ApplicationAttribute), false)
128                                     select (ApplicationAttribute)x).Single();
129        ApplicationDescription info = new ApplicationDescription();
130        info.Name = application.Name;
131        info.Version = appType.Assembly.GetName().Version;
132        info.Description = application.Description;
133        info.AutoRestart = attr.RestartOnErrors;
134        info.DeclaringAssemblyName = appType.Assembly.GetName().Name;
135        info.DeclaringTypeName = appType.Namespace + "." + application.GetType().Name;
136
137        applications.Add(info);
138      }
139    }
140
141    private static IEnumerable<IApplication> GetApplications() {
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
149    private static IEnumerable<Assembly> ReflectionOnlyLoadDlls(string baseDir) {
150      List<Assembly> assemblies = new List<Assembly>();
151      // recursively load .dll files in subdirectories
152      foreach (string dirName in Directory.GetDirectories(baseDir)) {
153        assemblies.AddRange(ReflectionOnlyLoadDlls(dirName));
154      }
155      // try to load each .dll file in the plugin directory into the reflection only context
156      foreach (string filename in Directory.GetFiles(baseDir, "*.dll")) {
157        try {
158          assemblies.Add(Assembly.ReflectionOnlyLoadFrom(filename));
159        }
160        catch (BadImageFormatException) { } // just ignore the case that the .dll file is not a CLR assembly (e.g. a native dll)
161        catch (FileLoadException) { }
162        catch (SecurityException) { }
163      }
164      return assemblies;
165    }
166
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
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>();
207      foreach (Assembly assembly in assemblies) {
208        // GetExportedTypes throws FileNotFoundException when a referenced assembly
209        // of the current assembly is missing.
210        try {
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);
218        }
219        // ignore exceptions. Just don't yield a plugin description when an exception is thrown
220        catch (FileNotFoundException) {
221        }
222        catch (FileLoadException) {
223        }
224        catch (InvalidPluginException) {
225        }
226      }
227      return pluginDescriptions;
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>
236    private PluginDescription GetPluginDescription(Type pluginType) {
237      // get all attributes of that type
238      IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(pluginType);
239      List<string> pluginAssemblies = new List<string>();
240      List<string> pluginDependencies = new List<string>();
241      List<string> pluginFiles = new List<string>();
242      string pluginName = null;
243      string pluginDescription = null;
244      // iterate through all custom attributes and search for attributed that we are interested in
245      foreach (CustomAttributeData attributeData in attributes) {
246        if (IsAttributeDataForType(attributeData, typeof(PluginAttribute))) {
247          pluginName = (string)attributeData.ConstructorArguments[0].Value;
248          if (attributeData.ConstructorArguments.Count() == 2) {
249            pluginDescription = (string)attributeData.ConstructorArguments[1].Value;
250          } else pluginDescription = pluginName;
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;
256          pluginFiles.Add(Path.GetFullPath(Path.Combine(PluginDir, pluginFileName)));
257          if (fileType == PluginFileType.Assembly) {
258            pluginAssemblies.Add(Path.GetFullPath(Path.Combine(PluginDir, pluginFileName)));
259          }
260        }
261      }
262
263      var buildDates = from attr in CustomAttributeData.GetCustomAttributes(pluginType.Assembly)
264                       where IsAttributeDataForType(attr, typeof(AssemblyBuildDateAttribute))
265                       select (string)attr.ConstructorArguments[0].Value;
266
267      // minimal sanity check of the attribute values
268      if (!string.IsNullOrEmpty(pluginName) &&
269          pluginFiles.Count > 0 &&
270          pluginAssemblies.Count > 0 &&
271          buildDates.Count() == 1) {
272        // create a temporary PluginDescription that contains the attribute values
273        PluginDescription info = new PluginDescription();
274        info.Name = pluginName;
275        info.Description = pluginDescription;
276        info.Version = pluginType.Assembly.GetName().Version;
277        info.BuildDate = DateTime.Parse(buildDates.Single(), System.Globalization.CultureInfo.InvariantCulture);
278        info.AddAssemblies(pluginAssemblies);
279        info.AddFiles(pluginFiles);
280
281        this.pluginDependencies[info] = pluginDependencies;
282        return info;
283      } else {
284        throw new InvalidPluginException("Invalid metadata in plugin " + pluginType.ToString());
285      }
286    }
287
288    private static bool IsAttributeDataForType(CustomAttributeData attributeData, Type attributeType) {
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) {
300            desc.AddDependency(matchingDescriptions.Single());
301          } else {
302            // no plugin description that matches the dependency name is available => plugin is disabled
303            desc.Disable();
304          }
305        }
306      }
307    }
308
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
329    private void CheckPluginDependencies(IEnumerable<PluginDescription> pluginDescriptions) {
330      foreach (PluginDescription pluginDescription in pluginDescriptions.Where(x => x.PluginState != PluginState.Disabled)) {
331        if (IsAnyDependencyDisabled(pluginDescription)) {
332          pluginDescription.Disable();
333        }
334      }
335    }
336
337
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;
342      }
343      return false;
344    }
345
346    private void LoadPlugins(IEnumerable<PluginDescription> pluginDescriptions) {
347      // load all loadable plugins (all dependencies available) into the execution context
348      foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(pluginDescriptions
349                                                                                .Where(x => x.PluginState != PluginState.Disabled))) {
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            }
357          }
358        }
359
360        foreach (Type pluginType in types) {
361          if (!pluginType.IsAbstract && !pluginType.IsInterface && !pluginType.HasElementType) {
362            IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);
363            plugin.OnLoad();
364            OnPluginLoaded(new PluginInfrastructureEventArgs("Plugin loaded", plugin.Name));
365          }
366        }
367        desc.Load();
368      }
369    }
370
371    // checks if all declared plugin files are actually available and disables plugins with missing files
372    private void CheckPluginFiles(IEnumerable<PluginDescription> pluginDescriptions) {
373      foreach (PluginDescription desc in pluginDescriptions) {
374        if (!CheckPluginFiles(desc)) {
375          desc.Disable();
376        }
377      }
378    }
379
380    private bool CheckPluginFiles(PluginDescription pluginDescription) {
381      foreach (string filename in pluginDescription.Files) {
382        if (!FileLiesInDirectory(PluginDir, filename) ||
383          !File.Exists(filename)) {
384          return false;
385        }
386      }
387      return true;
388    }
389
390    private static bool FileLiesInDirectory(string dir, string fileName) {
391      var basePath = Path.GetFullPath(dir);
392      return Path.GetFullPath(fileName).StartsWith(basePath);
393    }
394
395    internal void OnPluginLoaded(PluginInfrastructureEventArgs e) {
396      if (PluginLoaded != null)
397        PluginLoaded(this, e);
398    }
399
400    /// <summary>
401    /// Initializes the life time service with an infinite lease time.
402    /// </summary>
403    /// <returns><c>null</c>.</returns>
404    public override object InitializeLifetimeService() {
405      return null;
406    }
407  }
408}
Note: See TracBrowser for help on using the repository browser.