ArchiveReadRequest.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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.Region.Framework.Scenes.Serialization;
  44. using OpenSim.Services.Interfaces;
  45. using System.Threading;
  46. namespace OpenSim.Region.CoreModules.World.Archiver
  47. {
  48. /// <summary>
  49. /// Handles an individual archive read request
  50. /// </summary>
  51. public class ArchiveReadRequest
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. /// <summary>
  55. /// Contains data used while dearchiving a single scene.
  56. /// </summary>
  57. private class DearchiveContext
  58. {
  59. public Scene Scene { get; set; }
  60. public List<string> SerialisedSceneObjects { get; set; }
  61. public List<string> SerialisedParcels { get; set; }
  62. public List<SceneObjectGroup> SceneObjects { get; set; }
  63. public DearchiveContext(Scene scene)
  64. {
  65. Scene = scene;
  66. SerialisedSceneObjects = new List<string>();
  67. SerialisedParcels = new List<string>();
  68. SceneObjects = new List<SceneObjectGroup>();
  69. }
  70. }
  71. /// <summary>
  72. /// The maximum major version of OAR that we can read. Minor versions shouldn't need a max number since version
  73. /// bumps here should be compatible.
  74. /// </summary>
  75. public static int MAX_MAJOR_VERSION = 1;
  76. /// <summary>
  77. /// Has the control file been loaded for this archive?
  78. /// </summary>
  79. public bool ControlFileLoaded { get; private set; }
  80. protected string m_loadPath;
  81. protected Scene m_rootScene;
  82. protected Stream m_loadStream;
  83. protected Guid m_requestId;
  84. protected string m_errorMessage;
  85. /// <value>
  86. /// Should the archive being loaded be merged with what is already on the region?
  87. /// Merging usually suppresses terrain and parcel loading
  88. /// </value>
  89. protected bool m_merge;
  90. /// <value>
  91. /// If true, force the loading of terrain from the oar file
  92. /// </value>
  93. protected bool m_forceTerrain;
  94. /// <value>
  95. /// If true, force the loading of parcels from the oar file
  96. /// </value>
  97. protected bool m_forceParcels;
  98. /// <value>
  99. /// Should we ignore any assets when reloading the archive?
  100. /// </value>
  101. protected bool m_skipAssets;
  102. /// <value>
  103. /// Displacement added to each object as it is added to the world
  104. /// </value>
  105. protected Vector3 m_displacement = Vector3.Zero;
  106. /// <value>
  107. /// Rotation (in radians) to apply to the objects as they are loaded.
  108. /// </value>
  109. protected float m_rotation = 0f;
  110. /// <value>
  111. /// Center around which to apply the rotation relative to the origional oar position
  112. /// </value>
  113. protected Vector3 m_rotationCenter = new Vector3(Constants.RegionSize / 2f, Constants.RegionSize / 2f, 0f);
  114. protected bool m_noObjects = false;
  115. /// <summary>
  116. /// Used to cache lookups for valid uuids.
  117. /// </summary>
  118. private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
  119. private IUserManagement m_UserMan;
  120. private IUserManagement UserManager
  121. {
  122. get
  123. {
  124. if (m_UserMan == null)
  125. {
  126. m_UserMan = m_rootScene.RequestModuleInterface<IUserManagement>();
  127. }
  128. return m_UserMan;
  129. }
  130. }
  131. /// <summary>
  132. /// Used to cache lookups for valid groups.
  133. /// </summary>
  134. private IDictionary<UUID, bool> m_validGroupUuids = new Dictionary<UUID, bool>();
  135. private IGroupsModule m_groupsModule;
  136. private IAssetService m_assetService = null;
  137. public ArchiveReadRequest(Scene scene, string loadPath, Guid requestId, Dictionary<string,object>options)
  138. {
  139. m_rootScene = scene;
  140. m_loadPath = loadPath;
  141. try
  142. {
  143. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress);
  144. }
  145. catch (EntryPointNotFoundException e)
  146. {
  147. m_log.ErrorFormat(
  148. "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
  149. + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
  150. m_log.Error(e);
  151. }
  152. m_errorMessage = String.Empty;
  153. m_merge = options.ContainsKey("merge");
  154. m_forceTerrain = options.ContainsKey("force-terrain");
  155. m_forceParcels = options.ContainsKey("force-parcels");
  156. m_noObjects = options.ContainsKey("no-objects");
  157. m_skipAssets = options.ContainsKey("skipAssets");
  158. m_requestId = requestId;
  159. m_displacement = options.ContainsKey("displacement") ? (Vector3)options["displacement"] : Vector3.Zero;
  160. m_rotation = options.ContainsKey("rotation") ? (float)options["rotation"] : 0f;
  161. m_rotationCenter = options.ContainsKey("rotation-center") ? (Vector3)options["rotation-center"]
  162. : new Vector3(scene.RegionInfo.RegionSizeX / 2f, scene.RegionInfo.RegionSizeY / 2f, 0f);
  163. // Zero can never be a valid user or group id
  164. m_validUserUuids[UUID.Zero] = false;
  165. m_validGroupUuids[UUID.Zero] = false;
  166. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  167. m_assetService = m_rootScene.AssetService;
  168. }
  169. public ArchiveReadRequest(Scene scene, Stream loadStream, Guid requestId, Dictionary<string, object>options)
  170. {
  171. m_rootScene = scene;
  172. m_loadPath = null;
  173. m_loadStream = loadStream;
  174. m_skipAssets = options.ContainsKey("skipAssets");
  175. m_merge = options.ContainsKey("merge");
  176. m_requestId = requestId;
  177. // Zero can never be a valid user id
  178. m_validUserUuids[UUID.Zero] = false;
  179. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  180. m_assetService = m_rootScene.AssetService;
  181. }
  182. /// <summary>
  183. /// Dearchive the region embodied in this request.
  184. /// </summary>
  185. public void DearchiveRegion()
  186. {
  187. int successfulAssetRestores = 0;
  188. int failedAssetRestores = 0;
  189. DearchiveScenesInfo dearchivedScenes;
  190. // We dearchive all the scenes at once, because the files in the TAR archive might be mixed.
  191. // Therefore, we have to keep track of the dearchive context of all the scenes.
  192. Dictionary<UUID, DearchiveContext> sceneContexts = new Dictionary<UUID, DearchiveContext>();
  193. string fullPath = "NONE";
  194. TarArchiveReader archive = null;
  195. byte[] data;
  196. TarArchiveReader.TarEntryType entryType;
  197. try
  198. {
  199. FindAndLoadControlFile(out archive, out dearchivedScenes);
  200. while ((data = archive.ReadEntry(out fullPath, out entryType)) != null)
  201. {
  202. //m_log.DebugFormat(
  203. // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
  204. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  205. continue;
  206. // Find the scene that this file belongs to
  207. Scene scene;
  208. string filePath;
  209. if (!dearchivedScenes.GetRegionFromPath(fullPath, out scene, out filePath))
  210. continue; // this file belongs to a region that we're not loading
  211. DearchiveContext sceneContext = null;
  212. if (scene != null)
  213. {
  214. if (!sceneContexts.TryGetValue(scene.RegionInfo.RegionID, out sceneContext))
  215. {
  216. sceneContext = new DearchiveContext(scene);
  217. sceneContexts.Add(scene.RegionInfo.RegionID, sceneContext);
  218. }
  219. }
  220. // Process the file
  221. if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH) && !m_noObjects)
  222. {
  223. sceneContext.SerialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
  224. }
  225. else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
  226. {
  227. if (LoadAsset(filePath, data))
  228. successfulAssetRestores++;
  229. else
  230. failedAssetRestores++;
  231. if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
  232. m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
  233. }
  234. else if (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH) && (!m_merge || m_forceTerrain))
  235. {
  236. LoadTerrain(scene, filePath, data);
  237. }
  238. else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
  239. {
  240. LoadRegionSettings(scene, filePath, data, dearchivedScenes);
  241. }
  242. else if (filePath.StartsWith(ArchiveConstants.LANDDATA_PATH) && (!m_merge || m_forceParcels))
  243. {
  244. sceneContext.SerialisedParcels.Add(Encoding.UTF8.GetString(data));
  245. }
  246. else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  247. {
  248. // Ignore, because we already read the control file
  249. }
  250. }
  251. //m_log.Debug("[ARCHIVER]: Reached end of archive");
  252. }
  253. catch (Exception e)
  254. {
  255. m_log.Error(
  256. String.Format("[ARCHIVER]: Aborting load with error in archive file {0} ", fullPath), e);
  257. m_errorMessage += e.ToString();
  258. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  259. return;
  260. }
  261. finally
  262. {
  263. if (archive != null)
  264. archive.Close();
  265. }
  266. if (!m_skipAssets)
  267. {
  268. m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
  269. if (failedAssetRestores > 0)
  270. {
  271. m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
  272. m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
  273. }
  274. }
  275. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  276. {
  277. m_log.InfoFormat("[ARCHIVER]: Loading region {0}", sceneContext.Scene.RegionInfo.RegionName);
  278. if (!m_merge)
  279. {
  280. m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
  281. sceneContext.Scene.DeleteAllSceneObjects();
  282. }
  283. try
  284. {
  285. LoadParcels(sceneContext.Scene, sceneContext.SerialisedParcels);
  286. LoadObjects(sceneContext.Scene, sceneContext.SerialisedSceneObjects, sceneContext.SceneObjects);
  287. // Inform any interested parties that the region has changed. We waited until now so that all
  288. // of the region's objects will be loaded when we send this notification.
  289. IEstateModule estateModule = sceneContext.Scene.RequestModuleInterface<IEstateModule>();
  290. if (estateModule != null)
  291. estateModule.TriggerRegionInfoChange();
  292. }
  293. catch (Exception e)
  294. {
  295. m_log.Error("[ARCHIVER]: Error loading parcels or objects ", e);
  296. m_errorMessage += e.ToString();
  297. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  298. return;
  299. }
  300. }
  301. // Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so
  302. // that users can enter the scene. If we allow the scripts to start in the loop above
  303. // then they significantly increase the time until the OAR finishes loading.
  304. Util.FireAndForget(delegate(object o)
  305. {
  306. Thread.Sleep(15000);
  307. m_log.Info("[ARCHIVER]: Starting scripts in scene objects");
  308. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  309. {
  310. foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects)
  311. {
  312. sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart
  313. sceneObject.ResumeScripts();
  314. }
  315. sceneContext.SceneObjects.Clear();
  316. }
  317. });
  318. m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
  319. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, dearchivedScenes.GetLoadedScenes(), m_errorMessage);
  320. }
  321. /// <summary>
  322. /// Searches through the files in the archive for the control file, and reads it.
  323. /// We must read the control file first, in order to know which regions are available.
  324. /// </summary>
  325. /// <remarks>
  326. /// In most cases the control file *is* first, since that's how we create archives. However,
  327. /// it's possible that someone rewrote the archive externally so we can't rely on this fact.
  328. /// </remarks>
  329. /// <param name="archive"></param>
  330. /// <param name="dearchivedScenes"></param>
  331. private void FindAndLoadControlFile(out TarArchiveReader archive, out DearchiveScenesInfo dearchivedScenes)
  332. {
  333. archive = new TarArchiveReader(m_loadStream);
  334. dearchivedScenes = new DearchiveScenesInfo();
  335. string filePath;
  336. byte[] data;
  337. TarArchiveReader.TarEntryType entryType;
  338. bool firstFile = true;
  339. while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
  340. {
  341. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  342. continue;
  343. if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  344. {
  345. LoadControlFile(filePath, data, dearchivedScenes);
  346. // Find which scenes are available in the simulator
  347. ArchiveScenesGroup simulatorScenes = new ArchiveScenesGroup();
  348. SceneManager.Instance.ForEachScene(delegate(Scene scene2)
  349. {
  350. simulatorScenes.AddScene(scene2);
  351. });
  352. simulatorScenes.CalcSceneLocations();
  353. dearchivedScenes.SetSimulatorScenes(m_rootScene, simulatorScenes);
  354. // If the control file wasn't the first file then reset the read pointer
  355. if (!firstFile)
  356. {
  357. m_log.Warn("Control file wasn't the first file in the archive");
  358. if (m_loadStream.CanSeek)
  359. {
  360. m_loadStream.Seek(0, SeekOrigin.Begin);
  361. }
  362. else if (m_loadPath != null)
  363. {
  364. archive.Close();
  365. archive = null;
  366. m_loadStream.Close();
  367. m_loadStream = null;
  368. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(m_loadPath), CompressionMode.Decompress);
  369. archive = new TarArchiveReader(m_loadStream);
  370. }
  371. else
  372. {
  373. // There isn't currently a scenario where this happens, but it's best to add a check just in case
  374. throw new Exception("Error reading archive: control file wasn't the first file, and the input stream doesn't allow seeking");
  375. }
  376. }
  377. return;
  378. }
  379. firstFile = false;
  380. }
  381. throw new Exception("Control file not found");
  382. }
  383. /// <summary>
  384. /// Load serialized scene objects.
  385. /// </summary>
  386. protected void LoadObjects(Scene scene, List<string> serialisedSceneObjects, List<SceneObjectGroup> sceneObjects)
  387. {
  388. // Reload serialized prims
  389. m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
  390. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, m_rotation);
  391. UUID oldTelehubUUID = scene.RegionInfo.RegionSettings.TelehubObject;
  392. IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
  393. int sceneObjectsLoadedCount = 0;
  394. foreach (string serialisedSceneObject in serialisedSceneObjects)
  395. {
  396. /*
  397. m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length);
  398. // Really large xml files (multi megabyte) appear to cause
  399. // memory problems
  400. // when loading the xml. But don't enable this check yet
  401. if (serialisedSceneObject.Length > 5000000)
  402. {
  403. m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);");
  404. continue;
  405. }
  406. */
  407. SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
  408. // Happily this does not do much to the object since it hasn't been added to the scene yet
  409. if (!sceneObject.IsAttachment)
  410. {
  411. if (m_displacement != Vector3.Zero || m_rotation != 0f)
  412. {
  413. Vector3 pos = sceneObject.AbsolutePosition;
  414. if (m_rotation != 0f)
  415. {
  416. // Rotate the object
  417. sceneObject.RootPart.RotationOffset = rot * sceneObject.GroupRotation;
  418. // Get object position relative to rotation axis
  419. Vector3 offset = pos - m_rotationCenter;
  420. // Rotate the object position
  421. offset *= rot;
  422. // Restore the object position back to relative to the region
  423. pos = m_rotationCenter + offset;
  424. }
  425. if (m_displacement != Vector3.Zero)
  426. {
  427. pos += m_displacement;
  428. }
  429. sceneObject.AbsolutePosition = pos;
  430. }
  431. }
  432. bool isTelehub = (sceneObject.UUID == oldTelehubUUID) && (oldTelehubUUID != UUID.Zero);
  433. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  434. // on the same region server and multiple examples a single object archive to be imported
  435. // to the same scene (when this is possible).
  436. sceneObject.ResetIDs();
  437. if (isTelehub)
  438. {
  439. // Change the Telehub Object to the new UUID
  440. scene.RegionInfo.RegionSettings.TelehubObject = sceneObject.UUID;
  441. scene.RegionInfo.RegionSettings.Save();
  442. oldTelehubUUID = UUID.Zero;
  443. }
  444. ModifySceneObject(scene, sceneObject);
  445. if (scene.AddRestoredSceneObject(sceneObject, true, false))
  446. {
  447. sceneObjectsLoadedCount++;
  448. sceneObject.CreateScriptInstances(0, false, scene.DefaultScriptEngine, 0);
  449. sceneObject.ResumeScripts();
  450. }
  451. }
  452. m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
  453. int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
  454. if (ignoredObjects > 0)
  455. m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
  456. if (oldTelehubUUID != UUID.Zero)
  457. {
  458. m_log.WarnFormat("Telehub object not found: {0}", oldTelehubUUID);
  459. scene.RegionInfo.RegionSettings.TelehubObject = UUID.Zero;
  460. scene.RegionInfo.RegionSettings.ClearSpawnPoints();
  461. }
  462. }
  463. /// <summary>
  464. /// Optionally modify a loaded SceneObjectGroup. Currently this just ensures that the
  465. /// User IDs and Group IDs are valid, but other manipulations could be done as well.
  466. /// </summary>
  467. private void ModifySceneObject(Scene scene, SceneObjectGroup sceneObject)
  468. {
  469. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  470. // or creator data is present. Otherwise, use the estate owner instead.
  471. foreach (SceneObjectPart part in sceneObject.Parts)
  472. {
  473. if (string.IsNullOrEmpty(part.CreatorData))
  474. {
  475. if (!ResolveUserUuid(scene, part.CreatorID))
  476. part.CreatorID = scene.RegionInfo.EstateSettings.EstateOwner;
  477. }
  478. if (UserManager != null)
  479. UserManager.AddUser(part.CreatorID, part.CreatorData);
  480. if (!(ResolveUserUuid(scene, part.OwnerID) || ResolveGroupUuid(part.OwnerID)))
  481. part.OwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  482. if (!(ResolveUserUuid(scene, part.LastOwnerID) || ResolveGroupUuid(part.LastOwnerID)))
  483. part.LastOwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  484. if (!ResolveGroupUuid(part.GroupID))
  485. part.GroupID = UUID.Zero;
  486. // And zap any troublesome sit target information
  487. // part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  488. // part.SitTargetPosition = new Vector3(0, 0, 0);
  489. // Fix ownership/creator of inventory items
  490. // Not doing so results in inventory items
  491. // being no copy/no mod for everyone
  492. lock (part.TaskInventory)
  493. {
  494. TaskInventoryDictionary inv = part.TaskInventory;
  495. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  496. {
  497. if (!(ResolveUserUuid(scene, kvp.Value.OwnerID) || ResolveGroupUuid(kvp.Value.OwnerID)))
  498. {
  499. kvp.Value.OwnerID = scene.RegionInfo.EstateSettings.EstateOwner;
  500. }
  501. if (string.IsNullOrEmpty(kvp.Value.CreatorData))
  502. {
  503. if (!ResolveUserUuid(scene, kvp.Value.CreatorID))
  504. kvp.Value.CreatorID = scene.RegionInfo.EstateSettings.EstateOwner;
  505. }
  506. if (UserManager != null)
  507. UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
  508. if (!ResolveGroupUuid(kvp.Value.GroupID))
  509. kvp.Value.GroupID = UUID.Zero;
  510. }
  511. }
  512. }
  513. }
  514. /// <summary>
  515. /// Load serialized parcels.
  516. /// </summary>
  517. /// <param name="scene"></param>
  518. /// <param name="serialisedParcels"></param>
  519. protected void LoadParcels(Scene scene, List<string> serialisedParcels)
  520. {
  521. // Reload serialized parcels
  522. m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
  523. List<LandData> landData = new List<LandData>();
  524. foreach (string serialisedParcel in serialisedParcels)
  525. {
  526. LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
  527. if (m_displacement != Vector3.Zero)
  528. {
  529. Vector3 parcelDisp = new Vector3(m_displacement.X, m_displacement.Y, 0f);
  530. parcel.AABBMin += parcelDisp;
  531. parcel.AABBMax += parcelDisp;
  532. }
  533. // Validate User and Group UUID's
  534. if (parcel.IsGroupOwned)
  535. {
  536. if (!ResolveGroupUuid(parcel.GroupID))
  537. {
  538. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  539. parcel.GroupID = UUID.Zero;
  540. parcel.IsGroupOwned = false;
  541. }
  542. }
  543. else
  544. {
  545. if (!ResolveUserUuid(scene, parcel.OwnerID))
  546. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  547. if (!ResolveGroupUuid(parcel.GroupID))
  548. parcel.GroupID = UUID.Zero;
  549. }
  550. List<LandAccessEntry> accessList = new List<LandAccessEntry>();
  551. foreach (LandAccessEntry entry in parcel.ParcelAccessList)
  552. {
  553. if (ResolveUserUuid(scene, entry.AgentID))
  554. accessList.Add(entry);
  555. // else, drop this access rule
  556. }
  557. parcel.ParcelAccessList = accessList;
  558. // m_log.DebugFormat(
  559. // "[ARCHIVER]: Adding parcel {0}, local id {1}, owner {2}, group {3}, isGroupOwned {4}, area {5}",
  560. // parcel.Name, parcel.LocalID, parcel.OwnerID, parcel.GroupID, parcel.IsGroupOwned, parcel.Area);
  561. landData.Add(parcel);
  562. }
  563. if (!m_merge)
  564. {
  565. bool setupDefaultParcel = (landData.Count == 0);
  566. scene.LandChannel.Clear(setupDefaultParcel);
  567. }
  568. scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
  569. m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
  570. }
  571. /// <summary>
  572. /// Look up the given user id to check whether it's one that is valid for this grid.
  573. /// </summary>
  574. /// <param name="scene"></param>
  575. /// <param name="uuid"></param>
  576. /// <returns></returns>
  577. private bool ResolveUserUuid(Scene scene, UUID uuid)
  578. {
  579. lock (m_validUserUuids)
  580. {
  581. if (!m_validUserUuids.ContainsKey(uuid))
  582. {
  583. // Note: we call GetUserAccount() inside the lock because this UserID is likely
  584. // to occur many times, and we only want to query the users service once.
  585. UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, uuid);
  586. m_validUserUuids.Add(uuid, account != null);
  587. }
  588. return m_validUserUuids[uuid];
  589. }
  590. }
  591. /// <summary>
  592. /// Look up the given group id to check whether it's one that is valid for this grid.
  593. /// </summary>
  594. /// <param name="uuid"></param>
  595. /// <returns></returns>
  596. private bool ResolveGroupUuid(UUID uuid)
  597. {
  598. lock (m_validGroupUuids)
  599. {
  600. if (!m_validGroupUuids.ContainsKey(uuid))
  601. {
  602. bool exists;
  603. if (m_groupsModule == null)
  604. {
  605. exists = false;
  606. }
  607. else
  608. {
  609. // Note: we call GetGroupRecord() inside the lock because this GroupID is likely
  610. // to occur many times, and we only want to query the groups service once.
  611. exists = (m_groupsModule.GetGroupRecord(uuid) != null);
  612. }
  613. m_validGroupUuids.Add(uuid, exists);
  614. }
  615. return m_validGroupUuids[uuid];
  616. }
  617. }
  618. /// Load an asset
  619. /// </summary>
  620. /// <param name="assetFilename"></param>
  621. /// <param name="data"></param>
  622. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  623. private bool LoadAsset(string assetPath, byte[] data)
  624. {
  625. // Right now we're nastily obtaining the UUID from the filename
  626. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  627. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  628. if (i == -1)
  629. {
  630. m_log.ErrorFormat(
  631. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  632. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  633. return false;
  634. }
  635. string extension = filename.Substring(i);
  636. string uuid = filename.Remove(filename.Length - extension.Length);
  637. if (m_assetService.GetMetadata(uuid) != null)
  638. {
  639. // m_log.DebugFormat("[ARCHIVER]: found existing asset {0}",uuid);
  640. return true;
  641. }
  642. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  643. {
  644. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  645. if (assetType == (sbyte)AssetType.Unknown)
  646. {
  647. m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  648. }
  649. else if (assetType == (sbyte)AssetType.Object)
  650. {
  651. data = SceneObjectSerializer.ModifySerializedObject(UUID.Parse(uuid), data,
  652. sog =>
  653. {
  654. ModifySceneObject(m_rootScene, sog);
  655. return true;
  656. });
  657. if (data == null)
  658. return false;
  659. }
  660. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  661. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
  662. asset.Data = data;
  663. // We're relying on the asset service to do the sensible thing and not store the asset if it already
  664. // exists.
  665. m_assetService.Store(asset);
  666. /**
  667. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  668. * it might be best done when dearchive takes place on a separate thread
  669. if (asset.Type=AssetType.Texture)
  670. {
  671. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  672. if (cacheLayerDecode != null)
  673. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  674. }
  675. */
  676. return true;
  677. }
  678. else
  679. {
  680. m_log.ErrorFormat(
  681. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  682. assetPath, extension);
  683. return false;
  684. }
  685. }
  686. /// <summary>
  687. /// Load region settings data
  688. /// </summary>
  689. /// <param name="scene"></param>
  690. /// <param name="settingsPath"></param>
  691. /// <param name="data"></param>
  692. /// <param name="dearchivedScenes"></param>
  693. /// <returns>
  694. /// true if settings were loaded successfully, false otherwise
  695. /// </returns>
  696. private bool LoadRegionSettings(Scene scene, string settingsPath, byte[] data, DearchiveScenesInfo dearchivedScenes)
  697. {
  698. RegionSettings loadedRegionSettings;
  699. try
  700. {
  701. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
  702. }
  703. catch (Exception e)
  704. {
  705. m_log.ErrorFormat(
  706. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  707. settingsPath, e);
  708. return false;
  709. }
  710. RegionSettings currentRegionSettings = scene.RegionInfo.RegionSettings;
  711. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  712. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  713. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  714. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  715. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  716. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  717. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  718. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  719. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  720. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  721. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  722. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  723. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  724. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  725. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  726. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  727. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  728. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  729. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  730. currentRegionSettings.SunPosition = loadedRegionSettings.SunPosition;
  731. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  732. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  733. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  734. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  735. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  736. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  737. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  738. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  739. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  740. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  741. currentRegionSettings.TelehubObject = loadedRegionSettings.TelehubObject;
  742. currentRegionSettings.ClearSpawnPoints();
  743. foreach (SpawnPoint sp in loadedRegionSettings.SpawnPoints())
  744. currentRegionSettings.AddSpawnPoint(sp);
  745. currentRegionSettings.LoadedCreationDateTime = dearchivedScenes.LoadedCreationDateTime;
  746. currentRegionSettings.LoadedCreationID = dearchivedScenes.GetOriginalRegionID(scene.RegionInfo.RegionID).ToString();
  747. currentRegionSettings.Save();
  748. scene.TriggerEstateSunUpdate();
  749. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  750. if (estateModule != null)
  751. estateModule.sendRegionHandshakeToAll();
  752. return true;
  753. }
  754. /// <summary>
  755. /// Load terrain data
  756. /// </summary>
  757. /// <param name="scene"></param>
  758. /// <param name="terrainPath"></param>
  759. /// <param name="data"></param>
  760. /// <returns>
  761. /// true if terrain was resolved successfully, false otherwise.
  762. /// </returns>
  763. private bool LoadTerrain(Scene scene, string terrainPath, byte[] data)
  764. {
  765. ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
  766. MemoryStream ms = new MemoryStream(data);
  767. if (m_displacement != Vector3.Zero || m_rotation != 0f)
  768. {
  769. Vector2 rotationCenter = new Vector2(m_rotationCenter.X, m_rotationCenter.Y);
  770. terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, rotationCenter, ms);
  771. }
  772. else
  773. {
  774. terrainModule.LoadFromStream(terrainPath, ms);
  775. }
  776. ms.Close();
  777. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  778. return true;
  779. }
  780. /// <summary>
  781. /// Load oar control file
  782. /// </summary>
  783. /// <param name="path"></param>
  784. /// <param name="data"></param>
  785. /// <param name="dearchivedScenes"></param>
  786. public DearchiveScenesInfo LoadControlFile(string path, byte[] data, DearchiveScenesInfo dearchivedScenes)
  787. {
  788. XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
  789. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  790. XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
  791. // Loaded metadata will be empty if no information exists in the archive
  792. dearchivedScenes.LoadedCreationDateTime = 0;
  793. dearchivedScenes.DefaultOriginalID = "";
  794. bool multiRegion = false;
  795. while (xtr.Read())
  796. {
  797. if (xtr.NodeType == XmlNodeType.Element)
  798. {
  799. if (xtr.Name.ToString() == "archive")
  800. {
  801. int majorVersion = int.Parse(xtr["major_version"]);
  802. int minorVersion = int.Parse(xtr["minor_version"]);
  803. string version = string.Format("{0}.{1}", majorVersion, minorVersion);
  804. if (majorVersion > MAX_MAJOR_VERSION)
  805. {
  806. throw new Exception(
  807. string.Format(
  808. "The OAR you are trying to load has major version number of {0} but this version of OpenSim can only load OARs with major version number {1} and below",
  809. majorVersion, MAX_MAJOR_VERSION));
  810. }
  811. m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version);
  812. }
  813. if (xtr.Name.ToString() == "datetime")
  814. {
  815. int value;
  816. if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
  817. dearchivedScenes.LoadedCreationDateTime = value;
  818. }
  819. else if (xtr.Name.ToString() == "row")
  820. {
  821. multiRegion = true;
  822. dearchivedScenes.StartRow();
  823. }
  824. else if (xtr.Name.ToString() == "region")
  825. {
  826. dearchivedScenes.StartRegion();
  827. }
  828. else if (xtr.Name.ToString() == "id")
  829. {
  830. string id = xtr.ReadElementContentAsString();
  831. dearchivedScenes.DefaultOriginalID = id;
  832. if (multiRegion)
  833. dearchivedScenes.SetRegionOriginalID(id);
  834. }
  835. else if (xtr.Name.ToString() == "dir")
  836. {
  837. dearchivedScenes.SetRegionDirectory(xtr.ReadElementContentAsString());
  838. }
  839. }
  840. }
  841. dearchivedScenes.MultiRegionFormat = multiRegion;
  842. if (!multiRegion)
  843. {
  844. // Add the single scene
  845. dearchivedScenes.StartRow();
  846. dearchivedScenes.StartRegion();
  847. dearchivedScenes.SetRegionOriginalID(dearchivedScenes.DefaultOriginalID);
  848. dearchivedScenes.SetRegionDirectory("");
  849. }
  850. ControlFileLoaded = true;
  851. return dearchivedScenes;
  852. }
  853. }
  854. }