PluginLoader.cs 13 KB

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