RegionModulesControllerPlugin.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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.Reflection;
  30. using log4net;
  31. using Mono.Addins;
  32. using Nini.Config;
  33. using OpenSim;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenSim.Region.Framework.Scenes;
  37. namespace OpenSim.ApplicationPlugins.RegionModulesController
  38. {
  39. [Extension(Path = "/OpenSim/Startup", Id = "LoadRegions", NodeName = "Plugin")]
  40. public class RegionModulesControllerPlugin : IRegionModulesController,
  41. IApplicationPlugin
  42. {
  43. // Logger
  44. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  45. /// <summary>
  46. /// Controls whether we load modules from Mono.Addins.
  47. /// </summary>
  48. /// <remarks>For debug purposes. Defaults to true.</remarks>
  49. public bool LoadModulesFromAddins { get; set; }
  50. // Config access
  51. private OpenSimBase m_openSim;
  52. // Our name
  53. private string m_name;
  54. // Internal lists to collect information about modules present
  55. private List<TypeExtensionNode> m_nonSharedModules = new List<TypeExtensionNode>();
  56. private List<TypeExtensionNode> m_sharedModules = new List<TypeExtensionNode>();
  57. // List of shared module instances, for adding to Scenes
  58. private List<ISharedRegionModule> m_sharedInstances = new List<ISharedRegionModule>();
  59. public RegionModulesControllerPlugin()
  60. {
  61. LoadModulesFromAddins = true;
  62. }
  63. #region IApplicationPlugin implementation
  64. public void Initialise (OpenSimBase openSim)
  65. {
  66. m_openSim = openSim;
  67. m_openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this);
  68. m_log.DebugFormat("[REGIONMODULES]: Initializing...");
  69. if (!LoadModulesFromAddins)
  70. return;
  71. // Who we are
  72. string id = AddinManager.CurrentAddin.Id;
  73. // Make friendly name
  74. int pos = id.LastIndexOf(".");
  75. if (pos == -1)
  76. m_name = id;
  77. else
  78. m_name = id.Substring(pos + 1);
  79. // The [Modules] section in the ini file
  80. IConfig modulesConfig = m_openSim.ConfigSource.Source.Configs["Modules"];
  81. if (modulesConfig == null)
  82. modulesConfig = m_openSim.ConfigSource.Source.AddConfig("Modules");
  83. Dictionary<RuntimeAddin, IList<int>> loadedModules = new Dictionary<RuntimeAddin, IList<int>>();
  84. // Scan modules and load all that aren't disabled
  85. foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes("/OpenSim/RegionModules"))
  86. AddNode(node, modulesConfig, loadedModules);
  87. foreach (KeyValuePair<RuntimeAddin, IList<int>> loadedModuleData in loadedModules)
  88. {
  89. m_log.InfoFormat(
  90. "[REGIONMODULES]: From plugin {0}, (version {1}), loaded {2} modules, {3} shared, {4} non-shared {5} unknown",
  91. loadedModuleData.Key.Id,
  92. loadedModuleData.Key.Version,
  93. loadedModuleData.Value[0] + loadedModuleData.Value[1] + loadedModuleData.Value[2],
  94. loadedModuleData.Value[0], loadedModuleData.Value[1], loadedModuleData.Value[2]);
  95. }
  96. // Load and init the module. We try a constructor with a port
  97. // if a port was given, fall back to one without if there is
  98. // no port or the more specific constructor fails.
  99. // This will be removed, so that any module capable of using a port
  100. // must provide a constructor with a port in the future.
  101. // For now, we do this so migration is easy.
  102. //
  103. foreach (TypeExtensionNode node in m_sharedModules)
  104. {
  105. object[] ctorArgs = new object[] { (uint)0 };
  106. // Read the config again
  107. string moduleString = modulesConfig.GetString("Setup_" + node.Id, string.Empty);
  108. // Test to see if we want this module
  109. if (moduleString == "disabled")
  110. continue;
  111. // Get the port number, if there is one
  112. if (moduleString != string.Empty)
  113. {
  114. // Get the port number from the string
  115. string[] moduleParts = moduleString.Split(new char[] { '/' }, 2);
  116. if (moduleParts.Length > 1)
  117. ctorArgs[0] = Convert.ToUInt32(moduleParts[0]);
  118. }
  119. // Try loading and initilaizing the module, using the
  120. // port if appropriate
  121. ISharedRegionModule module = null;
  122. try
  123. {
  124. module = (ISharedRegionModule)Activator.CreateInstance(node.Type, ctorArgs);
  125. }
  126. catch
  127. {
  128. module = (ISharedRegionModule)Activator.CreateInstance(node.Type);
  129. }
  130. // OK, we're up and running
  131. m_sharedInstances.Add(module);
  132. module.Initialise(m_openSim.ConfigSource.Source);
  133. }
  134. }
  135. public void PostInitialise ()
  136. {
  137. m_log.DebugFormat("[REGIONMODULES]: PostInitializing...");
  138. // Immediately run PostInitialise on shared modules
  139. foreach (ISharedRegionModule module in m_sharedInstances)
  140. {
  141. module.PostInitialise();
  142. }
  143. }
  144. #endregion
  145. #region IPlugin implementation
  146. private void AddNode(TypeExtensionNode node, IConfig modulesConfig, Dictionary<RuntimeAddin, IList<int>> loadedModules)
  147. {
  148. IList<int> loadedModuleData;
  149. if (!loadedModules.ContainsKey(node.Addin))
  150. loadedModules.Add(node.Addin, new List<int> { 0, 0, 0 });
  151. loadedModuleData = loadedModules[node.Addin];
  152. if (node.Type.GetInterface(typeof(ISharedRegionModule).ToString()) != null)
  153. {
  154. if (CheckModuleEnabled(node, modulesConfig))
  155. {
  156. m_log.DebugFormat("[REGIONMODULES]: Found shared region module {0}, class {1}", node.Id, node.Type);
  157. m_sharedModules.Add(node);
  158. loadedModuleData[0]++;
  159. }
  160. }
  161. else if (node.Type.GetInterface(typeof(INonSharedRegionModule).ToString()) != null)
  162. {
  163. if (CheckModuleEnabled(node, modulesConfig))
  164. {
  165. m_log.DebugFormat("[REGIONMODULES]: Found non-shared region module {0}, class {1}", node.Id, node.Type);
  166. m_nonSharedModules.Add(node);
  167. loadedModuleData[1]++;
  168. }
  169. }
  170. else
  171. {
  172. m_log.WarnFormat("[REGIONMODULES]: Found unknown type of module {0}, class {1}", node.Id, node.Type);
  173. loadedModuleData[2]++;
  174. }
  175. }
  176. // We don't do that here
  177. //
  178. public void Initialise ()
  179. {
  180. throw new System.NotImplementedException();
  181. }
  182. #endregion
  183. #region IDisposable implementation
  184. // Cleanup
  185. //
  186. public void Dispose ()
  187. {
  188. // We expect that all regions have been removed already
  189. while (m_sharedInstances.Count > 0)
  190. {
  191. m_sharedInstances[0].Close();
  192. m_sharedInstances.RemoveAt(0);
  193. }
  194. m_sharedModules.Clear();
  195. m_nonSharedModules.Clear();
  196. }
  197. #endregion
  198. public string Version
  199. {
  200. get
  201. {
  202. return AddinManager.CurrentAddin.Version;
  203. }
  204. }
  205. public string Name
  206. {
  207. get
  208. {
  209. return m_name;
  210. }
  211. }
  212. #region Region Module interfacesController implementation
  213. /// <summary>
  214. /// Check that the given module is no disabled in the [Modules] section of the config files.
  215. /// </summary>
  216. /// <param name="node"></param>
  217. /// <param name="modulesConfig">The config section</param>
  218. /// <returns>true if the module is enabled, false if it is disabled</returns>
  219. protected bool CheckModuleEnabled(TypeExtensionNode node, IConfig modulesConfig)
  220. {
  221. // Get the config string
  222. string moduleString = modulesConfig.GetString("Setup_" + node.Id, string.Empty);
  223. // We have a selector
  224. if (!string.IsNullOrEmpty(moduleString))
  225. {
  226. // Allow disabling modules even if they don't have
  227. // support for it
  228. if (moduleString == "disabled")
  229. return false;
  230. // Split off port, if present
  231. string[] moduleParts = moduleString.Split(new char[] { '/' }, 2);
  232. // Format is [port/][class]
  233. string className = moduleParts[0];
  234. if (moduleParts.Length > 1)
  235. className = moduleParts[1];
  236. // Match the class name if given
  237. if (className != String.Empty &&
  238. node.Type.ToString() != className)
  239. return false;
  240. }
  241. return true;
  242. }
  243. // The root of all evil.
  244. // This is where we handle adding the modules to scenes when they
  245. // load. This means that here we deal with replaceable interfaces,
  246. // nonshared modules, etc.
  247. //
  248. public void AddRegionToModules (Scene scene)
  249. {
  250. Dictionary<Type, ISharedRegionModule> deferredSharedModules = new Dictionary<Type, ISharedRegionModule>();
  251. Dictionary<Type, INonSharedRegionModule> deferredNonSharedModules = new Dictionary<Type, INonSharedRegionModule>();
  252. // We need this to see if a module has already been loaded and
  253. // has defined a replaceable interface. It's a generic call,
  254. // so this can't be used directly. It will be used later
  255. Type s = scene.GetType();
  256. MethodInfo mi = s.GetMethod("RequestModuleInterface");
  257. // This will hold the shared modules we actually load
  258. List<ISharedRegionModule> sharedlist = new List<ISharedRegionModule>();
  259. // Iterate over the shared modules that have been loaded
  260. // Add them to the new Scene
  261. foreach (ISharedRegionModule module in m_sharedInstances)
  262. {
  263. // Here is where we check if a replaceable interface
  264. // is defined. If it is, the module is checked against
  265. // the interfaces already defined. If the interface is
  266. // defined, we simply skip the module. Else, if the module
  267. // defines a replaceable interface, we add it to the deferred
  268. // list.
  269. Type replaceableInterface = module.ReplaceableInterface;
  270. if (replaceableInterface != null)
  271. {
  272. MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
  273. if (mii.Invoke(scene, new object[0]) != null)
  274. {
  275. m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
  276. continue;
  277. }
  278. deferredSharedModules[replaceableInterface] = module;
  279. m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name);
  280. continue;
  281. }
  282. m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1}",
  283. scene.RegionInfo.RegionName, module.Name);
  284. module.AddRegion(scene);
  285. scene.AddRegionModule(module.Name, module);
  286. sharedlist.Add(module);
  287. }
  288. IConfig modulesConfig = m_openSim.ConfigSource.Source.Configs["Modules"];
  289. // Scan for, and load, nonshared modules
  290. List<INonSharedRegionModule> list = new List<INonSharedRegionModule>();
  291. foreach (TypeExtensionNode node in m_nonSharedModules)
  292. {
  293. object[] ctorArgs = new object[] {0};
  294. // Read the config
  295. string moduleString = modulesConfig.GetString("Setup_" + node.Id, string.Empty);
  296. // We may not want to load this at all
  297. if (moduleString == "disabled")
  298. continue;
  299. // Get the port number, if there is one
  300. if (!string.IsNullOrEmpty(moduleString))
  301. {
  302. // Get the port number from the string
  303. string[] moduleParts = moduleString.Split(new char[] {'/'}, 2);
  304. if (moduleParts.Length > 1)
  305. ctorArgs[0] = Convert.ToUInt32(moduleParts[0]);
  306. }
  307. // Actually load it
  308. INonSharedRegionModule module = null;
  309. Type[] ctorParamTypes = new Type[ctorArgs.Length];
  310. for (int i = 0; i < ctorParamTypes.Length; i++)
  311. ctorParamTypes[i] = ctorArgs[i].GetType();
  312. if (node.Type.GetConstructor(ctorParamTypes) != null)
  313. module = (INonSharedRegionModule)Activator.CreateInstance(node.Type, ctorArgs);
  314. else
  315. module = (INonSharedRegionModule)Activator.CreateInstance(node.Type);
  316. // Check for replaceable interfaces
  317. Type replaceableInterface = module.ReplaceableInterface;
  318. if (replaceableInterface != null)
  319. {
  320. MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
  321. if (mii.Invoke(scene, new object[0]) != null)
  322. {
  323. m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
  324. continue;
  325. }
  326. deferredNonSharedModules[replaceableInterface] = module;
  327. m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name);
  328. continue;
  329. }
  330. m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1}",
  331. scene.RegionInfo.RegionName, module.Name);
  332. // Initialise the module
  333. module.Initialise(m_openSim.ConfigSource.Source);
  334. list.Add(module);
  335. }
  336. // Now add the modules that we found to the scene. If a module
  337. // wishes to override a replaceable interface, it needs to
  338. // register it in Initialise, so that the deferred module
  339. // won't load.
  340. foreach (INonSharedRegionModule module in list)
  341. {
  342. module.AddRegion(scene);
  343. scene.AddRegionModule(module.Name, module);
  344. }
  345. // Now all modules without a replaceable base interface are loaded
  346. // Replaceable modules have either been skipped, or omitted.
  347. // Now scan the deferred modules here
  348. foreach (ISharedRegionModule module in deferredSharedModules.Values)
  349. {
  350. // Determine if the interface has been replaced
  351. Type replaceableInterface = module.ReplaceableInterface;
  352. MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
  353. if (mii.Invoke(scene, new object[0]) != null)
  354. {
  355. m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
  356. continue;
  357. }
  358. m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1} (deferred)",
  359. scene.RegionInfo.RegionName, module.Name);
  360. // Not replaced, load the module
  361. module.AddRegion(scene);
  362. scene.AddRegionModule(module.Name, module);
  363. sharedlist.Add(module);
  364. }
  365. // Same thing for nonshared modules, load them unless overridden
  366. List<INonSharedRegionModule> deferredlist = new List<INonSharedRegionModule>();
  367. foreach (INonSharedRegionModule module in deferredNonSharedModules.Values)
  368. {
  369. // Check interface override
  370. Type replaceableInterface = module.ReplaceableInterface;
  371. if (replaceableInterface != null)
  372. {
  373. MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
  374. if (mii.Invoke(scene, new object[0]) != null)
  375. {
  376. m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString());
  377. continue;
  378. }
  379. }
  380. m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1} (deferred)",
  381. scene.RegionInfo.RegionName, module.Name);
  382. module.Initialise(m_openSim.ConfigSource.Source);
  383. list.Add(module);
  384. deferredlist.Add(module);
  385. }
  386. // Finally, load valid deferred modules
  387. foreach (INonSharedRegionModule module in deferredlist)
  388. {
  389. module.AddRegion(scene);
  390. scene.AddRegionModule(module.Name, module);
  391. }
  392. // This is needed for all module types. Modules will register
  393. // Interfaces with scene in AddScene, and will also need a means
  394. // to access interfaces registered by other modules. Without
  395. // this extra method, a module attempting to use another modules's
  396. // interface would be successful only depending on load order,
  397. // which can't be depended upon, or modules would need to resort
  398. // to ugly kludges to attempt to request interfaces when needed
  399. // and unneccessary caching logic repeated in all modules.
  400. // The extra function stub is just that much cleaner
  401. //
  402. foreach (ISharedRegionModule module in sharedlist)
  403. {
  404. module.RegionLoaded(scene);
  405. }
  406. foreach (INonSharedRegionModule module in list)
  407. {
  408. module.RegionLoaded(scene);
  409. }
  410. scene.AllModulesLoaded();
  411. }
  412. public void RemoveRegionFromModules (Scene scene)
  413. {
  414. foreach (IRegionModuleBase module in scene.RegionModules.Values)
  415. {
  416. m_log.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}",
  417. scene.RegionInfo.RegionName, module.Name);
  418. module.RemoveRegion(scene);
  419. if (module is INonSharedRegionModule)
  420. {
  421. // as we were the only user, this instance has to die
  422. module.Close();
  423. }
  424. }
  425. scene.RegionModules.Clear();
  426. }
  427. #endregion
  428. }
  429. }