GridService.cs 41 KB

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