This commit is contained in:
UbitUmarov
2017-07-20 11:30:12 +01:00
60 changed files with 2493 additions and 41860 deletions

View File

@@ -59,23 +59,23 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// </summary>
/// <remarks>
/// Config Settings Documentation.
/// Each configuration setting can be specified in two places: OpenSim.ini or Regions.ini.
/// If specified in Regions.ini, the settings should be within the region's section name.
/// If specified in OpenSim.ini, the settings should be within the [AutoBackupModule] section.
/// Region-specific settings take precedence.
/// Configuration setting can be specified in two places: OpenSim.ini and/or Regions.ini.
///
/// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis.
/// All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings!
/// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
/// This is the only required option for enabling auto-backup; the other options have sane defaults.
/// If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored.
/// If False globally (the default), only regions that specifically override it in Regions.ini will get AutoBackup functionality.
/// OpenSim.ini only settings section [AutoBackupModule]
/// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module.
/// if false module is disable and all rest is ignored
/// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours).
/// The number of minutes between each backup attempt.
/// If a negative or zero value is given, it is equivalent to setting AutoBackup = False.
/// AutoBackupBusyCheck: True/False. Default: True.
/// If True, we will only take an auto-backup if a set of conditions are met.
/// These conditions are heuristics to try and avoid taking a backup when the sim is busy.
/// AutoBackupDir: String. Default: "." (the current directory).
/// A directory (absolute or relative) where backups should be saved.
/// AutoBackupKeepFilesForDays remove files older than this number of days. 0 disables
///
/// Next can be set on OpenSim.ini, as default, and or per region in Regions.ini
/// Region-specific settings take precedence.
///
/// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
/// controls backup per region, with default optionaly set on OpenSim.ini
/// AutoBackupSkipAssets
/// 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
/// AutoBackupKeepFilesForDays
@@ -89,40 +89,28 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// AutoBackupNaming: string. Default: Time.
/// One of three strings (case insensitive):
/// "Time": Current timestamp is appended to file name. An existing file will never be overwritten.
/// "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.
/// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
/// AutoBackupDir: String. Default: "." (the current directory).
/// A directory (absolute or relative) where backups should be saved.
/// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass.
/// If the time dilation is below this value, don't take a backup right now.
/// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass.
/// If the number of agents is greater than this value, don't take a backup right now
/// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions.
/// Also helps if you don't want AutoBackup at all.
/// "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.
/// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AutoBackupModule")]
public class AutoBackupModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Dictionary<Guid, IScene> m_pendingSaves = new Dictionary<Guid, IScene>(1);
private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState();
private readonly Dictionary<IScene, AutoBackupModuleState> m_states =
new Dictionary<IScene, AutoBackupModuleState>(1);
private readonly Dictionary<Timer, List<IScene>> m_timerMap =
new Dictionary<Timer, List<IScene>>(1);
private readonly Dictionary<double, Timer> m_timers = new Dictionary<double, Timer>(1);
private delegate T DefaultGetter<T>(string settingName, T defaultValue);
private bool m_enabled;
private ICommandConsole m_console;
private List<Scene> m_Scenes = new List<Scene> ();
/// <summary>
/// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState!
/// </summary>
private bool m_closed;
private Timer m_masterTimer;
private bool m_busy;
private int m_KeepFilesForDays = -1;
private string m_backupDir;
private bool m_doneFirst;
private double m_baseInterval;
private IConfigSource m_configSource;
@@ -159,36 +147,38 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
void IRegionModuleBase.Initialise(IConfigSource source)
{
// Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module
this.m_configSource = source;
m_configSource = source;
IConfig moduleConfig = source.Configs["AutoBackupModule"];
if (moduleConfig == null)
{
this.m_enabled = false;
m_enabled = false;
return;
}
else
{
this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
if (this.m_enabled)
{
m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
}
else
{
return;
}
}
Timer defTimer = new Timer(43200000);
this.m_defaultState.Timer = defTimer;
this.m_timers.Add(43200000, defTimer);
defTimer.Elapsed += this.HandleElapsed;
defTimer.AutoReset = true;
defTimer.Start();
m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
if(!m_enabled)
return;
AutoBackupModuleState abms = this.ParseConfig(null, true);
m_log.Debug("[AUTO BACKUP]: Here is the default config:");
m_log.Debug(abms.ToString());
ParseDefaultConfig(moduleConfig);
if(!m_enabled)
return;
m_log.Debug("[AUTO BACKUP]: Default config:");
m_log.Debug(m_defaultState.ToString());
m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
m_masterTimer = new Timer();
m_masterTimer.Interval = m_baseInterval;
m_masterTimer.Elapsed += HandleElapsed;
m_masterTimer.AutoReset = false;
m_console = MainConsole.Instance;
m_console.Commands.AddCommand (
"AutoBackup", true, "dooarbackup",
"dooarbackup <regionName> | ALL",
"saves the single region <regionName> to a oar or ALL regions in instance to oars, using same settings as AutoBackup. Note it restarts time interval", DoBackup);
m_busy = true;
}
/// <summary>
@@ -196,13 +186,11 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// </summary>
void IRegionModuleBase.Close()
{
if (!this.m_enabled)
{
if (!m_enabled)
return;
}
// We don't want any timers firing while the sim's coming down; strange things may happen.
this.StopAllTimers();
m_masterTimer.Dispose();
}
/// <summary>
@@ -211,18 +199,11 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// <param name="scene"></param>
void IRegionModuleBase.AddRegion (Scene scene)
{
if (!this.m_enabled) {
if (!m_enabled)
return;
}
lock (m_Scenes) {
m_Scenes.Add (scene);
}
m_console = MainConsole.Instance;
m_console.Commands.AddCommand (
"AutoBackup", false, "dobackup",
"dobackup",
"do backup.", DoBackup);
lock (m_Scenes)
m_Scenes.Add (scene);
}
/// <summary>
@@ -231,28 +212,14 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// <param name="scene">The scene (region) to stop performing AutoBackup on.</param>
void IRegionModuleBase.RemoveRegion(Scene scene)
{
if (!this.m_enabled)
{
if (m_enabled)
return;
}
m_Scenes.Remove (scene);
if (this.m_states.ContainsKey(scene))
lock(m_Scenes)
{
AutoBackupModuleState abms = this.m_states[scene];
// Remove this scene out of the timer map list
Timer timer = abms.Timer;
List<IScene> list = this.m_timerMap[timer];
list.Remove(scene);
// Shut down the timer if this was the last scene for the timer
if (list.Count == 0)
{
this.m_timerMap.Remove(timer);
this.m_timers.Remove(timer.Interval);
timer.Close();
}
this.m_states.Remove(scene);
if (m_states.ContainsKey(scene))
m_states.Remove(scene);
m_Scenes.Remove(scene);
}
}
@@ -263,22 +230,29 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// <param name="scene">The scene to (possibly) perform AutoBackup on.</param>
void IRegionModuleBase.RegionLoaded(Scene scene)
{
if (!this.m_enabled)
{
if (!m_enabled)
return;
}
// This really ought not to happen, but just in case, let's pretend it didn't...
if (scene == null)
{
return;
AutoBackupModuleState abms = ParseConfig(scene);
if(abms == null)
{
m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
m_log.Debug("DEFAULT");
abms = new AutoBackupModuleState(m_defaultState);
}
else
{
m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
m_log.Debug(abms.ToString());
}
AutoBackupModuleState abms = this.ParseConfig(scene, false);
m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
m_states.Add(scene, abms);
m_busy = false;
m_masterTimer.Start();
}
/// <summary>
@@ -292,24 +266,122 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
private void DoBackup (string module, string[] args)
{
if (args.Length != 2) {
MainConsole.Instance.OutputFormat ("Usage: dobackup <regionname>");
if (!m_enabled)
return;
if (args.Length != 2)
{
MainConsole.Instance.OutputFormat ("Usage: dooarbackup <regionname>");
return;
}
if(m_busy)
{
MainConsole.Instance.OutputFormat ("Already doing a backup, please try later");
return;
}
m_masterTimer.Stop();
m_busy = true;
bool found = false;
string name = args [1];
lock (m_Scenes) {
foreach (Scene s in m_Scenes) {
string test = s.Name.ToString ();
if (test == name) {
Scene[] scenes;
lock (m_Scenes)
scenes = m_Scenes.ToArray();
if(scenes == null)
return;
Scene s;
try
{
if(name == "ALL")
{
for(int i = 0; i < scenes.Length; i++)
{
s = scenes[i];
DoRegionBackup(s);
if (!m_enabled)
return;
}
return;
}
for(int i = 0; i < scenes.Length; i++)
{
s = scenes[i];
if (s.Name == name)
{
found = true;
DoRegionBackup (s);
DoRegionBackup(s);
break;
}
}
if (!found) {
}
catch { }
finally
{
if (m_enabled)
m_masterTimer.Start();
m_busy = false;
}
if (!found)
MainConsole.Instance.OutputFormat ("No such region {0}. Nothing to backup", name);
}
private void ParseDefaultConfig(IConfig config)
{
m_backupDir = ".";
string backupDir = config.GetString("AutoBackupDir", ".");
if (backupDir != ".")
{
try
{
DirectoryInfo dirinfo = new DirectoryInfo(backupDir);
if (!dirinfo.Exists)
dirinfo.Create();
}
catch (Exception e)
{
m_enabled = false;
m_log.WarnFormat("[AUTO BACKUP]: Error accessing backup folder {0}. Module disabled. {1}",
backupDir, e);
return;
}
}
m_backupDir = backupDir;
double interval = config.GetDouble("AutoBackupInterval", 720);
interval *= 60000.0;
m_baseInterval = interval;
// How long to keep backup files in days, 0 Disables this feature
m_KeepFilesForDays = config.GetInt("AutoBackupKeepFilesForDays",m_KeepFilesForDays);
m_defaultState.Enabled = config.GetBoolean("AutoBackup", m_defaultState.Enabled);
m_defaultState.SkipAssets = config.GetBoolean("AutoBackupSkipAssets",m_defaultState.SkipAssets);
// Set file naming algorithm
string stmpNamingType = config.GetString("AutoBackupNaming", m_defaultState.NamingType.ToString());
NamingType tmpNamingType;
if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
tmpNamingType = NamingType.Time;
else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
tmpNamingType = NamingType.Sequential;
else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
tmpNamingType = NamingType.Overwrite;
else
{
m_log.Warn("Unknown naming type specified for Default");
tmpNamingType = NamingType.Time;
}
m_defaultState.NamingType = tmpNamingType;
m_defaultState.Script = config.GetString("AutoBackupScript", m_defaultState.Script);
}
/// <summary>
@@ -319,329 +391,49 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// <param name="scene">The scene to look at.</param>
/// <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>
/// <returns>An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.</returns>
private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault)
private AutoBackupModuleState ParseConfig(IScene scene)
{
string sRegionName;
string sRegionLabel;
// string prepend;
AutoBackupModuleState state;
if(scene == null)
return null;
if (parseDefault)
{
sRegionName = null;
sRegionLabel = "DEFAULT";
// prepend = "";
state = this.m_defaultState;
}
else
{
sRegionName = scene.RegionInfo.RegionName;
sRegionLabel = sRegionName;
// prepend = sRegionName + ".";
state = null;
}
string sRegionName;
AutoBackupModuleState state = null;
sRegionName = scene.RegionInfo.RegionName;
// Read the config settings and set variables.
IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null);
IConfig config = this.m_configSource.Configs["AutoBackupModule"];
if (config == null)
{
// defaultState would be disabled too if the section doesn't exist.
state = this.m_defaultState;
return state;
}
IConfig regionConfig = scene.Config.Configs[sRegionName];
if (regionConfig == null)
return null;
bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig);
if (state == null && tmpEnabled != this.m_defaultState.Enabled)
//Varies from default state
{
state = new AutoBackupModuleState();
}
state = new AutoBackupModuleState();
if (state != null)
{
state.Enabled = tmpEnabled;
}
// If you don't want AutoBackup, we stop.
if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled))
{
return state;
}
else
{
m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED.");
}
// Borrow an existing timer if one exists for the same interval; otherwise, make a new one.
double interval =
this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
config, regionConfig) * 60000.0;
if (state == null && interval != this.m_defaultState.IntervalMinutes * 60000.0)
{
state = new AutoBackupModuleState();
}
if (this.m_timers.ContainsKey(interval))
{
if (state != null)
{
state.Timer = this.m_timers[interval];
}
m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " +
sRegionLabel);
}
else
{
// 0 or negative interval == do nothing.
if (interval <= 0.0 && state != null)
{
state.Enabled = false;
return state;
}
if (state == null)
{
state = new AutoBackupModuleState();
}
Timer tim = new Timer(interval);
state.Timer = tim;
//Milliseconds -> minutes
this.m_timers.Add(interval, tim);
tim.Elapsed += this.HandleElapsed;
tim.AutoReset = true;
tim.Start();
}
// Add the current region to the list of regions tied to this timer.
if (scene != null)
{
if (state != null)
{
if (this.m_timerMap.ContainsKey(state.Timer))
{
this.m_timerMap[state.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(state.Timer, scns);
}
}
else
{
if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer))
{
this.m_timerMap[this.m_defaultState.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(this.m_defaultState.Timer, scns);
}
}
}
bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck",
this.m_defaultState.BusyCheck, config, regionConfig);
if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BusyCheck = tmpBusyCheck;
}
state.Enabled = regionConfig.GetBoolean("AutoBackup", m_defaultState.Enabled);
// Included Option To Skip Assets
bool tmpSkipAssets = ResolveBoolean("AutoBackupSkipAssets",
this.m_defaultState.SkipAssets, config, regionConfig);
if (state == null && tmpSkipAssets != this.m_defaultState.SkipAssets)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.SkipAssets = tmpSkipAssets;
}
// How long to keep backup files in days, 0 Disables this feature
int tmpKeepFilesForDays = ResolveInt("AutoBackupKeepFilesForDays",
this.m_defaultState.KeepFilesForDays, config, regionConfig);
if (state == null && tmpKeepFilesForDays != this.m_defaultState.KeepFilesForDays)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.KeepFilesForDays = tmpKeepFilesForDays;
}
state.SkipAssets = regionConfig.GetBoolean("AutoBackupSkipAssets", m_defaultState.SkipAssets);
// Set file naming algorithm
string stmpNamingType = ResolveString("AutoBackupNaming",
this.m_defaultState.NamingType.ToString(), config, regionConfig);
string stmpNamingType = regionConfig.GetString("AutoBackupNaming", m_defaultState.NamingType.ToString());
NamingType tmpNamingType;
if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Time;
}
else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Sequential;
}
else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Overwrite;
}
else
{
m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " +
m_log.Warn("Unknown naming type specified for region " + sRegionName + ": " +
stmpNamingType);
tmpNamingType = NamingType.Time;
}
m_defaultState.NamingType = tmpNamingType;
if (state == null && tmpNamingType != this.m_defaultState.NamingType)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.NamingType = tmpNamingType;
}
string tmpScript = ResolveString("AutoBackupScript",
this.m_defaultState.Script, config, regionConfig);
if (state == null && tmpScript != this.m_defaultState.Script)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Script = tmpScript;
}
string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig);
if (state == null && tmpBackupDir != this.m_defaultState.BackupDir)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BackupDir = tmpBackupDir;
// Let's give the user some convenience and auto-mkdir
if (state.BackupDir != ".")
{
try
{
DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir);
if (!dirinfo.Exists)
{
dirinfo.Create();
}
}
catch (Exception e)
{
m_log.Warn(
"[AUTO BACKUP]: BAD NEWS. You won't be able to save backups to directory " +
state.BackupDir +
" because it doesn't exist or there's a permissions issue with it. Here's the exception.",
e);
}
}
}
if(state == null)
return m_defaultState;
state.Script = regionConfig.GetString("AutoBackupScript", m_defaultState.Script);
return state;
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local)
{
if(local != null)
{
return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue));
}
else
{
return global.GetBoolean(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue));
}
else
{
return global.GetDouble(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetInt(settingName, global.GetInt(settingName, defaultValue));
}
else
{
return global.GetInt(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetString(settingName, global.GetString(settingName, defaultValue));
}
else
{
return global.GetString(settingName, defaultValue);
}
}
/// <summary>
/// Called when any auto-backup timer expires. This starts the code path for actually performing a backup.
@@ -650,63 +442,27 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// <param name="e"></param>
private void HandleElapsed(object sender, ElapsedEventArgs e)
{
// TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region
// XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to
// check whether the region is too busy! Especially on sims with LOTS of regions.
// Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible,
// but would allow us to be semantically correct while being easier on perf.
// Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi...
// Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter.
// Since this is pretty experimental, I haven't decided which alternative makes the most sense.
if (this.m_closed)
{
if (!m_enabled || m_busy)
return;
}
bool heuristicsRun = false;
bool heuristicsPassed = false;
if (!this.m_timerMap.ContainsKey((Timer) sender))
m_busy = true;
if(m_doneFirst && m_KeepFilesForDays > 0)
RemoveOldFiles();
foreach (IScene scene in m_Scenes)
{
m_log.Debug("[AUTO BACKUP]: Code-up error: timerMap doesn't contain timer " + sender);
if (!m_enabled)
return;
DoRegionBackup(scene);
}
List<IScene> tmap = this.m_timerMap[(Timer) sender];
if (tmap != null && tmap.Count > 0)
if (m_enabled)
{
foreach (IScene scene in tmap)
{
AutoBackupModuleState state = this.m_states[scene];
bool heuristics = state.BusyCheck;
// Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region.
if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics)
{
this.DoRegionBackup(scene);
// Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off!
}
else if (heuristicsRun)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
// Logical Deduction: heuristics are on but haven't been run
}
else
{
heuristicsPassed = this.RunHeuristics(scene);
heuristicsRun = true;
if (!heuristicsPassed)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
}
this.DoRegionBackup(scene);
}
// Remove Old Backups
this.RemoveOldFiles(state);
}
m_masterTimer.Start();
m_busy = false;
}
m_doneFirst = true;
}
/// <summary>
@@ -723,21 +479,29 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
return;
}
AutoBackupModuleState state = this.m_states[scene];
m_busy = true;
AutoBackupModuleState state;
if(!m_states.TryGetValue(scene, out state))
return;
if(state == null || !state.Enabled)
return;
IRegionArchiverModule iram = scene.RequestModuleInterface<IRegionArchiverModule>();
if(iram == null)
return;
string savePath = BuildOarPath(scene.RegionInfo.RegionName,
state.BackupDir,
m_backupDir,
state.NamingType);
if (savePath == null)
{
m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed");
return;
}
Guid guid = Guid.NewGuid();
m_pendingSaves.Add(guid, scene);
state.LiveRequests.Add(guid, savePath);
((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
Guid guid = Guid.NewGuid();
m_log.Info("[AUTO BACKUP]: Backing up region " + scene.RegionInfo.RegionName);
// Must pass options, even if dictionary is empty!
@@ -747,47 +511,37 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
options["noassets"] = true;
iram.ArchiveRegion(savePath, guid, options);
ExecuteScript(state.Script, savePath);
}
// For the given state, remove backup files older than the states KeepFilesForDays property
private void RemoveOldFiles(AutoBackupModuleState state)
private void RemoveOldFiles()
{
// 0 Means Disabled, Keep Files Indefinitely
if (state.KeepFilesForDays > 0)
string[] files;
try
{
string[] files = Directory.GetFiles(state.BackupDir, "*.oar");
DateTime CuttOffDate = DateTime.Now.AddDays(0 - state.KeepFilesForDays);
foreach (string file in files)
{
try
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < CuttOffDate)
fi.Delete();
}
catch (Exception Ex)
{
m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
}
}
files = Directory.GetFiles(m_backupDir, "*.oar");
}
}
/// <summary>
/// Called by the Event Manager when the OnOarFileSaved event is fired.
/// </summary>
/// <param name="guid"></param>
/// <param name="message"></param>
void EventManager_OnOarFileSaved(Guid guid, string message)
{
// Ignore if the OAR save is being done by some other part of the system
if (m_pendingSaves.ContainsKey(guid))
catch (Exception Ex)
{
AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])];
ExecuteScript(abms.Script, abms.LiveRequests[guid]);
m_pendingSaves.Remove(guid);
abms.LiveRequests.Remove(guid);
m_log.Error("[AUTO BACKUP]: Error reading backup folder " + m_backupDir + ": " + Ex.Message);
return;
}
DateTime CuttOffDate = DateTime.Now.AddDays(-m_KeepFilesForDays);
foreach (string file in files)
{
try
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < CuttOffDate)
fi.Delete();
}
catch (Exception Ex)
{
m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
}
}
}
@@ -817,63 +571,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
return output;
}
/// <summary>Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.</summary>
private bool RunHeuristics(IScene region)
{
try
{
return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region);
}
catch (Exception e)
{
m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e);
return false;
}
}
/// <summary>
/// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5),
/// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR).
/// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got worse time dilation than the threshold.</returns>
private bool RunTimeDilationHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
return region.TimeDilation >=
this.m_configSource.Configs["AutoBackupModule"].GetFloat(
regionName + ".AutoBackupDilationThreshold", 0.5f);
}
/// <summary>
/// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10),
/// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR).
/// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.</returns>
private bool RunAgentLimitHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
try
{
Scene scene = (Scene) region;
// TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful...
return scene.GetRootAgentCount() <=
this.m_configSource.Configs["AutoBackupModule"].GetInt(
regionName + ".AutoBackupAgentThreshold", 10);
}
catch (InvalidCastException ice)
{
m_log.Debug(
"[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!",
ice);
return true;
// Non-obstructionist safest answer...
}
}
/// <summary>
/// Run the script or executable specified by the "AutoBackupScript" config setting.
/// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script.
@@ -919,18 +616,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
" is yacking on stderr: " + e.Data);
}
/// <summary>
/// Quickly stop all timers from firing.
/// </summary>
private void StopAllTimers()
{
foreach (Timer t in this.m_timerMap.Keys)
{
t.Close();
}
this.m_closed = true;
}
/// <summary>
/// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType.
/// </summary>
@@ -1033,5 +718,3 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
}
}
}

