MySQLXAssetData.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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.Data;
  30. using System.IO;
  31. using System.IO.Compression;
  32. using System.Reflection;
  33. using System.Security.Cryptography;
  34. using System.Text;
  35. using log4net;
  36. using MySql.Data.MySqlClient;
  37. using OpenMetaverse;
  38. using OpenSim.Framework;
  39. using OpenSim.Data;
  40. namespace OpenSim.Data.MySQL
  41. {
  42. public class MySQLXAssetData : IXAssetDataPlugin
  43. {
  44. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  45. protected virtual Assembly Assembly
  46. {
  47. get { return GetType().Assembly; }
  48. }
  49. /// <summary>
  50. /// Number of days that must pass before we update the access time on an asset when it has been fetched.
  51. /// </summary>
  52. private const int DaysBetweenAccessTimeUpdates = 30;
  53. private bool m_enableCompression = false;
  54. private string m_connectionString;
  55. private object m_dbLock = new object();
  56. /// <summary>
  57. /// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock
  58. /// </summary>
  59. private HashAlgorithm hasher = new SHA256CryptoServiceProvider();
  60. #region IPlugin Members
  61. public string Version { get { return "1.0.0.0"; } }
  62. /// <summary>
  63. /// <para>Initialises Asset interface</para>
  64. /// <para>
  65. /// <list type="bullet">
  66. /// <item>Loads and initialises the MySQL storage plugin.</item>
  67. /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
  68. /// <item>Check for migration</item>
  69. /// </list>
  70. /// </para>
  71. /// </summary>
  72. /// <param name="connect">connect string</param>
  73. public void Initialise(string connect)
  74. {
  75. m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
  76. m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
  77. m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
  78. m_log.ErrorFormat("[MYSQL XASSETDATA]: THIS PLUGIN IS STRICTLY EXPERIMENTAL.");
  79. m_log.ErrorFormat("[MYSQL XASSETDATA]: DO NOT USE FOR ANY DATA THAT YOU DO NOT MIND LOSING.");
  80. m_log.ErrorFormat("[MYSQL XASSETDATA]: DATABASE TABLES CAN CHANGE AT ANY TIME, CAUSING EXISTING DATA TO BE LOST.");
  81. m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
  82. m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
  83. m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************");
  84. m_connectionString = connect;
  85. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  86. {
  87. dbcon.Open();
  88. Migration m = new Migration(dbcon, Assembly, "XAssetStore");
  89. m.Update();
  90. }
  91. }
  92. public void Initialise()
  93. {
  94. throw new NotImplementedException();
  95. }
  96. public void Dispose() { }
  97. /// <summary>
  98. /// The name of this DB provider
  99. /// </summary>
  100. public string Name
  101. {
  102. get { return "MySQL XAsset storage engine"; }
  103. }
  104. #endregion
  105. #region IAssetDataPlugin Members
  106. /// <summary>
  107. /// Fetch Asset <paramref name="assetID"/> from database
  108. /// </summary>
  109. /// <param name="assetID">Asset UUID to fetch</param>
  110. /// <returns>Return the asset</returns>
  111. /// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
  112. public AssetBase GetAsset(UUID assetID)
  113. {
  114. // m_log.DebugFormat("[MYSQL XASSET DATA]: Looking for asset {0}", assetID);
  115. AssetBase asset = null;
  116. lock (m_dbLock)
  117. {
  118. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  119. {
  120. dbcon.Open();
  121. using (MySqlCommand cmd = new MySqlCommand(
  122. "SELECT Name, Description, AccessTime, AssetType, Local, Temporary, AssetFlags, CreatorID, Data FROM XAssetsMeta JOIN XAssetsData ON XAssetsMeta.Hash = XAssetsData.Hash WHERE ID=?ID",
  123. dbcon))
  124. {
  125. cmd.Parameters.AddWithValue("?ID", assetID.ToString());
  126. try
  127. {
  128. using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
  129. {
  130. if (dbReader.Read())
  131. {
  132. asset = new AssetBase(assetID, (string)dbReader["Name"], (sbyte)dbReader["AssetType"], dbReader["CreatorID"].ToString());
  133. asset.Data = (byte[])dbReader["Data"];
  134. asset.Description = (string)dbReader["Description"];
  135. string local = dbReader["Local"].ToString();
  136. if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
  137. asset.Local = true;
  138. else
  139. asset.Local = false;
  140. asset.Temporary = Convert.ToBoolean(dbReader["Temporary"]);
  141. asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]);
  142. if (m_enableCompression)
  143. {
  144. using (GZipStream decompressionStream = new GZipStream(new MemoryStream(asset.Data), CompressionMode.Decompress))
  145. {
  146. MemoryStream outputStream = new MemoryStream();
  147. WebUtil.CopyStream(decompressionStream, outputStream, int.MaxValue);
  148. // int compressedLength = asset.Data.Length;
  149. asset.Data = outputStream.ToArray();
  150. // m_log.DebugFormat(
  151. // "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}",
  152. // asset.ID, asset.Name, asset.Data.Length, compressedLength);
  153. }
  154. }
  155. UpdateAccessTime(asset.Metadata, (int)dbReader["AccessTime"]);
  156. }
  157. }
  158. }
  159. catch (Exception e)
  160. {
  161. m_log.Error(string.Format("[MYSQL XASSET DATA]: Failure fetching asset {0}", assetID), e);
  162. }
  163. }
  164. }
  165. }
  166. return asset;
  167. }
  168. /// <summary>
  169. /// Create an asset in database, or update it if existing.
  170. /// </summary>
  171. /// <param name="asset">Asset UUID to create</param>
  172. /// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
  173. public void StoreAsset(AssetBase asset)
  174. {
  175. // m_log.DebugFormat("[XASSETS DB]: Storing asset {0} {1}", asset.Name, asset.ID);
  176. lock (m_dbLock)
  177. {
  178. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  179. {
  180. dbcon.Open();
  181. using (MySqlTransaction transaction = dbcon.BeginTransaction())
  182. {
  183. string assetName = asset.Name;
  184. if (asset.Name.Length > 64)
  185. {
  186. assetName = asset.Name.Substring(0, 64);
  187. m_log.WarnFormat(
  188. "[XASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
  189. asset.Name, asset.ID, asset.Name.Length, assetName.Length);
  190. }
  191. string assetDescription = asset.Description;
  192. if (asset.Description.Length > 64)
  193. {
  194. assetDescription = asset.Description.Substring(0, 64);
  195. m_log.WarnFormat(
  196. "[XASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
  197. asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
  198. }
  199. if (m_enableCompression)
  200. {
  201. MemoryStream outputStream = new MemoryStream();
  202. using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, false))
  203. {
  204. // Console.WriteLine(WebUtil.CopyTo(new MemoryStream(asset.Data), compressionStream, int.MaxValue));
  205. // We have to close the compression stream in order to make sure it writes everything out to the underlying memory output stream.
  206. compressionStream.Close();
  207. byte[] compressedData = outputStream.ToArray();
  208. asset.Data = compressedData;
  209. }
  210. }
  211. byte[] hash = hasher.ComputeHash(asset.Data);
  212. // m_log.DebugFormat(
  213. // "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}",
  214. // asset.ID, asset.Name, hash, compressedData.Length);
  215. try
  216. {
  217. using (MySqlCommand cmd =
  218. new MySqlCommand(
  219. "replace INTO XAssetsMeta(ID, Hash, Name, Description, AssetType, Local, Temporary, CreateTime, AccessTime, AssetFlags, CreatorID)" +
  220. "VALUES(?ID, ?Hash, ?Name, ?Description, ?AssetType, ?Local, ?Temporary, ?CreateTime, ?AccessTime, ?AssetFlags, ?CreatorID)",
  221. dbcon))
  222. {
  223. // create unix epoch time
  224. int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
  225. cmd.Parameters.AddWithValue("?ID", asset.ID);
  226. cmd.Parameters.AddWithValue("?Hash", hash);
  227. cmd.Parameters.AddWithValue("?Name", assetName);
  228. cmd.Parameters.AddWithValue("?Description", assetDescription);
  229. cmd.Parameters.AddWithValue("?AssetType", asset.Type);
  230. cmd.Parameters.AddWithValue("?Local", asset.Local);
  231. cmd.Parameters.AddWithValue("?Temporary", asset.Temporary);
  232. cmd.Parameters.AddWithValue("?CreateTime", now);
  233. cmd.Parameters.AddWithValue("?AccessTime", now);
  234. cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID);
  235. cmd.Parameters.AddWithValue("?AssetFlags", (int)asset.Flags);
  236. cmd.ExecuteNonQuery();
  237. }
  238. }
  239. catch (Exception e)
  240. {
  241. m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset metadata {0} with name \"{1}\". Error: {2}",
  242. asset.FullID, asset.Name, e.Message);
  243. transaction.Rollback();
  244. return;
  245. }
  246. if (!ExistsData(dbcon, transaction, hash))
  247. {
  248. try
  249. {
  250. using (MySqlCommand cmd =
  251. new MySqlCommand(
  252. "INSERT INTO XAssetsData(Hash, Data) VALUES(?Hash, ?Data)",
  253. dbcon))
  254. {
  255. cmd.Parameters.AddWithValue("?Hash", hash);
  256. cmd.Parameters.AddWithValue("?Data", asset.Data);
  257. cmd.ExecuteNonQuery();
  258. }
  259. }
  260. catch (Exception e)
  261. {
  262. m_log.ErrorFormat("[XASSET DB]: MySQL failure creating asset data {0} with name \"{1}\". Error: {2}",
  263. asset.FullID, asset.Name, e.Message);
  264. transaction.Rollback();
  265. return;
  266. }
  267. }
  268. transaction.Commit();
  269. }
  270. }
  271. }
  272. }
  273. /// <summary>
  274. /// Updates the access time of the asset if it was accessed above a given threshhold amount of time.
  275. /// </summary>
  276. /// <remarks>
  277. /// This gives us some insight into assets which haven't ben accessed for a long period. This is only done
  278. /// over the threshold time to avoid excessive database writes as assets are fetched.
  279. /// </remarks>
  280. /// <param name='asset'></param>
  281. /// <param name='accessTime'></param>
  282. private void UpdateAccessTime(AssetMetadata assetMetadata, int accessTime)
  283. {
  284. DateTime now = DateTime.UtcNow;
  285. if ((now - Utils.UnixTimeToDateTime(accessTime)).TotalDays < DaysBetweenAccessTimeUpdates)
  286. return;
  287. lock (m_dbLock)
  288. {
  289. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  290. {
  291. dbcon.Open();
  292. MySqlCommand cmd =
  293. new MySqlCommand("update XAssetsMeta set AccessTime=?AccessTime where ID=?ID", dbcon);
  294. try
  295. {
  296. using (cmd)
  297. {
  298. // create unix epoch time
  299. cmd.Parameters.AddWithValue("?ID", assetMetadata.ID);
  300. cmd.Parameters.AddWithValue("?AccessTime", (int)Utils.DateTimeToUnixTime(now));
  301. cmd.ExecuteNonQuery();
  302. }
  303. }
  304. catch (Exception e)
  305. {
  306. m_log.ErrorFormat(
  307. "[XASSET MYSQL DB]: Failure updating access_time for asset {0} with name {1}",
  308. assetMetadata.ID, assetMetadata.Name);
  309. }
  310. }
  311. }
  312. }
  313. /// <summary>
  314. /// We assume we already have the m_dbLock.
  315. /// </summary>
  316. /// TODO: need to actually use the transaction.
  317. /// <param name="dbcon"></param>
  318. /// <param name="transaction"></param>
  319. /// <param name="hash"></param>
  320. /// <returns></returns>
  321. private bool ExistsData(MySqlConnection dbcon, MySqlTransaction transaction, byte[] hash)
  322. {
  323. // m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid);
  324. bool exists = false;
  325. using (MySqlCommand cmd = new MySqlCommand("SELECT Hash FROM XAssetsData WHERE Hash=?Hash", dbcon))
  326. {
  327. cmd.Parameters.AddWithValue("?Hash", hash);
  328. try
  329. {
  330. using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
  331. {
  332. if (dbReader.Read())
  333. {
  334. // m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid);
  335. exists = true;
  336. }
  337. }
  338. }
  339. catch (Exception e)
  340. {
  341. m_log.ErrorFormat(
  342. "[XASSETS DB]: MySql failure in ExistsData fetching hash {0}. Exception {1}{2}",
  343. hash, e.Message, e.StackTrace);
  344. }
  345. }
  346. return exists;
  347. }
  348. /// <summary>
  349. /// Check if the asset exists in the database
  350. /// </summary>
  351. /// <param name="uuid">The asset UUID</param>
  352. /// <returns>true if it exists, false otherwise.</returns>
  353. public bool ExistsAsset(UUID uuid)
  354. {
  355. // m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid);
  356. bool assetExists = false;
  357. lock (m_dbLock)
  358. {
  359. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  360. {
  361. dbcon.Open();
  362. using (MySqlCommand cmd = new MySqlCommand("SELECT ID FROM XAssetsMeta WHERE ID=?ID", dbcon))
  363. {
  364. cmd.Parameters.AddWithValue("?ID", uuid.ToString());
  365. try
  366. {
  367. using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
  368. {
  369. if (dbReader.Read())
  370. {
  371. // m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid);
  372. assetExists = true;
  373. }
  374. }
  375. }
  376. catch (Exception e)
  377. {
  378. m_log.Error(string.Format("[XASSETS DB]: MySql failure fetching asset {0}", uuid), e);
  379. }
  380. }
  381. }
  382. }
  383. return assetExists;
  384. }
  385. /// <summary>
  386. /// Returns a list of AssetMetadata objects. The list is a subset of
  387. /// the entire data set offset by <paramref name="start" /> containing
  388. /// <paramref name="count" /> elements.
  389. /// </summary>
  390. /// <param name="start">The number of results to discard from the total data set.</param>
  391. /// <param name="count">The number of rows the returned list should contain.</param>
  392. /// <returns>A list of AssetMetadata objects.</returns>
  393. public List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
  394. {
  395. List<AssetMetadata> retList = new List<AssetMetadata>(count);
  396. lock (m_dbLock)
  397. {
  398. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  399. {
  400. dbcon.Open();
  401. MySqlCommand cmd = new MySqlCommand("SELECT Name, Description, AccessTime, AssetType, Temporary, ID, AssetFlags, CreatorID FROM XAssetsMeta LIMIT ?start, ?count", dbcon);
  402. cmd.Parameters.AddWithValue("?start", start);
  403. cmd.Parameters.AddWithValue("?count", count);
  404. try
  405. {
  406. using (MySqlDataReader dbReader = cmd.ExecuteReader())
  407. {
  408. while (dbReader.Read())
  409. {
  410. AssetMetadata metadata = new AssetMetadata();
  411. metadata.Name = (string)dbReader["Name"];
  412. metadata.Description = (string)dbReader["Description"];
  413. metadata.Type = (sbyte)dbReader["AssetType"];
  414. metadata.Temporary = Convert.ToBoolean(dbReader["Temporary"]); // Not sure if this is correct.
  415. metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]);
  416. metadata.FullID = DBGuid.FromDB(dbReader["ID"]);
  417. metadata.CreatorID = dbReader["CreatorID"].ToString();
  418. // We'll ignore this for now - it appears unused!
  419. // metadata.SHA1 = dbReader["hash"]);
  420. UpdateAccessTime(metadata, (int)dbReader["AccessTime"]);
  421. retList.Add(metadata);
  422. }
  423. }
  424. }
  425. catch (Exception e)
  426. {
  427. m_log.Error("[XASSETS DB]: MySql failure fetching asset set" + Environment.NewLine + e.ToString());
  428. }
  429. }
  430. }
  431. return retList;
  432. }
  433. public bool Delete(string id)
  434. {
  435. // m_log.DebugFormat("[XASSETS DB]: Deleting asset {0}", id);
  436. lock (m_dbLock)
  437. {
  438. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  439. {
  440. dbcon.Open();
  441. using (MySqlCommand cmd = new MySqlCommand("delete from XAssetsMeta where ID=?ID", dbcon))
  442. {
  443. cmd.Parameters.AddWithValue("?ID", id);
  444. cmd.ExecuteNonQuery();
  445. }
  446. // TODO: How do we deal with data from deleted assets? Probably not easily reapable unless we
  447. // keep a reference count (?)
  448. }
  449. }
  450. return true;
  451. }
  452. #endregion
  453. }
  454. }