Exemplo n.º 1
0
        public static async Task RunAsync(Application application, string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Logging for this application
            builder.Host.UseSerilog((context, configuration) => configuration
                                    .MinimumLevel.Verbose()
                                    .Filter.ByExcluding(Matching.FromSource("Microsoft"))
                                    .Enrich
                                    .FromLogContext()
                                    .WriteTo
                                    .Console()
                                    );

            builder.Services.AddRazorPages(o => o.RootDirectory = "/Dashboard/Pages");

            builder.Services.AddServerSideBlazor();

            builder.Services.AddOptions <StaticFileOptions>()
            .PostConfigure(o =>
            {
                var fileProvider = new ManifestEmbeddedFileProvider(typeof(MicronetesHost).Assembly, "wwwroot");

                // Make sure we don't remove the existing file providers (blazor needs this)
                o.FileProvider = new CompositeFileProvider(o.FileProvider, fileProvider);
            });

            builder.Services.AddSingleton(application);

            builder.Services.AddCors(
                options =>
            {
                options.AddPolicy(
                    "default",
                    policy =>
                {
                    policy
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            using var app = builder.Build();

            var port = app.Configuration["port"] ?? "0";

            app.Listen($"http://127.0.0.1:{port}");

            app.UseDeveloperExceptionPage();

            app.UseCors("default");

            app.UseStaticFiles();

            app.UseRouting();

            var api = new MicronetesApi();

            api.MapRoutes(app);

            app.MapBlazorHub();
            app.MapFallbackToPage("/_Host");

            var logger = app.Logger;

            logger.LogInformation("Executing application from  {Source}", application.Source);

            var lifetime      = app.ApplicationLifetime;
            var configuration = app.Configuration;

            var diagnosticOptions    = DiagnosticOptions.FromConfiguration(configuration);
            var diagnosticsCollector = new DiagnosticsCollector(logger, diagnosticOptions);

            // Print out what providers were selected and their values
            diagnosticOptions.DumpDiagnostics(logger);

            var processor = new AggregateApplicationProcessor(new IApplicationProcessor[] {
                new EventPipeDiagnosticsRunner(logger, diagnosticsCollector),
                new ProxyService(logger),
                new DockerRunner(logger),
                new ProcessRunner(logger, ProcessRunnerOptions.FromArgs(args)),
            });

            await app.StartAsync();

            logger.LogInformation("Dashboard running on {Address}", app.Addresses.First());

            try
            {
                await processor.StartAsync(application);
            }
            catch (Exception ex)
            {
                logger.LogError(0, ex, "Failed to launch application");
            }

            var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

            lifetime.ApplicationStopping.Register(obj => waitForStop.TrySetResult(null), null);

            await waitForStop.Task;

            logger.LogInformation("Shutting down...");

            try
            {
                await processor.StopAsync(application);
            }
            finally
            {
                // Stop the host after everything else has been shutdown
                await app.StopAsync();
            }
        }
Exemplo n.º 2
0
        public static async Task RunAsync(Application application, string[] args)
        {
            var options = new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true,
                PropertyNamingPolicy        = JsonNamingPolicy.CamelCase,
                WriteIndented = true,
            };

            options.Converters.Add(ReplicaStatus.JsonConverter);

            using var host = Host.CreateDefaultBuilder(args)
                             .UseSerilog((context, configuration) =>
            {
                // Logging for this application
                configuration
                .MinimumLevel.Verbose()
                .Filter.ByExcluding(Matching.FromSource("Microsoft"))
                .Enrich
                .FromLogContext()
                .WriteTo
                .Console();
            })
                             .ConfigureWebHostDefaults(web =>
            {
                web.ConfigureServices(services =>
                {
                    services.AddRazorPages();
                    services.AddServerSideBlazor();

                    services.AddOptions <StaticFileOptions>()
                    .PostConfigure(o =>
                    {
                        // Make sure we don't remove the other file providers (blazor needs this)
                        o.FileProvider = new CompositeFileProvider(o.FileProvider, new ManifestEmbeddedFileProvider(typeof(MicronetesHost).Assembly, "wwwroot"));
                    });

                    services.AddSingleton(application);
                });

                web.ConfigureKestrel(options =>
                {
                    var config = options.ApplicationServices.GetRequiredService <IConfiguration>();

                    if (config["port"] != null && int.TryParse(config["port"], out int cpPort))
                    {
                        // Use the specified port
                        options.Listen(IPAddress.Loopback, cpPort);
                    }
                    else
                    {
                        // This is lame but it allows running multiple versions of this
                        // we should also allow ports to be specified as input
                        options.Listen(IPAddress.Loopback, 0);
                    }
                });

                web.Configure(app =>
                {
                    app.UseDeveloperExceptionPage();

                    app.UseStaticFiles();

                    app.UseRouting();

                    var api = new MicronetesApi(options);

                    app.UseEndpoints(endpoints =>
                    {
                        api.MapRoutes(endpoints);

                        endpoints.MapBlazorHub();
                        endpoints.MapFallbackToPage("/_Host");
                    });
                });
            })
                             .Build();

            var logger                 = host.Services.GetRequiredService <ILogger <MicronetesHost> >();
            var lifetime               = host.Services.GetRequiredService <IHostApplicationLifetime>();
            var configuration          = host.Services.GetRequiredService <IConfiguration>();
            var serverAddressesFeature = host.Services.GetRequiredService <IServer>().Features.Get <IServerAddressesFeature>();

            var diagnosticOptions    = DiagnosticOptions.FromConfiguration(configuration);
            var diagnosticsCollector = new DiagnosticsCollector(logger, diagnosticOptions);
            var proxyService         = new ProxyService(logger);

            // Print out what providers were selected and their values
            diagnosticOptions.DumpDiagnostics(logger);

            var target = new OutOfProcessExecutionTarget(logger, OutOfProcessOptions.FromArgs(args), diagnosticsCollector);

            await host.StartAsync();

            logger.LogInformation("Dashboard running on {Address}", serverAddressesFeature.Addresses.First());

            try
            {
                await proxyService.StartAsync(application);

                await target.StartAsync(application);
            }
            catch (Exception ex)
            {
                logger.LogError(0, ex, "Failed to launch application");
            }

            var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

            lifetime.ApplicationStopping.Register(obj => waitForStop.TrySetResult(null), null);

            await waitForStop.Task;

            logger.LogInformation("Shutting down...");

            try
            {
                await target.StopAsync(application);

                await proxyService.StopAsync(application);
            }
            finally
            {
                // Stop the host after everything else has been shutdown
                await host.StopAsync();
            }
        }
 public DiagnosticsCollector(Microsoft.Extensions.Logging.ILogger logger, DiagnosticOptions options)
 {
     _logger  = logger;
     _options = options;
 }