View File

@@ -38,26 +38,20 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
///
public class AutoBackupModuleState
{
private Dictionary<Guid, string> m_liveRequests = null;
public AutoBackupModuleState()
{
this.Enabled = false;
this.BackupDir = ".";
this.BusyCheck = true;
this.SkipAssets = false;
this.Timer = null;
this.NamingType = NamingType.Time;
this.Script = null;
this.KeepFilesForDays = 0;
Enabled = false;
SkipAssets = false;
NamingType = NamingType.Time;
Script = null;
}
public Dictionary<Guid, string> LiveRequests
public AutoBackupModuleState(AutoBackupModuleState copyFrom)
{
get {
return this.m_liveRequests ??
(this.m_liveRequests = new Dictionary<Guid, string>(1));
}
Enabled = copyFrom.Enabled;
SkipAssets = copyFrom.SkipAssets;
NamingType = copyFrom.NamingType;
Script = copyFrom.Script;
}
public bool Enabled
@@ -66,33 +60,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
set;
}
public System.Timers.Timer Timer
{
get;
set;
}
public double IntervalMinutes
{
get
{
if (this.Timer == null)
{
return -1.0;
}
else
{
return this.Timer.Interval / 60000.0;
}
}
}
public bool BusyCheck
{
get;
set;
}
public bool SkipAssets
{
get;
@@ -105,36 +72,19 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
set;
}
public string BackupDir
{
get;
set;
}
public NamingType NamingType
{
get;
set;
}
public int KeepFilesForDays
{
get;
set;
}
public new string ToString()
{
string retval = "";
retval += "[AUTO BACKUP]: AutoBackup: " + (Enabled ? "ENABLED" : "DISABLED") + "\n";
retval += "[AUTO BACKUP]: Interval: " + IntervalMinutes + " minutes" + "\n";
retval += "[AUTO BACKUP]: Do Busy Check: " + (BusyCheck ? "Yes" : "No") + "\n";
retval += "[AUTO BACKUP]: Naming Type: " + NamingType.ToString() + "\n";
retval += "[AUTO BACKUP]: Backup Dir: " + BackupDir + "\n";
retval += "[AUTO BACKUP]: Script: " + Script + "\n";
return retval;
}
}
}

