RESTInterregionComms.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 OpenSim 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;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Net;
  32. using System.Net.Sockets;
  33. using System.Reflection;
  34. using System.Threading;
  35. using System.Xml;
  36. using OpenMetaverse;
  37. using OpenMetaverse.StructuredData;
  38. using log4net;
  39. using Nini.Config;
  40. using Nwc.XmlRpc;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Communications;
  43. using OpenSim.Framework.Communications.Cache;
  44. using OpenSim.Region.Environment.Interfaces;
  45. using OpenSim.Region.Interfaces;
  46. using OpenSim.Region.Environment.Scenes;
  47. using OpenSim.Region.Environment.Modules.Communications.Local;
  48. namespace OpenSim.Region.Environment.Modules.Communications.REST
  49. {
  50. public class RESTInterregionComms : IRegionModule, IInterregionCommsOut
  51. {
  52. private static bool initialized = false;
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. protected bool m_enabled = false;
  55. protected Scene m_aScene;
  56. // RESTInterregionComms does not care about local regions; it delegates that to the Local module
  57. protected LocalInterregionComms m_localBackend;
  58. protected CommunicationsManager m_commsManager;
  59. #region IRegionModule
  60. public virtual void Initialise(Scene scene, IConfigSource config)
  61. {
  62. if (!initialized)
  63. {
  64. initialized = true;
  65. IConfig startupConfig = config.Configs["Communications"];
  66. if ((startupConfig != null) && (startupConfig.GetString("InterregionComms", "RESTCommms") == "RESTComms"))
  67. {
  68. m_enabled = true;
  69. InitOnce(scene);
  70. }
  71. }
  72. if (!m_enabled)
  73. return;
  74. InitEach(scene);
  75. }
  76. public virtual void PostInitialise()
  77. {
  78. if (m_enabled)
  79. AddHTTPHandlers();
  80. }
  81. public virtual void Close()
  82. {
  83. }
  84. public virtual string Name
  85. {
  86. get { return "RESTInterregionCommsModule"; }
  87. }
  88. public virtual bool IsSharedModule
  89. {
  90. get { return true; }
  91. }
  92. protected virtual void InitEach(Scene scene)
  93. {
  94. m_localBackend.Init(scene);
  95. scene.RegisterModuleInterface<IInterregionCommsOut>(this);
  96. }
  97. protected virtual void InitOnce(Scene scene)
  98. {
  99. m_localBackend = new LocalInterregionComms();
  100. m_commsManager = scene.CommsManager;
  101. m_aScene = scene;
  102. }
  103. protected virtual void AddHTTPHandlers()
  104. {
  105. m_aScene.AddHTTPHandler("/ChildAgentUpdate/", ChildAgentUpdateHandler);
  106. }
  107. #endregion /* IRegionModule */
  108. #region IInterregionComms
  109. public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData)
  110. {
  111. // Try local first
  112. if (m_localBackend.SendChildAgentUpdate(regionHandle, cAgentData))
  113. return true;
  114. // else do the remote thing
  115. RegionInfo regInfo = m_commsManager.GridService.RequestNeighbourInfo(regionHandle);
  116. if (regInfo != null)
  117. {
  118. return DoChildAgentUpdateCall(regInfo, cAgentData);
  119. }
  120. return false;
  121. }
  122. protected bool DoChildAgentUpdateCall(RegionInfo region, AgentData cAgentData)
  123. {
  124. string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/ChildAgentUpdate/";
  125. //Console.WriteLine(" >>> DoChildAgentUpdateCall <<< " + uri);
  126. WebRequest ChildUpdateRequest = WebRequest.Create(uri);
  127. ChildUpdateRequest.Method = "PUT";
  128. ChildUpdateRequest.ContentType = "application/json";
  129. ChildUpdateRequest.Timeout = 10000;
  130. // Fill it in
  131. OSDMap args = null;
  132. try
  133. {
  134. args = cAgentData.PackUpdateMessage();
  135. }
  136. catch (Exception e)
  137. {
  138. m_log.Debug("[REST COMMS]: PackUpdateMessage failed with exception: " + e.Message);
  139. }
  140. // Add the regionhandle of the destination region
  141. ulong regionHandle = GetRegionHandle(region);
  142. args["destination_handle"] = OSD.FromString(regionHandle.ToString());
  143. string strBuffer = "";
  144. byte[] buffer = new byte[1];
  145. try
  146. {
  147. strBuffer = OSDParser.SerializeJsonString(args);
  148. System.Text.UTF8Encoding str = new System.Text.UTF8Encoding();
  149. buffer = str.GetBytes(strBuffer);
  150. }
  151. catch (Exception e)
  152. {
  153. m_log.WarnFormat("[OSG2]: Exception thrown on serialization of ChildUpdate: {0}", e.Message);
  154. // ignore. buffer will be empty, caller should check.
  155. }
  156. Stream os = null;
  157. try
  158. { // send the Post
  159. ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send
  160. os = ChildUpdateRequest.GetRequestStream();
  161. os.Write(buffer, 0, strBuffer.Length); //Send it
  162. os.Close();
  163. //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
  164. }
  165. catch (WebException ex)
  166. {
  167. //m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
  168. return false;
  169. }
  170. // Let's wait for the response
  171. //m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
  172. string reply = null;
  173. try
  174. {
  175. WebResponse webResponse = ChildUpdateRequest.GetResponse();
  176. if (webResponse == null)
  177. {
  178. m_log.Info("[REST COMMS]: Null reply on ChilAgentUpdate post");
  179. }
  180. StreamReader sr = new StreamReader(webResponse.GetResponseStream());
  181. reply = sr.ReadToEnd().Trim();
  182. sr.Close();
  183. //m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
  184. }
  185. catch (WebException ex)
  186. {
  187. m_log.InfoFormat("[REST COMMS]: exception on reply of ChilAgentUpdate {0}", ex.Message);
  188. // ignore, really
  189. }
  190. return true;
  191. }
  192. #endregion /* IInterregionComms */
  193. #region Called from remote instances on this instance
  194. public Hashtable ChildAgentUpdateHandler(Hashtable request)
  195. {
  196. //m_log.Debug("[CONNECTION DEBUGGING]: ChildDataUpdateHandler Called");
  197. Hashtable responsedata = new Hashtable();
  198. responsedata["content_type"] = "text/html";
  199. OSDMap args = null;
  200. try
  201. {
  202. OSD buffer;
  203. // We should pay attention to the content-type, but let's assume we know it's Json
  204. buffer = OSDParser.DeserializeJson((string)request["body"]);
  205. if (buffer.Type == OSDType.Map)
  206. args = (OSDMap)buffer;
  207. else
  208. {
  209. // uh?
  210. m_log.Debug("[REST COMMS]: Got OSD of type " + buffer.Type.ToString());
  211. }
  212. }
  213. catch (Exception ex)
  214. {
  215. m_log.InfoFormat("[REST COMMS]: exception on parse of ChildAgentUpdate message {0}", ex.Message);
  216. responsedata["int_response_code"] = 400;
  217. responsedata["str_response_string"] = "false";
  218. return responsedata;
  219. }
  220. // retrieve the regionhandle
  221. ulong regionhandle = 0;
  222. if (args["destination_handle"] != null)
  223. UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
  224. AgentData agent = new AgentData();
  225. try
  226. {
  227. agent.UnpackUpdateMessage(args);
  228. }
  229. catch (Exception ex)
  230. {
  231. m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  232. }
  233. //agent.Dump();
  234. bool result = m_localBackend.SendChildAgentUpdate(regionhandle, agent);
  235. responsedata["int_response_code"] = 200;
  236. responsedata["str_response_string"] = result.ToString();
  237. return responsedata;
  238. }
  239. #endregion
  240. #region Misc
  241. protected virtual ulong GetRegionHandle(RegionInfo region)
  242. {
  243. return region.RegionHandle;
  244. }
  245. #endregion /* Misc */
  246. }
  247. }