1
0

DataSnapshotManager.cs 16 KB

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