DataSnapshotManager.cs 18 KB

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