Free cookie consent management tool by TermsFeed Policy Generator

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

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

added a try-catch block to handle the case that a plug-in installs a non-CLR .dll file

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