ArchiveReadRequest.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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.Net;
  32. using System.Reflection;
  33. using System.Text;
  34. using System.Xml;
  35. using log4net;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Serialization;
  39. using OpenSim.Framework.Serialization.External;
  40. using OpenSim.Region.CoreModules.World.Terrain;
  41. using OpenSim.Region.Framework.Interfaces;
  42. using OpenSim.Region.Framework.Scenes;
  43. using OpenSim.Services.Interfaces;
  44. namespace OpenSim.Region.CoreModules.World.Archiver
  45. {
  46. /// <summary>
  47. /// Handles an individual archive read request
  48. /// </summary>
  49. public class ArchiveReadRequest
  50. {
  51. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. protected Scene m_scene;
  53. protected Stream m_loadStream;
  54. protected Guid m_requestId;
  55. protected string m_errorMessage;
  56. /// <value>
  57. /// Should the archive being loaded be merged with what is already on the region?
  58. /// </value>
  59. protected bool m_merge;
  60. /// <value>
  61. /// Should we ignore any assets when reloading the archive?
  62. /// </value>
  63. protected bool m_skipAssets;
  64. /// <summary>
  65. /// Used to cache lookups for valid uuids.
  66. /// </summary>
  67. private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
  68. public ArchiveReadRequest(Scene scene, string loadPath, bool merge, bool skipAssets, Guid requestId)
  69. {
  70. m_scene = scene;
  71. try
  72. {
  73. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress);
  74. }
  75. catch (EntryPointNotFoundException e)
  76. {
  77. m_log.ErrorFormat(
  78. "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
  79. + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
  80. m_log.Error(e);
  81. }
  82. m_errorMessage = String.Empty;
  83. m_merge = merge;
  84. m_skipAssets = skipAssets;
  85. m_requestId = requestId;
  86. }
  87. public ArchiveReadRequest(Scene scene, Stream loadStream, bool merge, bool skipAssets, Guid requestId)
  88. {
  89. m_scene = scene;
  90. m_loadStream = loadStream;
  91. m_merge = merge;
  92. m_skipAssets = skipAssets;
  93. m_requestId = requestId;
  94. }
  95. /// <summary>
  96. /// Dearchive the region embodied in this request.
  97. /// </summary>
  98. public void DearchiveRegion()
  99. {
  100. // The same code can handle dearchiving 0.1 and 0.2 OpenSim Archive versions
  101. DearchiveRegion0DotStar();
  102. }
  103. private void DearchiveRegion0DotStar()
  104. {
  105. int successfulAssetRestores = 0;
  106. int failedAssetRestores = 0;
  107. List<string> serialisedSceneObjects = new List<string>();
  108. List<string> serialisedParcels = new List<string>();
  109. string filePath = "NONE";
  110. TarArchiveReader archive = new TarArchiveReader(m_loadStream);
  111. byte[] data;
  112. TarArchiveReader.TarEntryType entryType;
  113. try
  114. {
  115. while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
  116. {
  117. //m_log.DebugFormat(
  118. // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
  119. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  120. continue;
  121. if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
  122. {
  123. serialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
  124. }
  125. else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
  126. {
  127. if (LoadAsset(filePath, data))
  128. successfulAssetRestores++;
  129. else
  130. failedAssetRestores++;
  131. if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
  132. m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
  133. }
  134. else if (!m_merge && filePath.StartsWith(ArchiveConstants.TERRAINS_PATH))
  135. {
  136. LoadTerrain(filePath, data);
  137. }
  138. else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
  139. {
  140. LoadRegionSettings(filePath, data);
  141. }
  142. else if (!m_merge && filePath.StartsWith(ArchiveConstants.LANDDATA_PATH))
  143. {
  144. serialisedParcels.Add(Encoding.UTF8.GetString(data));
  145. }
  146. else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  147. {
  148. LoadControlFile(filePath, data);
  149. }
  150. }
  151. //m_log.Debug("[ARCHIVER]: Reached end of archive");
  152. }
  153. catch (Exception e)
  154. {
  155. m_log.ErrorFormat(
  156. "[ARCHIVER]: Aborting load with error in archive file {0}. {1}", filePath, e);
  157. m_errorMessage += e.ToString();
  158. m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage);
  159. return;
  160. }
  161. finally
  162. {
  163. archive.Close();
  164. }
  165. if (!m_skipAssets)
  166. {
  167. m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
  168. if (failedAssetRestores > 0)
  169. {
  170. m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
  171. m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
  172. }
  173. }
  174. if (!m_merge)
  175. {
  176. m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
  177. m_scene.DeleteAllSceneObjects();
  178. }
  179. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  180. // otherwise, use the master avatar uuid instead
  181. // Reload serialized parcels
  182. m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
  183. List<LandData> landData = new List<LandData>();
  184. foreach (string serialisedParcel in serialisedParcels)
  185. {
  186. LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
  187. if (!ResolveUserUuid(parcel.OwnerID))
  188. parcel.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  189. landData.Add(parcel);
  190. }
  191. m_scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
  192. m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
  193. // Reload serialized prims
  194. m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
  195. IRegionSerialiserModule serialiser = m_scene.RequestModuleInterface<IRegionSerialiserModule>();
  196. int sceneObjectsLoadedCount = 0;
  197. foreach (string serialisedSceneObject in serialisedSceneObjects)
  198. {
  199. /*
  200. m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length);
  201. // Really large xml files (multi megabyte) appear to cause
  202. // memory problems
  203. // when loading the xml. But don't enable this check yet
  204. if (serialisedSceneObject.Length > 5000000)
  205. {
  206. m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);");
  207. continue;
  208. }
  209. */
  210. SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
  211. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  212. // on the same region server and multiple examples a single object archive to be imported
  213. // to the same scene (when this is possible).
  214. sceneObject.ResetIDs();
  215. foreach (SceneObjectPart part in sceneObject.Children.Values)
  216. {
  217. if (!ResolveUserUuid(part.CreatorID))
  218. part.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  219. if (!ResolveUserUuid(part.OwnerID))
  220. part.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  221. if (!ResolveUserUuid(part.LastOwnerID))
  222. part.LastOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  223. // And zap any troublesome sit target information
  224. part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  225. part.SitTargetPosition = new Vector3(0, 0, 0);
  226. // Fix ownership/creator of inventory items
  227. // Not doing so results in inventory items
  228. // being no copy/no mod for everyone
  229. lock (part.TaskInventory)
  230. {
  231. TaskInventoryDictionary inv = part.TaskInventory;
  232. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  233. {
  234. if (!ResolveUserUuid(kvp.Value.OwnerID))
  235. {
  236. kvp.Value.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  237. }
  238. if (!ResolveUserUuid(kvp.Value.CreatorID))
  239. {
  240. kvp.Value.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  241. }
  242. }
  243. }
  244. }
  245. if (m_scene.AddRestoredSceneObject(sceneObject, true, false))
  246. {
  247. sceneObjectsLoadedCount++;
  248. sceneObject.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, 0);
  249. sceneObject.ResumeScripts();
  250. }
  251. }
  252. m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
  253. int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
  254. if (ignoredObjects > 0)
  255. m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
  256. m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
  257. m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage);
  258. }
  259. /// <summary>
  260. /// Look up the given user id to check whether it's one that is valid for this grid.
  261. /// </summary>
  262. /// <param name="uuid"></param>
  263. /// <returns></returns>
  264. private bool ResolveUserUuid(UUID uuid)
  265. {
  266. if (!m_validUserUuids.ContainsKey(uuid))
  267. {
  268. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
  269. if (account != null)
  270. m_validUserUuids.Add(uuid, true);
  271. else
  272. m_validUserUuids.Add(uuid, false);
  273. }
  274. if (m_validUserUuids[uuid])
  275. return true;
  276. else
  277. return false;
  278. }
  279. /// <summary>
  280. /// Load an asset
  281. /// </summary>
  282. /// <param name="assetFilename"></param>
  283. /// <param name="data"></param>
  284. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  285. private bool LoadAsset(string assetPath, byte[] data)
  286. {
  287. // Right now we're nastily obtaining the UUID from the filename
  288. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  289. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  290. if (i == -1)
  291. {
  292. m_log.ErrorFormat(
  293. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  294. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  295. return false;
  296. }
  297. string extension = filename.Substring(i);
  298. string uuid = filename.Remove(filename.Length - extension.Length);
  299. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  300. {
  301. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  302. if (assetType == (sbyte)AssetType.Unknown)
  303. m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  304. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  305. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
  306. asset.Data = data;
  307. // We're relying on the asset service to do the sensible thing and not store the asset if it already
  308. // exists.
  309. m_scene.AssetService.Store(asset);
  310. /**
  311. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  312. * it might be best done when dearchive takes place on a separate thread
  313. if (asset.Type=AssetType.Texture)
  314. {
  315. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  316. if (cacheLayerDecode != null)
  317. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  318. }
  319. */
  320. return true;
  321. }
  322. else
  323. {
  324. m_log.ErrorFormat(
  325. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  326. assetPath, extension);
  327. return false;
  328. }
  329. }
  330. /// <summary>
  331. /// Load region settings data
  332. /// </summary>
  333. /// <param name="settingsPath"></param>
  334. /// <param name="data"></param>
  335. /// <returns>
  336. /// true if settings were loaded successfully, false otherwise
  337. /// </returns>
  338. private bool LoadRegionSettings(string settingsPath, byte[] data)
  339. {
  340. RegionSettings loadedRegionSettings;
  341. try
  342. {
  343. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
  344. }
  345. catch (Exception e)
  346. {
  347. m_log.ErrorFormat(
  348. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  349. settingsPath, e);
  350. return false;
  351. }
  352. RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
  353. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  354. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  355. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  356. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  357. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  358. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  359. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  360. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  361. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  362. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  363. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  364. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  365. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  366. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  367. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  368. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  369. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  370. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  371. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  372. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  373. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  374. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  375. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  376. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  377. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  378. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  379. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  380. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  381. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  382. currentRegionSettings.Save();
  383. IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
  384. if (estateModule != null)
  385. estateModule.sendRegionHandshakeToAll();
  386. return true;
  387. }
  388. /// <summary>
  389. /// Load terrain data
  390. /// </summary>
  391. /// <param name="terrainPath"></param>
  392. /// <param name="data"></param>
  393. /// <returns>
  394. /// true if terrain was resolved successfully, false otherwise.
  395. /// </returns>
  396. private bool LoadTerrain(string terrainPath, byte[] data)
  397. {
  398. ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>();
  399. MemoryStream ms = new MemoryStream(data);
  400. terrainModule.LoadFromStream(terrainPath, ms);
  401. ms.Close();
  402. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  403. return true;
  404. }
  405. /// <summary>
  406. /// Load oar control file
  407. /// </summary>
  408. /// <param name="path"></param>
  409. /// <param name="data"></param>
  410. private void LoadControlFile(string path, byte[] data)
  411. {
  412. //Create the XmlNamespaceManager.
  413. NameTable nt = new NameTable();
  414. XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
  415. // Create the XmlParserContext.
  416. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  417. XmlTextReader xtr
  418. = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
  419. RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
  420. // Loaded metadata will empty if no information exists in the archive
  421. currentRegionSettings.LoadedCreationDateTime = 0;
  422. currentRegionSettings.LoadedCreationID = "";
  423. while (xtr.Read())
  424. {
  425. if (xtr.NodeType == XmlNodeType.Element)
  426. {
  427. if (xtr.Name.ToString() == "datetime")
  428. {
  429. int value;
  430. if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
  431. currentRegionSettings.LoadedCreationDateTime = value;
  432. }
  433. else if (xtr.Name.ToString() == "id")
  434. {
  435. currentRegionSettings.LoadedCreationID = xtr.ReadElementContentAsString();
  436. }
  437. }
  438. }
  439. currentRegionSettings.Save();
  440. }
  441. }
  442. }