SimianPresenceServiceConnector.cs 20 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.Collections.Specialized;
  30. using System.Net;
  31. using System.Reflection;
  32. using log4net;
  33. using Mono.Addins;
  34. using Nini.Config;
  35. using OpenSim.Framework;
  36. using OpenSim.Framework.Servers.HttpServer;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.Framework.Scenes;
  39. using OpenSim.Services.Interfaces;
  40. using OpenSim.Server.Base;
  41. using OpenMetaverse;
  42. using OpenMetaverse.StructuredData;
  43. using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
  44. namespace OpenSim.Services.Connectors.SimianGrid
  45. {
  46. /// <summary>
  47. /// Connects avatar presence information (for tracking current location and
  48. /// message routing) to the SimianGrid backend
  49. /// </summary>
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
  51. public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule
  52. {
  53. private static readonly ILog m_log =
  54. LogManager.GetLogger(
  55. MethodBase.GetCurrentMethod().DeclaringType);
  56. private string m_serverUrl = String.Empty;
  57. private SimianActivityDetector m_activityDetector;
  58. #region ISharedRegionModule
  59. public Type ReplaceableInterface { get { return null; } }
  60. public void RegionLoaded(Scene scene) { }
  61. public void PostInitialise() { }
  62. public void Close() { }
  63. public SimianPresenceServiceConnector() { m_activityDetector = new SimianActivityDetector(this); }
  64. public string Name { get { return "SimianPresenceServiceConnector"; } }
  65. public void AddRegion(Scene scene)
  66. {
  67. if (!String.IsNullOrEmpty(m_serverUrl))
  68. {
  69. scene.RegisterModuleInterface<IPresenceService>(this);
  70. scene.RegisterModuleInterface<IGridUserService>(this);
  71. m_activityDetector.AddRegion(scene);
  72. LogoutRegionAgents(scene.RegionInfo.RegionID);
  73. }
  74. }
  75. public void RemoveRegion(Scene scene)
  76. {
  77. if (!String.IsNullOrEmpty(m_serverUrl))
  78. {
  79. scene.UnregisterModuleInterface<IPresenceService>(this);
  80. scene.UnregisterModuleInterface<IGridUserService>(this);
  81. m_activityDetector.RemoveRegion(scene);
  82. LogoutRegionAgents(scene.RegionInfo.RegionID);
  83. }
  84. }
  85. #endregion ISharedRegionModule
  86. public SimianPresenceServiceConnector(IConfigSource source)
  87. {
  88. Initialise(source);
  89. }
  90. public void Initialise(IConfigSource source)
  91. {
  92. if (Simian.IsSimianEnabled(source, "PresenceServices", this.Name))
  93. {
  94. IConfig gridConfig = source.Configs["PresenceService"];
  95. if (gridConfig == null)
  96. {
  97. m_log.Error("[SIMIAN PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini");
  98. throw new Exception("Presence connector init error");
  99. }
  100. string serviceUrl = gridConfig.GetString("PresenceServerURI");
  101. if (String.IsNullOrEmpty(serviceUrl))
  102. {
  103. m_log.Error("[SIMIAN PRESENCE CONNECTOR]: No PresenceServerURI in section PresenceService");
  104. throw new Exception("Presence connector init error");
  105. }
  106. m_serverUrl = serviceUrl;
  107. }
  108. }
  109. #region IPresenceService
  110. public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
  111. {
  112. m_log.ErrorFormat("[SIMIAN PRESENCE CONNECTOR]: Login requested, UserID={0}, SessionID={1}, SecureSessionID={2}",
  113. userID, sessionID, secureSessionID);
  114. NameValueCollection requestArgs = new NameValueCollection
  115. {
  116. { "RequestMethod", "AddSession" },
  117. { "UserID", userID.ToString() }
  118. };
  119. if (sessionID != UUID.Zero)
  120. {
  121. requestArgs["SessionID"] = sessionID.ToString();
  122. requestArgs["SecureSessionID"] = secureSessionID.ToString();
  123. }
  124. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  125. bool success = response["Success"].AsBoolean();
  126. if (!success)
  127. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to login agent " + userID + ": " + response["Message"].AsString());
  128. return success;
  129. }
  130. public bool LogoutAgent(UUID sessionID)
  131. {
  132. m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID);
  133. NameValueCollection requestArgs = new NameValueCollection
  134. {
  135. { "RequestMethod", "RemoveSession" },
  136. { "SessionID", sessionID.ToString() }
  137. };
  138. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  139. bool success = response["Success"].AsBoolean();
  140. if (!success)
  141. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agent with sessionID " + sessionID + ": " + response["Message"].AsString());
  142. return success;
  143. }
  144. public bool LogoutRegionAgents(UUID regionID)
  145. {
  146. m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for all agents in region " + regionID);
  147. NameValueCollection requestArgs = new NameValueCollection
  148. {
  149. { "RequestMethod", "RemoveSessions" },
  150. { "SceneID", regionID.ToString() }
  151. };
  152. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  153. bool success = response["Success"].AsBoolean();
  154. if (!success)
  155. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agents from region " + regionID + ": " + response["Message"].AsString());
  156. return success;
  157. }
  158. public bool ReportAgent(UUID sessionID, UUID regionID)
  159. {
  160. // Not needed for SimianGrid
  161. return true;
  162. }
  163. public PresenceInfo GetAgent(UUID sessionID)
  164. {
  165. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent with sessionID " + sessionID);
  166. NameValueCollection requestArgs = new NameValueCollection
  167. {
  168. { "RequestMethod", "GetSession" },
  169. { "SessionID", sessionID.ToString() }
  170. };
  171. OSDMap sessionResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
  172. if (sessionResponse["Success"].AsBoolean())
  173. {
  174. UUID userID = sessionResponse["UserID"].AsUUID();
  175. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
  176. requestArgs = new NameValueCollection
  177. {
  178. { "RequestMethod", "GetUser" },
  179. { "UserID", userID.ToString() }
  180. };
  181. OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
  182. if (userResponse["Success"].AsBoolean())
  183. return ResponseToPresenceInfo(sessionResponse, userResponse);
  184. else
  185. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString());
  186. }
  187. else
  188. {
  189. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session " + sessionID + ": " + sessionResponse["Message"].AsString());
  190. }
  191. return null;
  192. }
  193. public PresenceInfo[] GetAgents(string[] userIDs)
  194. {
  195. List<PresenceInfo> presences = new List<PresenceInfo>(userIDs.Length);
  196. for (int i = 0; i < userIDs.Length; i++)
  197. {
  198. UUID userID;
  199. if (UUID.TryParse(userIDs[i], out userID) && userID != UUID.Zero)
  200. presences.AddRange(GetSessions(userID));
  201. }
  202. return presences.ToArray();
  203. }
  204. #endregion IPresenceService
  205. #region IGridUserService
  206. public GridUserInfo LoggedIn(string userID)
  207. {
  208. // Never implemented at the sim
  209. return null;
  210. }
  211. public bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
  212. {
  213. // Save our last position as user data
  214. NameValueCollection requestArgs = new NameValueCollection
  215. {
  216. { "RequestMethod", "AddUserData" },
  217. { "UserID", userID.ToString() },
  218. { "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) }
  219. };
  220. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  221. bool success = response["Success"].AsBoolean();
  222. if (!success)
  223. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString());
  224. return success;
  225. }
  226. public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
  227. {
  228. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID);
  229. NameValueCollection requestArgs = new NameValueCollection
  230. {
  231. { "RequestMethod", "AddUserData" },
  232. { "UserID", userID.ToString() },
  233. { "HomeLocation", SerializeLocation(regionID, position, lookAt) }
  234. };
  235. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  236. bool success = response["Success"].AsBoolean();
  237. if (!success)
  238. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set home location for " + userID + ": " + response["Message"].AsString());
  239. return success;
  240. }
  241. public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
  242. {
  243. return UpdateSession(sessionID, regionID, lastPosition, lastLookAt);
  244. }
  245. public bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
  246. {
  247. // Never called
  248. return false;
  249. }
  250. public GridUserInfo GetGridUserInfo(string user)
  251. {
  252. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user);
  253. UUID userID = new UUID(user);
  254. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
  255. NameValueCollection requestArgs = new NameValueCollection
  256. {
  257. { "RequestMethod", "GetUser" },
  258. { "UserID", userID.ToString() }
  259. };
  260. OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
  261. if (userResponse["Success"].AsBoolean())
  262. return ResponseToGridUserInfo(userResponse);
  263. else
  264. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString());
  265. return null;
  266. }
  267. #endregion
  268. #region Helpers
  269. private OSDMap GetUserData(UUID userID)
  270. {
  271. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
  272. NameValueCollection requestArgs = new NameValueCollection
  273. {
  274. { "RequestMethod", "GetUser" },
  275. { "UserID", userID.ToString() }
  276. };
  277. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  278. if (response["Success"].AsBoolean() && response["User"] is OSDMap)
  279. return response;
  280. else
  281. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + response["Message"].AsString());
  282. return null;
  283. }
  284. // private OSDMap GetSessionData(UUID sessionID)
  285. // {
  286. // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for session " + sessionID);
  287. //
  288. // NameValueCollection requestArgs = new NameValueCollection
  289. // {
  290. // { "RequestMethod", "GetSession" },
  291. // { "SessionID", sessionID.ToString() }
  292. // };
  293. //
  294. // OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  295. // if (response["Success"].AsBoolean())
  296. // return response;
  297. // else
  298. // m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session data for session " + sessionID);
  299. //
  300. // return null;
  301. // }
  302. private List<PresenceInfo> GetSessions(UUID userID)
  303. {
  304. List<PresenceInfo> presences = new List<PresenceInfo>(1);
  305. OSDMap userResponse = GetUserData(userID);
  306. if (userResponse != null)
  307. {
  308. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting sessions for " + userID);
  309. NameValueCollection requestArgs = new NameValueCollection
  310. {
  311. { "RequestMethod", "GetSession" },
  312. { "UserID", userID.ToString() }
  313. };
  314. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  315. if (response["Success"].AsBoolean())
  316. {
  317. PresenceInfo presence = ResponseToPresenceInfo(response, userResponse);
  318. if (presence != null)
  319. presences.Add(presence);
  320. }
  321. else
  322. {
  323. m_log.Debug("[SIMIAN PRESENCE CONNECTOR]: No session returned for " + userID + ": " + response["Message"].AsString());
  324. }
  325. }
  326. return presences;
  327. }
  328. private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
  329. {
  330. // Save our current location as session data
  331. NameValueCollection requestArgs = new NameValueCollection
  332. {
  333. { "RequestMethod", "UpdateSession" },
  334. { "SessionID", sessionID.ToString() },
  335. { "SceneID", regionID.ToString() },
  336. { "ScenePosition", lastPosition.ToString() },
  337. { "SceneLookAt", lastLookAt.ToString() }
  338. };
  339. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  340. bool success = response["Success"].AsBoolean();
  341. if (!success)
  342. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString());
  343. return success;
  344. }
  345. ///// <summary>
  346. ///// Fetch the last known avatar location with GetSession and persist it
  347. ///// as user data with AddUserData
  348. ///// </summary>
  349. //private bool SetLastLocation(UUID sessionID)
  350. //{
  351. // NameValueCollection requestArgs = new NameValueCollection
  352. // {
  353. // { "RequestMethod", "GetSession" },
  354. // { "SessionID", sessionID.ToString() }
  355. // };
  356. // OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  357. // bool success = response["Success"].AsBoolean();
  358. // if (success)
  359. // {
  360. // UUID userID = response["UserID"].AsUUID();
  361. // UUID sceneID = response["SceneID"].AsUUID();
  362. // Vector3 position = response["ScenePosition"].AsVector3();
  363. // Vector3 lookAt = response["SceneLookAt"].AsVector3();
  364. // return SetLastLocation(userID, sceneID, position, lookAt);
  365. // }
  366. // else
  367. // {
  368. // m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve presence information for session " + sessionID +
  369. // " while saving last location: " + response["Message"].AsString());
  370. // }
  371. // return success;
  372. //}
  373. private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse, OSDMap userResponse)
  374. {
  375. if (sessionResponse == null)
  376. return null;
  377. PresenceInfo info = new PresenceInfo();
  378. info.UserID = sessionResponse["UserID"].AsUUID().ToString();
  379. info.RegionID = sessionResponse["SceneID"].AsUUID();
  380. return info;
  381. }
  382. private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse)
  383. {
  384. if (userResponse != null && userResponse["User"] is OSDMap)
  385. {
  386. GridUserInfo info = new GridUserInfo();
  387. info.Online = true;
  388. info.UserID = userResponse["UserID"].AsUUID().ToString();
  389. info.LastRegionID = userResponse["SceneID"].AsUUID();
  390. info.LastPosition = userResponse["ScenePosition"].AsVector3();
  391. info.LastLookAt = userResponse["SceneLookAt"].AsVector3();
  392. OSDMap user = (OSDMap)userResponse["User"];
  393. info.Login = user["LastLoginDate"].AsDate();
  394. info.Logout = user["LastLogoutDate"].AsDate();
  395. DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt);
  396. return info;
  397. }
  398. return null;
  399. }
  400. private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt)
  401. {
  402. return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}";
  403. }
  404. private bool DeserializeLocation(string location, out UUID regionID, out Vector3 position, out Vector3 lookAt)
  405. {
  406. OSDMap map = null;
  407. try { map = OSDParser.DeserializeJson(location) as OSDMap; }
  408. catch { }
  409. if (map != null)
  410. {
  411. regionID = map["SceneID"].AsUUID();
  412. if (Vector3.TryParse(map["Position"].AsString(), out position) &&
  413. Vector3.TryParse(map["LookAt"].AsString(), out lookAt))
  414. {
  415. return true;
  416. }
  417. }
  418. regionID = UUID.Zero;
  419. position = Vector3.Zero;
  420. lookAt = Vector3.Zero;
  421. return false;
  422. }
  423. #endregion Helpers
  424. }
  425. }