PluginLoader.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. clear_registry_();
  184. suppress_console_output_(true);
  185. AddinManager.Initialize(dir);
  186. AddinManager.Registry.Update(null);
  187. suppress_console_output_(false);
  188. }
  189. private void on_addinloaded_(object sender, AddinEventArgs args)
  190. {
  191. log.Info ("[PLUGINS]: Plugin Loaded: " + args.AddinId);
  192. }
  193. private void on_addinloaderror_(object sender, AddinErrorEventArgs args)
  194. {
  195. if (args.Exception == null)
  196. log.Error ("[PLUGINS]: Plugin Error: "
  197. + args.Message);
  198. else
  199. log.Error ("[PLUGINS]: Plugin Error: "
  200. + args.Exception.Message + "\n"
  201. + args.Exception.StackTrace);
  202. }
  203. private void clear_registry_()
  204. {
  205. // The Mono addin manager (in Mono.Addins.dll version 0.2.0.0)
  206. // occasionally seems to corrupt its addin cache
  207. // Hence, as a temporary solution we'll remove it before each startup
  208. try
  209. {
  210. if (Directory.Exists("addin-db-000"))
  211. Directory.Delete("addin-db-000", true);
  212. if (Directory.Exists("addin-db-001"))
  213. Directory.Delete("addin-db-001", true);
  214. }
  215. catch (IOException)
  216. {
  217. // If multiple services are started simultaneously, they may
  218. // each test whether the directory exists at the same time, and
  219. // attempt to delete the directory at the same time. However,
  220. // one of the services will likely succeed first, causing the
  221. // second service to throw an IOException. We catch it here and
  222. // continue on our merry way.
  223. // Mike 2008.08.01, patch from Zaki
  224. }
  225. }
  226. private static TextWriter prev_console_;
  227. public void suppress_console_output_(bool save)
  228. {
  229. if (save)
  230. {
  231. prev_console_ = System.Console.Out;
  232. System.Console.SetOut(new StreamWriter(Stream.Null));
  233. }
  234. else
  235. {
  236. if (prev_console_ != null)
  237. System.Console.SetOut(prev_console_);
  238. }
  239. }
  240. }
  241. public class PluginExtensionNode : ExtensionNode
  242. {
  243. [NodeAttribute]
  244. string id = "";
  245. [NodeAttribute]
  246. string provider = "";
  247. [NodeAttribute]
  248. string type = "";
  249. Type typeobj;
  250. public string ID { get { return id; } }
  251. public string Provider { get { return provider; } }
  252. public string TypeName { get { return type; } }
  253. public Type TypeObject
  254. {
  255. get
  256. {
  257. if (typeobj != null)
  258. return typeobj;
  259. if (type.Length == 0)
  260. throw new InvalidOperationException("Type name not specified.");
  261. return typeobj = Addin.GetType(type, true);
  262. }
  263. }
  264. public object CreateInstance()
  265. {
  266. return Activator.CreateInstance(TypeObject);
  267. }
  268. }
  269. /// <summary>
  270. /// Constraint that bounds the number of plugins to be loaded.
  271. /// </summary>
  272. public class PluginCountConstraint : IPluginConstraint
  273. {
  274. private int min;
  275. private int max;
  276. public PluginCountConstraint(int exact)
  277. {
  278. min = exact;
  279. max = exact;
  280. }
  281. public PluginCountConstraint(int minimum, int maximum)
  282. {
  283. min = minimum;
  284. max = maximum;
  285. }
  286. public string Message
  287. {
  288. get
  289. {
  290. return "The number of plugins is constrained to the interval ["
  291. + min + ", " + max + "]";
  292. }
  293. }
  294. public bool Apply (string extpoint)
  295. {
  296. int count = AddinManager.GetExtensionNodes(extpoint).Count;
  297. if ((count < min) || (count > max))
  298. throw new PluginConstraintViolatedException(Message);
  299. return true;
  300. }
  301. }
  302. /// <summary>
  303. /// Filters out which plugin to load based on the plugin name or names given. Plugin names are contained in
  304. /// their addin.xml
  305. /// </summary>
  306. public class PluginProviderFilter : IPluginFilter
  307. {
  308. private string[] m_filters;
  309. /// <summary>
  310. /// Constructor.
  311. /// </summary>
  312. /// <param name="p">
  313. /// Plugin name or names on which to filter. Multiple names should be separated by commas.
  314. /// </param>
  315. public PluginProviderFilter(string p)
  316. {
  317. m_filters = p.Split(',');
  318. for (int i = 0; i < m_filters.Length; i++)
  319. {
  320. m_filters[i] = m_filters[i].Trim();
  321. }
  322. }
  323. /// <summary>
  324. /// Apply this filter to the given plugin.
  325. /// </summary>
  326. /// <param name="plugin"></param>
  327. /// <returns>true if the plugin's name matched one of the filters, false otherwise.</returns>
  328. public bool Apply (PluginExtensionNode plugin)
  329. {
  330. for (int i = 0; i < m_filters.Length; i++)
  331. {
  332. if (m_filters[i] == plugin.Provider)
  333. {
  334. return true;
  335. }
  336. }
  337. return false;
  338. }
  339. }
  340. /// <summary>
  341. /// Filters plugins according to their ID. Plugin IDs are contained in their addin.xml
  342. /// </summary>
  343. public class PluginIdFilter : IPluginFilter
  344. {
  345. private string[] m_filters;
  346. /// <summary>
  347. /// Constructor.
  348. /// </summary>
  349. /// <param name="p">
  350. /// Plugin ID or IDs on which to filter. Multiple names should be separated by commas.
  351. /// </param>
  352. public PluginIdFilter(string p)
  353. {
  354. m_filters = p.Split(',');
  355. for (int i = 0; i < m_filters.Length; i++)
  356. {
  357. m_filters[i] = m_filters[i].Trim();
  358. }
  359. }
  360. /// <summary>
  361. /// Apply this filter to <paramref name="plugin" />.
  362. /// </summary>
  363. /// <param name="plugin">PluginExtensionNode instance to check whether it passes the filter.</param>
  364. /// <returns>true if the plugin's ID matches one of the filters, false otherwise.</returns>
  365. public bool Apply (PluginExtensionNode plugin)
  366. {
  367. for (int i = 0; i < m_filters.Length; i++)
  368. {
  369. if (m_filters[i] == plugin.ID)
  370. {
  371. return true;
  372. }
  373. }
  374. return false;
  375. }
  376. }
  377. }