MySQLFSAssetData.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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.Reflection;
  29. using System.Collections.Generic;
  30. using System.Data;
  31. using OpenSim.Framework;
  32. using OpenSim.Framework.Console;
  33. using log4net;
  34. using MySql.Data.MySqlClient;
  35. using OpenMetaverse;
  36. namespace OpenSim.Data.MySQL
  37. {
  38. public class MySQLFSAssetData : IFSAssetDataPlugin
  39. {
  40. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  41. protected string m_ConnectionString;
  42. protected string m_Table;
  43. /// <summary>
  44. /// Number of days that must pass before we update the access time on an asset when it has been fetched
  45. /// Config option to change this is "DaysBetweenAccessTimeUpdates"
  46. /// </summary>
  47. private int DaysBetweenAccessTimeUpdates = 0;
  48. protected virtual Assembly Assembly
  49. {
  50. get { return GetType().Assembly; }
  51. }
  52. public MySQLFSAssetData()
  53. {
  54. }
  55. #region IPlugin Members
  56. public string Version { get { return "1.0.0.0"; } }
  57. // Loads and initialises the MySQL storage plugin and checks for migrations
  58. public void Initialise(string connect, string realm, int UpdateAccessTime)
  59. {
  60. m_ConnectionString = connect;
  61. m_Table = realm;
  62. DaysBetweenAccessTimeUpdates = UpdateAccessTime;
  63. try
  64. {
  65. using (MySqlConnection conn = new MySqlConnection(m_ConnectionString))
  66. {
  67. conn.Open();
  68. Migration m = new Migration(conn, Assembly, "FSAssetStore");
  69. m.Update();
  70. }
  71. }
  72. catch (MySqlException e)
  73. {
  74. m_log.ErrorFormat("[FSASSETS]: Can't connect to database: {0}", e.Message.ToString());
  75. }
  76. }
  77. public void Initialise()
  78. {
  79. throw new NotImplementedException();
  80. }
  81. public void Dispose() { }
  82. public string Name
  83. {
  84. get { return "MySQL FSAsset storage engine"; }
  85. }
  86. #endregion
  87. private bool ExecuteNonQuery(MySqlCommand cmd)
  88. {
  89. using (MySqlConnection conn = new MySqlConnection(m_ConnectionString))
  90. {
  91. try
  92. {
  93. conn.Open();
  94. }
  95. catch (MySqlException e)
  96. {
  97. m_log.ErrorFormat("[FSASSETS]: Database open failed with {0}", e.ToString());
  98. return false;
  99. }
  100. cmd.Connection = conn;
  101. try
  102. {
  103. cmd.ExecuteNonQuery();
  104. }
  105. catch (MySqlException e)
  106. {
  107. m_log.ErrorFormat("[FSASSETS]: Query {0} failed with {1}", cmd.CommandText, e.ToString());
  108. return false;
  109. }
  110. }
  111. return true;
  112. }
  113. #region IFSAssetDataPlugin Members
  114. public AssetMetadata Get(string id, out string hash)
  115. {
  116. hash = String.Empty;
  117. AssetMetadata meta = new AssetMetadata();
  118. using (MySqlConnection conn = new MySqlConnection(m_ConnectionString))
  119. {
  120. try
  121. {
  122. conn.Open();
  123. }
  124. catch (MySqlException e)
  125. {
  126. m_log.ErrorFormat("[FSASSETS]: Database open failed with {0}", e.ToString());
  127. return null;
  128. }
  129. using (MySqlCommand cmd = conn.CreateCommand())
  130. {
  131. cmd.CommandText = String.Format("select id, name, description, type, hash, create_time, asset_flags, access_time from {0} where id = ?id", m_Table);
  132. cmd.Parameters.AddWithValue("?id", id);
  133. using (IDataReader reader = cmd.ExecuteReader())
  134. {
  135. if (!reader.Read())
  136. return null;
  137. hash = reader["hash"].ToString();
  138. meta.ID = id;
  139. meta.FullID = new UUID(id);
  140. meta.Name = reader["name"].ToString();
  141. meta.Description = reader["description"].ToString();
  142. meta.Type = (sbyte)Convert.ToInt32(reader["type"]);
  143. meta.ContentType = SLUtil.SLAssetTypeToContentType(meta.Type);
  144. meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"]));
  145. meta.Flags = (AssetFlags)Convert.ToInt32(reader["asset_flags"]);
  146. int AccessTime = Convert.ToInt32(reader["access_time"]);
  147. UpdateAccessTime(id, AccessTime);
  148. }
  149. }
  150. }
  151. return meta;
  152. }
  153. private void UpdateAccessTime(string AssetID, int AccessTime)
  154. {
  155. // Reduce DB work by only updating access time if asset hasn't recently been accessed
  156. // 0 By Default, Config option is "DaysBetweenAccessTimeUpdates"
  157. if (DaysBetweenAccessTimeUpdates > 0 && (DateTime.UtcNow - Utils.UnixTimeToDateTime(AccessTime)).TotalDays < DaysBetweenAccessTimeUpdates)
  158. return;
  159. using (MySqlConnection conn = new MySqlConnection(m_ConnectionString))
  160. {
  161. try
  162. {
  163. conn.Open();
  164. }
  165. catch (MySqlException e)
  166. {
  167. m_log.ErrorFormat("[FSASSETS]: Database open failed with {0}", e.ToString());
  168. return;
  169. }
  170. using (MySqlCommand cmd = conn.CreateCommand())
  171. {
  172. cmd.CommandText = String.Format("UPDATE {0} SET `access_time` = UNIX_TIMESTAMP() WHERE `id` = ?id", m_Table);
  173. cmd.Parameters.AddWithValue("?id", AssetID);
  174. cmd.ExecuteNonQuery();
  175. }
  176. }
  177. }
  178. public bool Store(AssetMetadata meta, string hash)
  179. {
  180. try
  181. {
  182. string oldhash;
  183. AssetMetadata existingAsset = Get(meta.ID, out oldhash);
  184. using (MySqlCommand cmd = new MySqlCommand())
  185. {
  186. cmd.Parameters.AddWithValue("?id", meta.ID);
  187. cmd.Parameters.AddWithValue("?name", meta.Name);
  188. cmd.Parameters.AddWithValue("?description", meta.Description);
  189. cmd.Parameters.AddWithValue("?type", meta.Type.ToString());
  190. cmd.Parameters.AddWithValue("?hash", hash);
  191. cmd.Parameters.AddWithValue("?asset_flags", meta.Flags);
  192. if (existingAsset == null)
  193. {
  194. cmd.CommandText = String.Format("insert into {0} (id, name, description, type, hash, asset_flags, create_time, access_time) values ( ?id, ?name, ?description, ?type, ?hash, ?asset_flags, UNIX_TIMESTAMP(), UNIX_TIMESTAMP())", m_Table);
  195. ExecuteNonQuery(cmd);
  196. return true;
  197. }
  198. //cmd.CommandText = String.Format("update {0} set hash = ?hash, access_time = UNIX_TIMESTAMP() where id = ?id", m_Table);
  199. //ExecuteNonQuery(cmd);
  200. }
  201. return false;
  202. }
  203. catch(Exception e)
  204. {
  205. m_log.Error("[FSAssets] Failed to store asset with ID " + meta.ID);
  206. m_log.Error(e.ToString());
  207. return false;
  208. }
  209. }
  210. /// <summary>
  211. /// Check if the assets exist in the database.
  212. /// </summary>
  213. /// <param name="uuids">The asset UUID's</param>
  214. /// <returns>For each asset: true if it exists, false otherwise</returns>
  215. public bool[] AssetsExist(UUID[] uuids)
  216. {
  217. if (uuids.Length == 0)
  218. return new bool[0];
  219. bool[] results = new bool[uuids.Length];
  220. for (int i = 0; i < uuids.Length; i++)
  221. results[i] = false;
  222. HashSet<UUID> exists = new HashSet<UUID>();
  223. string ids = "'" + string.Join("','", uuids) + "'";
  224. string sql = string.Format("select id from {1} where id in ({0})", ids, m_Table);
  225. using (MySqlConnection conn = new MySqlConnection(m_ConnectionString))
  226. {
  227. try
  228. {
  229. conn.Open();
  230. }
  231. catch (MySqlException e)
  232. {
  233. m_log.ErrorFormat("[FSASSETS]: Failed to open database: {0}", e.ToString());
  234. return results;
  235. }
  236. using (MySqlCommand cmd = conn.CreateCommand())
  237. {
  238. cmd.CommandText = sql;
  239. using (MySqlDataReader dbReader = cmd.ExecuteReader())
  240. {
  241. while (dbReader.Read())
  242. {
  243. UUID id = DBGuid.FromDB(dbReader["ID"]);
  244. exists.Add(id);
  245. }
  246. }
  247. }
  248. }
  249. for (int i = 0; i < uuids.Length; i++)
  250. results[i] = exists.Contains(uuids[i]);
  251. return results;
  252. }
  253. public int Count()
  254. {
  255. int count = 0;
  256. using (MySqlConnection conn = new MySqlConnection(m_ConnectionString))
  257. {
  258. try
  259. {
  260. conn.Open();
  261. }
  262. catch (MySqlException e)
  263. {
  264. m_log.ErrorFormat("[FSASSETS]: Failed to open database: {0}", e.ToString());
  265. return 0;
  266. }
  267. using(MySqlCommand cmd = conn.CreateCommand())
  268. {
  269. cmd.CommandText = String.Format("select count(*) as count from {0}",m_Table);
  270. using (IDataReader reader = cmd.ExecuteReader())
  271. {
  272. reader.Read();
  273. count = Convert.ToInt32(reader["count"]);
  274. }
  275. }
  276. }
  277. return count;
  278. }
  279. public bool Delete(string id)
  280. {
  281. using(MySqlCommand cmd = new MySqlCommand())
  282. {
  283. cmd.CommandText = String.Format("delete from {0} where id = ?id",m_Table);
  284. cmd.Parameters.AddWithValue("?id", id);
  285. ExecuteNonQuery(cmd);
  286. }
  287. return true;
  288. }
  289. public void Import(string conn, string table, int start, int count, bool force, FSStoreDelegate store)
  290. {
  291. int imported = 0;
  292. using (MySqlConnection importConn = new MySqlConnection(conn))
  293. {
  294. try
  295. {
  296. importConn.Open();
  297. }
  298. catch (MySqlException e)
  299. {
  300. m_log.ErrorFormat("[FSASSETS]: Can't connect to database: {0}",
  301. e.Message.ToString());
  302. return;
  303. }
  304. using (MySqlCommand cmd = importConn.CreateCommand())
  305. {
  306. string limit = String.Empty;
  307. if (count != -1)
  308. {
  309. limit = String.Format(" limit {0},{1}", start, count);
  310. }
  311. cmd.CommandText = String.Format("select * from {0}{1}", table, limit);
  312. MainConsole.Instance.Output("Querying database");
  313. using (IDataReader reader = cmd.ExecuteReader())
  314. {
  315. MainConsole.Instance.Output("Reading data");
  316. while (reader.Read())
  317. {
  318. if ((imported % 100) == 0)
  319. {
  320. MainConsole.Instance.Output(String.Format("{0} assets imported so far", imported));
  321. }
  322. AssetBase asset = new AssetBase();
  323. AssetMetadata meta = new AssetMetadata();
  324. meta.ID = reader["id"].ToString();
  325. meta.FullID = new UUID(meta.ID);
  326. meta.Name = reader["name"].ToString();
  327. meta.Description = reader["description"].ToString();
  328. meta.Type = (sbyte)Convert.ToInt32(reader["assetType"]);
  329. meta.ContentType = SLUtil.SLAssetTypeToContentType(meta.Type);
  330. meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"]));
  331. asset.Metadata = meta;
  332. asset.Data = (byte[])reader["data"];
  333. store(asset, force);
  334. imported++;
  335. }
  336. }
  337. }
  338. }
  339. MainConsole.Instance.Output(String.Format("Import done, {0} assets imported", imported));
  340. }
  341. #endregion
  342. }
  343. }