1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2010 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Text;
|
---|
25 | using System.Reflection;
|
---|
26 | using System.IO;
|
---|
27 | using System.Diagnostics;
|
---|
28 | using System.Linq;
|
---|
29 | using System.Security;
|
---|
30 |
|
---|
31 |
|
---|
32 | namespace HeuristicLab.PluginInfrastructure.Manager {
|
---|
33 | /// <summary>
|
---|
34 | /// Discovers all installed plugins in the plugin directory. Checks correctness of plugin meta-data and if
|
---|
35 | /// all plugin files are available and checks plugin dependencies.
|
---|
36 | /// </summary>
|
---|
37 | internal sealed class PluginValidator : MarshalByRefObject {
|
---|
38 | // private class to store plugin dependency declarations while reflecting over plugins
|
---|
39 | private class PluginDependency {
|
---|
40 | public string Name { get; private set; }
|
---|
41 | public Version Version { get; private set; }
|
---|
42 |
|
---|
43 | public PluginDependency(string name, Version version) {
|
---|
44 | this.Name = name;
|
---|
45 | this.Version = version;
|
---|
46 | }
|
---|
47 | }
|
---|
48 |
|
---|
49 |
|
---|
50 | internal event EventHandler<PluginInfrastructureEventArgs> PluginLoaded;
|
---|
51 |
|
---|
52 | private Dictionary<PluginDescription, IEnumerable<PluginDependency>> pluginDependencies;
|
---|
53 |
|
---|
54 | private List<ApplicationDescription> applications;
|
---|
55 | internal IEnumerable<ApplicationDescription> Applications {
|
---|
56 | get {
|
---|
57 | if (string.IsNullOrEmpty(PluginDir)) throw new InvalidOperationException("PluginDir is not set.");
|
---|
58 | if (applications == null) DiscoverAndCheckPlugins();
|
---|
59 | return applications;
|
---|
60 | }
|
---|
61 | }
|
---|
62 |
|
---|
63 | private IEnumerable<PluginDescription> plugins;
|
---|
64 | internal IEnumerable<PluginDescription> Plugins {
|
---|
65 | get {
|
---|
66 | if (string.IsNullOrEmpty(PluginDir)) throw new InvalidOperationException("PluginDir is not set.");
|
---|
67 | if (plugins == null) DiscoverAndCheckPlugins();
|
---|
68 | return plugins;
|
---|
69 | }
|
---|
70 | }
|
---|
71 |
|
---|
72 | internal string PluginDir { get; set; }
|
---|
73 |
|
---|
74 | internal PluginValidator() {
|
---|
75 | this.pluginDependencies = new Dictionary<PluginDescription, IEnumerable<PluginDependency>>();
|
---|
76 |
|
---|
77 | // ReflectionOnlyAssemblyResolveEvent must be handled because we load assemblies from the plugin path
|
---|
78 | // (which is not listed in the default assembly lookup locations)
|
---|
79 | AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionOnlyAssemblyResolveEventHandler;
|
---|
80 | }
|
---|
81 |
|
---|
82 | private Dictionary<string, Assembly> reflectionOnlyAssemblies = new Dictionary<string, Assembly>();
|
---|
83 | private Assembly ReflectionOnlyAssemblyResolveEventHandler(object sender, ResolveEventArgs args) {
|
---|
84 | if (reflectionOnlyAssemblies.ContainsKey(args.Name))
|
---|
85 | return reflectionOnlyAssemblies[args.Name];
|
---|
86 | else
|
---|
87 | return Assembly.ReflectionOnlyLoad(args.Name);
|
---|
88 | }
|
---|
89 |
|
---|
90 |
|
---|
91 | /// <summary>
|
---|
92 | /// Init first clears all internal datastructures (including plugin lists)
|
---|
93 | /// 1. All assemblies in the plugins directory are loaded into the reflection only context.
|
---|
94 | /// 2. The validator checks if all necessary files for each plugin are available.
|
---|
95 | /// 3. The validator checks if all declared plugin assemblies can be loaded.
|
---|
96 | /// 4. The validator builds the tree of plugin descriptions (dependencies)
|
---|
97 | /// 5. The validator checks if there are any cycles in the plugin dependency graph and disables plugin with circular dependencies
|
---|
98 | /// 6. The validator checks for each plugin if any dependency is disabled.
|
---|
99 | /// 7. All plugins that are not disabled are loaded into the execution context.
|
---|
100 | /// 8. Each loaded plugin (all assemblies) is searched for a types that implement IPlugin
|
---|
101 | /// then one instance of each IPlugin type is activated and the OnLoad hook is called.
|
---|
102 | /// 9. All types implementing IApplication are discovered
|
---|
103 | /// </summary>
|
---|
104 | internal void DiscoverAndCheckPlugins() {
|
---|
105 | pluginDependencies.Clear();
|
---|
106 |
|
---|
107 | IEnumerable<Assembly> reflectionOnlyAssemblies = ReflectionOnlyLoadDlls(PluginDir);
|
---|
108 | IEnumerable<PluginDescription> pluginDescriptions = GatherPluginDescriptions(reflectionOnlyAssemblies);
|
---|
109 | CheckPluginFiles(pluginDescriptions);
|
---|
110 |
|
---|
111 | // check if all plugin assemblies can be loaded
|
---|
112 | CheckPluginAssemblies(pluginDescriptions);
|
---|
113 |
|
---|
114 | // a full list of plugin descriptions is available now we can build the dependency tree
|
---|
115 | BuildDependencyTree(pluginDescriptions);
|
---|
116 |
|
---|
117 | // check for dependency cycles
|
---|
118 | CheckPluginDependencyCycles(pluginDescriptions);
|
---|
119 |
|
---|
120 | // recursively check if all necessary plugins are available and not disabled
|
---|
121 | // disable plugins with missing or disabled dependencies
|
---|
122 | CheckPluginDependencies(pluginDescriptions);
|
---|
123 |
|
---|
124 | // mark all plugins as enabled that were not disabled in CheckPluginFiles, CheckPluginAssemblies,
|
---|
125 | // CheckCircularDependencies, or CheckPluginDependencies
|
---|
126 | foreach (var desc in pluginDescriptions)
|
---|
127 | if (desc.PluginState != PluginState.Disabled)
|
---|
128 | desc.Enable();
|
---|
129 |
|
---|
130 | // test full loading (in contrast to reflection only loading) of plugins
|
---|
131 | // disables plugins that are not loaded correctly
|
---|
132 | LoadPlugins(pluginDescriptions);
|
---|
133 |
|
---|
134 | plugins = pluginDescriptions;
|
---|
135 | DiscoverApplications();
|
---|
136 | }
|
---|
137 |
|
---|
138 | private void DiscoverApplications() {
|
---|
139 | applications = new List<ApplicationDescription>();
|
---|
140 |
|
---|
141 | foreach (IApplication application in GetApplications()) {
|
---|
142 | Type appType = application.GetType();
|
---|
143 | ApplicationAttribute attr = (from x in appType.GetCustomAttributes(typeof(ApplicationAttribute), false)
|
---|
144 | select (ApplicationAttribute)x).Single();
|
---|
145 | var declaringPlugin = GetDeclaringPlugin(appType, plugins);
|
---|
146 | ApplicationDescription info = new ApplicationDescription();
|
---|
147 | info.Name = application.Name;
|
---|
148 | info.Version = declaringPlugin.Version;
|
---|
149 | info.Description = application.Description;
|
---|
150 | info.AutoRestart = attr.RestartOnErrors;
|
---|
151 | info.DeclaringAssemblyName = appType.Assembly.GetName().Name;
|
---|
152 | info.DeclaringTypeName = appType.Namespace + "." + application.GetType().Name;
|
---|
153 |
|
---|
154 | applications.Add(info);
|
---|
155 | }
|
---|
156 | }
|
---|
157 |
|
---|
158 | private static IEnumerable<IApplication> GetApplications() {
|
---|
159 | return from asm in AppDomain.CurrentDomain.GetAssemblies()
|
---|
160 | from t in asm.GetTypes()
|
---|
161 | where typeof(IApplication).IsAssignableFrom(t) &&
|
---|
162 | !t.IsAbstract && !t.IsInterface && !t.HasElementType
|
---|
163 | select (IApplication)Activator.CreateInstance(t);
|
---|
164 | }
|
---|
165 |
|
---|
166 | private IEnumerable<Assembly> ReflectionOnlyLoadDlls(string baseDir) {
|
---|
167 | List<Assembly> assemblies = new List<Assembly>();
|
---|
168 | // recursively load .dll files in subdirectories
|
---|
169 | foreach (string dirName in Directory.GetDirectories(baseDir)) {
|
---|
170 | assemblies.AddRange(ReflectionOnlyLoadDlls(dirName));
|
---|
171 | }
|
---|
172 | // try to load each .dll file in the plugin directory into the reflection only context
|
---|
173 | foreach (string filename in Directory.GetFiles(baseDir, "*.dll")) {
|
---|
174 | try {
|
---|
175 | Assembly asm = Assembly.ReflectionOnlyLoadFrom(filename);
|
---|
176 | RegisterLoadedAssembly(asm);
|
---|
177 | assemblies.Add(asm);
|
---|
178 | }
|
---|
179 | catch (BadImageFormatException) { } // just ignore the case that the .dll file is not a CLR assembly (e.g. a native dll)
|
---|
180 | catch (FileLoadException) { }
|
---|
181 | catch (SecurityException) { }
|
---|
182 | catch (ReflectionTypeLoadException) { } // referenced assemblies are missing
|
---|
183 | }
|
---|
184 | return assemblies;
|
---|
185 | }
|
---|
186 |
|
---|
187 | /// <summary>
|
---|
188 | /// Checks if all plugin assemblies can be loaded. If an assembly can't be loaded the plugin is disabled.
|
---|
189 | /// </summary>
|
---|
190 | /// <param name="pluginDescriptions"></param>
|
---|
191 | private void CheckPluginAssemblies(IEnumerable<PluginDescription> pluginDescriptions) {
|
---|
192 | foreach (var desc in pluginDescriptions.Where(x => x.PluginState != PluginState.Disabled)) {
|
---|
193 | try {
|
---|
194 | var missingAssemblies = new List<string>();
|
---|
195 | foreach (var asmLocation in desc.AssemblyLocations) {
|
---|
196 | // the assembly must have been loaded in ReflectionOnlyDlls
|
---|
197 | // so we simply determine the name of the assembly and try to find it in the cache of loaded assemblies
|
---|
198 | var asmName = AssemblyName.GetAssemblyName(asmLocation);
|
---|
199 | if (!reflectionOnlyAssemblies.ContainsKey(asmName.FullName)) {
|
---|
200 | missingAssemblies.Add(asmName.FullName);
|
---|
201 | }
|
---|
202 | }
|
---|
203 | if (missingAssemblies.Count > 0) {
|
---|
204 | StringBuilder errorStrBuiler = new StringBuilder();
|
---|
205 | errorStrBuiler.AppendLine("Missing assemblies:");
|
---|
206 | foreach (string missingAsm in missingAssemblies) {
|
---|
207 | errorStrBuiler.AppendLine(missingAsm);
|
---|
208 | }
|
---|
209 | desc.Disable(errorStrBuiler.ToString());
|
---|
210 | }
|
---|
211 | }
|
---|
212 | catch (BadImageFormatException ex) {
|
---|
213 | // disable the plugin
|
---|
214 | desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "BadImageFormatException: " + ex.Message);
|
---|
215 | }
|
---|
216 | catch (FileNotFoundException ex) {
|
---|
217 | // disable the plugin
|
---|
218 | desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "FileNotFoundException: " + ex.Message);
|
---|
219 | }
|
---|
220 | catch (FileLoadException ex) {
|
---|
221 | // disable the plugin
|
---|
222 | desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "FileLoadException: " + ex.Message);
|
---|
223 | }
|
---|
224 | catch (ArgumentException ex) {
|
---|
225 | // disable the plugin
|
---|
226 | desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "ArgumentException: " + ex.Message);
|
---|
227 | }
|
---|
228 | catch (SecurityException ex) {
|
---|
229 | // disable the plugin
|
---|
230 | desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "SecurityException: " + ex.Message);
|
---|
231 | }
|
---|
232 | }
|
---|
233 | }
|
---|
234 |
|
---|
235 |
|
---|
236 | // find all types implementing IPlugin in the reflectionOnlyAssemblies and create a list of plugin descriptions
|
---|
237 | // the dependencies in the plugin descriptions are not yet set correctly because we need to create
|
---|
238 | // the full list of all plugin descriptions first
|
---|
239 | private IEnumerable<PluginDescription> GatherPluginDescriptions(IEnumerable<Assembly> assemblies) {
|
---|
240 | List<PluginDescription> pluginDescriptions = new List<PluginDescription>();
|
---|
241 | foreach (Assembly assembly in assemblies) {
|
---|
242 | // GetExportedTypes throws FileNotFoundException when a referenced assembly
|
---|
243 | // of the current assembly is missing.
|
---|
244 | try {
|
---|
245 | // if there is a type that implements IPlugin
|
---|
246 | // use AssemblyQualifiedName to compare the types because we can't directly
|
---|
247 | // compare ReflectionOnly types and execution types
|
---|
248 | var assemblyPluginDescriptions = from t in assembly.GetExportedTypes()
|
---|
249 | where !t.IsAbstract && t.GetInterfaces().Any(x => x.AssemblyQualifiedName == typeof(IPlugin).AssemblyQualifiedName)
|
---|
250 | select GetPluginDescription(t);
|
---|
251 | pluginDescriptions.AddRange(assemblyPluginDescriptions);
|
---|
252 | }
|
---|
253 | // ignore exceptions. Just don't yield a plugin description when an exception is thrown
|
---|
254 | catch (FileNotFoundException) {
|
---|
255 | }
|
---|
256 | catch (FileLoadException) {
|
---|
257 | }
|
---|
258 | catch (InvalidPluginException) {
|
---|
259 | }
|
---|
260 | }
|
---|
261 | return pluginDescriptions;
|
---|
262 | }
|
---|
263 |
|
---|
264 | /// <summary>
|
---|
265 | /// Extracts plugin information for this type.
|
---|
266 | /// Reads plugin name, list and type of files and dependencies of the plugin. This information is necessary for
|
---|
267 | /// plugin dependency checking before plugin activation.
|
---|
268 | /// </summary>
|
---|
269 | /// <param name="pluginType"></param>
|
---|
270 | private PluginDescription GetPluginDescription(Type pluginType) {
|
---|
271 |
|
---|
272 | string pluginName, pluginDescription, pluginVersion;
|
---|
273 | string contactName, contactAddress;
|
---|
274 | GetPluginMetaData(pluginType, out pluginName, out pluginDescription, out pluginVersion);
|
---|
275 | GetPluginContactMetaData(pluginType, out contactName, out contactAddress);
|
---|
276 | var pluginFiles = GetPluginFilesMetaData(pluginType);
|
---|
277 | var pluginDependencies = GetPluginDependencyMetaData(pluginType);
|
---|
278 |
|
---|
279 | // minimal sanity check of the attribute values
|
---|
280 | if (!string.IsNullOrEmpty(pluginName) &&
|
---|
281 | pluginFiles.Count() > 0 && // at least one file
|
---|
282 | pluginFiles.Any(f => f.Type == PluginFileType.Assembly)) { // at least one assembly
|
---|
283 | // create a temporary PluginDescription that contains the attribute values
|
---|
284 | PluginDescription info = new PluginDescription();
|
---|
285 | info.Name = pluginName;
|
---|
286 | info.Description = pluginDescription;
|
---|
287 | info.Version = new Version(pluginVersion);
|
---|
288 | info.ContactName = contactName;
|
---|
289 | info.ContactEmail = contactAddress;
|
---|
290 | info.LicenseText = ReadLicenseFiles(pluginFiles);
|
---|
291 | info.AddFiles(pluginFiles);
|
---|
292 |
|
---|
293 | this.pluginDependencies[info] = pluginDependencies;
|
---|
294 | return info;
|
---|
295 | } else {
|
---|
296 | throw new InvalidPluginException("Invalid metadata in plugin " + pluginType.ToString());
|
---|
297 | }
|
---|
298 | }
|
---|
299 |
|
---|
300 | private string ReadLicenseFiles(IEnumerable<PluginFile> pluginFiles) {
|
---|
301 | // combine the contents of all plugin files
|
---|
302 | var licenseFiles = from file in pluginFiles
|
---|
303 | where file.Type == PluginFileType.License
|
---|
304 | select file;
|
---|
305 | if (licenseFiles.Count() == 0) return string.Empty;
|
---|
306 | StringBuilder licenseTextBuilder = new StringBuilder();
|
---|
307 | licenseTextBuilder.AppendLine(File.ReadAllText(licenseFiles.First().Name));
|
---|
308 | foreach (var licenseFile in licenseFiles.Skip(1)) {
|
---|
309 | licenseTextBuilder.AppendLine().AppendLine(); // leave some empty space between multiple license files
|
---|
310 | licenseTextBuilder.AppendLine(File.ReadAllText(licenseFile.Name));
|
---|
311 | }
|
---|
312 | return licenseTextBuilder.ToString();
|
---|
313 | }
|
---|
314 |
|
---|
315 | private static IEnumerable<PluginDependency> GetPluginDependencyMetaData(Type pluginType) {
|
---|
316 | // get all attributes of type PluginDependency
|
---|
317 | var dependencyAttributes = from attr in CustomAttributeData.GetCustomAttributes(pluginType)
|
---|
318 | where IsAttributeDataForType(attr, typeof(PluginDependencyAttribute))
|
---|
319 | select attr;
|
---|
320 |
|
---|
321 | foreach (var dependencyAttr in dependencyAttributes) {
|
---|
322 | string name = (string)dependencyAttr.ConstructorArguments[0].Value;
|
---|
323 | Version version = new Version("0.0.0.0"); // default version
|
---|
324 | // check if version is given for now
|
---|
325 | // later when the constructor of PluginDependencyAttribute with only one argument has been removed
|
---|
326 | // this conditional can be removed as well
|
---|
327 | if (dependencyAttr.ConstructorArguments.Count > 1) {
|
---|
328 | try {
|
---|
329 | version = new Version((string)dependencyAttr.ConstructorArguments[1].Value); // might throw FormatException
|
---|
330 | }
|
---|
331 | catch (FormatException ex) {
|
---|
332 | throw new InvalidPluginException("Invalid version format of dependency " + name + " in plugin " + pluginType.ToString(), ex);
|
---|
333 | }
|
---|
334 | }
|
---|
335 | yield return new PluginDependency(name, version);
|
---|
336 | }
|
---|
337 | }
|
---|
338 |
|
---|
339 | private static void GetPluginContactMetaData(Type pluginType, out string contactName, out string contactAddress) {
|
---|
340 | // get attribute of type ContactInformation if there is any
|
---|
341 | var contactInfoAttribute = (from attr in CustomAttributeData.GetCustomAttributes(pluginType)
|
---|
342 | where IsAttributeDataForType(attr, typeof(ContactInformationAttribute))
|
---|
343 | select attr).SingleOrDefault();
|
---|
344 |
|
---|
345 | if (contactInfoAttribute != null) {
|
---|
346 | contactName = (string)contactInfoAttribute.ConstructorArguments[0].Value;
|
---|
347 | contactAddress = (string)contactInfoAttribute.ConstructorArguments[1].Value;
|
---|
348 | } else {
|
---|
349 | contactName = string.Empty;
|
---|
350 | contactAddress = string.Empty;
|
---|
351 | }
|
---|
352 | }
|
---|
353 |
|
---|
354 | // not static because we need the PluginDir property
|
---|
355 | private IEnumerable<PluginFile> GetPluginFilesMetaData(Type pluginType) {
|
---|
356 | // get all attributes of type PluginFileAttribute
|
---|
357 | var pluginFileAttributes = from attr in CustomAttributeData.GetCustomAttributes(pluginType)
|
---|
358 | where IsAttributeDataForType(attr, typeof(PluginFileAttribute))
|
---|
359 | select attr;
|
---|
360 | foreach (var pluginFileAttribute in pluginFileAttributes) {
|
---|
361 | string pluginFileName = (string)pluginFileAttribute.ConstructorArguments[0].Value;
|
---|
362 | PluginFileType fileType = (PluginFileType)pluginFileAttribute.ConstructorArguments[1].Value;
|
---|
363 | yield return new PluginFile(Path.GetFullPath(Path.Combine(PluginDir, pluginFileName)), fileType);
|
---|
364 | }
|
---|
365 | }
|
---|
366 |
|
---|
367 | private static void GetPluginMetaData(Type pluginType, out string pluginName, out string pluginDescription, out string pluginVersion) {
|
---|
368 | // there must be a single attribute of type PluginAttribute
|
---|
369 | var pluginMetaDataAttr = (from attr in CustomAttributeData.GetCustomAttributes(pluginType)
|
---|
370 | where IsAttributeDataForType(attr, typeof(PluginAttribute))
|
---|
371 | select attr).Single();
|
---|
372 |
|
---|
373 | pluginName = (string)pluginMetaDataAttr.ConstructorArguments[0].Value;
|
---|
374 |
|
---|
375 | // default description and version
|
---|
376 | pluginVersion = "0.0.0.0";
|
---|
377 | pluginDescription = pluginName;
|
---|
378 | if (pluginMetaDataAttr.ConstructorArguments.Count() == 2) {
|
---|
379 | // if two arguments are given the second argument is the version
|
---|
380 | pluginVersion = (string)pluginMetaDataAttr.ConstructorArguments[1].Value;
|
---|
381 | } else if (pluginMetaDataAttr.ConstructorArguments.Count() == 3) {
|
---|
382 | // if three arguments are given the second argument is the description and the third is the version
|
---|
383 | pluginDescription = (string)pluginMetaDataAttr.ConstructorArguments[1].Value;
|
---|
384 | pluginVersion = (string)pluginMetaDataAttr.ConstructorArguments[2].Value;
|
---|
385 | }
|
---|
386 | }
|
---|
387 |
|
---|
388 | private static bool IsAttributeDataForType(CustomAttributeData attributeData, Type attributeType) {
|
---|
389 | return attributeData.Constructor.DeclaringType.AssemblyQualifiedName == attributeType.AssemblyQualifiedName;
|
---|
390 | }
|
---|
391 |
|
---|
392 | // builds a dependency tree of all plugin descriptions
|
---|
393 | // searches matching plugin descriptions based on the list of dependency names for each plugin
|
---|
394 | // and sets the dependencies in the plugin descriptions
|
---|
395 | private void BuildDependencyTree(IEnumerable<PluginDescription> pluginDescriptions) {
|
---|
396 | foreach (var desc in pluginDescriptions) {
|
---|
397 | var missingDependencies = new List<PluginDependency>();
|
---|
398 | foreach (var dependency in pluginDependencies[desc]) {
|
---|
399 | var matchingDescriptions = from availablePlugin in pluginDescriptions
|
---|
400 | where availablePlugin.Name == dependency.Name
|
---|
401 | where IsCompatiblePluginVersion(availablePlugin.Version, dependency.Version)
|
---|
402 | select availablePlugin;
|
---|
403 | if (matchingDescriptions.Count() > 0) {
|
---|
404 | desc.AddDependency(matchingDescriptions.Single());
|
---|
405 | } else {
|
---|
406 | missingDependencies.Add(dependency);
|
---|
407 | }
|
---|
408 | }
|
---|
409 | // no plugin description that matches the dependencies are available => plugin is disabled
|
---|
410 | if (missingDependencies.Count > 0) {
|
---|
411 | StringBuilder errorStrBuilder = new StringBuilder();
|
---|
412 | errorStrBuilder.AppendLine("Missing dependencies:");
|
---|
413 | foreach (var missingDep in missingDependencies) {
|
---|
414 | errorStrBuilder.AppendLine(missingDep.Name + " " + missingDep.Version);
|
---|
415 | }
|
---|
416 | desc.Disable(errorStrBuilder.ToString());
|
---|
417 | }
|
---|
418 | }
|
---|
419 | }
|
---|
420 |
|
---|
421 | /// <summary>
|
---|
422 | /// Checks if version <paramref name="available"/> is compatible to version <paramref name="requested"/>.
|
---|
423 | /// Note: the compatibility relation is not bijective.
|
---|
424 | /// Compatibility rules:
|
---|
425 | /// * major and minor number must be the same
|
---|
426 | /// * build and revision number of <paramref name="available"/> must be larger or equal to <paramref name="requested"/>.
|
---|
427 | /// </summary>
|
---|
428 | /// <param name="available">The available version which should be compared to <paramref name="requested"/>.</param>
|
---|
429 | /// <param name="requested">The requested version that must be matched.</param>
|
---|
430 | /// <returns></returns>
|
---|
431 | private bool IsCompatiblePluginVersion(Version available, Version requested) {
|
---|
432 | // this condition must be removed after all plugins have been updated to declare plugin and dependency versions
|
---|
433 | if (
|
---|
434 | (requested.Major == 0 && requested.Minor == 0) ||
|
---|
435 | (available.Major == 0 && available.Minor == 0)) return true;
|
---|
436 | return
|
---|
437 | available.Major == requested.Major &&
|
---|
438 | available.Minor == requested.Minor &&
|
---|
439 | available.Build >= requested.Build &&
|
---|
440 | available.Revision >= requested.Revision;
|
---|
441 | }
|
---|
442 |
|
---|
443 | private void CheckPluginDependencyCycles(IEnumerable<PluginDescription> pluginDescriptions) {
|
---|
444 | foreach (var plugin in pluginDescriptions) {
|
---|
445 | // if the plugin is not disabled check if there are cycles
|
---|
446 | if (plugin.PluginState != PluginState.Disabled && HasCycleInDependencies(plugin, plugin.Dependencies)) {
|
---|
447 | plugin.Disable("Dependency graph has a cycle.");
|
---|
448 | }
|
---|
449 | }
|
---|
450 | }
|
---|
451 |
|
---|
452 | private bool HasCycleInDependencies(PluginDescription plugin, IEnumerable<PluginDescription> pluginDependencies) {
|
---|
453 | foreach (var dep in pluginDependencies) {
|
---|
454 | // if one of the dependencies is the original plugin we found a cycle and can return
|
---|
455 | // if the dependency is already disabled we can ignore the cycle detection because we will disable the plugin anyway
|
---|
456 | // if following one of the dependencies recursively leads to a cycle then we also return
|
---|
457 | if (dep == plugin || dep.PluginState == PluginState.Disabled || HasCycleInDependencies(plugin, dep.Dependencies)) return true;
|
---|
458 | }
|
---|
459 | // no cycle found and none of the direct and indirect dependencies is disabled
|
---|
460 | return false;
|
---|
461 | }
|
---|
462 |
|
---|
463 | private void CheckPluginDependencies(IEnumerable<PluginDescription> pluginDescriptions) {
|
---|
464 | foreach (PluginDescription pluginDescription in pluginDescriptions.Where(x => x.PluginState != PluginState.Disabled)) {
|
---|
465 | List<PluginDescription> disabledPlugins = new List<PluginDescription>();
|
---|
466 | if (IsAnyDependencyDisabled(pluginDescription, disabledPlugins)) {
|
---|
467 | StringBuilder errorStrBuilder = new StringBuilder();
|
---|
468 | errorStrBuilder.AppendLine("Dependencies are disabled:");
|
---|
469 | foreach (var disabledPlugin in disabledPlugins) {
|
---|
470 | errorStrBuilder.AppendLine(disabledPlugin.Name + " " + disabledPlugin.Version);
|
---|
471 | }
|
---|
472 | pluginDescription.Disable(errorStrBuilder.ToString());
|
---|
473 | }
|
---|
474 | }
|
---|
475 | }
|
---|
476 |
|
---|
477 |
|
---|
478 | private bool IsAnyDependencyDisabled(PluginDescription descr, List<PluginDescription> disabledPlugins) {
|
---|
479 | if (descr.PluginState == PluginState.Disabled) {
|
---|
480 | disabledPlugins.Add(descr);
|
---|
481 | return true;
|
---|
482 | }
|
---|
483 | foreach (PluginDescription dependency in descr.Dependencies) {
|
---|
484 | IsAnyDependencyDisabled(dependency, disabledPlugins);
|
---|
485 | }
|
---|
486 | return disabledPlugins.Count > 0;
|
---|
487 | }
|
---|
488 |
|
---|
489 | private void LoadPlugins(IEnumerable<PluginDescription> pluginDescriptions) {
|
---|
490 | // load all loadable plugins (all dependencies available) into the execution context
|
---|
491 | foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(pluginDescriptions
|
---|
492 | .Where(x => x.PluginState != PluginState.Disabled))) {
|
---|
493 | List<Type> types = new List<Type>();
|
---|
494 | foreach (string assemblyLocation in desc.AssemblyLocations) {
|
---|
495 | // now load the assemblies into the execution context
|
---|
496 | var asm = Assembly.LoadFrom(assemblyLocation);
|
---|
497 | foreach (Type t in asm.GetTypes()) {
|
---|
498 | if (typeof(IPlugin).IsAssignableFrom(t)) {
|
---|
499 | types.Add(t);
|
---|
500 | }
|
---|
501 | }
|
---|
502 | }
|
---|
503 |
|
---|
504 | foreach (Type pluginType in types) {
|
---|
505 | if (!pluginType.IsAbstract && !pluginType.IsInterface && !pluginType.HasElementType) {
|
---|
506 | IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);
|
---|
507 | plugin.OnLoad();
|
---|
508 | OnPluginLoaded(new PluginInfrastructureEventArgs(desc));
|
---|
509 | }
|
---|
510 | }
|
---|
511 | desc.Load();
|
---|
512 | }
|
---|
513 | }
|
---|
514 |
|
---|
515 | // checks if all declared plugin files are actually available and disables plugins with missing files
|
---|
516 | private void CheckPluginFiles(IEnumerable<PluginDescription> pluginDescriptions) {
|
---|
517 | foreach (PluginDescription desc in pluginDescriptions) {
|
---|
518 | IEnumerable<string> missingFiles;
|
---|
519 | if (ArePluginFilesMissing(desc, out missingFiles)) {
|
---|
520 | StringBuilder errorStrBuilder = new StringBuilder();
|
---|
521 | errorStrBuilder.AppendLine("Missing files:");
|
---|
522 | foreach (string fileName in missingFiles) {
|
---|
523 | errorStrBuilder.AppendLine(fileName);
|
---|
524 | }
|
---|
525 | desc.Disable(errorStrBuilder.ToString());
|
---|
526 | }
|
---|
527 | }
|
---|
528 | }
|
---|
529 |
|
---|
530 | private bool ArePluginFilesMissing(PluginDescription pluginDescription, out IEnumerable<string> missingFiles) {
|
---|
531 | List<string> missing = new List<string>();
|
---|
532 | foreach (string filename in pluginDescription.Files.Select(x => x.Name)) {
|
---|
533 | if (!FileLiesInDirectory(PluginDir, filename) ||
|
---|
534 | !File.Exists(filename)) {
|
---|
535 | missing.Add(filename);
|
---|
536 | }
|
---|
537 | }
|
---|
538 | missingFiles = missing;
|
---|
539 | return missing.Count > 0;
|
---|
540 | }
|
---|
541 |
|
---|
542 | private static bool FileLiesInDirectory(string dir, string fileName) {
|
---|
543 | var basePath = Path.GetFullPath(dir);
|
---|
544 | return Path.GetFullPath(fileName).StartsWith(basePath);
|
---|
545 | }
|
---|
546 |
|
---|
547 | private PluginDescription GetDeclaringPlugin(Type appType, IEnumerable<PluginDescription> plugins) {
|
---|
548 | return (from p in plugins
|
---|
549 | from asmLocation in p.AssemblyLocations
|
---|
550 | where Path.GetFullPath(asmLocation).Equals(Path.GetFullPath(appType.Assembly.Location), StringComparison.CurrentCultureIgnoreCase)
|
---|
551 | select p).Single();
|
---|
552 | }
|
---|
553 |
|
---|
554 | // register assembly in the assembly cache for the ReflectionOnlyAssemblyResolveEvent
|
---|
555 | private void RegisterLoadedAssembly(Assembly asm) {
|
---|
556 | reflectionOnlyAssemblies.Add(asm.FullName, asm);
|
---|
557 | reflectionOnlyAssemblies.Add(asm.GetName().Name, asm); // add short name
|
---|
558 | }
|
---|
559 |
|
---|
560 | private void OnPluginLoaded(PluginInfrastructureEventArgs e) {
|
---|
561 | if (PluginLoaded != null)
|
---|
562 | PluginLoaded(this, e);
|
---|
563 | }
|
---|
564 |
|
---|
565 | /// <summary>
|
---|
566 | /// Initializes the life time service with an infinite lease time.
|
---|
567 | /// </summary>
|
---|
568 | /// <returns><c>null</c>.</returns>
|
---|
569 | public override object InitializeLifetimeService() {
|
---|
570 | return null;
|
---|
571 | }
|
---|
572 | }
|
---|
573 | }
|
---|