ArchiveReadRequest.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 OpenSim 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.Xml;
  33. using System.Net;
  34. using OpenMetaverse;
  35. using log4net;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Communications.Cache;
  38. using OpenSim.Region.Environment.Interfaces;
  39. using OpenSim.Region.Environment.Scenes;
  40. using OpenSim.Region.Environment.Modules.World.Terrain;
  41. namespace OpenSim.Region.Environment.Modules.World.Archiver
  42. {
  43. /// <summary>
  44. /// Handles an individual archive read request
  45. /// </summary>
  46. public class ArchiveReadRequest
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private static System.Text.ASCIIEncoding m_asciiEncoding = new System.Text.ASCIIEncoding();
  50. private Scene m_scene;
  51. private string m_loadPath;
  52. /// <summary>
  53. /// Used to cache lookups for valid uuids.
  54. /// </summary>
  55. private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
  56. public ArchiveReadRequest(Scene scene, string loadPath)
  57. {
  58. m_scene = scene;
  59. m_loadPath = loadPath;
  60. DearchiveRegion();
  61. }
  62. private void DearchiveRegion()
  63. {
  64. TarArchiveReader archive
  65. = new TarArchiveReader(
  66. new GZipStream(GetStream(m_loadPath), CompressionMode.Decompress));
  67. //AssetsDearchiver dearchiver = new AssetsDearchiver(m_scene.AssetCache);
  68. List<string> serialisedSceneObjects = new List<string>();
  69. string filePath = "ERROR";
  70. int successfulAssetRestores = 0;
  71. int failedAssetRestores = 0;
  72. byte[] data;
  73. while ((data = archive.ReadEntry(out filePath)) != null)
  74. {
  75. //m_log.DebugFormat(
  76. // "[ARCHIVER]: Successfully read {0} ({1} bytes)}", filePath, data.Length);
  77. if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
  78. {
  79. serialisedSceneObjects.Add(m_asciiEncoding.GetString(data));
  80. }
  81. // else if (filePath.Equals(ArchiveConstants.ASSETS_METADATA_PATH))
  82. // {
  83. // string xml = m_asciiEncoding.GetString(data);
  84. // dearchiver.AddAssetMetadata(xml);
  85. // }
  86. else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
  87. {
  88. if (LoadAsset(filePath, data))
  89. successfulAssetRestores++;
  90. else
  91. failedAssetRestores++;
  92. }
  93. else if (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH))
  94. {
  95. LoadTerrain(filePath, data);
  96. }
  97. }
  98. //m_log.Debug("[ARCHIVER]: Reached end of archive");
  99. archive.Close();
  100. m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
  101. if (failedAssetRestores > 0)
  102. m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
  103. m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
  104. m_scene.DeleteAllSceneObjects();
  105. // Reload serialized prims
  106. m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
  107. IRegionSerialiserModule serialiser = m_scene.RequestModuleInterface<IRegionSerialiserModule>();
  108. ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
  109. foreach (string serialisedSceneObject in serialisedSceneObjects)
  110. {
  111. SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
  112. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  113. // on the same region server and multiple examples a single object archive to be imported
  114. // to the same scene (when this is possible).
  115. sceneObject.ResetIDs();
  116. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  117. // otherwise, use the master avatar uuid instead
  118. UUID masterAvatarId = m_scene.RegionInfo.MasterAvatarAssignedUUID;
  119. if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero)
  120. masterAvatarId = m_scene.RegionInfo.EstateSettings.EstateOwner;
  121. foreach (SceneObjectPart part in sceneObject.Children.Values)
  122. {
  123. if (!resolveUserUuid(part.CreatorID))
  124. part.CreatorID = masterAvatarId;
  125. if (!resolveUserUuid(part.OwnerID))
  126. part.OwnerID = masterAvatarId;
  127. if (!resolveUserUuid(part.LastOwnerID))
  128. part.LastOwnerID = masterAvatarId;
  129. // And zap any troublesome sit target information
  130. part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  131. part.SitTargetPosition = new Vector3(0, 0, 0);
  132. // Fix ownership/creator of inventory items
  133. // Not doing so results in inventory items
  134. // being no copy/no mod for everyone
  135. TaskInventoryDictionary inv = part.TaskInventory;
  136. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  137. {
  138. if (!resolveUserUuid(kvp.Value.OwnerID))
  139. {
  140. kvp.Value.OwnerID = masterAvatarId;
  141. }
  142. if (!resolveUserUuid(kvp.Value.CreatorID))
  143. {
  144. kvp.Value.CreatorID = masterAvatarId;
  145. }
  146. }
  147. }
  148. if (m_scene.AddRestoredSceneObject(sceneObject, true, false))
  149. {
  150. sceneObjects.Add(sceneObject);
  151. }
  152. }
  153. m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjects.Count);
  154. int ignoredObjects = serialisedSceneObjects.Count - sceneObjects.Count;
  155. if (ignoredObjects > 0)
  156. m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
  157. m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
  158. m_log.Debug("[ARCHIVER]: Starting scripts");
  159. foreach (SceneObjectGroup sceneObject in sceneObjects)
  160. {
  161. sceneObject.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 0);
  162. }
  163. }
  164. /// <summary>
  165. /// Look up the given user id to check whether it's one that is valid for this grid.
  166. /// </summary>
  167. /// <param name="uuid"></param>
  168. /// <returns></returns>
  169. private bool resolveUserUuid(UUID uuid)
  170. {
  171. if (!m_validUserUuids.ContainsKey(uuid))
  172. {
  173. CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(uuid);
  174. if (profile != null && profile.UserProfile != null)
  175. m_validUserUuids.Add(uuid, true);
  176. else
  177. m_validUserUuids.Add(uuid, false);
  178. }
  179. if (m_validUserUuids[uuid])
  180. return true;
  181. else
  182. return false;
  183. }
  184. /// <summary>
  185. /// Load an asset
  186. /// </summary>
  187. /// <param name="assetFilename"></param>
  188. /// <param name="data"></param>
  189. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  190. private bool LoadAsset(string assetPath, byte[] data)
  191. {
  192. // Right now we're nastily obtaining the UUID from the filename
  193. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  194. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  195. if (i == -1)
  196. {
  197. m_log.ErrorFormat(
  198. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  199. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  200. return false;
  201. }
  202. string extension = filename.Substring(i);
  203. string uuid = filename.Remove(filename.Length - extension.Length);
  204. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  205. {
  206. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  207. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  208. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty);
  209. asset.Type = assetType;
  210. asset.Data = data;
  211. m_scene.AssetCache.AddAsset(asset);
  212. return true;
  213. }
  214. else
  215. {
  216. m_log.ErrorFormat(
  217. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  218. assetPath, extension);
  219. return false;
  220. }
  221. }
  222. /// <summary>
  223. /// Load terrain data
  224. /// </summary>
  225. /// <param name="terrainPath"></param>
  226. /// <param name="data"></param>
  227. /// <returns>
  228. /// true if terrain was resolved successfully, false otherwise.
  229. /// </returns>
  230. private bool LoadTerrain(string terrainPath, byte[] data)
  231. {
  232. ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>();
  233. MemoryStream ms = new MemoryStream(data);
  234. terrainModule.LoadFromStream(terrainPath, ms);
  235. ms.Close();
  236. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  237. return true;
  238. }
  239. /// <summary>
  240. /// Resolve path to a working FileStream
  241. /// </summary>
  242. private Stream GetStream(string path)
  243. {
  244. try
  245. {
  246. if (File.Exists(path))
  247. {
  248. return new FileStream(path, FileMode.Open);
  249. }
  250. else
  251. {
  252. Uri uri = new Uri(path); // throw exception if not valid URI
  253. if (uri.Scheme == "file")
  254. {
  255. return new FileStream(uri.AbsolutePath, FileMode.Open);
  256. }
  257. else
  258. {
  259. if (uri.Scheme != "http")
  260. throw new Exception(String.Format("Unsupported URI scheme ({0})", path));
  261. // OK, now we know we have an HTTP URI to work with
  262. return URIFetch(uri);
  263. }
  264. }
  265. }
  266. catch (Exception e)
  267. {
  268. throw new Exception(String.Format("Unable to create file input stream for {0}: {1}", path, e));
  269. }
  270. }
  271. private static Stream URIFetch(Uri uri)
  272. {
  273. HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
  274. // request.Credentials = credentials;
  275. request.ContentLength = 0;
  276. WebResponse response = request.GetResponse();
  277. Stream file = response.GetResponseStream();
  278. if (response.ContentType != "application/x-oar")
  279. throw new Exception(String.Format("{0} does not identify an OAR file", uri.ToString()));
  280. if (response.ContentLength == 0)
  281. throw new Exception(String.Format("{0} returned an empty file", uri.ToString()));
  282. // return new BufferedStream(file, (int) response.ContentLength);
  283. return new BufferedStream(file, 1000000);
  284. }
  285. }
  286. }