ArchiveWriteRequestPreparation.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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.Text.RegularExpressions;
  33. using System.Threading;
  34. using System.Xml;
  35. using log4net;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Serialization;
  39. using OpenSim.Region.CoreModules.World.Terrain;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. namespace OpenSim.Region.CoreModules.World.Archiver
  43. {
  44. /// <summary>
  45. /// Prepare to write out an archive.
  46. /// </summary>
  47. public class ArchiveWriteRequestPreparation
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. /// <summary>
  51. /// The minimum major version of OAR that we can write.
  52. /// </summary>
  53. public static int MIN_MAJOR_VERSION = 0;
  54. /// <summary>
  55. /// The maximum major version of OAR that we can write.
  56. /// </summary>
  57. public static int MAX_MAJOR_VERSION = 0;
  58. /// <summary>
  59. /// Determine whether this archive will save assets. Default is true.
  60. /// </summary>
  61. public bool SaveAssets { get; set; }
  62. protected Scene m_scene;
  63. protected Stream m_saveStream;
  64. protected Guid m_requestId;
  65. /// <summary>
  66. /// Constructor
  67. /// </summary>
  68. /// <param name="scene"></param>
  69. /// <param name="savePath">The path to which to save data.</param>
  70. /// <param name="requestId">The id associated with this request</param>
  71. /// <exception cref="System.IO.IOException">
  72. /// If there was a problem opening a stream for the file specified by the savePath
  73. /// </exception>
  74. public ArchiveWriteRequestPreparation(Scene scene, string savePath, Guid requestId) : this(scene, requestId)
  75. {
  76. try
  77. {
  78. m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress);
  79. }
  80. catch (EntryPointNotFoundException e)
  81. {
  82. m_log.ErrorFormat(
  83. "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
  84. + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
  85. m_log.ErrorFormat("{0} {1}", e.Message, e.StackTrace);
  86. }
  87. }
  88. /// <summary>
  89. /// Constructor.
  90. /// </summary>
  91. /// <param name="scene"></param>
  92. /// <param name="saveStream">The stream to which to save data.</param>
  93. /// <param name="requestId">The id associated with this request</param>
  94. public ArchiveWriteRequestPreparation(Scene scene, Stream saveStream, Guid requestId) : this(scene, requestId)
  95. {
  96. m_saveStream = saveStream;
  97. }
  98. protected ArchiveWriteRequestPreparation(Scene scene, Guid requestId)
  99. {
  100. m_scene = scene;
  101. m_requestId = requestId;
  102. SaveAssets = true;
  103. }
  104. /// <summary>
  105. /// Archive the region requested.
  106. /// </summary>
  107. /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception>
  108. public void ArchiveRegion(Dictionary<string, object> options)
  109. {
  110. if (options.ContainsKey("noassets") && (bool)options["noassets"])
  111. SaveAssets = false;
  112. try
  113. {
  114. Dictionary<UUID, AssetType> assetUuids = new Dictionary<UUID, AssetType>();
  115. EntityBase[] entities = m_scene.GetEntities();
  116. List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
  117. // Filter entities so that we only have scene objects.
  118. // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods
  119. // end up having to do this
  120. foreach (EntityBase entity in entities)
  121. {
  122. if (entity is SceneObjectGroup)
  123. {
  124. SceneObjectGroup sceneObject = (SceneObjectGroup)entity;
  125. if (!sceneObject.IsDeleted && !sceneObject.IsAttachment)
  126. sceneObjects.Add((SceneObjectGroup)entity);
  127. }
  128. }
  129. if (SaveAssets)
  130. {
  131. UuidGatherer assetGatherer = new UuidGatherer(m_scene.AssetService);
  132. foreach (SceneObjectGroup sceneObject in sceneObjects)
  133. {
  134. assetGatherer.GatherAssetUuids(sceneObject, assetUuids);
  135. }
  136. m_log.DebugFormat(
  137. "[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets",
  138. sceneObjects.Count, assetUuids.Count);
  139. }
  140. else
  141. {
  142. m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified");
  143. }
  144. // Make sure that we also request terrain texture assets
  145. RegionSettings regionSettings = m_scene.RegionInfo.RegionSettings;
  146. if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
  147. assetUuids[regionSettings.TerrainTexture1] = AssetType.Texture;
  148. if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
  149. assetUuids[regionSettings.TerrainTexture2] = AssetType.Texture;
  150. if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
  151. assetUuids[regionSettings.TerrainTexture3] = AssetType.Texture;
  152. if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
  153. assetUuids[regionSettings.TerrainTexture4] = AssetType.Texture;
  154. TarArchiveWriter archiveWriter = new TarArchiveWriter(m_saveStream);
  155. // Asynchronously request all the assets required to perform this archive operation
  156. ArchiveWriteRequestExecution awre
  157. = new ArchiveWriteRequestExecution(
  158. sceneObjects,
  159. m_scene.RequestModuleInterface<ITerrainModule>(),
  160. m_scene.RequestModuleInterface<IRegionSerialiserModule>(),
  161. m_scene,
  162. archiveWriter,
  163. m_requestId,
  164. options);
  165. m_log.InfoFormat("[ARCHIVER]: Creating archive file. This may take some time.");
  166. // Write out control file. This has to be done first so that subsequent loaders will see this file first
  167. // XXX: I know this is a weak way of doing it since external non-OAR aware tar executables will not do this
  168. archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(options));
  169. m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");
  170. if (SaveAssets)
  171. new AssetsRequest(
  172. new AssetsArchiver(archiveWriter), assetUuids,
  173. m_scene.AssetService, m_scene.UserAccountService,
  174. m_scene.RegionInfo.ScopeID, options, awre.ReceivedAllAssets).Execute();
  175. else
  176. awre.ReceivedAllAssets(new List<UUID>(), new List<UUID>());
  177. }
  178. catch (Exception)
  179. {
  180. m_saveStream.Close();
  181. throw;
  182. }
  183. }
  184. /// <summary>
  185. /// Create the control file for the most up to date archive
  186. /// </summary>
  187. /// <returns></returns>
  188. public string CreateControlFile(Dictionary<string, object> options)
  189. {
  190. int majorVersion = MAX_MAJOR_VERSION, minorVersion = 7;
  191. //
  192. // if (options.ContainsKey("version"))
  193. // {
  194. // string[] parts = options["version"].ToString().Split('.');
  195. // if (parts.Length >= 1)
  196. // {
  197. // majorVersion = Int32.Parse(parts[0]);
  198. //
  199. // if (parts.Length >= 2)
  200. // minorVersion = Int32.Parse(parts[1]);
  201. // }
  202. // }
  203. //
  204. // if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION)
  205. // {
  206. // throw new Exception(
  207. // string.Format(
  208. // "OAR version number for save must be between {0} and {1}",
  209. // MIN_MAJOR_VERSION, MAX_MAJOR_VERSION));
  210. // }
  211. // else if (majorVersion == MAX_MAJOR_VERSION)
  212. // {
  213. // // Force 1.0
  214. // minorVersion = 0;
  215. // }
  216. // else if (majorVersion == MIN_MAJOR_VERSION)
  217. // {
  218. // // Force 0.4
  219. // minorVersion = 4;
  220. // }
  221. m_log.InfoFormat("[ARCHIVER]: Creating version {0}.{1} OAR", majorVersion, minorVersion);
  222. //if (majorVersion == 1)
  223. //{
  224. // m_log.WarnFormat("[ARCHIVER]: Please be aware that version 1.0 OARs are not compatible with OpenSim 0.7.0.2 and earlier. Please use the --version=0 option if you want to produce a compatible OAR");
  225. //}
  226. StringWriter sw = new StringWriter();
  227. XmlTextWriter xtw = new XmlTextWriter(sw);
  228. xtw.Formatting = Formatting.Indented;
  229. xtw.WriteStartDocument();
  230. xtw.WriteStartElement("archive");
  231. xtw.WriteAttributeString("major_version", majorVersion.ToString());
  232. xtw.WriteAttributeString("minor_version", minorVersion.ToString());
  233. xtw.WriteStartElement("creation_info");
  234. DateTime now = DateTime.UtcNow;
  235. TimeSpan t = now - new DateTime(1970, 1, 1);
  236. xtw.WriteElementString("datetime", ((int)t.TotalSeconds).ToString());
  237. xtw.WriteElementString("id", UUID.Random().ToString());
  238. xtw.WriteEndElement();
  239. xtw.WriteElementString("assets_included", SaveAssets.ToString());
  240. xtw.WriteEndElement();
  241. xtw.Flush();
  242. xtw.Close();
  243. String s = sw.ToString();
  244. sw.Close();
  245. return s;
  246. }
  247. }
  248. }