Free cookie consent management tool by TermsFeed Policy Generator

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

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

Merged implementation of #471 (OnLoad hook for plugins) (r1228) from CEDMA branch into the trunk.

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