Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.PluginInfrastructure/Loader.cs @ 1416

Last change on this file since 1416 was 1395, checked in by gkronber, 16 years ago

Fixed #458 (HeuristicLab crashes when it tries to load plugins with missing attributes).

File size: 18.8 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.Windows.Forms;
29
30namespace HeuristicLab.PluginInfrastructure {
31  internal class Loader : MarshalByRefObject {
32    /// <summary>
33    /// Event handler for loaded plugins.
34    /// </summary>
35    /// <param name="pluginName">The plugin that has been loaded.</param>
36    public delegate void PluginLoadedEventHandler(string pluginName);
37
38    public delegate void PluginLoadFailedEventHandler(string pluginName, string args);
39
40    private Dictionary<PluginInfo, List<string>> pluginDependencies = new Dictionary<PluginInfo, List<string>>();
41    private List<PluginInfo> preloadedPluginInfos = new List<PluginInfo>();
42    private Dictionary<IPlugin, PluginInfo> pluginInfos = new Dictionary<IPlugin, PluginInfo>();
43    private Dictionary<PluginInfo, IPlugin> allPlugins = new Dictionary<PluginInfo, IPlugin>();
44    private List<PluginInfo> disabledPlugins = new List<PluginInfo>();
45    private string pluginDir = Application.StartupPath + "/" + HeuristicLab.PluginInfrastructure.Properties.Settings.Default.PluginDir;
46
47    internal event PluginLoadFailedEventHandler MissingPluginFile;
48    internal event PluginManagerActionEventHandler PluginAction;
49
50    internal ICollection<PluginInfo> ActivePlugins {
51      get {
52        List<PluginInfo> list = new List<PluginInfo>();
53        foreach (PluginInfo info in allPlugins.Keys) {
54          if (!disabledPlugins.Exists(delegate(PluginInfo disabledInfo) { return info.Name == disabledInfo.Name; })) {
55            list.Add(info);
56          }
57        }
58        return list;
59      }
60    }
61
62    internal ICollection<PluginInfo> InstalledPlugins {
63      get {
64        return new List<PluginInfo>(allPlugins.Keys);
65      }
66    }
67
68    internal ICollection<PluginInfo> DisabledPlugins {
69      get {
70        return disabledPlugins;
71      }
72    }
73
74    private ICollection<ApplicationInfo> applications;
75    internal ICollection<ApplicationInfo> InstalledApplications {
76      get {
77        return applications;
78      }
79    }
80
81    private IPlugin FindPlugin(PluginInfo plugin) {
82      if (allPlugins.ContainsKey(plugin)) {
83        return allPlugins[plugin];
84      } else return null;
85    }
86
87
88    /// <summary>
89    /// Init first clears all internal datastructures (including plugin lists)
90    /// 1. All assemblies in the plugins directory are loaded into the reflection only context.
91    /// 2. The loader checks if all dependencies for each assembly are available.
92    /// 3. All assemblies for which there are no dependencies missing are loaded into the execution context.
93    /// 4. Each loaded assembly is searched for a type that implements IPlugin, then one instance of each IPlugin type is activated
94    /// 5. The loader checks if all necessary files for each plugin are available.
95    /// 6. The loader builds an acyclic graph of PluginDescriptions (childs are dependencies of a plugin) based on the
96    /// list of assemblies of an plugin and the list of dependencies for each of those assemblies
97    /// </summary>
98    /// <exception cref="FileLoadException">Thrown when the file could not be loaded.</exception>
99    internal void Init() {
100      AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += delegate(object sender, ResolveEventArgs args) {
101        try {
102          return Assembly.ReflectionOnlyLoad(args.Name);
103        }
104        catch (FileLoadException ex) {
105          return null;
106        }
107      };
108      allPlugins.Clear();
109      disabledPlugins.Clear();
110      pluginInfos.Clear();
111      pluginsByName.Clear();
112      pluginDependencies.Clear();
113
114      List<Assembly> assemblies = ReflectionOnlyLoadDlls();
115      CheckAssemblyDependencies(assemblies);
116      CheckPluginFiles();
117      CheckPluginDependencies();
118      LoadPlugins();
119
120      DiscoveryService service = new DiscoveryService();
121      IApplication[] apps = service.GetInstances<IApplication>();
122      applications = new List<ApplicationInfo>();
123
124      foreach (IApplication application in apps) {
125        ApplicationInfo info = new ApplicationInfo();
126        info.Name = application.Name;
127        info.Version = application.Version;
128        info.Description = application.Description;
129        info.AutoRestart = application.AutoRestart;
130        info.PluginAssembly = application.GetType().Assembly.GetName().Name;
131        info.PluginType = application.GetType().Namespace + "." + application.GetType().Name;
132
133        applications.Add(info);
134      }
135    }
136
137    private List<Assembly> ReflectionOnlyLoadDlls() {
138      List<Assembly> assemblies = new List<Assembly>();
139      // load all installed plugins into the reflection only context
140      foreach (String filename in Directory.GetFiles(pluginDir, "*.dll")) {
141        try {
142          assemblies.Add(ReflectionOnlyLoadDll(filename));
143        }
144        catch (BadImageFormatException) { } // just ignore the case that the .dll file is not actually a CLR dll
145      }
146      return assemblies;
147    }
148
149    private Assembly ReflectionOnlyLoadDll(string filename) {
150      return Assembly.ReflectionOnlyLoadFrom(filename);
151    }
152
153    private void CheckAssemblyDependencies(List<Assembly> assemblies) {
154      foreach (Assembly assembly in assemblies) {
155        // GetExportedTypes throws FileNotFoundException when a referenced assembly
156        // of the current assembly is missing.
157        try {
158          Type[] exported = assembly.GetExportedTypes();
159
160          foreach (Type t in exported) {
161            // if there is a type that implements IPlugin
162            if (Array.Exists<Type>(t.GetInterfaces(), delegate(Type iface) {
163              // use AssemblyQualifiedName to compare the types because we can't directly
164              // compare ReflectionOnly types and Execution types
165              return iface.AssemblyQualifiedName == typeof(IPlugin).AssemblyQualifiedName;
166            })) {
167              // fetch the attributes of the IPlugin type
168              GetPluginAttributeData(t);
169            }
170          }
171        }
172        catch (FileNotFoundException ex) {
173          PluginInfo info = new PluginInfo();
174          AssemblyName name = assembly.GetName();
175          info.Name = name.Name;
176          info.Version = name.Version;
177          info.Assemblies.Add(assembly.FullName);
178          info.Files.Add(assembly.Location);
179          info.Message = "File not found: " + ex.FileName;
180          disabledPlugins.Add(info);
181        }
182        catch (FileLoadException ex) {
183          PluginInfo info = new PluginInfo();
184          AssemblyName name = assembly.GetName();
185          info.Name = name.Name;
186          info.Version = name.Version;
187          info.Files.Add(assembly.Location);
188          info.Assemblies.Add(assembly.FullName);
189          info.Message = "Couldn't load file: " + ex.FileName;
190          disabledPlugins.Add(info);
191        }
192        catch (InvalidPluginException ex) {
193          PluginInfo info = new PluginInfo();
194          AssemblyName name = assembly.GetName();
195          info.Name = name.Name;
196          info.Version = name.Version;
197          info.Files.Add(assembly.Location);
198          info.Assemblies.Add(assembly.FullName);
199          info.Message = "Couldn't load plugin class from assembly: " + assembly.GetName().Name+". Necessary plugin attributes are missing.";
200          disabledPlugins.Add(info);
201        }
202      }
203    }
204
205    /// <summary>
206    /// Extracts plugin information for this type.
207    /// Reads plugin name, list and type of files and dependencies of the plugin. This information is necessary for
208    /// plugin dependency checking before plugin activation.
209    /// </summary>
210    /// <param name="t"></param>
211    private void GetPluginAttributeData(Type t) {
212      // get all attributes of that type
213      IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(t);
214      List<string> pluginAssemblies = new List<string>();
215      List<string> pluginDependencies = new List<string>();
216      List<string> pluginFiles = new List<string>();
217      string pluginName = "";
218      // iterate through all custom attributes and search for named arguments that we are interested in
219      foreach (CustomAttributeData attributeData in attributes) {
220        List<CustomAttributeNamedArgument> namedArguments = new List<CustomAttributeNamedArgument>(attributeData.NamedArguments);
221        // if the current attribute contains a named argument with the name "Name" then extract the plugin name
222        CustomAttributeNamedArgument pluginNameArgument = namedArguments.Find(delegate(CustomAttributeNamedArgument arg) {
223          return arg.MemberInfo.Name == "Name";
224        });
225        if (pluginNameArgument.MemberInfo != null) {
226          pluginName = (string)pluginNameArgument.TypedValue.Value;
227        }
228        // if the current attribute contains a named argument with the name "Dependency" then extract the dependency
229        // and store it in the list of all dependencies
230        CustomAttributeNamedArgument dependencyNameArgument = namedArguments.Find(delegate(CustomAttributeNamedArgument arg) {
231          return arg.MemberInfo.Name == "Dependency";
232        });
233        if (dependencyNameArgument.MemberInfo != null) {
234          pluginDependencies.Add((string)dependencyNameArgument.TypedValue.Value);
235        }
236        // if the current attribute has a named argument "Filename" then find if the argument "Filetype" is also supplied
237        // and if the filetype is Assembly then store the name of the assembly in the list of assemblies
238        CustomAttributeNamedArgument filenameArg = namedArguments.Find(delegate(CustomAttributeNamedArgument arg) {
239          return arg.MemberInfo.Name == "Filename";
240        });
241        CustomAttributeNamedArgument filetypeArg = namedArguments.Find(delegate(CustomAttributeNamedArgument arg) {
242          return arg.MemberInfo.Name == "Filetype";
243        });
244        if (filenameArg.MemberInfo != null && filetypeArg.MemberInfo != null) {
245          pluginFiles.Add(pluginDir + "/" + (string)filenameArg.TypedValue.Value);
246          if ((PluginFileType)filetypeArg.TypedValue.Value == PluginFileType.Assembly) {
247            pluginAssemblies.Add(pluginDir + "/" + (string)filenameArg.TypedValue.Value);
248          }
249        }
250      }
251
252      // minimal sanity check of the attribute values
253      if (pluginName != "" && pluginAssemblies.Count > 0) {
254        // create a temporary PluginInfo that contains the attribute values
255        PluginInfo info = new PluginInfo();
256        info.Name = pluginName;
257        info.Version = t.Assembly.GetName().Version;
258        info.Assemblies = pluginAssemblies;
259        info.Files.AddRange(pluginFiles);
260        info.Assemblies.AddRange(pluginAssemblies);
261        this.pluginDependencies[info] = pluginDependencies;
262        preloadedPluginInfos.Add(info);
263      } else {
264        throw new InvalidPluginException();
265      }
266    }
267
268    private void CheckPluginDependencies() {
269      foreach (PluginInfo pluginInfo in preloadedPluginInfos) {
270        // don't need to check plugins that are already disabled
271        if (disabledPlugins.Contains(pluginInfo)) {
272          continue;
273        }
274        visitedDependencies.Clear();
275        if (!CheckPluginDependencies(pluginInfo.Name)) {
276          PluginInfo matchingInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == pluginInfo.Name; });
277          if (matchingInfo == null) throw new InvalidProgramException(); // shouldn't happen
278          foreach (string dependency in pluginDependencies[matchingInfo]) {
279            PluginInfo dependencyInfo = new PluginInfo();
280            dependencyInfo.Name = dependency;
281            pluginInfo.Dependencies.Add(dependencyInfo);
282          }
283
284          pluginInfo.Message = "Disabled: missing plugin dependency.";
285          disabledPlugins.Add(pluginInfo);
286        }
287      }
288    }
289
290    private List<string> visitedDependencies = new List<string>();
291    private bool CheckPluginDependencies(string pluginName) {
292      if (!preloadedPluginInfos.Exists(delegate(PluginInfo info) { return pluginName == info.Name; }) ||
293        disabledPlugins.Exists(delegate(PluginInfo info) { return pluginName == info.Name; }) ||
294        visitedDependencies.Contains(pluginName)) {
295        // when the plugin is not available return false;
296        return false;
297      } else {
298        // otherwise check if all dependencies of the plugin are OK
299        // if yes then this plugin is also ok and we store it in the list of loadable plugins
300
301        PluginInfo matchingInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == pluginName; });
302        if (matchingInfo == null) throw new InvalidProgramException(); // shouldn't happen
303        foreach (string dependency in pluginDependencies[matchingInfo]) {
304          visitedDependencies.Add(pluginName);
305          if (CheckPluginDependencies(dependency) == false) {
306            // if only one dependency is not available that means that the current plugin also is unloadable
307            return false;
308          }
309          visitedDependencies.Remove(pluginName);
310        }
311        // all dependencies OK
312        return true;
313      }
314    }
315
316
317    private Dictionary<string, IPlugin> pluginsByName = new Dictionary<string, IPlugin>();
318    private void LoadPlugins() {
319      // load all loadable plugins (all dependencies available) into the execution context
320      foreach (PluginInfo pluginInfo in preloadedPluginInfos) {
321        if (!disabledPlugins.Contains(pluginInfo)) {
322          foreach (string assembly in pluginInfo.Assemblies) {
323            Assembly.LoadFrom(assembly);
324          }
325        }
326      }
327
328      DiscoveryService service = new DiscoveryService();
329      // now search and instantiate an IPlugin type in each loaded assembly
330      foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
331        // don't search for plugins in the PluginInfrastructure
332        if (assembly == this.GetType().Assembly)
333          continue;
334        Type[] availablePluginTypes = service.GetTypes(typeof(IPlugin), assembly);
335        foreach (Type pluginType in availablePluginTypes) {
336          if (!pluginType.IsAbstract && !pluginType.IsInterface && !pluginType.HasElementType) {
337            IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);
338            PluginAction(this, new PluginManagerActionEventArgs(plugin.Name, PluginManagerAction.InitializingPlugin));
339            plugin.OnLoad();
340            pluginsByName.Add(plugin.Name, plugin);
341          }
342        }
343      }
344
345      foreach (IPlugin plugin in pluginsByName.Values) {
346        PluginInfo pluginInfo = GetPluginInfo(plugin);
347        allPlugins.Add(pluginInfo, plugin);
348        PluginAction(this, new PluginManagerActionEventArgs(plugin.Name, PluginManagerAction.InitializedPlugin));
349      }
350    }
351    private PluginInfo GetPluginInfo(IPlugin plugin) {
352      if (pluginInfos.ContainsKey(plugin)) {
353        return pluginInfos[plugin];
354      }
355      // store the data of the plugin in a description file which can be used without loading the plugin assemblies
356      PluginInfo pluginInfo = new PluginInfo();
357      pluginInfo.Name = plugin.Name;
358      pluginInfo.Version = plugin.Version;
359
360      object[] customAttributes = plugin.GetType().Assembly.GetCustomAttributes(typeof(AssemblyBuildDateAttribute), false);
361      if (customAttributes.Length > 0) {
362        pluginInfo.BuildDate = ((AssemblyBuildDateAttribute)customAttributes[0]).BuildDate;
363      }
364
365      string baseDir = AppDomain.CurrentDomain.BaseDirectory;
366
367      Array.ForEach<string>(plugin.Files, delegate(string file) {
368        string filename = pluginDir + "/" + file;
369        // always use \ as the directory separator
370        pluginInfo.Files.Add(filename.Replace('/', '\\'));
371      });
372
373      PluginInfo preloadedInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == plugin.Name; });
374      foreach (string assembly in preloadedInfo.Assemblies) {
375        // always use \ as directory separator (this is necessary for discovery of types in
376        // plugins see DiscoveryService.GetTypes()
377        pluginInfo.Assemblies.Add(assembly.Replace('/', '\\'));
378      }
379      foreach (string dependency in pluginDependencies[preloadedInfo]) {
380        // accumulate the dependencies of each assembly into the dependencies of the whole plugin
381        PluginInfo dependencyInfo = GetPluginInfo(pluginsByName[dependency]);
382        pluginInfo.Dependencies.Add(dependencyInfo);
383      }
384      pluginInfos[plugin] = pluginInfo;
385      return pluginInfo;
386    }
387
388    private void CheckPluginFiles() {
389      foreach (PluginInfo plugin in preloadedPluginInfos) {
390        if (!CheckPluginFiles(plugin)) {
391          plugin.Message = "Disabled: missing plugin file.";
392          disabledPlugins.Add(plugin);
393        }
394      }
395    }
396
397    private bool CheckPluginFiles(PluginInfo pluginInfo) {
398      foreach (string filename in pluginInfo.Files) {
399        if (!File.Exists(filename)) {
400          if (MissingPluginFile != null) {
401            MissingPluginFile(pluginInfo.Name, filename);
402          }
403          return false;
404        }
405      }
406      return true;
407    }
408
409    /// <summary>
410    /// Initializes the life time service with an infinte lease time.
411    /// </summary>
412    /// <returns><c>null</c>.</returns>
413    public override object InitializeLifetimeService() {
414      return null;
415    }
416
417    internal void OnDelete(PluginInfo pluginInfo) {
418      IPlugin plugin = FindPlugin(pluginInfo);
419      if (plugin != null) plugin.OnDelete();
420    }
421
422    internal void OnInstall(PluginInfo pluginInfo) {
423      IPlugin plugin = FindPlugin(pluginInfo);
424      if (plugin != null) plugin.OnInstall();
425    }
426
427    internal void OnPreUpdate(PluginInfo pluginInfo) {
428      IPlugin plugin = FindPlugin(pluginInfo);
429      if (plugin != null) plugin.OnPreUpdate();
430    }
431
432    internal void OnPostUpdate(PluginInfo pluginInfo) {
433      IPlugin plugin = FindPlugin(pluginInfo);
434      if (plugin != null) plugin.OnPostUpdate();
435    }
436  }
437}
Note: See TracBrowser for help on using the repository browser.