ArchiveWriteRequest.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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.IO;
  30. using System.IO.Compression;
  31. using System.Reflection;
  32. using System.Runtime;
  33. using System.Text.RegularExpressions;
  34. using System.Threading;
  35. using System.Xml;
  36. using log4net;
  37. using OpenMetaverse;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Monitoring;
  40. using OpenSim.Framework.Serialization;
  41. using OpenSim.Region.CoreModules.World.Terrain;
  42. using OpenSim.Region.Framework.Interfaces;
  43. using OpenSim.Region.Framework.Scenes;
  44. using Ionic.Zlib;
  45. using GZipStream = Ionic.Zlib.GZipStream;
  46. using CompressionMode = Ionic.Zlib.CompressionMode;
  47. using CompressionLevel = Ionic.Zlib.CompressionLevel;
  48. using OpenSim.Framework.Serialization.External;
  49. using PermissionMask = OpenSim.Framework.PermissionMask;
  50. namespace OpenSim.Region.CoreModules.World.Archiver
  51. {
  52. /// <summary>
  53. /// Prepare to write out an archive.
  54. /// </summary>
  55. public class ArchiveWriteRequest
  56. {
  57. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  58. /// <summary>
  59. /// The minimum major version of OAR that we can write.
  60. /// </summary>
  61. public static int MIN_MAJOR_VERSION = 0;
  62. /// <summary>
  63. /// The maximum major version of OAR that we can write.
  64. /// </summary>
  65. public static int MAX_MAJOR_VERSION = 1;
  66. /// <summary>
  67. /// Whether we're saving a multi-region archive.
  68. /// </summary>
  69. public bool MultiRegionFormat { get; set; }
  70. /// <summary>
  71. /// Determine whether this archive will save assets. Default is true.
  72. /// </summary>
  73. public bool SaveAssets { get; set; }
  74. /// <summary>
  75. /// Determines which objects will be included in the archive, according to their permissions.
  76. /// Default is null, meaning no permission checks.
  77. /// </summary>
  78. public string FilterContent { get; set; }
  79. protected Scene m_rootScene;
  80. protected Stream m_saveStream;
  81. protected TarArchiveWriter m_archiveWriter;
  82. protected Guid m_requestId;
  83. protected Dictionary<string, object> m_options;
  84. /// <summary>
  85. /// Constructor
  86. /// </summary>
  87. /// <param name="module">Calling module</param>
  88. /// <param name="savePath">The path to which to save data.</param>
  89. /// <param name="requestId">The id associated with this request</param>
  90. /// <exception cref="System.IO.IOException">
  91. /// If there was a problem opening a stream for the file specified by the savePath
  92. /// </exception>
  93. public ArchiveWriteRequest(Scene scene, string savePath, Guid requestId) : this(scene, requestId)
  94. {
  95. try
  96. {
  97. m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression);
  98. }
  99. catch (EntryPointNotFoundException e)
  100. {
  101. m_log.ErrorFormat(
  102. "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
  103. + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
  104. m_log.ErrorFormat("{0} {1}", e.Message, e.StackTrace);
  105. }
  106. }
  107. /// <summary>
  108. /// Constructor.
  109. /// </summary>
  110. /// <param name="scene">The root scene to archive</param>
  111. /// <param name="saveStream">The stream to which to save data.</param>
  112. /// <param name="requestId">The id associated with this request</param>
  113. public ArchiveWriteRequest(Scene scene, Stream saveStream, Guid requestId) : this(scene, requestId)
  114. {
  115. m_saveStream = saveStream;
  116. }
  117. protected ArchiveWriteRequest(Scene scene, Guid requestId)
  118. {
  119. m_rootScene = scene;
  120. m_requestId = requestId;
  121. m_archiveWriter = null;
  122. MultiRegionFormat = false;
  123. SaveAssets = true;
  124. FilterContent = null;
  125. }
  126. /// <summary>
  127. /// Archive the region requested.
  128. /// </summary>
  129. /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception>
  130. public void ArchiveRegion(Dictionary<string, object> options)
  131. {
  132. m_options = options;
  133. if (options.ContainsKey("all") && (bool)options["all"])
  134. MultiRegionFormat = true;
  135. if (options.ContainsKey("noassets") && (bool)options["noassets"])
  136. SaveAssets = false;
  137. if (options.TryGetValue("checkPermissions", out Object temp))
  138. FilterContent = (string)temp;
  139. // Find the regions to archive
  140. ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup();
  141. if (MultiRegionFormat)
  142. {
  143. m_log.InfoFormat("[ARCHIVER]: Saving {0} regions", SceneManager.Instance.Scenes.Count);
  144. SceneManager.Instance.ForEachScene(delegate(Scene scene)
  145. {
  146. scenesGroup.AddScene(scene);
  147. });
  148. }
  149. else
  150. {
  151. scenesGroup.AddScene(m_rootScene);
  152. }
  153. scenesGroup.CalcSceneLocations();
  154. m_archiveWriter = new TarArchiveWriter(m_saveStream);
  155. try
  156. {
  157. // Write out control file. It should be first so that it will be found ASAP when loading the file.
  158. m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(scenesGroup));
  159. m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");
  160. // Archive the regions
  161. Dictionary<UUID, sbyte> assetUuids = new Dictionary<UUID, sbyte>();
  162. HashSet<UUID> failedIDs = new HashSet<UUID>();
  163. HashSet<UUID> uncertainAssetsUUIDs = new HashSet<UUID>();
  164. scenesGroup.ForEachScene(delegate(Scene scene)
  165. {
  166. string regionDir = MultiRegionFormat ? scenesGroup.GetRegionDir(scene.RegionInfo.RegionID) : "";
  167. ArchiveOneRegion(scene, regionDir, assetUuids, failedIDs, uncertainAssetsUUIDs);
  168. });
  169. // Archive the assets
  170. if (SaveAssets)
  171. {
  172. m_log.DebugFormat("[ARCHIVER]: Saving {0} assets", assetUuids.Count);
  173. AssetsRequest ar = new AssetsRequest(
  174. new AssetsArchiver(m_archiveWriter), assetUuids,
  175. failedIDs.Count,
  176. m_rootScene.AssetService, m_rootScene.UserAccountService,
  177. m_rootScene.RegionInfo.ScopeID, options, null);
  178. ar.Execute();
  179. assetUuids = null;
  180. }
  181. else
  182. {
  183. m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified");
  184. // CloseArchive(string.Empty);
  185. }
  186. CloseArchive(string.Empty);
  187. }
  188. catch (Exception e)
  189. {
  190. CloseArchive(e.Message);
  191. throw;
  192. }
  193. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  194. GC.Collect();
  195. GC.WaitForPendingFinalizers();
  196. GC.Collect();
  197. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
  198. }
  199. private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary<UUID, sbyte> assetUuids,
  200. HashSet<UUID> failedIDs, HashSet<UUID> uncertainAssetsUUIDs)
  201. {
  202. m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.Name);
  203. EntityBase[] entities = scene.GetEntities();
  204. List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
  205. int numObjectsSkippedPermissions = 0;
  206. // Filter entities so that we only have scene objects.
  207. // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods
  208. // end up having to do this
  209. IPermissionsModule permissionsModule = scene.RequestModuleInterface<IPermissionsModule>();
  210. foreach (EntityBase entity in entities)
  211. {
  212. if (entity is SceneObjectGroup)
  213. {
  214. SceneObjectGroup sceneObject = entity as SceneObjectGroup;
  215. if (!sceneObject.IsDeleted && !sceneObject.IsAttachment && !sceneObject.IsTemporary && !sceneObject.inTransit)
  216. {
  217. if (!CanUserArchiveObject(scene.RegionInfo.EstateSettings.EstateOwner, sceneObject, FilterContent, permissionsModule))
  218. {
  219. // The user isn't allowed to copy/transfer this object, so it will not be included in the OAR.
  220. ++numObjectsSkippedPermissions;
  221. }
  222. else
  223. {
  224. sceneObjects.Add(sceneObject);
  225. }
  226. }
  227. }
  228. }
  229. if (SaveAssets)
  230. {
  231. UuidGatherer assetGatherer = new UuidGatherer(scene.AssetService, assetUuids, failedIDs, uncertainAssetsUUIDs);
  232. int prevAssets = assetUuids.Count;
  233. foreach (SceneObjectGroup sceneObject in sceneObjects)
  234. {
  235. int curErrorCntr = assetGatherer.ErrorCount;
  236. int possible = assetGatherer.possibleNotAssetCount;
  237. assetGatherer.AddForInspection(sceneObject);
  238. assetGatherer.GatherAll();
  239. curErrorCntr = assetGatherer.ErrorCount - curErrorCntr;
  240. possible = assetGatherer.possibleNotAssetCount - possible;
  241. if(curErrorCntr > 0)
  242. {
  243. m_log.ErrorFormat("[ARCHIVER]: object {0} '{1}', at {2}, contains {3} references to missing or damaged assets",
  244. sceneObject.UUID, sceneObject.Name ,sceneObject.AbsolutePosition.ToString(), curErrorCntr);
  245. if(possible > 0)
  246. m_log.WarnFormat("[ARCHIVER Warning]: object also contains {0} references that may not be assets or are missing", possible);
  247. }
  248. else if(possible > 0)
  249. {
  250. m_log.WarnFormat("[ARCHIVER Warning]: object {0} '{1}', at {2}, contains {3} references that may not be assets or are missing",
  251. sceneObject.UUID, sceneObject.Name ,sceneObject.AbsolutePosition.ToString(), possible);
  252. }
  253. }
  254. assetGatherer.GatherAll();
  255. GC.Collect();
  256. int errors = assetGatherer.FailedUUIDs.Count;
  257. m_log.DebugFormat(
  258. "[ARCHIVER]: {0} region scene objects to save reference {1} possible assets",
  259. sceneObjects.Count, assetUuids.Count - prevAssets + errors);
  260. if(errors > 0)
  261. m_log.DebugFormat("[ARCHIVER]: {0} of these have problems or are not assets and will be ignored", errors);
  262. }
  263. if (numObjectsSkippedPermissions > 0)
  264. {
  265. m_log.DebugFormat(
  266. "[ARCHIVER]: {0} scene objects skipped due to lack of permissions",
  267. numObjectsSkippedPermissions);
  268. }
  269. // Make sure that we also request terrain texture assets
  270. RegionSettings regionSettings = scene.RegionInfo.RegionSettings;
  271. if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
  272. assetUuids[regionSettings.TerrainTexture1] = (sbyte)AssetType.Texture;
  273. if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
  274. assetUuids[regionSettings.TerrainTexture2] = (sbyte)AssetType.Texture;
  275. if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
  276. assetUuids[regionSettings.TerrainTexture3] = (sbyte)AssetType.Texture;
  277. if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
  278. assetUuids[regionSettings.TerrainTexture4] = (sbyte)AssetType.Texture;
  279. if (regionSettings.TerrainPBR1 != RegionSettings.DEFAULT_TERRAIN_PBR_1)
  280. assetUuids[regionSettings.TerrainPBR1] = (sbyte)AssetType.Texture; // it can be both tex or material
  281. if (regionSettings.TerrainPBR2 != RegionSettings.DEFAULT_TERRAIN_PBR_2)
  282. assetUuids[regionSettings.TerrainPBR2] = (sbyte)AssetType.Texture;
  283. if (regionSettings.TerrainPBR3 != RegionSettings.DEFAULT_TERRAIN_PBR_3)
  284. assetUuids[regionSettings.TerrainPBR3] = (sbyte)AssetType.Texture;
  285. if (regionSettings.TerrainPBR4 != RegionSettings.DEFAULT_TERRAIN_PBR_4)
  286. assetUuids[regionSettings.TerrainPBR4] = (sbyte)AssetType.Texture;
  287. if (scene.RegionEnvironment != null)
  288. scene.RegionEnvironment.GatherAssets(assetUuids);
  289. List<ILandObject> landObjects = scene.LandChannel.AllParcels();
  290. foreach (ILandObject lo in landObjects)
  291. {
  292. if(lo.LandData != null && lo.LandData.Environment != null)
  293. lo.LandData.Environment.GatherAssets(assetUuids);
  294. }
  295. Save(scene, sceneObjects, regionDir);
  296. GC.Collect();
  297. }
  298. /// <summary>
  299. /// Checks whether the user has permission to export an object group to an OAR.
  300. /// </summary>
  301. /// <param name="user">The user</param>
  302. /// <param name="objGroup">The object group</param>
  303. /// <param name="filterContent">Which permissions to check: "C" = Copy, "T" = Transfer</param>
  304. /// <param name="permissionsModule">The scene's permissions module</param>
  305. /// <returns>Whether the user is allowed to export the object to an OAR</returns>
  306. private bool CanUserArchiveObject(UUID user, SceneObjectGroup objGroup, string filterContent, IPermissionsModule permissionsModule)
  307. {
  308. if (filterContent == null)
  309. return true;
  310. if (permissionsModule == null)
  311. return true; // this shouldn't happen
  312. // Check whether the user is permitted to export all of the parts in the SOG. If any
  313. // part can't be exported then the entire SOG can't be exported.
  314. bool permitted = true;
  315. //int primNumber = 1;
  316. foreach (SceneObjectPart obj in objGroup.Parts)
  317. {
  318. uint perm;
  319. PermissionClass permissionClass = permissionsModule.GetPermissionClass(user, obj);
  320. switch (permissionClass)
  321. {
  322. case PermissionClass.Owner:
  323. perm = obj.BaseMask;
  324. break;
  325. case PermissionClass.Group:
  326. perm = obj.GroupMask | obj.EveryoneMask;
  327. break;
  328. case PermissionClass.Everyone:
  329. default:
  330. perm = obj.EveryoneMask;
  331. break;
  332. }
  333. bool canCopy = (perm & (uint)PermissionMask.Copy) != 0;
  334. bool canTransfer = (perm & (uint)PermissionMask.Transfer) != 0;
  335. // Special case: if Everyone can copy the object then this implies it can also be
  336. // Transferred.
  337. // However, if the user is the Owner then we don't check EveryoneMask, because it seems that the mask
  338. // always (incorrectly) includes the Copy bit set in this case. But that's a mistake: the viewer
  339. // does NOT show that the object has Everyone-Copy permissions, and doesn't allow it to be copied.
  340. if (permissionClass != PermissionClass.Owner)
  341. canTransfer |= (obj.EveryoneMask & (uint)PermissionMask.Copy) != 0;
  342. bool partPermitted = true;
  343. if (filterContent.Contains("C") && !canCopy)
  344. partPermitted = false;
  345. if (filterContent.Contains("T") && !canTransfer)
  346. partPermitted = false;
  347. // If the user is the Creator of the object then it can always be included in the OAR
  348. bool creator = (obj.CreatorID.Guid == user.Guid);
  349. if (creator)
  350. partPermitted = true;
  351. //string name = (objGroup.PrimCount == 1) ? objGroup.Name : string.Format("{0} ({1}/{2})", obj.Name, primNumber, objGroup.PrimCount);
  352. //m_log.DebugFormat("[ARCHIVER]: Object permissions: {0}: Base={1:X4}, Owner={2:X4}, Everyone={3:X4}, permissionClass={4}, checkPermissions={5}, canCopy={6}, canTransfer={7}, creator={8}, permitted={9}",
  353. // name, obj.BaseMask, obj.OwnerMask, obj.EveryoneMask,
  354. // permissionClass, checkPermissions, canCopy, canTransfer, creator, partPermitted);
  355. if (!partPermitted)
  356. {
  357. permitted = false;
  358. break;
  359. }
  360. //++primNumber;
  361. }
  362. return permitted;
  363. }
  364. /// <summary>
  365. /// Create the control file.
  366. /// </summary>
  367. /// <returns></returns>
  368. public string CreateControlFile(ArchiveScenesGroup scenesGroup)
  369. {
  370. int majorVersion;
  371. int minorVersion;
  372. if (MultiRegionFormat)
  373. {
  374. majorVersion = MAX_MAJOR_VERSION;
  375. minorVersion = 0;
  376. }
  377. else
  378. {
  379. // To support older versions of OpenSim, we continue to create single-region OARs
  380. // using the old file format. In the future this format will be discontinued.
  381. majorVersion = 0;
  382. minorVersion = 8;
  383. }
  384. //
  385. // if (m_options.ContainsKey("version"))
  386. // {
  387. // string[] parts = m_options["version"].ToString().Split('.');
  388. // if (parts.Length >= 1)
  389. // {
  390. // majorVersion = Int32.Parse(parts[0]);
  391. //
  392. // if (parts.Length >= 2)
  393. // minorVersion = Int32.Parse(parts[1]);
  394. // }
  395. // }
  396. //
  397. // if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION)
  398. // {
  399. // throw new Exception(
  400. // string.Format(
  401. // "OAR version number for save must be between {0} and {1}",
  402. // MIN_MAJOR_VERSION, MAX_MAJOR_VERSION));
  403. // }
  404. // else if (majorVersion == MAX_MAJOR_VERSION)
  405. // {
  406. // // Force 1.0
  407. // minorVersion = 0;
  408. // }
  409. // else if (majorVersion == MIN_MAJOR_VERSION)
  410. // {
  411. // // Force 0.4
  412. // minorVersion = 4;
  413. // }
  414. m_log.InfoFormat("[ARCHIVER]: Creating version {0}.{1} OAR", majorVersion, minorVersion);
  415. if (majorVersion == 1)
  416. {
  417. m_log.WarnFormat("[ARCHIVER]: Please be aware that version 1.0 OARs are not compatible with OpenSim versions prior to 0.7.4. Do not use the --all option if you want to produce a compatible OAR");
  418. }
  419. String s;
  420. using (StringWriter sw = new StringWriter())
  421. {
  422. using (XmlTextWriter xtw = new XmlTextWriter(sw))
  423. {
  424. xtw.Formatting = Formatting.Indented;
  425. xtw.WriteStartDocument();
  426. xtw.WriteStartElement("archive");
  427. xtw.WriteAttributeString("major_version", majorVersion.ToString());
  428. xtw.WriteAttributeString("minor_version", minorVersion.ToString());
  429. xtw.WriteStartElement("creation_info");
  430. DateTime now = DateTime.UtcNow;
  431. TimeSpan t = now - new DateTime(1970, 1, 1);
  432. xtw.WriteElementString("datetime", ((int)t.TotalSeconds).ToString());
  433. if (!MultiRegionFormat)
  434. xtw.WriteElementString("id", m_rootScene.RegionInfo.RegionID.ToString());
  435. xtw.WriteEndElement();
  436. xtw.WriteElementString("assets_included", SaveAssets.ToString());
  437. if (MultiRegionFormat)
  438. {
  439. WriteRegionsManifest(scenesGroup, xtw);
  440. }
  441. else
  442. {
  443. xtw.WriteStartElement("region_info");
  444. WriteRegionInfo(m_rootScene, xtw);
  445. xtw.WriteEndElement();
  446. }
  447. xtw.WriteEndElement();
  448. xtw.Flush();
  449. }
  450. s = sw.ToString();
  451. }
  452. return s;
  453. }
  454. /// <summary>
  455. /// Writes the list of regions included in a multi-region OAR.
  456. /// </summary>
  457. private static void WriteRegionsManifest(ArchiveScenesGroup scenesGroup, XmlTextWriter xtw)
  458. {
  459. xtw.WriteStartElement("regions");
  460. // Write the regions in order: rows from South to North, then regions from West to East.
  461. // The list of regions can have "holes"; we write empty elements in their position.
  462. for (uint y = (uint)scenesGroup.Rect.Top; y < scenesGroup.Rect.Bottom; ++y)
  463. {
  464. if (scenesGroup.Regions.TryGetValue(y, out SortedDictionary<uint, Scene> row))
  465. {
  466. xtw.WriteStartElement("row");
  467. for (uint x = (uint)scenesGroup.Rect.Left; x < scenesGroup.Rect.Right; ++x)
  468. {
  469. if (row.TryGetValue(x, out Scene scene))
  470. {
  471. xtw.WriteStartElement("region");
  472. xtw.WriteElementString("id", scene.RegionInfo.RegionID.ToString());
  473. xtw.WriteElementString("dir", scenesGroup.GetRegionDir(scene.RegionInfo.RegionID));
  474. WriteRegionInfo(scene, xtw);
  475. xtw.WriteEndElement();
  476. }
  477. else
  478. {
  479. // Write a placeholder for a missing region
  480. xtw.WriteElementString("region", "");
  481. }
  482. }
  483. xtw.WriteEndElement();
  484. }
  485. else
  486. {
  487. // Write a placeholder for a missing row
  488. xtw.WriteElementString("row", "");
  489. }
  490. }
  491. xtw.WriteEndElement(); // "regions"
  492. }
  493. protected static void WriteRegionInfo(Scene scene, XmlTextWriter xtw)
  494. {
  495. Vector2 size;
  496. size = new Vector2((float)scene.RegionInfo.RegionSizeX, (float)scene.RegionInfo.RegionSizeY);
  497. xtw.WriteElementString("size_in_meters", string.Format("{0},{1}", size.X, size.Y));
  498. }
  499. protected void Save(Scene scene, List<SceneObjectGroup> sceneObjects, string regionDir)
  500. {
  501. if (regionDir != string.Empty)
  502. regionDir = ArchiveConstants.REGIONS_PATH + regionDir + "/";
  503. m_log.InfoFormat("[ARCHIVER]: Adding region settings to archive.");
  504. // Write out region settings
  505. string settingsPath = String.Format("{0}{1}{2}.xml",
  506. regionDir, ArchiveConstants.SETTINGS_PATH, scene.RegionInfo.RegionName);
  507. m_archiveWriter.WriteFile(settingsPath, RegionSettingsSerializer.Serialize(scene.RegionInfo.RegionSettings, scene.RegionEnvironment, scene.RegionInfo.EstateSettings));
  508. m_log.InfoFormat("[ARCHIVER]: Adding parcel settings to archive.");
  509. // Write out land data (aka parcel) settings
  510. List<ILandObject> landObjects = scene.LandChannel.AllParcels();
  511. foreach (ILandObject lo in landObjects)
  512. {
  513. LandData landData = lo.LandData;
  514. string landDataPath
  515. = String.Format("{0}{1}", regionDir, ArchiveConstants.CreateOarLandDataPath(landData));
  516. m_archiveWriter.WriteFile(landDataPath, LandDataSerializer.Serialize(landData, m_options));
  517. }
  518. m_log.InfoFormat("[ARCHIVER]: Adding terrain information to archive.");
  519. // Write out terrain
  520. string terrainPath = String.Format("{0}{1}{2}.r32",
  521. regionDir, ArchiveConstants.TERRAINS_PATH, scene.RegionInfo.RegionName);
  522. using (MemoryStream ms = new MemoryStream())
  523. {
  524. scene.RequestModuleInterface<ITerrainModule>().SaveToStream(terrainPath, ms);
  525. m_archiveWriter.WriteFile(terrainPath, ms.ToArray());
  526. }
  527. m_log.InfoFormat("[ARCHIVER]: Adding scene objects to archive.");
  528. // Write out scene object metadata
  529. IRegionSerialiserModule serializer = scene.RequestModuleInterface<IRegionSerialiserModule>();
  530. foreach (SceneObjectGroup sceneObject in sceneObjects)
  531. {
  532. //m_log.DebugFormat("[ARCHIVER]: Saving {0} {1}, {2}", entity.Name, entity.UUID, entity.GetType());
  533. if(sceneObject.IsDeleted || sceneObject.inTransit)
  534. continue;
  535. string serializedObject = serializer.SerializeGroupToXml2(sceneObject, m_options);
  536. string objectPath = string.Format("{0}{1}", regionDir, ArchiveHelpers.CreateObjectPath(sceneObject));
  537. m_archiveWriter.WriteFile(objectPath, serializedObject);
  538. }
  539. }
  540. protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut)
  541. {
  542. string errorMessage;
  543. if (timedOut)
  544. {
  545. errorMessage = "Loading assets timed out";
  546. }
  547. else
  548. {
  549. foreach (UUID uuid in assetsNotFoundUuids)
  550. {
  551. m_log.DebugFormat("[ARCHIVER]: Could not find asset {0}", uuid);
  552. }
  553. // m_log.InfoFormat(
  554. // "[ARCHIVER]: Received {0} of {1} assets requested",
  555. // assetsFoundUuids.Count, assetsFoundUuids.Count + assetsNotFoundUuids.Count);
  556. errorMessage = String.Empty;
  557. }
  558. CloseArchive(errorMessage);
  559. }
  560. /// <summary>
  561. /// Closes the archive and notifies that we're done.
  562. /// </summary>
  563. /// <param name="errorMessage">The error that occurred, or empty for success</param>
  564. protected void CloseArchive(string errorMessage)
  565. {
  566. try
  567. {
  568. if (m_archiveWriter != null)
  569. m_archiveWriter.Close();
  570. m_saveStream.Close();
  571. }
  572. catch (Exception e)
  573. {
  574. m_log.Error(string.Format("[ARCHIVER]: Error closing archive: {0} ", e.Message), e);
  575. if (errorMessage.Length == 0)
  576. errorMessage = e.Message;
  577. }
  578. m_log.InfoFormat("[ARCHIVER]: Finished writing out OAR for {0}", m_rootScene.RegionInfo.RegionName);
  579. m_rootScene.EventManager.TriggerOarFileSaved(m_requestId, errorMessage);
  580. }
  581. }
  582. }