Example #1
0
        public static void Startup(ArgvConfigSource originalConfigSource, IConfigSource configSource, ISimulationBase simBase)
        {
            //Get it ready to run
            simBase.Initialize(originalConfigSource, configSource);
            try
            {
                //Start it. This starts ALL modules and completes the startup of the application
                simBase.Startup();
                //Run the console now that we are done
                simBase.Run();
            }
            catch (Exception ex)
            {
                if (ex.Message != "Restart") //Internal needs a restart message
                {
                    string mes = "[AURORA]: Aurora has crashed! Error: " + ex + ", Stack trace: " + ex.StackTrace;

                    m_log.Error(mes);
                    handleException(mes, ex);
                    //Just clean it out as good as we can
                    simBase.Shutdown(false);
                }
                //Then let it restart if it needs by sending it back up to 'while (AutoRestart || Running)' above
                return;
            }
            //If it didn't throw an error, it wants to quit
            Environment.Exit(0);
        }
Example #2
0
        static void Main(string[] args)
        {
            ArgvConfigSource options = new ArgvConfigSource(args);

            // Initialize log4net
            XmlConfigurator.Configure();

            m_log.InfoFormat("Avatar Inventory System (AISv3) API Server 0.1  [{0} at {1}]",
                             DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString());

            // Allocate the new API server
            APIRouter _router = new APIRouter(8123);

            // Add inventory-related API methods
            InventoryAPI _inventoryMethods = new InventoryAPI(options);

            _inventoryMethods.AddRoutes(_router);

            // Now that the routes are added, start the router.
            _router.Run();

            m_log.Info("Server ready.");
            Console.WriteLine("Press Ctrl-C or Ctrl-Break to quit.");
            while (_router.IsRunning)
            {
                Thread.Sleep(50);
            }
            m_log.Info("Server shutting down.");
            Thread.Sleep(1000); // for now, give the last async request a chance to complete.
        }
Example #3
0
 public ConfigBase(string name, string file, string[] args)
 {
     Name      = name;
     this.file = file;
     argConfig = Init.InitArgConfig(args);
     InitConfig();
 }
Example #4
0
 protected static IConfigSource GetMainConfig(string[] args, out ArgvConfigSource argConfig, out string file)
 {
     argConfig = Init.InitArgConfig(args);
     argConfig.AddSwitch("General", "MainConfigFile", "f");
     file = argConfig.Configs["General"].Get("MainConfigFile", AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
     return(Init.AddFile(argConfig, file));
 }
Example #5
0
        private IInventoryStorage _storage; // per-user specific storage reference

        public InventoryAPI(ArgvConfigSource options)
        {
            options.AddSwitch("Inventory", "local", "l");
            string useLocal = options.Configs["Inventory"].Get("local");

            if (useLocal != null)   // any value include "" will do
            {
                _cluster    = Properties.LocalSettings.Default.cassandraCluster;
                _connstring = Properties.LocalSettings.Default.coreConnStr;
                m_log.Warn("Using LOCAL settings.");
            }


            try
            {
                _cassandraStorage = new InventoryStorage(_cluster);
                _legacy           = new LegacyMysqlInventoryStorage(_connstring);
                _selector         = new CassandraMigrationProviderSelector(true, _connstring, _cassandraStorage, _legacy);
                m_log.InfoFormat("Cassandra support on '{0}' enabled and ready.", _cluster);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("Unable to connect to cassandra cluster: {0}", e);
            }
        }
Example #6
0
        private static IConfigSource LoadCommandLineConfig()
        {
            var argvSource = new ArgvConfigSource(Environment.GetCommandLineArgs());

            argvSource.AddSwitch("haven", "gamesrv", "g");
            argvSource.AddSwitch("haven", "authsrv", "a");
            return(argvSource);
        }
Example #7
0
        public ConfigBase(string file, string frame, string[] args)
        {
            Frame      = frame;
            mFile      = file;
            mArgConfig = Init.InitArgConfig(args);

            InitConfig();
        }
Example #8
0
        public ConfigBase(string name, string[] args)
        {
            Name      = name;
            argConfig = Init.InitArgConfig(args);
            argConfig.AddSwitch("General", "File", "f");

            IConfigSource config = Init.AddFile(argConfig, out file);

            InitConfig();
        }
Example #9
0
        public MainApplication(string[] args)
        {
            commandLineArgs = args;
            argvSource      = new ArgvConfigSource(args);
            SetSwitches();

            if (!ProcessArgs(args))
            {
                return;
            }
        }
Example #10
0
        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"));
        }
