private static async Task <string> StartWebServer(string contentRoot, Func <WebSocket, Task> onConsoleConnected, CancellationToken token) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(contentRoot) .UseStartup <WasmTestWebServerStartup>() .ConfigureLogging(logging => { logging.AddConsole().AddFilter(null, LogLevel.Warning); }) .ConfigureServices((ctx, services) => { services.AddRouting(); services.Configure <WasmTestWebServerOptions>(ctx.Configuration); services.Configure <WasmTestWebServerOptions>(options => { options.OnConsoleConnected = onConsoleConnected; }); }) .UseUrls("http://127.0.0.1:0") .Build(); await host.StartAsync(token); return(host.ServerFeatures .Get <IServerAddressesFeature>() .Addresses .First()); }
public async Task LoggingConnectionAdapterCanBeAddedBeforeAndAfterHttpsAdapter() { var host = new WebHostBuilder() .UseKestrel(options => { options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => { listenOptions.UseConnectionLogging(); listenOptions.UseHttps(TestResources.TestCertificatePath, "testPassword"); listenOptions.UseConnectionLogging(); }); }) .Configure(app => { app.Run(context => { context.Response.ContentLength = 12; return(context.Response.WriteAsync("Hello World!")); }); }) .Build(); using (host) { await host.StartAsync(); var response = await HttpClientSlim.GetStringAsync($"https://localhost:{host.GetPort()}/", validateCertificate : false) .TimeoutAfter(TimeSpan.FromSeconds(10)); Assert.Equal("Hello World!", response); } }
static void Main(string[] args) { ServicePointManager.DefaultConnectionLimit = 100; IWebHost host = null; var processor = new ConsoleLoggerProcessor(); CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(loggerProvider); var logger = loggerFactory.CreateLogger("Configuration"); try { var conf = new DefaultConfiguration() { Logger = logger }.CreateConfiguration(args); if (conf == null) { return; } host = new WebHostBuilder() .UseKestrel() .UseIISIntegration() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(conf) .ConfigureLogging(l => { l.AddFilter("Microsoft", LogLevel.Error); l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical); l.AddProvider(new CustomConsoleLogProvider(processor)); }) .UseStartup <Startup>() .Build(); host.StartAsync().GetAwaiter().GetResult(); var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses; foreach (var url in urls) { logger.LogInformation("Listening on " + url); } host.WaitForShutdown(); } catch (ConfigException ex) { if (!string.IsNullOrEmpty(ex.Message)) { Logs.Configuration.LogError(ex.Message); } } finally { processor.Dispose(); if (host != null) { host.Dispose(); } loggerProvider.Dispose(); } }
public async Task CanGetVersionViaHttpTransport() { var host = new WebHostBuilder() .ConfigureServices(services => { services.AddSingleton <ILoggerFactory>(LoggerFactory); services.AddHwiServer(); }) .Configure(app => { app.UseHwiServer(); }) .UseKestrel(kestrel => { kestrel.Listen(IPAddress.Loopback, 0); }) .UseStartup <Startup>() .Build(); try { await host.StartAsync(); var address = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses.First(); var version = await new HwiClient(Network.Main) { Transport = new HttpTransport(address) }.GetVersionAsync(); Logger.LogInformation(version.ToString()); } finally { await host.StopAsync(); } }
async Task StartAsync() { WriteLine("Server thread started!"); var currentDir = Directory.GetCurrentDirectory(); WriteLine($"Current dir is: {currentDir}"); var dir = currentDir; var separator = "\\"; while (!dir.EndsWith("test")) { var lastIndex = dir.LastIndexOf(separator); if (lastIndex <= 0) { break; } dir = dir.Substring(0, lastIndex); WriteLine(dir); } var serverDir = dir + separator + "server"; WriteLine($"Using directory: {serverDir}"); var host = new WebHostBuilder() .UseKestrel(option => option.ListenLocalhost(this.Port)) .UseContentRoot(serverDir) .UseStartup <ApiTest.Startup>() .Build(); Command = host.Services.GetService <CommandService>(); await host.StartAsync(); }
public static async Task <IWebHost> CreateServer(int port) { var configBuilder = new ConfigurationBuilder(); configBuilder.AddInMemoryCollection(); var config = configBuilder.Build(); config["server.urls"] = $"http://localhost:{port}"; var host = new WebHostBuilder() .ConfigureLogging((ctx, logging) => logging.AddDebug()) .UseConfiguration(config) .UseKestrel() .UseStartup <Startup>() .Build(); var tcs = new TaskCompletionSource <bool>(); host.Services.GetService <IHostApplicationLifetime>().ApplicationStarted.Register(() => tcs.TrySetResult(true)); await host.StartAsync(); await tcs.Task; return(host); }
static int Main(string[] args) { var startUrl = Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? "http://localhost:5000/"; var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .UseUrls(startUrl) .Build(); host.StartAsync(); var config = new CefConfig(Debug) { Args = args, StartUrl = startUrl, HideConsoleWindow = false, Width = 1200, Height = 1024, // Kiosk = true, // FullScreen = true, }; return(CefPlatformWindows.Start(config)); }
private async Task <FluentProxyServer> CreateServerInternal(IFluentProxySettings settings, string serverKey, CancellationToken cancellationToken) { IWebHost webHost = new WebHostBuilder() .UseKestrel() .UseUrls($"http://localhost:{settings.InternalPort}") .ConfigureServices(services => services.AddSingleton <IFluentProxySettings>(settings)) .UseStartup <FluentProxyStartup>() .Build(); await webHost.StartAsync(cancellationToken); return(new FluentProxyServer(settings, webHost, () => _webHosts.TryRemove(serverKey, out _))); }
public static void UseV8DebugTargetsEndpoint(this IApplicationBuilder applicationBuilder) { // TODO: Support configuring this endpoint to listen on different ports var host = new WebHostBuilder() .UseSetting(nameof(WebHostBuilderIISExtensions.UseIISIntegration), false.ToString()) .UseKestrel() .UseStartup <V8DebugTargetsEndpointStartup>() .UseUrls("http://localhost:9223") .Build(); host.StartAsync(); }
public void Start(CancellationToken cancellationToken = default) { Task.Run(async() => { try { // Ensure server content path exists var contentRoot = "BoltRoot"; var contentPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, contentRoot); if (!Directory.Exists(contentPath)) { Directory.CreateDirectory(contentPath); } var boltLogger = Log.Logger.ForContext <BoltServer>(); var config = new ConfigurationBuilder() .Build(); var host = new WebHostBuilder() .UseKestrel() .CaptureStartupErrors(true) .UseContentRoot(contentPath) .UseSetting(WebHostDefaults.DetailedErrorsKey, true.ToString()) .UseConfiguration(config) .ConfigureServices(s => s.AddSingleton(config)) .UseSerilog(boltLogger, true) .UseContentRoot(contentRoot) .UseStartup <BoltStartup>() .Build(); try { boltLogger.Information("Starting Bolt..."); await host.StartAsync(cancellationToken); } catch (Exception ex) { Log.Error(ex, "Bolt terminated unexpectedly."); } } catch (Exception ex) { Log.Error(ex, "Failed to start Bolt server."); } }, cancellationToken); }
public void Run(CancellationToken cancellationToken) { var config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseUrls("http://localhost:9090") .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup <Startup>() .Build(); host.StartAsync(cancellationToken); // was Run() in earlier .NET Core SDKs? }
public NFigFixture() { var host = new WebHostBuilder().UseStartup <TStartup>().UseServer(new NoOpServer()).Build(); var t = host.StartAsync(); // minimal attempt to make sure host starts successfully for (var i = 0; i < 5; i++) { Thread.Sleep(100); if (t.IsFaulted) { // force exception to be thrown t.Wait(); } } Host = host; }
private static async Task <string> StartWebServer(string contentRoot, CancellationToken token) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(contentRoot) .UseStartup <WasmTestWebServerStartup>() .ConfigureLogging(logging => { logging.AddConsole().AddFilter(null, LogLevel.Warning); }) .UseUrls("http://127.0.0.1:0") .Build(); await host.StartAsync(token); return(host.ServerFeatures .Get <IServerAddressesFeature>() .Addresses .First()); }
private static async Task <IWebHost> RegisterHttpRemoting() { var certificate = new X509Certificate2(CertificateName, Password); var host = new WebHostBuilder() .UseKestrel(options => { options.Listen(IPAddress.Loopback, HttpPort); options.Listen(IPAddress.Loopback, HttpsPort, listenOptions => { listenOptions.UseHttps(certificate); }); }) .UseStartup <Startup>() .UseContentRoot(AppContext.BaseDirectory) .Build(); await host.StartAsync(); return(host); }
public async Task MapEndPointWithWebSocketSubProtocolSetsProtocol() { var host = new WebHostBuilder() .UseUrls("http://127.0.0.1:0") .UseKestrel() .ConfigureServices(services => { services.AddSockets(); services.AddEndPoint <MyEndPoint>(); }) .Configure(app => { app.UseSockets(routes => { routes.MapEndPoint <MyEndPoint>("socket", httpSocketOptions => { httpSocketOptions.WebSockets.SubProtocol = "protocol1"; }); }); }) .Build(); await host.StartAsync(); var feature = host.ServerFeatures.Get <IServerAddressesFeature>(); var address = feature.Addresses.First().Replace("http", "ws") + "/socket"; var client = new ClientWebSocket(); client.Options.AddSubProtocol("protocol1"); client.Options.AddSubProtocol("protocol2"); await client.ConnectAsync(new Uri(address), CancellationToken.None); Assert.Equal("protocol1", client.SubProtocol); await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).OrTimeout(); var result = await client.ReceiveAsync(new ArraySegment <byte>(new byte[1024]), CancellationToken.None).OrTimeout(); Assert.Equal(WebSocketMessageType.Close, result.MessageType); }
public async Task maybe_itll_fail_i_dont_even() { var toServer = new WebHostBuilder() .UseKestrel() .UseUrls("http://127.0.0.1:0") .Configure(app => { app.Run(async context => { await context.Response.WriteAsync("hello"); }); }) .Build(); await toServer.StartAsync(); var toPort = toServer.Port(); var rpClient = new ReproReverseProxy(); var fromServer = new WebHostBuilder() .Configure(app => { app.Run(async context => { var targetResponse = await rpClient.Send(context, $"http://127.0.0.1:{toPort}"); await ReproCodec.Write(context, targetResponse); }); }) .UseKestrel() .UseUrls("http://127.0.0.1:0") .Build(); await fromServer.StartAsync(); var client = new HttpClient(); var response = await client.GetAsync($"http://127.0.0.1:{fromServer.Port()}"); response.EnsureSuccessStatusCode(); }
public static async Task Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseModularStartup <Startup>() .UseUrls(Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? "http://localhost:5000/") .Build(); await host.StartAsync(); Console.WriteLine("Press Enter"); Console.ReadLine(); using var container = GetContainer(); var runner = container.Resolve <IConsoleRunner>(); var result = await runner.Run(args); Environment.ExitCode = result; await host.StopAsync(); }
static void Main(string[] args) { DotBPE.Rpc.Environment.SetLogger(new DotBPE.Rpc.Logging.ConsoleLogger()); // 启动HTTP服务 var urls = "http://127.0.0.1:6200"; var webHost = new WebHostBuilder() .UseKestrel() .UseUrls(urls) .UseStartup <Startup>() .Build(); webHost.StartAsync().Wait(); Console.WriteLine("running http server listen {0}", urls); // RPC Server string ip = "127.0.0.1"; int port = 6201; var rpcHost = new RpcHostBuilder() .UseServer(ip, 6201) .UseStartup <DotBPEStartup>() .Build(); rpcHost.StartAsync().Wait(); Console.WriteLine("running server on {0}:{1}", ip, port); Console.WriteLine("press any key to shutdown"); Console.ReadKey(); webHost.StopAsync().Wait(); Console.WriteLine("http server is shutdown"); rpcHost.ShutdownAsync().Wait(); Console.WriteLine("dotbpe server is shutdown"); }
public async Task <int> RunAsync() { var port = _options.Port; var cts = new CancellationTokenSource(); _console.CancelKeyPress += (o, e) => { _console.WriteLine("Shutting down..."); cts.Cancel(); }; var config = GetAppServerConfig(_options); IWebHost host = new WebHostBuilder() .ConfigureLogging(l => { l.SetMinimumLevel(_options.MinLogLevel); l.AddConsole(); }) .PreferHostingUrls(false) .UseKestrel(o => { o.ListenAnyIP(port); }) .UseEnvironment("Production") .UseStartup <Startup>() .ConfigureServices(s => s.AddSingleton(config)) .Build(); _console.Write("Starting server"); await host.StartAsync(cts.Token); AfterServerStart(host); await host.WaitForShutdownAsync(cts.Token); return(0); }
public async Task <int> RunAsync(CancellationToken cancellationToken) { var directory = Path.GetFullPath(_options.Directory ?? _currentDirectory); var port = _options.Port; if (!CertificateLoader.TryLoadCertificate(_options, _currentDirectory, out var cert, out var certLoadError)) { _reporter.Verbose(certLoadError.ToString()); _reporter.Error(certLoadError.Message); return(1); } if (cert != null) { _reporter.Verbose($"Using certificate {cert.SubjectName.Name} ({cert.Thumbprint})"); } void ConfigureHttps(ListenOptions options) { if (cert != null) { options.UseHttps(cert); } } var host = new WebHostBuilder() .ConfigureLogging(l => { l.SetMinimumLevel(_options.MinLogLevel); l.AddConsole(); }) .PreferHostingUrls(false) .UseKestrel(o => { if (_options.ShouldUseLocalhost()) { if (port.GetValueOrDefault() == 0) { o.ListenAnyIP(0, ConfigureHttps); } else { o.ListenLocalhost(port.GetValueOrDefault(), ConfigureHttps); } } else { foreach (var a in _options.Addresses) { o.Listen(a, port.GetValueOrDefault(), ConfigureHttps); } } }) .UseWebRoot(directory) .UseContentRoot(directory) .UseEnvironment("Production") .SuppressStatusMessages(true) .UseStartup <Startup>() .ConfigureServices(s => s.AddSingleton(_options)) .Build(); _console.Write(ConsoleColor.DarkYellow, "Starting server, serving "); _console.WriteLine(Path.GetRelativePath(_currentDirectory, directory)); var defaultExtensions = _options.GetDefaultExtensions(); if (defaultExtensions != null) { _console.WriteLine(ConsoleColor.DarkYellow, $"Using default extensions " + string.Join(", ", defaultExtensions)); } await host.StartAsync(cancellationToken); AfterServerStart(host); await host.WaitForShutdownAsync(cancellationToken); return(0); }
private async Task <int> OnExecuteAsync(CommandLineApplication app) { if (string.IsNullOrEmpty(Url) && string.IsNullOrEmpty(RemotePageLocation) && !HelloWorld) { app.ShowHelp(); return(0); } Console.WriteLine(HostFolder); Directory.CreateDirectory(HostFolder); Directory.CreateDirectory("output"); await InstallNPMPackage(HostFolder, "requirejs"); await InstallNPMPackage(HostFolder, "puppeteer"); await InstallNPMPackage(HostFolder, "websocket"); await InstallNPMPackage(HostFolder, "isomorphic-fetch"); await InstallNPMPackage(HostFolder, "earthml-temply-headless"); var engine = new RazorLightEngineBuilder() .UseEmbeddedResourcesProject(typeof(Program)) .UseMemoryCachingProvider() .Build(); Console.WriteLine(string.Join(" ", app.RemainingArguments)); var args = new JObject(); for (var j = 0; j < app.RemainingArguments.Count; j += 2) { args[app.RemainingArguments[j].Trim('-')] = app.RemainingArguments[j + 1]; } IWebHost host = new WebHostBuilder() .UseKestrel() .Configure(appbuilder => { appbuilder.Use(async(context, next) => { Console.WriteLine(context.Request.Path); if (context.Request.Path == "/installDependencies") { var dps = JToken.Parse(await new StreamReader(context.Request.Body).ReadToEndAsync()); foreach (JProperty dependency in dps.SelectToken("$.dependencies")) { await InstallNPMPackage(HostFolder, dependency.Name, dependency.Value.ToString()); } context.Response.StatusCode = 200; return; } if (context.Request.Path == "/hello-world") { await context.Response.WriteAsync(@"<html><head><script src=""node_modules/requirejs/require.js""></script></head><body><script type=""text/javascript"">require.config({paths:{'earthml-temply-headless':'node_modules/earthml-temply-headless/artifacts/src'}}); require(['earthml-temply-headless/remotepage/remotepage'],(RemotePageModule)=>{console.log(RemotePageModule);let rp = new RemotePageModule.RemotePage(); rp.helloWorld(); })</script></body></html>"); return; } if (context.Request.Path == "/") { try { string result = await engine.CompileRenderAsync("GenericRemoteHost.cshtml", new { Name = "John Doe" }); await context.Response.WriteAsync(result); } catch (Exception ex) { Console.WriteLine(ex); } return; } await next(); Console.WriteLine($"{context.Request.Path} {context.Response.StatusCode}"); }); foreach (var volumne in Volumes) { appbuilder.Map(volumne.Split(':').Last(), (b) => { b.Use(async(ctx, next) => { await next(); Console.WriteLine($"{ctx.Request.Path} {ctx.Response.StatusCode}"); }); b.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(string.Join(":", volumne.Split(':').Reverse().Skip(1).Reverse())) }); }); } //appbuilder.Map("/appinsight", (b) => //{ // b.UseStaticFiles(new StaticFileOptions { FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(@"C:\dev\EarthML\EarthML.TemplyHeadless\samples\ApplicationInsightsGraphGenerator\wwwroot") }); //}); //appbuilder.Map("/AscendRegistration", (b) => //{ // b.UseStaticFiles(new StaticFileOptions { FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(@"C:\dev\Ascend\AscendRecording\AscendRecording\www\libs\AscendRegistration") }); //}); //appbuilder.Map("/node_modules/earthml-temply-headless/artifacts/src", (b) => //{ // b.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider("C:/dev/EarthML/EarthML.TemplyHeadless/src/EarthML.TemplyHeadless/artifacts/src") }); //}); appbuilder.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(HostFolder) }); }) .Build(); await host.StartAsync();; if (HelloWorld) { Url = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses .Select(a => a.Replace("://+", "://localhost").Replace("[::]", "127.0.0.1")).FirstOrDefault() + "/hello-world"; } if (!string.IsNullOrEmpty(RemotePageLocation)) { Url = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses .Select(a => a.Replace("://+", "://localhost").Replace("[::]", "127.0.0.1")).FirstOrDefault() + $"?remote-main={RemotePageMain}&remote-location={WebUtility.UrlEncode(RemotePageLocation)}"; } { var services = new ServiceCollection(); services.AddNodeServices(a => { // a.ProjectPath = Directory.GetCurrentDirectory(); // Set any properties that you want on 'options' here }); var serviceProvider = services.BuildServiceProvider(); var options = new NodeServicesOptions(serviceProvider) { ProjectPath = HostFolder, InvocationTimeoutMilliseconds = 60000 * 10, WatchFileExtensions = new string[] { } }; var _nodeServices = NodeServicesFactory.CreateNodeServices(options); try { var data = await RequireJS.RunAsync <object, JToken>(_nodeServices, HostFolder, "earthml-temply-headless/Headless/headless", new { url = Url, headlessHost = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses .Select(a => a.Replace("://+", "://localhost").Replace("[::]", "127.0.0.1")).FirstOrDefault(), headless = true, size = new { width = Width, height = Height }, data = args, inputPrefix = InputFolder, outputPrefix = OutputFolder }); Console.WriteLine(data.ToString()); }catch (Exception ex) { Console.WriteLine(ex); await Task.Delay(60000); } } if (host != null) { await host.StopAsync(); } return(0); }
public static async Task Main(string[] args) { var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"; var isDevelopment = "Development".Equals(environment, StringComparison.OrdinalIgnoreCase); var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddInMemoryCollection(new Dictionary <string, string> // add default settings, that will be overridden by commandline { { "Id", "Webapp" }, { "Version", "1.0.0" }, { "ClusterId", "rrod-cluster" }, { "ServiceId", "rrod" } }) .AddCommandLine(args) .AddJsonFile("Webapp.settings.json", optional: true, reloadOnChange: true) .AddJsonFile($"Webapp.settings.{environment}.json", optional: true, reloadOnChange: true) .AddJsonFile("/run/config/Webapp.settings.json", optional: true, reloadOnChange: true) .AddDockerSecrets("/run/secrets", optional: true) .AddUserSecrets <Program>(optional: true) .AddEnvironmentVariables("RROD_") .Build(); var loggerFactory = new LoggerFactory() .AddConsole(config.GetSection("Logging")) .AddDebug(); var logger = loggerFactory.CreateLogger <Program>(); logger.LogWarning($"Starting Webapp in {environment} environment..."); foreach (var provider in config.Providers) { logger.LogInformation($"Config Provider {provider.GetType().Name}: {provider.GetChildKeys(Enumerable.Empty<string>(), null).Count()} settings"); } // ServicePointManager.CheckCertificateRevocationList = false; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ServicePointManager.DefaultConnectionLimit = 20; int attempt = 0; int initializeAttemptsBeforeFailing = 7; IClusterClient clusterClient = null; while (true) { // Initialize orleans client clusterClient = new ClientBuilder() .ConfigureServices((context, services) => { // services.AddOptions(); services.AddSingleton <ILoggerFactory>(loggerFactory); // services.AddSingleton<IConfiguration>(config); services.Configure <ClusterOptions>(config); }) .AddAzureQueueStreams <AzureQueueDataAdapterV2>("Default", builder => builder.Configure(options => options.ConnectionString = config.GetConnectionString("DataConnectionString"))) .ConfigureApplicationParts(parts => { parts.AddApplicationPart(typeof(ICounterGrain).Assembly).WithReferences(); parts.AddApplicationPart(typeof(AzureQueueDataAdapterV2).Assembly).WithReferences(); }) .UseAzureStorageClustering(options => options.ConnectionString = config.GetConnectionString("DataConnectionString")) .Build(); try { await clusterClient.Connect().ConfigureAwait(false); logger.LogInformation("Client successfully connected to silo host"); break; } catch (OrleansException) { attempt++; logger.LogWarning($"Attempt {attempt} of {initializeAttemptsBeforeFailing} failed to initialize the Orleans client."); if (clusterClient != null) { clusterClient.Dispose(); clusterClient = null; } if (attempt > initializeAttemptsBeforeFailing) { throw; } // Wait 4 seconds before retrying await Task.Delay(TimeSpan.FromSeconds(4)); } } var endpoints = config.GetSection("Http:Endpoints") .GetChildren() .ToDictionary(section => section.Key, section => { var endpoint = new EndpointConfiguration(); section.Bind(endpoint); return(endpoint); }); // if so, start a listener to respond to Acme (Let's Encrypt) requests, using a response received via an Orleans Cache Grain var hasHttps = endpoints.Any(endpoint => endpoint.Value.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase)); var needPort80 = endpoints.Any(endpoint => (endpoint.Value.Port ?? (endpoint.Value.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase) ? 443 : 80)) == 80); var certs = new Dictionary <string, X509Certificate2>(); var acmeOptions = new AcmeOptions { AcmeSettings = config.GetSection(nameof(AcmeSettings)).Get <AcmeSettings>(), GetChallengeResponse = async(challenge) => { var cacheGrain = clusterClient.GetGrain <ICacheGrain <string> >(challenge); var response = await cacheGrain.Get(); return(response.Value); }, SetChallengeResponse = async(challenge, response) => { var cacheGrain = clusterClient.GetGrain <ICacheGrain <string> >(challenge); await cacheGrain.Set(new Immutable <string>(response), TimeSpan.FromHours(2)); }, StoreCertificate = async(string domainName, byte[] certData) => { var certGrain = clusterClient.GetGrain <ICertGrain>(domainName); await certGrain.UpdateCertificate(certData); }, RetrieveCertificate = async(domainName) => { var certGrain = clusterClient.GetGrain <ICertGrain>(domainName); var certData = await certGrain.GetCertificate(); return(certData.Value); } }; if (hasHttps) { logger.LogWarning($"At least one https endpoint is present. Initialize Acme endpoint."); var acmeHost = new WebHostBuilder() .UseEnvironment(environment) .UseConfiguration(config) .ConfigureServices(services => { services.AddSingleton <IClusterClient>(clusterClient); services.AddSingleton <ILoggerFactory>(loggerFactory); services.Configure <AcmeSettings>(config.GetSection(nameof(AcmeSettings))); // Register a certitificate manager, supplying methods to store and retreive certificates and acme challenge responses services.AddAcmeCertificateManager(acmeOptions); }) // .UseUrls("http://*:80") .PreferHostingUrls(false) .UseKestrel(options => { options.Listen(IPAddress.Any, 80); }) .Configure(app => { app.UseAcmeResponse(); }) .Build(); try { await acmeHost.StartAsync().ConfigureAwait(false); } catch (Exception e) { logger.LogError("Error: can't start web listener for acme certificate renewal, probably the web address is in use by another process. Exception message is: " + e.Message); logger.LogError("Ignoring noncritical error (stop W3SVC or Skype to fix this), continuing..."); } var certificateManager = acmeHost.Services.GetRequiredService <ICertificateManager>(); // var certificateManager = new AcmeCertificateManager(Options.Create(acmeOptions)); foreach (var endpoint in endpoints) { var endpointConfig = endpoint.Value; bool isHttpsEndpoint = endpointConfig.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase); var port = endpointConfig.Port ?? (isHttpsEndpoint ? 443 : 80); X509Certificate2 certificate = null; if (isHttpsEndpoint) { try { var domains = new List <string> { endpointConfig.Domain } .Concat(endpointConfig.Domains) .Where(ep => !string.IsNullOrEmpty(ep)) .Distinct() .ToArray(); logger.LogInformation($"Getting certificate for domain {domains.First()} on port {port}"); // Request a new certificate with Let's Encrypt and store it for next time try { certificate = await certificateManager.GetCertificate(domains); } catch (Exception e) { logger.LogCritical(e, $"Exception getting certificate for domain {domains.First()}. PfxPassword configured incorrectly?"); } if (certificate == null) { // It didn't work - create a temporary certificate so that we can still start with an untrusted certificate logger.LogCritical($"Error getting certificate for domain {domains.First()} (endpoint '{endpoint.Key}'). Creating self-signed temporary certificate..."); certificate = CertHelper.BuildTlsSelfSignedServer(domains); } certs.Add(domains.First(), certificate); logger.LogInformation($"Certificate for domain {domains.First()}: {certificate != null}"); } catch (Exception e) { logger.LogCritical($"Kestrel startup: Exception getting certificate. {e.Message}"); } } } if (needPort80) { await acmeHost.StopAsync(); } } var webHost = new WebHostBuilder() .UseEnvironment(environment) .UseConfiguration(config) .ConfigureServices(services => { // services.AddSingleton<IConfiguration>(config); services.AddSingleton <IClusterClient>(clusterClient); services.AddSingleton <ILoggerFactory>(loggerFactory); services.Configure <AcmeSettings>(config.GetSection(nameof(AcmeSettings))); services.AddAcmeCertificateManager(acmeOptions); }) .UseContentRoot(Directory.GetCurrentDirectory()) // .UseUrls(listenUrls.ToArray()) .PreferHostingUrls(false) .Configure(app => { app.UseAcmeResponse(); }) .UseStartup <Startup>() .UseKestrel(options => { foreach (var endpoint in endpoints) { var endpointConfig = endpoint.Value; bool isHttpsEndpoint = endpointConfig.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase); var port = endpointConfig.Port ?? (isHttpsEndpoint ? 443 : 80); var ipAddresses = new List <IPAddress>(); var hosts = new List <string> { endpointConfig.Host } .Concat(endpointConfig.Hosts) .Where(ep => !string.IsNullOrEmpty(ep)) .Distinct(); foreach (var host in hosts) { if (host == "localhost") { ipAddresses.Add(IPAddress.IPv6Loopback); ipAddresses.Add(IPAddress.Loopback); } else if (IPAddress.TryParse(host, out var address)) { ipAddresses.Add(address); } else { logger.LogError($"Error parsing endpoint host: {host}"); } } foreach (var address in ipAddresses) { options.Listen(address, port, listenOptions => { if (isHttpsEndpoint) { var domains = new List <string> { endpointConfig.Domain } .Concat(endpointConfig.Domains) .Where(ep => !string.IsNullOrEmpty(ep)) .Distinct() .ToArray(); if (certs.TryGetValue(domains.First(), out var certificate)) { logger.LogInformation($"Kestrel config: Listen on address {address.ToString()}:{port}, certificate {(certificate == null ? "NULL" : certificate.Subject.ToString())}"); listenOptions.UseHttps(certificate); listenOptions.NoDelay = false; // listenOptions.UseConnectionLogging(); } else { logger.LogError($"No certificate for domain: {domains.First()}"); } } }); } } }) .Build(); await webHost.RunAsync(); }
public async Task <int> OnExecute(IConsole console) { var cts = new CancellationTokenSource(); console.CancelKeyPress += (o, e) => { console.WriteLine("Shutting down..."); cts.Cancel(); }; var address = IPAddress.Parse(Address); var path = Path != null ? IOPath.GetFullPath(Path) : Directory.GetCurrentDirectory(); if (!string.IsNullOrEmpty(PathBase) && PathBase[0] != '/') { PathBase = "/" + PathBase; } var host = new WebHostBuilder() .ConfigureLogging(l => { l.SetMinimumLevel(LogLevel.Information); l.AddConsole(); }) .PreferHostingUrls(false) .UseKestrel(o => { if (IPAddress.Any.Equals(address)) { o.ListenLocalhost(Port); o.ListenAnyIP(Port); } o.Listen(address, Port); }) .UseSockets() .UseWebRoot(path) .UseContentRoot(path) .UseEnvironment("Production") .Configure(app => { app.UseStatusCodePages("text/html", "<html><head><title>Error {0}</title></head><body><h1>HTTP {0}</h1></body></html>"); if (!string.IsNullOrEmpty(PathBase)) { app.Map(PathBase, Configure); } else { Configure(app); } }) .Build(); console.ForegroundColor = ConsoleColor.DarkYellow; console.Write("Starting server, serving "); console.ResetColor(); console.WriteLine(IOPath.GetRelativePath(Directory.GetCurrentDirectory(), path)); await host.StartAsync(cts.Token); var addresses = host.ServerFeatures.Get <IServerAddressesFeature>(); console.WriteLine("Listening on:"); console.ForegroundColor = ConsoleColor.Green; foreach (var a in addresses.Addresses) { console.WriteLine(" " + a + PathBase); } console.ResetColor(); console.WriteLine(""); console.WriteLine("Press CTRL+C to exit"); if (OpenBrowser) { var url = addresses.Addresses.First(); // normalize to loopback if binding to IPAny url = url.Replace("0.0.0.0", "localhost"); url = url.Replace("[::]", "localhost"); if (!string.IsNullOrEmpty(PathBase)) { url += PathBase; } LaunchBrowser(url); } await host.WaitForShutdownAsync(cts.Token); return(0); }
public async Task <int> RunAsync() { var cts = new CancellationTokenSource(); var addresses = _options.Addresses.Length > 0 ? _options.Addresses : s_defaultAddresses; var directory = _options.Directory; var port = _options.Port; _console.CancelKeyPress += (o, e) => { _console.WriteLine("Shutting down..."); cts.Cancel(); }; var path = directory != null ? Path.GetFullPath(directory) : Directory.GetCurrentDirectory(); var host = new WebHostBuilder() .ConfigureLogging(l => { l.SetMinimumLevel(_options.MinLogLevel); l.AddConsole(); }) .PreferHostingUrls(false) .UseKestrel(o => { foreach (var a in addresses) { if (a.Equals(IPAddress.Loopback) || a.Equals(IPAddress.IPv6Loopback)) { o.ListenLocalhost(port); } else { o.Listen(a, port); } } }) .UseSockets() .UseWebRoot(path) .UseContentRoot(path) .UseEnvironment("Production") .SuppressStatusMessages(true) .UseStartup <Startup>() .ConfigureServices(s => s.AddSingleton(_options) .AddSingleton <RazorPageSourceProvider>()) .Build(); _console.Write(ConsoleColor.DarkYellow, "Starting server, serving "); _console.WriteLine(Path.GetRelativePath(Directory.GetCurrentDirectory(), path)); var defaultExtensions = _options.GetDefaultExtensions(); if (defaultExtensions != null) { _console.WriteLine(ConsoleColor.DarkYellow, $"Using default extensions " + string.Join(", ", defaultExtensions)); } await host.StartAsync(cts.Token); AfterServerStart(host); await host.WaitForShutdownAsync(cts.Token); return(0); }
public async Task <int> OnExecute(IConsole console) { var cts = new CancellationTokenSource(); console.CancelKeyPress += (o, e) => { console.WriteLine("Shutting down..."); cts.Cancel(); }; var address = IPAddress.Parse(Address); var path = Path != null ? IOPath.GetFullPath(Path) : Directory.GetCurrentDirectory(); var host = new WebHostBuilder() .ConfigureLogging(l => { l.SetMinimumLevel(LogLevel.Information); l.AddConsole(); }) .PreferHostingUrls(false) .UseKestrel(o => { o.Listen(address, Port); }) .UseSockets() .UseWebRoot(path) .UseContentRoot(path) .UseEnvironment("Production") .Configure(app => { app.UseStatusCodePages("text/html", "<html><head><title>Error {0}</title></head><body><h1>HTTP {0}</h1></body></html>"); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = true, StaticFileOptions = { ServeUnknownFileTypes = true, }, }); }) .Build(); console.ForegroundColor = ConsoleColor.DarkYellow; console.Write("Starting server, serving "); console.ResetColor(); console.WriteLine(IOPath.GetRelativePath(Directory.GetCurrentDirectory(), path)); await host.StartAsync(cts.Token); var addresses = host.ServerFeatures.Get <IServerAddressesFeature>(); console.WriteLine("Listening on:"); console.ForegroundColor = ConsoleColor.Green; foreach (var a in addresses.Addresses) { console.WriteLine(" " + a); } console.ResetColor(); console.WriteLine(""); console.WriteLine("Press CTRL+C to exit"); if (OpenBrowser) { LaunchBrowser(addresses.Addresses.First()); } await host.WaitForShutdownAsync(cts.Token); return(0); }
public static async Task Main(string[] args) { string[] salutations = { "Have a nice day!", "Thank you for using PlayFab Multiplayer Servers", "Check out our docs at aka.ms/playfabdocs!", "Have a question? Check our community at community.playfab.com" }; Console.WriteLine(salutations[new Random().Next(salutations.Length)]); string debuggingUrl = "https://github.com/PlayFab/gsdkSamples/blob/master/Debugging.md"; Console.WriteLine($"Check this page for debugging tips: {debuggingUrl}"); // lcow stands for Linux Containers On Windows => https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/linux-containers Globals.GameServerEnvironment = args.Contains("-lcow") && RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? GameServerEnvironment.Linux : GameServerEnvironment.Windows; // LocalMultiplayerAgent is running only on Windows for the time being MultiplayerSettings settings = JsonConvert.DeserializeObject <MultiplayerSettings>(File.ReadAllText("MultiplayerSettings.json")); settings.SetDefaultsIfNotSpecified(); MultiplayerSettingsValidator validator = new MultiplayerSettingsValidator(settings); if (!validator.IsValid()) { Console.WriteLine("The specified settings are invalid. Please correct them and re-run the agent."); Environment.Exit(1); } string vmId = $"xcloudwusu4uyz5daouzl:{settings.Region}:{Guid.NewGuid()}:tvmps_{Guid.NewGuid():N}{Guid.NewGuid():N}_d"; Console.WriteLine($"TitleId: {settings.TitleId}"); Console.WriteLine($"BuildId: {settings.BuildId}"); Console.WriteLine($"VmId: {vmId}"); Globals.Settings = settings; string rootOutputFolder = Path.Combine(settings.OutputFolder, "PlayFabVmAgentOutput", DateTime.Now.ToString("s").Replace(':', '-')); Console.WriteLine($"Root output folder: {rootOutputFolder}"); VmDirectories vmDirectories = new VmDirectories(rootOutputFolder); Globals.VmConfiguration = new VmConfiguration(settings.AgentListeningPort, vmId, vmDirectories); if (Globals.GameServerEnvironment == GameServerEnvironment.Linux && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Globals.AdaptFolderPathsForLinuxContainersOnWindows(); // Linux Containers on Windows requires special folder mapping } Directory.CreateDirectory(rootOutputFolder); Directory.CreateDirectory(vmDirectories.GameLogsRootFolderVm); Directory.CreateDirectory(Globals.VmConfiguration.VmDirectories.CertificateRootFolderVm); IWebHost host = new WebHostBuilder() .UseKestrel() .UseUrls($"http://*:{settings.AgentListeningPort}") .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .Build(); await host.StartAsync(); Console.WriteLine($"Local Multiplayer Agent is listening on port {settings.AgentListeningPort}"); Globals.SessionConfig = settings.SessionConfig ?? new SessionConfig() { SessionId = Guid.NewGuid() }; Console.WriteLine($"{string.Join(", ", Globals.SessionConfig.InitialPlayers)}"); await new MultiplayerServerManager(SystemOperations.Default, Globals.VmConfiguration, Globals.MultiLogger, SessionHostRunnerFactory.Instance) .CreateAndStartContainerWaitForExit(settings.ToSessionHostsStartInfo()); await host.StopAsync(); }
private const long MAX_DEBUG_LOG_FILE_SIZE = 2000000; // If debug log is in use roll it every N MB. static void Main(string[] args) { ServicePointManager.DefaultConnectionLimit = 100; IWebHost host = null; var processor = new ConsoleLoggerProcessor(); CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(loggerProvider); var logger = loggerFactory.CreateLogger("Configuration"); try { // This is the only way that LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called var conf = new DefaultConfiguration() { Logger = logger }.CreateConfiguration(args); if (conf == null) { return; } Logs.Configure(loggerFactory); new BTCPayServerOptions().LoadArgs(conf); Logs.Configure(null); ///// host = new WebHostBuilder() .UseKestrel() .UseIISIntegration() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(conf) .ConfigureLogging(l => { l.AddFilter("Microsoft", LogLevel.Error); l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical); l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical); l.AddProvider(new CustomConsoleLogProvider(processor)); // Use Serilog for debug log file. var debugLogFile = BTCPayServerOptions.GetDebugLog(conf); if (string.IsNullOrEmpty(debugLogFile) != false) { return; } Serilog.Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Is(BTCPayServerOptions.GetDebugLogLevel(conf)) .WriteTo.File(debugLogFile, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: MAX_DEBUG_LOG_FILE_SIZE, rollOnFileSizeLimit: true, retainedFileCountLimit: 1) .CreateLogger(); l.AddSerilog(Serilog.Log.Logger); }) .UseStartup <Startup>() .Build(); host.StartAsync().GetAwaiter().GetResult(); var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses; foreach (var url in urls) { logger.LogInformation("Listening on " + url); } host.WaitForShutdown(); } catch (ConfigException ex) { if (!string.IsNullOrEmpty(ex.Message)) { Logs.Configuration.LogError(ex.Message); } } finally { processor.Dispose(); if (host == null) { Logs.Configuration.LogError("Configuration error"); } if (host != null) { host.Dispose(); } Serilog.Log.CloseAndFlush(); loggerProvider.Dispose(); } }