MySQLXAssetData.cs 23 KB

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