Esempio n. 1
0
        public virtual async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            HostingEventSource.Log.HostStart();
            _logger = _applicationServices.GetRequiredService <ILogger <WebHost> >();

            Initialize();

            _applicationLifetime   = _applicationServices.GetRequiredService <IApplicationLifetime>() as ApplicationLifetime;
            _hostedServiceExecutor = _applicationServices.GetRequiredService <HostedServiceExecutor>();
            var diagnosticSource   = _applicationServices.GetRequiredService <DiagnosticListener>();
            var httpContextFactory = _applicationServices.GetRequiredService <IHttpContextFactory>();
            var hostingApp         = new HostingApplication(_application, _logger, diagnosticSource, httpContextFactory);
            await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false);

            // Fire IApplicationLifetime.Started
            _applicationLifetime?.NotifyStarted();

            // Fire IHostedService.Start
            await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false);

            // Log the fact that we did load hosting startup assemblies.
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                foreach (var assembly in _options.HostingStartupAssemblies)
                {
                    _logger.LogDebug("Loaded hosting startup assembly {assemblyName}", assembly);
                }
            }
        }
        private static IServiceCollection GetInitialServiceCollection()
        {
            var serviceCollection   = new ServiceCollection();
            var diagnosticSource    = new DiagnosticListener(TestFrameworkName);
            var applicationLifetime = new ApplicationLifetime();

            // default server services
            serviceCollection.AddSingleton(Environment);
            serviceCollection.AddSingleton <IApplicationLifetime>(applicationLifetime);

            serviceCollection.AddSingleton <ILoggerFactory>(LoggerFactoryMock.Create());
            serviceCollection.AddLogging();

            serviceCollection.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
            serviceCollection.AddTransient <IHttpContextFactory, HttpContextFactory>();
            serviceCollection.AddOptions();

            serviceCollection.AddSingleton <DiagnosticSource>(diagnosticSource);
            serviceCollection.AddSingleton(diagnosticSource);

            serviceCollection.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>();
            serviceCollection.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            serviceCollection.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

            return(serviceCollection);
        }
Esempio n. 3
0
        private async Task startAspNetCoreServer()
        {
            if (!Registry.HttpRoutes.Enabled || Registry.BootstrappedWithinAspNetCore)
            {
                return;
            }


            HostingEventSource.Log.HostStart();

            _logger = Get <ILoggerFactory>().CreateLogger("Jasper");

            _applicationLifetime = TypeExtensions.As <ApplicationLifetime>(Container.GetInstance <IApplicationLifetime>());

            var httpContextFactory = Container.QuickBuild <HttpContextFactory>();

            var hostingApp = new HostingApplication(
                RequestDelegate,
                _logger,
                Container.GetInstance <DiagnosticListener>(), // See if this can be passed in directly
                httpContextFactory);

            await _server.StartAsync(hostingApp, Settings.Cancellation);

            // Fire IApplicationLifetime.Started
            _applicationLifetime?.NotifyStarted();
        }
