ArchiveWriteRequest.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. Object temp;
  138. if (options.TryGetValue("checkPermissions", out temp))
  139. FilterContent = (string)temp;
  140. // Find the regions to archive
  141. ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup();
  142. if (MultiRegionFormat)
  143. {
  144. m_log.InfoFormat("[ARCHIVER]: Saving {0} regions", SceneManager.Instance.Scenes.Count);
  145. SceneManager.Instance.ForEachScene(delegate(Scene scene)
  146. {
  147. scenesGroup.AddScene(scene);
  148. });
  149. }
  150. else
  151. {
  152. scenesGroup.AddScene(m_rootScene);
  153. }
  154. scenesGroup.CalcSceneLocations();
  155. m_archiveWriter = new TarArchiveWriter(m_saveStream);
  156. try
  157. {
  158. // Write out control file. It should be first so that it will be found ASAP when loading the file.
  159. m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(scenesGroup));
  160. m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");
  161. // Archive the regions
  162. Dictionary<UUID, sbyte> assetUuids = new Dictionary<UUID, sbyte>();
  163. HashSet<UUID> failedIDs = new HashSet<UUID>();
  164. HashSet<UUID> uncertainAssetsUUIDs = new HashSet<UUID>();
  165. scenesGroup.ForEachScene(delegate(Scene scene)
  166. {
  167. string regionDir = MultiRegionFormat ? scenesGroup.GetRegionDir(scene.RegionInfo.RegionID) : "";
  168. ArchiveOneRegion(scene, regionDir, assetUuids, failedIDs, uncertainAssetsUUIDs);
  169. });
  170. // Archive the assets
  171. if (SaveAssets)
  172. {
  173. m_log.DebugFormat("[ARCHIVER]: Saving {0} assets", assetUuids.Count);
  174. AssetsRequest ar = new AssetsRequest(
  175. new AssetsArchiver(m_archiveWriter), assetUuids,
  176. failedIDs.Count,
  177. m_rootScene.AssetService, m_rootScene.UserAccountService,
  178. m_rootScene.RegionInfo.ScopeID, options, null);
  179. ar.Execute();
  180. assetUuids = null;
  181. }
  182. else
  183. {
  184. m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified");
  185. // CloseArchive(string.Empty);
  186. }
  187. CloseArchive(string.Empty);
  188. }
  189. catch (Exception e)
  190. {
  191. CloseArchive(e.Message);
  192. throw;
  193. }
  194. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  195. GC.Collect();
  196. GC.WaitForPendingFinalizers();
  197. GC.Collect();
  198. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
  199. }
  200. private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary<UUID, sbyte> assetUuids,
  201. HashSet<UUID> failedIDs, HashSet<UUID> uncertainAssetsUUIDs)
  202. {
  203. m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.Name);
  204. EntityBase[] entities = scene.GetEntities();
  205. List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
  206. int numObjectsSkippedPermissions = 0;
  207. // Filter entities so that we only have scene objects.
  208. // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods
  209. // end up having to do this
  210. IPermissionsModule permissionsModule = scene.RequestModuleInterface<IPermissionsModule>();
  211. foreach (EntityBase entity in entities)
  212. {
  213. if (entity is SceneObjectGroup)
  214. {
  215. SceneObjectGroup sceneObject = (SceneObjectGroup)entity;
  216. if (!sceneObject.IsDeleted && !sceneObject.IsAttachment && !sceneObject.IsTemporary && !sceneObject.inTransit)
  217. {
  218. if (!CanUserArchiveObject(scene.RegionInfo.EstateSettings.EstateOwner, sceneObject, FilterContent, permissionsModule))
  219. {
  220. // The user isn't allowed to copy/transfer this object, so it will not be included in the OAR.
  221. ++numObjectsSkippedPermissions;
  222. }
  223. else
  224. {
  225. sceneObjects.Add(sceneObject);
  226. }
  227. }
  228. }
  229. }
  230. if (SaveAssets)
  231. {
  232. UuidGatherer assetGatherer = new UuidGatherer(scene.AssetService, assetUuids, failedIDs, uncertainAssetsUUIDs);
  233. int prevAssets = assetUuids.Count;
  234. foreach (SceneObjectGroup sceneObject in sceneObjects)
  235. {
  236. int curErrorCntr = assetGatherer.ErrorCount;
  237. int possible = assetGatherer.possibleNotAssetCount;
  238. assetGatherer.AddForInspection(sceneObject);
  239. assetGatherer.GatherAll();
  240. curErrorCntr = assetGatherer.ErrorCount - curErrorCntr;
  241. possible = assetGatherer.possibleNotAssetCount - possible;
  242. if(curErrorCntr > 0)
  243. {
  244. m_log.ErrorFormat("[ARCHIVER]: object {0} '{1}', at {2}, contains {3} references to missing or damaged assets",
  245. sceneObject.UUID, sceneObject.Name ,sceneObject.AbsolutePosition.ToString(), curErrorCntr);
  246. if(possible > 0)
  247. m_log.WarnFormat("[ARCHIVER Warning]: object also contains {0} references that may be to missing or damaged assets or not a problem", possible);
  248. }
  249. else if(possible > 0)
  250. {
  251. m_log.WarnFormat("[ARCHIVER Warning]: object {0} '{1}', at {2}, contains {3} references that may be to missing or damaged assets or not a problem",
  252. sceneObject.UUID, sceneObject.Name ,sceneObject.AbsolutePosition.ToString(), possible);
  253. }
  254. }
  255. assetGatherer.GatherAll();
  256. GC.Collect();
  257. int errors = assetGatherer.FailedUUIDs.Count;
  258. m_log.DebugFormat(
  259. "[ARCHIVER]: {0} region scene objects to save reference {1} possible assets",
  260. sceneObjects.Count, assetUuids.Count - prevAssets + errors);
  261. if(errors > 0)
  262. m_log.DebugFormat("[ARCHIVER]: {0} of these have problems or are not assets and will be ignored", errors);
  263. }
  264. if (numObjectsSkippedPermissions > 0)
  265. {
  266. m_log.DebugFormat(
  267. "[ARCHIVER]: {0} scene objects skipped due to lack of permissions",
  268. numObjectsSkippedPermissions);
  269. }
  270. // Make sure that we also request terrain texture assets
  271. RegionSettings regionSettings = scene.RegionInfo.RegionSettings;
  272. if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
  273. assetUuids[regionSettings.TerrainTexture1] = (sbyte)AssetType.Texture;
  274. if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
  275. assetUuids[regionSettings.TerrainTexture2] = (sbyte)AssetType.Texture;
  276. if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
  277. assetUuids[regionSettings.TerrainTexture3] = (sbyte)AssetType.Texture;
  278. if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
  279. assetUuids[regionSettings.TerrainTexture4] = (sbyte)AssetType.Texture;
  280. Save(scene, sceneObjects, regionDir);
  281. GC.Collect();
  282. }
  283. /// <summary>
  284. /// Checks whether the user has permission to export an object group to an OAR.
  285. /// </summary>
  286. /// <param name="user">The user</param>
  287. /// <param name="objGroup">The object group</param>
  288. /// <param name="filterContent">Which permissions to check: "C" = Copy, "T" = Transfer</param>
  289. /// <param name="permissionsModule">The scene's permissions module</param>
  290. /// <returns>Whether the user is allowed to export the object to an OAR</returns>
  291. private bool CanUserArchiveObject(UUID user, SceneObjectGroup objGroup, string filterContent, IPermissionsModule permissionsModule)
  292. {
  293. if (filterContent == null)
  294. return true;
  295. if (permissionsModule == null)
  296. return true; // this shouldn't happen
  297. // Check whether the user is permitted to export all of the parts in the SOG. If any
  298. // part can't be exported then the entire SOG can't be exported.
  299. bool permitted = true;
  300. //int primNumber = 1;
  301. foreach (SceneObjectPart obj in objGroup.Parts)
  302. {
  303. uint perm;
  304. PermissionClass permissionClass = permissionsModule.GetPermissionClass(user, obj);
  305. switch (permissionClass)
  306. {
  307. case PermissionClass.Owner:
  308. perm = obj.BaseMask;
  309. break;
  310. case PermissionClass.Group:
  311. perm = obj.GroupMask | obj.EveryoneMask;
  312. break;
  313. case PermissionClass.Everyone:
  314. default:
  315. perm = obj.EveryoneMask;
  316. break;
  317. }
  318. bool canCopy = (perm & (uint)PermissionMask.Copy) != 0;
  319. bool canTransfer = (perm & (uint)PermissionMask.Transfer) != 0;
  320. // Special case: if Everyone can copy the object then this implies it can also be
  321. // Transferred.
  322. // However, if the user is the Owner then we don't check EveryoneMask, because it seems that the mask
  323. // always (incorrectly) includes the Copy bit set in this case. But that's a mistake: the viewer
  324. // does NOT show that the object has Everyone-Copy permissions, and doesn't allow it to be copied.
  325. if (permissionClass != PermissionClass.Owner)
  326. canTransfer |= (obj.EveryoneMask & (uint)PermissionMask.Copy) != 0;
  327. bool partPermitted = true;
  328. if (filterContent.Contains("C") && !canCopy)
  329. partPermitted = false;
  330. if (filterContent.Contains("T") && !canTransfer)
  331. partPermitted = false;
  332. // If the user is the Creator of the object then it can always be included in the OAR
  333. bool creator = (obj.CreatorID.Guid == user.Guid);
  334. if (creator)
  335. partPermitted = true;
  336. //string name = (objGroup.PrimCount == 1) ? objGroup.Name : string.Format("{0} ({1}/{2})", obj.Name, primNumber, objGroup.PrimCount);
  337. //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}",
  338. // name, obj.BaseMask, obj.OwnerMask, obj.EveryoneMask,
  339. // permissionClass, checkPermissions, canCopy, canTransfer, creator, partPermitted);
  340. if (!partPermitted)
  341. {
  342. permitted = false;
  343. break;
  344. }
  345. //++primNumber;
  346. }
  347. return permitted;
  348. }
  349. /// <summary>
  350. /// Create the control file.
  351. /// </summary>
  352. /// <returns></returns>
  353. public string CreateControlFile(ArchiveScenesGroup scenesGroup)
  354. {
  355. int majorVersion;
  356. int minorVersion;
  357. if (MultiRegionFormat)
  358. {
  359. majorVersion = MAX_MAJOR_VERSION;
  360. minorVersion = 0;
  361. }
  362. else
  363. {
  364. // To support older versions of OpenSim, we continue to create single-region OARs
  365. // using the old file format. In the future this format will be discontinued.
  366. majorVersion = 0;
  367. minorVersion = 8;
  368. }
  369. //
  370. // if (m_options.ContainsKey("version"))
  371. // {
  372. // string[] parts = m_options["version"].ToString().Split('.');
  373. // if (parts.Length >= 1)
  374. // {
  375. // majorVersion = Int32.Parse(parts[0]);
  376. //
  377. // if (parts.Length >= 2)
  378. // minorVersion = Int32.Parse(parts[1]);
  379. // }
  380. // }
  381. //
  382. // if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION)
  383. // {
  384. // throw new Exception(
  385. // string.Format(
  386. // "OAR version number for save must be between {0} and {1}",
  387. // MIN_MAJOR_VERSION, MAX_MAJOR_VERSION));
  388. // }
  389. // else if (majorVersion == MAX_MAJOR_VERSION)
  390. // {
  391. // // Force 1.0
  392. // minorVersion = 0;
  393. // }
  394. // else if (majorVersion == MIN_MAJOR_VERSION)
  395. // {
  396. // // Force 0.4
  397. // minorVersion = 4;
  398. // }
  399. m_log.InfoFormat("[ARCHIVER]: Creating version {0}.{1} OAR", majorVersion, minorVersion);
  400. if (majorVersion == 1)
  401. {
  402. 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");
  403. }
  404. String s;
  405. using (StringWriter sw = new StringWriter())
  406. {
  407. using (XmlTextWriter xtw = new XmlTextWriter(sw))
  408. {
  409. xtw.Formatting = Formatting.Indented;
  410. xtw.WriteStartDocument();
  411. xtw.WriteStartElement("archive");
  412. xtw.WriteAttributeString("major_version", majorVersion.ToString());
  413. xtw.WriteAttributeString("minor_version", minorVersion.ToString());
  414. xtw.WriteStartElement("creation_info");
  415. DateTime now = DateTime.UtcNow;
  416. TimeSpan t = now - new DateTime(1970, 1, 1);
  417. xtw.WriteElementString("datetime", ((int)t.TotalSeconds).ToString());
  418. if (!MultiRegionFormat)
  419. xtw.WriteElementString("id", m_rootScene.RegionInfo.RegionID.ToString());
  420. xtw.WriteEndElement();
  421. xtw.WriteElementString("assets_included", SaveAssets.ToString());
  422. if (MultiRegionFormat)
  423. {
  424. WriteRegionsManifest(scenesGroup, xtw);
  425. }
  426. else
  427. {
  428. xtw.WriteStartElement("region_info");
  429. WriteRegionInfo(m_rootScene, xtw);
  430. xtw.WriteEndElement();
  431. }
  432. xtw.WriteEndElement();
  433. xtw.Flush();
  434. }
  435. s = sw.ToString();
  436. }
  437. return s;
  438. }
  439. /// <summary>
  440. /// Writes the list of regions included in a multi-region OAR.
  441. /// </summary>
  442. private static void WriteRegionsManifest(ArchiveScenesGroup scenesGroup, XmlTextWriter xtw)
  443. {
  444. xtw.WriteStartElement("regions");
  445. // Write the regions in order: rows from South to North, then regions from West to East.
  446. // The list of regions can have "holes"; we write empty elements in their position.
  447. for (uint y = (uint)scenesGroup.Rect.Top; y < scenesGroup.Rect.Bottom; ++y)
  448. {
  449. SortedDictionary<uint, Scene> row;
  450. if (scenesGroup.Regions.TryGetValue(y, out row))
  451. {
  452. xtw.WriteStartElement("row");
  453. for (uint x = (uint)scenesGroup.Rect.Left; x < scenesGroup.Rect.Right; ++x)
  454. {
  455. Scene scene;
  456. if (row.TryGetValue(x, out scene))
  457. {
  458. xtw.WriteStartElement("region");
  459. xtw.WriteElementString("id", scene.RegionInfo.RegionID.ToString());
  460. xtw.WriteElementString("dir", scenesGroup.GetRegionDir(scene.RegionInfo.RegionID));
  461. WriteRegionInfo(scene, xtw);
  462. xtw.WriteEndElement();
  463. }
  464. else
  465. {
  466. // Write a placeholder for a missing region
  467. xtw.WriteElementString("region", "");
  468. }
  469. }
  470. xtw.WriteEndElement();
  471. }
  472. else
  473. {
  474. // Write a placeholder for a missing row
  475. xtw.WriteElementString("row", "");
  476. }
  477. }
  478. xtw.WriteEndElement(); // "regions"
  479. }
  480. protected static void WriteRegionInfo(Scene scene, XmlTextWriter xtw)
  481. {
  482. Vector2 size;
  483. size = new Vector2((float)scene.RegionInfo.RegionSizeX, (float)scene.RegionInfo.RegionSizeY);
  484. xtw.WriteElementString("size_in_meters", string.Format("{0},{1}", size.X, size.Y));
  485. }
  486. protected void Save(Scene scene, List<SceneObjectGroup> sceneObjects, string regionDir)
  487. {
  488. if (regionDir != string.Empty)
  489. regionDir = ArchiveConstants.REGIONS_PATH + regionDir + "/";
  490. m_log.InfoFormat("[ARCHIVER]: Adding region settings to archive.");
  491. // Write out region settings
  492. string settingsPath = String.Format("{0}{1}{2}.xml",
  493. regionDir, ArchiveConstants.SETTINGS_PATH, scene.RegionInfo.RegionName);
  494. m_archiveWriter.WriteFile(settingsPath, RegionSettingsSerializer.Serialize(scene.RegionInfo.RegionSettings));
  495. m_log.InfoFormat("[ARCHIVER]: Adding parcel settings to archive.");
  496. // Write out land data (aka parcel) settings
  497. List<ILandObject> landObjects = scene.LandChannel.AllParcels();
  498. foreach (ILandObject lo in landObjects)
  499. {
  500. LandData landData = lo.LandData;
  501. string landDataPath
  502. = String.Format("{0}{1}", regionDir, ArchiveConstants.CreateOarLandDataPath(landData));
  503. m_archiveWriter.WriteFile(landDataPath, LandDataSerializer.Serialize(landData, m_options));
  504. }
  505. m_log.InfoFormat("[ARCHIVER]: Adding terrain information to archive.");
  506. // Write out terrain
  507. string terrainPath = String.Format("{0}{1}{2}.r32",
  508. regionDir, ArchiveConstants.TERRAINS_PATH, scene.RegionInfo.RegionName);
  509. using (MemoryStream ms = new MemoryStream())
  510. {
  511. scene.RequestModuleInterface<ITerrainModule>().SaveToStream(terrainPath, ms);
  512. m_archiveWriter.WriteFile(terrainPath, ms.ToArray());
  513. }
  514. m_log.InfoFormat("[ARCHIVER]: Adding scene objects to archive.");
  515. // Write out scene object metadata
  516. IRegionSerialiserModule serializer = scene.RequestModuleInterface<IRegionSerialiserModule>();
  517. foreach (SceneObjectGroup sceneObject in sceneObjects)
  518. {
  519. //m_log.DebugFormat("[ARCHIVER]: Saving {0} {1}, {2}", entity.Name, entity.UUID, entity.GetType());
  520. if(sceneObject.IsDeleted || sceneObject.inTransit)
  521. continue;
  522. string serializedObject = serializer.SerializeGroupToXml2(sceneObject, m_options);
  523. string objectPath = string.Format("{0}{1}", regionDir, ArchiveHelpers.CreateObjectPath(sceneObject));
  524. m_archiveWriter.WriteFile(objectPath, serializedObject);
  525. }
  526. }
  527. protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut)
  528. {
  529. string errorMessage;
  530. if (timedOut)
  531. {
  532. errorMessage = "Loading assets timed out";
  533. }
  534. else
  535. {
  536. foreach (UUID uuid in assetsNotFoundUuids)
  537. {
  538. m_log.DebugFormat("[ARCHIVER]: Could not find asset {0}", uuid);
  539. }
  540. // m_log.InfoFormat(
  541. // "[ARCHIVER]: Received {0} of {1} assets requested",
  542. // assetsFoundUuids.Count, assetsFoundUuids.Count + assetsNotFoundUuids.Count);
  543. errorMessage = String.Empty;
  544. }
  545. CloseArchive(errorMessage);
  546. }
  547. /// <summary>
  548. /// Closes the archive and notifies that we're done.
  549. /// </summary>
  550. /// <param name="errorMessage">The error that occurred, or empty for success</param>
  551. protected void CloseArchive(string errorMessage)
  552. {
  553. try
  554. {
  555. if (m_archiveWriter != null)
  556. m_archiveWriter.Close();
  557. m_saveStream.Close();
  558. }
  559. catch (Exception e)
  560. {
  561. m_log.Error(string.Format("[ARCHIVER]: Error closing archive: {0} ", e.Message), e);
  562. if (errorMessage == string.Empty)
  563. errorMessage = e.Message;
  564. }
  565. m_log.InfoFormat("[ARCHIVER]: Finished writing out OAR for {0}", m_rootScene.RegionInfo.RegionName);
  566. m_rootScene.EventManager.TriggerOarFileSaved(m_requestId, errorMessage);
  567. }
  568. }
  569. }