MySQLXAssetData.cs 22 KB

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