AutoBackupModule.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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.Diagnostics;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Timers;
  33. using System.Text.RegularExpressions;
  34. using log4net;
  35. using Mono.Addins;
  36. using Nini.Config;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Framework.Interfaces;
  39. using OpenSim.Region.Framework.Scenes;
  40. namespace OpenSim.Region.OptionalModules.World.AutoBackup
  41. {
  42. /// <summary>
  43. /// Choose between ways of naming the backup files that are generated.
  44. /// </summary>
  45. /// <remarks>Time: OARs are named by a timestamp.
  46. /// Sequential: OARs are named by counting (Region_1.oar, Region_2.oar, etc.)
  47. /// Overwrite: Only one file per region is created; it's overwritten each time a backup is made.</remarks>
  48. public enum NamingType
  49. {
  50. Time,
  51. Sequential,
  52. Overwrite
  53. }
  54. ///<summary>
  55. /// AutoBackupModule: save OAR region backups to disk periodically
  56. /// </summary>
  57. /// <remarks>
  58. /// Config Settings Documentation.
  59. /// Each configuration setting can be specified in two places: OpenSim.ini or Regions.ini.
  60. /// If specified in Regions.ini, the settings should be within the region's section name.
  61. /// If specified in OpenSim.ini, the settings should be within the [AutoBackupModule] section.
  62. /// Region-specific settings take precedence.
  63. ///
  64. /// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis.
  65. /// All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings!
  66. /// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
  67. /// This is the only required option for enabling auto-backup; the other options have sane defaults.
  68. /// If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored.
  69. /// If False globally (the default), only regions that specifically override it in Regions.ini will get AutoBackup functionality.
  70. /// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours).
  71. /// The number of minutes between each backup attempt.
  72. /// If a negative or zero value is given, it is equivalent to setting AutoBackup = False.
  73. /// AutoBackupBusyCheck: True/False. Default: True.
  74. /// If True, we will only take an auto-backup if a set of conditions are met.
  75. /// These conditions are heuristics to try and avoid taking a backup when the sim is busy.
  76. /// AutoBackupSkipAssets
  77. /// If true, assets are not saved to the oar file. Considerably reduces impact on simulator when backing up. Intended for when assets db is backed up separately
  78. /// AutoBackupKeepFilesForDays
  79. /// Backup files older than this value (in days) are deleted during the current backup process, 0 will disable this and keep all backup files indefinitely
  80. /// AutoBackupScript: String. Default: not specified (disabled).
  81. /// File path to an executable script or binary to run when an automatic backup is taken.
  82. /// The file should really be (Windows) an .exe or .bat, or (Linux/Mac) a shell script or binary.
  83. /// Trying to "run" directories, or things with weird file associations on Win32, might cause unexpected results!
  84. /// argv[1] of the executed file/script will be the file name of the generated OAR.
  85. /// If the process can't be spawned for some reason (file not found, no execute permission, etc), write a warning to the console.
  86. /// AutoBackupNaming: string. Default: Time.
  87. /// One of three strings (case insensitive):
  88. /// "Time": Current timestamp is appended to file name. An existing file will never be overwritten.
  89. /// "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
  90. /// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
  91. /// AutoBackupDir: String. Default: "." (the current directory).
  92. /// A directory (absolute or relative) where backups should be saved.
  93. /// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass.
  94. /// If the time dilation is below this value, don't take a backup right now.
  95. /// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass.
  96. /// If the number of agents is greater than this value, don't take a backup right now
  97. /// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions.
  98. /// Also helps if you don't want AutoBackup at all.
  99. /// </remarks>
  100. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AutoBackupModule")]
  101. public class AutoBackupModule : ISharedRegionModule
  102. {
  103. private static readonly ILog m_log =
  104. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  105. private readonly Dictionary<Guid, IScene> m_pendingSaves = new Dictionary<Guid, IScene>(1);
  106. private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState();
  107. private readonly Dictionary<IScene, AutoBackupModuleState> m_states =
  108. new Dictionary<IScene, AutoBackupModuleState>(1);
  109. private readonly Dictionary<Timer, List<IScene>> m_timerMap =
  110. new Dictionary<Timer, List<IScene>>(1);
  111. private readonly Dictionary<double, Timer> m_timers = new Dictionary<double, Timer>(1);
  112. private delegate T DefaultGetter<T>(string settingName, T defaultValue);
  113. private bool m_enabled;
  114. private ICommandConsole m_console;
  115. private List<Scene> m_Scenes = new List<Scene> ();
  116. /// <summary>
  117. /// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState!
  118. /// </summary>
  119. private bool m_closed;
  120. private IConfigSource m_configSource;
  121. /// <summary>
  122. /// Required by framework.
  123. /// </summary>
  124. public bool IsSharedModule
  125. {
  126. get { return true; }
  127. }
  128. #region ISharedRegionModule Members
  129. /// <summary>
  130. /// Identifies the module to the system.
  131. /// </summary>
  132. string IRegionModuleBase.Name
  133. {
  134. get { return "AutoBackupModule"; }
  135. }
  136. /// <summary>
  137. /// We don't implement an interface, this is a single-use module.
  138. /// </summary>
  139. Type IRegionModuleBase.ReplaceableInterface
  140. {
  141. get { return null; }
  142. }
  143. /// <summary>
  144. /// Called once in the lifetime of the module at startup.
  145. /// </summary>
  146. /// <param name="source">The input config source for OpenSim.ini.</param>
  147. void IRegionModuleBase.Initialise(IConfigSource source)
  148. {
  149. // Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module
  150. this.m_configSource = source;
  151. IConfig moduleConfig = source.Configs["AutoBackupModule"];
  152. if (moduleConfig == null)
  153. {
  154. this.m_enabled = false;
  155. return;
  156. }
  157. else
  158. {
  159. this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
  160. if (this.m_enabled)
  161. {
  162. m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
  163. }
  164. else
  165. {
  166. return;
  167. }
  168. }
  169. Timer defTimer = new Timer(43200000);
  170. this.m_defaultState.Timer = defTimer;
  171. this.m_timers.Add(43200000, defTimer);
  172. defTimer.Elapsed += this.HandleElapsed;
  173. defTimer.AutoReset = true;
  174. defTimer.Start();
  175. AutoBackupModuleState abms = this.ParseConfig(null, true);
  176. m_log.Debug("[AUTO BACKUP]: Here is the default config:");
  177. m_log.Debug(abms.ToString());
  178. }
  179. /// <summary>
  180. /// Called once at de-init (sim shutting down).
  181. /// </summary>
  182. void IRegionModuleBase.Close()
  183. {
  184. if (!this.m_enabled)
  185. {
  186. return;
  187. }
  188. // We don't want any timers firing while the sim's coming down; strange things may happen.
  189. this.StopAllTimers();
  190. }
  191. /// <summary>
  192. /// Currently a no-op for AutoBackup because we have to wait for region to be fully loaded.
  193. /// </summary>
  194. /// <param name="scene"></param>
  195. void IRegionModuleBase.AddRegion (Scene scene)
  196. {
  197. if (!this.m_enabled) {
  198. return;
  199. }
  200. lock (m_Scenes) {
  201. m_Scenes.Add (scene);
  202. }
  203. m_console = MainConsole.Instance;
  204. m_console.Commands.AddCommand (
  205. "AutoBackup", false, "dobackup",
  206. "dobackup",
  207. "do backup.", DoBackup);
  208. }
  209. /// <summary>
  210. /// Here we just clean up some resources and stop the OAR backup (if any) for the given scene.
  211. /// </summary>
  212. /// <param name="scene">The scene (region) to stop performing AutoBackup on.</param>
  213. void IRegionModuleBase.RemoveRegion(Scene scene)
  214. {
  215. if (!this.m_enabled)
  216. {
  217. return;
  218. }
  219. m_Scenes.Remove (scene);
  220. if (this.m_states.ContainsKey(scene))
  221. {
  222. AutoBackupModuleState abms = this.m_states[scene];
  223. // Remove this scene out of the timer map list
  224. Timer timer = abms.Timer;
  225. List<IScene> list = this.m_timerMap[timer];
  226. list.Remove(scene);
  227. // Shut down the timer if this was the last scene for the timer
  228. if (list.Count == 0)
  229. {
  230. this.m_timerMap.Remove(timer);
  231. this.m_timers.Remove(timer.Interval);
  232. timer.Close();
  233. }
  234. this.m_states.Remove(scene);
  235. }
  236. }
  237. /// <summary>
  238. /// Most interesting/complex code paths in AutoBackup begin here.
  239. /// We read lots of Nini config, maybe set a timer, add members to state tracking Dictionaries, etc.
  240. /// </summary>
  241. /// <param name="scene">The scene to (possibly) perform AutoBackup on.</param>
  242. void IRegionModuleBase.RegionLoaded(Scene scene)
  243. {
  244. if (!this.m_enabled)
  245. {
  246. return;
  247. }
  248. // This really ought not to happen, but just in case, let's pretend it didn't...
  249. if (scene == null)
  250. {
  251. return;
  252. }
  253. AutoBackupModuleState abms = this.ParseConfig(scene, false);
  254. m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
  255. m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
  256. m_states.Add(scene, abms);
  257. }
  258. /// <summary>
  259. /// Currently a no-op.
  260. /// </summary>
  261. void ISharedRegionModule.PostInitialise()
  262. {
  263. }
  264. #endregion
  265. private void DoBackup (string module, string[] args)
  266. {
  267. if (args.Length != 2) {
  268. MainConsole.Instance.OutputFormat ("Usage: dobackup <regionname>");
  269. return;
  270. }
  271. bool found = false;
  272. string name = args [1];
  273. lock (m_Scenes) {
  274. foreach (Scene s in m_Scenes) {
  275. string test = s.Name.ToString ();
  276. if (test == name) {
  277. found = true;
  278. DoRegionBackup (s);
  279. }
  280. }
  281. if (!found) {
  282. MainConsole.Instance.OutputFormat ("No such region {0}. Nothing to backup", name);
  283. }
  284. }
  285. }
  286. /// <summary>
  287. /// Set up internal state for a given scene. Fairly complex code.
  288. /// When this method returns, we've started auto-backup timers, put members in Dictionaries, and created a State object for this scene.
  289. /// </summary>
  290. /// <param name="scene">The scene to look at.</param>
  291. /// <param name="parseDefault">Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).</param>
  292. /// <returns>An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.</returns>
  293. private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault)
  294. {
  295. string sRegionName;
  296. string sRegionLabel;
  297. // string prepend;
  298. AutoBackupModuleState state;
  299. if (parseDefault)
  300. {
  301. sRegionName = null;
  302. sRegionLabel = "DEFAULT";
  303. // prepend = "";
  304. state = this.m_defaultState;
  305. }
  306. else
  307. {
  308. sRegionName = scene.RegionInfo.RegionName;
  309. sRegionLabel = sRegionName;
  310. // prepend = sRegionName + ".";
  311. state = null;
  312. }
  313. // Read the config settings and set variables.
  314. IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null);
  315. IConfig config = this.m_configSource.Configs["AutoBackupModule"];
  316. if (config == null)
  317. {
  318. // defaultState would be disabled too if the section doesn't exist.
  319. state = this.m_defaultState;
  320. return state;
  321. }
  322. bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig);
  323. if (state == null && tmpEnabled != this.m_defaultState.Enabled)
  324. //Varies from default state
  325. {
  326. state = new AutoBackupModuleState();
  327. }
  328. if (state != null)
  329. {
  330. state.Enabled = tmpEnabled;
  331. }
  332. // If you don't want AutoBackup, we stop.
  333. if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled))
  334. {
  335. return state;
  336. }
  337. else
  338. {
  339. m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED.");
  340. }
  341. // Borrow an existing timer if one exists for the same interval; otherwise, make a new one.
  342. double interval =
  343. this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
  344. config, regionConfig) * 60000.0;
  345. if (state == null && interval != this.m_defaultState.IntervalMinutes * 60000.0)
  346. {
  347. state = new AutoBackupModuleState();
  348. }
  349. if (this.m_timers.ContainsKey(interval))
  350. {
  351. if (state != null)
  352. {
  353. state.Timer = this.m_timers[interval];
  354. }
  355. m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " +
  356. sRegionLabel);
  357. }
  358. else
  359. {
  360. // 0 or negative interval == do nothing.
  361. if (interval <= 0.0 && state != null)
  362. {
  363. state.Enabled = false;
  364. return state;
  365. }
  366. if (state == null)
  367. {
  368. state = new AutoBackupModuleState();
  369. }
  370. Timer tim = new Timer(interval);
  371. state.Timer = tim;
  372. //Milliseconds -> minutes
  373. this.m_timers.Add(interval, tim);
  374. tim.Elapsed += this.HandleElapsed;
  375. tim.AutoReset = true;
  376. tim.Start();
  377. }
  378. // Add the current region to the list of regions tied to this timer.
  379. if (scene != null)
  380. {
  381. if (state != null)
  382. {
  383. if (this.m_timerMap.ContainsKey(state.Timer))
  384. {
  385. this.m_timerMap[state.Timer].Add(scene);
  386. }
  387. else
  388. {
  389. List<IScene> scns = new List<IScene>(1);
  390. scns.Add(scene);
  391. this.m_timerMap.Add(state.Timer, scns);
  392. }
  393. }
  394. else
  395. {
  396. if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer))
  397. {
  398. this.m_timerMap[this.m_defaultState.Timer].Add(scene);
  399. }
  400. else
  401. {
  402. List<IScene> scns = new List<IScene>(1);
  403. scns.Add(scene);
  404. this.m_timerMap.Add(this.m_defaultState.Timer, scns);
  405. }
  406. }
  407. }
  408. bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck",
  409. this.m_defaultState.BusyCheck, config, regionConfig);
  410. if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck)
  411. {
  412. state = new AutoBackupModuleState();
  413. }
  414. if (state != null)
  415. {
  416. state.BusyCheck = tmpBusyCheck;
  417. }
  418. // Included Option To Skip Assets
  419. bool tmpSkipAssets = ResolveBoolean("AutoBackupSkipAssets",
  420. this.m_defaultState.SkipAssets, config, regionConfig);
  421. if (state == null && tmpSkipAssets != this.m_defaultState.SkipAssets)
  422. {
  423. state = new AutoBackupModuleState();
  424. }
  425. if (state != null)
  426. {
  427. state.SkipAssets = tmpSkipAssets;
  428. }
  429. // How long to keep backup files in days, 0 Disables this feature
  430. int tmpKeepFilesForDays = ResolveInt("AutoBackupKeepFilesForDays",
  431. this.m_defaultState.KeepFilesForDays, config, regionConfig);
  432. if (state == null && tmpKeepFilesForDays != this.m_defaultState.KeepFilesForDays)
  433. {
  434. state = new AutoBackupModuleState();
  435. }
  436. if (state != null)
  437. {
  438. state.KeepFilesForDays = tmpKeepFilesForDays;
  439. }
  440. // Set file naming algorithm
  441. string stmpNamingType = ResolveString("AutoBackupNaming",
  442. this.m_defaultState.NamingType.ToString(), config, regionConfig);
  443. NamingType tmpNamingType;
  444. if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
  445. {
  446. tmpNamingType = NamingType.Time;
  447. }
  448. else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
  449. {
  450. tmpNamingType = NamingType.Sequential;
  451. }
  452. else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
  453. {
  454. tmpNamingType = NamingType.Overwrite;
  455. }
  456. else
  457. {
  458. m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " +
  459. stmpNamingType);
  460. tmpNamingType = NamingType.Time;
  461. }
  462. if (state == null && tmpNamingType != this.m_defaultState.NamingType)
  463. {
  464. state = new AutoBackupModuleState();
  465. }
  466. if (state != null)
  467. {
  468. state.NamingType = tmpNamingType;
  469. }
  470. string tmpScript = ResolveString("AutoBackupScript",
  471. this.m_defaultState.Script, config, regionConfig);
  472. if (state == null && tmpScript != this.m_defaultState.Script)
  473. {
  474. state = new AutoBackupModuleState();
  475. }
  476. if (state != null)
  477. {
  478. state.Script = tmpScript;
  479. }
  480. string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig);
  481. if (state == null && tmpBackupDir != this.m_defaultState.BackupDir)
  482. {
  483. state = new AutoBackupModuleState();
  484. }
  485. if (state != null)
  486. {
  487. state.BackupDir = tmpBackupDir;
  488. // Let's give the user some convenience and auto-mkdir
  489. if (state.BackupDir != ".")
  490. {
  491. try
  492. {
  493. DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir);
  494. if (!dirinfo.Exists)
  495. {
  496. dirinfo.Create();
  497. }
  498. }
  499. catch (Exception e)
  500. {
  501. m_log.Warn(
  502. "[AUTO BACKUP]: BAD NEWS. You won't be able to save backups to directory " +
  503. state.BackupDir +
  504. " because it doesn't exist or there's a permissions issue with it. Here's the exception.",
  505. e);
  506. }
  507. }
  508. }
  509. if(state == null)
  510. return m_defaultState;
  511. return state;
  512. }
  513. /// <summary>
  514. /// Helper function for ParseConfig.
  515. /// </summary>
  516. /// <param name="settingName"></param>
  517. /// <param name="defaultValue"></param>
  518. /// <param name="global"></param>
  519. /// <param name="local"></param>
  520. /// <returns></returns>
  521. private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local)
  522. {
  523. if(local != null)
  524. {
  525. return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue));
  526. }
  527. else
  528. {
  529. return global.GetBoolean(settingName, defaultValue);
  530. }
  531. }
  532. /// <summary>
  533. /// Helper function for ParseConfig.
  534. /// </summary>
  535. /// <param name="settingName"></param>
  536. /// <param name="defaultValue"></param>
  537. /// <param name="global"></param>
  538. /// <param name="local"></param>
  539. /// <returns></returns>
  540. private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local)
  541. {
  542. if (local != null)
  543. {
  544. return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue));
  545. }
  546. else
  547. {
  548. return global.GetDouble(settingName, defaultValue);
  549. }
  550. }
  551. /// <summary>
  552. /// Helper function for ParseConfig.
  553. /// </summary>
  554. /// <param name="settingName"></param>
  555. /// <param name="defaultValue"></param>
  556. /// <param name="global"></param>
  557. /// <param name="local"></param>
  558. /// <returns></returns>
  559. private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local)
  560. {
  561. if (local != null)
  562. {
  563. return local.GetInt(settingName, global.GetInt(settingName, defaultValue));
  564. }
  565. else
  566. {
  567. return global.GetInt(settingName, defaultValue);
  568. }
  569. }
  570. /// <summary>
  571. /// Helper function for ParseConfig.
  572. /// </summary>
  573. /// <param name="settingName"></param>
  574. /// <param name="defaultValue"></param>
  575. /// <param name="global"></param>
  576. /// <param name="local"></param>
  577. /// <returns></returns>
  578. private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local)
  579. {
  580. if (local != null)
  581. {
  582. return local.GetString(settingName, global.GetString(settingName, defaultValue));
  583. }
  584. else
  585. {
  586. return global.GetString(settingName, defaultValue);
  587. }
  588. }
  589. /// <summary>
  590. /// Called when any auto-backup timer expires. This starts the code path for actually performing a backup.
  591. /// </summary>
  592. /// <param name="sender"></param>
  593. /// <param name="e"></param>
  594. private void HandleElapsed(object sender, ElapsedEventArgs e)
  595. {
  596. // TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region
  597. // XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to
  598. // check whether the region is too busy! Especially on sims with LOTS of regions.
  599. // Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible,
  600. // but would allow us to be semantically correct while being easier on perf.
  601. // Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi...
  602. // Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter.
  603. // Since this is pretty experimental, I haven't decided which alternative makes the most sense.
  604. if (this.m_closed)
  605. {
  606. return;
  607. }
  608. bool heuristicsRun = false;
  609. bool heuristicsPassed = false;
  610. if (!this.m_timerMap.ContainsKey((Timer) sender))
  611. {
  612. m_log.Debug("[AUTO BACKUP]: Code-up error: timerMap doesn't contain timer " + sender);
  613. }
  614. List<IScene> tmap = this.m_timerMap[(Timer) sender];
  615. if (tmap != null && tmap.Count > 0)
  616. {
  617. foreach (IScene scene in tmap)
  618. {
  619. AutoBackupModuleState state = this.m_states[scene];
  620. bool heuristics = state.BusyCheck;
  621. // Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region.
  622. if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics)
  623. {
  624. this.DoRegionBackup(scene);
  625. // Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off!
  626. }
  627. else if (heuristicsRun)
  628. {
  629. m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
  630. scene.RegionInfo.RegionName + " right now.");
  631. continue;
  632. // Logical Deduction: heuristics are on but haven't been run
  633. }
  634. else
  635. {
  636. heuristicsPassed = this.RunHeuristics(scene);
  637. heuristicsRun = true;
  638. if (!heuristicsPassed)
  639. {
  640. m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
  641. scene.RegionInfo.RegionName + " right now.");
  642. continue;
  643. }
  644. this.DoRegionBackup(scene);
  645. }
  646. // Remove Old Backups
  647. this.RemoveOldFiles(state);
  648. }
  649. }
  650. }
  651. /// <summary>
  652. /// Save an OAR, register for the callback for when it's done, then call the AutoBackupScript (if applicable).
  653. /// </summary>
  654. /// <param name="scene"></param>
  655. private void DoRegionBackup(IScene scene)
  656. {
  657. if (!scene.Ready)
  658. {
  659. // We won't backup a region that isn't operating normally.
  660. m_log.Warn("[AUTO BACKUP]: Not backing up region " + scene.RegionInfo.RegionName +
  661. " because its status is " + scene.RegionStatus);
  662. return;
  663. }
  664. AutoBackupModuleState state = this.m_states[scene];
  665. IRegionArchiverModule iram = scene.RequestModuleInterface<IRegionArchiverModule>();
  666. string savePath = BuildOarPath(scene.RegionInfo.RegionName,
  667. state.BackupDir,
  668. state.NamingType);
  669. if (savePath == null)
  670. {
  671. m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed");
  672. return;
  673. }
  674. Guid guid = Guid.NewGuid();
  675. m_pendingSaves.Add(guid, scene);
  676. state.LiveRequests.Add(guid, savePath);
  677. ((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
  678. m_log.Info("[AUTO BACKUP]: Backing up region " + scene.RegionInfo.RegionName);
  679. // Must pass options, even if dictionary is empty!
  680. Dictionary<string, object> options = new Dictionary<string, object>();
  681. if (state.SkipAssets)
  682. options["noassets"] = true;
  683. iram.ArchiveRegion(savePath, guid, options);
  684. }
  685. // For the given state, remove backup files older than the states KeepFilesForDays property
  686. private void RemoveOldFiles(AutoBackupModuleState state)
  687. {
  688. // 0 Means Disabled, Keep Files Indefinitely
  689. if (state.KeepFilesForDays > 0)
  690. {
  691. string[] files = Directory.GetFiles(state.BackupDir, "*.oar");
  692. DateTime CuttOffDate = DateTime.Now.AddDays(0 - state.KeepFilesForDays);
  693. foreach (string file in files)
  694. {
  695. try
  696. {
  697. FileInfo fi = new FileInfo(file);
  698. if (fi.CreationTime < CuttOffDate)
  699. fi.Delete();
  700. }
  701. catch (Exception Ex)
  702. {
  703. m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
  704. }
  705. }
  706. }
  707. }
  708. /// <summary>
  709. /// Called by the Event Manager when the OnOarFileSaved event is fired.
  710. /// </summary>
  711. /// <param name="guid"></param>
  712. /// <param name="message"></param>
  713. void EventManager_OnOarFileSaved(Guid guid, string message)
  714. {
  715. // Ignore if the OAR save is being done by some other part of the system
  716. if (m_pendingSaves.ContainsKey(guid))
  717. {
  718. AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])];
  719. ExecuteScript(abms.Script, abms.LiveRequests[guid]);
  720. m_pendingSaves.Remove(guid);
  721. abms.LiveRequests.Remove(guid);
  722. }
  723. }
  724. /// <summary>This format may turn out to be too unwieldy to keep...
  725. /// Besides, that's what ctimes are for. But then how do I name each file uniquely without using a GUID?
  726. /// Sequential numbers, right? We support those, too!</summary>
  727. private static string GetTimeString()
  728. {
  729. StringWriter sw = new StringWriter();
  730. sw.Write("_");
  731. DateTime now = DateTime.Now;
  732. sw.Write(now.Year);
  733. sw.Write("y_");
  734. sw.Write(now.Month);
  735. sw.Write("M_");
  736. sw.Write(now.Day);
  737. sw.Write("d_");
  738. sw.Write(now.Hour);
  739. sw.Write("h_");
  740. sw.Write(now.Minute);
  741. sw.Write("m_");
  742. sw.Write(now.Second);
  743. sw.Write("s");
  744. sw.Flush();
  745. string output = sw.ToString();
  746. sw.Close();
  747. return output;
  748. }
  749. /// <summary>Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.</summary>
  750. private bool RunHeuristics(IScene region)
  751. {
  752. try
  753. {
  754. return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region);
  755. }
  756. catch (Exception e)
  757. {
  758. m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e);
  759. return false;
  760. }
  761. }
  762. /// <summary>
  763. /// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5),
  764. /// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR).
  765. /// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy".
  766. /// </summary>
  767. /// <param name="region"></param>
  768. /// <returns>Returns true if we're not too busy; false means we've got worse time dilation than the threshold.</returns>
  769. private bool RunTimeDilationHeuristic(IScene region)
  770. {
  771. string regionName = region.RegionInfo.RegionName;
  772. return region.TimeDilation >=
  773. this.m_configSource.Configs["AutoBackupModule"].GetFloat(
  774. regionName + ".AutoBackupDilationThreshold", 0.5f);
  775. }
  776. /// <summary>
  777. /// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10),
  778. /// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR).
  779. /// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy".
  780. /// </summary>
  781. /// <param name="region"></param>
  782. /// <returns>Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.</returns>
  783. private bool RunAgentLimitHeuristic(IScene region)
  784. {
  785. string regionName = region.RegionInfo.RegionName;
  786. try
  787. {
  788. Scene scene = (Scene) region;
  789. // TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful...
  790. return scene.GetRootAgentCount() <=
  791. this.m_configSource.Configs["AutoBackupModule"].GetInt(
  792. regionName + ".AutoBackupAgentThreshold", 10);
  793. }
  794. catch (InvalidCastException ice)
  795. {
  796. m_log.Debug(
  797. "[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!",
  798. ice);
  799. return true;
  800. // Non-obstructionist safest answer...
  801. }
  802. }
  803. /// <summary>
  804. /// Run the script or executable specified by the "AutoBackupScript" config setting.
  805. /// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script.
  806. /// But there are plenty of other nasty things that can be done with an untrusted OpenSim.ini, such as running high threat level scripting functions.
  807. /// </summary>
  808. /// <param name="scriptName"></param>
  809. /// <param name="savePath"></param>
  810. private static void ExecuteScript(string scriptName, string savePath)
  811. {
  812. // Do nothing if there's no script.
  813. if (scriptName == null || scriptName.Length <= 0)
  814. {
  815. return;
  816. }
  817. try
  818. {
  819. FileInfo fi = new FileInfo(scriptName);
  820. if (fi.Exists)
  821. {
  822. ProcessStartInfo psi = new ProcessStartInfo(scriptName);
  823. psi.Arguments = savePath;
  824. psi.CreateNoWindow = true;
  825. Process proc = Process.Start(psi);
  826. proc.ErrorDataReceived += HandleProcErrorDataReceived;
  827. }
  828. }
  829. catch (Exception e)
  830. {
  831. m_log.Warn(
  832. "Exception encountered when trying to run script for oar backup " + savePath, e);
  833. }
  834. }
  835. /// <summary>
  836. /// Called if a running script process writes to stderr.
  837. /// </summary>
  838. /// <param name="sender"></param>
  839. /// <param name="e"></param>
  840. private static void HandleProcErrorDataReceived(object sender, DataReceivedEventArgs e)
  841. {
  842. m_log.Warn("ExecuteScript hook " + ((Process) sender).ProcessName +
  843. " is yacking on stderr: " + e.Data);
  844. }
  845. /// <summary>
  846. /// Quickly stop all timers from firing.
  847. /// </summary>
  848. private void StopAllTimers()
  849. {
  850. foreach (Timer t in this.m_timerMap.Keys)
  851. {
  852. t.Close();
  853. }
  854. this.m_closed = true;
  855. }
  856. /// <summary>
  857. /// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType.
  858. /// </summary>
  859. /// <param name="dirName"></param>
  860. /// <param name="regionName"></param>
  861. /// <returns></returns>
  862. private static string GetNextFile(string dirName, string regionName)
  863. {
  864. FileInfo uniqueFile = null;
  865. long biggestExistingFile = GetNextOarFileNumber(dirName, regionName);
  866. biggestExistingFile++;
  867. // We don't want to overwrite the biggest existing file; we want to write to the NEXT biggest.
  868. uniqueFile =
  869. new FileInfo(dirName + Path.DirectorySeparatorChar + regionName + "_" +
  870. biggestExistingFile + ".oar");
  871. return uniqueFile.FullName;
  872. }
  873. /// <summary>
  874. /// Top-level method for creating an absolute path to an OAR backup file based on what naming scheme the user wants.
  875. /// </summary>
  876. /// <param name="regionName">Name of the region to save.</param>
  877. /// <param name="baseDir">Absolute or relative path to the directory where the file should reside.</param>
  878. /// <param name="naming">The naming scheme for the file name.</param>
  879. /// <returns></returns>
  880. private static string BuildOarPath(string regionName, string baseDir, NamingType naming)
  881. {
  882. FileInfo path = null;
  883. switch (naming)
  884. {
  885. case NamingType.Overwrite:
  886. path = new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName + ".oar");
  887. return path.FullName;
  888. case NamingType.Time:
  889. path =
  890. new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName +
  891. GetTimeString() + ".oar");
  892. return path.FullName;
  893. case NamingType.Sequential:
  894. // All codepaths in GetNextFile should return a file name ending in .oar
  895. path = new FileInfo(GetNextFile(baseDir, regionName));
  896. return path.FullName;
  897. default:
  898. m_log.Warn("VERY BAD: Unhandled case element " + naming);
  899. break;
  900. }
  901. return null;
  902. }
  903. /// <summary>
  904. /// Helper function for Sequential file naming type (see BuildOarPath and GetNextFile).
  905. /// </summary>
  906. /// <param name="dirName"></param>
  907. /// <param name="regionName"></param>
  908. /// <returns></returns>
  909. private static long GetNextOarFileNumber(string dirName, string regionName)
  910. {
  911. long retval = 1;
  912. DirectoryInfo di = new DirectoryInfo(dirName);
  913. FileInfo[] fi = di.GetFiles(regionName, SearchOption.TopDirectoryOnly);
  914. Array.Sort(fi, (f1, f2) => StringComparer.CurrentCultureIgnoreCase.Compare(f1.Name, f2.Name));
  915. if (fi.LongLength > 0)
  916. {
  917. long subtract = 1L;
  918. bool worked = false;
  919. Regex reg = new Regex(regionName + "_([0-9])+" + ".oar");
  920. while (!worked && subtract <= fi.LongLength)
  921. {
  922. // Pick the file with the last natural ordering
  923. string biggestFileName = fi[fi.LongLength - subtract].Name;
  924. MatchCollection matches = reg.Matches(biggestFileName);
  925. long l = 1;
  926. if (matches.Count > 0 && matches[0].Groups.Count > 0)
  927. {
  928. try
  929. {
  930. long.TryParse(matches[0].Groups[1].Value, out l);
  931. retval = l;
  932. worked = true;
  933. }
  934. catch (FormatException fe)
  935. {
  936. m_log.Warn(
  937. "[AUTO BACKUP]: Error: Can't parse long value from file name to determine next OAR backup file number!",
  938. fe);
  939. subtract++;
  940. }
  941. }
  942. else
  943. {
  944. subtract++;
  945. }
  946. }
  947. }
  948. return retval;
  949. }
  950. }
  951. }