PluginLoader.cs 12 KB

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