MySQLXAssetData.cs 23 KB

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