Exemple #1
0
        public void Initialize()
        {
            var sp          = Stopwatch.StartNew();
            var clusterCert = InitializeClusterCertificate(out var httpsCert);

            try
            {
                ServerStore.Initialize();
            }
            catch (Exception e)
            {
                if (Logger.IsOperationsEnabled)
                {
                    Logger.Operations("Could not open the server store", e);
                }
                throw;
            }

            if (Logger.IsInfoEnabled)
            {
                Logger.Info(string.Format("Server store started took {0:#,#;;0} ms", sp.ElapsedMilliseconds));
            }

            sp.Restart();
            ListenToPipes().IgnoreUnobservedExceptions();
            Router = new RequestRouter(RouteScanner.Scan(), this);

            try
            {
                void ConfigureKestrel(KestrelServerOptions options)
                {
                    options.Limits.MaxRequestLineSize     = (int)Configuration.Http.MaxRequestLineSize.GetValue(SizeUnit.Bytes);
                    options.Limits.MaxRequestBodySize     = null;   // no limit!
                    options.Limits.MinResponseDataRate    = null;   // no limit!
                    options.Limits.MinRequestBodyDataRate = null;   // no limit!

                    if (Configuration.Http.MinDataRatePerSecond.HasValue && Configuration.Http.MinDataRateGracePeriod.HasValue)
                    {
                        options.Limits.MinResponseDataRate    = new MinDataRate(Configuration.Http.MinDataRatePerSecond.Value.GetValue(SizeUnit.Bytes), Configuration.Http.MinDataRateGracePeriod.Value.AsTimeSpan);
                        options.Limits.MinRequestBodyDataRate = new MinDataRate(Configuration.Http.MinDataRatePerSecond.Value.GetValue(SizeUnit.Bytes), Configuration.Http.MinDataRateGracePeriod.Value.AsTimeSpan);
                    }

                    if (Configuration.Http.MaxRequestBufferSize.HasValue)
                    {
                        options.Limits.MaxRequestBufferSize = Configuration.Http.MaxRequestBufferSize.Value.GetValue(SizeUnit.Bytes);
                    }

                    var actualCert = httpsCert ?? clusterCert;

                    if (actualCert != null)
                    {
                        var adapterOptions = new HttpsConnectionAdapterOptions
                        {
                            ServerCertificate          = actualCert.Certificate,
                            CheckCertificateRevocation = true,
                            ClientCertificateMode      = ClientCertificateMode.AllowCertificate,
                            SslProtocols = SslProtocols.Tls12,
                            ClientCertificateValidation = (cert, chain, errors) =>
                                                          // Here we are explicitly ignoring trust chain issues for client certificates
                                                          // this is because we don't actually require trust, we just use the certificate
                                                          // as a way to authenticate. The admin is going to tell us which specific certs
                                                          // we can trust anyway, so we can ignore such errors.
                                                          errors == SslPolicyErrors.RemoteCertificateChainErrors || errors == SslPolicyErrors.None
                        };

                        var uri         = new Uri(Configuration.Core.ServerUrl);
                        var host        = uri.DnsSafeHost;
                        var ipAddresses = GetListenIpAddresses(host);

                        var loggerFactory = options.ApplicationServices.GetRequiredService <ILoggerFactory>();
                        var adapter       = new AuthenticatingAdapter(this, new HttpsConnectionAdapter(adapterOptions, loggerFactory));

                        foreach (var address in ipAddresses)
                        {
                            options.Listen(address, uri.Port, listenOptions => { listenOptions.ConnectionAdapters.Add(adapter); });
                        }
                    }
                }

                _webHost = new WebHostBuilder()
                           .CaptureStartupErrors(captureStartupErrors: true)
                           .UseKestrel(ConfigureKestrel)
                           .UseUrls(Configuration.Core.ServerUrl)
                           .UseStartup <RavenServerStartup>()
                           .UseShutdownTimeout(TimeSpan.FromSeconds(1))
                           .ConfigureServices(services =>
                {
                    if (Configuration.Http.UseResponseCompression)
                    {
                        services.Configure <ResponseCompressionOptions>(options =>
                        {
                            options.EnableForHttps = Configuration.Http.AllowResponseCompressionOverHttps;
                            options.Providers.Add(typeof(GzipCompressionProvider));
                            options.Providers.Add(typeof(DeflateCompressionProvider));
                        });

                        services.Configure <GzipCompressionProviderOptions>(options =>
                        {
                            options.Level = Configuration.Http.GzipResponseCompressionLevel;
                        });

                        services.Configure <DeflateCompressionProviderOptions>(options =>
                        {
                            options.Level = Configuration.Http.DeflateResponseCompressionLevel;
                        });

                        services.AddResponseCompression();
                    }

                    services.AddSingleton(Router);
                    services.AddSingleton(this);
                    services.Configure <FormOptions>(options =>
                    {
                        options.MultipartBodyLengthLimit = long.MaxValue;
                    });
                })
                           // ReSharper disable once AccessToDisposedClosure
                           .Build();

                ClusterCertificateHolder = ClusterCertificateHolder ?? httpsCert ?? new CertificateHolder();
            }
            catch (Exception e)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Could not configure server", e);
                }
                throw;
            }

            if (Logger.IsInfoEnabled)
            {
                Logger.Info(string.Format("Configuring HTTP server took {0:#,#;;0} ms", sp.ElapsedMilliseconds));
            }

            try
            {
                _webHost.Start();

                var serverAddressesFeature = _webHost.ServerFeatures.Get <IServerAddressesFeature>();
                WebUrl = GetWebUrl(serverAddressesFeature.Addresses.First()).TrimEnd('/');

                if (Logger.IsInfoEnabled)
                {
                    Logger.Info($"Initialized Server... {WebUrl}");
                }

                ServerStore.TriggerDatabases();

                _tcpListenerStatus = StartTcpListener();

                StartSnmp();
            }
            catch (Exception e)
            {
                if (Logger.IsOperationsEnabled)
                {
                    Logger.Operations("Could not start server", e);
                }
                throw;
            }
        }
