clockwerk-opensim – Blame information for rev 1

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