MySQLAssetData.cs 13 KB

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