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