Example #11
0
        public void Init()
        {
            // Configure Log4Net
            XmlConfigurator.Configure(new FileInfo(Constants.LOG_CONFIG_PATH));

            // Set CWD so that native libs are found.
            Directory.SetCurrentDirectory(TestContext.CurrentContext.TestDirectory);

            // Load INI stuff
            var configSource = new ArgvConfigSource(new string[] { });

            // Configure nIni aliases and locale
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US", true);

            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);

            // Read in the ini file
            configSource.Merge(new IniConfigSource(Constants.INI_PATH));

            // Prep cache folder
            try {
                Directory.Delete(Constants.TEST_CACHE_PATH, true);
            }
            catch (DirectoryNotFoundException) {
                // Skip.
            }

            Directory.CreateDirectory(Constants.TEST_CACHE_PATH);

            // Start booting server
            var pidFileManager = new PIDFileManager(Constants.PID_FILE_PATH);

            var chattelConfigRead = new ChattelConfiguration(Constants.TEST_CACHE_PATH);

            LocalStorage = new AssetStorageSimpleFolderTree(chattelConfigRead);
            var chattelReader = new ChattelReader(chattelConfigRead, LocalStorage);

            _service = new F_Stop(
                Constants.SERVICE_URI,
                Constants.SERVICE_ADMIN_TOKEN,
                TimeSpan.FromSeconds(Constants.SERVICE_NC_LIFETIME_SECONDS),
                chattelReader,
                new List <sbyte> {
                0, 12, /*18, 19,*/ 49
            }
                );

            _service.Start();
        }
Example #12
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"));
        }
Example #13
0
        public ConfigBase(params string[] args)
        {
            argConfig = Init.InitArgConfig(args);
            argConfig.AddSwitch("General", "File", "f");
            argConfig.AddSwitch("General", "Name", "n");

            IConfigSource config = Init.AddFile(argConfig, out file);

            Name = Init.Get(config.Configs["General"], "Name", "MainWindow");

            argConfig = Init.InitArgConfig(args);

            InitConfig();
        }
Example #14
0
        public static void Main(string[] args)
        {
            // Please note that if you are changing something in this function you should check to see if you need to change the other server's Main functions as well.

            // Under any circumstance other than an explicit exit the exit code should be 1.
            Environment.ExitCode = 1;

            ServicePointManager.DefaultConnectionLimit = 12;

            // Add the arguments supplied when running the application to the configuration
            var configSource = new ArgvConfigSource(args);

            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", "pidfile");

            m_log.Info("[SERVER]: Launching GridServer...");

            var pidFile = new PIDFileManager(configSource.Configs["Startup"].GetString("pidfile", string.Empty));

            XmlConfigurator.Configure();

            bool background = configSource.Configs["Startup"].GetBoolean("background", false);

            GridServerBase app;

            if (background)
            {
                m_log.Info("[GridServer MAIN]: set to background");
                app = new GridServerBackground();
            }
            else
            {
                m_log.Info("[GridServer MAIN]: set to foreground");
                app = new GridServerBase();
            }

            pidFile.SetStatus(PIDFileManager.Status.Starting);
            app.Startup();

            pidFile.SetStatus(PIDFileManager.Status.Running);
            app.Work();
        }
Example #15
0
        /// <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;
        }
