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

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

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

File size: 18.3 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      }
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>();
206      List<string> pluginFiles = new List<string>();
207      string pluginName = "";
208      // iterate through all custom attributes and search for named arguments that we are interested in
209      foreach (CustomAttributeData attributeData in attributes) {
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        });
215        if (pluginNameArgument.MemberInfo != null) {
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        });
223        if (dependencyNameArgument.MemberInfo != null) {
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        });
234        if (filenameArg.MemberInfo != null && filetypeArg.MemberInfo != null) {
235          pluginFiles.Add(pluginDir + "/" + (string)filenameArg.TypedValue.Value);
236          if ((PluginFileType)filetypeArg.TypedValue.Value == PluginFileType.Assembly) {
237            pluginAssemblies.Add(pluginDir + "/" + (string)filenameArg.TypedValue.Value);
238          }
239        }
240      }
241
242      // minimal sanity check of the attribute values
243      if (pluginName != "" && pluginAssemblies.Count > 0) {
244        // create a temporary PluginInfo that contains the attribute values
245        PluginInfo info = new PluginInfo();
246        info.Name = pluginName;
247        info.Version = t.Assembly.GetName().Version;
248        info.Assemblies = pluginAssemblies;
249        info.Files.AddRange(pluginFiles);
250        info.Assemblies.AddRange(pluginAssemblies);
251        this.pluginDependencies[info] = pluginDependencies;
252        preloadedPluginInfos.Add(info);
253      } else {
254        throw new InvalidPluginException();
255      }
256    }
257
258    private void CheckPluginDependencies() {
259      foreach (PluginInfo pluginInfo in preloadedPluginInfos) {
260        // don't need to check plugins that are already disabled
261        if (disabledPlugins.Contains(pluginInfo)) {
262          continue;
263        }
264        visitedDependencies.Clear();
265        if (!CheckPluginDependencies(pluginInfo.Name)) {
266          PluginInfo matchingInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == pluginInfo.Name; });
267          if (matchingInfo == null) throw new InvalidProgramException(); // shouldn't happen
268          foreach (string dependency in pluginDependencies[matchingInfo]) {
269            PluginInfo dependencyInfo = new PluginInfo();
270            dependencyInfo.Name = dependency;
271            pluginInfo.Dependencies.Add(dependencyInfo);
272          }
273
274          pluginInfo.Message = "Disabled: missing plugin dependency.";
275          disabledPlugins.Add(pluginInfo);
276        }
277      }
278    }
279
280    private List<string> visitedDependencies = new List<string>();
281    private bool CheckPluginDependencies(string pluginName) {
282      if (!preloadedPluginInfos.Exists(delegate(PluginInfo info) { return pluginName == info.Name; }) ||
283        disabledPlugins.Exists(delegate(PluginInfo info) { return pluginName == info.Name; }) ||
284        visitedDependencies.Contains(pluginName)) {
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
290
291        PluginInfo matchingInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == pluginName; });
292        if (matchingInfo == null) throw new InvalidProgramException(); // shouldn't happen
293        foreach (string dependency in pluginDependencies[matchingInfo]) {
294          visitedDependencies.Add(pluginName);
295          if (CheckPluginDependencies(dependency) == false) {
296            // if only one dependency is not available that means that the current plugin also is unloadable
297            return false;
298          }
299          visitedDependencies.Remove(pluginName);
300        }
301        // all dependencies OK
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
310      foreach (PluginInfo pluginInfo in preloadedPluginInfos) {
311        if (!disabledPlugins.Contains(pluginInfo)) {
312          foreach (string assembly in pluginInfo.Assemblies) {
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
320      foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
321        // don't search for plugins in the PluginInfrastructure
322        if (assembly == this.GetType().Assembly)
323          continue;
324        Type[] availablePluginTypes = service.GetTypes(typeof(IPlugin), assembly);
325        foreach (Type pluginType in availablePluginTypes) {
326          if (!pluginType.IsAbstract && !pluginType.IsInterface && !pluginType.HasElementType) {
327            IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);
328            PluginAction(this, new PluginManagerActionEventArgs(plugin.Name, PluginManagerAction.InitializingPlugin));
329            plugin.OnLoad();
330            pluginsByName.Add(plugin.Name, plugin);
331          }
332        }
333      }
334
335      foreach (IPlugin plugin in pluginsByName.Values) {
336        PluginInfo pluginInfo = GetPluginInfo(plugin);
337        allPlugins.Add(pluginInfo, plugin);
338        PluginAction(this, new PluginManagerActionEventArgs(plugin.Name, PluginManagerAction.InitializedPlugin));
339      }
340    }
341    private PluginInfo GetPluginInfo(IPlugin plugin) {
342      if (pluginInfos.ContainsKey(plugin)) {
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;
349
350      object[] customAttributes = plugin.GetType().Assembly.GetCustomAttributes(typeof(AssemblyBuildDateAttribute), false);
351      if (customAttributes.Length > 0) {
352        pluginInfo.BuildDate = ((AssemblyBuildDateAttribute)customAttributes[0]).BuildDate;
353      }
354
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
360        pluginInfo.Files.Add(filename.Replace('/', '\\'));
361      });
362
363      PluginInfo preloadedInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == plugin.Name; });
364      foreach (string assembly in preloadedInfo.Assemblies) {
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      }
369      foreach (string dependency in pluginDependencies[preloadedInfo]) {
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() {
379      foreach (PluginInfo plugin in preloadedPluginInfos) {
380        if (!CheckPluginFiles(plugin)) {
381          plugin.Message = "Disabled: missing plugin file.";
382          disabledPlugins.Add(plugin);
383        }
384      }
385    }
386
387    private bool CheckPluginFiles(PluginInfo pluginInfo) {
388      foreach (string filename in pluginInfo.Files) {
389        if (!File.Exists(filename)) {
390          if (MissingPluginFile != null) {
391            MissingPluginFile(pluginInfo.Name, filename);
392          }
393          return false;
394        }
395      }
396      return true;
397    }
398
399    /// <summary>
400    /// Initializes the life time service with an infinte lease time.
401    /// </summary>
402    /// <returns><c>null</c>.</returns>
403    public override object InitializeLifetimeService() {
404      return null;
405    }
406
407    internal void OnDelete(PluginInfo pluginInfo) {
408      IPlugin plugin = FindPlugin(pluginInfo);
409      if (plugin != null) plugin.OnDelete();
410    }
411
412    internal void OnInstall(PluginInfo pluginInfo) {
413      IPlugin plugin = FindPlugin(pluginInfo);
414      if (plugin != null) plugin.OnInstall();
415    }
416
417    internal void OnPreUpdate(PluginInfo pluginInfo) {
418      IPlugin plugin = FindPlugin(pluginInfo);
419      if (plugin != null) plugin.OnPreUpdate();
420    }
421
422    internal void OnPostUpdate(PluginInfo pluginInfo) {
423      IPlugin plugin = FindPlugin(pluginInfo);
424      if (plugin != null) plugin.OnPostUpdate();
425    }
426  }
427}
Note: See TracBrowser for help on using the repository browser.