RegionModulesControllerPlugin.cs 21 KB

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