SvnBackupModule.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 List<Scene> m_scenes;
  47. private Timer m_timer;
  48. private bool m_enabled;
  49. private bool m_installBackupOnLoad;
  50. private IRegionSerialiserModule m_serialiser;
  51. private bool m_svnAutoSave;
  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. m_scenes = new List<Scene>();
  173. m_timer = new Timer();
  174. try
  175. {
  176. if (!source.Configs["SVN"].GetBoolean("Enabled", false))
  177. return;
  178. m_enabled = true;
  179. m_svndir = source.Configs["SVN"].GetString("Directory", m_svndir);
  180. m_svnurl = source.Configs["SVN"].GetString("URL", m_svnurl);
  181. m_svnuser = source.Configs["SVN"].GetString("Username", m_svnuser);
  182. m_svnpass = source.Configs["SVN"].GetString("Password", m_svnpass);
  183. m_installBackupOnLoad = source.Configs["SVN"].GetBoolean("ImportOnStartup", m_installBackupOnLoad);
  184. m_svnAutoSave = source.Configs["SVN"].GetBoolean("Autosave", m_svnAutoSave);
  185. m_svnperiod = new TimeSpan(0, source.Configs["SVN"].GetInt("AutosavePeriod", (int) m_svnperiod.TotalMinutes), 0);
  186. }
  187. catch (Exception)
  188. {
  189. }
  190. lock (m_scenes)
  191. {
  192. m_scenes.Add(scene);
  193. }
  194. //Only register it once, to prevent command being executed x*region times
  195. if (m_scenes.Count == 1)
  196. {
  197. scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  198. }
  199. }
  200. public void PostInitialise()
  201. {
  202. if (m_enabled == false)
  203. return;
  204. if (m_svnAutoSave)
  205. {
  206. m_timer.Interval = m_svnperiod.TotalMilliseconds;
  207. m_timer.Elapsed += m_timer_Elapsed;
  208. m_timer.AutoReset = true;
  209. m_timer.Start();
  210. }
  211. m_log.Info("[SVNBACKUP]: Connecting to SVN server " + m_svnurl + " ...");
  212. SetupSvnProvider();
  213. m_log.Info("[SVNBACKUP]: Creating repository in " + m_svndir + ".");
  214. CreateSvnDirectory();
  215. CheckoutSvn();
  216. SetupSerialiser();
  217. if (m_installBackupOnLoad)
  218. {
  219. m_log.Info("[SVNBACKUP]: Importing latest SVN revision to scenes...");
  220. foreach (Scene scene in m_scenes)
  221. {
  222. LoadRegion(scene);
  223. }
  224. }
  225. }
  226. public void Close()
  227. {
  228. }
  229. public string Name
  230. {
  231. get { return "SvnBackupModule"; }
  232. }
  233. public bool IsSharedModule
  234. {
  235. get { return true; }
  236. }
  237. #endregion
  238. private void EventManager_OnPluginConsole(string[] args)
  239. {
  240. if (args[0] == "svn" && args[1] == "save")
  241. {
  242. SaveAllRegions();
  243. }
  244. if (args.Length == 2)
  245. {
  246. if (args[0] == "svn" && args[1] == "load")
  247. {
  248. LoadAllScenes();
  249. }
  250. }
  251. if (args.Length == 3)
  252. {
  253. if (args[0] == "svn" && args[1] == "load")
  254. {
  255. LoadAllScenes(Int32.Parse(args[2]));
  256. }
  257. }
  258. if (args.Length == 3)
  259. {
  260. if (args[0] == "svn" && args[1] == "load-region")
  261. {
  262. LoadScene(args[2]);
  263. }
  264. }
  265. if (args.Length == 4)
  266. {
  267. if (args[0] == "svn" && args[1] == "load-region")
  268. {
  269. LoadScene(args[2], Int32.Parse(args[3]));
  270. }
  271. }
  272. }
  273. public void LoadScene(string name)
  274. {
  275. CheckoutSvn();
  276. foreach (Scene scene in m_scenes)
  277. {
  278. if (scene.RegionInfo.RegionName.ToLower().Equals(name.ToLower()))
  279. {
  280. LoadRegion(scene);
  281. return;
  282. }
  283. }
  284. m_log.Warn("[SVNBACKUP]: No region loaded - unable to find matching name.");
  285. }
  286. public void LoadScene(string name, int revision)
  287. {
  288. CheckoutSvn(new SvnRevision(revision));
  289. foreach (Scene scene in m_scenes)
  290. {
  291. if (scene.RegionInfo.RegionName.ToLower().Equals(name.ToLower()))
  292. {
  293. LoadRegion(scene);
  294. return;
  295. }
  296. }
  297. m_log.Warn("[SVNBACKUP]: No region loaded - unable to find matching name.");
  298. }
  299. public void LoadAllScenes()
  300. {
  301. CheckoutSvn();
  302. foreach (Scene scene in m_scenes)
  303. {
  304. LoadRegion(scene);
  305. }
  306. }
  307. public void LoadAllScenes(int revision)
  308. {
  309. CheckoutSvn(new SvnRevision(revision));
  310. foreach (Scene scene in m_scenes)
  311. {
  312. LoadRegion(scene);
  313. }
  314. }
  315. private void m_timer_Elapsed(object sender, ElapsedEventArgs e)
  316. {
  317. SaveAllRegions();
  318. }
  319. private void SetupSerialiser()
  320. {
  321. if (m_scenes.Count > 0)
  322. m_serialiser = m_scenes[0].RequestModuleInterface<IRegionSerialiserModule>();
  323. }
  324. private void SetupSvnProvider()
  325. {
  326. m_svnClient = new SvnClient();
  327. m_svnClient.AddUsernameProvider();
  328. m_svnClient.AddPromptProvider(new SvnAuthProviderObject.SimplePrompt(SimpleAuth), IntPtr.Zero, 2);
  329. m_svnClient.OpenAuth();
  330. m_svnClient.Context.LogMsgFunc2 = new SvnDelegate(new SvnClient.GetCommitLog2(GetCommitLogCallback));
  331. }
  332. private void CreateSvnDirectory()
  333. {
  334. if (!Directory.Exists(m_svndir))
  335. Directory.CreateDirectory(m_svndir);
  336. }
  337. }
  338. }