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