SimianGridMaptileModule.cs 11 KB

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