Example #16
0
            public Config(string[] args, string section, string file)
            {
                ArgvConfigSource argConfig = InitArgConfig(args);

                argConfig.AddSwitch("General", "ViewerExe", "v");
                argConfig.AddSwitch("General", "WorkingDirectory", "d");
                argConfig.AddSwitch("General", "UseGrid", "ug");
                argConfig.AddSwitch("General", "UseSetFollowCamPackets", "uf");
                argConfig.AddSwitch("General", "EnableWindowPackets", "ew");
                argConfig.AddSwitch("General", "ProxyGrid", "g");
                argConfig.AddSwitch("General", "LoginURI", "u");
                argConfig.AddSwitch("General", "MasterAddress", "ma");
                argConfig.AddSwitch("General", "MasterPort", "mp");
                argConfig.AddSwitch("General", "WorldPosition", "cw");
                argConfig.AddSwitch("General", "WorldPitch", "pw");
                argConfig.AddSwitch("General", "WorldYaw", "yw");
                argConfig.AddSwitch(section, "ProxyPort", "p");
                argConfig.AddSwitch(section, "FirstName", "fn");
                argConfig.AddSwitch(section, "LastName", "l");
                argConfig.AddSwitch(section, "Password", "pw");
                argConfig.AddSwitch(section, "ControlCamera", "c");

                IConfigSource config = AddFile(argConfig, file);

                sectionConfig = config.Configs[section];
                generalConfig = config.Configs["General"];

                masterPort    = Get(generalConfig, "MasterPort", DEFAULT_MASTER_PORT);
                masterAddress = Get(generalConfig, "MasterAddress", DEFAULT_MASTER_ADDRESS);
                worldPosition = GetV(generalConfig, "WorldPosition", new Vector3(128, 128, 40));
                worldPitch    = Get(generalConfig, "WorldPitch", 0f);
                worldYaw      = Get(generalConfig, "WorldYaw", 0f);

                viewerExe              = Get(generalConfig, "ViewerExe", DEFAULT_CLIENT_EXE);
                workingDir             = Get(generalConfig, "WorkingDirectory", Path.GetDirectoryName(viewerExe));
                loginURI               = Get(generalConfig, "LoginURI", DEFAULT_LOGINURI);
                UseGrid                = Get(generalConfig, "UseGrid", false);
                EnableWindowPackets    = Get(generalConfig, "EnableWindowPackets", true);
                UseSetFollowCamPackets = !enableWindowPackets || Get(generalConfig, "UseSetFollowCamPackets", false);

                firstName = Get(sectionConfig, "FirstName", null);
                lastName  = Get(sectionConfig, "LastName", null);
                password  = Get(sectionConfig, "Password", null);
                proxyPort = Get(sectionConfig, "ProxyPort", CURRENT_PORT++);
                LoginGrid = Get(sectionConfig, "ProxyGrid", proxyPort.ToString());

                controlCamera = Get(sectionConfig, "ControlCamera", true);
            }
Example #17
0
        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);
        }
Example #18
0
        private void LoadCmdLineArgs(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Wrong number of parameters");
                DisplayHelpAndExit(ExitCodes.SyntaxError);
            }

            ArgvConfigSource source = new ArgvConfigSource(args);

            //source.AddSwitch ("Main", "file-name", "f");
            source.AddSwitch("Main", "bank-type", "t");

            //m_fileName = source.Configs ["Main"].Get ("file-name");
            m_fileName = args[args.Length - 1];
            m_bankType = source.Configs ["Main"].Get("bank-type");
        }
Example #19
0
        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);

            string pidFile = serverConfig.GetString("PIDFile", String.Empty);

            while (m_Server.Running)
            {
                System.Threading.Thread.Sleep(500);
                MainConsole.Instance.Prompt();
            }

            if (pidFile != String.Empty)
            {
                File.Delete(pidFile);
            }

            Environment.Exit(0);

            return(0);
        }
Example #20
0
        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]);
        }
Example #21
0
        public static void Startup(ArgvConfigSource originalConfigSource, IConfigSource configSource,
                                   ISimulationBase simBase, string[] cmdParameters)
        {
            //Get it ready to run
            simBase.Initialize(originalConfigSource, configSource, cmdParameters, m_configLoader);
            try
            {
                //Start it. This starts ALL modules and completes the startup of the application
                simBase.Startup();
                //Run the console now that we are done
                simBase.Run();
            }
            catch (Exception ex)
            {
                if (ex.Message != "Restart") //Internal needs a restart message
                {
                    UnhandledException(false, ex);
                    //Just clean it out as good as we can
                    simBase.Shutdown(false);
                    IRegionLoader[] regionLoaders = simBase.ApplicationRegistry.RequestModuleInterfaces <IRegionLoader>();
#if (!ISWIN)
                    foreach (IRegionLoader loader in regionLoaders)
                    {
                        if (loader != null && loader.Default)
                        {
                            loader.FailedToStartRegions(ex.Message);
                        }
                    }
#else
                    foreach (IRegionLoader loader in regionLoaders.Where(loader => loader != null && loader.Default))
                    {
                        loader.FailedToStartRegions(ex.Message);
                    }
#endif
                }
                //Then let it restart if it needs by sending it back up to 'while (AutoRestart || Running)' above
                return;
            }
            //If it didn't throw an error, it wants to quit
            Environment.Exit(0);
        }