Esempio n. 4
0
        public HostingEngine(
            IServiceCollection appServices,
            IStartupLoader startupLoader,
            IConfiguration config,
            bool captureStartupErrors)
        {
            if (appServices == null)
            {
                throw new ArgumentNullException(nameof(appServices));
            }

            if (startupLoader == null)
            {
                throw new ArgumentNullException(nameof(startupLoader));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            _config = config;
            _applicationServiceCollection = appServices;
            _startupLoader        = startupLoader;
            _captureStartupErrors = captureStartupErrors;
            _applicationLifetime  = new ApplicationLifetime();
            _applicationServiceCollection.AddInstance <IApplicationLifetime>(_applicationLifetime);
        }
 // Called by base.Stop. This may be called multiple times by service Stop, ApplicationStopping, and StopAsync.
 // That's OK because StopApplication uses a CancellationTokenSource and prevents any recursion.
 protected override void OnStop()
 {
     ApplicationLifetime.StopApplication();
     // Wait for the host to shutdown before marking service as stopped.
     _delayStop.Wait(_hostOptions.ShutdownTimeout);
     base.OnStop();
 }
Esempio n. 6
0
        async Task DoMain()
        {
            try
            {
                using var applicationLifetime = new ApplicationLifetime();
                var services = InitializeDependencyInjection();
                ConfigureServices(services, applicationLifetime);

                using (var provider = services.BuildServiceProvider())
                {
                    var encryptionService = provider.GetRequiredService <IEncryptionService>();

                    var encryptedString = encryptionService.Encrypt("Sample123!");
                    var decryptedString = encryptionService.Decrypt(encryptedString);
                    Console.WriteLine(
                        $@"Encrypted String
{ encryptedString }

Decrypted String
{ decryptedString }
");
                }
                applicationLifetime.StopApplication();
                await Task.CompletedTask.ConfigureAwait(false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine("End...");
                Console.ReadKey();
            }
        }
Esempio n. 7
0
        private void HandlePosixSignal(PosixSignalContext context)
        {
            Debug.Assert(context.Signal == PosixSignal.SIGTERM);

            context.Cancel = true;
            ApplicationLifetime.StopApplication();
        }
Esempio n. 8
0
        /// <summary>
        /// Starts listening for new Websocket stream connections
        /// </summary>
        /// <param name="endpoint">The endpoint to listen to</param>
        /// <param name="connectionAdded">A connection delegate that is called when a new client is connected</param>
        /// <param name="bufferSize">Buffer sized used for receiving</param>
        /// <param name="defaultPage">Default response to clients like browsers</param>
        /// <returns></returns>
        public Task StartAsync(IPEndPoint endpoint, Func <WsStream, Task> connectionAdded, int bufferSize = Config.InternalBufferSize, string defaultPage = Config.Version)
        {
            if (IsListening)
            {
                throw new InvalidOperationException("WsServer is already running!");
            }
            _stopSource = new CancellationTokenSource();
            IsListening = true;
            // setup kestrel parameters
            var logger                 = new NullLoggerFactory();
            var kestrelOptions         = new KestrelServerOptions();
            var lifetime               = new ApplicationLifetime(logger.CreateLogger <ApplicationLifetime>());
            var socketTransportFactory = new SocketTransportFactory(Options.Create(new SocketTransportOptions()), lifetime, logger);

            // start kestrel
            _server = new KestrelServer(Options.Create(kestrelOptions), socketTransportFactory, logger);
            _server.Options.Listen(endpoint);
            return(_server
                   .StartAsync(new KestrelRequestHandler(connectionAdded, bufferSize, _stopSource.Token, defaultPage),
                               CancellationToken.None).ContinueWith(
                       x =>
            {
                var addr = _server.Features.Get <IServerAddressesFeature>();
                ListeningAddresses = addr.Addresses.ToArray();
            }));
        }
Esempio n. 9
0
        private KestrelServer CreateKestrelServer(string prefix)
        {
            var options = new KestrelServerOptions
            {
                AddServerHeader = false,
                Limits          =
                {
                    KeepAliveTimeout           = 2.Minutes(),
                    MaxRequestHeaderCount      =         200,
                    MaxRequestHeadersTotalSize =  128 * 1024,
                    MaxRequestLineSize         = 256 * 1024
                }
            };

            SetupHttps(prefix, options);

            var optionsWrapper = new OptionsWrapper <KestrelServerOptions>(options);


            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(new MicrosoftLoggerWrapperProvider(_log));

            var lifeTime = new ApplicationLifetime(loggerFactory.CreateLogger <ApplicationLifetime>());

            var socketTransportFactory = CreatSocketTransportFactory(lifeTime, loggerFactory);

            return(new KestrelServer(optionsWrapper, socketTransportFactory, loggerFactory));
        }
        public static Task Main(string[] args)
        {
            var parsedArgs = Args.Parse(args);

            if (parsedArgs.Benchmark)
            {
                BenchmarkInHarness(parsedArgs);
                return(Task.CompletedTask);
            }

            IServerApplication app = null;

            if (parsedArgs.Mode == Mode.Raw)
            {
                app = new PlainTextRawApplication();
            }
            else if (parsedArgs.Mode == Mode.Features)
            {
                app = new PlainTextApplication();
            }
            else if (parsedArgs.Mode == Mode.RawWithHeaders)
            {
                app = new PlainTextRawWithHeadersApplication();
            }
            else
            {
                app = new HttpServer <BenchmarkHandler>();
            }

            var lifetime         = new ApplicationLifetime(NullLoggerFactory.Instance.CreateLogger <ApplicationLifetime>());
            var binding          = new IPEndPointInformation(new IPEndPoint(IPAddress.Any, parsedArgs.Port));
            var transportFactory = CreateTransport(parsedArgs, lifetime);

            return(app.RunAsync(transportFactory, binding, lifetime));
        }
        public async Task RunAsync(int port, int threadCount)
        {
            var lifetime = new ApplicationLifetime(NullLoggerFactory.Instance.CreateLogger <ApplicationLifetime>());

            Console.CancelKeyPress += (sender, e) => lifetime.StopApplication();

            var libuvOptions = new LibuvTransportOptions
            {
                ThreadCount = threadCount
            };
            var libuvTransport = new LibuvTransportFactory(
                Options.Create(libuvOptions),
                lifetime,
                NullLoggerFactory.Instance);

            var binding = new IPEndPointInformation(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port));

            var transport = libuvTransport.Create(binding, this);
            await transport.BindAsync();

            Console.WriteLine($"Server (raw with headers) listening on http://*:{port} with {libuvOptions.ThreadCount} thread(s)");

            lifetime.ApplicationStopping.WaitHandle.WaitOne();

            await transport.UnbindAsync();

            await transport.StopAsync();
        }
Esempio n. 12
0
        public async Task RunAsync(int port, int threadCount)
        {
            var lifetime = new ApplicationLifetime(NullLoggerFactory.Instance.CreateLogger <ApplicationLifetime>());

            Console.CancelKeyPress += (sender, e) => lifetime.StopApplication();

            var libuvOptions = new LibuvTransportOptions
            {
                ThreadCount = threadCount
            };
            var libuvTransport = new LibuvTransportFactory(
                Options.Create(libuvOptions),
                lifetime,
                NullLoggerFactory.Instance);

            var serverOptions = new KestrelServerOptions();

            serverOptions.Listen(IPAddress.Any, port);

            var server = new KestrelServer(Options.Create(serverOptions),
                                           libuvTransport,
                                           NullLoggerFactory.Instance);

            await server.StartAsync(this, CancellationToken.None);

            Console.WriteLine($"Server listening on http://*:{port} with {libuvOptions.ThreadCount} thread(s)");

            lifetime.ApplicationStopping.WaitHandle.WaitOne();

            await server.StopAsync(CancellationToken.None);
        }
Esempio n. 13
0
 public HostingEngine(IServiceProvider fallbackServices)
 {
     _fallbackServices = fallbackServices ?? CallContextServiceLocator.Locator.ServiceProvider;
     _appLifetime = new ApplicationLifetime();
     _applicationEnvironment = _fallbackServices.GetRequiredService<IApplicationEnvironment>();
     _hostingEnvironment = new HostingEnvironment(_applicationEnvironment);
     _fallbackServices = new WrappingServiceProvider(_fallbackServices, _hostingEnvironment, _appLifetime);
 }
Esempio n. 14
0
 public MycoHost(IServiceProvider services, IHostApplicationLifetime applicationLifetime, ILogger <MycoHost> logger,
                 IHostLifetime hostLifetime, IOptions <HostOptions> options)
 {
     this.Services            = services ?? throw new ArgumentNullException(nameof(services));
     this.applicationLifetime = (applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime))) as ApplicationLifetime;
     this.logger       = logger ?? throw new ArgumentNullException(nameof(logger));
     this.hostLifetime = hostLifetime ?? throw new ArgumentNullException(nameof(hostLifetime));
     this.options      = options?.Value ?? throw new ArgumentNullException(nameof(options));
 }
