PluginLoader.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 OpenSimulator 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.Collections.Generic;
  29. using System.IO;
  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(PluginExtensionNode 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 T Plugin
  86. {
  87. get { return (loaded.Count == 1)? loaded [0] : default (T); }
  88. }
  89. public PluginLoader()
  90. {
  91. Initialiser = new PluginInitialiserBase();
  92. initialise_plugin_dir_(".");
  93. }
  94. public PluginLoader(PluginInitialiserBase init)
  95. {
  96. Initialiser = init;
  97. initialise_plugin_dir_(".");
  98. }
  99. public PluginLoader(PluginInitialiserBase init, string dir)
  100. {
  101. Initialiser = init;
  102. initialise_plugin_dir_(dir);
  103. }
  104. public void Add(string extpoint)
  105. {
  106. if (extpoints.Contains(extpoint))
  107. return;
  108. extpoints.Add(extpoint);
  109. }
  110. public void Add(string extpoint, IPluginConstraint cons)
  111. {
  112. Add(extpoint);
  113. AddConstraint(extpoint, cons);
  114. }
  115. public void Add(string extpoint, IPluginFilter filter)
  116. {
  117. Add(extpoint);
  118. AddFilter(extpoint, filter);
  119. }
  120. public void AddConstraint(string extpoint, IPluginConstraint cons)
  121. {
  122. constraints.Add(extpoint, cons);
  123. }
  124. public void AddFilter(string extpoint, IPluginFilter filter)
  125. {
  126. filters.Add(extpoint, filter);
  127. }
  128. public void Load(string extpoint)
  129. {
  130. Add(extpoint);
  131. Load();
  132. }
  133. public void Load()
  134. {
  135. foreach (string ext in extpoints)
  136. {
  137. log.Info("[PLUGINS]: Loading extension point " + ext);
  138. if (constraints.ContainsKey(ext))
  139. {
  140. IPluginConstraint cons = constraints[ext];
  141. if (cons.Apply(ext))
  142. log.Error("[PLUGINS]: " + ext + " failed constraint: " + cons.Message);
  143. }
  144. IPluginFilter filter = null;
  145. if (filters.ContainsKey(ext))
  146. filter = filters[ext];
  147. List<T> loadedPlugins = new List<T>();
  148. foreach (PluginExtensionNode node in AddinManager.GetExtensionNodes(ext))
  149. {
  150. log.Info("[PLUGINS]: Trying plugin " + node.Path);
  151. if ((filter != null) && (filter.Apply(node) == false))
  152. continue;
  153. T plugin = (T)node.CreateInstance();
  154. loadedPlugins.Add(plugin);
  155. }
  156. // We do Initialise() in a second loop after CreateInstance
  157. // So that modules who need init before others can do it
  158. // Example: Script Engine Component System needs to load its components before RegionLoader starts
  159. foreach (T plugin in loadedPlugins)
  160. {
  161. Initialiser.Initialise(plugin);
  162. Plugins.Add(plugin);
  163. }
  164. }
  165. }
  166. /// <summary>
  167. /// Unregisters Mono.Addins event handlers, allowing temporary Mono.Addins
  168. /// data to be garbage collected. Since the plugins created by this loader
  169. /// are meant to outlive the loader itself, they must be disposed separately
  170. /// </summary>
  171. public void Dispose()
  172. {
  173. AddinManager.AddinLoadError -= on_addinloaderror_;
  174. AddinManager.AddinLoaded -= on_addinloaded_;
  175. }
  176. private void initialise_plugin_dir_(string dir)
  177. {
  178. if (AddinManager.IsInitialized == true)
  179. return;
  180. log.Info("[PLUGINS]: Initializing addin manager");
  181. AddinManager.AddinLoadError += on_addinloaderror_;
  182. AddinManager.AddinLoaded += on_addinloaded_;
  183. //suppress_console_output_(true);
  184. AddinManager.Initialize(dir);
  185. AddinManager.Registry.Update(null);
  186. //suppress_console_output_(false);
  187. }
  188. private void on_addinloaded_(object sender, AddinEventArgs args)
  189. {
  190. log.Info ("[PLUGINS]: Plugin Loaded: " + args.AddinId);
  191. }
  192. private void on_addinloaderror_(object sender, AddinErrorEventArgs args)
  193. {
  194. if (args.Exception == null)
  195. log.Error ("[PLUGINS]: Plugin Error: "
  196. + args.Message);
  197. else
  198. log.Error ("[PLUGINS]: Plugin Error: "
  199. + args.Exception.Message + "\n"
  200. + args.Exception.StackTrace);
  201. }
  202. private static TextWriter prev_console_;
  203. public void suppress_console_output_(bool save)
  204. {
  205. if (save)
  206. {
  207. prev_console_ = System.Console.Out;
  208. System.Console.SetOut(new StreamWriter(Stream.Null));
  209. }
  210. else
  211. {
  212. if (prev_console_ != null)
  213. System.Console.SetOut(prev_console_);
  214. }
  215. }
  216. }
  217. public class PluginExtensionNode : ExtensionNode
  218. {
  219. [NodeAttribute]
  220. string id = "";
  221. [NodeAttribute]
  222. string provider = "";
  223. [NodeAttribute]
  224. string type = "";
  225. Type typeobj;
  226. public string ID { get { return id; } }
  227. public string Provider { get { return provider; } }
  228. public string TypeName { get { return type; } }
  229. public Type TypeObject
  230. {
  231. get
  232. {
  233. if (typeobj != null)
  234. return typeobj;
  235. if (type.Length == 0)
  236. throw new InvalidOperationException("Type name not specified.");
  237. return typeobj = Addin.GetType(type, true);
  238. }
  239. }
  240. public object CreateInstance()
  241. {
  242. return Activator.CreateInstance(TypeObject);
  243. }
  244. }
  245. /// <summary>
  246. /// Constraint that bounds the number of plugins to be loaded.
  247. /// </summary>
  248. public class PluginCountConstraint : IPluginConstraint
  249. {
  250. private int min;
  251. private int max;
  252. public PluginCountConstraint(int exact)
  253. {
  254. min = exact;
  255. max = exact;
  256. }
  257. public PluginCountConstraint(int minimum, int maximum)
  258. {
  259. min = minimum;
  260. max = maximum;
  261. }
  262. public string Message
  263. {
  264. get
  265. {
  266. return "The number of plugins is constrained to the interval ["
  267. + min + ", " + max + "]";
  268. }
  269. }
  270. public bool Apply (string extpoint)
  271. {
  272. int count = AddinManager.GetExtensionNodes(extpoint).Count;
  273. if ((count < min) || (count > max))
  274. throw new PluginConstraintViolatedException(Message);
  275. return true;
  276. }
  277. }
  278. /// <summary>
  279. /// Filters out which plugin to load based on the plugin name or names given. Plugin names are contained in
  280. /// their addin.xml
  281. /// </summary>
  282. public class PluginProviderFilter : IPluginFilter
  283. {
  284. private string[] m_filters;
  285. /// <summary>
  286. /// Constructor.
  287. /// </summary>
  288. /// <param name="p">
  289. /// Plugin name or names on which to filter. Multiple names should be separated by commas.
  290. /// </param>
  291. public PluginProviderFilter(string p)
  292. {
  293. m_filters = p.Split(',');
  294. for (int i = 0; i < m_filters.Length; i++)
  295. {
  296. m_filters[i] = m_filters[i].Trim();
  297. }
  298. }
  299. /// <summary>
  300. /// Apply this filter to the given plugin.
  301. /// </summary>
  302. /// <param name="plugin"></param>
  303. /// <returns>true if the plugin's name matched one of the filters, false otherwise.</returns>
  304. public bool Apply (PluginExtensionNode plugin)
  305. {
  306. for (int i = 0; i < m_filters.Length; i++)
  307. {
  308. if (m_filters[i] == plugin.Provider)
  309. {
  310. return true;
  311. }
  312. }
  313. return false;
  314. }
  315. }
  316. /// <summary>
  317. /// Filters plugins according to their ID. Plugin IDs are contained in their addin.xml
  318. /// </summary>
  319. public class PluginIdFilter : IPluginFilter
  320. {
  321. private string[] m_filters;
  322. /// <summary>
  323. /// Constructor.
  324. /// </summary>
  325. /// <param name="p">
  326. /// Plugin ID or IDs on which to filter. Multiple names should be separated by commas.
  327. /// </param>
  328. public PluginIdFilter(string p)
  329. {
  330. m_filters = p.Split(',');
  331. for (int i = 0; i < m_filters.Length; i++)
  332. {
  333. m_filters[i] = m_filters[i].Trim();
  334. }
  335. }
  336. /// <summary>
  337. /// Apply this filter to <paramref name="plugin" />.
  338. /// </summary>
  339. /// <param name="plugin">PluginExtensionNode instance to check whether it passes the filter.</param>
  340. /// <returns>true if the plugin's ID matches one of the filters, false otherwise.</returns>
  341. public bool Apply (PluginExtensionNode plugin)
  342. {
  343. for (int i = 0; i < m_filters.Length; i++)
  344. {
  345. if (m_filters[i] == plugin.ID)
  346. {
  347. return true;
  348. }
  349. }
  350. return false;
  351. }
  352. }
  353. }