Example #22
0
        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);
        }
Example #23
0
        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"));
        }
Example #24
0
        public Tray()
        {
            InitializeComponent();

            // Create a notify icon
            this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
            this.notifyIcon.ContextMenuStrip = this.notifyContextMenu;
            this.notifyIcon.Icon             = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
            this.notifyIcon.Text             = "Watch Dog";
            this.notifyIcon.Visible          = true;

            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);
        }
Example #25
0
        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");
            }
        }
Example #26
0
        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();
            }
        }
Example #27
0
        //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);

            Culture.SetCurrentCulture();
            Culture.SetDefaultCurrentCulture();

            if (Util.IsWindows())
            {
                ServicePointManager.DefaultConnectionLimit = 32;
            }
            else
            {
                ServicePointManager.DefaultConnectionLimit = 12;
            }

            try { ServicePointManager.DnsRefreshTimeout = 300000; } catch { }
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.UseNagleAlgorithm = false;

            // 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");
            }

            m_log.InfoFormat("Default culture changed to {0}", Culture.GetDefaultCurrentCulture().DisplayName);

            // Configure nIni aliases and localles

            // 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);
                    }
                }
            }
        }
        public static int Main(string[] args)
        {
            ArgvConfigSource argvConfig = new ArgvConfigSource(args);

            argvConfig.AddSwitch("Startup", "format", "f");

            IConfig startupConfig = argvConfig.Configs["Startup"];

            string format = startupConfig.GetString("format", "ini");

            ConfigurationLoader loader = new ConfigurationLoader();

            IConfigSource s = loader.LoadConfigSettings();

            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);
        }
