GridService.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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. int snapX = (int)(x / Constants.RegionSize) * (int)Constants.RegionSize;
  464. int snapY = (int)(y / Constants.RegionSize) * (int)Constants.RegionSize;
  465. RegionData rdata = m_Database.Get(snapX, snapY, scopeID);
  466. if (rdata != null)
  467. return RegionData2RegionInfo(rdata);
  468. return null;
  469. }
  470. public GridRegion GetRegionByName(UUID scopeID, string name)
  471. {
  472. List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name), scopeID);
  473. if ((rdatas != null) && (rdatas.Count > 0))
  474. return RegionData2RegionInfo(rdatas[0]); // get the first
  475. if (m_AllowHypergridMapSearch)
  476. {
  477. GridRegion r = GetHypergridRegionByName(scopeID, name);
  478. if (r != null)
  479. return r;
  480. }
  481. return null;
  482. }
  483. public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
  484. {
  485. // m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name);
  486. List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name) + "%", scopeID);
  487. int count = 0;
  488. List<GridRegion> rinfos = new List<GridRegion>();
  489. if (rdatas != null)
  490. {
  491. // m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
  492. foreach (RegionData rdata in rdatas)
  493. {
  494. if (count++ < maxNumber)
  495. rinfos.Add(RegionData2RegionInfo(rdata));
  496. }
  497. }
  498. if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0)))
  499. {
  500. GridRegion r = GetHypergridRegionByName(scopeID, name);
  501. if (r != null)
  502. rinfos.Add(r);
  503. }
  504. return rinfos;
  505. }
  506. /// <summary>
  507. /// Get a hypergrid region.
  508. /// </summary>
  509. /// <param name="scopeID"></param>
  510. /// <param name="name"></param>
  511. /// <returns>null if no hypergrid region could be found.</returns>
  512. protected GridRegion GetHypergridRegionByName(UUID scopeID, string name)
  513. {
  514. if (name.Contains("."))
  515. return m_HypergridLinker.LinkRegion(scopeID, name);
  516. else
  517. return null;
  518. }
  519. public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
  520. {
  521. int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
  522. int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
  523. int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
  524. int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
  525. List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);
  526. List<GridRegion> rinfos = new List<GridRegion>();
  527. foreach (RegionData rdata in rdatas)
  528. rinfos.Add(RegionData2RegionInfo(rdata));
  529. return rinfos;
  530. }
  531. #endregion
  532. #region Data structure conversions
  533. public RegionData RegionInfo2RegionData(GridRegion rinfo)
  534. {
  535. RegionData rdata = new RegionData();
  536. rdata.posX = (int)rinfo.RegionLocX;
  537. rdata.posY = (int)rinfo.RegionLocY;
  538. rdata.sizeX = rinfo.RegionSizeX;
  539. rdata.sizeY = rinfo.RegionSizeY;
  540. rdata.RegionID = rinfo.RegionID;
  541. rdata.RegionName = rinfo.RegionName;
  542. rdata.Data = rinfo.ToKeyValuePairs();
  543. rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);
  544. rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString();
  545. return rdata;
  546. }
  547. public GridRegion RegionData2RegionInfo(RegionData rdata)
  548. {
  549. GridRegion rinfo = new GridRegion(rdata.Data);
  550. rinfo.RegionLocX = rdata.posX;
  551. rinfo.RegionLocY = rdata.posY;
  552. rinfo.RegionSizeX = rdata.sizeX;
  553. rinfo.RegionSizeY = rdata.sizeY;
  554. rinfo.RegionID = rdata.RegionID;
  555. rinfo.RegionName = rdata.RegionName;
  556. rinfo.ScopeID = rdata.ScopeID;
  557. return rinfo;
  558. }
  559. #endregion
  560. public List<GridRegion> GetDefaultRegions(UUID scopeID)
  561. {
  562. List<GridRegion> ret = new List<GridRegion>();
  563. List<RegionData> regions = m_Database.GetDefaultRegions(scopeID);
  564. foreach (RegionData r in regions)
  565. {
  566. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  567. ret.Add(RegionData2RegionInfo(r));
  568. }
  569. m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count);
  570. return ret;
  571. }
  572. public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
  573. {
  574. List<GridRegion> ret = new List<GridRegion>();
  575. List<RegionData> regions = m_Database.GetDefaultHypergridRegions(scopeID);
  576. foreach (RegionData r in regions)
  577. {
  578. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  579. ret.Add(RegionData2RegionInfo(r));
  580. }
  581. int hgDefaultRegionsFoundOnline = regions.Count;
  582. // For now, hypergrid default regions will always be given precedence but we will also return simple default
  583. // regions in case no specific hypergrid regions are specified.
  584. ret.AddRange(GetDefaultRegions(scopeID));
  585. int normalDefaultRegionsFoundOnline = ret.Count - hgDefaultRegionsFoundOnline;
  586. m_log.DebugFormat(
  587. "[GRID SERVICE]: GetDefaultHypergridRegions returning {0} hypergrid default and {1} normal default regions",
  588. hgDefaultRegionsFoundOnline, normalDefaultRegionsFoundOnline);
  589. return ret;
  590. }
  591. public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
  592. {
  593. List<GridRegion> ret = new List<GridRegion>();
  594. List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y);
  595. foreach (RegionData r in regions)
  596. {
  597. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  598. ret.Add(RegionData2RegionInfo(r));
  599. }
  600. m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count);
  601. return ret;
  602. }
  603. public List<GridRegion> GetHyperlinks(UUID scopeID)
  604. {
  605. List<GridRegion> ret = new List<GridRegion>();
  606. List<RegionData> regions = m_Database.GetHyperlinks(scopeID);
  607. foreach (RegionData r in regions)
  608. {
  609. if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
  610. ret.Add(RegionData2RegionInfo(r));
  611. }
  612. m_log.DebugFormat("[GRID SERVICE]: Hyperlinks returned {0} regions", ret.Count);
  613. return ret;
  614. }
  615. public int GetRegionFlags(UUID scopeID, UUID regionID)
  616. {
  617. RegionData region = m_Database.Get(regionID, scopeID);
  618. if (region != null)
  619. {
  620. int flags = Convert.ToInt32(region.Data["flags"]);
  621. //m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags);
  622. return flags;
  623. }
  624. else
  625. return -1;
  626. }
  627. private void HandleDeregisterRegion(string module, string[] cmd)
  628. {
  629. if (cmd.Length < 4)
  630. {
  631. MainConsole.Instance.Output("Usage: degregister region id <region-id>+");
  632. return;
  633. }
  634. for (int i = 3; i < cmd.Length; i++)
  635. {
  636. string rawRegionUuid = cmd[i];
  637. UUID regionUuid;
  638. if (!UUID.TryParse(rawRegionUuid, out regionUuid))
  639. {
  640. MainConsole.Instance.OutputFormat("{0} is not a valid region uuid", rawRegionUuid);
  641. return;
  642. }
  643. GridRegion region = GetRegionByUUID(UUID.Zero, regionUuid);
  644. if (region == null)
  645. {
  646. MainConsole.Instance.OutputFormat("No region with UUID {0}", regionUuid);
  647. return;
  648. }
  649. if (DeregisterRegion(regionUuid))
  650. {
  651. MainConsole.Instance.OutputFormat("Deregistered {0} {1}", region.RegionName, regionUuid);
  652. }
  653. else
  654. {
  655. // I don't think this can ever occur if we know that the region exists.
  656. MainConsole.Instance.OutputFormat("Error deregistering {0} {1}", region.RegionName, regionUuid);
  657. }
  658. }
  659. }
  660. private void HandleShowRegions(string module, string[] cmd)
  661. {
  662. if (cmd.Length != 2)
  663. {
  664. MainConsole.Instance.Output("Syntax: show regions");
  665. return;
  666. }
  667. List<RegionData> regions = m_Database.Get(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, UUID.Zero);
  668. OutputRegionsToConsoleSummary(regions);
  669. }
  670. private void HandleShowGridSize(string module, string[] cmd)
  671. {
  672. List<RegionData> regions = m_Database.Get(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, UUID.Zero);
  673. double size = 0;
  674. foreach (RegionData region in regions)
  675. {
  676. int flags = Convert.ToInt32(region.Data["flags"]);
  677. if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0)
  678. size += region.sizeX * region.sizeY;
  679. }
  680. MainConsole.Instance.Output("This is a very rough approximation.");
  681. MainConsole.Instance.Output("Although it will not count regions that are actually links to others over the Hypergrid, ");
  682. MainConsole.Instance.Output("it will count regions that are inactive but were not deregistered from the grid service");
  683. MainConsole.Instance.Output("(e.g. simulator crashed rather than shutting down cleanly).\n");
  684. MainConsole.Instance.OutputFormat("Grid size: {0} km squared.", size / 1000000);
  685. }
  686. private void HandleShowRegion(string module, string[] cmd)
  687. {
  688. if (cmd.Length != 4)
  689. {
  690. MainConsole.Instance.Output("Syntax: show region name <region name>");
  691. return;
  692. }
  693. string regionName = cmd[3];
  694. List<RegionData> regions = m_Database.Get(Util.EscapeForLike(regionName), UUID.Zero);
  695. if (regions == null || regions.Count < 1)
  696. {
  697. MainConsole.Instance.Output("No region with name {0} found", regionName);
  698. return;
  699. }
  700. OutputRegionsToConsole(regions);
  701. }
  702. private void HandleShowRegionAt(string module, string[] cmd)
  703. {
  704. if (cmd.Length != 5)
  705. {
  706. MainConsole.Instance.Output("Syntax: show region at <x-coord> <y-coord>");
  707. return;
  708. }
  709. uint x, y;
  710. if (!uint.TryParse(cmd[3], out x))
  711. {
  712. MainConsole.Instance.Output("x-coord must be an integer");
  713. return;
  714. }
  715. if (!uint.TryParse(cmd[4], out y))
  716. {
  717. MainConsole.Instance.Output("y-coord must be an integer");
  718. return;
  719. }
  720. RegionData region = m_Database.Get((int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y), UUID.Zero);
  721. if (region == null)
  722. {
  723. MainConsole.Instance.OutputFormat("No region found at {0},{1}", x, y);
  724. return;
  725. }
  726. OutputRegionToConsole(region);
  727. }
  728. private void OutputRegionToConsole(RegionData r)
  729. {
  730. OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
  731. ConsoleDisplayList dispList = new ConsoleDisplayList();
  732. dispList.AddRow("Region Name", r.RegionName);
  733. dispList.AddRow("Region ID", r.RegionID);
  734. dispList.AddRow("Position", string.Format("{0},{1}", r.coordX, r.coordY));
  735. dispList.AddRow("Size", string.Format("{0}x{1}", r.sizeX, r.sizeY));
  736. dispList.AddRow("URI", r.Data["serverURI"]);
  737. dispList.AddRow("Owner ID", r.Data["owner_uuid"]);
  738. dispList.AddRow("Flags", flags);
  739. MainConsole.Instance.Output(dispList.ToString());
  740. }
  741. private void OutputRegionsToConsole(List<RegionData> regions)
  742. {
  743. foreach (RegionData r in regions)
  744. OutputRegionToConsole(r);
  745. }
  746. private void OutputRegionsToConsoleSummary(List<RegionData> regions)
  747. {
  748. ConsoleDisplayTable dispTable = new ConsoleDisplayTable();
  749. dispTable.AddColumn("Name", 44);
  750. dispTable.AddColumn("ID", 36);
  751. dispTable.AddColumn("Position", 11);
  752. dispTable.AddColumn("Size", 11);
  753. dispTable.AddColumn("Flags", 60);
  754. foreach (RegionData r in regions)
  755. {
  756. OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
  757. dispTable.AddRow(
  758. r.RegionName,
  759. r.RegionID.ToString(),
  760. string.Format("{0},{1}", r.coordX, r.coordY),
  761. string.Format("{0}x{1}", r.sizeX, r.sizeY),
  762. flags.ToString());
  763. }
  764. MainConsole.Instance.Output(dispTable.ToString());
  765. }
  766. private int ParseFlags(int prev, string flags)
  767. {
  768. OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)prev;
  769. string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
  770. foreach (string p in parts)
  771. {
  772. int val;
  773. try
  774. {
  775. if (p.StartsWith("+"))
  776. {
  777. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
  778. f |= (OpenSim.Framework.RegionFlags)val;
  779. }
  780. else if (p.StartsWith("-"))
  781. {
  782. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
  783. f &= ~(OpenSim.Framework.RegionFlags)val;
  784. }
  785. else
  786. {
  787. val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p);
  788. f |= (OpenSim.Framework.RegionFlags)val;
  789. }
  790. }
  791. catch (Exception)
  792. {
  793. MainConsole.Instance.Output("Error in flag specification: " + p);
  794. }
  795. }
  796. return (int)f;
  797. }
  798. private void HandleSetFlags(string module, string[] cmd)
  799. {
  800. if (cmd.Length < 5)
  801. {
  802. MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>");
  803. return;
  804. }
  805. List<RegionData> regions = m_Database.Get(Util.EscapeForLike(cmd[3]), UUID.Zero);
  806. if (regions == null || regions.Count < 1)
  807. {
  808. MainConsole.Instance.Output("Region not found");
  809. return;
  810. }
  811. foreach (RegionData r in regions)
  812. {
  813. int flags = Convert.ToInt32(r.Data["flags"]);
  814. flags = ParseFlags(flags, cmd[4]);
  815. r.Data["flags"] = flags.ToString();
  816. OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)flags;
  817. MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f));
  818. m_Database.Store(r);
  819. }
  820. }
  821. /// <summary>
  822. /// Gets the grid extra service URls we wish for the region to send in OpenSimExtras to dynamically refresh
  823. /// parameters in the viewer used to access services like map, search and destination guides.
  824. /// <para>see "SimulatorFeaturesModule" </para>
  825. /// </summary>
  826. /// <returns>
  827. /// The grid extra service URls.
  828. /// </returns>
  829. public Dictionary<string,object> GetExtraFeatures()
  830. {
  831. return m_ExtraFeatures;
  832. }
  833. }
  834. }