DataSnapshotManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. */
  28. using System;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Net;
  32. using System.Reflection;
  33. using System.Xml;
  34. using log4net;
  35. using Nini.Config;
  36. using OpenMetaverse;
  37. using Mono.Addins;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Communications;
  40. using OpenSim.Region.DataSnapshot.Interfaces;
  41. using OpenSim.Region.Framework.Interfaces;
  42. using OpenSim.Region.Framework.Scenes;
  43. [assembly: Addin("DataSnapshot", "0.1")]
  44. [assembly: AddinDependency("OpenSim", "0.5")]
  45. namespace OpenSim.Region.DataSnapshot
  46. {
  47. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DataSnapshotManager")]
  48. public class DataSnapshotManager : ISharedRegionModule, IDataSnapshot
  49. {
  50. #region Class members
  51. //Information from config
  52. private bool m_enabled = false;
  53. private bool m_configLoaded = false;
  54. private List<string> m_disabledModules = new List<string>();
  55. private Dictionary<string, string> m_gridinfo = new Dictionary<string, string>();
  56. private string m_snapsDir = "DataSnapshot";
  57. private string m_exposure_level = "minimum";
  58. //Lists of stuff we need
  59. private List<Scene> m_scenes = new List<Scene>();
  60. private List<IDataSnapshotProvider> m_dataproviders = new List<IDataSnapshotProvider>();
  61. //Various internal objects
  62. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  63. internal object m_syncInit = new object();
  64. //DataServices and networking
  65. private string m_dataServices = "noservices";
  66. public string m_listener_port = ConfigSettings.DefaultRegionHttpPort.ToString();
  67. public string m_hostname = "127.0.0.1";
  68. private UUID m_Secret = UUID.Random();
  69. private bool m_servicesNotified = false;
  70. //Update timers
  71. private int m_period = 20; // in seconds
  72. private int m_maxStales = 500;
  73. private int m_stales = 0;
  74. private int m_lastUpdate = 0;
  75. //Program objects
  76. private SnapshotStore m_snapStore = null;
  77. #endregion
  78. #region Properties
  79. public string ExposureLevel
  80. {
  81. get { return m_exposure_level; }
  82. }
  83. public UUID Secret
  84. {
  85. get { return m_Secret; }
  86. }
  87. #endregion
  88. #region Region Module interface
  89. public void Initialise(IConfigSource config)
  90. {
  91. if (!m_configLoaded)
  92. {
  93. m_configLoaded = true;
  94. //m_log.Debug("[DATASNAPSHOT]: Loading configuration");
  95. //Read from the config for options
  96. lock (m_syncInit)
  97. {
  98. try
  99. {
  100. m_enabled = config.Configs["DataSnapshot"].GetBoolean("index_sims", m_enabled);
  101. IConfig conf = config.Configs["GridService"];
  102. if (conf != null)
  103. m_gridinfo.Add("gatekeeperURL", conf.GetString("Gatekeeper", String.Empty));
  104. m_gridinfo.Add(
  105. "name", config.Configs["DataSnapshot"].GetString("gridname", "the lost continent of hippo"));
  106. m_exposure_level = config.Configs["DataSnapshot"].GetString("data_exposure", m_exposure_level);
  107. m_period = config.Configs["DataSnapshot"].GetInt("default_snapshot_period", m_period);
  108. m_maxStales = config.Configs["DataSnapshot"].GetInt("max_changes_before_update", m_maxStales);
  109. m_snapsDir = config.Configs["DataSnapshot"].GetString("snapshot_cache_directory", m_snapsDir);
  110. m_dataServices = config.Configs["DataSnapshot"].GetString("data_services", m_dataServices);
  111. m_listener_port = config.Configs["Network"].GetString("http_listener_port", m_listener_port);
  112. String[] annoying_string_array = config.Configs["DataSnapshot"].GetString("disable_modules", "").Split(".".ToCharArray());
  113. foreach (String bloody_wanker in annoying_string_array)
  114. {
  115. m_disabledModules.Add(bloody_wanker);
  116. }
  117. m_lastUpdate = Environment.TickCount;
  118. }
  119. catch (Exception)
  120. {
  121. m_log.Warn("[DATASNAPSHOT]: Could not load configuration. DataSnapshot will be disabled.");
  122. m_enabled = false;
  123. return;
  124. }
  125. }
  126. }
  127. }
  128. public void AddRegion(Scene scene)
  129. {
  130. if (!m_enabled)
  131. return;
  132. m_log.DebugFormat("[DATASNAPSHOT]: Module added to Scene {0}.", scene.RegionInfo.RegionName);
  133. if (!m_servicesNotified)
  134. {
  135. m_hostname = scene.RegionInfo.ExternalHostName;
  136. m_snapStore = new SnapshotStore(m_snapsDir, m_gridinfo, m_listener_port, m_hostname);
  137. //Hand it the first scene, assuming that all scenes have the same BaseHTTPServer
  138. new DataRequestHandler(scene, this);
  139. if (m_dataServices != "" && m_dataServices != "noservices")
  140. NotifyDataServices(m_dataServices, "online");
  141. m_servicesNotified = true;
  142. }
  143. m_scenes.Add(scene);
  144. m_snapStore.AddScene(scene);
  145. Assembly currentasm = Assembly.GetExecutingAssembly();
  146. foreach (Type pluginType in currentasm.GetTypes())
  147. {
  148. if (pluginType.IsPublic)
  149. {
  150. if (!pluginType.IsAbstract)
  151. {
  152. if (pluginType.GetInterface("IDataSnapshotProvider") != null)
  153. {
  154. IDataSnapshotProvider module = (IDataSnapshotProvider)Activator.CreateInstance(pluginType);
  155. module.Initialize(scene, this);
  156. module.OnStale += MarkDataStale;
  157. m_dataproviders.Add(module);
  158. m_snapStore.AddProvider(module);
  159. m_log.Debug("[DATASNAPSHOT]: Added new data provider type: " + pluginType.Name);
  160. }
  161. }
  162. }
  163. }
  164. }
  165. public void RemoveRegion(Scene scene)
  166. {
  167. if (!m_enabled)
  168. return;
  169. m_log.Info("[DATASNAPSHOT]: Region " + scene.RegionInfo.RegionName + " is being removed, removing from indexing");
  170. Scene restartedScene = SceneForUUID(scene.RegionInfo.RegionID);
  171. m_scenes.Remove(restartedScene);
  172. m_snapStore.RemoveScene(restartedScene);
  173. //Getting around the fact that we can't remove objects from a collection we are enumerating over
  174. List<IDataSnapshotProvider> providersToRemove = new List<IDataSnapshotProvider>();
  175. foreach (IDataSnapshotProvider provider in m_dataproviders)
  176. {
  177. if (provider.GetParentScene == restartedScene)
  178. {
  179. providersToRemove.Add(provider);
  180. }
  181. }
  182. foreach (IDataSnapshotProvider provider in providersToRemove)
  183. {
  184. m_dataproviders.Remove(provider);
  185. m_snapStore.RemoveProvider(provider);
  186. }
  187. m_snapStore.RemoveScene(restartedScene);
  188. }
  189. public void PostInitialise()
  190. {
  191. }
  192. public void RegionLoaded(Scene scene)
  193. {
  194. if (!m_enabled)
  195. return;
  196. m_log.DebugFormat("[DATASNAPSHOT]: Marking scene {0} as stale.", scene.RegionInfo.RegionName);
  197. m_snapStore.ForceSceneStale(scene);
  198. }
  199. public void Close()
  200. {
  201. if (!m_enabled)
  202. return;
  203. if (m_enabled && m_dataServices != "" && m_dataServices != "noservices")
  204. NotifyDataServices(m_dataServices, "offline");
  205. }
  206. public string Name
  207. {
  208. get { return "External Data Generator"; }
  209. }
  210. public Type ReplaceableInterface
  211. {
  212. get { return null; }
  213. }
  214. #endregion
  215. #region Associated helper functions
  216. public Scene SceneForName(string name)
  217. {
  218. foreach (Scene scene in m_scenes)
  219. if (scene.RegionInfo.RegionName == name)
  220. return scene;
  221. return null;
  222. }
  223. public Scene SceneForUUID(UUID id)
  224. {
  225. foreach (Scene scene in m_scenes)
  226. if (scene.RegionInfo.RegionID == id)
  227. return scene;
  228. return null;
  229. }
  230. #endregion
  231. #region [Public] Snapshot storage functions
  232. /**
  233. * Reply to the http request
  234. */
  235. public XmlDocument GetSnapshot(string regionName)
  236. {
  237. CheckStale();
  238. XmlDocument requestedSnap = new XmlDocument();
  239. requestedSnap.AppendChild(requestedSnap.CreateXmlDeclaration("1.0", null, null));
  240. requestedSnap.AppendChild(requestedSnap.CreateWhitespace("\r\n"));
  241. XmlNode regiondata = requestedSnap.CreateNode(XmlNodeType.Element, "regiondata", "");
  242. try
  243. {
  244. if (regionName == null || regionName == "")
  245. {
  246. XmlNode timerblock = requestedSnap.CreateNode(XmlNodeType.Element, "expire", "");
  247. timerblock.InnerText = m_period.ToString();
  248. regiondata.AppendChild(timerblock);
  249. regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n"));
  250. foreach (Scene scene in m_scenes)
  251. {
  252. regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap));
  253. }
  254. }
  255. else
  256. {
  257. Scene scene = SceneForName(regionName);
  258. regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap));
  259. }
  260. requestedSnap.AppendChild(regiondata);
  261. regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n"));
  262. }
  263. catch (XmlException e)
  264. {
  265. m_log.Warn("[DATASNAPSHOT]: XmlException while trying to load snapshot: " + e.ToString());
  266. requestedSnap = GetErrorMessage(regionName, e);
  267. }
  268. catch (Exception e)
  269. {
  270. m_log.Warn("[DATASNAPSHOT]: Caught unknown exception while trying to load snapshot: " + e.StackTrace);
  271. requestedSnap = GetErrorMessage(regionName, e);
  272. }
  273. return requestedSnap;
  274. }
  275. private XmlDocument GetErrorMessage(string regionName, Exception e)
  276. {
  277. XmlDocument errorMessage = new XmlDocument();
  278. XmlNode error = errorMessage.CreateNode(XmlNodeType.Element, "error", "");
  279. XmlNode region = errorMessage.CreateNode(XmlNodeType.Element, "region", "");
  280. region.InnerText = regionName;
  281. XmlNode exception = errorMessage.CreateNode(XmlNodeType.Element, "exception", "");
  282. exception.InnerText = e.ToString();
  283. error.AppendChild(region);
  284. error.AppendChild(exception);
  285. errorMessage.AppendChild(error);
  286. return errorMessage;
  287. }
  288. #endregion
  289. #region External data services
  290. private void NotifyDataServices(string servicesStr, string serviceName)
  291. {
  292. Stream reply = null;
  293. string delimStr = ";";
  294. char [] delimiter = delimStr.ToCharArray();
  295. string[] services = servicesStr.Split(delimiter);
  296. for (int i = 0; i < services.Length; i++)
  297. {
  298. string url = services[i].Trim();
  299. RestClient cli = new RestClient(url);
  300. cli.AddQueryParameter("service", serviceName);
  301. cli.AddQueryParameter("host", m_hostname);
  302. cli.AddQueryParameter("port", m_listener_port);
  303. cli.AddQueryParameter("secret", m_Secret.ToString());
  304. cli.RequestMethod = "GET";
  305. try
  306. {
  307. reply = cli.Request();
  308. }
  309. catch (WebException)
  310. {
  311. m_log.Warn("[DATASNAPSHOT]: Unable to notify " + url);
  312. }
  313. catch (Exception e)
  314. {
  315. m_log.Warn("[DATASNAPSHOT]: Ignoring unknown exception " + e.ToString());
  316. }
  317. byte[] response = new byte[1024];
  318. // int n = 0;
  319. try
  320. {
  321. // n = reply.Read(response, 0, 1024);
  322. reply.Read(response, 0, 1024);
  323. }
  324. catch (Exception e)
  325. {
  326. m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace);
  327. }
  328. // This is not quite working, so...
  329. // string responseStr = Util.UTF8.GetString(response);
  330. m_log.Info("[DATASNAPSHOT]: data service " + url + " notified. Secret: " + m_Secret);
  331. }
  332. }
  333. #endregion
  334. #region Latency-based update functions
  335. public void MarkDataStale(IDataSnapshotProvider provider)
  336. {
  337. //Behavior here: Wait m_period seconds, then update if there has not been a request in m_period seconds
  338. //or m_maxStales has been exceeded
  339. m_stales++;
  340. }
  341. private void CheckStale()
  342. {
  343. // Wrap check
  344. if (Environment.TickCount < m_lastUpdate)
  345. {
  346. m_lastUpdate = Environment.TickCount;
  347. }
  348. if (m_stales >= m_maxStales)
  349. {
  350. if (Environment.TickCount - m_lastUpdate >= 20000)
  351. {
  352. m_stales = 0;
  353. m_lastUpdate = Environment.TickCount;
  354. MakeEverythingStale();
  355. }
  356. }
  357. else
  358. {
  359. if (m_lastUpdate + 1000 * m_period < Environment.TickCount)
  360. {
  361. m_stales = 0;
  362. m_lastUpdate = Environment.TickCount;
  363. MakeEverythingStale();
  364. }
  365. }
  366. }
  367. public void MakeEverythingStale()
  368. {
  369. m_log.Debug("[DATASNAPSHOT]: Marking all scenes as stale.");
  370. foreach (Scene scene in m_scenes)
  371. {
  372. m_snapStore.ForceSceneStale(scene);
  373. }
  374. }
  375. #endregion
  376. }
  377. }