private void Start() { _host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\..\")) .UseStartup<Startup>() .UseEnvironment("AcceptanceTesting") .ConfigureServices(services => { services.AddScoped(serviceProvider => new LicensingContextBuilder().InMemory().Build()); }) .Build(); _host.Start(); }
Task<string> ICommunicationListener.OpenAsync(CancellationToken cancellationToken) { var endpoint = FabricRuntime.GetActivationContext().GetEndpoint(_endpointName); string serverUrl = $"{endpoint.Protocol}://{FabricRuntime.GetNodeContext().IPAddressOrFQDN}:{endpoint.Port}"; _webHost = new WebHostBuilder().UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .UseUrls(serverUrl) .Build(); _webHost.Start(); return Task.FromResult(serverUrl); }
public StressServer(Configuration configuration) { ServerUri = configuration.ServerUri; IWebHostBuilder host = WebHost.CreateDefaultBuilder(); if (configuration.UseHttpSys) { // Use http.sys. This requires additional manual configuration ahead of time; // see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/httpsys?view=aspnetcore-2.2#configure-windows-server. // In particular, you need to: // 1. Create a self-signed cert and install it into your local personal store, e.g. New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" // 2. Pre-register the URL prefix, e.g. netsh http add urlacl url=https://localhost:5001/ user=Users // 3. Register the cert, e.g. netsh http add sslcert ipport=[::1]:5001 certhash=THUMBPRINTFROMABOVE appid="{some-guid}" host = host.UseHttpSys(hso => { hso.UrlPrefixes.Add(ServerUri.ToString()); hso.Authentication.Schemes = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None; hso.Authentication.AllowAnonymous = true; hso.MaxConnections = null; hso.MaxRequestBodySize = null; }); } else { // Use Kestrel, and configure it for HTTPS with a self-signed test certificate. host = host.UseKestrel(ko => { // conservative estimation based on https://github.com/aspnet/AspNetCore/blob/caa910ceeba5f2b2c02c47a23ead0ca31caea6f0/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.cs#L204 ko.Limits.MaxRequestLineSize = Math.Max(ko.Limits.MaxRequestLineSize, configuration.MaxRequestUriSize + 100); ko.Limits.MaxRequestHeaderCount = Math.Max(ko.Limits.MaxRequestHeaderCount, configuration.MaxRequestHeaderCount); ko.Limits.MaxRequestHeadersTotalSize = Math.Max(ko.Limits.MaxRequestHeadersTotalSize, configuration.MaxRequestHeaderTotalSize); ko.Limits.Http2.MaxStreamsPerConnection = configuration.ServerMaxConcurrentStreams ?? ko.Limits.Http2.MaxStreamsPerConnection; ko.Limits.Http2.MaxFrameSize = configuration.ServerMaxFrameSize ?? ko.Limits.Http2.MaxFrameSize; ko.Limits.Http2.InitialConnectionWindowSize = configuration.ServerInitialConnectionWindowSize ?? ko.Limits.Http2.InitialConnectionWindowSize; ko.Limits.Http2.MaxRequestHeaderFieldSize = configuration.ServerMaxRequestHeaderFieldSize ?? ko.Limits.Http2.MaxRequestHeaderFieldSize; IPAddress iPAddress = Dns.GetHostAddresses(configuration.ServerUri.Host).First(); ko.Listen(iPAddress, configuration.ServerUri.Port, listenOptions => { if (configuration.ServerUri.Scheme == "https") { // Create self-signed cert for server. using (RSA rsa = RSA.Create()) { var certReq = new CertificateRequest($"CN={ServerUri.Host}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1)); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { cert = new X509Certificate2(cert.Export(X509ContentType.Pfx)); } listenOptions.UseHttps(cert); } } else { listenOptions.Protocols = configuration.HttpVersion == new Version(2, 0) ? HttpProtocols.Http2 : HttpProtocols.Http1; } }); }); }; // Output only warnings and errors from Kestrel host = host .ConfigureLogging(log => log.AddFilter("Microsoft.AspNetCore", level => configuration.LogAspNet ? level >= LogLevel.Warning : false)) // Set up how each request should be handled by the server. .Configure(app => { app.UseRouting(); app.UseEndpoints(MapRoutes); }); // Handle command-line arguments. _eventListener = configuration.LogPath == null ? null : new HttpEventListener(configuration.LogPath != "console" ? new StreamWriter(configuration.LogPath) { AutoFlush = true } : null); SetUpJustInTimeLogging(); _webHost = host.Build(); _webHost.Start(); }
public void Start() { _internalWebHost.Start(); }
public BaseIntegrationTest() { host = Program.CreateWebHostBuilder(null).UseUrls($"http://*:{hostPort}").Build(); host.Start(); }
private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseUrls(url) .ConfigureServices(services => { services.AddLogging(); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(new List <ApiResource> { new ApiResource { Name = apiName, Description = "My API", Enabled = true, DisplayName = "test", Scopes = new List <Scope>() { new Scope("api"), new Scope("openid"), new Scope("offline_access") }, ApiSecrets = new List <Secret>() { new Secret { Value = "secret".Sha256() } }, UserClaims = new List <string>() { "CustomerId", "LocationId", "UserType", "UserId" } } }) .AddInMemoryClients(new List <Client> { new Client { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }, AllowedScopes = new List <string> { apiName, "openid", "offline_access" }, AccessTokenType = tokenType, Enabled = true, RequireClientSecret = false } }) .AddTestUsers(new List <TestUser> { user }); }) .Configure(app => { app.UseIdentityServer(); }) .Build(); _identityServerBuilder.Start(); _steps.VerifyIdentiryServerStarted(url); }
public void FaultOnDiffString() { IWebHost host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); System.ServiceModel.BasicHttpBinding httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestFaultContractName>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/TestFaultContractNameService.svc"))); ClientContract.ITestFaultContractName channel = factory.CreateChannel(); //test variations count int count = 21; string faultToThrow = "Test fault thrown from a service"; //variation method1 try { string s = channel.Method1(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method2 try { string s = channel.Method2(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method3 try { string s = channel.Method3(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method4 try { string s = channel.Method4(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method5 try { string s = channel.Method5(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method6 try { string s = channel.Method6(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method7 try { string s = channel.Method7(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method8 try { string s = channel.Method8(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method9 try { string s = channel.Method9(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method10 try { string s = channel.Method10(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method11 try { string s = channel.Method11(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method12 try { string s = channel.Method12(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method13 try { string s = channel.Method13(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method14 try { string s = channel.Method14(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method15 try { string s = channel.Method15(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method16 try { string s = channel.Method16(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method17 try { string s = channel.Method17(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method18 try { string s = channel.Method18(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method19 try { string s = channel.Method19(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method20 try { string s = channel.Method20(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method21 try { string s = channel.Method21(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } Assert.Equal(0, count); } }
/// <inheritdoc /> public void Start() => _host.Start();
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; } }
private void GivenThereIsAFakeEurekaServiceDiscoveryProvider(string url, string serviceName) { _fakeConsulBuilder = new WebHostBuilder() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseUrls(url) .Configure(app => { app.Run(async context => { if (context.Request.Path.Value == "/eureka/apps/") { var apps = new List <Application>(); foreach (var serviceInstance in _eurekaInstances) { var a = new Application { name = serviceName, instance = new List <Instance> { new Instance { instanceId = $"{serviceInstance.Host}:{serviceInstance}", hostName = serviceInstance.Host, app = serviceName, ipAddr = "127.0.0.1", status = "UP", overriddenstatus = "UNKNOWN", port = new Port { value = serviceInstance.Port, enabled = "true" }, securePort = new SecurePort { value = serviceInstance.Port, enabled = "true" }, countryId = 1, dataCenterInfo = new DataCenterInfo { value = "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo", name = "MyOwn" }, leaseInfo = new LeaseInfo { renewalIntervalInSecs = 30, durationInSecs = 90, registrationTimestamp = 1457714988223, lastRenewalTimestamp = 1457716158319, evictionTimestamp = 0, serviceUpTimestamp = 1457714988223 }, metadata = new Metadata { value = "java.util.Collections$EmptyMap" }, homePageUrl = $"{serviceInstance.Host}:{serviceInstance.Port}", statusPageUrl = $"{serviceInstance.Host}:{serviceInstance.Port}", healthCheckUrl = $"{serviceInstance.Host}:{serviceInstance.Port}", vipAddress = serviceName, isCoordinatingDiscoveryServer = "false", lastUpdatedTimestamp = "1457714988223", lastDirtyTimestamp = "1457714988172", actionType = "ADDED" } } }; apps.Add(a); } var applications = new EurekaApplications { applications = new Applications { application = apps, apps__hashcode = "UP_1_", versions__delta = "1" } }; await context.Response.WriteJsonAsync(applications); } }); }) .Build(); _fakeConsulBuilder.Start(); }
/// <inheritdoc/> protected async override Task <int> OnRunAsync() { // Read the configuration environment variable or file to initialize // endpoint response text. responseText = "UNCONFIGURED"; var resultVar = GetEnvironmentVariable("WEB_RESULT"); if (resultVar != null) { responseText = resultVar; } else { var configPath = GetConfigFilePath("/etc/complex/response"); if (configPath != null && File.Exists(configPath)) { responseText = File.ReadAllText(configPath); } } // Start the web service. var endpoint = Description.Endpoints.Default; webHost = new WebHostBuilder() .UseStartup <ComplexServiceStartup>() .UseKestrel(options => options.Listen(IPAddress.Any, endpoint.Port)) .ConfigureServices(services => services.AddSingleton(typeof(ComplexService), this)) .Build(); webHost.Start(); // Start the worker thread. thread = new Thread(new ThreadStart(ThreadFunc)); thread.Start(); // Start the service task task = Task.Run(async() => await TaskFunc()); // Indicate that the service is ready for business. SetRunning(); // Wait for the process terminator to signal that the service is stopping. await Terminator.StopEvent.WaitAsync(); // Wait for the service thread and task to exit. thread.Join(); await task; // Return the exit code specified by the configuration. return(await Task.FromResult(0)); }
public void ServiceOp_ThrowsFaultException(string serviceOpType) { IWebHost host = ServiceHelper.CreateWebHostBuilder <AggregateExceptionStartup>(_output).Build(); using (host) { host.Start(); ClientContract.IAggregateExceptionService sampleServiceClient = ClientHelper.GetProxy <ClientContract.IAggregateExceptionService>(); try { switch (serviceOpType) { case "SimpleOperationThrowingFault": sampleServiceClient.SimpleOperationThrowingFault(); break; case "SimpleOperationThrowingFault_WithTask": { Task task = sampleServiceClient.SimpleOperationThrowingFaultAsync(); task.Wait(); break; } case "ServiceOpWithMultipleTasks": sampleServiceClient.ServiceOpWithMultipleTasks(); break; case "ServiceOpWithMultipleTasks_WithTask": { Task task2 = sampleServiceClient.ServiceOpWithMultipleTasksAsync(); task2.Wait(); break; } case "ServiceOpWithChainedTasks_ThrowFaultExceptionInOneTask": sampleServiceClient.ServiceOpWithChainedTasks_ThrowFaultExceptionInOneTask(); break; case "ServiceOpWithChainedTasks_ThrowFaultExceptionInOneTask_WithTask": { Task task3 = sampleServiceClient.ServiceOpWithChainedTasks_ThrowFaultExceptionInOneTaskAsync(); task3.Wait(); break; } } throw new Exception("Expected fault but got result successfully."); } catch (System.ServiceModel.FaultException <ClientContract.SampleServiceFault> faultEx) { VerifyFaultThrown(faultEx); } catch (AggregateException ex) { System.ServiceModel.FaultException <ClientContract.SampleServiceFault> faultEx2 = ex.InnerExceptions[0] as System.ServiceModel.FaultException <ClientContract.SampleServiceFault>; VerifyFaultThrown(faultEx2); } catch (Exception ex2) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(); stringBuilder.AppendLine("Expected a fault exception of type 'SampleServiceFault' but got the following."); stringBuilder.Append("Message: " + ex2.GetType().ToString()); stringBuilder.AppendLine(ex2.Message); stringBuilder.Append("StackTrace: "); stringBuilder.AppendLine(ex2.StackTrace); throw new Exception(stringBuilder.ToString()); } } }
public override void StartPlugin() { // важно запускать Start вместо Run, чтобы оно не лезло напрямую в консоль host.Start(); }
internal async Task Run(string configFileName, bool clearDBs, string fileStartComplete) { theSyncContext = SynchronizationContext.Current; reqHandler.Start(); foreach (ReqDef entry in RequestDefinitions.Definitions) { mapRequests[entry.HttpPath] = entry; } Configuration config = Util.Xml.FromXmlFile <Configuration>(configFileName); userManagement = config.UserManagement; locations = config.Locations; listenPort = config.ClientListenPort; string host = config.ClientListenHost; var builder = new WebHostBuilder(); builder.UseKestrel((KestrelServerOptions options) => { if (host.Equals("localhost", StringComparison.InvariantCultureIgnoreCase)) { options.ListenLocalhost(listenPort); } else { options.Listen(IPAddress.Parse(host), listenPort); } }); builder.UseStartup <MediatorCore>(); IWebHost webHost = builder.Build(); webHost.Start(); Module[] enabledModules = config.Modules.Where(a => a.Enabled).ToArray(); this.modules = enabledModules.Select(m => new ModuleState(m, this)).ToArray(); foreach (ModuleState module in modules) { module.CreateInstance(); } history.TimestampCheckWarning = config.TimestampCheckWarning; await history.Start(enabledModules, GetVariableDescription, reqHandler.OnVariableHistoryChanged, clearDBs); try { // Some modules (e.g. Alarms&Events) need to be initialized before the others var sequentialModules = modules.Where(m => !m.Config.ConcurrentInit).ToArray(); foreach (var m in sequentialModules) { await InitModule(m); } var concurrentModules = modules.Where(m => m.Config.ConcurrentInit).ToArray(); Task[] initTasks = concurrentModules.Select(InitModule).ToArray(); await Task.WhenAll(initTasks); } catch (Exception exp) { foreach (var module in modules) { if (module.State == State.InitError) { string msg = "Init of module " + module.Config.Name + " failed: " + module.LastError; Log_Event(Severity.Alarm, "InitFailed", msg, module.ID); } } await Shutdown(); throw new Exception("Init of modules failed", exp); } Log_Event(Severity.Info, "SysStartup", "System started successfully"); logger.Info("All modules initialized successfully."); foreach (ModuleState module in modules) { StartRunningModule(module); } if (!string.IsNullOrEmpty(fileStartComplete)) { try { File.WriteAllText(fileStartComplete, DateTime.Now.ToString()); } catch (Exception) { } } while (!requestShutdown) { await Task.Delay(100); } shutdown = true; reqHandler.setTerminating(); await Shutdown(); if (!string.IsNullOrEmpty(fileStartComplete)) { try { File.Delete(fileStartComplete); } catch (Exception) { } } Task ignored = webHost.StopAsync(); // Don't wait for StopAsync to finish (takes a few seconds) }
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() }); } }
public void Start() { webHost.Start(); }
public StressServer(Configuration configuration) { WorkaroundAssemblyResolutionIssues(); ServerUri = configuration.ServerUri; (string scheme, string hostname, int port) = ParseServerUri(configuration.ServerUri); IWebHostBuilder host = WebHost.CreateDefaultBuilder(); if (configuration.UseHttpSys && OperatingSystem.IsWindows()) { // Use http.sys. This requires additional manual configuration ahead of time; // see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/httpsys?view=aspnetcore-2.2#configure-windows-server. // In particular, you need to: // 1. Create a self-signed cert and install it into your local personal store, e.g. New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" // 2. Pre-register the URL prefix, e.g. netsh http add urlacl url=https://localhost:5001/ user=Users // 3. Register the cert, e.g. netsh http add sslcert ipport=[::1]:5001 certhash=THUMBPRINTFROMABOVE appid="{some-guid}" host = host.UseHttpSys(hso => { hso.UrlPrefixes.Add(ServerUri); hso.Authentication.Schemes = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None; hso.Authentication.AllowAnonymous = true; hso.MaxConnections = null; hso.MaxRequestBodySize = null; }); } else { // Use Kestrel, and configure it for HTTPS with a self-signed test certificate. host = host.UseKestrel(ko => { // conservative estimation based on https://github.com/dotnet/aspnetcore/blob/caa910ceeba5f2b2c02c47a23ead0ca31caea6f0/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.cs#L204 ko.Limits.MaxRequestLineSize = Math.Max(ko.Limits.MaxRequestLineSize, configuration.MaxRequestUriSize + 100); ko.Limits.MaxRequestHeaderCount = Math.Max(ko.Limits.MaxRequestHeaderCount, configuration.MaxRequestHeaderCount); ko.Limits.MaxRequestHeadersTotalSize = Math.Max(ko.Limits.MaxRequestHeadersTotalSize, configuration.MaxRequestHeaderTotalSize); ko.Limits.Http2.MaxStreamsPerConnection = configuration.ServerMaxConcurrentStreams ?? ko.Limits.Http2.MaxStreamsPerConnection; ko.Limits.Http2.MaxFrameSize = configuration.ServerMaxFrameSize ?? ko.Limits.Http2.MaxFrameSize; ko.Limits.Http2.InitialConnectionWindowSize = configuration.ServerInitialConnectionWindowSize ?? ko.Limits.Http2.InitialConnectionWindowSize; ko.Limits.Http2.MaxRequestHeaderFieldSize = configuration.ServerMaxRequestHeaderFieldSize ?? ko.Limits.Http2.MaxRequestHeaderFieldSize; switch (hostname) { case "+": case "*": ko.ListenAnyIP(port, ConfigureListenOptions); break; default: IPAddress iPAddress = Dns.GetHostAddresses(hostname).First(); ko.Listen(iPAddress, port, ConfigureListenOptions); break; } void ConfigureListenOptions(ListenOptions listenOptions) { if (scheme == "https") { // Create self-signed cert for server. using (RSA rsa = RSA.Create()) { var certReq = new CertificateRequest("CN=contoso.com", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1)); if (OperatingSystem.IsWindows()) { cert = new X509Certificate2(cert.Export(X509ContentType.Pfx)); } listenOptions.UseHttps(cert); } if (configuration.HttpVersion == HttpVersion.Version30) { listenOptions.Protocols = HttpProtocols.Http3; } } else { listenOptions.Protocols = configuration.HttpVersion == HttpVersion.Version20 ? HttpProtocols.Http2 : HttpProtocols.Http1; } } }); }; LoggerConfiguration loggerConfiguration = new LoggerConfiguration(); if (configuration.Trace) { if (!Directory.Exists(LogHttpEventListener.LogDirectory)) { Directory.CreateDirectory(LogHttpEventListener.LogDirectory); } // Clear existing logs first. foreach (var filename in Directory.GetFiles(LogHttpEventListener.LogDirectory, "server*.log")) { try { File.Delete(filename); } catch { } } loggerConfiguration = loggerConfiguration // Output diagnostics to the file .WriteTo.File(Path.Combine(LogHttpEventListener.LogDirectory, "server.log"), fileSizeLimitBytes: 100 << 20, rollOnFileSizeLimit: true) .MinimumLevel.Debug(); } if (configuration.LogAspNet) { loggerConfiguration = loggerConfiguration // Output only warnings and errors .WriteTo.Console(Serilog.Events.LogEventLevel.Warning); } Log.Logger = loggerConfiguration.CreateLogger(); if (configuration.Trace) { _listener = new LogQuicEventListener(Log.Logger); } host = host .UseSerilog() // Set up how each request should be handled by the server. .Configure(app => { app.UseRouting(); app.UseEndpoints(MapRoutes); }); _webHost = host.Build(); _webHost.Start(); }
protected override void OnStart() { // Update some basic settings _appSettings.AddOrUpdate(CommonAppSettingsKeys.ClientIdSetting.Name, Guid.NewGuid().ToString()); _appSettings.AddOrUpdate(CommonAppSettingsKeys.ClientNameSetting.Name, "RESTFul Service"); // Start dependent components // Get a TCP port that is available var portReservation = _localTcpPortManager.GetNextAvailablePort(); var hostPort = portReservation.Port; var sslPort = portReservation.Port + 1; // Update the local setting to begin hosting with the port _appSettings.AddOrUpdate(CommonAppSettingsKeys.HttpHostPortSetting.Name, portReservation.Port.ToString()); try { // Expose API endpoint if (_webHost.IsNotNull()) { _webHost.Dispose(); } var builder = WebHost.CreateDefaultBuilder(); // _hostUri = new UriBuilder( "https", "localhost", sslPort ).Uri; builder.UseKestrel(options => { options.Limits.MaxConcurrentConnections = 100; options.Limits.MaxConcurrentUpgradedConnections = 100; options.Limits.MaxRequestBodySize = 10 * 1024; options.Limits.MinRequestBodyDataRate = new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10)); options.Limits.MinResponseDataRate = new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10)); options.Listen(IPAddress.Loopback, hostPort); options.Listen(IPAddress.Loopback, sslPort, listenOptions => { listenOptions.UseHttps(StoreName.My, "localhost"); }); } ); builder.ConfigureServices(ConfigureServices); builder.Configure(Configure); _webHost = builder.Build(); try { _webHost.Start(); } catch (Exception ex) { _log.Error(ex, ex.Message); throw; } } finally { portReservation.Dispose(); } _log.InfoFormat( "Listening on: http://localhost:{0}/ and https://localhost:{1}/", hostPort, sslPort ); }
public override async Task Init(ModuleInitInfo info, VariableValue[] restoreVariableValues, Notifier notifier, ModuleThread moduleThread) { theSyncContext = SynchronizationContext.Current; await base.Init(info, restoreVariableValues, notifier, moduleThread); var config = info.GetConfigReader(); clientPort = info.LoginPort; string baseDir = config.GetString("base-dir"); string host = config.GetString("listen-host"); int port = config.GetInt("listen-port"); string strViewAssemblies = config.GetString("view-assemblies"); const string releaseDebugPlaceHolder = "{RELEASE_OR_DEBUG}"; if (strViewAssemblies.Contains(releaseDebugPlaceHolder)) { #if DEBUG strViewAssemblies = strViewAssemblies.Replace(releaseDebugPlaceHolder, "Debug"); #else strViewAssemblies = strViewAssemblies.Replace(releaseDebugPlaceHolder, "Release"); #endif } string[] viewAssemblies = strViewAssemblies.Split(";", StringSplitOptions.RemoveEmptyEntries); absolutBaseDir = Path.GetFullPath(baseDir); if (!Directory.Exists(absolutBaseDir)) { throw new Exception($"base-dir does not exist: {absolutBaseDir}"); } string[] absoluteViewAssemblies = viewAssemblies.Select(d => Path.GetFullPath(d)).ToArray(); foreach (string dir in absoluteViewAssemblies) { if (!File.Exists(dir)) { throw new Exception($"view-assembly does not exist: {dir}"); } } viewTypes = ReadAvailableViewTypes(absolutBaseDir, absoluteViewAssemblies); uiModel = MakeUiModel(model, viewTypes); var builder = new WebHostBuilder(); builder.UseKestrel((KestrelServerOptions options) => { if (host.Equals("localhost", StringComparison.InvariantCultureIgnoreCase)) { options.ListenLocalhost(port); } else { options.Listen(IPAddress.Parse(host), port); } }); builder.UseWebRoot(absolutBaseDir); builder.UseStartup <Module>(); webHost = builder.Build(); webHost.Start(); }
public void Run() { Utils.Init(); var rpcClasses = from a in AppDomain.CurrentDomain.GetAssemblies().AsParallel() where !a.IsDynamic from t in a.GetTypes() from i in t.GetInterfaces() let attributes = i.GetCustomAttributes(typeof(HTTPRPCInterfaceAttribute), true) where attributes != null && attributes.Length > 0 select t; foreach (var rpcClass in rpcClasses) { bool addInterfaceNameToPath = false; var basePath = "api"; HTTPRPCInterfaceAttribute?aServer = null; foreach (var i in rpcClass.GetInterfaces()) { aServer = i.GetCustomAttribute <HTTPRPCInterfaceAttribute>(); if (aServer != null) { break; } } if (aServer != null) { addInterfaceNameToPath = aServer.AddInterfaceNameToPath; basePath = aServer.BasePath; } var obj = Activator.CreateInstance(rpcClass); if (obj != null) { var t = obj.GetType().GetInterfaces()[0]; MethodInfo[] procs = t.GetMethods(); foreach (var m in procs) { var aHTTP = m.GetCustomAttribute <HTTPHandlerAttribute>(); var lHttpMethod = HttpMethods.Post; var lCacheMilliseconds = 0; string lPath = ""; if (aHTTP != null) { lHttpMethod = aHTTP.Method; lCacheMilliseconds = aHTTP.CacheMilliseconds; lPath += "/" + aHTTP.Path; } var mName = m.Name.Trim().ToUpperInvariant(); var path = mName; if (addInterfaceNameToPath) { string iName = Utils.StripInterfaceName(t.Name).Trim().ToUpperInvariant(); if (iName != mName) { path = iName + "/" + path; } } path = "/" + path; if (!string.IsNullOrEmpty(lPath.Trim().Trim('/'))) { path = "/" + lPath.Trim('/') + "/" + path.Trim('/'); } if (basePath != null && !string.IsNullOrEmpty(basePath.Trim().Trim('/'))) { path = "/" + basePath.Trim('/') + path; } handlers.Add(new HttpHandler() { path = path.ToUpperInvariant(), httpMethod = lHttpMethod, CacheMilliseconds = lCacheMilliseconds, obj = obj, m = m, MethodRequestType = Utils.GetMethodRequestType(t, m.Name), MethodResponseType = (m.ReturnType == typeof(RPCBinaryResult)) ? null : Utils.GetMethodResponseHolderType(t.Name + "/" + m.Name, m.ReturnType), BinaryResult = (m.ReturnType == typeof(RPCBinaryResult)) }); } } } // Task.Delay(10000).ContinueWith(o=>{IsStarted = true;}); // Wait 10 sec t be sure that host is started and then change IsStarted status host.Start(); IsStarted = true; }
/// <summary> /// Start /// </summary> public void Start() { Stop(); _host = WebHost.CreateDefaultBuilder() .UseKestrel(options => options.Listen(EndPoint.Address, EndPoint.Port, listenOptions => { if (string.IsNullOrEmpty(HTTPSCertFile)) { return; } listenOptions.UseHttps(HTTPSCertFile, HTTPSCertificatePassword, httpsConnectionAdapterOptions => { //if (trustedAuthorities is null || trustedAuthorities.Length == 0) // return; //httpsConnectionAdapterOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate; //httpsConnectionAdapterOptions.ClientCertificateValidation = (cert, chain, err) => //{ // if (err != SslPolicyErrors.None) // return false; // X509Certificate2 authority = chain.ChainElements[chain.ChainElements.Count - 1].Certificate; // return trustedAuthorities.Contains(authority.Thumbprint); //}; }); })) .Configure(app => { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "TuringMachine API V1"); }); app.UseResponseCompression(); app.UseRouting(); app.UseEndpoints(endpoints => endpoints.MapControllers()); }) .ConfigureServices(services => { services.AddSingleton(this); services.AddSingleton <ConfigsController, ConfigsController>(); services.AddSingleton <ConnectionsController, ConnectionsController>(); services.AddSingleton <InputsController, InputsController>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo() { Title = "TuringMachine API", Version = "v1" }); }); services .AddMvcCore() .AddApiExplorer() .AddControllersAsServices() .AddNewtonsoftJson(c => { SerializationHelper.Configure(c.SerializerSettings); }); services.AddLogging(builder => { if (Debugger.IsAttached) { builder .ClearProviders() .AddConsole(); } else { builder .ClearProviders() .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) .AddFilter("NToastNotify", LogLevel.Warning) .AddEventLog(); } }); services.AddResponseCompression(options => { // options.EnableForHttps = false; options.Providers.Add <GzipCompressionProvider>(); options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "application/json" }); }); services.Configure <GzipCompressionProviderOptions>(options => { options.Level = CompressionLevel.Fastest; }); }) .Build(); _host.Start(); }
private static void StartApi() { var address = clusterConfig.Api?.ListenAddress != null ? (clusterConfig.Api.ListenAddress != "*" ? IPAddress.Parse(clusterConfig.Api.ListenAddress) : IPAddress.Any) : IPAddress.Parse("127.0.0.1"); var port = clusterConfig.Api?.Port ?? 4000; var enableApiRateLimiting = !(clusterConfig.Api?.RateLimiting?.Disabled == true); webHost = WebHost.CreateDefaultBuilder() .ConfigureLogging(logging => { // NLog logging.ClearProviders(); logging.AddNLog(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .ConfigureServices(services => { // rate limiting if (enableApiRateLimiting) { services.Configure <IpRateLimitOptions>(ConfigureIpRateLimitOptions); services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>(); } // Controllers services.AddSingleton <PoolApiController, PoolApiController>(); services.AddSingleton <AdminApiController, AdminApiController>(); // MVC services.AddSingleton((IComponentContext)container); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddControllersAsServices() .AddNewtonsoftJson(options => { options.SerializerSettings.Formatting = Formatting.Indented; }); services.AddMvc(option => option.EnableEndpointRouting = false); // Gzip Compression services.AddResponseCompression(); // Cors services.AddCors(); // WebSockets services.AddWebSocketManager(); }) .Configure(app => { if (enableApiRateLimiting) { app.UseIpRateLimiting(); } app.UseMiddleware <ApiExceptionHandlingMiddleware>(); UseIpWhiteList(app, true, new[] { "/api/admin" }, clusterConfig.Api?.AdminIpWhitelist); UseIpWhiteList(app, true, new[] { "/metrics" }, clusterConfig.Api?.MetricsIpWhitelist); app.UseResponseCompression(); app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("x-total-count")); app.UseWebSockets(); app.MapWebSocketManager("/notifications", app.ApplicationServices.GetService <WebSocketNotificationsRelay>()); app.UseMetricServer(); app.UseMvc(); }) .UseKestrel(options => { options.Listen(address, clusterConfig.Api.Port, listenOptions => { if (clusterConfig.Api.SSLConfig?.Enabled == true) { listenOptions.UseHttps(clusterConfig.Api.SSLConfig.SSLPath, clusterConfig.Api.SSLConfig.SSLPassword); } }); }) .Build(); webHost.Start(); logger.Info(() => $"API Online @ {address}:{port}{(!enableApiRateLimiting ? " [rate-limiting disabled]" : string.Empty)}"); logger.Info(() => $"Prometheus Metrics Online @ {address}:{port}/metrics"); logger.Info(() => $"WebSocket notifications streaming @ {address}:{port}/notifications"); }
public void Start() { if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } string chain = ChainType.Regtest.ToNetwork().Name; string chainDirectory = Path.Combine(_Directory, chain); if (!Directory.Exists(chainDirectory)) { Directory.CreateDirectory(chainDirectory); } StringBuilder config = new StringBuilder(); config.AppendLine($"{chain.ToLowerInvariant()}=1"); config.AppendLine($"port={Port}"); config.AppendLine($"chains=btc,ltc"); config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}"); config.AppendLine($"btc.explorer.cookiefile=0"); config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}"); config.AppendLine($"ltc.explorer.cookiefile=0"); config.AppendLine($"btc.lightning={IntegratedLightning.AbsoluteUri}"); if (Postgres != null) { config.AppendLine($"postgres=" + Postgres); } var confPath = Path.Combine(chainDirectory, "settings.config"); File.WriteAllText(confPath, config.ToString()); ServerUri = new Uri("http://" + HostName + ":" + Port + "/"); Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); var conf = new DefaultConfiguration() { Logger = Logs.LogProvider.CreateLogger("Console") }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath }); _Host = new WebHostBuilder() .UseConfiguration(conf) .ConfigureServices(s => { var mockRates = new MockRateProviderFactory(); var btc = new MockRateProvider("BTC", new Rate("USD", 5000m)); var ltc = new MockRateProvider("LTC", new Rate("USD", 500m)); mockRates.AddMock(btc); mockRates.AddMock(ltc); s.AddSingleton <IRateProviderFactory>(mockRates); s.AddLogging(l => { l.SetMinimumLevel(LogLevel.Information) .AddFilter("Microsoft", LogLevel.Error) .AddFilter("Hangfire", LogLevel.Error) .AddProvider(Logs.LogProvider); }); }) .UseKestrel() .UseStartup <Startup>() .Build(); _Host.Start(); InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository)); ((LightningLikePaymentHandler)_Host.Services.GetService(typeof(IPaymentMethodHandler <LightningSupportedPaymentMethod>))).SkipP2PTest = !InContainer; }
public void Start() { if (InDocker) { FallbackToRandomPort = false; if (Port == 0) { Port = 8080; } BindToAny = true; } _webHost = BuildWebHost(Port); if (Port != 0 && FallbackToRandomPort) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IAsyncResult result = socket.BeginConnect(IPAddress.Loopback, Port, null, null); result.AsyncWaitHandle.WaitOne(100, true); if (socket.Connected) { socket.EndConnect(result); socket.Close(); _webHost = BuildWebHost(0); } else { socket.Close(); } _webHost.Start(); } catch (Exception) { try { _webHost.Dispose(); _webHost = BuildWebHost(0); _webHost.Start(); } catch (Exception) { for (int i = 1; i < 20; i++) { try { if (_webHost != null) { _webHost.Dispose(); _webHost = null; } _webHost = BuildWebHost(Port + i); _webHost.Start(); break; } catch (Exception) { _webHost.Dispose(); _webHost = null; } } } } } else { _webHost.Start(); } if (_webHost == null) { throw new Exception("Cannot find empty port to be allowed to listen on. Started on " + Port); } Port = new Uri(_webHost.ServerFeatures.Get <IServerAddressesFeature>().Addresses.First()).Port; }
public static IWebHost Initialize(IEnumerable <ServiceDescriptor> services, FullNode fullNode, ApiSettings apiSettings, ICertificateStore store, IWebHostBuilder webHostBuilder) { Guard.NotNull(fullNode, nameof(fullNode)); Guard.NotNull(webHostBuilder, nameof(webHostBuilder)); Uri apiUri = apiSettings.ApiUri; X509Certificate2 certificate = apiSettings.UseHttps ? GetHttpsCertificate(apiSettings.HttpsCertificateFilePath, store) : null; webHostBuilder .UseKestrel(options => { if (!apiSettings.UseHttps) { return; } Action <ListenOptions> configureListener = listenOptions => { listenOptions.UseHttps(certificate); }; var ipAddresses = Dns.GetHostAddresses(apiSettings.ApiUri.DnsSafeHost); foreach (var ipAddress in ipAddresses) { options.Listen(ipAddress, apiSettings.ApiPort, configureListener); } }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseUrls(apiUri.ToString()) .ConfigureServices(collection => { if (services == null) { return; } // copies all the services defined for the full node to the Api. // also copies over singleton instances already defined foreach (ServiceDescriptor service in services) { // open types can't be singletons if (service.ServiceType.IsGenericType || service.Lifetime == ServiceLifetime.Scoped) { collection.Add(service); continue; } object obj = fullNode.Services.ServiceProvider.GetService(service.ServiceType); if (obj != null && service.Lifetime == ServiceLifetime.Singleton && service.ImplementationInstance == null) { collection.AddSingleton(service.ServiceType, obj); } else { collection.Add(service); } } }) .UseStartup <Startup>(); IWebHost host = webHostBuilder.Build(); host.Start(); return(host); }
public void Start() { if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } string chain = NBXplorerDefaultSettings.GetFolderName(NetworkType.Regtest); string chainDirectory = Path.Combine(_Directory, chain); if (!Directory.Exists(chainDirectory)) { Directory.CreateDirectory(chainDirectory); } StringBuilder config = new StringBuilder(); config.AppendLine($"{chain.ToLowerInvariant()}=1"); if (InContainer) { config.AppendLine($"bind=0.0.0.0"); } config.AppendLine($"port={Port}"); config.AppendLine($"chains=btc,ltc"); config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}"); config.AppendLine($"btc.explorer.cookiefile=0"); config.AppendLine("allow-admin-registration=1"); config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}"); config.AppendLine($"ltc.explorer.cookiefile=0"); config.AppendLine($"btc.lightning={IntegratedLightning.AbsoluteUri}"); if (TestDatabase == TestDatabases.MySQL && !String.IsNullOrEmpty(MySQL)) { config.AppendLine($"mysql=" + MySQL); } else if (!String.IsNullOrEmpty(Postgres)) { config.AppendLine($"postgres=" + Postgres); } var confPath = Path.Combine(chainDirectory, "settings.config"); File.WriteAllText(confPath, config.ToString()); ServerUri = new Uri("http://" + HostName + ":" + Port + "/"); HttpClient = new HttpClient(); HttpClient.BaseAddress = ServerUri; Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); var conf = new DefaultConfiguration() { Logger = Logs.LogProvider.CreateLogger("Console") }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath, "--disable-registration", "false" }); _Host = new WebHostBuilder() .UseConfiguration(conf) .UseContentRoot(FindBTCPayServerDirectory()) .ConfigureServices(s => { s.AddLogging(l => { l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical); l.SetMinimumLevel(LogLevel.Information) .AddFilter("Microsoft", LogLevel.Error) .AddFilter("Hangfire", LogLevel.Error) .AddProvider(Logs.LogProvider); }); }) .UseKestrel() .UseStartup <Startup>() .Build(); _Host.Start(); var urls = _Host.ServerFeatures.Get <IServerAddressesFeature>().Addresses; foreach (var url in urls) { Logs.Tester.LogInformation("Listening on " + url); } Logs.Tester.LogInformation("Server URI " + ServerUri); InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository)); StoreRepository = (StoreRepository)_Host.Services.GetService(typeof(StoreRepository)); Networks = (BTCPayNetworkProvider)_Host.Services.GetService(typeof(BTCPayNetworkProvider)); if (MockRates) { var rateProvider = (RateProviderFactory)_Host.Services.GetService(typeof(RateProviderFactory)); rateProvider.Providers.Clear(); var coinAverageMock = new MockRateProvider(); coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate() { Exchange = "coinaverage", CurrencyPair = CurrencyPair.Parse("BTC_USD"), BidAsk = new BidAsk(5000m) }); coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate() { Exchange = "coinaverage", CurrencyPair = CurrencyPair.Parse("BTC_CAD"), BidAsk = new BidAsk(4500m) }); coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate() { Exchange = "coinaverage", CurrencyPair = CurrencyPair.Parse("LTC_BTC"), BidAsk = new BidAsk(0.001m) }); coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate() { Exchange = "coinaverage", CurrencyPair = CurrencyPair.Parse("LTC_USD"), BidAsk = new BidAsk(500m) }); rateProvider.Providers.Add("coinaverage", coinAverageMock); var bitflyerMock = new MockRateProvider(); bitflyerMock.ExchangeRates.Add(new Rating.ExchangeRate() { Exchange = "bitflyer", CurrencyPair = CurrencyPair.Parse("BTC_JPY"), BidAsk = new BidAsk(700000m) }); rateProvider.Providers.Add("bitflyer", bitflyerMock); var quadrigacx = new MockRateProvider(); quadrigacx.ExchangeRates.Add(new Rating.ExchangeRate() { Exchange = "quadrigacx", CurrencyPair = CurrencyPair.Parse("BTC_CAD"), BidAsk = new BidAsk(6000m) }); rateProvider.Providers.Add("quadrigacx", quadrigacx); var bittrex = new MockRateProvider(); bittrex.ExchangeRates.Add(new Rating.ExchangeRate() { Exchange = "bittrex", CurrencyPair = CurrencyPair.Parse("DOGE_BTC"), BidAsk = new BidAsk(0.004m) }); rateProvider.Providers.Add("bittrex", bittrex); } WaitSiteIsOperational().GetAwaiter().GetResult(); }
private void GivenThereIsAnIdentityServerOn(string url, string apiName) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureServices(services => { services.AddLogging(); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(new List <ApiResource> { new ApiResource { Name = apiName, Description = apiName, Enabled = true, DisplayName = apiName, Scopes = new List <Scope>() { new Scope(apiName) } } }) .AddInMemoryClients(new List <Client> { new Client { ClientId = apiName, AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }, AllowedScopes = new List <string> { apiName }, AccessTokenType = AccessTokenType.Jwt, Enabled = true } }) .AddTestUsers(new List <TestUser> { new TestUser { Username = "******", Password = "******", SubjectId = "1231231" } }); }) .Configure(app => { app.UseIdentityServer(); }) .Build(); _identityServerBuilder.Start(); using (var httpClient = new HttpClient()) { var response = httpClient.GetAsync($"{url}/.well-known/openid-configuration").Result; response.EnsureSuccessStatusCode(); } }
public void Start() { _MonitorHubHost.Start(); LoadRegistrations(); CheckHosts(); }
private static void StartApi() { var address = clusterConfig.Api?.ListenAddress != null ? (clusterConfig.Api.ListenAddress != "*" ? IPAddress.Parse(clusterConfig.Api.ListenAddress) : IPAddress.Any) : IPAddress.Parse("127.0.0.1"); var port = clusterConfig.Api?.Port ?? 4000; var enableApiRateLimiting = !(clusterConfig.Api?.RateLimiting?.Disabled == true); webHost = WebHost.CreateDefaultBuilder() .ConfigureLogging(logging => { // NLog logging.ClearProviders(); logging.AddNLog(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .ConfigureServices(services => { // rate limiting if (enableApiRateLimiting) { services.Configure <IpRateLimitOptions>(ConfigureIpRateLimitOptions); services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); } // MVC services.AddSingleton((IComponentContext)container); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <PoolApiController, PoolApiController>(); services.AddSingleton <AdminApiController, AdminApiController>(); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddControllersAsServices(); // Cors services.AddCors(); // WebSockets services.AddWebSocketManager(); }) .Configure(app => { if (enableApiRateLimiting) { app.UseIpRateLimiting(); } app.UseMiddleware <ApiExceptionHandlingMiddleware>(); UseIpWhiteList(app, true, new[] { "/api/admin" }, clusterConfig.Api?.AdminIpWhitelist); UseIpWhiteList(app, true, new[] { "/metrics" }, clusterConfig.Api?.MetricsIpWhitelist); app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()); app.UseWebSockets(); app.MapWebSocketManager("/notifications", app.ApplicationServices.GetService <WebSocketNotificationsRelay>()); app.UseMetricServer(); app.UseMvc(); }) .UseKestrel(options => { options.Listen(address, port); }) .Build(); webHost.Start(); logger.Info(() => $"API Online @ {address}:{port}"); logger.Info(() => $"Prometheus Metrics Online @ {address}:{port}/metrics"); logger.Info(() => $"WebSocket notifications streaming @ {address}:{port}/notifications"); }
/// <summary> /// Starts Asp.Net core host for the specified controller on the specified <c>urls</c>. /// </summary> /// <typeparam name="TController">Type of controller to host.</typeparam> /// <param name="urls">Hosting <c>urls</c>.</param> /// <param name="hostBuilderAction">Performs additional steps to build host.</param> /// <param name="exceptionHandler">Hosting global exception handler.</param> /// <returns>Configured and running asp.net core host.</returns> public static IWebHost HostController <TController>( string urls, Func <IWebHostBuilder, IWebHostBuilder> hostBuilderAction = null, Func <Exception, Task> exceptionHandler = null) { if (urls == null) { throw new ArgumentNullException(nameof(urls)); } IWebHostBuilder builder = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseOnlyController <TController>() .ConfigureServices(services => services.AddMvc()) .Configure( app => { app.UseMvc(); }); if (exceptionHandler != null) { builder.ConfigureServices( services => { services.AddSingleton <IStartupFilter>( new DelegatingStartupFilter( app => { app.UseExceptionHandler( new ExceptionHandlerOptions { ExceptionHandler = async context => { if (context.Response.StatusCode == (int)HttpStatusCode.InternalServerError) { var errorFeature = context .Features .Get <IExceptionHandlerFeature>(); // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (errorFeature != null) { await exceptionHandler(errorFeature.Error); } } } }); })); }); } if (hostBuilderAction != null) { builder = hostBuilderAction(builder); } IWebHost host = builder .UseUrls(urls) .Build(); host.Start(); return(host); }
public StressServer(Uri serverUri, bool httpSys, int maxContentLength, string logPath, bool enableAspNetLogs) { ServerUri = serverUri; IWebHostBuilder host = WebHost.CreateDefaultBuilder(); if (httpSys) { // Use http.sys. This requires additional manual configuration ahead of time; // see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/httpsys?view=aspnetcore-2.2#configure-windows-server. // In particular, you need to: // 1. Create a self-signed cert and install it into your local personal store, e.g. New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" // 2. Pre-register the URL prefix, e.g. netsh http add urlacl url=https://localhost:5001/ user=Users // 3. Register the cert, e.g. netsh http add sslcert ipport=[::1]:5001 certhash=THUMBPRINTFROMABOVE appid="{some-guid}" host = host.UseHttpSys(hso => { MaxRequestLineSize = 8192; hso.UrlPrefixes.Add(ServerUri.ToString()); hso.Authentication.Schemes = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None; hso.Authentication.AllowAnonymous = true; hso.MaxConnections = null; hso.MaxRequestBodySize = null; }); } else { // Use Kestrel, and configure it for HTTPS with a self-signed test certificate. host = host.UseKestrel(ko => { MaxRequestLineSize = ko.Limits.MaxRequestLineSize; ko.ListenLocalhost(serverUri.Port, listenOptions => { // Create self-signed cert for server. using (RSA rsa = RSA.Create()) { var certReq = new CertificateRequest($"CN={ServerUri.Host}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1)); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { cert = new X509Certificate2(cert.Export(X509ContentType.Pfx)); } listenOptions.UseHttps(cert); } }); }); }; // Output only warnings and errors from Kestrel host = host .ConfigureLogging(log => log.AddFilter("Microsoft.AspNetCore", level => enableAspNetLogs ? level >= LogLevel.Warning : false)) // Set up how each request should be handled by the server. .Configure(app => { var head = new[] { "HEAD" }; app.UseRouting(); app.UseEndpoints(e => MapRoutes(e, maxContentLength)); }); // Handle command-line arguments. _eventListener = logPath == null ? null : new HttpEventListener(logPath != "console" ? new StreamWriter(logPath) { AutoFlush = true } : null); SetUpJustInTimeLogging(); _webHost = host.Build(); _webHost.Start(); }
public void SerivceContractName_784749(string method, string clientString) { SerivceContractName._method = method; IWebHost host = ServiceHelper.CreateWebHostBuilder <SerivceContractName>(_output).Build(); using (host) { host.Start(); string result; switch (method) { case "XmlCharacters": { result = Variation_Service_XmlCharacters(clientString); Assert.Equal(clientString, result); } break; case "WhiteSpace": { result = Variation_Service_WhiteSpace(clientString); Assert.Equal(clientString, result); } break; case "XMLEncoded": { result = Variation_Service_XMLEncoded(clientString); Assert.Equal(clientString, result); } break; case "NonAlphaCharacters": { result = Variation_Service_NonAlphaCharacters(clientString); Assert.Equal(clientString, result); } break; case "LocalizedCharacters": { result = Variation_Service_LocalizedCharacters(clientString); Assert.Equal(clientString, result); } break; case "SurrogateCharacters": { result = Variation_Service_SurrogateCharacters(clientString); Assert.Equal(clientString, result); } break; case "XMLReservedCharacters": { result = Variation_Service_XMLReservedCharacters(clientString); Assert.Equal(clientString, result); } break; case "URI": { result = Variation_Service_URI(clientString); Assert.Equal(clientString, result); } break; default: { _output.WriteLine("Unknown ID : " + method); break; } } } }