InventoryArchiveWriteRequest.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.IO.Compression;
  31. using System.Reflection;
  32. using System.Xml;
  33. using log4net;
  34. using OpenMetaverse;
  35. using OpenSim.Framework;
  36. using OpenSim.Framework.Serialization;
  37. using OpenSim.Framework.Serialization.External;
  38. using OpenSim.Framework.Communications;
  39. using OpenSim.Framework.Communications.Cache;
  40. using OpenSim.Framework.Communications.Osp;
  41. using OpenSim.Region.CoreModules.World.Archiver;
  42. using OpenSim.Region.Framework.Scenes;
  43. namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
  44. {
  45. public class InventoryArchiveWriteRequest
  46. {
  47. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  48. /// <value>
  49. /// Used to select all inventory nodes in a folder but not the folder itself
  50. /// </value>
  51. private const string STAR_WILDCARD = "*";
  52. private InventoryArchiverModule m_module;
  53. private CachedUserInfo m_userInfo;
  54. private string m_invPath;
  55. protected TarArchiveWriter m_archiveWriter;
  56. protected UuidGatherer m_assetGatherer;
  57. /// <value>
  58. /// We only use this to request modules
  59. /// </value>
  60. protected Scene m_scene;
  61. /// <value>
  62. /// ID of this request
  63. /// </value>
  64. protected Guid m_id;
  65. /// <value>
  66. /// Used to collect the uuids of the assets that we need to save into the archive
  67. /// </value>
  68. protected Dictionary<UUID, int> m_assetUuids = new Dictionary<UUID, int>();
  69. /// <value>
  70. /// Used to collect the uuids of the users that we need to save into the archive
  71. /// </value>
  72. protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>();
  73. /// <value>
  74. /// The stream to which the inventory archive will be saved.
  75. /// </value>
  76. private Stream m_saveStream;
  77. /// <summary>
  78. /// Constructor
  79. /// </summary>
  80. public InventoryArchiveWriteRequest(
  81. Guid id, InventoryArchiverModule module, Scene scene,
  82. CachedUserInfo userInfo, string invPath, string savePath)
  83. : this(
  84. id,
  85. module,
  86. scene,
  87. userInfo,
  88. invPath,
  89. new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress))
  90. {
  91. }
  92. /// <summary>
  93. /// Constructor
  94. /// </summary>
  95. public InventoryArchiveWriteRequest(
  96. Guid id, InventoryArchiverModule module, Scene scene,
  97. CachedUserInfo userInfo, string invPath, Stream saveStream)
  98. {
  99. m_id = id;
  100. m_module = module;
  101. m_scene = scene;
  102. m_userInfo = userInfo;
  103. m_invPath = invPath;
  104. m_saveStream = saveStream;
  105. m_assetGatherer = new UuidGatherer(m_scene.AssetService);
  106. }
  107. protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids)
  108. {
  109. Exception reportedException = null;
  110. bool succeeded = true;
  111. try
  112. {
  113. // We're almost done. Just need to write out the control file now
  114. m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, Create0p1ControlFile());
  115. m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");
  116. m_archiveWriter.Close();
  117. }
  118. catch (Exception e)
  119. {
  120. m_saveStream.Close();
  121. reportedException = e;
  122. succeeded = false;
  123. }
  124. m_module.TriggerInventoryArchiveSaved(
  125. m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException);
  126. }
  127. protected void SaveInvItem(InventoryItemBase inventoryItem, string path)
  128. {
  129. string filename = path + CreateArchiveItemName(inventoryItem);
  130. // Record the creator of this item for user record purposes (which might go away soon)
  131. m_userUuids[inventoryItem.CreatorIdAsUuid] = 1;
  132. InventoryItemBase saveItem = (InventoryItemBase)inventoryItem.Clone();
  133. saveItem.CreatorId = OspResolver.MakeOspa(saveItem.CreatorIdAsUuid, m_scene.CommsManager);
  134. string serialization = UserInventoryItemSerializer.Serialize(saveItem);
  135. m_archiveWriter.WriteFile(filename, serialization);
  136. m_assetGatherer.GatherAssetUuids(saveItem.AssetID, (AssetType)saveItem.AssetType, m_assetUuids);
  137. }
  138. /// <summary>
  139. /// Save an inventory folder
  140. /// </summary>
  141. /// <param name="inventoryFolder">The inventory folder to save</param>
  142. /// <param name="path">The path to which the folder should be saved</param>
  143. /// <param name="saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param>
  144. protected void SaveInvFolder(InventoryFolderBase inventoryFolder, string path, bool saveThisFolderItself)
  145. {
  146. if (saveThisFolderItself)
  147. {
  148. path += CreateArchiveFolderName(inventoryFolder);
  149. // We need to make sure that we record empty folders
  150. m_archiveWriter.WriteDir(path);
  151. }
  152. InventoryCollection contents
  153. = m_scene.InventoryService.GetFolderContent(inventoryFolder.Owner, inventoryFolder.ID);
  154. //List<InventoryFolderImpl> childFolders = inventoryFolder.RequestListOfFolderImpls();
  155. //List<InventoryItemBase> items = inventoryFolder.RequestListOfItems();
  156. /*
  157. Dictionary identicalFolderNames = new Dictionary<string, int>();
  158. foreach (InventoryFolderImpl folder in inventories)
  159. {
  160. if (!identicalFolderNames.ContainsKey(folder.Name))
  161. identicalFolderNames[folder.Name] = 0;
  162. else
  163. identicalFolderNames[folder.Name] = identicalFolderNames[folder.Name]++;
  164. int folderNameNumber = identicalFolderName[folder.Name];
  165. SaveInvDir(
  166. folder,
  167. string.Format(
  168. "{0}{1}{2}/",
  169. path, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, folderNameNumber));
  170. }
  171. */
  172. foreach (InventoryFolderBase childFolder in contents.Folders)
  173. {
  174. SaveInvFolder(childFolder, path, true);
  175. }
  176. foreach (InventoryItemBase item in contents.Items)
  177. {
  178. SaveInvItem(item, path);
  179. }
  180. }
  181. /// <summary>
  182. /// Execute the inventory write request
  183. /// </summary>
  184. public void Execute()
  185. {
  186. InventoryFolderBase inventoryFolder = null;
  187. InventoryItemBase inventoryItem = null;
  188. InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.UserProfile.ID);
  189. bool foundStar = false;
  190. // Eliminate double slashes and any leading / on the path.
  191. string[] components
  192. = m_invPath.Split(
  193. new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries);
  194. int maxComponentIndex = components.Length - 1;
  195. // If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the
  196. // folder itself. This may get more sophisicated later on
  197. if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD)
  198. {
  199. foundStar = true;
  200. maxComponentIndex--;
  201. }
  202. m_invPath = String.Empty;
  203. for (int i = 0; i <= maxComponentIndex; i++)
  204. {
  205. m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER;
  206. }
  207. // Annoyingly Split actually returns the original string if the input string consists only of delimiters
  208. // Therefore if we still start with a / after the split, then we need the root folder
  209. if (m_invPath.Length == 0)
  210. {
  211. inventoryFolder = rootFolder;
  212. }
  213. else
  214. {
  215. m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER));
  216. inventoryFolder
  217. = InventoryArchiveUtils.FindFolderByPath(m_scene.InventoryService, rootFolder, m_invPath);
  218. //inventoryFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath);
  219. }
  220. // The path may point to an item instead
  221. if (inventoryFolder == null)
  222. {
  223. inventoryItem = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, rootFolder, m_invPath);
  224. //inventoryItem = m_userInfo.RootFolder.FindItemByPath(m_invPath);
  225. }
  226. if (null == inventoryFolder && null == inventoryItem)
  227. {
  228. // We couldn't find the path indicated
  229. string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath);
  230. m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", errorMessage);
  231. m_module.TriggerInventoryArchiveSaved(
  232. m_id, false, m_userInfo, m_invPath, m_saveStream,
  233. new Exception(errorMessage));
  234. return;
  235. }
  236. m_archiveWriter = new TarArchiveWriter(m_saveStream);
  237. try
  238. {
  239. if (inventoryFolder != null)
  240. {
  241. m_log.DebugFormat(
  242. "[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}",
  243. inventoryFolder.Name, inventoryFolder.ID, m_invPath);
  244. //recurse through all dirs getting dirs and files
  245. SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !foundStar);
  246. }
  247. else if (inventoryItem != null)
  248. {
  249. m_log.DebugFormat(
  250. "[INVENTORY ARCHIVER]: Found item {0} {1} at {2}",
  251. inventoryItem.Name, inventoryItem.ID, m_invPath);
  252. SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH);
  253. }
  254. // Don't put all this profile information into the archive right now.
  255. //SaveUsers();
  256. }
  257. catch (Exception)
  258. {
  259. m_archiveWriter.Close();
  260. throw;
  261. }
  262. new AssetsRequest(
  263. new AssetsArchiver(m_archiveWriter), m_assetUuids.Keys,
  264. m_scene.AssetService, ReceivedAllAssets).Execute();
  265. }
  266. /// <summary>
  267. /// Save information for the users that we've collected.
  268. /// </summary>
  269. protected void SaveUsers()
  270. {
  271. m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count);
  272. foreach (UUID creatorId in m_userUuids.Keys)
  273. {
  274. // Record the creator of this item
  275. CachedUserInfo creator
  276. = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(creatorId);
  277. if (creator != null)
  278. {
  279. m_archiveWriter.WriteFile(
  280. ArchiveConstants.USERS_PATH + creator.UserProfile.Name + ".xml",
  281. UserProfileSerializer.Serialize(creator.UserProfile));
  282. }
  283. else
  284. {
  285. m_log.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId);
  286. }
  287. }
  288. }
  289. /// <summary>
  290. /// Create the archive name for a particular folder.
  291. /// </summary>
  292. ///
  293. /// These names are prepended with an inventory folder's UUID so that more than one folder can have the
  294. /// same name
  295. ///
  296. /// <param name="folder"></param>
  297. /// <returns></returns>
  298. public static string CreateArchiveFolderName(InventoryFolderBase folder)
  299. {
  300. return CreateArchiveFolderName(folder.Name, folder.ID);
  301. }
  302. /// <summary>
  303. /// Create the archive name for a particular item.
  304. /// </summary>
  305. ///
  306. /// These names are prepended with an inventory item's UUID so that more than one item can have the
  307. /// same name
  308. ///
  309. /// <param name="item"></param>
  310. /// <returns></returns>
  311. public static string CreateArchiveItemName(InventoryItemBase item)
  312. {
  313. return CreateArchiveItemName(item.Name, item.ID);
  314. }
  315. /// <summary>
  316. /// Create an archive folder name given its constituent components
  317. /// </summary>
  318. /// <param name="name"></param>
  319. /// <param name="id"></param>
  320. /// <returns></returns>
  321. public static string CreateArchiveFolderName(string name, UUID id)
  322. {
  323. return string.Format(
  324. "{0}{1}{2}/",
  325. InventoryArchiveUtils.EscapeArchivePath(name),
  326. ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
  327. id);
  328. }
  329. /// <summary>
  330. /// Create an archive item name given its constituent components
  331. /// </summary>
  332. /// <param name="name"></param>
  333. /// <param name="id"></param>
  334. /// <returns></returns>
  335. public static string CreateArchiveItemName(string name, UUID id)
  336. {
  337. return string.Format(
  338. "{0}{1}{2}.xml",
  339. InventoryArchiveUtils.EscapeArchivePath(name),
  340. ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
  341. id);
  342. }
  343. /// <summary>
  344. /// Create the control file for a 0.1 version archive
  345. /// </summary>
  346. /// <returns></returns>
  347. public static string Create0p1ControlFile()
  348. {
  349. StringWriter sw = new StringWriter();
  350. XmlTextWriter xtw = new XmlTextWriter(sw);
  351. xtw.Formatting = Formatting.Indented;
  352. xtw.WriteStartDocument();
  353. xtw.WriteStartElement("archive");
  354. xtw.WriteAttributeString("major_version", "0");
  355. xtw.WriteAttributeString("minor_version", "1");
  356. xtw.WriteEndElement();
  357. xtw.Flush();
  358. xtw.Close();
  359. String s = sw.ToString();
  360. sw.Close();
  361. return s;
  362. }
  363. }
  364. }