SimianGridServiceConnector.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.IO;
  33. using System.Net;
  34. using System.Reflection;
  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 OpenSim.Services.Interfaces;
  42. using OpenMetaverse;
  43. using OpenMetaverse.StructuredData;
  44. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  45. namespace OpenSim.Services.Connectors.SimianGrid
  46. {
  47. /// <summary>
  48. /// Connects region registration and neighbor lookups to the SimianGrid
  49. /// backend
  50. /// </summary>
  51. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
  52. public class SimianGridServiceConnector : IGridService, ISharedRegionModule
  53. {
  54. private static readonly ILog m_log =
  55. LogManager.GetLogger(
  56. MethodBase.GetCurrentMethod().DeclaringType);
  57. private string m_serverUrl = String.Empty;
  58. private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
  59. #region ISharedRegionModule
  60. public Type ReplaceableInterface { get { return null; } }
  61. public void RegionLoaded(Scene scene) { }
  62. public void PostInitialise() { }
  63. public void Close() { }
  64. public SimianGridServiceConnector() { }
  65. public string Name { get { return "SimianGridServiceConnector"; } }
  66. public void AddRegion(Scene scene)
  67. {
  68. // Every shared region module has to maintain an indepedent list of
  69. // currently running regions
  70. lock (m_scenes)
  71. m_scenes[scene.RegionInfo.RegionID] = scene;
  72. if (!String.IsNullOrEmpty(m_serverUrl))
  73. scene.RegisterModuleInterface<IGridService>(this);
  74. }
  75. public void RemoveRegion(Scene scene)
  76. {
  77. lock (m_scenes)
  78. m_scenes.Remove(scene.RegionInfo.RegionID);
  79. if (!String.IsNullOrEmpty(m_serverUrl))
  80. scene.UnregisterModuleInterface<IGridService>(this);
  81. }
  82. #endregion ISharedRegionModule
  83. public SimianGridServiceConnector(IConfigSource source)
  84. {
  85. Initialise(source);
  86. }
  87. public void Initialise(IConfigSource source)
  88. {
  89. if (Simian.IsSimianEnabled(source, "GridServices", this.Name))
  90. {
  91. IConfig gridConfig = source.Configs["GridService"];
  92. if (gridConfig == null)
  93. {
  94. m_log.Error("[SIMIAN GRID CONNECTOR]: GridService missing from OpenSim.ini");
  95. throw new Exception("Grid connector init error");
  96. }
  97. string serviceUrl = gridConfig.GetString("GridServerURI");
  98. if (String.IsNullOrEmpty(serviceUrl))
  99. {
  100. m_log.Error("[SIMIAN GRID CONNECTOR]: No Server URI named in section GridService");
  101. throw new Exception("Grid connector init error");
  102. }
  103. m_serverUrl = serviceUrl;
  104. }
  105. }
  106. #region IGridService
  107. public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
  108. {
  109. // Generate and upload our map tile in PNG format to the SimianGrid AddMapTile service
  110. Scene scene;
  111. if (m_scenes.TryGetValue(regionInfo.RegionID, out scene))
  112. UploadMapTile(scene);
  113. else
  114. m_log.Warn("Registering region " + regionInfo.RegionName + " (" + regionInfo.RegionID + ") that we are not tracking");
  115. Vector3d minPosition = new Vector3d(regionInfo.RegionLocX, regionInfo.RegionLocY, 0.0);
  116. Vector3d maxPosition = minPosition + new Vector3d(Constants.RegionSize, Constants.RegionSize, 4096.0);
  117. string httpAddress = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort + "/";
  118. OSDMap extraData = new OSDMap
  119. {
  120. { "ServerURI", OSD.FromString(regionInfo.ServerURI) },
  121. { "InternalAddress", OSD.FromString(regionInfo.InternalEndPoint.Address.ToString()) },
  122. { "InternalPort", OSD.FromInteger(regionInfo.InternalEndPoint.Port) },
  123. { "ExternalAddress", OSD.FromString(regionInfo.ExternalEndPoint.Address.ToString()) },
  124. { "ExternalPort", OSD.FromInteger(regionInfo.ExternalEndPoint.Port) },
  125. { "MapTexture", OSD.FromUUID(regionInfo.TerrainImage) },
  126. { "Access", OSD.FromInteger(regionInfo.Access) },
  127. { "RegionSecret", OSD.FromString(regionInfo.RegionSecret) },
  128. { "EstateOwner", OSD.FromUUID(regionInfo.EstateOwner) },
  129. { "Token", OSD.FromString(regionInfo.Token) }
  130. };
  131. NameValueCollection requestArgs = new NameValueCollection
  132. {
  133. { "RequestMethod", "AddScene" },
  134. { "SceneID", regionInfo.RegionID.ToString() },
  135. { "Name", regionInfo.RegionName },
  136. { "MinPosition", minPosition.ToString() },
  137. { "MaxPosition", maxPosition.ToString() },
  138. { "Address", httpAddress },
  139. { "Enabled", "1" },
  140. { "ExtraData", OSDParser.SerializeJsonString(extraData) }
  141. };
  142. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  143. if (response["Success"].AsBoolean())
  144. return String.Empty;
  145. else
  146. return "Region registration for " + regionInfo.RegionName + " failed: " + response["Message"].AsString();
  147. }
  148. public bool DeregisterRegion(UUID regionID)
  149. {
  150. NameValueCollection requestArgs = new NameValueCollection
  151. {
  152. { "RequestMethod", "AddScene" },
  153. { "SceneID", regionID.ToString() },
  154. { "Enabled", "0" }
  155. };
  156. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  157. bool success = response["Success"].AsBoolean();
  158. if (!success)
  159. m_log.Warn("[SIMIAN GRID CONNECTOR]: Region deregistration for " + regionID + " failed: " + response["Message"].AsString());
  160. return success;
  161. }
  162. public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
  163. {
  164. const int NEIGHBOR_RADIUS = 128;
  165. GridRegion region = GetRegionByUUID(scopeID, regionID);
  166. if (region != null)
  167. {
  168. List<GridRegion> regions = GetRegionRange(scopeID,
  169. region.RegionLocX - NEIGHBOR_RADIUS, region.RegionLocX + (int)Constants.RegionSize + NEIGHBOR_RADIUS,
  170. region.RegionLocY - NEIGHBOR_RADIUS, region.RegionLocY + (int)Constants.RegionSize + NEIGHBOR_RADIUS);
  171. for (int i = 0; i < regions.Count; i++)
  172. {
  173. if (regions[i].RegionID == regionID)
  174. {
  175. regions.RemoveAt(i);
  176. break;
  177. }
  178. }
  179. m_log.Debug("[SIMIAN GRID CONNECTOR]: Found " + regions.Count + " neighbors for region " + regionID);
  180. return regions;
  181. }
  182. return new List<GridRegion>(0);
  183. }
  184. public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
  185. {
  186. NameValueCollection requestArgs = new NameValueCollection
  187. {
  188. { "RequestMethod", "GetScene" },
  189. { "SceneID", regionID.ToString() }
  190. };
  191. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  192. if (response["Success"].AsBoolean())
  193. {
  194. return ResponseToGridRegion(response);
  195. }
  196. else
  197. {
  198. m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID);
  199. return null;
  200. }
  201. }
  202. public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
  203. {
  204. // Go one meter in from the requested x/y coords to avoid requesting a position
  205. // that falls on the border of two sims
  206. Vector3d position = new Vector3d(x + 1, y + 1, 0.0);
  207. NameValueCollection requestArgs = new NameValueCollection
  208. {
  209. { "RequestMethod", "GetScene" },
  210. { "Position", position.ToString() },
  211. { "Enabled", "1" }
  212. };
  213. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  214. if (response["Success"].AsBoolean())
  215. {
  216. return ResponseToGridRegion(response);
  217. }
  218. else
  219. {
  220. //m_log.InfoFormat("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at {0},{1}",
  221. // x / Constants.RegionSize, y / Constants.RegionSize);
  222. return null;
  223. }
  224. }
  225. public GridRegion GetRegionByName(UUID scopeID, string regionName)
  226. {
  227. List<GridRegion> regions = GetRegionsByName(scopeID, regionName, 1);
  228. m_log.Debug("[SIMIAN GRID CONNECTOR]: Got " + regions.Count + " matches for region name " + regionName);
  229. if (regions.Count > 0)
  230. return regions[0];
  231. return null;
  232. }
  233. public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
  234. {
  235. List<GridRegion> foundRegions = new List<GridRegion>();
  236. NameValueCollection requestArgs = new NameValueCollection
  237. {
  238. { "RequestMethod", "GetScenes" },
  239. { "NameQuery", name },
  240. { "Enabled", "1" }
  241. };
  242. if (maxNumber > 0)
  243. requestArgs["MaxNumber"] = maxNumber.ToString();
  244. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  245. if (response["Success"].AsBoolean())
  246. {
  247. OSDArray array = response["Scenes"] as OSDArray;
  248. if (array != null)
  249. {
  250. for (int i = 0; i < array.Count; i++)
  251. {
  252. GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
  253. if (region != null)
  254. foundRegions.Add(region);
  255. }
  256. }
  257. }
  258. return foundRegions;
  259. }
  260. public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
  261. {
  262. List<GridRegion> foundRegions = new List<GridRegion>();
  263. Vector3d minPosition = new Vector3d(xmin, ymin, 0.0);
  264. Vector3d maxPosition = new Vector3d(xmax, ymax, 4096.0);
  265. NameValueCollection requestArgs = new NameValueCollection
  266. {
  267. { "RequestMethod", "GetScenes" },
  268. { "MinPosition", minPosition.ToString() },
  269. { "MaxPosition", maxPosition.ToString() },
  270. { "Enabled", "1" }
  271. };
  272. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  273. if (response["Success"].AsBoolean())
  274. {
  275. OSDArray array = response["Scenes"] as OSDArray;
  276. if (array != null)
  277. {
  278. for (int i = 0; i < array.Count; i++)
  279. {
  280. GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
  281. if (region != null)
  282. foundRegions.Add(region);
  283. }
  284. }
  285. }
  286. return foundRegions;
  287. }
  288. public List<GridRegion> GetDefaultRegions(UUID scopeID)
  289. {
  290. // TODO: Allow specifying the default grid location
  291. const int DEFAULT_X = 1000 * 256;
  292. const int DEFAULT_Y = 1000 * 256;
  293. GridRegion defRegion = GetNearestRegion(new Vector3d(DEFAULT_X, DEFAULT_Y, 0.0), true);
  294. if (defRegion != null)
  295. return new List<GridRegion>(1) { defRegion };
  296. else
  297. return new List<GridRegion>(0);
  298. }
  299. public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
  300. {
  301. GridRegion defRegion = GetNearestRegion(new Vector3d(x, y, 0.0), true);
  302. if (defRegion != null)
  303. return new List<GridRegion>(1) { defRegion };
  304. else
  305. return new List<GridRegion>(0);
  306. }
  307. public List<GridRegion> GetHyperlinks(UUID scopeID)
  308. {
  309. // Hypergrid/linked regions are not supported
  310. return new List<GridRegion>();
  311. }
  312. public int GetRegionFlags(UUID scopeID, UUID regionID)
  313. {
  314. const int REGION_ONLINE = 4;
  315. NameValueCollection requestArgs = new NameValueCollection
  316. {
  317. { "RequestMethod", "GetScene" },
  318. { "SceneID", regionID.ToString() }
  319. };
  320. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  321. if (response["Success"].AsBoolean())
  322. {
  323. return response["Enabled"].AsBoolean() ? REGION_ONLINE : 0;
  324. }
  325. else
  326. {
  327. m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID + " during region flags check");
  328. return -1;
  329. }
  330. }
  331. #endregion IGridService
  332. private void UploadMapTile(IScene scene)
  333. {
  334. string errorMessage = null;
  335. // Create a PNG map tile and upload it to the AddMapTile API
  336. byte[] pngData = Utils.EmptyBytes;
  337. IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>();
  338. if (tileGenerator == null)
  339. {
  340. m_log.Warn("[SIMIAN GRID CONNECTOR]: Cannot upload PNG map tile without an IMapImageGenerator");
  341. return;
  342. }
  343. using (Image mapTile = tileGenerator.CreateMapTile("defaultstripe.png"))
  344. {
  345. using (MemoryStream stream = new MemoryStream())
  346. {
  347. mapTile.Save(stream, ImageFormat.Png);
  348. pngData = stream.ToArray();
  349. }
  350. }
  351. List<MultipartForm.Element> postParameters = new List<MultipartForm.Element>()
  352. {
  353. new MultipartForm.Parameter("X", scene.RegionInfo.RegionLocX.ToString()),
  354. new MultipartForm.Parameter("Y", scene.RegionInfo.RegionLocY.ToString()),
  355. new MultipartForm.File("Tile", "tile.png", "image/png", pngData)
  356. };
  357. // Make the remote storage request
  358. try
  359. {
  360. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_serverUrl);
  361. HttpWebResponse response = MultipartForm.Post(request, postParameters);
  362. using (Stream responseStream = response.GetResponseStream())
  363. {
  364. string responseStr = null;
  365. try
  366. {
  367. responseStr = responseStream.GetStreamString();
  368. OSD responseOSD = OSDParser.Deserialize(responseStr);
  369. if (responseOSD.Type == OSDType.Map)
  370. {
  371. OSDMap responseMap = (OSDMap)responseOSD;
  372. if (responseMap["Success"].AsBoolean())
  373. m_log.Info("[SIMIAN GRID CONNECTOR]: Uploaded " + pngData.Length + " byte PNG map tile to AddMapTile");
  374. else
  375. errorMessage = "Upload failed: " + responseMap["Message"].AsString();
  376. }
  377. else
  378. {
  379. errorMessage = "Response format was invalid:\n" + responseStr;
  380. }
  381. }
  382. catch (Exception ex)
  383. {
  384. if (!String.IsNullOrEmpty(responseStr))
  385. errorMessage = "Failed to parse the response:\n" + responseStr;
  386. else
  387. errorMessage = "Failed to retrieve the response: " + ex.Message;
  388. }
  389. }
  390. }
  391. catch (WebException ex)
  392. {
  393. errorMessage = ex.Message;
  394. }
  395. if (!String.IsNullOrEmpty(errorMessage))
  396. {
  397. m_log.WarnFormat("[SIMIAN GRID CONNECTOR]: Failed to store {0} byte PNG map tile for {1}: {2}",
  398. pngData.Length, scene.RegionInfo.RegionName, errorMessage.Replace('\n', ' '));
  399. }
  400. }
  401. private GridRegion GetNearestRegion(Vector3d position, bool onlyEnabled)
  402. {
  403. NameValueCollection requestArgs = new NameValueCollection
  404. {
  405. { "RequestMethod", "GetScene" },
  406. { "Position", position.ToString() },
  407. { "FindClosest", "1" }
  408. };
  409. if (onlyEnabled)
  410. requestArgs["Enabled"] = "1";
  411. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  412. if (response["Success"].AsBoolean())
  413. {
  414. return ResponseToGridRegion(response);
  415. }
  416. else
  417. {
  418. m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at " + position);
  419. return null;
  420. }
  421. }
  422. private GridRegion ResponseToGridRegion(OSDMap response)
  423. {
  424. if (response == null)
  425. return null;
  426. OSDMap extraData = response["ExtraData"] as OSDMap;
  427. if (extraData == null)
  428. return null;
  429. GridRegion region = new GridRegion();
  430. region.RegionID = response["SceneID"].AsUUID();
  431. region.RegionName = response["Name"].AsString();
  432. Vector3d minPosition = response["MinPosition"].AsVector3d();
  433. region.RegionLocX = (int)minPosition.X;
  434. region.RegionLocY = (int)minPosition.Y;
  435. Uri httpAddress = response["Address"].AsUri();
  436. region.ExternalHostName = httpAddress.Host;
  437. region.HttpPort = (uint)httpAddress.Port;
  438. region.ServerURI = extraData["ServerURI"].AsString();
  439. IPAddress internalAddress;
  440. IPAddress.TryParse(extraData["InternalAddress"].AsString(), out internalAddress);
  441. if (internalAddress == null)
  442. internalAddress = IPAddress.Any;
  443. region.InternalEndPoint = new IPEndPoint(internalAddress, extraData["InternalPort"].AsInteger());
  444. region.TerrainImage = extraData["MapTexture"].AsUUID();
  445. region.Access = (byte)extraData["Access"].AsInteger();
  446. region.RegionSecret = extraData["RegionSecret"].AsString();
  447. region.EstateOwner = extraData["EstateOwner"].AsUUID();
  448. region.Token = extraData["Token"].AsString();
  449. return region;
  450. }
  451. }
  452. }