PluginLoader.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.IO;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using log4net;
  32. using Mono.Addins;
  33. namespace OpenSim.Framework
  34. {
  35. /// <summary>
  36. /// Exception thrown if an incorrect number of plugins are loaded
  37. /// </summary>
  38. public class PluginConstraintViolatedException : Exception
  39. {
  40. public PluginConstraintViolatedException () : base() {}
  41. public PluginConstraintViolatedException (string msg) : base(msg) {}
  42. public PluginConstraintViolatedException (string msg, Exception e) : base(msg, e) {}
  43. }
  44. /// <summary>
  45. /// Classes wishing to impose constraints on plugin loading must implement
  46. /// this class and pass it to PluginLoader AddConstraint()
  47. /// </summary>
  48. public interface IPluginConstraint
  49. {
  50. string Message { get; }
  51. bool Apply (string extpoint);
  52. }
  53. /// <summary>
  54. /// Classes wishing to select specific plugins from a range of possible options
  55. /// must implement this class and pass it to PluginLoader Load()
  56. /// </summary>
  57. public interface IPluginFilter
  58. {
  59. bool Apply (ExtensionNode plugin);
  60. }
  61. /// <summary>
  62. /// Generic Plugin Loader
  63. /// </summary>
  64. public class PluginLoader <T> : IDisposable where T : IPlugin
  65. {
  66. private const int max_loadable_plugins = 10000;
  67. private List<T> loaded = new List<T>();
  68. private List<string> extpoints = new List<string>();
  69. private PluginInitialiserBase initialiser;
  70. private Dictionary<string,IPluginConstraint> constraints
  71. = new Dictionary<string,IPluginConstraint>();
  72. private Dictionary<string,IPluginFilter> filters
  73. = new Dictionary<string,IPluginFilter>();
  74. private static readonly ILog log
  75. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  76. public PluginInitialiserBase Initialiser
  77. {
  78. set { initialiser = value; }
  79. get { return initialiser; }
  80. }
  81. public List<T> Plugins
  82. {
  83. get { return loaded; }
  84. }
  85. public PluginLoader ()
  86. {
  87. Initialiser = new PluginInitialiserBase();
  88. initialise_plugin_dir_ (".");
  89. }
  90. public PluginLoader (PluginInitialiserBase init)
  91. {
  92. Initialiser = init;
  93. initialise_plugin_dir_ (".");
  94. }
  95. public PluginLoader (PluginInitialiserBase init, string dir)
  96. {
  97. Initialiser = init;
  98. initialise_plugin_dir_ (dir);
  99. }
  100. public void AddExtensionPoint (string extpoint)
  101. {
  102. extpoints.Add (extpoint);
  103. }
  104. public void AddConstraint (string extpoint, IPluginConstraint cons)
  105. {
  106. constraints.Add (extpoint, cons);
  107. }
  108. public void AddFilter (string extpoint, IPluginFilter filter)
  109. {
  110. filters.Add (extpoint, filter);
  111. }
  112. public void Load (string extpoint)
  113. {
  114. AddExtensionPoint (extpoint);
  115. Load();
  116. }
  117. public void Load ()
  118. {
  119. foreach (string ext in extpoints)
  120. {
  121. log.Info("[PLUGINS]: Loading extension point " + ext);
  122. if (constraints.ContainsKey (ext))
  123. {
  124. IPluginConstraint cons = constraints [ext];
  125. if (cons.Apply (ext))
  126. log.Error ("[PLUGINS]: " + ext + " failed constraint: " + cons.Message);
  127. }
  128. IPluginFilter filter = null;
  129. if (filters.ContainsKey (ext))
  130. filter = filters [ext];
  131. foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes (ext))
  132. {
  133. log.Info("[PLUGINS]: Trying plugin " + node.Path);
  134. if ((filter != null) && (filter.Apply (node) == false))
  135. continue;
  136. T plugin = (T) node.CreateInstance();
  137. Initialiser.Initialise (plugin);
  138. Plugins.Add (plugin);
  139. }
  140. }
  141. }
  142. public void Dispose ()
  143. {
  144. foreach (T plugin in Plugins)
  145. plugin.Dispose ();
  146. }
  147. private void initialise_plugin_dir_ (string dir)
  148. {
  149. if (AddinManager.IsInitialized == true)
  150. return;
  151. log.Info("[PLUGINS]: Initialzing");
  152. AddinManager.AddinLoadError += on_addinloaderror_;
  153. AddinManager.AddinLoaded += on_addinloaded_;
  154. clear_registry_();
  155. suppress_console_output_ (true);
  156. AddinManager.Initialize (dir);
  157. AddinManager.Registry.Update (null);
  158. suppress_console_output_ (false);
  159. }
  160. private void on_addinloaded_(object sender, AddinEventArgs args)
  161. {
  162. log.Info ("[PLUGINS]: Plugin Loaded: " + args.AddinId);
  163. }
  164. private void on_addinloaderror_(object sender, AddinErrorEventArgs args)
  165. {
  166. log.Error ("[PLUGINS]: Plugin Error: " + args.Message);
  167. }
  168. private void clear_registry_ ()
  169. {
  170. // The Mono addin manager (in Mono.Addins.dll version 0.2.0.0)
  171. // occasionally seems to corrupt its addin cache
  172. // Hence, as a temporary solution we'll remove it before each startup
  173. if (Directory.Exists("addin-db-000"))
  174. Directory.Delete("addin-db-000", true);
  175. if (Directory.Exists("addin-db-001"))
  176. Directory.Delete("addin-db-001", true);
  177. }
  178. private static TextWriter prev_console_;
  179. public void suppress_console_output_ (bool save)
  180. {
  181. if (save)
  182. {
  183. prev_console_ = System.Console.Out;
  184. System.Console.SetOut(new StreamWriter(Stream.Null));
  185. }
  186. else
  187. {
  188. if (prev_console_ != null)
  189. System.Console.SetOut(prev_console_);
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// Constraint that bounds the number of plugins to be loaded.
  195. /// </summary>
  196. public class PluginCountConstraint : IPluginConstraint
  197. {
  198. private int min;
  199. private int max;
  200. public PluginCountConstraint (int exact)
  201. {
  202. min = exact;
  203. max = exact;
  204. }
  205. public PluginCountConstraint (int minimum, int maximum)
  206. {
  207. min = minimum;
  208. max = maximum;
  209. }
  210. public string Message
  211. {
  212. get
  213. {
  214. return "The number of plugins is constrained to the interval ["
  215. + min + ", " + max + "]";
  216. }
  217. }
  218. public bool Apply (string extpoint)
  219. {
  220. int count = AddinManager.GetExtensionNodes (extpoint).Count;
  221. if ((count < min) || (count > max))
  222. throw new PluginConstraintViolatedException (Message);
  223. return true;
  224. }
  225. }
  226. /// <summary>
  227. /// Filters out which plugin to load based on its "Id", which is name given by the namespace or by Mono.Addins.
  228. /// </summary>
  229. public class PluginIdFilter : IPluginFilter
  230. {
  231. private string id;
  232. public PluginIdFilter (string id)
  233. {
  234. this.id = id;
  235. }
  236. public bool Apply (ExtensionNode plugin)
  237. {
  238. return (plugin.Id == id);
  239. }
  240. }
  241. }