Esempio n. 15
0
        public IActionResult ShutDown()
        {
            Task.Run(() =>
            {
                Task.WaitAll(Task.Delay(500));
                ApplicationLifetime.StopApplication();
            });

            return(Redirect("https://google.com"));
        }
Esempio n. 16
0
 public HostingEngine(
     [NotNull] IServiceCollection appServices,
     [NotNull] IStartupLoader startupLoader,
     [NotNull] IConfiguration config)
 {
     _config = config;
     _applicationServiceCollection = appServices;
     _startupLoader       = startupLoader;
     _applicationLifetime = new ApplicationLifetime();
 }
Esempio n. 17
0
        private void OnProcessExit(object sender, EventArgs e)
        {
            ApplicationLifetime.StopApplication();

            _shutdownBlock.WaitOne();

            // On Linux if the shutdown is triggered by SIGTERM then that's signaled with the 143 exit code.
            // Suppress that since we shut down gracefully. https://github.com/dotnet/aspnetcore/issues/6526
            System.Environment.ExitCode = 0;
        }
Esempio n. 18
0
        protected void StartFeatures()
        {
            this.applicationLifetime     = this.Services?.ServiceProvider.GetRequiredService <IApplicationLifetime>() as ApplicationLifetime;
            this.fullNodeFeatureExecutor = this.Services?.ServiceProvider.GetRequiredService <FullNodeFeatureExecutor>();

            // Fire IApplicationLifetime.Started
            this.applicationLifetime?.NotifyStarted();

            //start all registered features
            this.fullNodeFeatureExecutor?.Start();
        }
