Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 91 was 91, checked in by gkronber, 16 years ago
  • added an attribute for the build time of an assembly.
  • build-date is automatically updated via SubWCRev in the pre-build action.
  • adapted PluginManager to correctly handle plugins with same version but newer build date

fixes ticket #39

File size: 17.7 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.PluginAssembly = application.GetType().Assembly.GetName().Name;
123        info.PluginType = application.GetType().Namespace + "." + application.GetType().Name;
124
125        applications.Add(info);
126      }
127    }
128
129    private List<Assembly> ReflectionOnlyLoadDlls() {
130      List<Assembly> assemblies = new List<Assembly>();
131      // load all installed plugins into the reflection only context
132      foreach(String filename in Directory.GetFiles(pluginDir, "*.dll")) {
133        assemblies.Add(ReflectionOnlyLoadDll(filename));
134      }
135      return assemblies;
136    }
137
138    private Assembly ReflectionOnlyLoadDll(string filename) {
139      return Assembly.ReflectionOnlyLoadFrom(filename);
140    }
141
142    private void CheckAssemblyDependencies(List<Assembly> assemblies) {
143      foreach(Assembly assembly in assemblies) {
144        // GetExportedTypes throws FileNotFoundException when a referenced assembly
145        // of the current assembly is missing.
146        try {
147          Type[] exported = assembly.GetExportedTypes();
148
149          foreach(Type t in exported) {
150            // if there is a type that implements IPlugin
151            if(Array.Exists<Type>(t.GetInterfaces(), delegate(Type iface) {
152              // use AssemblyQualifiedName to compare the types because we can't directly
153              // compare ReflectionOnly types and Execution types
154              return iface.AssemblyQualifiedName == typeof(IPlugin).AssemblyQualifiedName;
155            })) {
156              // fetch the attributes of the IPlugin type
157              GetPluginAttributeData(t);
158            }
159          }
160        } catch(FileNotFoundException ex) {
161          PluginInfo info = new PluginInfo();
162          AssemblyName name = assembly.GetName();
163          info.Name = name.Name;
164          info.Version = name.Version;
165          info.Assemblies.Add(assembly.FullName);
166          info.Files.Add(assembly.Location);
167          info.Message = "File not found: " + ex.FileName;
168          disabledPlugins.Add(info);
169        } catch(FileLoadException ex) {
170          PluginInfo info = new PluginInfo();
171          AssemblyName name = assembly.GetName();
172          info.Name = name.Name;
173          info.Version = name.Version;
174          info.Files.Add(assembly.Location);
175          info.Assemblies.Add(assembly.FullName);
176          info.Message = "Couldn't load file: " + ex.FileName;
177          disabledPlugins.Add(info);
178        }
179      }
180    }
181
182    /// <summary>
183    /// Extracts plugin information for this type.
184    /// Reads plugin name, list and type of files and dependencies of the plugin. This information is necessary for
185    /// plugin dependency checking before plugin activation.
186    /// </summary>
187    /// <param name="t"></param>
188    private void GetPluginAttributeData(Type t) {
189      // get all attributes of that type
190      IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(t);
191      List<string> pluginAssemblies = new List<string>();
192      List<string> pluginDependencies = new List<string>();
193      List<string> pluginFiles = new List<string>();
194      string pluginName = "";
195      // iterate through all custom attributes and search for named arguments that we are interested in
196      foreach(CustomAttributeData attributeData in attributes) {
197        List<CustomAttributeNamedArgument> namedArguments = new List<CustomAttributeNamedArgument>(attributeData.NamedArguments);
198        // if the current attribute contains a named argument with the name "Name" then extract the plugin name
199        CustomAttributeNamedArgument pluginNameArgument = namedArguments.Find(delegate(CustomAttributeNamedArgument arg) {
200          return arg.MemberInfo.Name == "Name";
201        });
202        if(pluginNameArgument.MemberInfo != null) {
203          pluginName = (string)pluginNameArgument.TypedValue.Value;
204        }
205        // if the current attribute contains a named argument with the name "Dependency" then extract the dependency
206        // and store it in the list of all dependencies
207        CustomAttributeNamedArgument dependencyNameArgument = namedArguments.Find(delegate(CustomAttributeNamedArgument arg) {
208          return arg.MemberInfo.Name == "Dependency";
209        });
210        if(dependencyNameArgument.MemberInfo != null) {
211          pluginDependencies.Add((string)dependencyNameArgument.TypedValue.Value);
212        }
213        // if the current attribute has a named argument "Filename" then find if the argument "Filetype" is also supplied
214        // and if the filetype is Assembly then store the name of the assembly in the list of assemblies
215        CustomAttributeNamedArgument filenameArg = namedArguments.Find(delegate(CustomAttributeNamedArgument arg) {
216          return arg.MemberInfo.Name == "Filename";
217        });
218        CustomAttributeNamedArgument filetypeArg = namedArguments.Find(delegate(CustomAttributeNamedArgument arg) {
219          return arg.MemberInfo.Name == "Filetype";
220        });
221        if(filenameArg.MemberInfo != null && filetypeArg.MemberInfo != null) {
222          pluginFiles.Add(pluginDir + "/" + (string)filenameArg.TypedValue.Value);
223          if((PluginFileType)filetypeArg.TypedValue.Value == PluginFileType.Assembly) {
224            pluginAssemblies.Add(pluginDir + "/" + (string)filenameArg.TypedValue.Value);
225          }
226        }
227      }
228
229      // minimal sanity check of the attribute values
230      if(pluginName != "" && pluginAssemblies.Count > 0) {
231        // create a temporary PluginInfo that contains the attribute values
232        PluginInfo info = new PluginInfo();
233        info.Name = pluginName;
234        info.Version = t.Assembly.GetName().Version;
235        info.Assemblies = pluginAssemblies;
236        info.Files.AddRange(pluginFiles);
237        info.Assemblies.AddRange(pluginAssemblies);
238        this.pluginDependencies[info] = pluginDependencies;
239        preloadedPluginInfos.Add(info);
240      } else {
241        throw new InvalidPluginException();
242      }
243    }
244
245    private void CheckPluginDependencies() {
246      foreach(PluginInfo pluginInfo in preloadedPluginInfos) {
247        // don't need to check plugins that are already disabled
248        if(disabledPlugins.Contains(pluginInfo)) {
249          continue;
250        }
251        visitedDependencies.Clear();
252        if(!CheckPluginDependencies(pluginInfo.Name)) {
253          PluginInfo matchingInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == pluginInfo.Name; });
254          if(matchingInfo == null) throw new InvalidProgramException(); // shouldn't happen
255          foreach(string dependency in pluginDependencies[matchingInfo]) {
256            PluginInfo dependencyInfo = new PluginInfo();
257            dependencyInfo.Name = dependency;
258            pluginInfo.Dependencies.Add(dependencyInfo);
259          }
260
261          pluginInfo.Message = "Disabled: missing plugin dependency.";
262          disabledPlugins.Add(pluginInfo);
263        }
264      }
265    }
266
267    private List<string> visitedDependencies = new List<string>();
268    private bool CheckPluginDependencies(string pluginName) {
269      if(!preloadedPluginInfos.Exists(delegate(PluginInfo info) { return pluginName == info.Name; }) ||
270        disabledPlugins.Exists(delegate(PluginInfo info) { return pluginName == info.Name; }) ||
271        visitedDependencies.Contains(pluginName)) {
272        // when the plugin is not available return false;
273        return false;
274      } else {
275        // otherwise check if all dependencies of the plugin are OK
276        // if yes then this plugin is also ok and we store it in the list of loadable plugins
277
278        PluginInfo matchingInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == pluginName; });
279        if(matchingInfo == null) throw new InvalidProgramException(); // shouldn't happen
280        foreach(string dependency in pluginDependencies[matchingInfo]) {
281          visitedDependencies.Add(pluginName);
282          if(CheckPluginDependencies(dependency) == false) {
283            // if only one dependency is not available that means that the current plugin also is unloadable
284            return false;
285          }
286          visitedDependencies.Remove(pluginName);
287        }
288        // all dependencies OK
289        return true;
290      }
291    }
292
293
294    private Dictionary<string, IPlugin> pluginsByName = new Dictionary<string, IPlugin>();
295    private void LoadPlugins() {
296      // load all loadable plugins (all dependencies available) into the execution context
297      foreach(PluginInfo pluginInfo in preloadedPluginInfos) {
298        if(!disabledPlugins.Contains(pluginInfo)) {
299          foreach(string assembly in pluginInfo.Assemblies) {
300            Assembly.LoadFrom(assembly);
301          }
302        }
303      }
304
305      DiscoveryService service = new DiscoveryService();
306      // now search and instantiate an IPlugin type in each loaded assembly
307      foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
308        // don't search for plugins in the PluginInfrastructure
309        if(assembly == this.GetType().Assembly)
310          continue;
311        Type[] availablePluginTypes = service.GetTypes(typeof(IPlugin), assembly);
312        foreach(Type pluginType in availablePluginTypes) {
313          if(!pluginType.IsAbstract && !pluginType.IsInterface && !pluginType.HasElementType) {
314            IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);
315            PluginAction(this, new PluginManagerActionEventArgs(plugin.Name, PluginManagerAction.InitializingPlugin));
316            pluginsByName.Add(plugin.Name, plugin);
317          }
318        }
319      }
320
321      foreach(IPlugin plugin in pluginsByName.Values) {
322        PluginInfo pluginInfo = GetPluginInfo(plugin);
323        allPlugins.Add(pluginInfo, plugin);
324        PluginAction(this, new PluginManagerActionEventArgs(plugin.Name, PluginManagerAction.InitializedPlugin));
325      }
326    }
327    private PluginInfo GetPluginInfo(IPlugin plugin) {
328      if(pluginInfos.ContainsKey(plugin)) {
329        return pluginInfos[plugin];
330      }
331      // store the data of the plugin in a description file which can be used without loading the plugin assemblies
332      PluginInfo pluginInfo = new PluginInfo();
333      pluginInfo.Name = plugin.Name;
334      pluginInfo.Version = plugin.Version;
335
336      object[] customAttributes = plugin.GetType().Assembly.GetCustomAttributes(typeof(AssemblyBuildDateAttribute), false);
337      if(customAttributes.Length > 0) {
338        pluginInfo.BuildDate = ((AssemblyBuildDateAttribute)customAttributes[0]).BuildDate;
339      }
340
341      string baseDir = AppDomain.CurrentDomain.BaseDirectory;
342
343      Array.ForEach<string>(plugin.Files, delegate(string file) {
344        string filename = pluginDir + "/" + file;
345        // always use \ as the directory separator
346        pluginInfo.Files.Add(filename.Replace('/', '\\'));
347      });
348
349      PluginInfo preloadedInfo = preloadedPluginInfos.Find(delegate(PluginInfo info) { return info.Name == plugin.Name; });
350      foreach(string assembly in preloadedInfo.Assemblies) {
351        // always use \ as directory separator (this is necessary for discovery of types in
352        // plugins see DiscoveryService.GetTypes()
353        pluginInfo.Assemblies.Add(assembly.Replace('/', '\\'));
354      }
355      foreach(string dependency in pluginDependencies[preloadedInfo]) {
356        // accumulate the dependencies of each assembly into the dependencies of the whole plugin
357        PluginInfo dependencyInfo = GetPluginInfo(pluginsByName[dependency]);
358        pluginInfo.Dependencies.Add(dependencyInfo);
359      }
360      pluginInfos[plugin] = pluginInfo;
361      return pluginInfo;
362    }
363
364    private void CheckPluginFiles() {
365      foreach(PluginInfo plugin in preloadedPluginInfos) {
366        if(!CheckPluginFiles(plugin)) {
367          plugin.Message = "Disabled: missing plugin file.";
368          disabledPlugins.Add(plugin);
369        }
370      }
371    }
372
373    private bool CheckPluginFiles(PluginInfo pluginInfo) {
374      foreach(string filename in pluginInfo.Files) {
375        if(!File.Exists(filename)) {
376          if(MissingPluginFile != null) {
377            MissingPluginFile(pluginInfo.Name, filename);
378          }
379          return false;
380        }
381      }
382      return true;
383    }
384
385    // infinite lease time
386    public override object InitializeLifetimeService() {
387      return null;
388    }
389
390    internal void OnDelete(PluginInfo pluginInfo) {
391      IPlugin plugin = FindPlugin(pluginInfo);
392      if(plugin!=null) plugin.OnDelete();
393    }
394
395    internal void OnInstall(PluginInfo pluginInfo) {
396      IPlugin plugin = FindPlugin(pluginInfo);
397      if(plugin != null) plugin.OnInstall();
398    }
399
400    internal void OnPreUpdate(PluginInfo pluginInfo) {
401      IPlugin plugin = FindPlugin(pluginInfo);
402      if(plugin != null) plugin.OnPreUpdate();
403    }
404
405    internal void OnPostUpdate(PluginInfo pluginInfo) {
406      IPlugin plugin = FindPlugin(pluginInfo);
407      if(plugin != null) plugin.OnPostUpdate();
408    }
409  }
410}
Note: See TracBrowser for help on using the repository browser.