Exemple #2
0
        public void Initialize()
        {
            var sp = Stopwatch.StartNew();

            try
            {
                ServerStore.Initialize();
            }
            catch (Exception e)
            {
                if (_logger.IsOperationsEnabled)
                {
                    _logger.Operations("Could not open the server store", e);
                }
                throw;
            }

            if (_logger.IsInfoEnabled)
            {
                _logger.Info(string.Format("Server store started took {0:#,#;;0} ms", sp.ElapsedMilliseconds));
            }

            sp.Restart();

            Router = new RequestRouter(RouteScanner.Scan(), this);

            try
            {
                _webHost = new WebHostBuilder()
                           .CaptureStartupErrors(captureStartupErrors: true)
                           .UseKestrel(options =>
                {
                    options.ShutdownTimeout = TimeSpan.FromSeconds(1);
                })
                           .UseUrls(Configuration.Core.ServerUrl)
                           .UseStartup <RavenServerStartup>()
                           .ConfigureServices(services =>
                {
                    services.AddSingleton(Router);
                    services.AddSingleton(this);
                    services.Configure <FormOptions>(options =>
                    {
                        options.MultipartBodyLengthLimit = long.MaxValue;
                    });
                })
                           // ReSharper disable once AccessToDisposedClosure
                           .Build();
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("Initialized Server...");
                }
            }
            catch (Exception e)
            {
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("Could not configure server", e);
                }
                throw;
            }

            if (_logger.IsInfoEnabled)
            {
                _logger.Info(string.Format("Configuring HTTP server took {0:#,#;;0} ms", sp.ElapsedMilliseconds));
            }

            try
            {
                _webHost.Start();
                _tcpListenerTask = StartTcpListener();
            }
            catch (Exception e)
            {
                if (_logger.IsOperationsEnabled)
                {
                    _logger.Operations("Could not start server", e);
                }
                throw;
            }

            try
            {
                _latestVersionCheck.Initialize();
            }
            catch (Exception e)
            {
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("Could not setup latest version check.", e);
                }
            }

            try
            {
                LicenseManager.Initialize();
            }
            catch (Exception e)
            {
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("Could not setup license check.", e);
                }

                ServerStore.Alerts.AddAlert(new Alert
                {
                    Type     = AlertType.LicenseManagerInitializationError,
                    Key      = nameof(AlertType.LicenseManagerInitializationError),
                    Severity = AlertSeverity.Info,
                    Content  = new LicenseManager.InitializationErrorAlertContent(e),
                    Message  = LicenseManager.InitializationErrorAlertContent.FormatMessage()
                });
            }
        }