ArchiveReadRequest.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. List<SceneObjectPart> partList = null;
  216. lock (sceneObject.Children)
  217. partList = new List<SceneObjectPart>(sceneObject.Children.Values);
  218. foreach (SceneObjectPart part in partList)
  219. {
  220. if (!ResolveUserUuid(part.CreatorID))
  221. part.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  222. if (!ResolveUserUuid(part.OwnerID))
  223. part.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  224. if (!ResolveUserUuid(part.LastOwnerID))
  225. part.LastOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  226. // And zap any troublesome sit target information
  227. part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  228. part.SitTargetPosition = new Vector3(0, 0, 0);
  229. // Fix ownership/creator of inventory items
  230. // Not doing so results in inventory items
  231. // being no copy/no mod for everyone
  232. lock (part.TaskInventory)
  233. {
  234. TaskInventoryDictionary inv = part.TaskInventory;
  235. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  236. {
  237. if (!ResolveUserUuid(kvp.Value.OwnerID))
  238. {
  239. kvp.Value.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  240. }
  241. if (!ResolveUserUuid(kvp.Value.CreatorID))
  242. {
  243. kvp.Value.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
  244. }
  245. }
  246. }
  247. }
  248. if (m_scene.AddRestoredSceneObject(sceneObject, true, false))
  249. {
  250. sceneObjectsLoadedCount++;
  251. sceneObject.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, 0);
  252. sceneObject.ResumeScripts();
  253. }
  254. }
  255. m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
  256. int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
  257. if (ignoredObjects > 0)
  258. m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
  259. m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
  260. m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage);
  261. }
  262. /// <summary>
  263. /// Look up the given user id to check whether it's one that is valid for this grid.
  264. /// </summary>
  265. /// <param name="uuid"></param>
  266. /// <returns></returns>
  267. private bool ResolveUserUuid(UUID uuid)
  268. {
  269. if (!m_validUserUuids.ContainsKey(uuid))
  270. {
  271. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
  272. if (account != null)
  273. m_validUserUuids.Add(uuid, true);
  274. else
  275. m_validUserUuids.Add(uuid, false);
  276. }
  277. if (m_validUserUuids[uuid])
  278. return true;
  279. else
  280. return false;
  281. }
  282. /// <summary>
  283. /// Load an asset
  284. /// </summary>
  285. /// <param name="assetFilename"></param>
  286. /// <param name="data"></param>
  287. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  288. private bool LoadAsset(string assetPath, byte[] data)
  289. {
  290. // Right now we're nastily obtaining the UUID from the filename
  291. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  292. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  293. if (i == -1)
  294. {
  295. m_log.ErrorFormat(
  296. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  297. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  298. return false;
  299. }
  300. string extension = filename.Substring(i);
  301. string uuid = filename.Remove(filename.Length - extension.Length);
  302. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  303. {
  304. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  305. if (assetType == (sbyte)AssetType.Unknown)
  306. m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  307. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  308. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
  309. asset.Data = data;
  310. // We're relying on the asset service to do the sensible thing and not store the asset if it already
  311. // exists.
  312. m_scene.AssetService.Store(asset);
  313. /**
  314. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  315. * it might be best done when dearchive takes place on a separate thread
  316. if (asset.Type=AssetType.Texture)
  317. {
  318. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  319. if (cacheLayerDecode != null)
  320. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  321. }
  322. */
  323. return true;
  324. }
  325. else
  326. {
  327. m_log.ErrorFormat(
  328. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  329. assetPath, extension);
  330. return false;
  331. }
  332. }
  333. /// <summary>
  334. /// Load region settings data
  335. /// </summary>
  336. /// <param name="settingsPath"></param>
  337. /// <param name="data"></param>
  338. /// <returns>
  339. /// true if settings were loaded successfully, false otherwise
  340. /// </returns>
  341. private bool LoadRegionSettings(string settingsPath, byte[] data)
  342. {
  343. RegionSettings loadedRegionSettings;
  344. try
  345. {
  346. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
  347. }
  348. catch (Exception e)
  349. {
  350. m_log.ErrorFormat(
  351. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  352. settingsPath, e);
  353. return false;
  354. }
  355. RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
  356. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  357. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  358. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  359. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  360. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  361. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  362. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  363. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  364. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  365. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  366. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  367. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  368. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  369. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  370. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  371. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  372. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  373. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  374. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  375. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  376. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  377. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  378. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  379. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  380. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  381. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  382. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  383. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  384. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  385. currentRegionSettings.Save();
  386. IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
  387. if (estateModule != null)
  388. estateModule.sendRegionHandshakeToAll();
  389. return true;
  390. }
  391. /// <summary>
  392. /// Load terrain data
  393. /// </summary>
  394. /// <param name="terrainPath"></param>
  395. /// <param name="data"></param>
  396. /// <returns>
  397. /// true if terrain was resolved successfully, false otherwise.
  398. /// </returns>
  399. private bool LoadTerrain(string terrainPath, byte[] data)
  400. {
  401. ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>();
  402. MemoryStream ms = new MemoryStream(data);
  403. terrainModule.LoadFromStream(terrainPath, ms);
  404. ms.Close();
  405. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  406. return true;
  407. }
  408. /// <summary>
  409. /// Load oar control file
  410. /// </summary>
  411. /// <param name="path"></param>
  412. /// <param name="data"></param>
  413. private void LoadControlFile(string path, byte[] data)
  414. {
  415. //Create the XmlNamespaceManager.
  416. NameTable nt = new NameTable();
  417. XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
  418. // Create the XmlParserContext.
  419. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  420. XmlTextReader xtr
  421. = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
  422. RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
  423. // Loaded metadata will empty if no information exists in the archive
  424. currentRegionSettings.LoadedCreationDateTime = 0;
  425. currentRegionSettings.LoadedCreationID = "";
  426. while (xtr.Read())
  427. {
  428. if (xtr.NodeType == XmlNodeType.Element)
  429. {
  430. if (xtr.Name.ToString() == "datetime")
  431. {
  432. int value;
  433. if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
  434. currentRegionSettings.LoadedCreationDateTime = value;
  435. }
  436. else if (xtr.Name.ToString() == "id")
  437. {
  438. currentRegionSettings.LoadedCreationID = xtr.ReadElementContentAsString();
  439. }
  440. }
  441. }
  442. currentRegionSettings.Save();
  443. }
  444. }
  445. }