MySQLFSAssetData.cs 13 KB

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