View File

@@ -27,8 +27,13 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Timers;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using OpenMetaverse;
using log4net;
using Mono.Addins;
@@ -38,9 +43,7 @@ using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Timer= System.Timers.Timer;
namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
@@ -48,7 +51,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
/// Version 2.02 - Still hacky
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TreePopulatorModule")]
public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule, IVegetationModule
public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Commander m_commander = new Commander("tree");
@@ -82,20 +85,20 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
Copse cp = (Copse)DeserializeObject(fileName);
this.m_name = cp.m_name;
this.m_frozen = cp.m_frozen;
this.m_tree_quantity = cp.m_tree_quantity;
this.m_treeline_high = cp.m_treeline_high;
this.m_treeline_low = cp.m_treeline_low;
this.m_range = cp.m_range;
this.m_tree_type = cp.m_tree_type;
this.m_seed_point = cp.m_seed_point;
this.m_initial_scale = cp.m_initial_scale;
this.m_maximum_scale = cp.m_maximum_scale;
this.m_initial_scale = cp.m_initial_scale;
this.m_rate = cp.m_rate;
this.m_planted = planted;
this.m_trees = new List<UUID>();
m_name = cp.m_name;
m_frozen = cp.m_frozen;
m_tree_quantity = cp.m_tree_quantity;
m_treeline_high = cp.m_treeline_high;
m_treeline_low = cp.m_treeline_low;
m_range = cp.m_range;
m_tree_type = cp.m_tree_type;
m_seed_point = cp.m_seed_point;
m_initial_scale = cp.m_initial_scale;
m_maximum_scale = cp.m_maximum_scale;
m_initial_scale = cp.m_initial_scale;
m_rate = cp.m_rate;
m_planted = planted;
m_trees = new List<UUID>();
}
public Copse(string copsedef)
@@ -103,61 +106,63 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
char[] delimiterChars = {':', ';'};
string[] field = copsedef.Split(delimiterChars);
this.m_name = field[1].Trim();
this.m_frozen = (copsedef[0] == 'F');
this.m_tree_quantity = int.Parse(field[2]);
this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
this.m_range = double.Parse(field[5], Culture.NumberFormatInfo);
this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
this.m_seed_point = Vector3.Parse(field[7]);
this.m_initial_scale = Vector3.Parse(field[8]);
this.m_maximum_scale = Vector3.Parse(field[9]);
this.m_rate = Vector3.Parse(field[10]);
this.m_planted = true;
this.m_trees = new List<UUID>();
m_name = field[1].Trim();
m_frozen = (copsedef[0] == 'F');
m_tree_quantity = int.Parse(field[2]);
m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
m_range = double.Parse(field[5], Culture.NumberFormatInfo);
m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
m_seed_point = Vector3.Parse(field[7]);
m_initial_scale = Vector3.Parse(field[8]);
m_maximum_scale = Vector3.Parse(field[9]);
m_rate = Vector3.Parse(field[10]);
m_planted = true;
m_trees = new List<UUID>();
}
public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List<UUID> trees)
{
this.m_name = name;
this.m_frozen = false;
this.m_tree_quantity = quantity;
this.m_treeline_high = high;
this.m_treeline_low = low;
this.m_range = range;
this.m_tree_type = type;
this.m_seed_point = point;
this.m_initial_scale = scale;
this.m_maximum_scale = max_scale;
this.m_rate = rate;
this.m_planted = false;
this.m_trees = trees;
m_name = name;
m_frozen = false;
m_tree_quantity = quantity;
m_treeline_high = high;
m_treeline_low = low;
m_range = range;
m_tree_type = type;
m_seed_point = point;
m_initial_scale = scale;
m_maximum_scale = max_scale;
m_rate = rate;
m_planted = false;
m_trees = trees;
}
public override string ToString()
{
string frozen = (this.m_frozen ? "F" : "A");
string frozen = (m_frozen ? "F" : "A");
return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};",
frozen,
this.m_name,
this.m_tree_quantity,
this.m_treeline_high,
this.m_treeline_low,
this.m_range,
this.m_tree_type,
this.m_seed_point.ToString(),
this.m_initial_scale.ToString(),
this.m_maximum_scale.ToString(),
this.m_rate.ToString());
m_name,
m_tree_quantity,
m_treeline_high,
m_treeline_low,
m_range,
m_tree_type,
m_seed_point.ToString(),
m_initial_scale.ToString(),
m_maximum_scale.ToString(),
m_rate.ToString());
}
}
private List<Copse> m_copse;
private List<Copse> m_copses = new List<Copse>();
private object mylock;
private double m_update_ms = 1000.0; // msec between updates
private bool m_active_trees = false;
private bool m_enabled = true; // original default
private bool m_allowGrow = true; // original default
Timer CalculateTrees;
@@ -174,51 +179,51 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
public void Initialise(IConfigSource config)
{
// ini file settings
try
IConfig moduleConfig = config.Configs["Trees"];
if (moduleConfig != null)
{
m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees);
}
catch (Exception)
{
m_log.Debug("[TREES]: ini failure for active_trees - using default");
m_enabled = moduleConfig.GetBoolean("enabled", m_enabled);
m_active_trees = moduleConfig.GetBoolean("active_trees", m_active_trees);
m_allowGrow = moduleConfig.GetBoolean("allowGrow", m_allowGrow);
m_update_ms = moduleConfig.GetDouble("update_rate", m_update_ms);
}
try
{
m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms);
}
catch (Exception)
{
m_log.Debug("[TREES]: ini failure for update_rate - using default");
}
if(!m_enabled)
return;
m_copses = new List<Copse>();
mylock = new object();
InstallCommands();
m_log.Debug("[TREES]: Initialised tree module");
m_log.Debug("[TREES]: Initialised tree populator module");
}
public void AddRegion(Scene scene)
{
if(!m_enabled)
return;
m_scene = scene;
m_scene.RegisterModuleCommander(m_commander);
m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
m_scene.EventManager.OnPrimsLoaded += EventManager_OnPrimsLoaded;
}
public void RemoveRegion(Scene scene)
{
}
if(!m_enabled)
return;
if(m_active_trees && CalculateTrees != null)
{
CalculateTrees.Dispose();
CalculateTrees = null;
}
m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
m_scene.EventManager.OnPrimsLoaded -= EventManager_OnPrimsLoaded;
}
public void RegionLoaded(Scene scene)
{
ReloadCopse();
if (m_copse.Count > 0)
m_log.Info("[TREES]: Copse load complete");
if (m_active_trees)
activeizeTreeze(true);
}
public void Close()
@@ -240,6 +245,16 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
//--------------------------------------------------------------
private void EventManager_OnPrimsLoaded(Scene s)
{
ReloadCopse();
if (m_copses.Count > 0)
m_log.Info("[TREES]: Copses loaded" );
if (m_active_trees)
activeizeTreeze(true);
}
#region ICommandableModule Members
private void HandleTreeActive(Object[] args)
@@ -267,25 +282,57 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
string copsename = ((string)args[0]).Trim();
Boolean freezeState = (Boolean) args[1];
foreach (Copse cp in m_copse)
lock(mylock)
{
if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState))
foreach (Copse cp in m_copses)
{
cp.m_frozen = freezeState;
foreach (UUID tree in cp.m_trees)
{
SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM"));
sop.ParentGroup.HasGroupChanged = true;
}
if (cp.m_name != copsename)
continue;
m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
return;
}
else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState))
{
m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
return;
if(!cp.m_frozen && freezeState || cp.m_frozen && !freezeState)
{
cp.m_frozen = freezeState;
List<UUID> losttrees = new List<UUID>();
foreach (UUID tree in cp.m_trees)
{
SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
if(sog != null && !sog.IsDeleted)
{
SceneObjectPart sop = sog.RootPart;
string name = sop.Name;
if(freezeState)
{
if(name.StartsWith("FTPM"))
continue;
if(!name.StartsWith("ATPM"))
continue;
sop.Name = sop.Name.Replace("ATPM", "FTPM");
}
else
{
if(name.StartsWith("ATPM"))
continue;
if(!name.StartsWith("FTPM"))
continue;
sop.Name = sop.Name.Replace("FTPM", "ATPM");
}
sop.ParentGroup.HasGroupChanged = true;
sog.ScheduleGroupForFullUpdate();
}
else
losttrees.Add(tree);
}
foreach (UUID tree in losttrees)
cp.m_trees.Remove(tree);
m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
return;
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
return;
}
}
}
m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
@@ -297,17 +344,21 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
m_log.InfoFormat("[TREES]: Loading copse definition....");
copse = new Copse(((string)args[0]), false);
foreach (Copse cp in m_copse)
lock(mylock)
{
if (cp.m_name == copse.m_name)
copse = new Copse(((string)args[0]), false);
{
m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
return;
foreach (Copse cp in m_copses)
{
if (cp.m_name == copse.m_name)
{
m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
return;
}
}
}
m_copses.Add(copse);
}
m_copse.Add(copse);
m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString());
}
@@ -318,20 +369,24 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
foreach (Copse copse in m_copse)
lock(mylock)
{
if (copse.m_name == copsename)
foreach (Copse copse in m_copses)
{
if (!copse.m_planted)
if (copse.m_name == copsename)
{
// The first tree for a copse is created here
CreateTree(uuid, copse, copse.m_seed_point);
copse.m_planted = true;
return;
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
if (!copse.m_planted)
{
// The first tree for a copse is created here
CreateTree(uuid, copse, copse.m_seed_point, true);
copse.m_planted = true;
return;
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
return;
}
}
}
}
@@ -376,45 +431,49 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
string copsename = ((string)args[0]).Trim();
Copse copseIdentity = null;
foreach (Copse cp in m_copse)
lock(mylock)
{
if (cp.m_name == copsename)
foreach (Copse cp in m_copses)
{
copseIdentity = cp;
if (cp.m_name == copsename)
{
copseIdentity = cp;
}
}
}
if (copseIdentity != null)
{
foreach (UUID tree in copseIdentity.m_trees)
if (copseIdentity != null)
{
if (m_scene.Entities.ContainsKey(tree))
foreach (UUID tree in copseIdentity.m_trees)
{
SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
// Delete tree and alert clients (not silent)
m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
// Delete tree and alert clients (not silent)
m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
copseIdentity.m_trees = null;
m_copses.Remove(copseIdentity);
m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
}
copseIdentity.m_trees = new List<UUID>();
m_copse.Remove(copseIdentity);
m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
}
}
private void HandleTreeStatistics(Object[] args)
{
m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
foreach (Copse cp in m_copse)
m_log.InfoFormat("[TREES]: region {0}:", m_scene.Name);
m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
foreach (Copse cp in m_copses)
{
m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
}
}
@@ -442,7 +501,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
Command treeReloadCommand =
new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees");
new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copses from the in-scene trees");
Command treeRemoveCommand =
new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
@@ -499,34 +558,17 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
treeShape.Scale = scale;
treeShape.State = (byte)treeType;
return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape);
}
#endregion
#region IEntityCreator Members
protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree };
public PCode[] CreationCapabilities { get { return creationCapabilities; } }
public SceneObjectGroup CreateEntity(
UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
{
if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0)
{
m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name);
return null;
}
SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
SceneObjectPart rootPart = sceneObject.GetPart(sceneObject.UUID);
SceneObjectGroup sog = new SceneObjectGroup(uuid, position, rotation, treeShape);
SceneObjectPart rootPart = sog.RootPart;
rootPart.AddFlag(PrimFlags.Phantom);
sceneObject.SetGroup(groupID, null);
m_scene.AddNewSceneObject(sceneObject, true);
sceneObject.InvalidateEffectivePerms();
return sceneObject;
sog.SetGroup(groupID, null);
m_scene.AddNewSceneObject(sog, true, false);
sog.IsSelected = false;
rootPart.IsSelected = false;
sog.InvalidateEffectivePerms();
return sog;
}
#endregion
@@ -569,26 +611,27 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
private void ReloadCopse()
{
m_copse = new List<Copse>();
m_copses = new List<Copse>();
EntityBase[] objs = m_scene.GetEntities();
foreach (EntityBase obj in objs)
List<SceneObjectGroup> grps = m_scene.GetSceneObjectGroups();
foreach (SceneObjectGroup grp in grps)
{
if (obj is SceneObjectGroup)
if(grp.RootPart.Shape.PCode != (byte)PCode.NewTree && grp.RootPart.Shape.PCode != (byte)PCode.Tree)
continue;
if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
{
SceneObjectGroup grp = (SceneObjectGroup)obj;
if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
// Create a new copse definition or add uuid to an existing definition
try
{
// Create a new copse definition or add uuid to an existing definition
try
{
Boolean copsefound = false;
Copse copse = new Copse(grp.Name);
Boolean copsefound = false;
Copse grpcopse = new Copse(grp.Name);
foreach (Copse cp in m_copse)
lock(mylock)
{
foreach (Copse cp in m_copses)
{
if (cp.m_name == copse.m_name)
if (cp.m_name == grpcopse.m_name)
{
copsefound = true;
cp.m_trees.Add(grp.UUID);
@@ -598,15 +641,15 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
if (!copsefound)
{
m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name);
m_copse.Add(copse);
copse.m_trees.Add(grp.UUID);
m_log.InfoFormat("[TREES]: adding copse {0}", grpcopse.m_name);
grpcopse.m_trees.Add(grp.UUID);
m_copses.Add(grpcopse);
}
}
catch
{
m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
}
}
catch
{
m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
}
}
}
@@ -617,8 +660,10 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
if (activeYN)
{
CalculateTrees = new Timer(m_update_ms);
if(CalculateTrees == null)
CalculateTrees = new Timer(m_update_ms);
CalculateTrees.Elapsed += CalculateTrees_Elapsed;
CalculateTrees.AutoReset = false;
CalculateTrees.Start();
}
else
@@ -629,154 +674,251 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
private void growTrees()
{
foreach (Copse copse in m_copse)
{
if (!copse.m_frozen)
{
foreach (UUID tree in copse.m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
if(!m_allowGrow)
return;
if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z)
{
s_tree.Scale += copse.m_rate;
s_tree.ParentGroup.HasGroupChanged = true;
s_tree.ScheduleFullUpdate();
}
}
else
foreach (Copse copse in m_copses)
{
if (copse.m_frozen)
continue;
if(copse.m_trees.Count == 0)
continue;
float maxscale = copse.m_maximum_scale.Z;
float ratescale = 1.0f;
List<UUID> losttrees = new List<UUID>();
foreach (UUID tree in copse.m_trees)
{
SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
if (sog != null && !sog.IsDeleted)
{
SceneObjectPart s_tree = sog.RootPart;
if (s_tree.Scale.Z < maxscale)
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
ratescale = (float)Util.RandomClass.NextDouble();
if(ratescale < 0.2f)
ratescale = 0.2f;
s_tree.Scale += copse.m_rate * ratescale;
sog.HasGroupChanged = true;
s_tree.ScheduleFullUpdate();
}
}
else
losttrees.Add(tree);
}
foreach (UUID tree in losttrees)
copse.m_trees.Remove(tree);
}
}
private void seedTrees()
{
foreach (Copse copse in m_copse)
foreach (Copse copse in m_copses)
{
if (!copse.m_frozen)
{
foreach (UUID tree in copse.m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
if (copse.m_frozen)
continue;
if (copse.m_trees.Count < copse.m_tree_quantity)
{
// Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0)
{
if (Util.RandomClass.NextDouble() > 0.75)
{
SpawnChild(copse, s_tree);
}
}
}
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
if(copse.m_trees.Count == 0)
return;
bool low = copse.m_trees.Count < (int)(copse.m_tree_quantity * 0.8f);
if (!low && Util.RandomClass.NextDouble() < 0.75)
return;
int maxbirths = (int)(copse.m_tree_quantity) - copse.m_trees.Count;
if(maxbirths <= 1)
return;
if(maxbirths > 20)
maxbirths = 20;
float minscale = 0;
if(!low && m_allowGrow)
minscale = copse.m_maximum_scale.Z * 0.75f;;
int i = 0;
UUID[] current = copse.m_trees.ToArray();
while(--maxbirths > 0)
{
if(current.Length > 1)
i = Util.RandomClass.Next(current.Length -1);
UUID tree = current[i];
SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
if (sog != null && !sog.IsDeleted)
{
SceneObjectPart s_tree = sog.RootPart;
// Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
if (s_tree.Scale.Z > minscale)
SpawnChild(copse, s_tree, true);
}
}
else if(copse.m_trees.Contains(tree))
copse.m_trees.Remove(tree);
}
}
}
private void killTrees()
{
foreach (Copse copse in m_copse)
foreach (Copse copse in m_copses)
{
if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity)
if (copse.m_frozen)
continue;
if (Util.RandomClass.NextDouble() < 0.25)
return;
int maxbdeaths = copse.m_trees.Count - (int)(copse.m_tree_quantity * .98f) ;
if(maxbdeaths < 1)
return;
float odds;
float scale = 1.0f / copse.m_maximum_scale.Z;
int ntries = maxbdeaths * 4;
while(ntries-- > 0 )
{
foreach (UUID tree in copse.m_trees)
int next = 0;
if (copse.m_trees.Count > 1)
next = Util.RandomClass.Next(copse.m_trees.Count - 1);
UUID tree = copse.m_trees[next];
SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
if (sog != null && !sog.IsDeleted)
{
double killLikelyhood = 0.0;
if (m_scene.Entities.ContainsKey(tree))
if(m_allowGrow)
{
SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
Math.Pow(selectedTree.Scale.Y, 2) +
Math.Pow(selectedTree.Scale.Z, 2));
foreach (UUID picktree in copse.m_trees)
{
if (picktree != tree)
{
SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart;
double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
Math.Pow(pickedTree.Scale.Y, 2) +
Math.Pow(pickedTree.Scale.Z, 2));
double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition);
killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
}
}
if (Util.RandomClass.NextDouble() < killLikelyhood)
{
// Delete tree and alert clients (not silent)
m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
copse.m_trees.Remove(selectedTree.ParentGroup.UUID);
break;
}
odds = sog.RootPart.Scale.Z * scale;
odds = odds * odds * odds;
odds *= (float)Util.RandomClass.NextDouble();
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
odds = (float)Util.RandomClass.NextDouble();
odds = odds * odds * odds;
}
if(odds > 0.9f)
{
m_scene.DeleteSceneObject(sog, false);
if(maxbdeaths <= 0)
break;
}
}
else
{
copse.m_trees.Remove(tree);
if(copse.m_trees.Count - (int)(copse.m_tree_quantity * .98f) <= 0 )
break;
}
}
}
}
private void SpawnChild(Copse copse, SceneObjectPart s_tree)
private void SpawnChild(Copse copse, SceneObjectPart s_tree, bool low)
{
Vector3 position = new Vector3();
double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
float randX = copse.m_maximum_scale.X * 1.25f;
float randY = copse.m_maximum_scale.Y * 1.25f;
float r = (float)Util.RandomClass.NextDouble();
randX *= 2.0f * r - 1.0f;
position.X = s_tree.AbsolutePosition.X + (float)randX;
r = (float)Util.RandomClass.NextDouble();
randY *= 2.0f * r - 1.0f;
position.Y = s_tree.AbsolutePosition.Y + (float)randY;
if (position.X <= (m_scene.RegionInfo.RegionSizeX - 1) && position.X >= 0 &&
position.Y <= (m_scene.RegionInfo.RegionSizeY - 1) && position.Y >= 0 &&
Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
{
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
if (position.X > (m_scene.RegionInfo.RegionSizeX - 1) || position.X <= 0 ||
position.Y > (m_scene.RegionInfo.RegionSizeY - 1) || position.Y <= 0)
return;
CreateTree(uuid, copse, position);
}
randX = position.X - copse.m_seed_point.X;
randX *= randX;
randY = position.Y - copse.m_seed_point.Y;
randY *= randY;
randX += randY;
if(randX > copse.m_range * copse.m_range)
return;
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
CreateTree(uuid, copse, position, low);
}
private void CreateTree(UUID uuid, Copse copse, Vector3 position)
private void CreateTree(UUID uuid, Copse copse, Vector3 position, bool randomScale)
{
position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high)
{
SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false);
if (position.Z < copse.m_treeline_low || position.Z > copse.m_treeline_high)
return;
tree.Name = copse.ToString();
copse.m_trees.Add(tree.UUID);
tree.SendGroupFullUpdate();
Vector3 scale = copse.m_initial_scale;
if(randomScale)
{
try
{
float t;
float r = (float)Util.RandomClass.NextDouble();
r *= (float)Util.RandomClass.NextDouble();
r *= (float)Util.RandomClass.NextDouble();
t = copse.m_maximum_scale.X / copse.m_initial_scale.X;
if(t < 1.0)
t = 1 / t;
t = t * r + 1.0f;
scale.X *= t;
t = copse.m_maximum_scale.Y / copse.m_initial_scale.Y;
if(t < 1.0)
t = 1 / t;
t = t * r + 1.0f;
scale.Y *= t;
t = copse.m_maximum_scale.Z / copse.m_initial_scale.Z;
if(t < 1.0)
t = 1 / t;
t = t * r + 1.0f;
scale.Z *= t;
}
catch
{
scale = copse.m_initial_scale;
}
}
SceneObjectGroup tree = AddTree(uuid, UUID.Zero, scale, Quaternion.Identity, position, copse.m_tree_type, false);
tree.Name = copse.ToString();
copse.m_trees.Add(tree.UUID);
tree.RootPart.ScheduleFullUpdate();
}
private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
{
growTrees();
seedTrees();
killTrees();
if(!m_scene.IsRunning)
return;
if(Monitor.TryEnter(mylock))
{
try
{
if(m_scene.LoginsEnabled )
{
growTrees();
seedTrees();
killTrees();
}
}
catch { }
if(CalculateTrees != null)
CalculateTrees.Start();
Monitor.Exit(mylock);
}
}
}
}