Example #29
0
        public static int Main(string[] args)
        {
            // First line, hook the appdomain to the crash reporter
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "70a9f94f-59e8-4073-93ab-00aaacc26111", out var createdNew);

            if (!createdNew)
            {
                LOG.Error("Server process already started, please stop that server first.");
                return(2);
            }

            // Add the arguments supplied when running the application to the configuration
            var configSource = new ArgvConfigSource(args);

            // Commandline switches
            configSource.AddSwitch("Startup", "inifile");
            configSource.AddSwitch("Startup", "logconfig");
            configSource.AddSwitch("Startup", "pidfile");
            configSource.AddSwitch("Startup", "purge");

            var startupConfig = configSource.Configs["Startup"];

            var pidFileManager = new PIDFileManager(startupConfig.GetString("pidfile", string.Empty));

            // Configure Log4Net
            {
                var logConfigFile = startupConfig.GetString("logconfig", string.Empty);
                if (string.IsNullOrEmpty(logConfigFile))
                {
                    XmlConfigurator.Configure();
                    LogBootMessage();
                    LOG.Info("Configured log4net using ./WHIP_LRU.exe.config as the default.");
                }
                else
                {
                    XmlConfigurator.Configure(new FileInfo(logConfigFile));
                    LogBootMessage();
                    LOG.Info($"Configured log4net using \"{logConfigFile}\" as configuration file.");
                }
            }

            // Configure nIni aliases and locale
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US", true);

            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);

            var     isRunning = true;
            WhipLru whipLru   = null;

            // Handlers for signals.
            UnixSignal[] signals = null;
            if (ON_POSIX_COMPLAINT_OS)
            {
                signals = new [] {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGTERM),
                    new UnixSignal(Signum.SIGHUP),
                };
            }
            else
            {
                Console.CancelKeyPress += (sender, cargs) => {
                    LOG.Debug("CTRL-C pressed, terminating.");
                    isRunning = false;
                    whipLru?.Stop();

                    cargs.Cancel = true;
                    waitHandle.Set();
                };
            }

            while (isRunning)
            {
                // Dump any known servers, we're going to reconfigure them.
                foreach (var server in _assetServersByName.Values)
                {
                    server.Dispose();
                }
                // TODO: might need to double buffer these, or something, so that old ones can finish out before being disposed.

                // Read in the ini file
                ReadConfigurationFromINI(configSource);

                // Read in a config list that lists the priority order of servers and their settings.

                var configRead  = configSource.Configs["AssetsRead"];
                var configWrite = configSource.Configs["AssetsWrite"];

                var serversRead  = GetServers(configSource, configRead, _assetServersByName);
                var serversWrite = GetServers(configSource, configWrite, _assetServersByName);

                var localStorageConfig = configSource.Configs["LocalStorage"];

                var chattelConfigRead  = GetConfig(localStorageConfig, serversRead);
                var chattelConfigWrite = GetConfig(localStorageConfig, serversWrite);

                var serverConfig = configSource.Configs["Server"];

                var address  = serverConfig?.GetString("Address", WHIPServer.DEFAULT_ADDRESS) ?? WHIPServer.DEFAULT_ADDRESS;
                var port     = (uint?)serverConfig?.GetInt("Port", (int)WHIPServer.DEFAULT_PORT) ?? WHIPServer.DEFAULT_PORT;
                var password = serverConfig?.GetString("Password", WHIPServer.DEFAULT_PASSWORD);
                if (password == null)                   // Would only be null if serverConfig was null or DEFAULT_PASSWORD is null.  Why not use the ?? operator? Compiler didn't like it.
                {
                    password = WHIPServer.DEFAULT_PASSWORD;
                }
                var listenBacklogLength = (uint?)serverConfig?.GetInt("ConnectionQueueLength", (int)WHIPServer.DEFAULT_BACKLOG_LENGTH) ?? WHIPServer.DEFAULT_BACKLOG_LENGTH;

                var maxAssetLocalStorageDiskSpaceByteCount = (ulong?)localStorageConfig?.GetLong("MaxDiskSpace", (long)AssetLocalStorageLmdbPartitionedLRU.DB_MAX_DISK_BYTES_MIN_RECOMMENDED) ?? AssetLocalStorageLmdbPartitionedLRU.DB_MAX_DISK_BYTES_MIN_RECOMMENDED;
                var negativeCacheItemLifetime = TimeSpan.FromSeconds((uint?)localStorageConfig?.GetInt("NegativeCacheItemLifetimeSeconds", (int)StorageManager.DEFAULT_NC_LIFETIME_SECONDS) ?? StorageManager.DEFAULT_NC_LIFETIME_SECONDS);
                var partitionInterval         = TimeSpan.FromMinutes((uint?)localStorageConfig?.GetInt("MinutesBetweenDatabasePartitions", (int)DEFAULT_DB_PARTITION_INTERVAL_MINUTES) ?? DEFAULT_DB_PARTITION_INTERVAL_MINUTES);

                var purgeAll = startupConfig.GetString("purge", string.Empty) == "all";
                if (purgeAll)
                {
                    LOG.Info("CLI request to purge all assets on startup specified.");
                }

                var readerLocalStorage = new AssetLocalStorageLmdbPartitionedLRU(
                    chattelConfigRead,
                    maxAssetLocalStorageDiskSpaceByteCount,
                    partitionInterval
                    );
                var chattelReader = new ChattelReader(chattelConfigRead, readerLocalStorage, purgeAll);
                var chattelWriter = new ChattelWriter(chattelConfigWrite, readerLocalStorage, purgeAll);

                var storageManager = new StorageManager(
                    readerLocalStorage,
                    negativeCacheItemLifetime,
                    chattelReader,
                    chattelWriter
                    );

                whipLru = new WhipLru(
                    address,
                    port,
                    password,
                    pidFileManager,
                    storageManager,
                    listenBacklogLength
                    );

                whipLru.Start();

                if (signals != null)
                {
                    var signalIndex = UnixSignal.WaitAny(signals, -1);

                    switch (signals[signalIndex].Signum)
                    {
                    case Signum.SIGHUP:
                        whipLru.Stop();
                        break;

                    case Signum.SIGINT:
                    case Signum.SIGKILL:
                        isRunning = false;
                        whipLru.Stop();
                        break;

                    default:
                        // Signal unknown, ignore it.
                        break;
                    }
                }
                else
                {
                    waitHandle.WaitOne();
                }
            }

            foreach (var server in _assetServersByName.Values)
            {
                server.Dispose();
            }

            return(0);
        }
Example #30
0
        static bool _IsHandlingException; // Make sure we don't go recursive on ourself

        //could move our main function into AuroraMain 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("[AURORA 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("[AURORA 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);
        }