1
0

SimulationServiceConnector.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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.IO;
  30. using System.Net;
  31. using System.Reflection;
  32. using System.Text;
  33. using System.Collections;
  34. using OpenSim.Framework;
  35. using OpenSim.Services.Interfaces;
  36. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  37. using OpenMetaverse;
  38. using OpenMetaverse.StructuredData;
  39. using log4net;
  40. using Nini.Config;
  41. namespace OpenSim.Services.Connectors.Simulation
  42. {
  43. public class SimulationServiceConnector : ISimulationService
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. // we use this dictionary to track the pending updateagent requests, maps URI --> position update
  47. private Dictionary<string,AgentPosition> m_updateAgentQueue = new Dictionary<string,AgentPosition>();
  48. //private GridRegion m_Region;
  49. public SimulationServiceConnector()
  50. {
  51. }
  52. public SimulationServiceConnector(IConfigSource config)
  53. {
  54. //m_Region = region;
  55. }
  56. public IScene GetScene(UUID regionId)
  57. {
  58. return null;
  59. }
  60. public ISimulationService GetInnerService()
  61. {
  62. return null;
  63. }
  64. #region Agents
  65. protected virtual string AgentPath()
  66. {
  67. return "agent/";
  68. }
  69. protected virtual void PackData(OSDMap args, GridRegion source, AgentCircuitData aCircuit, GridRegion destination, uint flags)
  70. {
  71. if (source != null)
  72. {
  73. args["source_x"] = OSD.FromString(source.RegionLocX.ToString());
  74. args["source_y"] = OSD.FromString(source.RegionLocY.ToString());
  75. args["source_name"] = OSD.FromString(source.RegionName);
  76. args["source_uuid"] = OSD.FromString(source.RegionID.ToString());
  77. if (!String.IsNullOrEmpty(source.RawServerURI))
  78. args["source_server_uri"] = OSD.FromString(source.RawServerURI);
  79. }
  80. args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
  81. args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
  82. args["destination_name"] = OSD.FromString(destination.RegionName);
  83. args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
  84. args["teleport_flags"] = OSD.FromString(flags.ToString());
  85. }
  86. public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, EntityTransferContext ctx, out string reason)
  87. {
  88. reason = String.Empty;
  89. if (destination == null)
  90. {
  91. reason = "Destination not found";
  92. m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Create agent destination is null");
  93. return false;
  94. }
  95. m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: Creating agent at {0}", destination.ServerURI);
  96. string uri = destination.ServerURI + AgentPath() + aCircuit.AgentID + "/";
  97. OSD tmpOSD;
  98. try
  99. {
  100. OSDMap args = aCircuit.PackAgentCircuitData(ctx);
  101. if(ctx == null)
  102. ctx = new EntityTransferContext();
  103. args["context"] = ctx.Pack();
  104. PackData(args, source, aCircuit, destination, flags);
  105. OSDMap result = WebUtil.PostToServiceCompressed(uri, args, 30000);
  106. bool success = result["success"].AsBoolean();
  107. if (success && result.TryGetValue("_Result", out tmpOSD) && tmpOSD is OSDMap)
  108. {
  109. OSDMap data = (OSDMap)tmpOSD;
  110. reason = data["reason"].AsString();
  111. success = data["success"].AsBoolean();
  112. return success;
  113. }
  114. // Try the old version, uncompressed
  115. result = WebUtil.PostToService(uri, args, 30000, false);
  116. success = result["success"].AsBoolean();
  117. if (success)
  118. {
  119. if (result.TryGetValue("_Result", out tmpOSD) && tmpOSD is OSDMap)
  120. {
  121. OSDMap data = (OSDMap)tmpOSD;
  122. reason = data["reason"].AsString();
  123. success = data["success"].AsBoolean();
  124. m_log.WarnFormat(
  125. "[REMOTE SIMULATION CONNECTOR]: Remote simulator {0} did not accept compressed transfer, suggest updating that simulator.", destination.RegionName);
  126. return success;
  127. }
  128. }
  129. m_log.WarnFormat(
  130. "[REMOTE SIMULATION CONNECTOR]: Failed to create agent {0} {1} at remote simulator {2}",
  131. aCircuit.firstname, aCircuit.lastname, destination.RegionName);
  132. reason = result["Message"] != null ? result["Message"].AsString() : "error";
  133. return false;
  134. }
  135. catch (Exception e)
  136. {
  137. m_log.Warn("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e.ToString());
  138. reason = e.Message;
  139. }
  140. return false;
  141. }
  142. /// <summary>
  143. /// Send complete data about an agent in this region to a neighbor
  144. /// </summary>
  145. public bool UpdateAgent(GridRegion destination, AgentData data, EntityTransferContext ctx)
  146. {
  147. return UpdateAgent(destination, (IAgentData)data, ctx, 200000); // yes, 200 seconds
  148. }
  149. private ExpiringCache<string, bool> _failedSims = new ExpiringCache<string, bool>();
  150. /// <summary>
  151. /// Send updated position information about an agent in this region to a neighbor
  152. /// This operation may be called very frequently if an avatar is moving about in
  153. /// the region.
  154. /// </summary>
  155. public bool UpdateAgent(GridRegion destination, AgentPosition data)
  156. {
  157. bool v = true;
  158. if (_failedSims.TryGetValue(destination.ServerURI, out v))
  159. return false;
  160. // The basic idea of this code is that the first thread that needs to
  161. // send an update for a specific avatar becomes the worker for any subsequent
  162. // requests until there are no more outstanding requests. Further, only send the most
  163. // recent update; this *should* never be needed but some requests get
  164. // slowed down and once that happens the problem with service end point
  165. // limits kicks in and nothing proceeds
  166. string uri = destination.ServerURI + AgentPath() + data.AgentID + "/";
  167. lock (m_updateAgentQueue)
  168. {
  169. if (m_updateAgentQueue.ContainsKey(uri))
  170. {
  171. // Another thread is already handling
  172. // updates for this simulator, just update
  173. // the position and return, overwrites are
  174. // not a problem since we only care about the
  175. // last update anyway
  176. m_updateAgentQueue[uri] = data;
  177. return true;
  178. }
  179. // Otherwise update the reference and start processing
  180. m_updateAgentQueue[uri] = data;
  181. }
  182. AgentPosition pos = null;
  183. bool success = true;
  184. while (success)
  185. {
  186. lock (m_updateAgentQueue)
  187. {
  188. // save the position
  189. AgentPosition lastpos = pos;
  190. pos = m_updateAgentQueue[uri];
  191. // this is true if no one put a new
  192. // update in the map since the last
  193. // one we processed, if thats the
  194. // case then we are done
  195. if (pos == lastpos)
  196. {
  197. m_updateAgentQueue.Remove(uri);
  198. return true;
  199. }
  200. }
  201. EntityTransferContext ctx = new EntityTransferContext(); // Dummy, not needed for position
  202. success = UpdateAgent(destination, (IAgentData)pos, ctx, 10000);
  203. }
  204. // we get here if success == false
  205. // blacklist sim for 2 minutes
  206. lock (m_updateAgentQueue)
  207. {
  208. _failedSims.AddOrUpdate(destination.ServerURI, true, 120);
  209. m_updateAgentQueue.Remove(uri);
  210. }
  211. return false;
  212. }
  213. /// <summary>
  214. /// This is the worker function to send AgentData to a neighbor region
  215. /// </summary>
  216. private bool UpdateAgent(GridRegion destination, IAgentData cAgentData, EntityTransferContext ctx, int timeout)
  217. {
  218. // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: UpdateAgent in {0}", destination.ServerURI);
  219. // Eventually, we want to use a caps url instead of the agentID
  220. string uri = destination.ServerURI + AgentPath() + cAgentData.AgentID + "/";
  221. try
  222. {
  223. OSDMap args = cAgentData.Pack(ctx);
  224. args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
  225. args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
  226. args["destination_name"] = OSD.FromString(destination.RegionName);
  227. args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
  228. args["context"] = ctx.Pack();
  229. OSDMap result;
  230. if (ctx.OutboundVersion >= 0.3)
  231. {
  232. result = WebUtil.PutToServiceCompressed(uri, args, timeout);
  233. return result["Success"].AsBoolean();
  234. }
  235. result = WebUtil.PutToServiceCompressed(uri, args, timeout);
  236. if (result["Success"].AsBoolean())
  237. return true;
  238. if(ctx.OutboundVersion < 0.2)
  239. result = WebUtil.PutToService(uri, args, timeout);
  240. return result["Success"].AsBoolean();
  241. }
  242. catch (Exception e)
  243. {
  244. m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
  245. }
  246. return false;
  247. }
  248. public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, List<UUID> featuresAvailable, EntityTransferContext ctx, out string reason)
  249. {
  250. Culture.SetCurrentCulture();
  251. reason = "Failed to contact destination";
  252. // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position);
  253. // Eventually, we want to use a caps url instead of the agentID
  254. string uri = destination.ServerURI + AgentPath() + agentID + "/" + destination.RegionID.ToString() + "/";
  255. OSDMap request = new OSDMap();
  256. request.Add("viaTeleport", OSD.FromBoolean(viaTeleport));
  257. request.Add("position", OSD.FromString(position.ToString()));
  258. // To those who still understad this field, we're telling them
  259. // the lowest version just to be safe
  260. request.Add("my_version", OSD.FromString(String.Format("SIMULATION/{0}", VersionInfo.SimulationServiceVersionSupportedMin)));
  261. // New simulation service negotiation
  262. request.Add("simulation_service_supported_min", OSD.FromReal(VersionInfo.SimulationServiceVersionSupportedMin));
  263. request.Add("simulation_service_supported_max", OSD.FromReal(VersionInfo.SimulationServiceVersionSupportedMax));
  264. request.Add("simulation_service_accepted_min", OSD.FromReal(VersionInfo.SimulationServiceVersionAcceptedMin));
  265. request.Add("simulation_service_accepted_max", OSD.FromReal(VersionInfo.SimulationServiceVersionAcceptedMax));
  266. request.Add("context", ctx.Pack());
  267. OSDArray features = new OSDArray();
  268. foreach (UUID feature in featuresAvailable)
  269. features.Add(OSD.FromString(feature.ToString()));
  270. request.Add("features", features);
  271. if (agentHomeURI != null)
  272. request.Add("agent_home_uri", OSD.FromString(agentHomeURI));
  273. OSD tmpOSD;
  274. try
  275. {
  276. OSDMap result = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 30000, false, false, true);
  277. bool success = result["success"].AsBoolean();
  278. bool has_Result = false;
  279. if (result.TryGetValue("_Result", out tmpOSD))
  280. {
  281. has_Result = true;
  282. OSDMap data = (OSDMap)tmpOSD;
  283. // FIXME: If there is a _Result map then it's the success key here that indicates the true success
  284. // or failure, not the sibling result node.
  285. //nte4.8 crap
  286. success = data["success"].AsBoolean();
  287. reason = data["reason"].AsString();
  288. // We will need to plumb this and start sing the outbound version as well
  289. // TODO: lay the pipe for version plumbing
  290. if (data.TryGetValue("negotiated_inbound_version", out tmpOSD) && tmpOSD != null)
  291. {
  292. ctx.InboundVersion = (float)tmpOSD.AsReal();
  293. ctx.OutboundVersion = (float)data["negotiated_outbound_version"].AsReal();
  294. }
  295. else if (data.TryGetValue("version", out tmpOSD) && tmpOSD != null)
  296. {
  297. string versionString = tmpOSD.AsString();
  298. if(versionString != string.Empty)
  299. {
  300. String[] parts = versionString.Split(new char[] {'/'});
  301. if (parts.Length > 1)
  302. {
  303. ctx.InboundVersion = float.Parse(parts[1], Culture.FormatProvider);
  304. ctx.OutboundVersion = float.Parse(parts[1], Culture.FormatProvider);
  305. }
  306. }
  307. }
  308. m_log.DebugFormat(
  309. "[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3}/{4}",
  310. uri, success, reason, ctx.InboundVersion, ctx.OutboundVersion);
  311. }
  312. if (!success || ctx.InboundVersion == 0f || ctx.OutboundVersion == 0f)
  313. {
  314. // If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the
  315. // actual failure message
  316. if (!has_Result)
  317. {
  318. if (result.TryGetValue("Message", out tmpOSD))
  319. {
  320. string message = tmpOSD.AsString();
  321. if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region
  322. {
  323. m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored");
  324. return true;
  325. }
  326. reason = result["Message"];
  327. }
  328. else
  329. {
  330. reason = "Communications failure";
  331. }
  332. }
  333. return false;
  334. }
  335. featuresAvailable.Clear();
  336. if (result.TryGetValue("features", out tmpOSD) && tmpOSD is OSDArray)
  337. {
  338. OSDArray array = (OSDArray)tmpOSD;
  339. foreach (OSD o in array)
  340. featuresAvailable.Add(new UUID(o.AsString()));
  341. }
  342. // Version stuff
  343. if (ctx.OutboundVersion < 0.5)
  344. ctx.WearablesCount = AvatarWearable.LEGACY_VERSION_MAX_WEARABLES;
  345. else if (ctx.OutboundVersion < 0.6)
  346. ctx.WearablesCount = AvatarWearable.LEGACY_VERSION_MAX_WEARABLES + 1;
  347. else
  348. ctx.WearablesCount = -1; // send all (just in case..)
  349. return success;
  350. }
  351. catch (Exception e)
  352. {
  353. m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}",e.ToString());
  354. }
  355. return false;
  356. }
  357. /// <summary>
  358. /// </summary>
  359. public bool ReleaseAgent(UUID origin, UUID id, string uri)
  360. {
  361. // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: ReleaseAgent start");
  362. try
  363. {
  364. WebUtil.ServiceOSDRequest(uri, null, "DELETE", 10000, false, false);
  365. }
  366. catch (Exception e)
  367. {
  368. m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] ReleaseAgent failed with exception; {0}",e.ToString());
  369. }
  370. return true;
  371. }
  372. /// <summary>
  373. /// </summary>
  374. public bool CloseAgent(GridRegion destination, UUID id, string auth_code)
  375. {
  376. string uri = destination.ServerURI + AgentPath() + id + "/" + destination.RegionID.ToString() + "/?auth=" + auth_code;
  377. m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CloseAgent {0}", uri);
  378. try
  379. {
  380. WebUtil.ServiceOSDRequest(uri, null, "DELETE", 10000, false, false);
  381. }
  382. catch (Exception e)
  383. {
  384. m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] CloseAgent failed with exception; {0}",e.ToString());
  385. }
  386. return true;
  387. }
  388. #endregion Agents
  389. #region Objects
  390. protected virtual string ObjectPath()
  391. {
  392. return "object/";
  393. }
  394. /// <summary>
  395. ///
  396. /// </summary>
  397. public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall)
  398. {
  399. // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateObject start");
  400. string uri = destination.ServerURI + ObjectPath() + sog.UUID + "/";
  401. try
  402. {
  403. OSDMap args = new OSDMap(16);
  404. args["sog"] = OSD.FromString(sog.ToXml2());
  405. args["extra"] = OSD.FromString(sog.ExtraToXmlString());
  406. args["modified"] = OSD.FromBoolean(sog.HasGroupChanged);
  407. args["new_position"] = newPosition.ToString();
  408. string state = sog.GetStateSnapshot();
  409. if (state.Length > 0)
  410. args["state"] = OSD.FromString(state);
  411. // Add the input general arguments
  412. args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
  413. args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
  414. args["destination_name"] = OSD.FromString(destination.RegionName);
  415. args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
  416. OSDMap result = WebUtil.PostToService(uri, args, 40000, false);
  417. if (result == null)
  418. return false;
  419. bool success = result["success"].AsBoolean();
  420. if (!success)
  421. return false;
  422. }
  423. catch (Exception e)
  424. {
  425. m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] CreateObject failed with exception; {0}",e.ToString());
  426. return false;
  427. }
  428. return true;
  429. }
  430. /// <summary>
  431. ///
  432. /// </summary>
  433. public bool CreateObject(GridRegion destination, UUID userID, UUID itemID)
  434. {
  435. // TODO, not that urgent
  436. return false;
  437. }
  438. #endregion Objects
  439. }
  440. }