Esempio n. 19
0
        public OicHost(IServiceCollection applicationServiceCollection, IServiceProvider hostingServiceProvider,
                       IConfiguration config)
        {
            _applicationServiceCollection = applicationServiceCollection;
            _hostingServiceProvider       = hostingServiceProvider ?? throw new ArgumentNullException(nameof(hostingServiceProvider));
            _config = config ?? throw new ArgumentNullException(nameof(config));

            _applicationLifetime = new ApplicationLifetime();
            _applicationServiceCollection.AddSingleton <IApplicationLifetime>(_applicationLifetime);
            _applicationServiceCollection.AddSingleton(this);
        }
Esempio n. 20
0
        private SocketTransportFactory CreatSocketTransportFactory(ApplicationLifetime lifeTime,
                                                                   LoggerFactory loggerFactory)
        {
            var configureOptions = new ConfigureOptions <SocketTransportOptions>(transportOptions =>
                                                                                 transportOptions.IOQueueCount = _serverSettings.IOQueueCount);
            var optionsFactory = new OptionsFactory <SocketTransportOptions>(new[] { configureOptions },
                                                                             new List <IPostConfigureOptions <SocketTransportOptions> >());
            var optionsManager         = new OptionsManager <SocketTransportOptions>(optionsFactory);
            var socketTransportFactory = new SocketTransportFactory(optionsManager, lifeTime, loggerFactory);

            return(socketTransportFactory);
        }
Esempio n. 21
0
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     try
     {
         await RunTest(stoppingToken);
     }
     catch (Exception ex)
     {
         Logger.LogError(ex, "Test run failed");
         ApplicationLifetime.StopApplication();
     }
 }
Esempio n. 22
0
        public KestrelWebServer(int port, List <IKoobooMiddleWare> middlewares, bool forcessl = false)
        {
            var life = new ApplicationLifetime(null);

            var log = new Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory();

            SocketTransportFactory usesocket = new SocketTransportFactory(new koobooSocketOption(), life, log);

            _server = new KestrelServer(new KoobooServerOption(port, forcessl), usesocket, log);

            SetMiddleWares(middlewares);
        }
Esempio n. 23
0
        private void OnProcessExit(object sender, EventArgs e)
        {
            ApplicationLifetime.StopApplication();
            if (!_shutdownBlock.WaitOne(HostOptions.ShutdownTimeout))
            {
                Logger.LogInformation("Waiting for the host to be disposed, ensure all 'IHost' instances are wrapped in 'using' blocks");
            }

            _shutdownBlock.WaitOne();
            // On Linux if the shutdown is triggered by SIGTERM then that's signaled with the 143 exit code.
            // Suppress that since we shut down gracefully. https://github.com/aspnet/AspNetCore/issues/6526
            System.Environment.ExitCode = 0;
        }
    private void OnExit(object sender, EventArgs e)
    {
        ApplicationLifetime.StopApplication();

        if (!_shutdownBlock.WaitOne(HostOptions.ShutdownTimeout))
        {
            Logger.LogInformation("Waiting for the host to be disposed. Ensure all 'IHost' instances are wrapped in 'using' blocks.");
        }

        _shutdownBlock.WaitOne();

        System.Environment.ExitCode = 0;
    }
