DataSnapshotManager.cs 16 KB

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