GridService.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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.Net;
  30. using System.Reflection;
  31. using Nini.Config;
  32. using log4net;
  33. using OpenSim.Framework;
  34. using OpenSim.Framework.Console;
  35. using OpenSim.Data;
  36. using OpenSim.Server.Base;
  37. using OpenSim.Services.Interfaces;
  38. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  39. using OpenMetaverse;
  40. namespace OpenSim.Services.GridService
  41. {
  42. public class GridService : GridServiceBase, IGridService
  43. {
  44. private static readonly ILog m_log =
  45. LogManager.GetLogger(
  46. MethodBase.GetCurrentMethod().DeclaringType);
  47. private string LogHeader = "[GRID SERVICE]";
  48. private bool m_DeleteOnUnregister = true;
  49. private static GridService m_RootInstance = null;
  50. protected IConfigSource m_config;
  51. protected static HypergridLinker m_HypergridLinker;
  52. protected IAuthenticationService m_AuthenticationService = null;
  53. protected bool m_AllowDuplicateNames = false;
  54. protected bool m_AllowHypergridMapSearch = false;
  55. protected bool m_SuppressVarregionOverlapCheckOnRegistration = false;
  56. private static Dictionary<string,object> m_ExtraFeatures = new Dictionary<string, object>();
  57. public GridService(IConfigSource config)
  58. : base(config)
  59. {
  60. m_log.DebugFormat("[GRID SERVICE]: Starting...");
  61. m_config = config;
  62. IConfig gridConfig = config.Configs["GridService"];
  63. bool suppressConsoleCommands = false;
  64. if (gridConfig != null)
  65. {
  66. m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true);
  67. string authService = gridConfig.GetString("AuthenticationService", String.Empty);
  68. if (authService != String.Empty)
  69. {
  70. Object[] args = new Object[] { config };
  71. m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
  72. }
  73. m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames);
  74. m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch);
  75. m_SuppressVarregionOverlapCheckOnRegistration = gridConfig.GetBoolean("SuppressVarregionOverlapCheckOnRegistration", m_SuppressVarregionOverlapCheckOnRegistration);
  76. // This service is also used locally by a simulator running in grid mode. This switches prevents
  77. // inappropriate console commands from being registered
  78. suppressConsoleCommands = gridConfig.GetBoolean("SuppressConsoleCommands", suppressConsoleCommands);
  79. }
  80. if (m_RootInstance == null)
  81. {
  82. m_RootInstance = this;
  83. if (!suppressConsoleCommands && MainConsole.Instance != null)
  84. {
  85. MainConsole.Instance.Commands.AddCommand("Regions", true,
  86. "deregister region id",
  87. "deregister region id <region-id>+",
  88. "Deregister a region manually.",
  89. String.Empty,
  90. HandleDeregisterRegion);
  91. MainConsole.Instance.Commands.AddCommand("Regions", true,
  92. "show regions",
  93. "show regions",
  94. "Show details on all regions",
  95. String.Empty,
  96. HandleShowRegions);
  97. MainConsole.Instance.Commands.AddCommand("Regions", true,
  98. "show region name",
  99. "show region name <Region name>",
  100. "Show details on a region",
  101. String.Empty,
  102. HandleShowRegion);
  103. MainConsole.Instance.Commands.AddCommand("Regions", true,
  104. "show region at",
  105. "show region at <x-coord> <y-coord>",
  106. "Show details on a region at the given co-ordinate.",
  107. "For example, show region at 1000 1000",
  108. HandleShowRegionAt);
  109. MainConsole.Instance.Commands.AddCommand("General", true,
  110. "show grid size",
  111. "show grid size",
  112. "Show the current grid size (excluding hyperlink references)",
  113. String.Empty,
  114. HandleShowGridSize);
  115. MainConsole.Instance.Commands.AddCommand("Regions", true,
  116. "set region flags",
  117. "set region flags <Region name> <flags>",
  118. "Set database flags for region",
  119. String.Empty,
  120. HandleSetFlags);
  121. }
  122. if (!suppressConsoleCommands)
  123. SetExtraServiceURLs(config);
  124. m_HypergridLinker = new HypergridLinker(m_config, this, m_Database);
  125. }
  126. }
  127. private void SetExtraServiceURLs(IConfigSource config)
  128. {
  129. IConfig loginConfig = config.Configs["LoginService"];
  130. IConfig gridConfig = config.Configs["GridService"];
  131. if (loginConfig == null || gridConfig == null)
  132. return;
  133. string configVal;
  134. configVal = loginConfig.GetString("SearchURL", string.Empty);
  135. if (!string.IsNullOrEmpty(configVal))
  136. m_ExtraFeatures["search-server-url"] = configVal;
  137. configVal = loginConfig.GetString("MapTileURL", string.Empty);
  138. if (!string.IsNullOrEmpty(configVal))
  139. {
  140. // This URL must end with '/', the viewer doesn't check
  141. configVal = configVal.Trim();
  142. if (!configVal.EndsWith("/"))
  143. configVal = configVal + "/";
  144. m_ExtraFeatures["map-server-url"] = configVal;
  145. }
  146. configVal = loginConfig.GetString("DestinationGuide", string.Empty);
  147. if (!string.IsNullOrEmpty(configVal))
  148. m_ExtraFeatures["destination-guide-url"] = configVal;
  149. configVal = Util.GetConfigVarFromSections<string>(
  150. config, "GatekeeperURI", new string[] { "Startup", "Hypergrid" }, String.Empty);
  151. if (!string.IsNullOrEmpty(configVal))
  152. m_ExtraFeatures["GridURL"] = configVal;
  153. configVal = Util.GetConfigVarFromSections<string>(
  154. config, "GridName", new string[] { "Const", "Hypergrid" }, String.Empty);
  155. if (string.IsNullOrEmpty(configVal))
  156. configVal = Util.GetConfigVarFromSections<string>(
  157. config, "gridname", new string[] { "GridInfo" }, String.Empty);
  158. if (!string.IsNullOrEmpty(configVal))
  159. m_ExtraFeatures["GridName"] = configVal;
  160. m_ExtraFeatures["ExportSupported"] = gridConfig.GetString("ExportSupported", "true");
  161. }
  162. #region IGridService
  163. public string RegisterRegion(UUID scopeID, GridRegion regionInfos)
  164. {
  165. IConfig gridConfig = m_config.Configs["GridService"];
  166. if (regionInfos.RegionID == UUID.Zero)
  167. return "Invalid RegionID - cannot be zero UUID";
  168. String reason = "Region overlaps another region";
  169. RegionData region = FindAnyConflictingRegion(regionInfos, scopeID, out reason);
  170. // If there is a conflicting region, if it has the same ID and same coordinates
  171. // then it is a region re-registering (permissions and ownership checked later).
  172. if ((region != null)
  173. && ( (region.coordX != regionInfos.RegionCoordX)
  174. || (region.coordY != regionInfos.RegionCoordY)
  175. || (region.RegionID != regionInfos.RegionID) )
  176. )
  177. {
  178. // If not same ID and same coordinates, this new region has conflicts and can't be registered.
  179. m_log.WarnFormat("{0} Register region conflict in scope {1}. {2}", LogHeader, scopeID, reason);
  180. return reason;
  181. }
  182. if (region != null)
  183. {
  184. // There is a preexisting record
  185. //
  186. // Get it's flags
  187. //
  188. OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(region.Data["flags"]);
  189. // Is this a reservation?
  190. //
  191. if ((rflags & OpenSim.Framework.RegionFlags.Reservation) != 0)
  192. {
  193. // Regions reserved for the null key cannot be taken.
  194. if ((string)region.Data["PrincipalID"] == UUID.Zero.ToString())
  195. return "Region location is reserved";
  196. // Treat it as an auth request
  197. //
  198. // NOTE: Fudging the flags value here, so these flags
  199. // should not be used elsewhere. Don't optimize
  200. // this with the later retrieval of the same flags!
  201. rflags |= OpenSim.Framework.RegionFlags.Authenticate;
  202. }
  203. if ((rflags & OpenSim.Framework.RegionFlags.Authenticate) != 0)
  204. {
  205. // Can we authenticate at all?
  206. //
  207. if (m_AuthenticationService == null)
  208. return "No authentication possible";
  209. if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30))
  210. return "Bad authentication";
  211. }
  212. }
  213. // If we get here, the destination is clear. Now for the real check.
  214. if (!m_AllowDuplicateNames)
  215. {
  216. List<RegionData> dupe = m_Database.Get(Util.EscapeForLike(regionInfos.RegionName), scopeID);
  217. if (dupe != null && dupe.Count > 0)
  218. {
  219. foreach (RegionData d in dupe)
  220. {
  221. if (d.RegionID != regionInfos.RegionID)
  222. {
  223. m_log.WarnFormat("[GRID SERVICE]: Region tried to register using a duplicate name. New region: {0} ({1}), existing region: {2} ({3}).",
  224. regionInfos.RegionName, regionInfos.RegionID, d.RegionName, d.RegionID);
  225. return "Duplicate region name";
  226. }
  227. }
  228. }
  229. }
  230. // If there is an old record for us, delete it if it is elsewhere.
  231. region = m_Database.Get(regionInfos.RegionID, scopeID);
  232. if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
  233. ((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
  234. {
  235. if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.NoMove) != 0)
  236. return "Can't move this region";
  237. if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.LockedOut) != 0)
  238. return "Region locked out";
  239. // Region reregistering in other coordinates. Delete the old entry
  240. m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
  241. regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);
  242. try
  243. {
  244. m_Database.Delete(regionInfos.RegionID);
  245. }
  246. catch (Exception e)
  247. {
  248. m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
  249. }
  250. }
  251. // Everything is ok, let's register
  252. RegionData rdata = RegionInfo2RegionData(regionInfos);
  253. rdata.ScopeID = scopeID;
  254. if (region != null)
  255. {
  256. int oldFlags = Convert.ToInt32(region.Data["flags"]);
  257. oldFlags &= ~(int)OpenSim.Framework.RegionFlags.Reservation;
  258. rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags
  259. }
  260. else
  261. {
  262. rdata.Data["flags"] = "0";
  263. if ((gridConfig != null) && rdata.RegionName != string.Empty)
  264. {
  265. int newFlags = 0;
  266. string regionName = rdata.RegionName.Trim().Replace(' ', '_');
  267. newFlags = ParseFlags(newFlags, gridConfig.GetString("DefaultRegionFlags", String.Empty));
  268. newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty));
  269. newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty));
  270. rdata.Data["flags"] = newFlags.ToString();
  271. }
  272. }
  273. int flags = Convert.ToInt32(rdata.Data["flags"]);
  274. flags |= (int)OpenSim.Framework.RegionFlags.RegionOnline;
  275. rdata.Data["flags"] = flags.ToString();
  276. try
  277. {
  278. rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch();
  279. m_Database.Store(rdata);
  280. }
  281. catch (Exception e)
  282. {
  283. m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
  284. }
  285. m_log.DebugFormat
  286. ("[GRID SERVICE]: Region {0} ({1}, {2}x{3}) registered at {4},{5} with flags {6}",
  287. regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionSizeX, regionInfos.RegionSizeY,
  288. regionInfos.RegionCoordX, regionInfos.RegionCoordY,
  289. (OpenSim.Framework.RegionFlags)flags);
  290. return String.Empty;
  291. }
  292. /// <summary>
  293. /// Search the region map for regions conflicting with this region.
  294. /// The region to be added is passed and we look for any existing regions that are
  295. /// in the requested location, that are large varregions that overlap this region, or
  296. /// are previously defined regions that would lie under this new region.
  297. /// </summary>
  298. /// <param name="regionInfos">Information on region requested to be added to the world map</param>
  299. /// <param name="scopeID">Grid id for region</param>
  300. /// <param name="reason">The reason the returned region conflicts with passed region</param>
  301. /// <returns></returns>
  302. private RegionData FindAnyConflictingRegion(GridRegion regionInfos, UUID scopeID, out string reason)
  303. {
  304. reason = "Reregistration";
  305. // First see if there is an existing region right where this region is trying to go
  306. // (We keep this result so it can be returned if suppressing errors)
  307. RegionData noErrorRegion = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
  308. RegionData region = noErrorRegion;
  309. if (region != null
  310. && region.RegionID == regionInfos.RegionID
  311. && region.sizeX == regionInfos.RegionSizeX
  312. && region.sizeY == regionInfos.RegionSizeY)
  313. {
  314. // If this seems to be exactly the same region, return this as it could be
  315. // a re-registration (permissions checked by calling routine).
  316. m_log.DebugFormat("{0} FindAnyConflictingRegion: re-register of {1}",
  317. LogHeader, RegionString(regionInfos));
  318. return region;
  319. }
  320. // No region exactly there or we're resizing an existing region.
  321. // Fetch regions that could be varregions overlapping requested location.
  322. int xmin = regionInfos.RegionLocX - (int)Constants.MaximumRegionSize + 10;
  323. int xmax = regionInfos.RegionLocX;
  324. int ymin = regionInfos.RegionLocY - (int)Constants.MaximumRegionSize + 10;
  325. int ymax = regionInfos.RegionLocY;
  326. List<RegionData> rdatas = m_Database.Get(xmin, ymin, xmax, ymax, scopeID);
  327. foreach (RegionData rdata in rdatas)
  328. {
  329. // m_log.DebugFormat("{0} FindAnyConflictingRegion: find existing. Checking {1}", LogHeader, RegionString(rdata) );
  330. if ( (rdata.posX + rdata.sizeX > regionInfos.RegionLocX)
  331. && (rdata.posY + rdata.sizeY > regionInfos.RegionLocY) )
  332. {
  333. region = rdata;
  334. m_log.WarnFormat("{0} FindAnyConflictingRegion: conflict of {1} by existing varregion {2}",
  335. LogHeader, RegionString(regionInfos), RegionString(region));
  336. reason = String.Format("Region location is overlapped by existing varregion {0}",
  337. RegionString(region));
  338. if (m_SuppressVarregionOverlapCheckOnRegistration)
  339. region = noErrorRegion;
  340. return region;
  341. }
  342. }
  343. // There isn't a region that overlaps this potential region.
  344. // See if this potential region overlaps an existing region.
  345. // First, a shortcut of not looking for overlap if new region is legacy region sized
  346. // and connot overlap anything.
  347. if (regionInfos.RegionSizeX != Constants.RegionSize
  348. || regionInfos.RegionSizeY != Constants.RegionSize)
  349. {
  350. // trim range looked for so we don't pick up neighbor regions just off the edges
  351. xmin = regionInfos.RegionLocX;
  352. xmax = regionInfos.RegionLocX + regionInfos.RegionSizeX - 10;
  353. ymin = regionInfos.RegionLocY;
  354. ymax = regionInfos.RegionLocY + regionInfos.RegionSizeY - 10;
  355. rdatas = m_Database.Get(xmin, ymin, xmax, ymax, scopeID);
  356. // If the region is being resized, the found region could be ourself.
  357. foreach (RegionData rdata in rdatas)
  358. {
  359. // m_log.DebugFormat("{0} FindAnyConflictingRegion: see if overlap. Checking {1}", LogHeader, RegionString(rdata) );
  360. if (region == null || region.RegionID != regionInfos.RegionID)
  361. {
  362. region = rdata;
  363. m_log.WarnFormat("{0} FindAnyConflictingRegion: conflict of varregion {1} overlaps existing region {2}",
  364. LogHeader, RegionString(regionInfos), RegionString(region));
  365. reason = String.Format("Region {0} would overlap existing region {1}",
  366. RegionString(regionInfos), RegionString(region));
  367. if (m_SuppressVarregionOverlapCheckOnRegistration)
  368. region = noErrorRegion;
  369. return region;
  370. }
  371. }
  372. }
  373. // If we get here, region is either null (nothing found here) or
  374. // is the non-conflicting region found at the location being requested.
  375. return region;
  376. }
  377. // String describing name and region location of passed region
  378. private String RegionString(RegionData reg)
  379. {
  380. return String.Format("{0}/{1} at <{2},{3}>",
  381. reg.RegionName, reg.RegionID, reg.coordX, reg.coordY);
  382. }
  383. // String describing name and region location of passed region
  384. private String RegionString(GridRegion reg)
  385. {
  386. return String.Format("{0}/{1} at <{2},{3}>",
  387. reg.RegionName, reg.RegionID, reg.RegionCoordX, reg.RegionCoordY);
  388. }
  389. public bool DeregisterRegion(UUID regionID)
  390. {
  391. RegionData region = m_Database.Get(regionID, UUID.Zero);
  392. if (region == null)
  393. return false;
  394. m_log.DebugFormat(
  395. "[GRID SERVICE]: Deregistering region {0} ({1}) at {2}-{3}",
  396. region.RegionName, region.RegionID, region.coordX, region.coordY);
  397. int flags = Convert.ToInt32(region.Data["flags"]);
  398. if (!m_DeleteOnUnregister || (flags & (int)OpenSim.Framework.RegionFlags.Persistent) != 0)
  399. {
  400. flags &= ~(int)OpenSim.Framework.RegionFlags.RegionOnline;
  401. region.Data["flags"] = flags.ToString();
  402. region.Data["last_seen"] = Util.UnixTimeSinceEpoch();
  403. try
  404. {
  405. m_Database.Store(region);
  406. }
  407. catch (Exception e)
  408. {
  409. m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
  410. }
  411. return true;
  412. }
  413. return m_Database.Delete(regionID);
  414. }
  415. public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
  416. {
  417. List<GridRegion> rinfos = new List<GridRegion>();
  418. RegionData region = m_Database.Get(regionID, scopeID);
  419. if (region != null)
  420. {
  421. // Not really? Maybe?
  422. // The adjacent regions are presumed to be the same size as the current region
  423. List<RegionData> rdatas = m_Database.Get(
  424. region.posX - region.sizeX - 1, region.posY - region.sizeY - 1,
  425. region.posX + region.sizeX + 1, region.posY + region.sizeY + 1, scopeID);
  426. foreach (RegionData rdata in rdatas)
  427. {
  428. if (rdata.RegionID != regionID)
  429. {
  430. int flags = Convert.ToInt32(rdata.Data["flags"]);
  431. if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours
  432. rinfos.Add(RegionData2RegionInfo(rdata));
  433. }
  434. }
  435. // string rNames = "";
  436. // foreach (GridRegion gr in rinfos)
  437. // rNames += gr.RegionName + ",";
  438. // m_log.DebugFormat("{0} region {1} has {2} neighbours ({3})",
  439. // LogHeader, region.RegionName, rinfos.Count, rNames);
  440. }
  441. else
  442. {
  443. m_log.WarnFormat(
  444. "[GRID SERVICE]: GetNeighbours() called for scope {0}, region {1} but no such region found",
  445. scopeID, regionID);
  446. }
  447. return rinfos;
  448. }
  449. public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
  450. {
  451. RegionData rdata = m_Database.Get(regionID, scopeID);
  452. if (rdata != null)
  453. return RegionData2RegionInfo(rdata);
  454. return null;
  455. }
  456. // Get a region given its base coordinates.
  457. // NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
  458. // be the base coordinate of the region.
  459. // The snapping is technically unnecessary but is harmless because regions are always
  460. // multiples of the legacy region size (256).
  461. public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
  462. {
  463. uint regionX = Util.WorldToRegionLoc((uint)x);
  464. uint regionY = Util.WorldToRegionLoc((uint)y);
  465. int snapX = (int)Util.RegionToWorldLoc(regionX);
  466. int snapY = (int)Util.RegionToWorldLoc(regionY);
  467. RegionData rdata = m_Database.Get(snapX, snapY, scopeID);
  468. if (rdata != null)
  469. {
  470. m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in database. Pos=<{2},{3}>",
  471. LogHeader, rdata.RegionName, regionX, regionY);
  472. return RegionData2RegionInfo(rdata);
  473. }
  474. else
  475. {
  476. m_log.DebugFormat("{0} GetRegionByPosition. Did not find region in database. Pos=<{1},{2}>",
  477. LogHeader, regionX, regionY);
  478. return null;
  479. }
  480. }
  481. public GridRegion GetRegionByName(UUID scopeID, string name)
  482. {
  483. List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name), scopeID);
  484. if ((rdatas != null) && (rdatas.Count > 0))
  485. return RegionData2RegionInfo(rdatas[0]); // get the first
  486. if (m_AllowHypergridMapSearch)
  487. {
  488. GridRegion r = GetHypergridRegionByName(scopeID, name);
  489. if (r != null)
  490. return r;
  491. }
  492. return null;
  493. }
  494. public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
  495. {
  496. // m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name);
  497. List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name) + "%", scopeID);
  498. int count = 0;
  499. List<GridRegion> rinfos = new List<GridRegion>();
  500. if (rdatas != null)
  501. {
  502. // m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
  503. foreach (RegionData rdata in rdatas)
  504. {
  505. if (count++ < maxNumber)
  506. rinfos.Add(RegionData2RegionInfo(rdata));
  507. }
  508. }
  509. if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0)))
  510. {
  511. GridRegion r = GetHypergridRegionByName(scopeID, name);
  512. if (r != null)
  513. rinfos.Add(r);
  514. }
  515. return rinfos;
  516. }
  517. /// <summary>
  518. /// Get a hypergrid region.
  519. /// </summary>
  520. /// <param name="scopeID"></param>
  521. /// <param name="name"></param>
  522. /// <returns>null if no hypergrid region could be found.</returns>
  523. protected GridRegion GetHypergridRegionByName(UUID scopeID, string name)
  524. {
  525. if (name.Contains("."))
  526. return m_HypergridLinker.LinkRegion(scopeID, name);
  527. else
  528. return null;
  529. }
  530. public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
  531. {
  532. int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
  533. int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
  534. int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
  535. int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
  536. List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);
  537. List<GridRegion> rinfos = new List<GridRegion>();
  538. foreach (RegionData rdata in rdatas)
  539. rinfos.Add(RegionData2RegionInfo(rdata));
  540. return rinfos;
  541. }
  542. #endregion
  543. #region Data structure conversions
  544. public RegionData RegionInfo2RegionData(GridRegion rinfo)
  545. {
  546. RegionData rdata = new RegionData();
  547. rdata.posX = (int)rinfo.RegionLocX;
  548. rdata.posY = (int)rinfo.RegionLocY;
  549. rdata.sizeX = rinfo.RegionSizeX;
  550. rdata.sizeY = rinfo.RegionSizeY;
  551. rdata.RegionID = rinfo.RegionID;
  552. rdata.RegionName = rinfo.RegionName;
  553. rdata.Data = rinfo.ToKeyValuePairs();
  554. rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);
  555. rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString();
  556. return rdata;
  557. }
  558. public GridRegion RegionData2RegionInfo(RegionData rdata)
  559. {
  560. GridRegion rinfo = new GridRegion(rdata.Data);
  561. rinfo.RegionLocX = rdata.posX;
  562. rinfo.RegionLocY = rdata.posY;
  563. rinfo.RegionSizeX = rdata.sizeX;
  564. rinfo.RegionSizeY = rdata.sizeY;
  565. rinfo.RegionID = rdata.RegionID;
  566. rinfo.RegionName = rdata.RegionName;
  567. rinfo.ScopeID = rdata.ScopeID;
  568. return rinfo;
  569. }
  570. #endregion
  571. public List<GridRegion> GetDefaultRegions(UUID scopeID)
  572. {
  573. List<GridRegion> ret = new List<GridRegion>();
  574. List<RegionData> regions = m_Database.GetDefaultRegions(scopeID);
  575. foreach (RegionData r in regions)
  576. {
  577. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  578. ret.Add(RegionData2RegionInfo(r));
  579. }
  580. m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count);
  581. return ret;
  582. }
  583. public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
  584. {
  585. List<GridRegion> ret = new List<GridRegion>();
  586. List<RegionData> regions = m_Database.GetDefaultHypergridRegions(scopeID);
  587. foreach (RegionData r in regions)
  588. {
  589. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  590. ret.Add(RegionData2RegionInfo(r));
  591. }
  592. int hgDefaultRegionsFoundOnline = regions.Count;
  593. // For now, hypergrid default regions will always be given precedence but we will also return simple default
  594. // regions in case no specific hypergrid regions are specified.
  595. ret.AddRange(GetDefaultRegions(scopeID));
  596. int normalDefaultRegionsFoundOnline = ret.Count - hgDefaultRegionsFoundOnline;
  597. m_log.DebugFormat(
  598. "[GRID SERVICE]: GetDefaultHypergridRegions returning {0} hypergrid default and {1} normal default regions",
  599. hgDefaultRegionsFoundOnline, normalDefaultRegionsFoundOnline);
  600. return ret;
  601. }
  602. public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
  603. {
  604. List<GridRegion> ret = new List<GridRegion>();
  605. List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y);
  606. foreach (RegionData r in regions)
  607. {
  608. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  609. ret.Add(RegionData2RegionInfo(r));
  610. }
  611. m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count);
  612. return ret;
  613. }
  614. public List<GridRegion> GetHyperlinks(UUID scopeID)
  615. {
  616. List<GridRegion> ret = new List<GridRegion>();
  617. List<RegionData> regions = m_Database.GetHyperlinks(scopeID);
  618. foreach (RegionData r in regions)
  619. {
  620. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  621. ret.Add(RegionData2RegionInfo(r));
  622. }
  623. m_log.DebugFormat("[GRID SERVICE]: Hyperlinks returned {0} regions", ret.Count);
  624. return ret;
  625. }
  626. public int GetRegionFlags(UUID scopeID, UUID regionID)
  627. {
  628. RegionData region = m_Database.Get(regionID, scopeID);
  629. if (region != null)
  630. {
  631. int flags = Convert.ToInt32(region.Data["flags"]);
  632. //m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags);
  633. return flags;
  634. }
  635. else
  636. return -1;
  637. }
  638. private void HandleDeregisterRegion(string module, string[] cmd)
  639. {
  640. if (cmd.Length < 4)
  641. {
  642. MainConsole.Instance.Output("Usage: degregister region id <region-id>+");
  643. return;
  644. }
  645. for (int i = 3; i < cmd.Length; i++)
  646. {
  647. string rawRegionUuid = cmd[i];
  648. UUID regionUuid;
  649. if (!UUID.TryParse(rawRegionUuid, out regionUuid))
  650. {
  651. MainConsole.Instance.OutputFormat("{0} is not a valid region uuid", rawRegionUuid);
  652. return;
  653. }
  654. GridRegion region = GetRegionByUUID(UUID.Zero, regionUuid);
  655. if (region == null)
  656. {
  657. MainConsole.Instance.OutputFormat("No region with UUID {0}", regionUuid);
  658. return;
  659. }
  660. if (DeregisterRegion(regionUuid))
  661. {
  662. MainConsole.Instance.OutputFormat("Deregistered {0} {1}", region.RegionName, regionUuid);
  663. }
  664. else
  665. {
  666. // I don't think this can ever occur if we know that the region exists.
  667. MainConsole.Instance.OutputFormat("Error deregistering {0} {1}", region.RegionName, regionUuid);
  668. }
  669. }
  670. }
  671. private void HandleShowRegions(string module, string[] cmd)
  672. {
  673. if (cmd.Length != 2)
  674. {
  675. MainConsole.Instance.Output("Syntax: show regions");
  676. return;
  677. }
  678. List<RegionData> regions = m_Database.Get(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, UUID.Zero);
  679. OutputRegionsToConsoleSummary(regions);
  680. }
  681. private void HandleShowGridSize(string module, string[] cmd)
  682. {
  683. List<RegionData> regions = m_Database.Get(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, UUID.Zero);
  684. double size = 0;
  685. foreach (RegionData region in regions)
  686. {
  687. int flags = Convert.ToInt32(region.Data["flags"]);
  688. if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0)
  689. size += region.sizeX * region.sizeY;
  690. }
  691. MainConsole.Instance.Output("This is a very rough approximation.");
  692. MainConsole.Instance.Output("Although it will not count regions that are actually links to others over the Hypergrid, ");
  693. MainConsole.Instance.Output("it will count regions that are inactive but were not deregistered from the grid service");
  694. MainConsole.Instance.Output("(e.g. simulator crashed rather than shutting down cleanly).\n");
  695. MainConsole.Instance.OutputFormat("Grid size: {0} km squared.", size / 1000000);
  696. }
  697. private void HandleShowRegion(string module, string[] cmd)
  698. {
  699. if (cmd.Length != 4)
  700. {
  701. MainConsole.Instance.Output("Syntax: show region name <region name>");
  702. return;
  703. }
  704. string regionName = cmd[3];
  705. List<RegionData> regions = m_Database.Get(Util.EscapeForLike(regionName), UUID.Zero);
  706. if (regions == null || regions.Count < 1)
  707. {
  708. MainConsole.Instance.Output("No region with name {0} found", regionName);
  709. return;
  710. }
  711. OutputRegionsToConsole(regions);
  712. }
  713. private void HandleShowRegionAt(string module, string[] cmd)
  714. {
  715. if (cmd.Length != 5)
  716. {
  717. MainConsole.Instance.Output("Syntax: show region at <x-coord> <y-coord>");
  718. return;
  719. }
  720. uint x, y;
  721. if (!uint.TryParse(cmd[3], out x))
  722. {
  723. MainConsole.Instance.Output("x-coord must be an integer");
  724. return;
  725. }
  726. if (!uint.TryParse(cmd[4], out y))
  727. {
  728. MainConsole.Instance.Output("y-coord must be an integer");
  729. return;
  730. }
  731. RegionData region = m_Database.Get((int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y), UUID.Zero);
  732. if (region == null)
  733. {
  734. MainConsole.Instance.OutputFormat("No region found at {0},{1}", x, y);
  735. return;
  736. }
  737. OutputRegionToConsole(region);
  738. }
  739. private void OutputRegionToConsole(RegionData r)
  740. {
  741. OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
  742. ConsoleDisplayList dispList = new ConsoleDisplayList();
  743. dispList.AddRow("Region Name", r.RegionName);
  744. dispList.AddRow("Region ID", r.RegionID);
  745. dispList.AddRow("Position", string.Format("{0},{1}", r.coordX, r.coordY));
  746. dispList.AddRow("Size", string.Format("{0}x{1}", r.sizeX, r.sizeY));
  747. dispList.AddRow("URI", r.Data["serverURI"]);
  748. dispList.AddRow("Owner ID", r.Data["owner_uuid"]);
  749. dispList.AddRow("Flags", flags);
  750. MainConsole.Instance.Output(dispList.ToString());
  751. }
  752. private void OutputRegionsToConsole(List<RegionData> regions)
  753. {
  754. foreach (RegionData r in regions)
  755. OutputRegionToConsole(r);
  756. }
  757. private void OutputRegionsToConsoleSummary(List<RegionData> regions)
  758. {
  759. ConsoleDisplayTable dispTable = new ConsoleDisplayTable();
  760. dispTable.AddColumn("Name", 44);
  761. dispTable.AddColumn("ID", 36);
  762. dispTable.AddColumn("Position", 11);
  763. dispTable.AddColumn("Size", 11);
  764. dispTable.AddColumn("Flags", 60);
  765. foreach (RegionData r in regions)
  766. {
  767. OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
  768. dispTable.AddRow(
  769. r.RegionName,
  770. r.RegionID.ToString(),
  771. string.Format("{0},{1}", r.coordX, r.coordY),
  772. string.Format("{0}x{1}", r.sizeX, r.sizeY),
  773. flags.ToString());
  774. }
  775. MainConsole.Instance.Output(dispTable.ToString());
  776. }
  777. private int ParseFlags(int prev, string flags)
  778. {
  779. OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)prev;
  780. string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
  781. foreach (string p in parts)
  782. {
  783. int val;
  784. try
  785. {
  786. if (p.StartsWith("+"))
  787. {
  788. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
  789. f |= (OpenSim.Framework.RegionFlags)val;
  790. }
  791. else if (p.StartsWith("-"))
  792. {
  793. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
  794. f &= ~(OpenSim.Framework.RegionFlags)val;
  795. }
  796. else
  797. {
  798. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p);
  799. f |= (OpenSim.Framework.RegionFlags)val;
  800. }
  801. }
  802. catch (Exception)
  803. {
  804. MainConsole.Instance.Output("Error in flag specification: " + p);
  805. }
  806. }
  807. return (int)f;
  808. }
  809. private void HandleSetFlags(string module, string[] cmd)
  810. {
  811. if (cmd.Length < 5)
  812. {
  813. MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>");
  814. return;
  815. }
  816. List<RegionData> regions = m_Database.Get(Util.EscapeForLike(cmd[3]), UUID.Zero);
  817. if (regions == null || regions.Count < 1)
  818. {
  819. MainConsole.Instance.Output("Region not found");
  820. return;
  821. }
  822. foreach (RegionData r in regions)
  823. {
  824. int flags = Convert.ToInt32(r.Data["flags"]);
  825. flags = ParseFlags(flags, cmd[4]);
  826. r.Data["flags"] = flags.ToString();
  827. OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)flags;
  828. MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f));
  829. m_Database.Store(r);
  830. }
  831. }
  832. /// <summary>
  833. /// Gets the grid extra service URls we wish for the region to send in OpenSimExtras to dynamically refresh
  834. /// parameters in the viewer used to access services like map, search and destination guides.
  835. /// <para>see "SimulatorFeaturesModule" </para>
  836. /// </summary>
  837. /// <returns>
  838. /// The grid extra service URls.
  839. /// </returns>
  840. public Dictionary<string,object> GetExtraFeatures()
  841. {
  842. return m_ExtraFeatures;
  843. }
  844. }
  845. }