PluginLoader.cs 14 KB

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