MySQLAssetData.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 OpenSim 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 log4net;
  31. using MySql.Data.MySqlClient;
  32. using OpenMetaverse;
  33. using OpenSim.Framework;
  34. namespace OpenSim.Data.MySQL
  35. {
  36. /// <summary>
  37. /// A MySQL Interface for the Asset Server
  38. /// </summary>
  39. public class MySQLAssetData : AssetDataBase
  40. {
  41. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  42. private MySQLManager _dbConnection;
  43. private long TicksToEpoch;
  44. #region IPlugin Members
  45. /// <summary>
  46. /// <para>Initialises Asset interface</para>
  47. /// <para>
  48. /// <list type="bullet">
  49. /// <item>Loads and initialises the MySQL storage plugin.</item>
  50. /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
  51. /// <item>Check for migration</item>
  52. /// </list>
  53. /// </para>
  54. /// </summary>
  55. /// <param name="connect">connect string</param>
  56. override public void Initialise(string connect)
  57. {
  58. TicksToEpoch = new DateTime(1970,1,1).Ticks;
  59. // TODO: This will let you pass in the connect string in
  60. // the config, though someone will need to write that.
  61. if (connect == String.Empty)
  62. {
  63. // This is old seperate config file
  64. m_log.Warn("no connect string, using old mysql_connection.ini instead");
  65. Initialise();
  66. }
  67. else
  68. {
  69. _dbConnection = new MySQLManager(connect);
  70. }
  71. // This actually does the roll forward assembly stuff
  72. Assembly assem = GetType().Assembly;
  73. Migration m = new Migration(_dbConnection.Connection, assem, "AssetStore");
  74. m.Update();
  75. }
  76. /// <summary>
  77. /// <para>Initialises Asset interface</para>
  78. /// <para>
  79. /// <list type="bullet">
  80. /// <item>Loads and initialises the MySQL storage plugin</item>
  81. /// <item>uses the obsolete mysql_connection.ini</item>
  82. /// </list>
  83. /// </para>
  84. /// </summary>
  85. /// <remarks>DEPRECATED and shouldn't be used</remarks>
  86. public override void Initialise()
  87. {
  88. IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini");
  89. string hostname = GridDataMySqlFile.ParseFileReadValue("hostname");
  90. string database = GridDataMySqlFile.ParseFileReadValue("database");
  91. string username = GridDataMySqlFile.ParseFileReadValue("username");
  92. string password = GridDataMySqlFile.ParseFileReadValue("password");
  93. string pooling = GridDataMySqlFile.ParseFileReadValue("pooling");
  94. string port = GridDataMySqlFile.ParseFileReadValue("port");
  95. _dbConnection = new MySQLManager(hostname, database, username, password, pooling, port);
  96. }
  97. public override void Dispose() { }
  98. #region IAssetDataPlugin Members
  99. /// <summary>
  100. /// Fetch Asset <paramref name="assetID"/> from database
  101. /// </summary>
  102. /// <param name="assetID">Asset UUID to fetch</param>
  103. /// <returns>Return the asset</returns>
  104. /// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
  105. override public AssetBase FetchAsset(UUID assetID)
  106. {
  107. AssetBase asset = null;
  108. lock (_dbConnection)
  109. {
  110. _dbConnection.CheckConnection();
  111. MySqlCommand cmd =
  112. new MySqlCommand(
  113. "SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id",
  114. _dbConnection.Connection);
  115. cmd.Parameters.AddWithValue("?id", assetID.ToString());
  116. try
  117. {
  118. using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
  119. {
  120. if (dbReader.Read())
  121. {
  122. asset = new AssetBase();
  123. asset.Data = (byte[]) dbReader["data"];
  124. asset.Description = (string) dbReader["description"];
  125. asset.FullID = assetID;
  126. try
  127. {
  128. asset.Local = (bool)dbReader["local"];
  129. }
  130. catch (InvalidCastException)
  131. {
  132. asset.Local = false;
  133. }
  134. asset.Name = (string) dbReader["name"];
  135. asset.Type = (sbyte) dbReader["assetType"];
  136. }
  137. dbReader.Close();
  138. cmd.Dispose();
  139. }
  140. if (asset != null)
  141. UpdateAccessTime(asset);
  142. }
  143. catch (Exception e)
  144. {
  145. m_log.ErrorFormat(
  146. "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
  147. + Environment.NewLine + "Reconnecting", assetID);
  148. _dbConnection.Reconnect();
  149. }
  150. }
  151. return asset;
  152. }
  153. /// <summary>
  154. /// Create an asset in database, or update it if existing.
  155. /// </summary>
  156. /// <param name="asset">Asset UUID to create</param>
  157. /// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
  158. override public void CreateAsset(AssetBase asset)
  159. {
  160. lock (_dbConnection)
  161. {
  162. //m_log.Info("[ASSET DB]: Creating Asset " + Util.ToRawUuidString(asset.FullID));
  163. if (ExistsAsset(asset.FullID))
  164. {
  165. //m_log.Info("[ASSET DB]: Asset exists already, ignoring.");
  166. return;
  167. }
  168. _dbConnection.CheckConnection();
  169. MySqlCommand cmd =
  170. new MySqlCommand(
  171. "insert INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, data)" +
  172. "VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?data)",
  173. _dbConnection.Connection);
  174. // need to ensure we dispose
  175. try
  176. {
  177. using (cmd)
  178. {
  179. // create unix epoch time
  180. int now = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000);
  181. cmd.Parameters.AddWithValue("?id", asset.ID);
  182. cmd.Parameters.AddWithValue("?name", asset.Name);
  183. cmd.Parameters.AddWithValue("?description", asset.Description);
  184. cmd.Parameters.AddWithValue("?assetType", asset.Type);
  185. cmd.Parameters.AddWithValue("?local", asset.Local);
  186. cmd.Parameters.AddWithValue("?temporary", asset.Temporary);
  187. cmd.Parameters.AddWithValue("?create_time", now);
  188. cmd.Parameters.AddWithValue("?access_time", now);
  189. cmd.Parameters.AddWithValue("?data", asset.Data);
  190. cmd.ExecuteNonQuery();
  191. cmd.Dispose();
  192. }
  193. }
  194. catch (Exception e)
  195. {
  196. m_log.ErrorFormat(
  197. "[ASSETS DB]: " +
  198. "MySql failure creating asset {0} with name {1}" + Environment.NewLine + e.ToString()
  199. + Environment.NewLine + "Attempting reconnection", asset.FullID, asset.Name);
  200. _dbConnection.Reconnect();
  201. }
  202. }
  203. }
  204. private void UpdateAccessTime(AssetBase asset)
  205. {
  206. lock (_dbConnection)
  207. {
  208. _dbConnection.CheckConnection();
  209. MySqlCommand cmd =
  210. new MySqlCommand("update assets set access_time=?access_time where id=?id",
  211. _dbConnection.Connection);
  212. // need to ensure we dispose
  213. try
  214. {
  215. using (cmd)
  216. {
  217. // create unix epoch time
  218. int now = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000);
  219. cmd.Parameters.AddWithValue("?id", asset.ID);
  220. cmd.Parameters.AddWithValue("?access_time", now);
  221. cmd.ExecuteNonQuery();
  222. cmd.Dispose();
  223. }
  224. }
  225. catch (Exception e)
  226. {
  227. m_log.ErrorFormat(
  228. "[ASSETS DB]: " +
  229. "MySql failure updating access_time for asset {0} with name {1}" + Environment.NewLine + e.ToString()
  230. + Environment.NewLine + "Attempting reconnection", asset.FullID, asset.Name);
  231. _dbConnection.Reconnect();
  232. }
  233. }
  234. }
  235. /// <summary>
  236. /// Update a asset in database, see <see cref="CreateAsset"/>
  237. /// </summary>
  238. /// <param name="asset">Asset UUID to update</param>
  239. override public void UpdateAsset(AssetBase asset)
  240. {
  241. CreateAsset(asset);
  242. }
  243. /// <summary>
  244. /// check if the asset UUID exist in database
  245. /// </summary>
  246. /// <param name="uuid">The asset UUID</param>
  247. /// <returns>true if exist.</returns>
  248. override public bool ExistsAsset(UUID uuid)
  249. {
  250. bool assetExists = false;
  251. lock (_dbConnection)
  252. {
  253. _dbConnection.CheckConnection();
  254. MySqlCommand cmd =
  255. new MySqlCommand(
  256. "SELECT id FROM assets WHERE id=?id",
  257. _dbConnection.Connection);
  258. cmd.Parameters.AddWithValue("?id", uuid.ToString());
  259. try
  260. {
  261. using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
  262. {
  263. if (dbReader.Read())
  264. {
  265. assetExists = true;
  266. }
  267. dbReader.Close();
  268. cmd.Dispose();
  269. }
  270. }
  271. catch (Exception e)
  272. {
  273. m_log.ErrorFormat(
  274. "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
  275. + Environment.NewLine + "Attempting reconnection", uuid);
  276. _dbConnection.Reconnect();
  277. }
  278. }
  279. return assetExists;
  280. }
  281. #endregion
  282. /// <summary>
  283. /// Database provider version
  284. /// </summary>
  285. override public string Version
  286. {
  287. get { return _dbConnection.getVersion(); }
  288. }
  289. /// <summary>
  290. /// The name of this DB provider
  291. /// </summary>
  292. override public string Name
  293. {
  294. get { return "MySQL Asset storage engine"; }
  295. }
  296. #endregion
  297. }
  298. }