SimianGridMaptileModule.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 System.Net;
  31. using System.IO;
  32. using System.Timers;
  33. using System.Drawing;
  34. using System.Drawing.Imaging;
  35. using log4net;
  36. using Mono.Addins;
  37. using Nini.Config;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenMetaverse;
  42. using OpenMetaverse.StructuredData;
  43. namespace OpenSim.Region.OptionalModules.Simian
  44. {
  45. /// <summary>
  46. /// </summary>
  47. /// <remarks>
  48. /// </remarks>
  49. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianGridMaptile")]
  50. public class SimianGridMaptile : ISharedRegionModule
  51. {
  52. private static readonly ILog m_log =
  53. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. private bool m_enabled = false;
  55. private string m_serverUrl = String.Empty;
  56. private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
  57. private int m_refreshtime = 0;
  58. private int m_lastrefresh = 0;
  59. private System.Timers.Timer m_refreshTimer = new System.Timers.Timer();
  60. #region ISharedRegionModule
  61. public Type ReplaceableInterface { get { return null; } }
  62. public string Name { get { return "SimianGridMaptile"; } }
  63. public void RegionLoaded(Scene scene) { }
  64. public void Close() { }
  65. ///<summary>
  66. ///
  67. ///</summary>
  68. public void Initialise(IConfigSource source)
  69. {
  70. IConfig config = source.Configs["SimianGridMaptiles"];
  71. if (config == null)
  72. return;
  73. if (! config.GetBoolean("Enabled", false))
  74. return;
  75. m_serverUrl = config.GetString("MaptileURL");
  76. if (String.IsNullOrEmpty(m_serverUrl))
  77. return;
  78. int refreshseconds = Convert.ToInt32(config.GetString("RefreshTime"));
  79. if (refreshseconds <= 0)
  80. return;
  81. m_refreshtime = refreshseconds * 1000; // convert from seconds to ms
  82. m_log.InfoFormat("[SIMIAN MAPTILE] enabled with refresh timeout {0} and URL {1}",
  83. m_refreshtime,m_serverUrl);
  84. m_enabled = true;
  85. }
  86. ///<summary>
  87. ///
  88. ///</summary>
  89. public void PostInitialise()
  90. {
  91. if (m_enabled)
  92. {
  93. m_refreshTimer.Enabled = true;
  94. m_refreshTimer.AutoReset = true;
  95. m_refreshTimer.Interval = 5 * 60 * 1000; // every 5 minutes
  96. m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh);
  97. }
  98. }
  99. ///<summary>
  100. ///
  101. ///</summary>
  102. public void AddRegion(Scene scene)
  103. {
  104. if (! m_enabled)
  105. return;
  106. // Every shared region module has to maintain an indepedent list of
  107. // currently running regions
  108. lock (m_scenes)
  109. m_scenes[scene.RegionInfo.RegionID] = scene;
  110. }
  111. ///<summary>
  112. ///
  113. ///</summary>
  114. public void RemoveRegion(Scene scene)
  115. {
  116. if (! m_enabled)
  117. return;
  118. lock (m_scenes)
  119. m_scenes.Remove(scene.RegionInfo.RegionID);
  120. }
  121. #endregion ISharedRegionModule
  122. ///<summary>
  123. ///
  124. ///</summary>
  125. private void HandleMaptileRefresh(object sender, EventArgs ea)
  126. {
  127. // this approach is a bit convoluted becase we want to wait for the
  128. // first upload to happen on startup but after all the objects are
  129. // loaded and initialized
  130. if (m_lastrefresh > 0 && Util.EnvironmentTickCountSubtract(m_lastrefresh) < m_refreshtime)
  131. return;
  132. m_log.DebugFormat("[SIMIAN MAPTILE] map refresh fired");
  133. lock (m_scenes)
  134. {
  135. foreach (IScene scene in m_scenes.Values)
  136. {
  137. try
  138. {
  139. UploadMapTile(scene);
  140. }
  141. catch (Exception ex)
  142. {
  143. m_log.WarnFormat("[SIMIAN MAPTILE] something bad happened {0}",ex.Message);
  144. }
  145. }
  146. }
  147. m_lastrefresh = Util.EnvironmentTickCount();
  148. }
  149. ///<summary>
  150. ///
  151. ///</summary>
  152. private void UploadMapTile(IScene scene)
  153. {
  154. m_log.DebugFormat("[SIMIAN MAPTILE]: upload maptile for {0}",scene.RegionInfo.RegionName);
  155. // Create a PNG map tile and upload it to the AddMapTile API
  156. byte[] pngData = Utils.EmptyBytes;
  157. IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>();
  158. if (tileGenerator == null)
  159. {
  160. m_log.Warn("[SIMIAN MAPTILE]: Cannot upload PNG map tile without an ImageGenerator");
  161. return;
  162. }
  163. using (Image mapTile = tileGenerator.CreateMapTile())
  164. {
  165. using (MemoryStream stream = new MemoryStream())
  166. {
  167. mapTile.Save(stream, ImageFormat.Png);
  168. pngData = stream.ToArray();
  169. }
  170. }
  171. List<MultipartForm.Element> postParameters = new List<MultipartForm.Element>()
  172. {
  173. new MultipartForm.Parameter("X", scene.RegionInfo.RegionLocX.ToString()),
  174. new MultipartForm.Parameter("Y", scene.RegionInfo.RegionLocY.ToString()),
  175. new MultipartForm.File("Tile", "tile.png", "image/png", pngData)
  176. };
  177. string errorMessage = null;
  178. int tickstart = Util.EnvironmentTickCount();
  179. // Make the remote storage request
  180. try
  181. {
  182. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_serverUrl);
  183. request.Timeout = 20000;
  184. request.ReadWriteTimeout = 5000;
  185. using (HttpWebResponse response = MultipartForm.Post(request, postParameters))
  186. {
  187. using (Stream responseStream = response.GetResponseStream())
  188. {
  189. string responseStr = responseStream.GetStreamString();
  190. OSD responseOSD = OSDParser.Deserialize(responseStr);
  191. if (responseOSD.Type == OSDType.Map)
  192. {
  193. OSDMap responseMap = (OSDMap)responseOSD;
  194. if (responseMap["Success"].AsBoolean())
  195. return;
  196. errorMessage = "Upload failed: " + responseMap["Message"].AsString();
  197. }
  198. else
  199. {
  200. errorMessage = "Response format was invalid:\n" + responseStr;
  201. }
  202. }
  203. }
  204. }
  205. catch (WebException we)
  206. {
  207. errorMessage = we.Message;
  208. if (we.Status == WebExceptionStatus.ProtocolError)
  209. {
  210. HttpWebResponse webResponse = (HttpWebResponse)we.Response;
  211. errorMessage = String.Format("[{0}] {1}",
  212. webResponse.StatusCode,webResponse.StatusDescription);
  213. }
  214. }
  215. catch (Exception ex)
  216. {
  217. errorMessage = ex.Message;
  218. }
  219. finally
  220. {
  221. // This just dumps a warning for any operation that takes more than 100 ms
  222. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  223. m_log.DebugFormat("[SIMIAN MAPTILE]: map tile uploaded in {0}ms",tickdiff);
  224. }
  225. m_log.WarnFormat("[SIMIAN MAPTILE]: Failed to store {0} byte tile for {1}: {2}",
  226. pngData.Length, scene.RegionInfo.RegionName, errorMessage);
  227. }
  228. }
  229. }