public static void Main(string[] args) { ArgvConfigSource argvSource = new ArgvConfigSource(args); argvSource.AddSwitch("Startup", "console", "c"); argvSource.AddSwitch("Startup", "xmlfile", "x"); XmlConfigurator.Configure(); GridServerBase app = new GridServerBase(); IConfig startupConfig = argvSource.Configs["Startup"]; if (startupConfig != null) { app.m_consoleType = startupConfig.GetString("console", "local"); app.m_configFile = startupConfig.GetString("xmlfile", "GridServer_Config.xml"); } app.m_configSource = argvSource; // if (args.Length > 0 && args[0] == "-setuponly") // { // app.Config(); // } // else // { app.Startup(); app.Work(); // } }
public Tray() { InitializeComponent(); FormClosing += Tray_FormClosing; Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); WindowState = FormWindowState.Minimized; ShowInTaskbar = false; MinimizeBox = false; MaximizeBox = false; // Process any command line parameters ArgvConfigSource source = new ArgvConfigSource(Environment.GetCommandLineArgs()); source.AddSwitch("Main", "watch-process", "p"); source.AddSwitch("Main", "library", "l"); // Create a watcher _watcher = new Watcher(source); _watcher.OnNotifyActivity += _watcher_OnNotifyActivity; _watcher.OnNotifyRestart += _watcher_OnNotifyRestart; _watcher.OnNotifyError += _watcher_OnNotifyError; // Start a thread for the watcher _watchThread = new Thread(new ThreadStart(_watcher.Run)); _watchThread.Start(); // Watch params libraryLabel.Text = source.Configs["Main"].GetString("library", Settings.Default.ClientLibrary); processLabel.Text = source.Configs["Main"].GetString("watch-process", Settings.Default.ProcessPath); }
static int Main(string[] args) { m_Server = new ServicesServerBase("Client", args); IConfig serverConfig = m_Server.Config.Configs["Startup"]; if (serverConfig == null) { System.Console.WriteLine("Startup config section missing in .ini file"); throw new Exception("Configuration error"); } ArgvConfigSource argvConfig = new ArgvConfigSource(args); argvConfig.AddSwitch("Startup", "host", "h"); argvConfig.AddSwitch("Startup", "port", "p"); argvConfig.AddSwitch("Startup", "user", "u"); argvConfig.AddSwitch("Startup", "pass", "P"); m_Server.Config.Merge(argvConfig); m_User = serverConfig.GetString("user", "Test"); m_Host = serverConfig.GetString("host", "localhost"); m_Port = serverConfig.GetInt("port", 8003); m_Pass = serverConfig.GetString("pass", "secret"); Requester.MakeRequest("http://"+m_Host+":"+m_Port.ToString()+"/StartSession/", String.Format("USER={0}&PASS={1}", m_User, m_Pass), LoginReply); int res = m_Server.Run(); Environment.Exit(res); return 0; }
public void AddSwitchCase () { string[] arguments = new string[] { "-H" }; ArgvConfigSource source = new ArgvConfigSource (arguments); source.AddSwitch ("Base", "help", "h"); source.AddSwitch ("Base", "heat", "H"); IConfig config = source.Configs["Base"]; Assert.IsNull (config.Get ("nothere")); Assert.AreEqual ("", config.Get ("help")); Assert.IsNotNull (config.Get ("heat")); }
private static IConfig ParseConfig(String[] args) { //Set up our nifty config.. thanks to nini ArgvConfigSource cs = new ArgvConfigSource(args); // TODO: unused: cs.AddSwitch("Startup", "botcount","n"); cs.AddSwitch("Startup", "loginuri","l"); cs.AddSwitch("Startup", "firstname"); cs.AddSwitch("Startup", "lastname"); cs.AddSwitch("Startup", "password"); cs.AddSwitch("Startup", "help","h"); IConfig ol = cs.Configs["Startup"]; return ol; }
public void GetArguments () { string[] arguments = new string[] { "--help", "-d", "doc.xml", "/pet:cat"}; ArgvConfigSource source = new ArgvConfigSource (arguments); source.AddSwitch ("Base", "help", "h"); source.AddSwitch ("Base", "doc", "d"); source.AddSwitch ("Base", "short"); string[] args = source.GetArguments (); Assert.IsTrue (args != arguments); // must be a different instance Assert.AreEqual (4, args.Length); Assert.AreEqual ("--help", args[0]); Assert.AreEqual ("-d", args[1]); Assert.AreEqual ("doc.xml", args[2]); Assert.AreEqual ("/pet:cat", args[3]); }
public void AddSwitch () { string[] arguments = new string[] { "--help", "-d", "doc.xml", "/pet:cat"}; ArgvConfigSource source = new ArgvConfigSource (arguments); source.AddSwitch ("Base", "help", "h"); source.AddSwitch ("Base", "doc", "d"); IConfig config = source.Configs["Base"]; Assert.IsNotNull (config.Get ("help")); Assert.IsNull (config.Get ("h")); Assert.IsNull (config.Get ("not here")); Assert.IsNull (config.Get ("pets")); Assert.AreEqual ("doc.xml", config.Get ("doc")); source.AddSwitch ("Pets", "pet"); config = source.Configs["Pets"]; Assert.IsNotNull (config.Get ("pet")); Assert.AreEqual ("cat", config.Get ("pet")); }
public static void Main(string[] args) { ArgvConfigSource configSource = new ArgvConfigSource(args); XmlConfigurator.Configure(); configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inidirectory"); ConfigurationLoader configurationLoader = new ConfigurationLoader(); ConfigSettings appSettings; NetworkServersInfo networkSettings; configurationLoader.LoadConfigSettings(configSource, out appSettings, out networkSettings); MigrationWorker app = new MigrationWorker(configSource); app.Start(); Console.WriteLine("Hit enter to quit"); Console.ReadLine(); }
/// <summary> /// The main function for this application which calls controllers to get them setup /// </summary> /// <param name="args">Arguments from the commandline</param> public static void Main( string[] args ) { ArgvConfigSource source = new ArgvConfigSource(args); source.AddSwitch("CommandLineArgs", "mode", "m"); source.AddSwitch("CommandLineArgs", "config", "c"); source.AddSwitch("CommandLineArgs", "logpath", "l"); source.AddSwitch("CommandLineArgs", "help", "h"); source.AddSwitch("CommandLineArgs", "serverip"); source.AddSwitch("CommandLineArgs", "serverport", "p"); source.AddSwitch("CommandLineArgs", "url"); source.AddSwitch("CommandLineArgs", "nochat"); bool help = source.Configs["CommandLineArgs"].Contains( "help" ); if( help ) { Console.WriteLine( @"Help text goes here" ); System.Environment.Exit( 0 ); } string mode = source.Configs["CommandLineArgs"].GetString( "mode","clientandserver" ); if( mode == "clientonly" ) { ClientController.Instance.Initialize( source ); ClientController.Instance.InitializeClient(); } else if ( mode == "serveronly" ) { ServerController.Instance.Initialize( source ); ServerController.Instance.InitializeServer(); } else if ( mode == "clientandserver" ) { ClientController.Instance.Initialize( source ); ServerController.Instance.Initialize( source ); ClientController.Instance.InitializeClientWithServer(); } else { Console.WriteLine( "You are trying to start Metaverse in an unknown mode. Please type \"Metaverse.exe -help\" for more options." ); System.Environment.Exit( 0 ); } return; }
static void Main(string[] args) { XmlConfigurator.Configure(); ArgvConfigSource configSource = new ArgvConfigSource(args); configSource.AddSwitch("Startup", "inifile"); AssetInventoryServer server = new AssetInventoryServer(configSource); if (server.Start()) { Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { m_log.Info("AssetInventory server is shutting down..."); server.Shutdown(); Environment.Exit(0); }; server.Work(); } }
public void SetupSettings(string[] args) { var argConfig = new ArgvConfigSource(args); argConfig.AddSwitch("Args", "ini", "i"); var file = argConfig.Configs["Args"].Get("ini", defaultFileSettings); if ( File.Exists(file) ) { Settings.Load(file); CoreSettings = Settings.Configs["Core"]; NetworkSettings = Settings.Configs["Network"]; WebSettings = Settings.Configs["Web"]; } else { CoreSettings = Settings.Configs.Add("Core"); NetworkSettings = Settings.Configs.Add("Network"); WebSettings = Settings.Configs.Add("Web"); } }
//could move our main function into OpenSimMain and kill this class public static void Main(string[] args) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile)); m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", logConfigFile); } else { XmlConfigurator.Configure(); m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met m_log.Info("Performing compatibility checks... "); string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { m_log.Info("Environment is compatible.\n"); } else { m_log.Warn("Environment is unsupported (" + supported + ")\n"); } // Configure nIni aliases and localles Culture.SetCurrentCulture(); configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); configSource.AddSwitch("Startup", "background"); configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "gridmode"); configSource.AddSwitch("Startup", "physics"); configSource.AddSwitch("Startup", "gui"); configSource.AddConfig("StandAlone"); configSource.AddConfig("Network"); // Check if we're running in the background or not bool background = configSource.Configs["Startup"].GetBoolean("background", false); // Check if we're saving crashes m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false); // load Crash directory config m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); if (background) { m_sim = new OpenSimBackground(configSource); m_sim.Startup(); } else { m_sim = new OpenSim(configSource); m_sim.Startup(); while (true) { try { // Block thread here for input MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } } }
private static IConfig ParseConfig(String[] args) { //Set up our nifty config.. thanks to nini ArgvConfigSource cs = new ArgvConfigSource(args); cs.AddSwitch("Startup", "connect", "c"); cs.AddSwitch("Startup", "botcount", "n"); cs.AddSwitch("Startup", "from", "f"); cs.AddSwitch("Startup", "loginuri", "l"); cs.AddSwitch("Startup", "start", "s"); cs.AddSwitch("Startup", "firstname"); cs.AddSwitch("Startup", "lastname"); cs.AddSwitch("Startup", "password"); cs.AddSwitch("Startup", "behaviours", "b"); cs.AddSwitch("Startup", "help", "h"); cs.AddSwitch("Startup", "wear"); IConfig ol = cs.Configs["Startup"]; return ol; }
private static bool _IsHandlingException; // Make sure we don't go recursive on ourself //could move our main function into OpenSimMain and kill this class public static void BaseMain(string[] args, string defaultIniFile, ISimulationBase simBase) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new FileInfo(logConfigFile)); //MainConsole.Instance.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", // logConfigFile); } else { XmlConfigurator.Configure(); //MainConsole.Instance.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } // Increase the number of IOCP threads available. Mono defaults to a tragically low number int workerThreads, iocpThreads; ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); //MainConsole.Instance.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} worker threads and {1} IOCP threads", workerThreads, iocpThreads); if (workerThreads < 500 || iocpThreads < 1000) { workerThreads = 500; iocpThreads = 1000; //MainConsole.Instance.Info("[OPENSIM MAIN]: Bumping up to 500 worker threads and 1000 IOCP threads"); ThreadPool.SetMaxThreads(workerThreads, iocpThreads); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met //MainConsole.Instance.Info("[Setup]: Performing compatibility checks... \n"); string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { int minWorker, minIOC; // Get the current settings. ThreadPool.GetMinThreads(out minWorker, out minIOC); //MainConsole.Instance.InfoFormat("[Setup]: Environment is compatible. Thread Workers: {0}, IO Workers {1}\n", minWorker, minIOC); } else { MainConsole.Instance.Warn("[Setup]: Environment is unsupported (" + supported + ")\n"); #if BlockUnsupportedVersions Thread.Sleep(10000); //Sleep 10 seconds return; #endif } // Configure nIni aliases and localles Culture.SetCurrentCulture(); configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); ///Command line switches configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inigrid"); configSource.AddSwitch("Startup", "inisim"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "oldoptions"); configSource.AddSwitch("Startup", "inishowfileloading"); configSource.AddSwitch("Startup", "mainIniDirectory"); configSource.AddSwitch("Startup", "mainIniFileName"); configSource.AddSwitch("Startup", "secondaryIniFileName"); configSource.AddConfig("Network"); IConfigSource m_configSource = Configuration(configSource, defaultIniFile); // Check if we're saving crashes m_saveCrashDumps = m_configSource.Configs["Startup"].GetBoolean("save_crashes", m_saveCrashDumps); // load Crash directory config m_crashDir = m_configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); // check auto restart bool AutoRestart = m_configSource.Configs["Startup"].GetBoolean("AutoRestartOnCrash", true); //Set up the error reporting if (m_configSource.Configs["ErrorReporting"] != null) { m_sendErrorReport = m_configSource.Configs["ErrorReporting"].GetBoolean("SendErrorReports", true); m_urlToPostErrors = m_configSource.Configs["ErrorReporting"].GetString("ErrorReportingURL", m_urlToPostErrors); } bool Running = true; //If auto restart is set, then we always run. // otherwise, just run the first time that Running == true while (AutoRestart || Running) { //Always run once, then disable this Running = false; //Initialize the sim base now Startup(configSource, m_configSource, simBase.Copy(), args); } }
// Handle all the automagical stuff // public ServicesServerBase(string prompt, string[] args) { m_startuptime = DateTime.Now; // Save raw arguments // m_Arguments = args; // Read command line // ArgvConfigSource argvConfig = new ArgvConfigSource(args); argvConfig.AddSwitch("Startup", "console", "c"); argvConfig.AddSwitch("Startup", "logfile", "l"); argvConfig.AddSwitch("Startup", "inifile", "i"); argvConfig.AddSwitch("Startup", "prompt", "p"); argvConfig.AddSwitch("Startup", "logconfig", "g"); // Automagically create the ini file name // string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); string iniFile = fileName + ".ini"; string logConfig = null; IConfig startupConfig = argvConfig.Configs["Startup"]; if (startupConfig != null) { // Check if a file name was given on the command line // iniFile = startupConfig.GetString("inifile", iniFile); // // Check if a prompt was given on the command line prompt = startupConfig.GetString("prompt", prompt); // // Check for a Log4Net config file on the command line logConfig =startupConfig.GetString("logconfig",logConfig); } // Find out of the file name is a URI and remote load it // if it's possible. Load it as a local file otherwise. // Uri configUri; try { if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp) { XmlReader r = XmlReader.Create(iniFile); m_Config = new XmlConfigSource(r); } else { m_Config = new IniConfigSource(iniFile); } } catch (Exception e) { System.Console.WriteLine("Error reading from config source. {0}", e.Message); Environment.Exit(1); } // Merge the configuration from the command line into the // loaded file // m_Config.Merge(argvConfig); // Refresh the startupConfig post merge // if (m_Config.Configs["Startup"] != null) { startupConfig = m_Config.Configs["Startup"]; } prompt = startupConfig.GetString("Prompt", prompt); // Allow derived classes to load config before the console is // opened. // ReadConfig(); // Create main console // string consoleType = "local"; if (startupConfig != null) consoleType = startupConfig.GetString("console", consoleType); if (consoleType == "basic") { MainConsole.Instance = new CommandConsole(prompt); } else if (consoleType == "rest") { MainConsole.Instance = new RemoteConsole(prompt); ((RemoteConsole)MainConsole.Instance).ReadConfig(Config); } else { MainConsole.Instance = new LocalConsole(prompt); } // Configure the appenders for log4net // OpenSimAppender consoleAppender = null; FileAppender fileAppender = null; if (logConfig != null) { FileInfo cfg = new FileInfo(logConfig); XmlConfigurator.Configure(cfg); } else { XmlConfigurator.Configure(); } ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "Console") { consoleAppender = (OpenSimAppender)appender; } if (appender.Name == "LogFileAppender") { fileAppender = (FileAppender)appender; } } if (consoleAppender == null) { System.Console.WriteLine("No console appender found. Server can't start"); Thread.CurrentThread.Abort(); } else { consoleAppender.Console = (ConsoleBase)MainConsole.Instance; if (null == consoleAppender.Threshold) consoleAppender.Threshold = Level.All; } // Set log file // if (fileAppender != null) { if (startupConfig != null) { string cfgFileName = startupConfig.GetString("logfile", null); if (cfgFileName != null) { fileAppender.File = cfgFileName; fileAppender.ActivateOptions(); } } } if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty) { CreatePIDFile(startupConfig.GetString("PIDFile")); } // Register the quit command // MainConsole.Instance.Commands.AddCommand("General", false, "quit", "quit", "Quit the application", HandleQuit); MainConsole.Instance.Commands.AddCommand("General", false, "shutdown", "shutdown", "Quit the application", HandleQuit); // Register a command to read other commands from a file MainConsole.Instance.Commands.AddCommand("General", false, "command-script", "command-script <script>", "Run a command script from file", HandleScript); MainConsole.Instance.Commands.AddCommand("General", false, "show uptime", "show uptime", "Show server uptime", HandleShow); // Allow derived classes to perform initialization that // needs to be done after the console has opened // Initialise(); }
//could move our main function into OpenSimMain and kill this class public static void Main(string[] args) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile)); m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", logConfigFile); } else { XmlConfigurator.Configure(); m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } // Increase the number of IOCP threads available. Mono defaults to a tragically low number int workerThreads, iocpThreads; System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} worker threads and {1} IOCP threads", workerThreads, iocpThreads); if (workerThreads < 500 || iocpThreads < 1000) { workerThreads = 500; iocpThreads = 1000; m_log.Info("[OPENSIM MAIN]: Bumping up to 500 worker threads and 1000 IOCP threads"); System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met m_log.Info("Performing compatibility checks... \n"); string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { m_log.Info("Environment is compatible.\n"); } else { m_log.Warn("Environment is unsupported (" + supported + ")\n"); } // Configure nIni aliases and localles Culture.SetCurrentCulture(); // Validate that the user has the most basic configuration done // If not, offer to do the most basic configuration for them warning them along the way of the importance of // reading these files. /* m_log.Info("Checking for reguired configuration...\n"); bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini"))); bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini")); bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini")); bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini")); if ((OpenSim_Ini) && ( (StanaloneCommon_ProperCased || StanaloneCommon_lowercased || GridCommon_ProperCased || GridCommon_lowerCased ))) { m_log.Info("Required Configuration Files Found\n"); } else { MainConsole.Instance = new LocalConsole("Region"); string resp = MainConsole.Instance.CmdPrompt( "\n\n*************Required Configuration files not found.*************\n\n OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?", "yes"); if (resp == "yes") { if (!(OpenSim_Ini)) { try { File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"), Path.Combine(Util.configDir(), "OpenSim.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } } if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased)) { try { File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"), Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } } } MainConsole.Instance = null; } */ configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); configSource.AddSwitch("Startup", "background"); configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "physics"); configSource.AddSwitch("Startup", "gui"); configSource.AddSwitch("Startup", "console"); configSource.AddConfig("StandAlone"); configSource.AddConfig("Network"); // Check if we're running in the background or not bool background = configSource.Configs["Startup"].GetBoolean("background", false); // Check if we're saving crashes m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false); // load Crash directory config m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); if (background) { m_sim = new OpenSimBackground(configSource); m_sim.Startup(); } else { m_sim = new OpenSim(configSource); m_sim.Startup(); while (true) { try { // Block thread here for input MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } } }
//could move our main function into OpenSimMain and kill this class public static void Main(string[] args) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); ServicePointManager.DefaultConnectionLimit = 12; // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile)); m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", logConfigFile); } else { XmlConfigurator.Configure(); m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } m_log.InfoFormat( "[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture); string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU"); m_log.InfoFormat( "[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset"); // Verify the Threadpool allocates or uses enough worker and IO completion threads // .NET 2.0, workerthreads default to 50 * numcores // .NET 3.0, workerthreads defaults to 250 * numcores // .NET 4.0, workerthreads are dynamic based on bitness and OS resources // Max IO Completion threads are 1000 on all 3 CLRs // // Mono 2.10.9 to at least Mono 3.1, workerthreads default to 100 * numcores, iocp threads to 4 * numcores int workerThreadsMin = 500; int workerThreadsMax = 1000; // may need further adjustment to match other CLR int iocpThreadsMin = 1000; int iocpThreadsMax = 2000; // may need further adjustment to match other CLR { int currentMinWorkerThreads, currentMinIocpThreads; System.Threading.ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIocpThreads); m_log.InfoFormat( "[OPENSIM MAIN]: Runtime gave us {0} min worker threads and {1} min IOCP threads", currentMinWorkerThreads, currentMinIocpThreads); } int workerThreads, iocpThreads; System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads); if (workerThreads < workerThreadsMin) { workerThreads = workerThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max worker threads to {0}",workerThreads); } if (workerThreads > workerThreadsMax) { workerThreads = workerThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting max worker threads to {0}",workerThreads); } // Increase the number of IOCP threads available. // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17) if (iocpThreads < iocpThreadsMin) { iocpThreads = iocpThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max IOCP threads to {0}",iocpThreads); } // Make sure we don't overallocate IOCP threads and thrash system resources if ( iocpThreads > iocpThreadsMax ) { iocpThreads = iocpThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting max IOCP completion threads to {0}",iocpThreads); } // set the resulting worker and IO completion thread counts back to ThreadPool if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) ) { m_log.InfoFormat( "[OPENSIM MAIN]: Threadpool set to {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads); } else { m_log.Warn("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect."); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { m_log.Info("[OPENSIM MAIN]: Environment is supported by OpenSimulator."); } else { m_log.Warn("[OPENSIM MAIN]: Environment is not supported by OpenSimulator (" + supported + ")\n"); } // Configure nIni aliases and localles Culture.SetCurrentCulture(); // Validate that the user has the most basic configuration done // If not, offer to do the most basic configuration for them warning them along the way of the importance of // reading these files. /* m_log.Info("Checking for reguired configuration...\n"); bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini"))); bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini")); bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini")); bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini")); if ((OpenSim_Ini) && ( (StanaloneCommon_ProperCased || StanaloneCommon_lowercased || GridCommon_ProperCased || GridCommon_lowerCased ))) { m_log.Info("Required Configuration Files Found\n"); } else { MainConsole.Instance = new LocalConsole("Region"); string resp = MainConsole.Instance.CmdPrompt( "\n\n*************Required Configuration files not found.*************\n\n OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?", "yes"); if (resp == "yes") { if (!(OpenSim_Ini)) { try { File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"), Path.Combine(Util.configDir(), "OpenSim.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } } if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased)) { try { File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"), Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } } } MainConsole.Instance = null; } */ configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); configSource.Alias.AddAlias("Yes", true); configSource.Alias.AddAlias("No", false); configSource.AddSwitch("Startup", "background"); configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "physics"); configSource.AddSwitch("Startup", "gui"); configSource.AddSwitch("Startup", "console"); configSource.AddSwitch("Startup", "save_crashes"); configSource.AddSwitch("Startup", "crash_dir"); configSource.AddConfig("StandAlone"); configSource.AddConfig("Network"); // Check if we're running in the background or not bool background = configSource.Configs["Startup"].GetBoolean("background", false); // Check if we're saving crashes m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false); // load Crash directory config m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); if (background) { m_sim = new OpenSimBackground(configSource); m_sim.Startup(); } else { m_sim = new OpenSim(configSource); m_sim.Startup(); while (true) { try { // Block thread here for input MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } } }
// Handle all the automagical stuff // public ServicesServerBase(string prompt, string[] args) : base() { // Save raw arguments m_Arguments = args; // Read command line ArgvConfigSource argvConfig = new ArgvConfigSource(args); argvConfig.AddSwitch("Startup", "console", "c"); argvConfig.AddSwitch("Startup", "logfile", "l"); argvConfig.AddSwitch("Startup", "inifile", "i"); argvConfig.AddSwitch("Startup", "prompt", "p"); argvConfig.AddSwitch("Startup", "logconfig", "g"); // Automagically create the ini file name string fileName = ""; if (Assembly.GetEntryAssembly() != null) fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); string iniFile = fileName + ".ini"; string logConfig = null; IConfig startupConfig = argvConfig.Configs["Startup"]; if (startupConfig != null) { // Check if a file name was given on the command line iniFile = startupConfig.GetString("inifile", iniFile); // Check if a prompt was given on the command line prompt = startupConfig.GetString("prompt", prompt); // Check for a Log4Net config file on the command line logConfig =startupConfig.GetString("logconfig", logConfig); } Config = ReadConfigSource(iniFile); List<string> sources = new List<string>(); sources.Add(iniFile); int sourceIndex = 1; while (AddIncludes(Config, sources)) { for ( ; sourceIndex < sources.Count ; ++sourceIndex) { IConfigSource s = ReadConfigSource(sources[sourceIndex]); Config.Merge(s); } } // Merge OpSys env vars Console.WriteLine("[CONFIG]: Loading environment variables for Config"); Util.MergeEnvironmentToConfig(Config); // Merge the configuration from the command line into the loaded file Config.Merge(argvConfig); Config.ReplaceKeyValues(); // Refresh the startupConfig post merge if (Config.Configs["Startup"] != null) { startupConfig = Config.Configs["Startup"]; } if (startupConfig != null) { m_configDirectory = startupConfig.GetString("ConfigDirectory", m_configDirectory); prompt = startupConfig.GetString("Prompt", prompt); } // Allow derived classes to load config before the console is opened. ReadConfig(); // Create main console string consoleType = "local"; if (startupConfig != null) consoleType = startupConfig.GetString("console", consoleType); if (consoleType == "basic") { MainConsole.Instance = new CommandConsole(prompt); } else if (consoleType == "rest") { MainConsole.Instance = new RemoteConsole(prompt); ((RemoteConsole)MainConsole.Instance).ReadConfig(Config); } else if (consoleType == "mock") { MainConsole.Instance = new MockConsole(); } else if (consoleType == "local") { MainConsole.Instance = new LocalConsole(prompt, startupConfig); } m_console = MainConsole.Instance; if (logConfig != null) { FileInfo cfg = new FileInfo(logConfig); XmlConfigurator.Configure(cfg); } else { XmlConfigurator.Configure(); } LogEnvironmentInformation(); RegisterCommonAppenders(startupConfig); if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty) { CreatePIDFile(startupConfig.GetString("PIDFile")); } RegisterCommonCommands(); RegisterCommonComponents(Config); // Allow derived classes to perform initialization that // needs to be done after the console has opened Initialise(); }
static bool _IsHandlingException; // Make sure we don't go recursive on ourself #endregion Fields #region Methods //could move our main function into OpenSimMain and kill this class public static void BaseMain(string[] args, string defaultIniFile, ISimulationBase simBase) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); if (!args.Contains("-skipconfig")) Configure(false); // Increase the number of IOCP threads available. Mono defaults to a tragically low number int workerThreads, iocpThreads; ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); //MainConsole.Instance.InfoFormat("[Universe MAIN]: Runtime gave us {0} worker threads and {1} IOCP threads", workerThreads, iocpThreads); if (workerThreads < 500 || iocpThreads < 1000) { workerThreads = 500; iocpThreads = 1000; //MainConsole.Instance.Info("[Universe MAIN]: Bumping up to 500 worker threads and 1000 IOCP threads"); ThreadPool.SetMaxThreads(workerThreads, iocpThreads); } BinMigratorService service = new BinMigratorService(); service.MigrateBin(); // Configure nIni aliases and localles Culture.SystemCultureInfo = CultureInfo.CurrentCulture; Culture.SetCurrentCulture(); configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); //Command line switches configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inigrid"); configSource.AddSwitch("Startup", "inisim"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "oldoptions"); configSource.AddSwitch("Startup", "inishowfileloading"); configSource.AddSwitch("Startup", "mainIniDirectory"); configSource.AddSwitch("Startup", "mainIniFileName"); configSource.AddSwitch("Startup", "secondaryIniFileName"); configSource.AddSwitch("Startup", "RegionDataFileName"); configSource.AddSwitch("Console", "Console"); configSource.AddSwitch("Console", "LogAppendName"); configSource.AddSwitch("Console", "LogPath"); configSource.AddSwitch("Network", "http_listener_port"); IConfigSource m_configSource = Configuration(configSource, defaultIniFile); // Check if we're saving crashes m_saveCrashDumps = m_configSource.Configs["Startup"].GetBoolean("save_crashes", m_saveCrashDumps); // load Crash directory config m_crashDir = m_configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); //Initialize the sim base now Startup(configSource, m_configSource, simBase.Copy(), args); }
// Handle all the automagical stuff // public ServicesServerBase(string prompt, string[] args) : base() { // Save raw arguments // m_Arguments = args; // Read command line // ArgvConfigSource argvConfig = new ArgvConfigSource(args); argvConfig.AddSwitch("Startup", "console", "c"); argvConfig.AddSwitch("Startup", "logfile", "l"); argvConfig.AddSwitch("Startup", "inifile", "i"); argvConfig.AddSwitch("Startup", "prompt", "p"); argvConfig.AddSwitch("Startup", "logconfig", "g"); // Automagically create the ini file name // string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); string iniFile = fileName + ".ini"; string logConfig = null; IConfig startupConfig = argvConfig.Configs["Startup"]; if (startupConfig != null) { // Check if a file name was given on the command line // iniFile = startupConfig.GetString("inifile", iniFile); // // Check if a prompt was given on the command line prompt = startupConfig.GetString("prompt", prompt); // // Check for a Log4Net config file on the command line logConfig =startupConfig.GetString("logconfig",logConfig); } // Find out of the file name is a URI and remote load it // if it's possible. Load it as a local file otherwise. // Uri configUri; try { if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp) { XmlReader r = XmlReader.Create(iniFile); Config = new XmlConfigSource(r); } else { Config = new IniConfigSource(iniFile); } } catch (Exception e) { System.Console.WriteLine("Error reading from config source. {0}", e.Message); Environment.Exit(1); } // Merge the configuration from the command line into the // loaded file // Config.Merge(argvConfig); // Refresh the startupConfig post merge // if (Config.Configs["Startup"] != null) { startupConfig = Config.Configs["Startup"]; } ConfigDirectory = startupConfig.GetString("ConfigDirectory", "."); prompt = startupConfig.GetString("Prompt", prompt); // Allow derived classes to load config before the console is // opened. // ReadConfig(); // Create main console // string consoleType = "local"; if (startupConfig != null) consoleType = startupConfig.GetString("console", consoleType); if (consoleType == "basic") { MainConsole.Instance = new CommandConsole(prompt); } else if (consoleType == "rest") { MainConsole.Instance = new RemoteConsole(prompt); ((RemoteConsole)MainConsole.Instance).ReadConfig(Config); } else { MainConsole.Instance = new LocalConsole(prompt); } m_console = MainConsole.Instance; if (logConfig != null) { FileInfo cfg = new FileInfo(logConfig); XmlConfigurator.Configure(cfg); } else { XmlConfigurator.Configure(); } LogEnvironmentInformation(); RegisterCommonAppenders(startupConfig); if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty) { CreatePIDFile(startupConfig.GetString("PIDFile")); } RegisterCommonCommands(); // Register the quit command // MainConsole.Instance.Commands.AddCommand("General", false, "quit", "quit", "Quit the application", HandleQuit); MainConsole.Instance.Commands.AddCommand("General", false, "shutdown", "shutdown", "Quit the application", HandleQuit); // Allow derived classes to perform initialization that // needs to be done after the console has opened // Initialise(); }
//could move our main function into OpenSimMain and kill this class public static void Main(string[] args) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); ServicePointManager.DefaultConnectionLimit = 12; // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile)); m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", logConfigFile); } else { XmlConfigurator.Configure(); m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } m_log.InfoFormat( "[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture); string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU"); m_log.InfoFormat( "[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset"); // Verify the Threadpool allocates or uses enough worker and IO completion threads // .NET 2.0, workerthreads default to 50 * numcores // .NET 3.0, workerthreads defaults to 250 * numcores // .NET 4.0, workerthreads are dynamic based on bitness and OS resources // Max IO Completion threads are 1000 on all 3 CLRs // // Mono 2.10.9 to at least Mono 3.1, workerthreads default to 100 * numcores, iocp threads to 4 * numcores int workerThreadsMin = 500; int workerThreadsMax = 1000; // may need further adjustment to match other CLR int iocpThreadsMin = 1000; int iocpThreadsMax = 2000; // may need further adjustment to match other CLR { int currentMinWorkerThreads, currentMinIocpThreads; System.Threading.ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIocpThreads); m_log.InfoFormat( "[OPENSIM MAIN]: Runtime gave us {0} min worker threads and {1} min IOCP threads", currentMinWorkerThreads, currentMinIocpThreads); } int workerThreads, iocpThreads; System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads); if (workerThreads < workerThreadsMin) { workerThreads = workerThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up to max worker threads to {0}",workerThreads); } if (workerThreads > workerThreadsMax) { workerThreads = workerThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting max worker threads to {0}",workerThreads); } // Increase the number of IOCP threads available. // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17) if (iocpThreads < iocpThreadsMin) { iocpThreads = iocpThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max IOCP threads to {0}",iocpThreads); } // Make sure we don't overallocate IOCP threads and thrash system resources if ( iocpThreads > iocpThreadsMax ) { iocpThreads = iocpThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting max IOCP completion threads to {0}",iocpThreads); } // set the resulting worker and IO completion thread counts back to ThreadPool if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) ) { m_log.InfoFormat( "[OPENSIM MAIN]: Threadpool set to {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads); } else { m_log.Warn("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect."); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { m_log.Info("[OPENSIM MAIN]: Environment is supported by OpenSimulator."); } else { m_log.Warn("[OPENSIM MAIN]: Environment is not supported by OpenSimulator (" + supported + ")\n"); } // Configure nIni aliases and localles Culture.SetCurrentCulture(); configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); configSource.Alias.AddAlias("Yes", true); configSource.Alias.AddAlias("No", false); configSource.AddSwitch("Startup", "background"); configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "physics"); configSource.AddSwitch("Startup", "gui"); configSource.AddSwitch("Startup", "console"); configSource.AddSwitch("Startup", "save_crashes"); configSource.AddSwitch("Startup", "crash_dir"); configSource.AddConfig("StandAlone"); configSource.AddConfig("Network"); // Check if we're running in the background or not bool background = configSource.Configs["Startup"].GetBoolean("background", false); // Check if we're saving crashes m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false); // load Crash directory config m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); if (background) { m_sim = new OpenSimBackground(configSource); m_sim.Startup(); } else { m_sim = new OpenSim(configSource); m_sim.Startup(); while (true) { try { // Block thread here for input MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } } }
public static int Main(string[] args) { ArgvConfigSource argvConfig = new ArgvConfigSource(args); argvConfig.AddSwitch("Startup", "format", "f"); argvConfig.AddSwitch("Startup", "inifile"); IConfig startupConfig = argvConfig.Configs["Startup"]; string format = startupConfig.GetString("format", "ini"); ConfigurationLoader loader = new ConfigurationLoader(); IConfigSource s = loader.LoadConfigSettings(startupConfig); if (format == "mysql") { foreach (IConfig c in s.Configs) { foreach (string k in c.GetKeys()) { string v = c.GetString(k); if (k.StartsWith("Include-")) continue; Console.WriteLine("insert ignore into config (section, name, value) values ('{0}', '{1}', '{2}');", c.Name, k, v); } } } else if (format == "xml") { Console.WriteLine("<Nini>"); foreach (IConfig c in s.Configs) { int count = 0; foreach (string k in c.GetKeys()) { if (k.StartsWith("Include-")) continue; count++; } if (count > 0) { Console.WriteLine("<Section Name=\"{0}\">", c.Name); foreach (string k in c.GetKeys()) { string v = c.GetString(k); if (k.StartsWith("Include-")) continue; Console.WriteLine(" <Key Name=\"{0}\" Value=\"{1}\" />", k, v); } Console.WriteLine("</Section>"); } } Console.WriteLine("</Nini>"); } else if (format == "ini") { foreach (IConfig c in s.Configs) { int count = 0; foreach (string k in c.GetKeys()) { if (k.StartsWith("Include-")) continue; count++; } if (count > 0) { Console.WriteLine("[{0}]", c.Name); foreach (string k in c.GetKeys()) { string v = c.GetString(k); if (k.StartsWith("Include-")) continue; Console.WriteLine("{0} = \"{1}\"", k, v); } Console.WriteLine(); } } } else { Console.WriteLine("Error: unknown format: {0}", format); } return 0; }
private static bool _IsHandlingException; // Make sure we don't go recursive on ourself //could move our main function into OpenSimMain and kill this class public static void BaseMain(string[] args, string defaultIniFile, ISimulationBase simBase) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; //Allow up to 12 simultaneous connections to a given endpoint rather than 2 -OS dev ServicePointManager.DefaultConnectionLimit = 12; // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); if (!args.Contains("-skipconfig")) Configure(false); // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new FileInfo(logConfigFile)); //MainConsole.Instance.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", // logConfigFile); } else { XmlConfigurator.Configure(); //MainConsole.Instance.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } // Increase the number of IOCP threads available. Mono defaults to a tragically low number // Added one block -------------------------------------------------------- VS //m_log.InfoFormat( // "[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture); string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU"); // m_log.InfoFormat( // "[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset"); // Verify the Threadpool allocates or uses enough worker and IO completion threads // .NET 2.0 workerthreads default to 50 * numcores // .NET 3.0 workerthreads defaults to 250 * numcores // .NET 4.0 workerthreads are dynamic based on bitness and OS resources // Max IO Completion threads are 1000 on all 3 CLRs. int workerThreadsMin = 500; int workerThreadsMax = 1000; // may need further adjustment to match other CLR int iocpThreadsMin = 1000; int iocpThreadsMax = 2000; // may need further adjustment to match other CLR // -------------------------------------- End block ------------------------- int workerThreads, iocpThreads; ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); // MainConsole.Instance.InfoFormat("[AURORA MAIN]: Runtime gave us {0} worker threads and {1} IOCP threads", workerThreads, iocpThreads); //if (workerThreads < 500 || iocpThreads < 1000) //commented out -VS if (workerThreads < workerThreadsMin) { /* workerThreads = 500; // comment out this block -VS // iocpThreads = 1000; //MainConsole.Instance.Info("[OPENSIM MAIN]: Bumping up to 500 worker threads and 1000 IOCP threads"); ThreadPool.SetMaxThreads(workerThreads, iocpThreads); */ workerThreads = workerThreadsMin; //+m_log.InfoFormat("[OPENSIM MAIN]: Bumping up to worker threads to {0}", workerThreads); } if (workerThreads > workerThreadsMax) { workerThreads = workerThreadsMax; // m_log.InfoFormat("[OPENSIM MAIN]: Limiting worker threads to {0}",workerThreads); } // Increase the number of IOCP threads available. // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17) if (iocpThreads < iocpThreadsMin) { iocpThreads = iocpThreadsMin; // m_log.InfoFormat("[OPENSIM MAIN]: Bumping up IO completion threads to {0}",iocpThreads); } // Make sure we don't overallocate IOCP threads and thrash system resources if ( iocpThreads > iocpThreadsMax ) { iocpThreads = iocpThreadsMax; //m_log.InfoFormat("[OPENSIM MAIN]: Limiting IO completion threads to {0}",iocpThreads); } // set the resulting worker and IO completion thread counts back to ThreadPool if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) ) { //m_log.InfoFormat("[OPENSIM MAIN]: Threadpool set to {0} worker threads and {1} IO completion threads", workerThreads, iocpThreads); } //else //{ //m_log.Info("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect."); // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met //MainConsole.Instance.Info("[Setup]: Performing compatibility checks... \n"); string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { int minWorker, minIOC; // Get the current settings. ThreadPool.GetMinThreads(out minWorker, out minIOC); //MainConsole.Instance.InfoFormat("[Setup]: Environment is compatible. Thread Workers: {0}, IO Workers {1}\n", minWorker, minIOC); } else { MainConsole.Instance.Warn("[Setup]: Environment is unsupported (" + supported + ")\n"); #if BlockUnsupportedVersions Thread.Sleep(10000); //Sleep 10 seconds return; #endif } BinMigratorService service = new BinMigratorService(); service.MigrateBin(); // Configure nIni aliases and localles Culture.SetCurrentCulture(); configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); //Command line switches configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inigrid"); configSource.AddSwitch("Startup", "inisim"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "oldoptions"); configSource.AddSwitch("Startup", "inishowfileloading"); configSource.AddSwitch("Startup", "mainIniDirectory"); configSource.AddSwitch("Startup", "mainIniFileName"); configSource.AddSwitch("Startup", "secondaryIniFileName"); configSource.AddConfig("Network"); IConfigSource m_configSource = Configuration(configSource, defaultIniFile); // Check if we're saving crashes m_saveCrashDumps = m_configSource.Configs["Startup"].GetBoolean("save_crashes", m_saveCrashDumps); // load Crash directory config m_crashDir = m_configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); // check auto restart bool AutoRestart = m_configSource.Configs["Startup"].GetBoolean("AutoRestartOnCrash", true); //Set up the error reporting if (m_configSource.Configs["ErrorReporting"] != null) { m_sendErrorReport = m_configSource.Configs["ErrorReporting"].GetBoolean("SendErrorReports", true); m_urlToPostErrors = m_configSource.Configs["ErrorReporting"].GetString("ErrorReportingURL", m_urlToPostErrors); } bool Running = true; //If auto restart is set, then we always run. // otherwise, just run the first time that Running == true while (AutoRestart || Running) { //Always run once, then disable this Running = false; //Initialize the sim base now Startup(configSource, m_configSource, simBase.Copy(), args); } }
static int Main(string[] args) { ResultCode resultCode = 0; // use a configuration file to list all the sites you want to check // provide SMTP server information too var version = Assembly.GetEntryAssembly().GetName().Version; string startup = "LINKCHECKER " + version + " (c) Ian Mercer 2010 http://blog.abodit.com"; Console.WriteLine(startup); Console.WriteLine("".PadLeft(startup.Length, '-')); Console.WriteLine(); if (!File.Exists("LinkChecker.ini")) { Console.WriteLine("Please reinstall, you need both the .EXE and the .INI file"); Console.WriteLine("See http://blog.abodit.com"); } IConfigSource mainSource = new IniConfigSource("LinkChecker.ini"); ArgvConfigSource argSource = new ArgvConfigSource(args); //argSource.AddSwitch("SMTP", "Server", "smtp"); //argSource.AddSwitch("SMTP", "Port", "port"); //argSource.AddSwitch("SMTP", "Username", "user"); //argSource.AddSwitch("SMTP", "Password", "password"); argSource.AddSwitch("Settings", "Domain", "d"); // a single domain argSource.AddSwitch("Settings", "Delay", "de"); // argSource.AddSwitch("Settings", "IncludeSelectors", "is"); // Exclude pages option argSource.AddSwitch("Settings", "ExcludeSelectors", "xs"); // Exclude pages option argSource.AddSwitch("Settings", "ExcludePages", "xp"); // Exclude pages option argSource.AddSwitch("Settings", "All", "a"); // argSource.AddSwitch("Settings", "Pages", "pa"); // argSource.AddSwitch("Settings", "Seo", "s"); // argSource.AddSwitch("Settings", "Changes", "c"); // argSource.AddSwitch("Settings", "Limit", "li"); // argSource.AddSwitch("Settings", "Dump", "du"); // dump all text found argSource.AddSwitch("Settings", "Suggestions", "su"); mainSource.Merge(argSource); //var SMTPConfig = mainSource.Configs["SMTP"]; var config = mainSource.Configs["Settings"]; //string SMTPServer = SMTPConfig.GetString("Server", ""); //int SMTPPort = SMTPConfig.GetInt("Port", 25); //string SMTPUsername = SMTPConfig.GetString("Username", ""); //string SMTPPassword = SMTPConfig.GetString("Password", ""); //SMTPConfig.Set("Server", SMTPServer); //SMTPConfig.Set("Port", SMTPPort); //SMTPConfig.Set("Username", SMTPUsername); //SMTPConfig.Set("Password", SMTPPassword); int delayBetween = config.GetInt("Delay", 10); config.Set("Delay", delayBetween); string excludedPathSetting = config.GetString("ExcludePages", ""); //""); // common duplicate pages / comments string excludedPaths = excludedPathSetting; config.Set("ExcludePages", excludedPaths); string includeSelector = config.GetString("IncludeSelectors", "head title,body"); string excludeSelector = config.GetString("ExcludeSelectors", ".pageHeader,#header,.header,#footer,.footer,#sidebar,.sidebar," + "#feedbackTab,#feedback,.feedback,#feedbackdialog," + "#smalltype,.share-links-footer,block-ec_blogs"); config.Set("IncludeSelector", includeSelector); config.Set("ExcludeSelector", excludeSelector); string listPages = config.GetString("Pages", "").ToLower(); if (listPages != "none" && listPages != "list") listPages = "error"; config.Set("Pages", listPages); string seo = config.GetString("Seo", "").ToLower(); if (seo != "none" && seo != "list") seo = "error"; config.Set("Seo", seo); string changes = config.GetString("Changes", "").ToLower(); if (changes != "none" && changes != "error") changes = "list"; config.Set("Changes", changes); int limit = config.GetInt("Limit", 3000); // 3000 pages limit by default string dumpFilePath = config.GetString("Dump"); if (dumpFilePath != null) config.Set("Dump", dumpFilePath); bool showSuggestedLinks = !string.IsNullOrWhiteSpace(config.Get("Suggestions", "")); config.Set("Suggestions", showSuggestedLinks); string domainSingle = config.GetString("Domain", ""); // Save any changes back to the config file // Don't do this because then they affect everyone after that ... //mainSource.Save(); if (string.IsNullOrWhiteSpace(domainSingle)) { Console.WriteLine(" Usage: linkchecker -d example.com"); Console.WriteLine(" Parameters:"); Console.WriteLine(" -d:example.com The domain or starting Url you wish to check"); Console.WriteLine(" all pages at the same level or below will be scanned"); Console.WriteLine(" -xp:path1,path2 Exclude any paths that include path1, path2, ..."); Console.WriteLine(" e.g. -xp:comment,/recommend,/email,/print"); Console.WriteLine(); Console.WriteLine(" -all Complete dump including pages, changes and errors (default)"); Console.WriteLine(" -pages:none|list|error Detailed information about page and links (default = error)"); Console.WriteLine(" -seo:none|list|error Information about any SEO issues (default = error)"); Console.WriteLine(" -changes:none|list|error Changes to pages or links since last run (default=list)"); Console.WriteLine(); Console.WriteLine(" -delay 10 Delay 10 seconds between pages (less load on server being tested)"); Console.WriteLine(" -limit 3000 Limit how many pages (3000 default)"); Console.WriteLine(); Console.WriteLine(" -dump filename Dump all content from pages to a file"); Console.WriteLine(" -xs:domSelector2,... Exclude DOM elements that match jQuery style selectors"); Console.WriteLine(" -is:domSelector1,... Include DOM elements that match jQuery style selectors"); Console.WriteLine(" e.g. -is:head title,body -xs:footer,#header,#sidebar,.comment"); Console.WriteLine(); Console.WriteLine(" -xs and -is are applied throughout the DOM tree to select elements"); Console.WriteLine(); Console.WriteLine(" You can put <meta linkedpages=\"\\url,\\url2,...\"> on any page to check that those links"); Console.WriteLine(" are present on the page somewhere. In effect a 'link contract' that the page must meet."); Console.WriteLine(" This allows you to check that none of the key links on your site are broken."); Console.WriteLine(); Console.WriteLine(" -suggestions Lists all the links that are on a page but not in a linkedpages meta tag"); Console.WriteLine(" e.g. <meta linkedpages=\"\\login,\\logout,\\home\">"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(" RESULT CODE is non-zero if there are any errors and you specified error on any element above"); //Console.WriteLine(" -smtp An SMTP server to email the results to"); //Console.WriteLine(" -port SMTP Server port (25)"); //Console.WriteLine(" -user SMTP Server user name"); //Console.WriteLine(" -password SMTP Server password"); Console.WriteLine(); Console.WriteLine(" Settings may also be placed in a file LinkChecker.ini"); Console.WriteLine(); Console.WriteLine(" An XML dump of your web site will be placed in a subdirectory and used for subsequent runs as a comparison"); Console.WriteLine(" to alert you when new pages appear or links get broken between pages on your site."); Console.WriteLine(); return 1; } int failed = 0; Console.WriteLine("Domain = " + (domainSingle ?? "null")); // Display the config settings to the user //if (!string.IsNullOrWhiteSpace(SMTPServer)) // Console.WriteLine("SMTP Server " + SMTPServer); string cleanDomain = domainSingle.Replace("http://", ""); Uri urlRoot = new Uri("http://" + cleanDomain); string directoryPath = System.IO.Path.Combine(Environment.CurrentDirectory, SafeFileName(cleanDomain)); if (!System.IO.Directory.Exists(directoryPath)) System.IO.Directory.CreateDirectory(directoryPath); string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH;mm") + ".xml"; string filePath = Path.Combine(directoryPath, fileName); // A web site or part of a web site, e.g. www.microsoft.com/presspass WebSite webSite = new WebSite(cleanDomain, delayBetween*1000) .Except(excludedPaths); // Collect error messages List<string> errorMessages = new List<string>(); // Collect SEO warnings List<string> seoWarnings = new List<string>(); // Look for duplicate titles Dictionary<string, int> titleCounts = new Dictionary<string, int>(); Console.WriteLine(" _______________________________________________________________________________________ "); int countdown = limit; foreach (var webPage in webSite.WebPages) { // Count only errors and good pages ... if ((!(webPage is WebPage.External) && !(webPage is WebPage.OtherContent)) && countdown-- < 0) { Console.WriteLine("Limit reached, use something more than -limit " + limit + ""); break; } Uri url = webPage.Url; if (webPage is WebPage.Internal) { WebPage.Internal webPageInternal = webPage as WebPage.Internal; if (listPages != "none") { Console.WriteLine(url); Console.WriteLine(" title = " + webPageInternal.Title); Console.WriteLine(" description = " + webPageInternal.MetaDescription); foreach (var message in webPageInternal.ErrorMessages) { string err = " ERROR ON PAGE = " + message; Console.WriteLine(err); } errorMessages.AddRange(webPageInternal.ErrorMessages); foreach (var message in webPageInternal.SeoWarnings) { string err = " WARNING = " + message; Console.WriteLine(err); } } errorMessages.AddRange(webPageInternal.ErrorMessages); seoWarnings.AddRange(webPageInternal.SeoWarnings); // Check for duplicates too string title = webPageInternal.Title ?? ""; if (titleCounts.ContainsKey(title)) titleCounts[title]++; else titleCounts.Add(title, 1); if (!string.IsNullOrWhiteSpace(dumpFilePath)) { var documentNode = webPageInternal.HtmlDocument.DocumentNode; //<td class="itm" style="text-align:left" nowrap><a href="/ESIG">ESIG</a></td> //<td class="dsc">Engineering Science Interactive Graphics</td> var includeSelected = documentNode.QuerySelectorAll(includeSelector).ToList(); var excludeSelected = documentNode.QuerySelectorAll(excludeSelector).ToList(); Func<HtmlNode, bool> includeFilter = node => includeSelected.Contains(node); Func<HtmlNode, bool> excludeFilter = node => excludeSelected.Contains(node); using (FileStream file = File.Open(dumpFilePath, FileMode.Append, FileAccess.Write, FileShare.Read)) using (StreamWriter sw = new StreamWriter(file)) { sw.WriteLine(url); sw.WriteLine(" title = " + webPageInternal.Title); sw.WriteLine(" description = " + webPageInternal.MetaDescription); var selected = documentNode.InnerTextButJustTheTextBits(includeFilter, excludeFilter, false); var lines = selected.Split('\n', '\r') .Select(s => s.Replace('\t', ' ')) .Where(s => !string.IsNullOrWhiteSpace(s) && s.Length > 1); // ignore single character lines foreach (var line in lines) sw.WriteLine(line.Trim()); //var lines = webPageInternal.HtmlDocument.DocumentNode.InnerTextButJustTheTextBits(filterPredicate).Split('\n', '\r') // .Select(s => s.Replace('\t', ' ')) // .Where(s => !string.IsNullOrWhiteSpace(s) && s.Length>1); // ignore single character lines //foreach (var line in lines) // sw.WriteLine(line.Trim()); sw.WriteLine(" _______________________________________________________________________________________ "); } } } else if (webPage is WebPage.External || webPage is WebPage.OtherContent) { if (listPages != "none") { Console.WriteLine(webPage.ToString()); } } else if (webPage is WebPage.Error) { Console.WriteLine(webPage.ToString()); failed++; errorMessages.Add(webPage.ToString()); } else { throw new ApplicationException("Unexpected type " + webPage); } //if (showSuggestedLinks) //foreach (var suggestion in webPageInternal.SuggestedLinks) //{ // Console.WriteLine(@"Consider adding [LinkedPage(""" + suggestion + @""")]"); //} //int count = requiredLinks.Count(x => x.Value > 0); //if (count == 0 && requiredLinks.Count > 0) //{ // Console.WriteLine(" +++ all required links found on page"); //} //else //{ // foreach (var missingLink in requiredLinks.Where(x => x.Value > 0)) // { // Console.WriteLine(" **** MISSING LINK FROM " + url + " to " + missingLink); // failed++; // } //} if (listPages != "none") Console.WriteLine("|---------------------------------------------------------------------------------------|"); } // Save the results ... XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; //xmlWriterSettings.CheckCharacters = false; xmlWriterSettings.NewLineHandling = NewLineHandling.Entitize; // Serialize to disk DataContractSerializer serializer = new DataContractSerializer(typeof(WebSite), new[] {typeof(WebPage) , typeof(WebPage.Error) , typeof(WebPage.ExceptionError) , typeof(WebPage.External) , typeof(WebPage.Internal) , typeof(WebPage.LoadError) , typeof(WebPage.OtherContent) , typeof(WebPage.Timeout) , typeof(System.UriFormatException) // ick! ,typeof(WebLink) }); // Now compare that against the previous version var lastFile = Directory.EnumerateFiles(directoryPath).Select(f => new FileInfo(f)).OrderByDescending(d => d.CreationTimeUtc).FirstOrDefault(); WebSite previous = null; // Read the previous last file in if (lastFile != null) { try { using (XmlReader xmlReader = XmlReader.Create(new FileStream(lastFile.FullName, FileMode.Open, FileAccess.Read))) { previous = (WebSite)serializer.ReadObject(xmlReader); } } catch (System.Runtime.Serialization.SerializationException ex) // the one we expect { previous = null; Console.WriteLine(ex); resultCode = resultCode | ResultCode.PROGRAM_ERROR; } catch (Exception ex) // and for now, catch all others ... { previous = null; Console.WriteLine(ex); resultCode = resultCode | ResultCode.PROGRAM_ERROR; } } if (changes != "none") { Console.WriteLine(@"|------------------------------------COMPARISON-----------------------------------------|"); bool writeXML = true; // unless ... try { if (previous != null) { var changeLines = previous.StructureCompare(0, webSite).ToArray(); if (changeLines.Any()) { resultCode = resultCode | ResultCode.CHANGE_DETECTED; foreach (var s in changeLines) { Console.WriteLine(s); } } else { writeXML = false; Console.WriteLine("NO CHANGES DETECTED SINCE " + lastFile.CreationTime.ToShortDateString()); } } } catch (Exception ex) { Console.WriteLine("Please report: Error comparing " + ex.ToString()); } if (writeXML) { try { // And write the updates to a new file using (XmlWriter xmlWriter = XmlWriter.Create(new FileStream(filePath, FileMode.CreateNew), xmlWriterSettings)) { serializer.WriteObject(xmlWriter, webSite); } } catch (Exception ex) { Console.WriteLine("Failed to write file " + ex.Message); } } } if (errorMessages.Count > 0) { resultCode = resultCode | ResultCode.PAGE_ERROR; Console.WriteLine(@"|-------------------------------------ERRORS " + errorMessages.Count() + "-----------------------------------------|"); foreach (var err in errorMessages) { Console.WriteLine(err); } } else { Console.WriteLine("No errors"); } // Find duplicate page titles var duplicatePageTitles = titleCounts.Where(x => x.Value > 1).ToList(); foreach (var duplicatePageTitle in duplicatePageTitles) { seoWarnings.Add("Duplicate title '" + duplicatePageTitle.Key + "' on " + duplicatePageTitle.Value + " pages"); } if (seo != "none") { if (seoWarnings.Any()) { if (seo == "error") resultCode = resultCode | ResultCode.SEO_ERROR; Console.WriteLine(@"|------------------------------------SEO WARNINGS (" + seoWarnings.Count() + ")------------------------------------|"); foreach (var err in seoWarnings) { Console.WriteLine(err); } } } Console.WriteLine(@"\_______________________________________________________________________________________/"); Console.WriteLine(); //Console.ReadKey(); // Now decide whether to fail or not ... if (resultCode > 0) { Console.WriteLine("**** FAILED WITH ERROR CODE ****"); if ((resultCode & ResultCode.CHANGE_DETECTED) != 0) Console.WriteLine(" Changes detected"); if ((resultCode & ResultCode.LINK_ERROR) != 0) Console.WriteLine(" Link error"); if ((resultCode & ResultCode.PAGE_ERROR) != 0) Console.WriteLine(" Page error"); if ((resultCode & ResultCode.PROGRAM_ERROR) != 0) Console.WriteLine(" Program error"); if ((resultCode & ResultCode.SEO_ERROR) != 0) Console.WriteLine(" SEO error"); } if (Environment.MachineName == "XPS") Thread.Sleep(20000); return (int)resultCode; }
public void GetStringWithColon() { string[] arguments = new string[] {"-c", "\"D:\\test directory\""}; ArgvConfigSource source = new ArgvConfigSource (arguments); source.AddSwitch ("Base", "colon", "c"); Assert.AreEqual ("D:\\test directory", source.Configs["Base"].GetString("colon")); }
//could move our main function into OpenSimMain and kill this class public static void Main(string[] args) { // First line AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); ArgvConfigSource configSource = new ArgvConfigSource(args); configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile)); m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", logConfigFile); } else { XmlConfigurator.Configure(); m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } m_log.Info("Performing compatibility checks... "); string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { m_log.Info("Environment is compatible.\n"); } else { m_log.Warn("Environment is unsupported (" + supported + ")\n"); } Culture.SetCurrentCulture(); configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); configSource.AddSwitch("Startup", "background"); configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "gridmode"); configSource.AddSwitch("Startup", "physics"); configSource.AddSwitch("Startup", "gui"); configSource.AddConfig("StandAlone"); configSource.AddConfig("Network"); bool background = configSource.Configs["Startup"].GetBoolean("background", false); m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false); m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); if (background) { m_sim = new OpenSimBackground(configSource); m_sim.Startup(); } else { m_sim = new OpenSim(configSource); m_sim.Startup(); while (true) { try { MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } } }