public void windsor_engine_is_available_as_component()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();

            // ACT
            var engineTakenFromWindsor = windsorEngine.GetComponent <IWindsorEngine>();

            // ASSERT
            Assert.AreEqual(windsorEngine, engineTakenFromWindsor);
            windsorEngine.Stop();
        }
        public void windsor_container_is_available_as_component()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();

            // ACT
            var containerTakenFromWindsor = windsorEngine.GetComponent <IWindsorContainer>();

            // ASSERT
            Assert.NotNull(containerTakenFromWindsor);
            windsorEngine.Stop();
        }
        public void component_can_be_overriden()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();

            // ACT
            var userRpository = windsorEngine.GetComponent <IUserRepository>();

            // ASSERT
            Assert.NotNull(userRpository);
            Assert.IsAssignableFrom <UserRepositoryMock>(userRpository);
        }
Exemplo n.º 4
0
        /// <summary>
        /// TODO: write a comment.
        /// </summary>
        /// <param name="serverRoot">
        /// A string
        /// </param>
        private void StartWebServerFromClass(string serverRoot)
        {
            XSPWebSource websource = new XSPWebSource(IPAddress.Any, this.ServerPort);

            webAppServer = new ApplicationServer(websource);

            // Adds application to the webserver
            webAppServer.AddApplicationsFromConfigFile(serverRoot + Path.DirectorySeparatorChar + "Ideas.webapp");

            // Starts server instance
            webAppServer.Start(false);
        }
Exemplo n.º 5
0
        public void can_have_multiple_transactions_to_the_same_database()
        {
            //ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();
            var            myService     = windsorEngine.GetComponent <IMyTransactionalService>();

            //ACT
            myService.InvokeAnotherSession();

            //ASSERT
            windsorEngine.Dispose();
        }
Exemplo n.º 6
0
        public void resolve_component_using_component_locator()
        {
            // ARRANGE
            IWindsorEngine windsorEngine    = ApplicationServer.Start();
            var            componentLocator = windsorEngine.GetComponent <IComponentLocator>();

            // ACT
            var component = componentLocator.GetComponent <ITransientComponentMock>();

            // ASSERT
            Assert.That(component, Is.Not.Null);
        }
Exemplo n.º 7
0
        public void GetRootLibrary()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();
            var            librarian     = windsorEngine.GetComponent <ILibrarian>();

            // ACT
            Library rootLibrary = librarian.GetRootLibrary();

            // ASSERT
            Assert.That(rootLibrary.Equals(new SynergyCoreTestLibrary()), Is.True);
            windsorEngine.Stop();
        }
Exemplo n.º 8
0
        public void automatic_transaction_can_be_disabled()
        {
            //ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();
            var            myService     = windsorEngine.GetComponent <IMyTransactionalService>();

            //ACT
            bool transactionStarted = myService.MethodWithDisabledAutoTransaction();

            //ASSERT
            Assert.IsFalse(transactionStarted, "Transaction was started but it shouldn't be");
            windsorEngine.Dispose();
        }
        public void component_marked_as_transient_is_really_so()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();

            // ACT
            var transient1 = windsorEngine.GetComponent <ITransientComponentMock>();
            var transient2 = windsorEngine.GetComponent <ITransientComponentMock>();

            // ASSERT
            Assert.That(transient1, Is.Not.EqualTo(transient2));
            windsorEngine.Stop();
        }
Exemplo n.º 10
0
        public void automatic_transaction_should_be_started()
        {
            //ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();
            var            myService     = windsorEngine.GetComponent <IMyTransactionalService>();

            //ACT
            int count = myService.GetMyEntitiesCount();

            //ASSERT
            Assert.AreEqual(0, count);
            windsorEngine.Dispose();
        }
Exemplo n.º 11
0
        public void automatic_transaction_should_be_started_because_of_attribute_inheritance()
        {
            //ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();
            var            myService     = windsorEngine.GetComponent <IMyTransactionalService>();

            //ACT
            int count = myService.StartTransactionBecauseThereIsAttributeOnInterface();

            //ASSERT
            Assert.AreEqual(0, count);
            windsorEngine.Dispose();
        }
        public void components_are_singletons_by_default()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();

            // ACT
            var component1 = windsorEngine.GetComponent <IComponentMock>();
            var component2 = windsorEngine.GetComponent <IComponentMock>();

            // ASSERT
            Assert.That(component1, Is.Not.Null);
            Assert.That(component1, Is.EqualTo(component2));
            windsorEngine.Stop();
        }
        public void component_marked_as_singleton_singletons__is_really_so()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();

            // ACT
            var component1 = windsorEngine.GetComponent <ISingletonComponentMock>();
            var component2 = windsorEngine.GetComponent <ISingletonComponentMock>();

            // ASSERT
            Assert.That(component1, Is.Not.Null);
            Assert.That(component1, Is.EqualTo(component2));
            windsorEngine.Stop();
        }
        public void ComponentShouldBeInteceptedIfRequired()
        {
            //ARRANGE
            IWindsorEngine c           = ApplicationServer.Start();
            var            intercepted = c.GetComponent <IInterceptedComponent>();

            ComponentInterceptor.WasInvoked = false;

            //ACT
            intercepted.Execute();

            //ASSERT
            Assert.That(ComponentInterceptor.WasInvoked, Is.True);
        }
        public void component_list_can_be_retrieved_from_windsor_engine()
        {
            // ARRANGE
            IWindsorEngine windsorEngine    = ApplicationServer.Start();
            var            componentLocator = windsorEngine.GetComponent <IComponentLocator>();

            // ACT
            IUserRepository[] components = componentLocator.GetComponents <IUserRepository>();

            // ASSERT
            Assert.NotNull(components);
            Assert.That(components, Is.Not.Empty);
            Assert.That(components.Length, Is.EqualTo(2));
            windsorEngine.Stop();
        }
        public void can_insert_dependent_collection_of_components()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();

            // ACT
            var component = windsorEngine.GetComponent <IComponentMock>();

            // ASSERT
            Assert.That(component, Is.Not.Null);
            IEnumerable <IDependentComponentMock> dependencies = component.GetDependencies();

            Assert.NotNull(dependencies);
            Assert.AreEqual(1, dependencies.Count());
            windsorEngine.Stop();
        }
Exemplo n.º 17
0
        public void resolve_stateful_component_using_component_locator()
        {
            // ARRANGE
            IWindsorEngine windsorEngine    = ApplicationServer.Start();
            var            componentLocator = windsorEngine.GetComponent <IComponentLocator>();
            var            id    = "1234";
            var            state = new State(id);

            // ACT
            var component = componentLocator.GetComponent <IStatefulComponent>(new { state });

            // ASSERT
            Assert.That(component, Is.Not.Null);
            Assert.That(component.Id, Is.EqualTo(id));
            Assert.That(component.Dependency, Is.Not.Null);
        }
        public void component_can_be_registered_using_factory_method()
        {
            // ARRANGE
            // see: https://github.com/castleproject/Windsor/blob/master/docs/registering-components-one-by-one.md
            IWindsorEngine windsorEngine = ApplicationServer.Start();

            // ACT
            var transient1 = windsorEngine.GetComponent <IComponentCreatedViaFactory>();
            var transient2 = windsorEngine.GetComponent <IComponentCreatedViaFactory>();
            var c1         = windsorEngine.GetComponent <IContainerForComponentCreatedViaFactory>();
            var c2         = windsorEngine.GetComponent <IContainerForComponentCreatedViaFactory>();

            // ASSERT
            Assert.That(transient1, Is.Not.EqualTo(transient2));
            Assert.That(c1, Is.EqualTo(c2));
            Assert.That(c1.GetComponentCreatedViaFactory(), Is.EqualTo(c2.GetComponentCreatedViaFactory()));

            windsorEngine.Stop();
        }
Exemplo n.º 19
0
        public void GetLibraries()
        {
            // ARRANGE
            IWindsorEngine windsorEngine = ApplicationServer.Start();
            var            librarian     = windsorEngine.GetComponent <ILibrarian>();

            // ACT
            Library[] libraries = librarian.GetLibraries();

            // ASSERT
            Assert.That(libraries,
                        Is.EquivalentTo(
                            new Library[]
            {
                new SynergyCoreTestLibrary(),
                new SynergyCoreSampleLibrary(),
                new SynergyCoreLibrary(),
            }));
            windsorEngine.Stop();
        }
Exemplo n.º 20
0
        private void StartServer() {
            ServerApplication serverApplication = new XpandServerApplication();
            serverApplication.ApplicationName = "SecurityDemo";
            serverApplication.DatabaseVersionMismatch += new EventHandler<DatabaseVersionMismatchEventArgs>(serverApplication_DatabaseVersionMismatch);
            serverApplication.SetupComplete+=ServerApplicationOnSetupComplete;

            foreach(ModuleBase module in GetModules()) {
                if(!serverApplication.Modules.Contains(module)) {
                    serverApplication.Modules.Add(module);
                }
            }
            serverApplication.ConnectionString = serverConnectionString;

            SecurityDemoAuthentication authentication = new SecurityDemoAuthentication();
            //AuthenticationActiveDirectory authentication = new AuthenticationActiveDirectory(typeof(SecurityDemo.Module.SecurityUser), null);
            //authenticationActiveDirectory.CreateUserAutomatically = true;
            //#region DEMO_REMOVE
            //authentication = new AuthenticationStandardForTests();
            //#endregion

            serverApplication.Security = new SecurityStrategyComplex(typeof(SecurityDemoUser), typeof(SecurityRole), authentication);
            ((ISupportFullConnectionString) serverApplication).ConnectionString = serverConnectionString;
            serverApplication.Setup();
            serverApplication.DatabaseUpdateMode=DatabaseUpdateMode.UpdateDatabaseAlways;
            serverApplication.CheckCompatibility();

            ApplicationServer applicationServer = new ApplicationServer(connectionString, "SecurityDemoApplicationServer", serverConnectionString);
            applicationServer.ObjectSpaceProvider = serverApplication.ObjectSpaceProvider;
            applicationServer.Security = serverApplication.Security;
            applicationServer.SecurityService = new ServerSecurityStrategyService(authentication);

            try {
                applicationServer.Start();
                SecurityModule.StrictSecurityStrategyBehavior = false;
            }
            catch (Exception e) {
                Console.WriteLine(e);
            }

        }
Exemplo n.º 21
0
        public void Start()
        {
            if (_started == true)
            {
                return;
            }
            _started = true;

            Mara.Log("XSP.Start()");
            _server = new ApplicationServer(new XSPWebSource(IPAddress.Any, Port));
            _server.AddApplicationsFromCommandLine(string.Format("{0}:/:{1}", Port, App));

            Mara.Log("XSP2 starting ... ");
            try {
                _server.Start(true);
            } catch (SocketException ex) {
                // it gets mad sometimes?
                Mara.Log("SocketException while starting XSP: {0}", ex.Message);
            }
            Mara.WaitForLocalPortToBecomeUnavailable(Port);
            Mara.Log("done");
        }
Exemplo n.º 22
0
        public static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(Console.In);

            XmlNode node = doc.SelectSingleNode("/xsp-options");

            var opts = new XspOptions(node);

            var source = new MonoWebSource(opts);

            Environment.CurrentDirectory = opts.LocalDirectory;

            var server = new ApplicationServer(source);

            server.AddApplicationsFromCommandLine("/:.");

            XspResult result;

            try {
                if (server.Start(false))
                {
                    result = new XspResult(source.EndPoint);
                }
                else
                {
                    result = new XspResult("Cannot start xsp.");
                }
            } catch (Exception ex) {
                var msg = String.Format("Cannot start xsp: {0}", ex.Message);
                result = new XspResult(msg);
            }

            Console.Out.WriteLine(result.ToXml());
            Console.Out.Flush();
        }
Exemplo n.º 23
0
        /// <param name="args">Original args passed to the program.</param>
        /// <param name="root">If set to <c>true</c> it means the caller is in the root domain.</param>
        /// <param name="ext_apphost">Used when single app mode is used, in a recursive call to RealMain from the single app domain.</param>
        /// <param name="quiet">If set to <c>true</c> don't show messages. Used to avoid double printing of the banner.</param>
        internal CompatTuple <int, string, ApplicationServer> DebugMain(string [] args, bool root, IApplicationHost ext_apphost, bool quiet)
        {
            var configurationManager = new ConfigurationManager("xsp", quiet);
            var security             = new SecurityConfiguration();

            if (!ParseOptions(configurationManager, args, security))
            {
                return(new CompatTuple <int, string, ApplicationServer> (1, "Error while parsing options", null));
            }

            // Show the help and exit.
            if (configurationManager.Help)
            {
                configurationManager.PrintHelp();
#if DEBUG
                Console.WriteLine("Press any key...");
                Console.ReadKey();
#endif
                return(success);
            }

            // Show the version and exit.
            if (configurationManager.Version)
            {
                Version.Show();
                return(success);
            }

            if (!configurationManager.LoadConfigFile())
            {
                return(new CompatTuple <int, string, ApplicationServer> (1, "Error while loading the configuration file", null));
            }

            configurationManager.SetupLogger();

            WebSource webSource;
            if (security.Enabled)
            {
                try {
                    key       = security.KeyPair;
                    webSource = new XSPWebSource(configurationManager.Address,
                                                 configurationManager.RandomPort ? default(ushort) : configurationManager.Port,
                                                 security.Protocol, security.ServerCertificate,
                                                 GetPrivateKey, security.AcceptClientCertificates,
                                                 security.RequireClientCertificates, !root);
                }
                catch (CryptographicException ce) {
                    Logger.Write(ce);
                    return(new CompatTuple <int, string, ApplicationServer> (1, "Error while setting up https", null));
                }
            }
            else
            {
                webSource = new XSPWebSource(configurationManager.Address, configurationManager.Port, !root);
            }

            var server = new ApplicationServer(webSource, configurationManager.Root)
            {
                Verbose           = configurationManager.Verbose,
                SingleApplication = !root
            };

            if (configurationManager.Applications != null)
            {
                server.AddApplicationsFromCommandLine(configurationManager.Applications);
            }

            if (configurationManager.AppConfigFile != null)
            {
                server.AddApplicationsFromConfigFile(configurationManager.AppConfigFile);
            }

            if (configurationManager.AppConfigDir != null)
            {
                server.AddApplicationsFromConfigDirectory(configurationManager.AppConfigDir);
            }

            if (configurationManager.Applications == null && configurationManager.AppConfigDir == null && configurationManager.AppConfigFile == null)
            {
                server.AddApplicationsFromCommandLine("/:.");
            }


            VPathToHost vh = server.GetSingleApp();
            if (root && vh != null)
            {
                // Redo in new domain
                vh.CreateHost(server, webSource);
                var svr = (Server)vh.AppHost.Domain.CreateInstanceAndUnwrap(GetType().Assembly.GetName().ToString(), GetType().FullName);
                webSource.Dispose();
                return(svr.DebugMain(args, false, vh.AppHost, configurationManager.Quiet));
            }
            server.AppHost = ext_apphost;

            if (!configurationManager.Quiet)
            {
                Logger.Write(LogLevel.Notice, Assembly.GetExecutingAssembly().GetName().Name);
                Logger.Write(LogLevel.Notice, "Listening on address: {0}", configurationManager.Address);
                Logger.Write(LogLevel.Notice, "Root directory: {0}", configurationManager.Root);
            }

            try {
                if (!server.Start(!configurationManager.NonStop, (int)configurationManager.Backlog))
                {
                    return(new CompatTuple <int, string, ApplicationServer> (2, "Error while starting server", server));
                }

                if (!configurationManager.Quiet)
                {
                    // MonoDevelop depends on this string. If you change it, let them know.
                    Logger.Write(LogLevel.Notice, "Listening on port: {0} {1}", server.Port, security);
                }
                if (configurationManager.RandomPort && !configurationManager.Quiet)
                {
                    Logger.Write(LogLevel.Notice, "Random port: {0}", server.Port);
                }

                if (!configurationManager.NonStop)
                {
                    if (!configurationManager.Quiet)
                    {
                        Console.WriteLine("Hit Return to stop the server.");
                    }

                    while (true)
                    {
                        bool doSleep;
                        try {
                            Console.ReadLine();
                            break;
                        } catch (IOException) {
                            // This might happen on appdomain unload
                            // until the previous threads are terminated.
                            doSleep = true;
                        } catch (ThreadAbortException) {
                            doSleep = true;
                        }

                        if (doSleep)
                        {
                            Thread.Sleep(500);
                        }
                    }
                    server.Stop();
                }
            } catch (Exception e) {
                if (!(e is ThreadAbortException))
                {
                    Logger.Write(e);
                }
                else
                {
                    server.ShutdownSockets();
                }
                return(new CompatTuple <int, string, ApplicationServer> (1, "Error running server", server));
            }

            return(new CompatTuple <int, string, ApplicationServer> (0, null, server));
        }
Exemplo n.º 24
0
        public static void Start()
        {
            XSPWebSource websource = new XSPWebSource(IPAddress.Loopback, 0);

            WebAppServer = new ApplicationServer(websource);

            string basePath   = Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString();
            string serverPath = basePath;

            if (serverPath[serverPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
            {
                serverPath += System.IO.Path.DirectorySeparatorChar;
            }
            serverPath += "WebUI";
            string serverBinPath = serverPath + System.IO.Path.DirectorySeparatorChar + "bin" + System.IO.Path.DirectorySeparatorChar;

            WebAppServer.AddApplication("", -1, "/", serverPath);

            bool started = false;

            DateTime curr = DateTime.Now;

            while (!started && curr.AddMinutes(1) > DateTime.Now)
            {
                try
                {
                    WebAppServer.Start(true);
                    started = true;
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    if (e.ErrorCode == 10049 || e.ErrorCode == 10022)
                    {
                        //strange error on bind, probably network still not started
                        //try to rerun server
                        System.Threading.Thread.Sleep(10000);
                        //WebAppServer.Start(true);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            if (!started)
            {
                WebAppServer.Start(true);
            }

            //copy Mono.WebServer2.dll

            /*try
             * {
             *      if (!Directory.Exists(serverBinPath))
             *              Directory.CreateDirectory(serverBinPath);
             *
             *      File.Copy(basePath + System.IO.Path.DirectorySeparatorChar+"Mono.WebServer2.dll", serverBinPath + "Mono.WebServer2.dll", true);
             * }
             *
             * catch { ;}
             */

            AppDomain ap = WebAppServer.GetApplicationForPath("", WebAppServer.Port, "/", false).AppHost.Domain;

            ap.AssemblyResolve    += new ResolveEventHandler(MyResolveEventHandler);
            ap.UnhandledException += OnUnhandledExceptionEvent;


            ap.SetData("WebUIGate", webServerGate);

            port = WebAppServer.Port;
            //uri = new Uri("http://127.0.0.1:" + port.ToString() + "/");
            uri = new Uri("http://localhost:" + port.ToString() + "/");
            Console.WriteLine("Webserver started at " + uri.ToString());
        }
Exemplo n.º 25
0
        // Protected Methods (2) 

        /// <summary>
        ///
        /// </summary>
        /// <see cref="ServiceBase.OnStart(string[])" />
        protected override void OnStart(string[] args)
        {
            var      asmDir     = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            TimeSpan?startDelay = null;

            var workDir = asmDir;

            foreach (var a in args)
            {
                if (a.ToLower().Trim().StartsWith("/rootdir:"))
                {
                    // custom root/working directory
                    var dir = new DirectoryInfo(a.Substring(a.IndexOf(':') + 1)
                                                .TrimStart()).FullName;

                    if (Path.IsPathRooted(dir))
                    {
                        workDir = new DirectoryInfo(dir).CreateDirectoryDeep().FullName;
                    }
                    else
                    {
                        workDir = new DirectoryInfo(Path.Combine(asmDir,
                                                                 dir)).CreateDirectoryDeep().FullName;
                    }
                }
                else if (a.ToLower().Trim().StartsWith("/startdelay:"))
                {
                    var seconds = a.Substring(a.IndexOf(':') + 1)
                                  .Trim();
                    if (seconds == string.Empty)
                    {
                        seconds = "15";
                    }

                    startDelay = TimeSpan.FromSeconds(double.Parse(seconds,
                                                                   CultureInfo.InvariantCulture));
                }
            }

            if (startDelay.HasValue)
            {
                Thread.Sleep(startDelay.Value);
            }

            this.EventLog
            .WriteEntry(string.Format("Root directory is: {0}",
                                      workDir),
                        EventLogEntryType.Information);

            this.LogDirectory = new DirectoryInfo(Path.Combine(workDir,
                                                               "logs")).CreateDirectoryDeep()
                                .FullName;

            this.EventLog
            .WriteEntry(string.Format("Log directory is: {0}",
                                      this.LogDirectory),
                        EventLogEntryType.Information);

            GlobalConsole.SetConsole(new ServiceConsole(this));

            var loggerFuncs = new DelegateLogger();

            loggerFuncs.Add(this.WriteEventLogMessage);

            var logger = new AggregateLogger();

            logger.Add(new AsyncLogger(loggerFuncs));

            var server = new ApplicationServer();

            try
            {
                if (!server.IsInitialized)
                {
                    var srvCtx = new SimpleAppServerContext(server);

                    var initCtx = new SimpleAppServerInitContext();
                    initCtx.Arguments        = args;
                    initCtx.Logger           = logger;
                    initCtx.ServerContext    = srvCtx;
                    initCtx.WorkingDirectory = workDir;

                    try
                    {
                        server.Initialize(initCtx);

                        this.EventLog
                        .WriteEntry("Server has been initialized.",
                                    EventLogEntryType.Information);
                    }
                    catch (Exception ex)
                    {
                        this.EventLog
                        .WriteEntry(string.Format("Server could not be initialized!{0}{0}{1}",
                                                  Environment.NewLine,
                                                  ex.GetBaseException() ?? ex),
                                    EventLogEntryType.Error);

                        throw;
                    }

                    srvCtx.InnerServiceLocator = server.GlobalServiceLocator;
                }

                try
                {
                    server.Start();

                    this.EventLog
                    .WriteEntry("Server has been started.",
                                EventLogEntryType.Information);
                }
                catch (Exception ex)
                {
                    this.EventLog
                    .WriteEntry(string.Format("Server could not be started!{0}{0}{1}",
                                              Environment.NewLine,
                                              ex.GetBaseException() ?? ex),
                                EventLogEntryType.Error);

                    throw;
                }

                this.Server = server;
            }
            catch
            {
                server.Dispose();

                throw;
            }
        }
Exemplo n.º 26
0
 public void Start()
 {
     WebAppServer.Start(true, 20);
 }
Exemplo n.º 27
0
Arquivo: main.cs Projeto: symform/xsp
        //
        // Parameters:
        //
        //   args - original args passed to the program
        //   root - true means caller is in the root domain
        //   ext_apphost - used when single app mode is used, in a recursive call to
        //        RealMain from the single app domain
        //   quiet - don't show messages. Used to avoid double printing of the banner
        //
        public int RealMain(string [] args, bool root, IApplicationHost ext_apphost, bool v_quiet)
        {
            var configurationManager = new ConfigurationManager (v_quiet,
                ext_apphost == null ? null : ext_apphost.Path);

            if (!configurationManager.LoadCommandLineArgs (args))
                return 1;

            // Show the help and exit.
            if (configurationManager.Help) {
                configurationManager.PrintHelp ();
            #if DEBUG
                Console.WriteLine("Press any key...");
                Console.ReadKey ();
            #endif
                return 0;
            }

            // Show the version and exit.
            if (configurationManager.Version) {
                Version.Show ();
                return 0;
            }

            var hash = GetHash (args);
            if (hash == -1) {
                Logger.Write(LogLevel.Error, "Couldn't calculate hash - should have left earlier - something is really wrong");
                return 1;
            }
            if (hash == -2) {
                Logger.Write(LogLevel.Error, "Couldn't calculate hash - unrecognized parameter");
                return 1;
            }

            if (!configurationManager.LoadConfigFile ())
                return 1;

            configurationManager.SetupLogger ();

            ushort port = configurationManager.Port ?? 0;
            bool useTCP = port != 0;
            string lockfile = useTCP ? Path.Combine (Path.GetTempPath (), "mod_mono_TCP_") : configurationManager.Filename;
            lockfile = String.Format ("{0}_{1}", lockfile, hash);

            ModMonoWebSource webSource = useTCP
                ? new ModMonoTCPWebSource (configurationManager.Address, port, lockfile)
                : new ModMonoWebSource (configurationManager.Filename, lockfile);

            if(configurationManager.Terminate) {
                if (configurationManager.Verbose)
                    Logger.Write (LogLevel.Notice, "Shutting down running mod-mono-server...");

                bool res = webSource.GracefulShutdown ();
                if (configurationManager.Verbose)
                    if (res)
                        Logger.Write (LogLevel.Notice, "Done");
                    else
                        Logger.Write (LogLevel.Error, "Failed.");

                return res ? 0 : 1;
            }

            var server = new ApplicationServer (webSource, configurationManager.Root) {
                Verbose = configurationManager.Verbose,
                SingleApplication = !root
            };

            #if DEBUG
            Console.WriteLine (Assembly.GetExecutingAssembly ().GetName ().Name);
            #endif
            if (configurationManager.Applications != null)
                server.AddApplicationsFromCommandLine (configurationManager.Applications);

            if (configurationManager.AppConfigFile != null)
                server.AddApplicationsFromConfigFile (configurationManager.AppConfigFile);

            if (configurationManager.AppConfigDir != null)
                server.AddApplicationsFromConfigDirectory (configurationManager.AppConfigDir);

            if (!configurationManager.Master && configurationManager.Applications == null
                && configurationManager.AppConfigDir == null && configurationManager.AppConfigFile == null)
                server.AddApplicationsFromCommandLine ("/:."); // TODO: do we really want this?

            VPathToHost vh = server.GetSingleApp ();
            if (root && vh != null) {
                // Redo in new domain
                vh.CreateHost (server, webSource);
                var svr = (Server)vh.AppHost.Domain.CreateInstanceAndUnwrap (GetType ().Assembly.GetName ().ToString (), GetType ().FullName);
                webSource.Dispose ();
                return svr.RealMain (args, false, vh.AppHost, configurationManager.Quiet);
            }
            if (ext_apphost != null) {
                ext_apphost.Server = server;
                server.AppHost = ext_apphost;
            }
            if (!configurationManager.Quiet) {
                if (!useTCP)
                    Logger.Write (LogLevel.Notice, "Listening on: {0}", configurationManager.Filename);
                else {
                    Logger.Write (LogLevel.Notice, "Listening on port: {0}", port);
                    Logger.Write (LogLevel.Notice, "Listening on address: {0}", configurationManager.Address);
                }
                Logger.Write (LogLevel.Notice, "Root directory: {0}", configurationManager.Root);
            }

            try {
                if (server.Start (!configurationManager.NonStop, (int)configurationManager.Backlog) == false)
                    return 2;

                if (!configurationManager.NonStop) {
                    Logger.Write (LogLevel.Notice, "Hit Return to stop the server.");
                    while (true) {
                        try {
                            Console.ReadLine ();
                            break;
                        } catch (IOException) {
                            // This might happen on appdomain unload
                            // until the previous threads are terminated.
                            Thread.Sleep (500);
                        }
                    }
                    server.Stop ();
                }
            } catch (Exception e) {
                if (!(e is ThreadAbortException))
                    Logger.Write (e);
                else
                    server.ShutdownSockets ();
                return 1;
            }

            return 0;
        }
Exemplo n.º 28
0
        //
        // Parameters:
        //
        //   args - original args passed to the program
        //   root - true means caller is in the root domain
        //   ext_apphost - used when single app mode is used, in a recursive call to
        //        RealMain from the single app domain
        //   quiet - don't show messages. Used to avoid double printing of the banner
        //
        public int RealMain(string [] args, bool root, IApplicationHost ext_apphost, bool v_quiet)
        {
            var configurationManager = new ConfigurationManager("mod_mono", v_quiet,
                                                                ext_apphost == null ? null : ext_apphost.Path);

            if (!configurationManager.LoadCommandLineArgs(args))
            {
                return(1);
            }

            // Show the help and exit.
            if (configurationManager.Help)
            {
                configurationManager.PrintHelp();
#if DEBUG
                Console.WriteLine("Press any key...");
                Console.ReadKey();
#endif
                return(0);
            }

            // Show the version and exit.
            if (configurationManager.Version)
            {
                Version.Show();
                return(0);
            }

            var hash = GetHash(args);
            if (hash == -1)
            {
                Logger.Write(LogLevel.Error, "Couldn't calculate hash - should have left earlier - something is really wrong");
                return(1);
            }
            if (hash == -2)
            {
                Logger.Write(LogLevel.Error, "Couldn't calculate hash - unrecognized parameter");
                return(1);
            }

            if (!configurationManager.LoadConfigFile())
            {
                return(1);
            }

            configurationManager.SetupLogger();

            ushort port     = configurationManager.Port ?? 0;
            bool   useTCP   = port != 0;
            string lockfile = useTCP ? Path.Combine(Path.GetTempPath(), "mod_mono_TCP_") : configurationManager.Filename;
            lockfile = String.Format("{0}_{1}", lockfile, hash);

            ModMonoWebSource webSource = useTCP
                                ? new ModMonoTCPWebSource(configurationManager.Address, port, lockfile)
                                : new ModMonoWebSource(configurationManager.Filename, lockfile);

            if (configurationManager.Terminate)
            {
                if (configurationManager.Verbose)
                {
                    Logger.Write(LogLevel.Notice, "Shutting down running mod-mono-server...");
                }

                bool res = webSource.GracefulShutdown();
                if (configurationManager.Verbose)
                {
                    if (res)
                    {
                        Logger.Write(LogLevel.Notice, "Done");
                    }
                    else
                    {
                        Logger.Write(LogLevel.Error, "Failed.");
                    }
                }

                return(res ? 0 : 1);
            }

            var server = new ApplicationServer(webSource, configurationManager.Root)
            {
                Verbose           = configurationManager.Verbose,
                SingleApplication = !root
            };

#if DEBUG
            Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name);
#endif
            if (configurationManager.Applications != null)
            {
                server.AddApplicationsFromCommandLine(configurationManager.Applications);
            }

            if (configurationManager.AppConfigFile != null)
            {
                server.AddApplicationsFromConfigFile(configurationManager.AppConfigFile);
            }

            if (configurationManager.AppConfigDir != null)
            {
                server.AddApplicationsFromConfigDirectory(configurationManager.AppConfigDir);
            }

            if (!configurationManager.Master && configurationManager.Applications == null &&
                configurationManager.AppConfigDir == null && configurationManager.AppConfigFile == null)
            {
                server.AddApplicationsFromCommandLine("/:.");                  // TODO: do we really want this?
            }
            VPathToHost vh = server.GetSingleApp();
            if (root && vh != null)
            {
                // Redo in new domain
                vh.CreateHost(server, webSource);
                var svr = (Server)vh.AppHost.Domain.CreateInstanceAndUnwrap(GetType().Assembly.GetName().ToString(), GetType().FullName);
                webSource.Dispose();
                return(svr.RealMain(args, false, vh.AppHost, configurationManager.Quiet));
            }
            if (ext_apphost != null)
            {
                ext_apphost.Server = server;
                server.AppHost     = ext_apphost;
            }
            if (!configurationManager.Quiet)
            {
                if (!useTCP)
                {
                    Logger.Write(LogLevel.Notice, "Listening on: {0}", configurationManager.Filename);
                }
                else
                {
                    Logger.Write(LogLevel.Notice, "Listening on port: {0}", port);
                    Logger.Write(LogLevel.Notice, "Listening on address: {0}", configurationManager.Address);
                }
                Logger.Write(LogLevel.Notice, "Root directory: {0}", configurationManager.Root);
            }

            try {
                if (!server.Start(!configurationManager.NonStop, (int)configurationManager.Backlog))
                {
                    return(2);
                }

                if (!configurationManager.NonStop)
                {
                    Logger.Write(LogLevel.Notice, "Hit Return to stop the server.");
                    while (true)
                    {
                        try {
                            Console.ReadLine();
                            break;
                        } catch (IOException) {
                            // This might happen on appdomain unload
                            // until the previous threads are terminated.
                            Thread.Sleep(500);
                        }
                    }
                    server.Stop();
                }
            } catch (Exception e) {
                if (!(e is ThreadAbortException))
                {
                    Logger.Write(e);
                }
                else
                {
                    server.ShutdownSockets();
                }
                return(1);
            }

            return(0);
        }
Exemplo n.º 29
0
		/// <param name="args">Original args passed to the program.</param>
		/// <param name="root">If set to <c>true</c> it means the caller is in the root domain.</param>
		/// <param name="ext_apphost">Used when single app mode is used, in a recursive call to RealMain from the single app domain.</param>
		/// <param name="quiet">If set to <c>true</c> don't show messages. Used to avoid double printing of the banner.</param>
		internal CompatTuple<int, string, ApplicationServer> DebugMain (string [] args, bool root, IApplicationHost ext_apphost, bool quiet)
		{
			var configurationManager = new ConfigurationManager ("xsp", quiet);
			var security = new SecurityConfiguration ();

			if (!ParseOptions (configurationManager, args, security))
				return new CompatTuple<int,string,ApplicationServer> (1, "Error while parsing options", null);

			// Show the help and exit.
			if (configurationManager.Help) {
				configurationManager.PrintHelp ();
#if DEBUG
				Console.WriteLine ("Press any key...");
				Console.ReadKey ();
#endif
				return success;
			}

			// Show the version and exit.
			if (configurationManager.Version) {
				Version.Show ();
				return success;
			}

			if (!configurationManager.LoadConfigFile ())
				return new CompatTuple<int,string,ApplicationServer> (1, "Error while loading the configuration file", null);

			configurationManager.SetupLogger ();

			WebSource webSource;
			if (security.Enabled) {
				try {
					key = security.KeyPair;
					webSource = new XSPWebSource (configurationManager.Address,
						configurationManager.RandomPort ? default(ushort) : configurationManager.Port,
						security.Protocol, security.ServerCertificate,
						GetPrivateKey, security.AcceptClientCertificates,
						security.RequireClientCertificates, !root);
				}
				catch (CryptographicException ce) {
					Logger.Write (ce);
					return new CompatTuple<int,string,ApplicationServer> (1, "Error while setting up https", null);
				}
			} else {
				webSource = new XSPWebSource (configurationManager.Address, configurationManager.Port, !root);
			}

			var server = new ApplicationServer (webSource, configurationManager.Root) {
				Verbose = configurationManager.Verbose,
				SingleApplication = !root
			};

			if (configurationManager.Applications != null)
				server.AddApplicationsFromCommandLine (configurationManager.Applications);

			if (configurationManager.AppConfigFile != null)
				server.AddApplicationsFromConfigFile (configurationManager.AppConfigFile);

			if (configurationManager.AppConfigDir != null)
				server.AddApplicationsFromConfigDirectory (configurationManager.AppConfigDir);

			if (configurationManager.Applications == null && configurationManager.AppConfigDir == null && configurationManager.AppConfigFile == null)
				server.AddApplicationsFromCommandLine ("/:.");


			VPathToHost vh = server.GetSingleApp ();
			if (root && vh != null) {
				// Redo in new domain
				vh.CreateHost (server, webSource);
				var svr = (Server) vh.AppHost.Domain.CreateInstanceAndUnwrap (GetType ().Assembly.GetName ().ToString (), GetType ().FullName);
				webSource.Dispose ();
				return svr.DebugMain (args, false, vh.AppHost, configurationManager.Quiet);
			}
			server.AppHost = ext_apphost;

			if (!configurationManager.Quiet) {
				Logger.Write(LogLevel.Notice, Assembly.GetExecutingAssembly().GetName().Name);
				Logger.Write(LogLevel.Notice, "Listening on address: {0}", configurationManager.Address);
				Logger.Write(LogLevel.Notice, "Root directory: {0}", configurationManager.Root);
			}

			try {
				if (!server.Start (!configurationManager.NonStop, (int)configurationManager.Backlog))
					return new CompatTuple<int,string,ApplicationServer> (2, "Error while starting server", server);

				if (!configurationManager.Quiet) {
					// MonoDevelop depends on this string. If you change it, let them know.
					Logger.Write(LogLevel.Notice, "Listening on port: {0} {1}", server.Port, security);
				}
				if (configurationManager.RandomPort && !configurationManager.Quiet)
					Logger.Write (LogLevel.Notice, "Random port: {0}", server.Port);
				
				if (!configurationManager.NonStop) {
					if (!configurationManager.Quiet)
						Console.WriteLine ("Hit Return to stop the server.");

					while (true) {
						bool doSleep;
						try {
							Console.ReadLine ();
							break;
						} catch (IOException) {
							// This might happen on appdomain unload
							// until the previous threads are terminated.
							doSleep = true;
						} catch (ThreadAbortException) {
							doSleep = true;
						}

						if (doSleep)
							Thread.Sleep (500);
					}
					server.Stop ();
				}
			} catch (Exception e) {
				if (!(e is ThreadAbortException))
					Logger.Write (e);
				else
					server.ShutdownSockets ();
				return new CompatTuple<int,string,ApplicationServer> (1, "Error running server", server);
			}

			return new CompatTuple<int,string,ApplicationServer> (0, null, server);
		}
Exemplo n.º 30
0
        //
        // Parameters:
        //
        //   args - original args passed to the program
        //   root - true means caller is in the root domain
        //   ext_apphost - used when single app mode is used, in a recursive call to
        //        RealMain from the single app domain
        //   quiet - don't show messages. Used to avoid double printing of the banner
        //
        public int RealMain(string [] args, bool root, IApplicationHost ext_apphost, bool quiet)
        {
            SecurityConfiguration security = new SecurityConfiguration();
            ApplicationSettings   settings = new ApplicationSettings();

            if (settings.IP == null || settings.IP.Length == 0)
            {
                settings.IP = "0.0.0.0";
            }

            if (settings.Oport == null)
            {
                settings.Oport = 8080;
            }

            Options options = 0;
            int     hash    = 0;
            int     backlog = 500;

            for (int i = 0; i < args.Length; i++)
            {
                string a   = args [i];
                int    idx = (i + 1 < args.Length) ? i + 1 : i;
                hash ^= args [idx].GetHashCode() + i;

                switch (a)
                {
                case "--https":
                    CheckAndSetOptions(a, Options.Https, ref options);
                    security.Enabled = true;
                    break;

                case "--https-client-accept":
                    CheckAndSetOptions(a, Options.Https, ref options);
                    security.Enabled = true;
                    security.AcceptClientCertificates  = true;
                    security.RequireClientCertificates = false;
                    break;

                case "--https-client-require":
                    CheckAndSetOptions(a, Options.Https, ref options);
                    security.Enabled = true;
                    security.AcceptClientCertificates  = true;
                    security.RequireClientCertificates = true;
                    break;

                case "--p12file":
                    security.Pkcs12File = args [++i];
                    break;

                case "--cert":
                    security.CertificateFile = args [++i];
                    break;

                case "--pkfile":
                    security.PvkFile = args [++i];
                    break;

                case "--pkpwd":
                    security.Password = args [++i];
                    break;

                case "--protocols":
                    security.SetProtocol(args [++i]);
                    break;

                case "--port":
                    CheckAndSetOptions(a, Options.Port, ref options);
                    settings.Oport = args [++i];
                    break;

                case "--random-port":
                    CheckAndSetOptions(a, Options.RandomPort, ref options);
                    settings.Oport = 0;
                    break;

                case "--address":
                    CheckAndSetOptions(a, Options.Address, ref options);
                    settings.IP = args [++i];
                    break;

                case "--backlog":
                    string backlogstr = args [++i];
                    try {
                        backlog = Convert.ToInt32(backlogstr);
                    } catch (Exception) {
                        Console.WriteLine("The value given for backlog is not valid {0}", backlogstr);
                        return(1);
                    }
                    break;

                case "--root":
                    CheckAndSetOptions(a, Options.Root, ref options);
                    settings.RootDir = args [++i];
                    break;

                case "--applications":
                    CheckAndSetOptions(a, Options.Applications, ref options);
                    settings.Apps = args [++i];
                    break;

                case "--appconfigfile":
                    CheckAndSetOptions(a, Options.AppConfigFile, ref options);
                    settings.AppConfigFile = args [++i];
                    break;

                case "--appconfigdir":
                    CheckAndSetOptions(a, Options.AppConfigDir, ref options);
                    settings.AppConfigDir = args [++i];
                    break;

                case "--minThreads":
                    string mtstr      = args [++i];
                    int    minThreads = 0;
                    try {
                        minThreads = Convert.ToInt32(mtstr);
                    } catch (Exception) {
                        Console.WriteLine("The value given for minThreads is not valid {0}", mtstr);
                        return(1);
                    }

                    if (minThreads > 0)
                    {
                        ThreadPool.SetMinThreads(minThreads, minThreads);
                    }

                    break;

                case "--nonstop":
                    settings.NonStop = true;
                    break;

                case "--help":
                    ShowHelp();
                    return(0);

                case "--quiet":
                    quiet = true;
                    break;

                case "--version":
                    ShowVersion();
                    return(0);

                case "--verbose":
                    settings.Verbose = true;
                    break;

                case "--pidfile": {
                    string pidfile = args[++i];
                    if (pidfile != null && pidfile.Length > 0)
                    {
                        try {
                            using (StreamWriter sw = File.CreateText(pidfile))
                                sw.Write(Process.GetCurrentProcess().Id);
                        } catch (Exception ex) {
                            Console.Error.WriteLine("Failed to write pidfile {0}: {1}", pidfile, ex.Message);
                        }
                    }
                    break;
                }

                case "--no-hidden":
                    MonoWorkerRequest.CheckFileAccess = false;
                    break;

                default:
                    ShowHelp();
                    return(1);
                }
            }

            IPAddress ipaddr = null;
            ushort    port;

            try {
                port = Convert.ToUInt16(settings.Oport);
            } catch (Exception) {
                Console.WriteLine("The value given for the listen port is not valid: " + settings.Oport);
                return(1);
            }

            try {
                ipaddr = IPAddress.Parse(settings.IP);
            } catch (Exception) {
                Console.WriteLine("The value given for the address is not valid: " + settings.IP);
                return(1);
            }

            if (settings.RootDir != null && settings.RootDir.Length != 0)
            {
                try {
                    Environment.CurrentDirectory = settings.RootDir;
                } catch (Exception e) {
                    Console.WriteLine("Error: {0}", e.Message);
                    return(1);
                }
            }

            settings.RootDir = Directory.GetCurrentDirectory();

            WebSource webSource;

            if (security.Enabled)
            {
                try {
                    key       = security.KeyPair;
                    webSource = new XSPWebSource(ipaddr, port, security.Protocol, security.ServerCertificate,
                                                 new PrivateKeySelectionCallback(GetPrivateKey),
                                                 security.AcceptClientCertificates, security.RequireClientCertificates, !root);
                }
                catch (CryptographicException ce) {
                    Console.WriteLine(ce.Message);
                    return(1);
                }
            }
            else
            {
                webSource = new XSPWebSource(ipaddr, port, !root);
            }

            ApplicationServer server = new ApplicationServer(webSource, settings.RootDir);

            server.Verbose           = settings.Verbose;
            server.SingleApplication = !root;

            if (settings.Apps != null)
            {
                server.AddApplicationsFromCommandLine(settings.Apps);
            }

            if (settings.AppConfigFile != null)
            {
                server.AddApplicationsFromConfigFile(settings.AppConfigFile);
            }

            if (settings.AppConfigDir != null)
            {
                server.AddApplicationsFromConfigDirectory(settings.AppConfigDir);
            }

            if (settings.Apps == null && settings.AppConfigDir == null && settings.AppConfigFile == null)
            {
                server.AddApplicationsFromCommandLine("/:.");
            }


            VPathToHost vh = server.GetSingleApp();

            if (root && vh != null)
            {
                // Redo in new domain
                vh.CreateHost(server, webSource);
                Server svr = (Server)vh.AppHost.Domain.CreateInstanceAndUnwrap(GetType().Assembly.GetName().ToString(), GetType().FullName);
                webSource.Dispose();
                return(svr.RealMain(args, false, vh.AppHost, quiet));
            }
            server.AppHost = ext_apphost;

            if (!quiet)
            {
                Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name);
                Console.WriteLine("Listening on address: {0}", settings.IP);
                Console.WriteLine("Root directory: {0}", settings.RootDir);
            }

            try {
                if (server.Start(!settings.NonStop, settings.Exception, backlog) == false)
                {
                    return(2);
                }

                if (!quiet)
                {
                    // MonoDevelop depends on this string. If you change it, let them know.
                    Console.WriteLine("Listening on port: {0} {1}", server.Port, security);
                }
                if (port == 0 && !quiet)
                {
                    Console.Error.WriteLine("Random port: {0}", server.Port);
                }

                if (!settings.NonStop)
                {
                    if (!quiet)
                    {
                        Console.WriteLine("Hit Return to stop the server.");
                    }

                    bool doSleep;
                    while (true)
                    {
                        doSleep = false;
                        try {
                            Console.ReadLine();
                            break;
                        } catch (IOException) {
                            // This might happen on appdomain unload
                            // until the previous threads are terminated.
                            doSleep = true;
                        } catch (ThreadAbortException) {
                            doSleep = true;
                        }

                        if (doSleep)
                        {
                            Thread.Sleep(500);
                        }
                    }
                    server.Stop();
                }
            } catch (Exception e) {
                if (!(e is ThreadAbortException))
                {
                    Console.WriteLine("Error: {0}", e);
                }
                else
                {
                    server.ShutdownSockets();
                }
                return(1);
            }

            return(0);
        }
        public void Start()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }
            if (Running)
            {
                throw new NotSupportedException("Web service already running");
            }
            if (Starting != null)
            {
                CancelEventArgs e = new CancelEventArgs(false);
                Starting(this, e);
                if (e.Cancel)
                {
                    return;
                }
            }
            try
            {
                if (!AmIRoot())
                {
                    throw new LogbusException("In order to start Web Service the process must be run as super user");
                }

                string appPath = InstallRuntime();
#if MONO
                WebSource ws = new XSPWebSource(IPAddress.Any, HttpPort, true);

                _appserver = new ApplicationServer(ws, appPath);
                _appserver.AddApplication(null, HttpPort, "/", appPath);

                _appserver.GetSingleApp().AppHost       = new XSPApplicationHost();
                _appserver.GetSingleApp().RequestBroker = new XSPRequestBroker();
                ((VPathToHost)_appserver.GetSingleApp()).CreateHost(_appserver, ws);

                AppDomain targetDomain = _appserver.AppHost.Domain;

                targetDomain.SetData("Logbus", (_target is MarshalByRefObject) ? (MarshalByRefObject)_target : new LogBusTie(_target));
                targetDomain.SetData("CustomFilterHelper", CustomFilterHelper.Instance);

                foreach (IPlugin plugin in _target.Plugins)
                {
                    MarshalByRefObject pluginRoot = plugin.GetPluginRoot();
                    if (pluginRoot != null)
                    {
                        targetDomain.SetData(plugin.Name, pluginRoot);
                    }
                }

                _appserver.Start(true);
#else
                string[] prefixes = { string.Format(CultureInfo.InvariantCulture, "http://+:{0}/", HttpPort) };

                _ctr = new HttpListenerController(prefixes, "/", appPath);

                _ctr.Start();

                //If object is not marshalled by reference, use a wrapper, otherwise don't complicate object graph
                _ctr.Domain.SetData("Logbus", (_target is MarshalByRefObject) ? (MarshalByRefObject)_target : new LogBusTie(_target));
                _ctr.Domain.SetData("CustomFilterHelper", CustomFilterHelper.Instance);

                foreach (IPlugin plugin in _target.Plugins)
                {
                    MarshalByRefObject pluginRoot = plugin.GetPluginRoot();
                    if (pluginRoot != null)
                    {
                        _ctr.Domain.SetData(plugin.Name, pluginRoot);
                    }
                }
#endif
                Running = true;
                if (Started != null)
                {
                    Started(this, EventArgs.Empty);
                }
            }
            catch (LogbusException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new LogbusException("Unable to start web server", ex);
            }
        }
Exemplo n.º 32
0
        private static int Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException      += TaskScheduler_UnobservedTaskException;

            var loggerFuncs = new DelegateLogger();

            loggerFuncs.Add(WriteLogMessageToConsole);

            var logger = new AggregateLogger();

            logger.Add(loggerFuncs);

            try
            {
                using (var server = new ApplicationServer())
                {
                    if (!server.IsInitialized)
                    {
                        GlobalConsole.Current.WriteLine("Initializing server... ");

                        var srvCtx = new SimpleAppServerContext(server);

                        var initCtx = new SimpleAppServerInitContext();
                        initCtx.Arguments     = args;
                        initCtx.Logger        = logger;
                        initCtx.ServerContext = srvCtx;

                        foreach (var a in args)
                        {
                            if (a.ToLower().Trim().StartsWith("/rootdir:"))
                            {
                                // custom root/working directory
                                initCtx.WorkingDirectory = new DirectoryInfo(a.Substring(a.IndexOf(':') + 1)
                                                                             .TrimStart()).FullName;
                            }
                        }

                        server.Initialize(initCtx);
                        GlobalConsole.Current.WriteLine("Server has been initialized.");

                        srvCtx.InnerServiceLocator = server.GlobalServiceLocator;
                    }

                    GlobalConsole.Current.WriteLine("Starting server... ");
                    server.Start();
                    GlobalConsole.Current.WriteLine("Server has been started.");

                    IMenuHandler currentMenu = new RootMenu();

                    string line;
                    while (true)
                    {
                        if (currentMenu == null)
                        {
                            break;
                        }

                        GlobalConsole.Current.Clear();
                        currentMenu.DrawMenu();

                        var inputIsValid = false;
                        while (!inputIsValid)
                        {
                            GlobalConsole.Current.WriteLine();
                            GlobalConsole.Current.Write("> ");

                            if (currentMenu.WaitsForInput)
                            {
                                line = GlobalConsole.Current.ReadLine();
                            }
                            else
                            {
                                line = null;
                            }

                            IMenuHandler temp;
                            if (!(inputIsValid = currentMenu.HandleInput(line, out temp)))
                            {
                                GlobalConsole.Current.WriteLine();
                                GlobalConsole.Current.WriteLine("Invalid input!");
                            }
                            else
                            {
                                currentMenu = temp;
                            }
                        }
                    }

                    GlobalConsole.Current.Write("Shutting down server... ");
                }
                GlobalConsole.Current.WriteLine("[OK]");

                return(0);
            }
            catch (Exception ex)
            {
                GlobalConsole.Current
                .WriteLine(ex.GetBaseException() ?? ex);

                return(1);
            }
        }
Exemplo n.º 33
0
        //
        // Parameters:
        //
        //   args - original args passed to the program
        //   root - true means caller is in the root domain
        //   ext_apphost - used when single app mode is used, in a recursive call to
        //        RealMain from the single app domain
        //   quiet - don't show messages. Used to avoid double printing of the banner
        //
        public int RealMain(string [] args, bool root, IApplicationHost ext_apphost, bool quiet)
        {
            ApplicationSettings settings = new ApplicationSettings();

            if (ext_apphost != null)
            {
                settings.RootDir = ext_apphost.Path;
            }

            Options options = 0;
            int     backlog = 500;
            int     hash    = 0;

            for (int i = 0; i < args.Length; i++)
            {
                string a   = args [i];
                int    idx = (i + 1 < args.Length) ? i + 1 : i;
                hash ^= args [idx].GetHashCode() + i;

                switch (a)
                {
                case "--filename":
                    CheckAndSetOptions(a, Options.FileName, ref options);
                    settings.FileName = args [++i];
                    break;

                case "--terminate":
                    CheckAndSetOptions(a, Options.Terminate, ref options);
                    break;

                case "--master":
                    CheckAndSetOptions(a, Options.Master, ref options);
                    settings.Master = true;
                    break;

                case "--port":
                    CheckAndSetOptions(a, Options.Port, ref options);
                    settings.Oport = args [++i];
                    break;

                case "--address":
                    CheckAndSetOptions(a, Options.Address, ref options);
                    settings.IP = args [++i];
                    break;

                case "--backlog":
                    string backlogstr = args [++i];
                    try {
                        backlog = Convert.ToInt32(backlogstr);
                    } catch (Exception) {
                        Console.WriteLine("The value given for backlog is not valid {0}", backlogstr);
                        return(1);
                    }
                    break;

                case "--root":
                    CheckAndSetOptions(a, Options.Root, ref options);
                    settings.RootDir = args [++i];
                    break;

                case "--applications":
                    CheckAndSetOptions(a, Options.Applications, ref options);
                    settings.Apps = args [++i];
                    break;

                case "--appconfigfile":
                    CheckAndSetOptions(a, Options.AppConfigFile, ref options);
                    settings.AppConfigFile = args [++i];
                    break;

                case "--appconfigdir":
                    CheckAndSetOptions(a, Options.AppConfigDir, ref options);
                    settings.AppConfigDir = args [++i];
                    break;

                case "--minThreads":
                    string mtstr      = args [++i];
                    int    minThreads = 0;
                    try {
                        minThreads = Convert.ToInt32(mtstr);
                    } catch (Exception) {
                        Console.WriteLine("The value given for minThreads is not valid {0}", mtstr);
                        return(1);
                    }

                    if (minThreads > 0)
                    {
                        ThreadPool.SetMinThreads(minThreads, minThreads);
                    }

                    break;

                case "--nonstop":
                    settings.NonStop = true;
                    break;

                case "--help":
                    ShowHelp();
                    return(0);

                case "--version":
                    ShowVersion();
                    return(0);

                case "--verbose":
                    settings.Verbose = true;
                    break;

                case "--pidfile": {
                    string pidfile = args[++i];
                    if (pidfile != null && pidfile.Length > 0)
                    {
                        try {
                            using (StreamWriter sw = File.CreateText(pidfile))
                                sw.Write(Process.GetCurrentProcess().Id);
                        } catch (Exception ex) {
                            Console.Error.WriteLine("Failed to write pidfile {0}: {1}", pidfile, ex.Message);
                        }
                    }
                    break;
                }

                case "--no-hidden":
                    MonoWorkerRequest.CheckFileAccess = false;
                    break;

                default:
                    Console.Error.WriteLine("Unknown argument: {0}", a);
                    ShowHelp();
                    return(1);
                }
            }

            if (hash < 0)
            {
                hash = -hash;
            }

            string lockfile;
            bool   useTCP = ((options & Options.Port) != 0);

            if (!useTCP)
            {
                if (settings.FileName == null || settings.FileName.Length == 0)
                {
                    settings.FileName = "/tmp/mod_mono_server";
                }

                if ((options & Options.Address) != 0)
                {
                    ShowHelp();
                    Console.Error.WriteLine();
                    Console.Error.WriteLine("ERROR: --address without --port");
                    Environment.Exit(1);
                }
                lockfile = Path.Combine(Path.GetTempPath(), Path.GetFileName(settings.FileName));
                lockfile = String.Format("{0}_{1}", lockfile, hash);
            }
            else
            {
                lockfile = Path.Combine(Path.GetTempPath(), "mod_mono_TCP_");
                lockfile = String.Format("{0}_{1}", lockfile, hash);
            }

            IPAddress ipaddr = null;
            ushort    port;

            try {
                port = Convert.ToUInt16(settings.Oport);
            } catch (Exception) {
                Console.Error.WriteLine("The value given for the listen port is not valid: " + settings.Oport);
                return(1);
            }

            try {
                ipaddr = IPAddress.Parse(settings.IP);
            } catch (Exception) {
                Console.Error.WriteLine("The value given for the address is not valid: " + settings.IP);
                return(1);
            }

            if (settings.RootDir != null && settings.RootDir.Length > 0)
            {
                try {
                    Environment.CurrentDirectory = settings.RootDir;
                } catch (Exception e) {
                    Console.Error.WriteLine("Error: {0}", e.Message);
                    return(1);
                }
            }

            settings.RootDir = Directory.GetCurrentDirectory();

            WebSource webSource;

            if (useTCP)
            {
                webSource = new ModMonoTCPWebSource(ipaddr, port, lockfile);
            }
            else
            {
                webSource = new ModMonoWebSource(settings.FileName, lockfile);
            }

            if ((options & Options.Terminate) != 0)
            {
                if (settings.Verbose)
                {
                    Console.Error.WriteLine("Shutting down running mod-mono-server...");
                }

                bool res = ((ModMonoWebSource)webSource).GracefulShutdown();
                if (settings.Verbose)
                {
                    Console.Error.WriteLine(res ? "Done." : "Failed");
                }

                return((res) ? 0 : 1);
            }

            ApplicationServer server = new ApplicationServer(webSource, settings.RootDir);

            server.Verbose           = settings.Verbose;
            server.SingleApplication = !root;

            Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name);
            if (settings.Apps != null)
            {
                server.AddApplicationsFromCommandLine(settings.Apps);
            }

            if (settings.AppConfigFile != null)
            {
                server.AddApplicationsFromConfigFile(settings.AppConfigFile);
            }

            if (settings.AppConfigDir != null)
            {
                server.AddApplicationsFromConfigDirectory(settings.AppConfigDir);
            }

            if (!settings.Master && settings.Apps == null && settings.AppConfigDir == null && settings.AppConfigFile == null)
            {
                server.AddApplicationsFromCommandLine("/:.");
            }

            VPathToHost vh = server.GetSingleApp();

            if (root && vh != null)
            {
                // Redo in new domain
                vh.CreateHost(server, webSource);
                Server svr = (Server)vh.AppHost.Domain.CreateInstanceAndUnwrap(GetType().Assembly.GetName().ToString(), GetType().FullName);
                webSource.Dispose();
                return(svr.RealMain(args, false, vh.AppHost, quiet));
            }
            if (ext_apphost != null)
            {
                ext_apphost.Server = server;
                server.AppHost     = ext_apphost;
            }
            if (!useTCP && !quiet)
            {
                Console.Error.WriteLine("Listening on: {0}", settings.FileName);
            }
            else if (!quiet)
            {
                Console.Error.WriteLine("Listening on port: {0}", port);
                Console.Error.WriteLine("Listening on address: {0}", settings.IP);
            }

            if (!quiet)
            {
                Console.Error.WriteLine("Root directory: {0}", settings.RootDir);
            }

            try {
                if (server.Start(!settings.NonStop, backlog) == false)
                {
                    return(2);
                }

                if (!settings.NonStop)
                {
                    Console.Error.WriteLine("Hit Return to stop the server.");
                    while (true)
                    {
                        try {
                            Console.ReadLine();
                            break;
                        } catch (IOException) {
                            // This might happen on appdomain unload
                            // until the previous threads are terminated.
                            Thread.Sleep(500);
                        }
                    }
                    server.Stop();
                }
            } catch (Exception e) {
                if (!(e is ThreadAbortException))
                {
                    Console.Error.WriteLine("Error: {0}", e.Message);
                }
                else
                {
                    server.ShutdownSockets();
                }
                return(1);
            }

            return(0);
        }