RegionModulesControllerPlugin.cs 21 KB

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