WebFetchInvDescModule.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Threading;
  32. using log4net;
  33. using Nini.Config;
  34. using Mono.Addins;
  35. using OpenMetaverse;
  36. using OpenMetaverse.StructuredData;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Monitoring;
  39. using OpenSim.Framework.Servers;
  40. using OpenSim.Framework.Servers.HttpServer;
  41. using OpenSim.Region.Framework.Interfaces;
  42. using OpenSim.Region.Framework.Scenes;
  43. using OpenSim.Framework.Capabilities;
  44. using OpenSim.Services.Interfaces;
  45. using Caps = OpenSim.Framework.Capabilities.Caps;
  46. using OpenSim.Capabilities.Handlers;
  47. namespace OpenSim.Region.ClientStack.Linden
  48. {
  49. /// <summary>
  50. /// This module implements both WebFetchInventoryDescendents and FetchInventoryDescendents2 capabilities.
  51. /// </summary>
  52. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebFetchInvDescModule")]
  53. public class WebFetchInvDescModule : INonSharedRegionModule
  54. {
  55. class aPollRequest
  56. {
  57. public PollServiceInventoryEventArgs thepoll;
  58. public UUID reqID;
  59. public Hashtable request;
  60. public ScenePresence presence;
  61. public List<UUID> folders;
  62. }
  63. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  64. /// <summary>
  65. /// Control whether requests will be processed asynchronously.
  66. /// </summary>
  67. /// <remarks>
  68. /// Defaults to true. Can currently not be changed once a region has been added to the module.
  69. /// </remarks>
  70. public bool ProcessQueuedRequestsAsync { get; private set; }
  71. /// <summary>
  72. /// Number of inventory requests processed by this module.
  73. /// </summary>
  74. /// <remarks>
  75. /// It's the PollServiceRequestManager that actually sends completed requests back to the requester.
  76. /// </remarks>
  77. public static int ProcessedRequestsCount { get; set; }
  78. private static Stat s_queuedRequestsStat;
  79. private static Stat s_processedRequestsStat;
  80. public Scene Scene { get; private set; }
  81. private IInventoryService m_InventoryService;
  82. private ILibraryService m_LibraryService;
  83. private bool m_Enabled;
  84. private string m_fetchInventoryDescendents2Url;
  85. private string m_webFetchInventoryDescendentsUrl;
  86. private static WebFetchInvDescHandler m_webFetchHandler;
  87. private static Thread[] m_workerThreads = null;
  88. private static DoubleQueue<aPollRequest> m_queue =
  89. new DoubleQueue<aPollRequest>();
  90. #region ISharedRegionModule Members
  91. public WebFetchInvDescModule() : this(true) {}
  92. public WebFetchInvDescModule(bool processQueuedResultsAsync)
  93. {
  94. ProcessQueuedRequestsAsync = processQueuedResultsAsync;
  95. }
  96. public void Initialise(IConfigSource source)
  97. {
  98. IConfig config = source.Configs["ClientStack.LindenCaps"];
  99. if (config == null)
  100. return;
  101. m_fetchInventoryDescendents2Url = config.GetString("Cap_FetchInventoryDescendents2", string.Empty);
  102. m_webFetchInventoryDescendentsUrl = config.GetString("Cap_WebFetchInventoryDescendents", string.Empty);
  103. if (m_fetchInventoryDescendents2Url != string.Empty || m_webFetchInventoryDescendentsUrl != string.Empty)
  104. {
  105. m_Enabled = true;
  106. }
  107. }
  108. public void AddRegion(Scene s)
  109. {
  110. if (!m_Enabled)
  111. return;
  112. Scene = s;
  113. }
  114. public void RemoveRegion(Scene s)
  115. {
  116. if (!m_Enabled)
  117. return;
  118. Scene.EventManager.OnRegisterCaps -= RegisterCaps;
  119. StatsManager.DeregisterStat(s_processedRequestsStat);
  120. StatsManager.DeregisterStat(s_queuedRequestsStat);
  121. if (ProcessQueuedRequestsAsync)
  122. {
  123. if (m_workerThreads != null)
  124. {
  125. foreach (Thread t in m_workerThreads)
  126. Watchdog.AbortThread(t.ManagedThreadId);
  127. m_workerThreads = null;
  128. }
  129. }
  130. Scene = null;
  131. }
  132. public void RegionLoaded(Scene s)
  133. {
  134. if (!m_Enabled)
  135. return;
  136. if (s_processedRequestsStat == null)
  137. s_processedRequestsStat =
  138. new Stat(
  139. "ProcessedFetchInventoryRequests",
  140. "Number of processed fetch inventory requests",
  141. "These have not necessarily yet been dispatched back to the requester.",
  142. "",
  143. "inventory",
  144. "httpfetch",
  145. StatType.Pull,
  146. MeasuresOfInterest.AverageChangeOverTime,
  147. stat => { stat.Value = ProcessedRequestsCount; },
  148. StatVerbosity.Debug);
  149. if (s_queuedRequestsStat == null)
  150. s_queuedRequestsStat =
  151. new Stat(
  152. "QueuedFetchInventoryRequests",
  153. "Number of fetch inventory requests queued for processing",
  154. "",
  155. "",
  156. "inventory",
  157. "httpfetch",
  158. StatType.Pull,
  159. MeasuresOfInterest.AverageChangeOverTime,
  160. stat => { stat.Value = m_queue.Count; },
  161. StatVerbosity.Debug);
  162. StatsManager.RegisterStat(s_processedRequestsStat);
  163. StatsManager.RegisterStat(s_queuedRequestsStat);
  164. m_InventoryService = Scene.InventoryService;
  165. m_LibraryService = Scene.LibraryService;
  166. // We'll reuse the same handler for all requests.
  167. m_webFetchHandler = new WebFetchInvDescHandler(m_InventoryService, m_LibraryService);
  168. Scene.EventManager.OnRegisterCaps += RegisterCaps;
  169. if (ProcessQueuedRequestsAsync && m_workerThreads == null)
  170. {
  171. m_workerThreads = new Thread[2];
  172. for (uint i = 0; i < 2; i++)
  173. {
  174. m_workerThreads[i] = WorkManager.StartThread(DoInventoryRequests,
  175. String.Format("InventoryWorkerThread{0}", i),
  176. ThreadPriority.Normal,
  177. false,
  178. true,
  179. null,
  180. int.MaxValue);
  181. }
  182. }
  183. }
  184. public void PostInitialise()
  185. {
  186. }
  187. public void Close() { }
  188. public string Name { get { return "WebFetchInvDescModule"; } }
  189. public Type ReplaceableInterface
  190. {
  191. get { return null; }
  192. }
  193. #endregion
  194. private class PollServiceInventoryEventArgs : PollServiceEventArgs
  195. {
  196. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  197. private Dictionary<UUID, Hashtable> responses =
  198. new Dictionary<UUID, Hashtable>();
  199. private WebFetchInvDescModule m_module;
  200. public PollServiceInventoryEventArgs(WebFetchInvDescModule module, string url, UUID pId) :
  201. base(null, url, null, null, null, pId, int.MaxValue)
  202. {
  203. m_module = module;
  204. HasEvents = (x, y) => { lock (responses) return responses.ContainsKey(x); };
  205. GetEvents = (x, y) =>
  206. {
  207. lock (responses)
  208. {
  209. try
  210. {
  211. return responses[x];
  212. }
  213. finally
  214. {
  215. responses.Remove(x);
  216. }
  217. }
  218. };
  219. Request = (x, y) =>
  220. {
  221. ScenePresence sp = m_module.Scene.GetScenePresence(Id);
  222. if (sp == null)
  223. {
  224. m_log.ErrorFormat("[INVENTORY]: Unable to find ScenePresence for {0}", Id);
  225. return;
  226. }
  227. aPollRequest reqinfo = new aPollRequest();
  228. reqinfo.thepoll = this;
  229. reqinfo.reqID = x;
  230. reqinfo.request = y;
  231. reqinfo.presence = sp;
  232. reqinfo.folders = new List<UUID>();
  233. // Decode the request here
  234. string request = y["body"].ToString();
  235. request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>");
  236. request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>");
  237. request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>");
  238. Hashtable hash = new Hashtable();
  239. try
  240. {
  241. hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  242. }
  243. catch (LLSD.LLSDParseException e)
  244. {
  245. m_log.ErrorFormat("[INVENTORY]: Fetch error: {0}{1}" + e.Message, e.StackTrace);
  246. m_log.Error("Request: " + request);
  247. return;
  248. }
  249. catch (System.Xml.XmlException)
  250. {
  251. m_log.ErrorFormat("[INVENTORY]: XML Format error");
  252. }
  253. ArrayList foldersrequested = (ArrayList)hash["folders"];
  254. bool highPriority = false;
  255. for (int i = 0; i < foldersrequested.Count; i++)
  256. {
  257. Hashtable inventoryhash = (Hashtable)foldersrequested[i];
  258. string folder = inventoryhash["folder_id"].ToString();
  259. UUID folderID;
  260. if (UUID.TryParse(folder, out folderID))
  261. {
  262. if (!reqinfo.folders.Contains(folderID))
  263. {
  264. //TODO: Port COF handling from Avination
  265. reqinfo.folders.Add(folderID);
  266. }
  267. }
  268. }
  269. if (highPriority)
  270. m_queue.EnqueueHigh(reqinfo);
  271. else
  272. m_queue.EnqueueLow(reqinfo);
  273. };
  274. NoEvents = (x, y) =>
  275. {
  276. /*
  277. lock (requests)
  278. {
  279. Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
  280. requests.Remove(request);
  281. }
  282. */
  283. Hashtable response = new Hashtable();
  284. response["int_response_code"] = 500;
  285. response["str_response_string"] = "Script timeout";
  286. response["content_type"] = "text/plain";
  287. response["keepalive"] = false;
  288. response["reusecontext"] = false;
  289. return response;
  290. };
  291. }
  292. public void Process(aPollRequest requestinfo)
  293. {
  294. UUID requestID = requestinfo.reqID;
  295. Hashtable response = new Hashtable();
  296. response["int_response_code"] = 200;
  297. response["content_type"] = "text/plain";
  298. response["keepalive"] = false;
  299. response["reusecontext"] = false;
  300. response["str_response_string"] = m_webFetchHandler.FetchInventoryDescendentsRequest(
  301. requestinfo.request["body"].ToString(), String.Empty, String.Empty, null, null);
  302. lock (responses)
  303. responses[requestID] = response;
  304. WebFetchInvDescModule.ProcessedRequestsCount++;
  305. }
  306. }
  307. private void RegisterCaps(UUID agentID, Caps caps)
  308. {
  309. RegisterFetchDescendentsCap(agentID, caps, "FetchInventoryDescendents2", m_fetchInventoryDescendents2Url);
  310. }
  311. private void RegisterFetchDescendentsCap(UUID agentID, Caps caps, string capName, string url)
  312. {
  313. string capUrl;
  314. // disable the cap clause
  315. if (url == "")
  316. {
  317. return;
  318. }
  319. // handled by the simulator
  320. else if (url == "localhost")
  321. {
  322. capUrl = "/CAPS/" + UUID.Random() + "/";
  323. // Register this as a poll service
  324. PollServiceInventoryEventArgs args = new PollServiceInventoryEventArgs(this, capUrl, agentID);
  325. args.Type = PollServiceEventArgs.EventType.Inventory;
  326. caps.RegisterPollHandler(capName, args);
  327. }
  328. // external handler
  329. else
  330. {
  331. capUrl = url;
  332. IExternalCapsModule handler = Scene.RequestModuleInterface<IExternalCapsModule>();
  333. if (handler != null)
  334. handler.RegisterExternalUserCapsHandler(agentID,caps,capName,capUrl);
  335. else
  336. caps.RegisterHandler(capName, capUrl);
  337. }
  338. // m_log.DebugFormat(
  339. // "[FETCH INVENTORY DESCENDENTS2 MODULE]: Registered capability {0} at {1} in region {2} for {3}",
  340. // capName, capUrl, m_scene.RegionInfo.RegionName, agentID);
  341. }
  342. // private void DeregisterCaps(UUID agentID, Caps caps)
  343. // {
  344. // string capUrl;
  345. //
  346. // if (m_capsDict.TryGetValue(agentID, out capUrl))
  347. // {
  348. // MainServer.Instance.RemoveHTTPHandler("", capUrl);
  349. // m_capsDict.Remove(agentID);
  350. // }
  351. // }
  352. private void DoInventoryRequests()
  353. {
  354. while (true)
  355. {
  356. Watchdog.UpdateThread();
  357. WaitProcessQueuedInventoryRequest();
  358. }
  359. }
  360. public void WaitProcessQueuedInventoryRequest()
  361. {
  362. aPollRequest poolreq = m_queue.Dequeue();
  363. if (poolreq != null && poolreq.thepoll != null)
  364. {
  365. try
  366. {
  367. poolreq.thepoll.Process(poolreq);
  368. }
  369. catch (Exception e)
  370. {
  371. m_log.ErrorFormat(
  372. "[INVENTORY]: Failed to process queued inventory request {0} for {1} in {2}. Exception {3}",
  373. poolreq.reqID, poolreq.presence != null ? poolreq.presence.Name : "unknown", Scene.Name, e);
  374. }
  375. }
  376. }
  377. }
  378. }