MySQLAssetData.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.Data;
  29. using System.Reflection;
  30. using System.Collections.Generic;
  31. using log4net;
  32. using MySql.Data.MySqlClient;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Data;
  36. namespace OpenSim.Data.MySQL
  37. {
  38. /// <summary>
  39. /// A MySQL Interface for the Asset Server
  40. /// </summary>
  41. public class MySQLAssetData : AssetDataBase
  42. {
  43. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  44. private string m_connectionString;
  45. protected virtual Assembly Assembly
  46. {
  47. get { return GetType().Assembly; }
  48. }
  49. #region IPlugin Members
  50. public override string Version { get { return "1.0.0.0"; } }
  51. /// <summary>
  52. /// <para>Initialises Asset interface</para>
  53. /// <para>
  54. /// <list type="bullet">
  55. /// <item>Loads and initialises the MySQL storage plugin.</item>
  56. /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
  57. /// <item>Check for migration</item>
  58. /// </list>
  59. /// </para>
  60. /// </summary>
  61. /// <param name="connect">connect string</param>
  62. public override void Initialise(string connect)
  63. {
  64. m_connectionString = connect;
  65. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  66. {
  67. dbcon.Open();
  68. Migration m = new Migration(dbcon, Assembly, "AssetStore");
  69. m.Update();
  70. }
  71. }
  72. public override void Initialise()
  73. {
  74. throw new NotImplementedException();
  75. }
  76. public override void Dispose() { }
  77. /// <summary>
  78. /// The name of this DB provider
  79. /// </summary>
  80. override public string Name
  81. {
  82. get { return "MySQL Asset storage engine"; }
  83. }
  84. #endregion
  85. #region IAssetDataPlugin Members
  86. /// <summary>
  87. /// Fetch Asset <paramref name="assetID"/> from database
  88. /// </summary>
  89. /// <param name="assetID">Asset UUID to fetch</param>
  90. /// <returns>Return the asset</returns>
  91. /// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
  92. override public AssetBase GetAsset(UUID assetID)
  93. {
  94. AssetBase asset = null;
  95. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  96. {
  97. dbcon.Open();
  98. using (MySqlCommand cmd = new MySqlCommand(
  99. "SELECT name, description, assetType, local, temporary, asset_flags, CreatorID, data FROM assets WHERE id=?id",
  100. dbcon))
  101. {
  102. cmd.Parameters.AddWithValue("?id", assetID.ToString());
  103. try
  104. {
  105. using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
  106. {
  107. if (dbReader.Read())
  108. {
  109. asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"], dbReader["CreatorID"].ToString());
  110. asset.Data = (byte[])dbReader["data"];
  111. asset.Description = (string)dbReader["description"];
  112. string local = dbReader["local"].ToString();
  113. if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
  114. asset.Local = true;
  115. else
  116. asset.Local = false;
  117. asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
  118. asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
  119. }
  120. }
  121. }
  122. catch (Exception e)
  123. {
  124. m_log.Error(
  125. string.Format("[ASSETS DB]: MySql failure fetching asset {0}. Exception ", assetID), e);
  126. }
  127. }
  128. }
  129. return asset;
  130. }
  131. /// <summary>
  132. /// Create an asset in database, or update it if existing.
  133. /// </summary>
  134. /// <param name="asset">Asset UUID to create</param>
  135. /// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
  136. override public void StoreAsset(AssetBase asset)
  137. {
  138. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  139. {
  140. dbcon.Open();
  141. using (MySqlCommand cmd =
  142. new MySqlCommand(
  143. "replace INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, asset_flags, CreatorID, data)" +
  144. "VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?asset_flags, ?CreatorID, ?data)",
  145. dbcon))
  146. {
  147. string assetName = asset.Name;
  148. if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
  149. {
  150. assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
  151. m_log.WarnFormat(
  152. "[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
  153. asset.Name, asset.ID, asset.Name.Length, assetName.Length);
  154. }
  155. string assetDescription = asset.Description;
  156. if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
  157. {
  158. assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
  159. m_log.WarnFormat(
  160. "[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
  161. asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
  162. }
  163. try
  164. {
  165. using (cmd)
  166. {
  167. // create unix epoch time
  168. int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
  169. cmd.Parameters.AddWithValue("?id", asset.ID);
  170. cmd.Parameters.AddWithValue("?name", assetName);
  171. cmd.Parameters.AddWithValue("?description", assetDescription);
  172. cmd.Parameters.AddWithValue("?assetType", asset.Type);
  173. cmd.Parameters.AddWithValue("?local", asset.Local);
  174. cmd.Parameters.AddWithValue("?temporary", asset.Temporary);
  175. cmd.Parameters.AddWithValue("?create_time", now);
  176. cmd.Parameters.AddWithValue("?access_time", now);
  177. cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID);
  178. cmd.Parameters.AddWithValue("?asset_flags", (int)asset.Flags);
  179. cmd.Parameters.AddWithValue("?data", asset.Data);
  180. cmd.ExecuteNonQuery();
  181. }
  182. }
  183. catch (Exception e)
  184. {
  185. m_log.Error(
  186. string.Format(
  187. "[ASSET DB]: MySQL failure creating asset {0} with name {1}. Exception ",
  188. asset.FullID, asset.Name)
  189. , e);
  190. }
  191. }
  192. }
  193. }
  194. private void UpdateAccessTime(AssetBase asset)
  195. {
  196. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  197. {
  198. dbcon.Open();
  199. using (MySqlCommand cmd
  200. = new MySqlCommand("update assets set access_time=?access_time where id=?id", dbcon))
  201. {
  202. try
  203. {
  204. using (cmd)
  205. {
  206. // create unix epoch time
  207. int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
  208. cmd.Parameters.AddWithValue("?id", asset.ID);
  209. cmd.Parameters.AddWithValue("?access_time", now);
  210. cmd.ExecuteNonQuery();
  211. }
  212. }
  213. catch (Exception e)
  214. {
  215. m_log.Error(
  216. string.Format(
  217. "[ASSETS DB]: Failure updating access_time for asset {0} with name {1}. Exception ",
  218. asset.FullID, asset.Name),
  219. e);
  220. }
  221. }
  222. }
  223. }
  224. /// <summary>
  225. /// Check if the assets exist in the database.
  226. /// </summary>
  227. /// <param name="uuidss">The assets' IDs</param>
  228. /// <returns>For each asset: true if it exists, false otherwise</returns>
  229. public override bool[] AssetsExist(UUID[] uuids)
  230. {
  231. if (uuids.Length == 0)
  232. return new bool[0];
  233. HashSet<UUID> exist = new HashSet<UUID>();
  234. string ids = "'" + string.Join("','", uuids) + "'";
  235. string sql = string.Format("SELECT id FROM assets WHERE id IN ({0})", ids);
  236. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  237. {
  238. dbcon.Open();
  239. using (MySqlCommand cmd = new MySqlCommand(sql, dbcon))
  240. {
  241. using (MySqlDataReader dbReader = cmd.ExecuteReader())
  242. {
  243. while (dbReader.Read())
  244. {
  245. UUID id = DBGuid.FromDB(dbReader["id"]);
  246. exist.Add(id);
  247. }
  248. }
  249. }
  250. }
  251. bool[] results = new bool[uuids.Length];
  252. for (int i = 0; i < uuids.Length; i++)
  253. results[i] = exist.Contains(uuids[i]);
  254. return results;
  255. }
  256. /// <summary>
  257. /// Returns a list of AssetMetadata objects. The list is a subset of
  258. /// the entire data set offset by <paramref name="start" /> containing
  259. /// <paramref name="count" /> elements.
  260. /// </summary>
  261. /// <param name="start">The number of results to discard from the total data set.</param>
  262. /// <param name="count">The number of rows the returned list should contain.</param>
  263. /// <returns>A list of AssetMetadata objects.</returns>
  264. public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
  265. {
  266. List<AssetMetadata> retList = new List<AssetMetadata>(count);
  267. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  268. {
  269. dbcon.Open();
  270. using (MySqlCommand cmd
  271. = new MySqlCommand(
  272. "SELECT name,description,assetType,temporary,id,asset_flags,CreatorID FROM assets LIMIT ?start, ?count",
  273. dbcon))
  274. {
  275. cmd.Parameters.AddWithValue("?start", start);
  276. cmd.Parameters.AddWithValue("?count", count);
  277. try
  278. {
  279. using (MySqlDataReader dbReader = cmd.ExecuteReader())
  280. {
  281. while (dbReader.Read())
  282. {
  283. AssetMetadata metadata = new AssetMetadata();
  284. metadata.Name = (string)dbReader["name"];
  285. metadata.Description = (string)dbReader["description"];
  286. metadata.Type = (sbyte)dbReader["assetType"];
  287. metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]); // Not sure if this is correct.
  288. metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
  289. metadata.FullID = DBGuid.FromDB(dbReader["id"]);
  290. metadata.CreatorID = dbReader["CreatorID"].ToString();
  291. // Current SHA1s are not stored/computed.
  292. metadata.SHA1 = new byte[] { };
  293. retList.Add(metadata);
  294. }
  295. }
  296. }
  297. catch (Exception e)
  298. {
  299. m_log.Error(
  300. string.Format(
  301. "[ASSETS DB]: MySql failure fetching asset set from {0}, count {1}. Exception ",
  302. start, count),
  303. e);
  304. }
  305. }
  306. }
  307. return retList;
  308. }
  309. public override bool Delete(string id)
  310. {
  311. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  312. {
  313. dbcon.Open();
  314. using (MySqlCommand cmd = new MySqlCommand("delete from assets where id=?id", dbcon))
  315. {
  316. cmd.Parameters.AddWithValue("?id", id);
  317. cmd.ExecuteNonQuery();
  318. }
  319. }
  320. return true;
  321. }
  322. #endregion
  323. }
  324. }