SvnBackupModule.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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.Collections.Generic;
  29. using System.IO;
  30. using System.Reflection;
  31. using System.Timers;
  32. using log4net;
  33. using Nini.Config;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using OpenSim.Region.CoreModules.World.Serialiser;
  36. using OpenSim.Region.CoreModules.World.Terrain;
  37. using OpenSim.Region.Framework.Scenes;
  38. using PumaCode.SvnDotNet.AprSharp;
  39. using PumaCode.SvnDotNet.SubversionSharp;
  40. using Slash = System.IO.Path;
  41. namespace OpenSim.Region.Modules.SvnSerialiser
  42. {
  43. public class SvnBackupModule : IRegionModule
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. private readonly List<Scene> m_scenes = new List<Scene>();
  47. private readonly Timer m_timer = new Timer();
  48. private bool m_enabled = false;
  49. private bool m_installBackupOnLoad = false;
  50. private IRegionSerialiserModule m_serialiser;
  51. private bool m_svnAutoSave = false;
  52. private SvnClient m_svnClient;
  53. private string m_svndir = "SVNmodule" + Slash.DirectorySeparatorChar + "repo";
  54. private string m_svnpass = "password";
  55. private TimeSpan m_svnperiod = new TimeSpan(0, 0, 15, 0, 0);
  56. private string m_svnurl = "svn://insert.Your.svn/here/";
  57. private string m_svnuser = "username";
  58. #region SvnModule Core
  59. /// <summary>
  60. /// Exports a specified scene to the SVN repo directory, then commits.
  61. /// </summary>
  62. /// <param name="scene">The scene to export</param>
  63. public void SaveRegion(Scene scene)
  64. {
  65. List<string> svnfilenames = CreateAndAddExport(scene);
  66. m_svnClient.Commit3(svnfilenames, true, false);
  67. m_log.Info("[SVNBACKUP]: Region backup successful (" + scene.RegionInfo.RegionName + ").");
  68. }
  69. /// <summary>
  70. /// Saves all registered scenes to the SVN repo, then commits.
  71. /// </summary>
  72. public void SaveAllRegions()
  73. {
  74. List<string> svnfilenames = new List<string>();
  75. List<string> regions = new List<string>();
  76. foreach (Scene scene in m_scenes)
  77. {
  78. svnfilenames.AddRange(CreateAndAddExport(scene));
  79. regions.Add("'" + scene.RegionInfo.RegionName + "' ");
  80. }
  81. m_svnClient.Commit3(svnfilenames, true, false);
  82. m_log.Info("[SVNBACKUP]: Server backup successful (" + String.Concat(regions.ToArray()) + ").");
  83. }
  84. private List<string> CreateAndAddExport(Scene scene)
  85. {
  86. m_log.Info("[SVNBACKUP]: Saving a region to SVN with name " + scene.RegionInfo.RegionName);
  87. List<string> filenames = m_serialiser.SerialiseRegion(scene, m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID + Slash.DirectorySeparatorChar);
  88. try
  89. {
  90. m_svnClient.Add3(m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID, true, false, false);
  91. }
  92. catch (SvnException)
  93. {
  94. }
  95. List<string> svnfilenames = new List<string>();
  96. foreach (string filename in filenames)
  97. svnfilenames.Add(m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID + Slash.DirectorySeparatorChar + filename);
  98. svnfilenames.Add(m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID);
  99. return svnfilenames;
  100. }
  101. public void LoadRegion(Scene scene)
  102. {
  103. IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
  104. if (serialiser != null)
  105. {
  106. serialiser.LoadPrimsFromXml2(
  107. scene,
  108. m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID
  109. + Slash.DirectorySeparatorChar + "objects.xml");
  110. scene.RequestModuleInterface<ITerrainModule>().LoadFromFile(
  111. m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID
  112. + Slash.DirectorySeparatorChar + "heightmap.r32");
  113. m_log.Info("[SVNBACKUP]: Region load successful (" + scene.RegionInfo.RegionName + ").");
  114. }
  115. else
  116. {
  117. m_log.ErrorFormat(
  118. "[SVNBACKUP]: Region load of {0} failed - no serialisation module available",
  119. scene.RegionInfo.RegionName);
  120. }
  121. }
  122. private void CheckoutSvn()
  123. {
  124. m_svnClient.Checkout2(m_svnurl, m_svndir, Svn.Revision.Head, Svn.Revision.Head, true, false);
  125. }
  126. private void CheckoutSvn(SvnRevision revision)
  127. {
  128. m_svnClient.Checkout2(m_svnurl, m_svndir, revision, revision, true, false);
  129. }
  130. // private void CheckoutSvnPartial(string subdir)
  131. // {
  132. // if (!Directory.Exists(m_svndir + Slash.DirectorySeparatorChar + subdir))
  133. // Directory.CreateDirectory(m_svndir + Slash.DirectorySeparatorChar + subdir);
  134. // m_svnClient.Checkout2(m_svnurl + "/" + subdir, m_svndir, Svn.Revision.Head, Svn.Revision.Head, true, false);
  135. // }
  136. // private void CheckoutSvnPartial(string subdir, SvnRevision revision)
  137. // {
  138. // if (!Directory.Exists(m_svndir + Slash.DirectorySeparatorChar + subdir))
  139. // Directory.CreateDirectory(m_svndir + Slash.DirectorySeparatorChar + subdir);
  140. // m_svnClient.Checkout2(m_svnurl + "/" + subdir, m_svndir, revision, revision, true, false);
  141. // }
  142. #endregion
  143. #region SvnDotNet Callbacks
  144. private SvnError SimpleAuth(out SvnAuthCredSimple svnCredentials, IntPtr baton,
  145. AprString realm, AprString username, bool maySave, AprPool pool)
  146. {
  147. svnCredentials = SvnAuthCredSimple.Alloc(pool);
  148. svnCredentials.Username = new AprString(m_svnuser, pool);
  149. svnCredentials.Password = new AprString(m_svnpass, pool);
  150. svnCredentials.MaySave = false;
  151. return SvnError.NoError;
  152. }
  153. private SvnError GetCommitLogCallback(out AprString logMessage, out SvnPath tmpFile, AprArray commitItems, IntPtr baton, AprPool pool)
  154. {
  155. if (!commitItems.IsNull)
  156. {
  157. foreach (SvnClientCommitItem2 item in commitItems)
  158. {
  159. m_log.Debug("[SVNBACKUP]: ... " + Path.GetFileName(item.Path.ToString()) + " (" + item.Kind.ToString() + ") r" + item.Revision.ToString());
  160. }
  161. }
  162. string msg = "Region Backup (" + System.Environment.MachineName + " at " + DateTime.UtcNow + " UTC)";
  163. m_log.Debug("[SVNBACKUP]: Saved with message: " + msg);
  164. logMessage = new AprString(msg, pool);
  165. tmpFile = new SvnPath(pool);
  166. return (SvnError.NoError);
  167. }
  168. #endregion
  169. #region IRegionModule Members
  170. public void Initialise(Scene scene, IConfigSource source)
  171. {
  172. try
  173. {
  174. if (!source.Configs["SVN"].GetBoolean("Enabled", false))
  175. return;
  176. m_enabled = true;
  177. m_svndir = source.Configs["SVN"].GetString("Directory", m_svndir);
  178. m_svnurl = source.Configs["SVN"].GetString("URL", m_svnurl);
  179. m_svnuser = source.Configs["SVN"].GetString("Username", m_svnuser);
  180. m_svnpass = source.Configs["SVN"].GetString("Password", m_svnpass);
  181. m_installBackupOnLoad = source.Configs["SVN"].GetBoolean("ImportOnStartup", m_installBackupOnLoad);
  182. m_svnAutoSave = source.Configs["SVN"].GetBoolean("Autosave", m_svnAutoSave);
  183. m_svnperiod = new TimeSpan(0, source.Configs["SVN"].GetInt("AutosavePeriod", (int) m_svnperiod.TotalMinutes), 0);
  184. }
  185. catch (Exception)
  186. {
  187. }
  188. lock (m_scenes)
  189. {
  190. m_scenes.Add(scene);
  191. }
  192. //Only register it once, to prevent command being executed x*region times
  193. if (m_scenes.Count == 1)
  194. {
  195. scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  196. }
  197. }
  198. public void PostInitialise()
  199. {
  200. if (m_enabled == false)
  201. return;
  202. if (m_svnAutoSave)
  203. {
  204. m_timer.Interval = m_svnperiod.TotalMilliseconds;
  205. m_timer.Elapsed += m_timer_Elapsed;
  206. m_timer.AutoReset = true;
  207. m_timer.Start();
  208. }
  209. m_log.Info("[SVNBACKUP]: Connecting to SVN server " + m_svnurl + " ...");
  210. SetupSvnProvider();
  211. m_log.Info("[SVNBACKUP]: Creating repository in " + m_svndir + ".");
  212. CreateSvnDirectory();
  213. CheckoutSvn();
  214. SetupSerialiser();
  215. if (m_installBackupOnLoad)
  216. {
  217. m_log.Info("[SVNBACKUP]: Importing latest SVN revision to scenes...");
  218. foreach (Scene scene in m_scenes)
  219. {
  220. LoadRegion(scene);
  221. }
  222. }
  223. }
  224. public void Close()
  225. {
  226. }
  227. public string Name
  228. {
  229. get { return "SvnBackupModule"; }
  230. }
  231. public bool IsSharedModule
  232. {
  233. get { return true; }
  234. }
  235. #endregion
  236. private void EventManager_OnPluginConsole(string[] args)
  237. {
  238. if (args[0] == "svn" && args[1] == "save")
  239. {
  240. SaveAllRegions();
  241. }
  242. if (args.Length == 2)
  243. {
  244. if (args[0] == "svn" && args[1] == "load")
  245. {
  246. LoadAllScenes();
  247. }
  248. }
  249. if (args.Length == 3)
  250. {
  251. if (args[0] == "svn" && args[1] == "load")
  252. {
  253. LoadAllScenes(Int32.Parse(args[2]));
  254. }
  255. }
  256. if (args.Length == 3)
  257. {
  258. if (args[0] == "svn" && args[1] == "load-region")
  259. {
  260. LoadScene(args[2]);
  261. }
  262. }
  263. if (args.Length == 4)
  264. {
  265. if (args[0] == "svn" && args[1] == "load-region")
  266. {
  267. LoadScene(args[2], Int32.Parse(args[3]));
  268. }
  269. }
  270. }
  271. public void LoadScene(string name)
  272. {
  273. CheckoutSvn();
  274. foreach (Scene scene in m_scenes)
  275. {
  276. if (scene.RegionInfo.RegionName.ToLower().Equals(name.ToLower()))
  277. {
  278. LoadRegion(scene);
  279. return;
  280. }
  281. }
  282. m_log.Warn("[SVNBACKUP]: No region loaded - unable to find matching name.");
  283. }
  284. public void LoadScene(string name, int revision)
  285. {
  286. CheckoutSvn(new SvnRevision(revision));
  287. foreach (Scene scene in m_scenes)
  288. {
  289. if (scene.RegionInfo.RegionName.ToLower().Equals(name.ToLower()))
  290. {
  291. LoadRegion(scene);
  292. return;
  293. }
  294. }
  295. m_log.Warn("[SVNBACKUP]: No region loaded - unable to find matching name.");
  296. }
  297. public void LoadAllScenes()
  298. {
  299. CheckoutSvn();
  300. foreach (Scene scene in m_scenes)
  301. {
  302. LoadRegion(scene);
  303. }
  304. }
  305. public void LoadAllScenes(int revision)
  306. {
  307. CheckoutSvn(new SvnRevision(revision));
  308. foreach (Scene scene in m_scenes)
  309. {
  310. LoadRegion(scene);
  311. }
  312. }
  313. private void m_timer_Elapsed(object sender, ElapsedEventArgs e)
  314. {
  315. SaveAllRegions();
  316. }
  317. private void SetupSerialiser()
  318. {
  319. if (m_scenes.Count > 0)
  320. m_serialiser = m_scenes[0].RequestModuleInterface<IRegionSerialiserModule>();
  321. }
  322. private void SetupSvnProvider()
  323. {
  324. m_svnClient = new SvnClient();
  325. m_svnClient.AddUsernameProvider();
  326. m_svnClient.AddPromptProvider(new SvnAuthProviderObject.SimplePrompt(SimpleAuth), IntPtr.Zero, 2);
  327. m_svnClient.OpenAuth();
  328. m_svnClient.Context.LogMsgFunc2 = new SvnDelegate(new SvnClient.GetCommitLog2(GetCommitLogCallback));
  329. }
  330. private void CreateSvnDirectory()
  331. {
  332. if (!Directory.Exists(m_svndir))
  333. Directory.CreateDirectory(m_svndir);
  334. }
  335. }
  336. }