Esempio n. 25
0
        public ServerKestrel()
        {
            var options = new KestrelServerOptions
            {
                AddServerHeader = false,
            };
            var optionsWrapper = new OptionsWrapper <KestrelServerOptions>(options);
            var loggerFactory  = new LoggerFactory();
            var lifeTime       = new ApplicationLifetime(loggerFactory.CreateLogger <ApplicationLifetime>());

            server = new KestrelServer(optionsWrapper, new LibuvTransportFactory(new OptionsManager <LibuvTransportOptions>(
                                                                                     new OptionsFactory <LibuvTransportOptions>(
                                                                                         new List <IConfigureOptions <LibuvTransportOptions> >(), new List <IPostConfigureOptions <LibuvTransportOptions> >())), lifeTime, loggerFactory), loggerFactory);
        }
Esempio n. 26
0
        public override void OnFrameworkInitializationCompleted()
        {
            base.OnFrameworkInitializationCompleted();

            switch (ApplicationLifetime)
            {
            case IClassicDesktopStyleApplicationLifetime classicDesktopStyleApplicationLifetime:
                classicDesktopStyleApplicationLifetime.MainWindow = new MainWindow();
                return;

            default:
                throw new NotSupportedException($"Unknown application life time: {ApplicationLifetime?.GetType().FullName}");
            }
        }
Esempio n. 27
0
        public KestrelOwinServer(KestrelServerOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var wrappedOptions = Options.Create(options);

            var lifetime = new ApplicationLifetime();

            var loggerFactory = new LoggerFactory();

            Server = new KestrelServer(wrappedOptions, lifetime, loggerFactory);
        }
Esempio n. 28
0
        private void ConfigureServices(IServiceCollection services, ApplicationLifetime applicationLifetime)
        {
            services.AddOptions();
            services.AddLogging(config =>
            {
                config.AddConfiguration(_configuration.GetSection("Logging"));

                if (Environment.GetEnvironmentVariable("BUILD_CONFIGURATION") == "DEBUG")
                {
                    config.AddConsole();
                }
            });
            services.AddSingleton <IApplicationLifetime>(applicationLifetime);
            services.AddEncryptionService();
            services.Configure <EncryptionServiceOptions>(_configuration.GetSection(nameof(EncryptionServiceOptions)));
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            var options = new KestrelServerOptions();

            options.NoDelay     = true;
            options.ThreadCount = 2;
            var applicationLifetime = new ApplicationLifetime();
            var server = new KestrelServer(new OptionsWrapper <KestrelServerOptions>(options), applicationLifetime,
                                           new LoggerFactory());

            server.Features.Get <IServerAddressesFeature>().Addresses.Add("http://localhost:8888");
            server.Start(new HttpApp());
            Console.WriteLine("Listening on 8888. Press Enter to stop.");
            Console.ReadLine();
            server.Dispose();
        }
        private async void Run()
        {
            Log.LogInformation($"Started. value=[{Settings.Value}]");

            try
            {
                // TODO
                await Task.Delay(30000);
            }
            catch (Exception e)
            {
                Log.LogError(e, "Error");
            }
            finally
            {
                ApplicationLifetime.StopApplication();
            }
        }
Esempio n. 31
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // Release current synchronization context for next services.
            await Task.Yield();

            using var listener = new HttpListener
                  {
                      IgnoreWriteExceptions = true,
                  };

            foreach (var prefix in Settings.Prefix.Split(','))
            {
                listener.Prefixes.Add($"http://{prefix}");
                listener.Prefixes.Add($"https://{prefix}");
            }

            Logger.LogInformation("Start listening.");
            listener.Start();

            try
            {
                using var _ = stoppingToken.Register(() => listener.Stop());

                while (listener.IsListening && !stoppingToken.IsCancellationRequested)
                {
                    await ProcessRequestAsync(await listener.GetContextAsync());
                }
            }
            // Catch cancellations and just log it.
            catch (Exception ex) when(
                (ex is HttpListenerException && stoppingToken.IsCancellationRequested) ||
                (ex is OperationCanceledException))
            {
                Logger.LogInformation("Shutdown listener due to cancellation.");
            }
            finally
            {
                Logger.LogInformation("Stopping listening.");
                listener.Close();
                ApplicationLifetime.StopApplication();
            }
        }