public EveindustryCliService(IConfiguration config, IManufacturingInfoBuilder manufacturingBuilder, IEveTypeRepository etRepository, IHostApplicationLifetime applicationLifetime, IMapper mapper)
 {
     this.config = config;
     this.manufacturingBuilder = manufacturingBuilder;
     this.etRepository         = etRepository;
     this.applicationLifetime  = applicationLifetime;
     this.mapper = mapper;
 }
Esempio n. 2
0
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifeTime)
 {
     app.DeleteAndRecreateDatabase(Configuration);
     lifeTime.StopApplication();
 }
Esempio n. 3
0
 public Worker(IHostApplicationLifetime hostApplicationLifetime, TestContext context)
 {
     _dbContext = context;
     _hostApplicationLifetime = hostApplicationLifetime;
 }
Esempio n. 4
0
 public ApplicationController(ISoulseekClient client, IHostApplicationLifetime lifetime)
 {
     Client   = client;
     Lifetime = lifetime;
 }
Esempio n. 5
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">The application to configure.</param>
        /// <param name="env">The environment information to use in configuration phase.</param>
        /// <param name="applicationLifetime"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
        {
            app.UseProblemDetails();
            if (!env.IsProduction())
            {
                //This test middleware needs to be before developer exception pages.
                app.Use(TestMiddleware);
                app.UseDeveloperExceptionPage();
            }

            //app.UseHealthChecks("/healthz");
            //app.UseMiddleware<StartupTasksMiddleware>();

            applicationLifetime.ApplicationStopping.Register(() => { });

            //This ensures (or improves chances) to flush log buffers before (a graceful) shutdown.
            //It appears there isn't other way (e.g. in Program) than taking a reference to the global
            //static Serilog instance.
            applicationLifetime.ApplicationStopped.Register(Log.CloseAndFlush);

            //Security headers will always be added and by default the disallow everything.
            //The trimming is a robustness measure to make sure the URL has one trailing slash.
            //The listening address is needed for security headers. This is the public
            //API address.
            var appsettingsSection = Configuration.GetSection("AppSettings");
            var listeningAddress   = appsettingsSection["OneBoxDeploymentApiUrl"];

            listeningAddress = (listeningAddress ?? app.ServerFeatures.Get <IServerAddressesFeature>().Addresses.FirstOrDefault()).EnsureTrailing('/');

            //Note: the constructor checks ConfigurationKeys forbidden in production are not found.
            if (!env.IsProduction())
            {
                //Creates a route to specifically throw and unhandled exception. This route is most likely injected only in testing.
                //This kind of testing middleware can be made to one code block guarded appropriately if there is more of it.
                var alwaysFaultyRoute = Configuration.GetValue <string>(ConfigurationKeys.AlwaysFaultyRoute, null);
                if (alwaysFaultyRoute != null)
                {
                    app.Use((context, next) =>
                    {
                        if (context.Request.Path.StartsWithSegments($"/{alwaysFaultyRoute}", out _, out _))
                        {
                            throw new Exception($"Fault injected route for testing ({context.Request.PathBase}/{alwaysFaultyRoute}).");
                        }

                        return(next());
                    });
                }
            }

            Logger.LogInformation(Events.SwaggerDocumentation.Id, Events.SwaggerDocumentation.FormatString, listeningAddress + SwaggerRoot + "/");
            var defaultSecurityPolicies = new HeaderPolicyCollection()
                                          .AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365)
                                          .RemoveServerHeader()
                                          .AddFrameOptionsDeny();

            app.UseSecurityHeaders(defaultSecurityPolicies);
            app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/" + SwaggerRoot), swaggerBranch =>
            {
                //See configuration at https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders.
                const string GoogleStyles   = "https://fonts.googleapis.com";
                const string GoogleFontsUrl = "https://fonts.gstatic.com";
                var clientUrl = Path.Combine(listeningAddress, SwaggerRoot).EnsureTrailing('/');
                //Additional information for the many Feature-Policy none definitions:
                //https://github.com/w3c/webappsec-feature-policy/issues/189#issuecomment-452401661.
                swaggerBranch.UseSecurityHeaders(new HeaderPolicyCollection().AddFeaturePolicy(builder =>
                {
                    builder.AddAccelerometer().None();
                    builder.AddAmbientLightSensor().None();
                    builder.AddAutoplay().None();
                    builder.AddCamera().None();
                    builder.AddEncryptedMedia().None();
                    builder.AddFullscreen().None();
                    builder.AddGeolocation().None();
                    builder.AddGyroscope().None();
                    builder.AddMagnetometer().None();
                    builder.AddMicrophone().None();
                    builder.AddMidi().None();
                    builder.AddPayment().None();
                    builder.AddPictureInPicture().None();
                    builder.AddSpeaker().None();
                    builder.AddSyncXHR().None();
                    builder.AddUsb().None();
                    builder.AddVR().None();
                })
                                                 .AddXssProtectionBlock()
                                                 .AddContentTypeOptionsNoSniff()
                                                 .AddReferrerPolicyStrictOriginWhenCrossOrigin()
                                                 .AddContentSecurityPolicy(builder =>
                {
                    builder.AddReportUri().To("/cspreport");
                    builder.AddBlockAllMixedContent();
                    builder.AddConnectSrc().Self();
                    builder.AddStyleSrc().Self().UnsafeInline().Sources.Add(GoogleStyles);
                    builder.AddFontSrc().Self().Sources.Add(GoogleFontsUrl);
                    builder.AddImgSrc().Self().Sources.Add("data:");
                    builder.AddScriptSrc().Self().UnsafeInline();
                    builder.AddObjectSrc().None();
                    builder.AddFormAction().Self();
                    builder.AddFrameAncestors().None().Sources.Add(clientUrl);
                }, asReportOnly: false));
            });

            //For further Swagger related information, see at
            //https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger.
            app.UseSwagger();
            app.UseSwagger(swagger => swagger.RouteTemplate = $"{SwaggerRoot}/{{documentName}}/swagger.json");

            if (Configuration["HideSwaggerUi"]?.Equals("true") != true)
            {
                app.UseSwaggerUI(swaggerSetup =>
                {
                    swaggerSetup.SwaggerEndpoint($"/{SwaggerRoot}/{SwaggerDocumentationBasePath}/swagger.json", SwaggerDocumentationBasePath);
                    swaggerSetup.RoutePrefix = SwaggerRoot;

                    swaggerSetup.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream($"{Assembly.GetAssembly(typeof(Startup)).GetName().Name}.wwwroot.swagger.index.html");
                });
            }

            app.UseCors("CorsPolicy");
            app.UseStaticFiles();
            app.UseRouting();
            //app.UseAuthorization();
            app.UseEndpoints(endpoints => endpoints.MapControllers());
        }
Esempio n. 6
0
 public DbMigratorHostedService(IHostApplicationLifetime hostApplicationLifetime, IConfiguration configuration)
 {
     _hostApplicationLifetime = hostApplicationLifetime;
     _configuration           = configuration;
 }
        public static async Task <IApplicationBuilder> UseNacosAspNet(this IApplicationBuilder app, IHostApplicationLifetime lifetime)
        {
            RegSvcBgTask regSvcBgTask = app.ApplicationServices.GetRequiredService <RegSvcBgTask>();
            await regSvcBgTask.StartAsync();

            lifetime.ApplicationStopping.Register(async() => {
                await regSvcBgTask.StopAsync();
            });
            return(app);
        }
Esempio n. 8
0
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            IHostApplicationLifetime appLifetime,
            Func <DateTimeOffset> getDateTimeOffset)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var configuration = app.ApplicationServices.GetService <IConfiguration>();

            var adminPassword = configuration.GetValue <string>(Configuration.AdminPasswordSettingKey);

            var publicWebHostUrls =
                configuration.GetValue <string>(Configuration.PublicWebHostUrlsSettingKey).Split(new[] { ',', ';' });

            var processStoreFileStore = app.ApplicationServices.GetService <FileStoreForProcessStore>().fileStore;

            object avoidConcurrencyLock = new object();

            PublicHostConfiguration publicAppHost = null;

            void stopPublicApp()
            {
                lock (avoidConcurrencyLock)
                {
                    if (publicAppHost != null)
                    {
                        logger.LogInformation("Begin to stop the public app.");

                        publicAppHost?.webHost?.StopAsync(TimeSpan.FromSeconds(10)).Wait();
                        publicAppHost?.webHost?.Dispose();
                        publicAppHost?.processVolatileRepresentation?.Dispose();
                        publicAppHost = null;
                    }
                }
            }

            appLifetime.ApplicationStopping.Register(() =>
            {
                stopPublicApp();
            });

            var processStoreWriter =
                new ProcessStoreSupportingMigrations.ProcessStoreWriterInFileStore(processStoreFileStore);

            void startPublicApp()
            {
                lock (avoidConcurrencyLock)
                {
                    stopPublicApp();

                    var newPublicAppConfig = new PublicHostConfiguration {
                    };

                    logger.LogInformation("Begin to build the process volatile representation.");

                    var processVolatileRepresentation =
                        PersistentProcess.PersistentProcessVolatileRepresentation.Restore(
                            new ProcessStoreSupportingMigrations.ProcessStoreReaderInFileStore(processStoreFileStore),
                            logger: logEntry => logger.LogInformation(logEntry));

                    logger.LogInformation("Completed building the process volatile representation.");

                    var            cyclicReductionStoreLock            = new object();
                    DateTimeOffset?cyclicReductionStoreLastTime        = null;
                    var            cyclicReductionStoreDistanceSeconds = (int)TimeSpan.FromMinutes(10).TotalSeconds;

                    void maintainStoreReductions()
                    {
                        var currentDateTime = getDateTimeOffset();

                        System.Threading.Thread.MemoryBarrier();
                        var cyclicReductionStoreLastAge = currentDateTime - cyclicReductionStoreLastTime;

                        if (!(cyclicReductionStoreLastAge?.TotalSeconds < cyclicReductionStoreDistanceSeconds))
                        {
                            if (System.Threading.Monitor.TryEnter(cyclicReductionStoreLock))
                            {
                                try
                                {
                                    var afterLockCyclicReductionStoreLastAge = currentDateTime - cyclicReductionStoreLastTime;

                                    if (afterLockCyclicReductionStoreLastAge?.TotalSeconds < cyclicReductionStoreDistanceSeconds)
                                    {
                                        return;
                                    }

                                    lock (avoidConcurrencyLock)
                                    {
                                        var reductionRecord = processVolatileRepresentation.StoreReductionRecordForCurrentState(processStoreWriter);
                                    }

                                    cyclicReductionStoreLastTime = currentDateTime;
                                    System.Threading.Thread.MemoryBarrier();
                                }
                                finally
                                {
                                    System.Threading.Monitor.Exit(cyclicReductionStoreLock);
                                }
                            }
                        }
                    }

                    IWebHost buildWebHost()
                    {
                        var appConfigTree = Composition.ParseAsTree(
                            processVolatileRepresentation.lastAppConfig.Value.appConfigComponent).Ok;

                        var appConfigFilesNamesAndContents =
                            appConfigTree.EnumerateBlobsTransitive()
                            .Select(blobPathAndContent => (
                                        fileName: (IImmutableList <string>)blobPathAndContent.path.Select(name => System.Text.Encoding.UTF8.GetString(name.ToArray())).ToImmutableList(),
                                        fileContent: blobPathAndContent.blobContent))
                            .ToImmutableList();

                        var webAppConfigurationFile =
                            appConfigFilesNamesAndContents
                            .FirstOrDefault(filePathAndContent => filePathAndContent.fileName.SequenceEqual(JsonFilePath))
                            .fileContent;

                        var webAppConfiguration =
                            webAppConfigurationFile == null
                            ?
                            null
                            :
                            Newtonsoft.Json.JsonConvert.DeserializeObject <WebAppConfigurationJsonStructure>(Encoding.UTF8.GetString(webAppConfigurationFile.ToArray()));

                        return
                            (Microsoft.AspNetCore.WebHost.CreateDefaultBuilder()
                             .ConfigureLogging((hostingContext, logging) =>
                        {
                            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                            logging.AddConsole();
                            logging.AddDebug();
                        })
                             .ConfigureKestrel(kestrelOptions =>
                        {
                            kestrelOptions.ConfigureHttpsDefaults(httpsOptions =>
                            {
                                httpsOptions.ServerCertificateSelector = (c, s) => FluffySpoon.AspNet.LetsEncrypt.LetsEncryptRenewalService.Certificate;
                            });
                        })
                             .UseUrls(publicWebHostUrls)
                             .UseStartup <StartupPublicApp>()
                             .WithSettingDateTimeOffsetDelegate(getDateTimeOffset)
                             .ConfigureServices(services =>
                        {
                            services.AddSingleton <WebAppAndElmAppConfig>(
                                new WebAppAndElmAppConfig
                            {
                                WebAppConfiguration = webAppConfiguration,
                                ProcessEventInElmApp = serializedEvent =>
                                {
                                    lock (avoidConcurrencyLock)
                                    {
                                        var elmEventResponse =
                                            processVolatileRepresentation.ProcessElmAppEvent(
                                                processStoreWriter, serializedEvent);

                                        maintainStoreReductions();

                                        return elmEventResponse;
                                    }
                                },
                            });
                        })
                             .Build());
                    }

                    var webHost =
                        processVolatileRepresentation?.lastAppConfig?.appConfigComponent == null
                        ?
                        null
                        :
                        buildWebHost();

                    newPublicAppConfig.processVolatileRepresentation = processVolatileRepresentation;
                    newPublicAppConfig.webHost = webHost;

                    webHost?.StartAsync(appLifetime.ApplicationStopping).Wait();

                    logger.LogInformation("Started the public app at '" + string.Join(",", publicWebHostUrls) + "'.");

                    publicAppHost = newPublicAppConfig;
                }
            }

            startPublicApp();

            app.Run(async(context) =>
            {
                var syncIOFeature = context.Features.Get <Microsoft.AspNetCore.Http.Features.IHttpBodyControlFeature>();
                if (syncIOFeature != null)
                {
                    syncIOFeature.AllowSynchronousIO = true;
                }

                {
                    context.Request.Headers.TryGetValue("Authorization", out var requestAuthorizationHeaderValue);

                    AuthenticationHeaderValue.TryParse(
                        requestAuthorizationHeaderValue.FirstOrDefault(), out var requestAuthorization);

                    if (!(0 < adminPassword?.Length))
                    {
                        context.Response.StatusCode = 403;
                        await context.Response.WriteAsync("Forbidden");
                        return;
                    }

                    var buffer = new byte[400];

                    var decodedRequestAuthorizationParameter =
                        Convert.TryFromBase64String(requestAuthorization?.Parameter ?? "", buffer, out var bytesWritten) ?
                        Encoding.UTF8.GetString(buffer, 0, bytesWritten) : null;

                    var requestAuthorizationPassword =
                        decodedRequestAuthorizationParameter?.Split(':')?.ElementAtOrDefault(1);

                    if (!(string.Equals(adminPassword, requestAuthorizationPassword) &&
                          string.Equals("basic", requestAuthorization?.Scheme, StringComparison.OrdinalIgnoreCase)))
                    {
                        context.Response.StatusCode = 401;
                        context.Response.Headers.Add(
                            "WWW-Authenticate",
                            @"Basic realm=""" + context.Request.Host + @""", charset=""UTF-8""");
                        await context.Response.WriteAsync("Unauthorized");
                        return;
                    }
                }

                var requestPathIsDeployAppConfigAndInitElmAppState =
                    context.Request.Path.Equals(new PathString(PathApiDeployAppConfigAndInitElmAppState));

                if (context.Request.Path.Equals(new PathString(PathApiGetDeployedAppConfig)))
                {
                    if (!string.Equals(context.Request.Method, "get", StringComparison.InvariantCultureIgnoreCase))
                    {
                        context.Response.StatusCode = 405;
                        await context.Response.WriteAsync("Method not supported.");
                        return;
                    }

                    var appConfig = publicAppHost?.processVolatileRepresentation?.lastAppConfig?.appConfigComponent;

                    if (appConfig == null)
                    {
                        context.Response.StatusCode = 404;
                        await context.Response.WriteAsync("I did not find an app config in the history. Looks like no app was deployed so far.");
                        return;
                    }

                    var appConfigHashBase16 = CommonConversion.StringBase16FromByteArray(Composition.GetHash(appConfig));

                    var appConfigTree = Composition.ParseAsTree(appConfig).Ok;

                    var appConfigFilesNamesAndContents =
                        appConfigTree.EnumerateBlobsTransitive()
                        .Select(blobPathAndContent => (
                                    fileName: (IImmutableList <string>)blobPathAndContent.path.Select(name => Encoding.UTF8.GetString(name.ToArray())).ToImmutableList(),
                                    fileContent: blobPathAndContent.blobContent))
                        .ToImmutableList();

                    var appConfigZipArchive =
                        ZipArchive.ZipArchiveFromEntries(
                            ElmApp.ToFlatDictionaryWithPathComparer(appConfigFilesNamesAndContents));

                    context.Response.StatusCode            = 200;
                    context.Response.Headers.ContentLength = appConfigZipArchive.LongLength;
                    context.Response.Headers.Add("Content-Disposition", new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = appConfigHashBase16 + ".zip"
                    }.ToString());
                    context.Response.Headers.Add("Content-Type", new MediaTypeHeaderValue("application/zip").ToString());

                    await context.Response.Body.WriteAsync(appConfigZipArchive);
                    return;
                }

                if (requestPathIsDeployAppConfigAndInitElmAppState ||
                    context.Request.Path.Equals(new PathString(PathApiDeployAppConfigAndMigrateElmAppState)))
                {
                    if (!string.Equals(context.Request.Method, "post", StringComparison.InvariantCultureIgnoreCase))
                    {
                        context.Response.StatusCode = 405;
                        await context.Response.WriteAsync("Method not supported.");
                        return;
                    }

                    var memoryStream = new MemoryStream();
                    context.Request.Body.CopyTo(memoryStream);

                    var webAppConfigZipArchive = memoryStream.ToArray();

                    {
                        try
                        {
                            var filesFromZipArchive = ZipArchive.EntriesFromZipArchive(webAppConfigZipArchive).ToImmutableList();

                            if (filesFromZipArchive.Count < 1)
                            {
                                throw new Exception("Contains no files.");
                            }
                        }
                        catch (Exception e)
                        {
                            context.Response.StatusCode = 400;
                            await context.Response.WriteAsync("Malformed web app config zip-archive:\n" + e);
                            return;
                        }
                    }

                    var appConfigTree =
                        Composition.SortedTreeFromSetOfBlobsWithCommonFilePath(
                            ZipArchive.EntriesFromZipArchive(webAppConfigZipArchive));

                    var appConfigComponent = Composition.FromTree(appConfigTree);

                    processStoreWriter.StoreComponent(appConfigComponent);

                    var appConfigValueInFile =
                        new ProcessStoreSupportingMigrations.ValueInFileStructure
                    {
                        HashBase16 = CommonConversion.StringBase16FromByteArray(Composition.GetHash(appConfigComponent))
                    };

                    var compositionLogEvent =
                        ProcessStoreSupportingMigrations.CompositionLogRecordInFile.CompositionEvent.EventForDeployAppConfig(
                            appConfigValueInFile: appConfigValueInFile,
                            initElmAppState: requestPathIsDeployAppConfigAndInitElmAppState);

                    await attemptContinueWithCompositionEventAndSendHttpResponse(compositionLogEvent);
                    return;
                }

                if (context.Request.Path.StartsWithSegments(new PathString(PathApiRevertProcessTo),
                                                            out var revertToRemainingPath))
                {
                    if (!string.Equals(context.Request.Method, "post", StringComparison.InvariantCultureIgnoreCase))
                    {
                        context.Response.StatusCode = 405;
                        await context.Response.WriteAsync("Method not supported.");
                        return;
                    }

                    var processVersionId = revertToRemainingPath.ToString().Trim('/');

                    var processVersionComponent =
                        new ProcessStoreReaderInFileStore(processStoreFileStore).LoadComponent(processVersionId);

                    if (processVersionComponent == null)
                    {
                        context.Response.StatusCode = 404;
                        await context.Response.WriteAsync("Did not find process version '" + processVersionId + "'.");
                        return;
                    }

                    await attemptContinueWithCompositionEventAndSendHttpResponse(new CompositionLogRecordInFile.CompositionEvent
                    {
                        RevertProcessTo = new ValueInFileStructure {
                            HashBase16 = processVersionId
                        },
                    });
                    return;
                }

                if (context.Request.Path.Equals(new PathString(PathApiElmAppState)))
                {
                    if (publicAppHost == null)
                    {
                        context.Response.StatusCode = 400;
                        await context.Response.WriteAsync("Not possible because there is no app (state).");
                        return;
                    }

                    if (string.Equals(context.Request.Method, "get", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var processVolatileRepresentation = publicAppHost?.processVolatileRepresentation;

                        var components = new List <Composition.Component>();

                        var storeWriter = new DelegatingProcessStoreWriter
                        {
                            StoreComponentDelegate              = components.Add,
                            StoreProvisionalReductionDelegate   = _ => { },
                            SetCompositionLogHeadRecordDelegate = _ => throw new Exception("Unexpected use of interface."),
                        };

                        var reductionRecord =
                            processVolatileRepresentation?.StoreReductionRecordForCurrentState(storeWriter);

                        if (reductionRecord == null)
                        {
                            context.Response.StatusCode = 500;
                            await context.Response.WriteAsync("Not possible because there is no Elm app deployed at the moment.");
                            return;
                        }

                        var elmAppStateReductionHashBase16 = reductionRecord.elmAppState?.HashBase16;

                        var elmAppStateReductionComponent =
                            components.First(c => CommonConversion.StringBase16FromByteArray(Composition.GetHash(c)) == elmAppStateReductionHashBase16);

                        var elmAppStateReductionString =
                            Encoding.UTF8.GetString(elmAppStateReductionComponent.BlobContent.ToArray());

                        context.Response.StatusCode  = 200;
                        context.Response.ContentType = "application/json";
                        await context.Response.WriteAsync(elmAppStateReductionString);
                        return;
                    }
                    else
                    {
                        if (string.Equals(context.Request.Method, "post", StringComparison.InvariantCultureIgnoreCase))
                        {
                            var elmAppStateToSet = new StreamReader(context.Request.Body, System.Text.Encoding.UTF8).ReadToEndAsync().Result;

                            var elmAppStateComponent = Composition.Component.Blob(Encoding.UTF8.GetBytes(elmAppStateToSet));

                            var appConfigValueInFile =
                                new ProcessStoreSupportingMigrations.ValueInFileStructure
                            {
                                HashBase16 = CommonConversion.StringBase16FromByteArray(Composition.GetHash(elmAppStateComponent))
                            };

                            processStoreWriter.StoreComponent(elmAppStateComponent);

                            await attemptContinueWithCompositionEventAndSendHttpResponse(
                                new ProcessStoreSupportingMigrations.CompositionLogRecordInFile.CompositionEvent
                            {
                                SetElmAppState = appConfigValueInFile
                            });
                            return;
                        }
                        else
                        {
                            context.Response.StatusCode = 405;
                            await context.Response.WriteAsync("Method not supported.");
                            return;
                        }
                    }
                }

                if (context.Request.Path.Equals(new PathString(PathApiReplaceProcessHistory)))
                {
                    var memoryStream = new MemoryStream();
                    context.Request.Body.CopyTo(memoryStream);

                    var webAppConfigZipArchive = memoryStream.ToArray();

                    var replacementFiles =
                        ZipArchive.EntriesFromZipArchive(webAppConfigZipArchive)
                        .Select(filePathAndContent =>
                                (path: filePathAndContent.name.Split(new[] { '/', '\\' }).ToImmutableList()
                                 , content: filePathAndContent.content))
                        .ToImmutableList();

                    lock (avoidConcurrencyLock)
                    {
                        stopPublicApp();

                        foreach (var filePath in processStoreFileStore.ListFilesInDirectory(ImmutableList <string> .Empty).ToImmutableList())
                        {
                            processStoreFileStore.DeleteFile(filePath);
                        }

                        foreach (var replacementFile in replacementFiles)
                        {
                            processStoreFileStore.SetFileContent(replacementFile.path, replacementFile.content);
                        }

                        startPublicApp();
                    }

                    context.Response.StatusCode = 200;
                    await context.Response.WriteAsync("Successfully replaced the process history.");
                    return;
                }

                TruncateProcessHistoryReport truncateProcessHistory(TimeSpan productionBlockDurationLimit)
                {
                    var beginTime = CommonConversion.TimeStringViewForReport(DateTimeOffset.UtcNow);

                    var totalStopwatch = System.Diagnostics.Stopwatch.StartNew();

                    lock (avoidConcurrencyLock)
                    {
                        var storeReductionStopwatch = System.Diagnostics.Stopwatch.StartNew();

                        publicAppHost?.processVolatileRepresentation?.StoreReductionRecordForCurrentState(processStoreWriter);

                        storeReductionStopwatch.Stop();

                        var getFilesForRestoreStopwatch = System.Diagnostics.Stopwatch.StartNew();

                        var filesForRestore =
                            PersistentProcess.PersistentProcessVolatileRepresentation.GetFilesForRestoreProcess(
                                processStoreFileStore).files
                            .Select(filePathAndContent => filePathAndContent.Key)
                            .ToImmutableHashSet(EnumerableExtension.EqualityComparer <string>());

                        getFilesForRestoreStopwatch.Stop();

                        var deleteFilesStopwatch = System.Diagnostics.Stopwatch.StartNew();

                        int deletedFilesCount = 0;

                        foreach (var filePath in processStoreFileStore.ListFilesInDirectory(ImmutableList <string> .Empty))
                        {
                            if (filesForRestore.Contains(filePath))
                            {
                                continue;
                            }

                            if (productionBlockDurationLimit < totalStopwatch.Elapsed)
                            {
                                break;
                            }

                            processStoreFileStore.DeleteFile(filePath);
                            ++deletedFilesCount;
                        }

                        deleteFilesStopwatch.Stop();

                        return(new TruncateProcessHistoryReport
                        {
                            beginTime = beginTime,
                            deletedFilesCount = deletedFilesCount,
                            storeReductionTimeSpentMilli = (int)storeReductionStopwatch.ElapsedMilliseconds,
                            getFilesForRestoreTimeSpentMilli = (int)getFilesForRestoreStopwatch.ElapsedMilliseconds,
                            deleteFilesTimeSpentMilli = (int)deleteFilesStopwatch.ElapsedMilliseconds,
                            totalTimeSpentMilli = (int)totalStopwatch.ElapsedMilliseconds,
                        });
                    }
                }

                if (context.Request.Path.Equals(new PathString(PathApiTruncateProcessHistory)))
                {
                    var truncateResult = truncateProcessHistory(productionBlockDurationLimit: TimeSpan.FromMinutes(1));

                    context.Response.StatusCode  = 200;
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(truncateResult));
                    return;
                }

                if (context.Request.Path.StartsWithSegments(
                        new PathString(PathApiProcessHistoryFileStoreGetFileContent), out var remainingPathString))
                {
                    if (!string.Equals(context.Request.Method, "get", StringComparison.InvariantCultureIgnoreCase))
                    {
                        context.Response.StatusCode = 405;
                        await context.Response.WriteAsync("Method not supported.");
                        return;
                    }

                    var filePathInStore =
                        remainingPathString.ToString().Trim('/').Split('/').ToImmutableList();

                    var fileContent = processStoreFileStore.GetFileContent(filePathInStore);

                    if (fileContent == null)
                    {
                        context.Response.StatusCode = 404;
                        await context.Response.WriteAsync("No file at '" + string.Join("/", filePathInStore) + "'.");
                        return;
                    }

                    context.Response.StatusCode  = 200;
                    context.Response.ContentType = "application/octet-stream";
                    await context.Response.Body.WriteAsync(fileContent);
                    return;
                }

                (int statusCode, AttemptContinueWithCompositionEventReport responseReport)attemptContinueWithCompositionEvent(
                    ProcessStoreSupportingMigrations.CompositionLogRecordInFile.CompositionEvent compositionLogEvent)
                {
                    lock (avoidConcurrencyLock)
                    {
                        publicAppHost?.processVolatileRepresentation?.StoreReductionRecordForCurrentState(processStoreWriter);

                        var response =
                            AttemptContinueWithCompositionEventAndCommit(compositionLogEvent, processStoreFileStore);

                        startPublicApp();

                        return(response);
                    }
                }

                async System.Threading.Tasks.Task attemptContinueWithCompositionEventAndSendHttpResponse(
                    ProcessStoreSupportingMigrations.CompositionLogRecordInFile.CompositionEvent compositionLogEvent)
                {
                    var(statusCode, attemptReport) = attemptContinueWithCompositionEvent(compositionLogEvent);

                    var responseBodyString = Newtonsoft.Json.JsonConvert.SerializeObject(attemptReport);

                    context.Response.StatusCode = statusCode;
                    await context.Response.WriteAsync(responseBodyString);
                    return;
                }

                if (context.Request.Path.Equals(PathString.Empty) || context.Request.Path.Equals(new PathString("/")))
                {
                    context.Response.StatusCode = 200;
                    await context.Response.WriteAsync(
                        "Welcome to Elm-fullstack version " + Program.AppVersionId + ".\n" +
                        "To learn about this admin interface, see http://elm-fullstack.org/");
                    return;
                }

                context.Response.StatusCode = 404;
                await context.Response.WriteAsync("Not Found");
                return;
            });
        }
Esempio n. 9
0

        
Esempio n. 11
0
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime)
        {
            var consultClient = new ConsulClient(c =>
            {
                //consul地址
                c.Address = new Uri(configuration["ConsulSetting:ConsulAddress"]);
            });

            var registration = new AgentServiceRegistration()
            {
                ID      = Guid.NewGuid().ToString(),                             //服务实例唯一标识
                Name    = configuration["ConsulSetting:ServiceName"],            //服务名
                Address = configuration["ConsulSetting:ServiceIP"],              //服务ip
                Port    = int.Parse(configuration["ConsulSetting:ServicePort"]), //服务端口 因为要运行多个实例,端口不能在appsettings.json里配置,在docker容器运行时传入
                Check   = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),                                                                                                        //服务启动多久后注册
                    Interval = TimeSpan.FromSeconds(10),                                                                                                                             //健康检查时间间隔
                    HTTP     = $"http://{configuration["ConsulSetting:ServiceIP"]}:{configuration["ConsulSetting:ServicePort"]}{configuration["ConsulSetting:ServiceHealthCheck"]}", //健康检查地址
                    Timeout  = TimeSpan.FromSeconds(5)                                                                                                                               //超时时间
                },
            };

            //注册服务
            consultClient.Agent.ServiceRegister(registration).Wait();

            //应用程序终止时,取消注册
            lifetime.ApplicationStopping.Register(() =>
            {
                consultClient.Agent.ServiceDeregister(registration.ID).Wait();
            });

            return(app);
        }
Esempio n. 12
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            UpdateDatabase(app);

            app
            .UseLogging(Configuration, loggerFactory)
            .UseSwagger(Configuration)
            .UseConsul(lifetime)
            .UseCore();

            app.UseSubscribeAllEvents();
        }
 public ServiceBaseLifetime(IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
 {
     Environment         = environment ?? throw new ArgumentNullException(nameof(environment));
     ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
     Logger = loggerFactory.CreateLogger("ClickView.Extensions.Hosting.Lifetime");
 }
Esempio n. 14
0

        
Esempio n. 15
0
        /// <summary>
        /// 使用时钟
        /// </summary>
        /// <param name="builder">应用生成</param>
        /// <param name="service">服务提供者</param>
        /// <param name="lifetime">生命周期</param>
        /// <returns>应用生成</returns>
        public static IApplicationBuilder UseQuartz(this IApplicationBuilder builder, IServiceProvider service, IHostApplicationLifetime lifetime)
        {
            if (QuartzStaticConfig.JobHandleException == null)
            {
                QuartzStaticConfig.JobHandleException = service.GetService <IJobHandleException>();
            }
            var config = service.GetService <IConfiguration>();

            if (config != null)
            {
                QuartzStaticConfig.Config = config;
            }
            var log = service.GetService <ILogable>();

            if (log != null)
            {
                QuartzStaticConfig.Log = log;
            }

            ISchedulerWrap scheduler = null;

            lifetime.ApplicationStarted.Register(() =>
            {
                scheduler = service.GetService <ISchedulerWrap>();
                scheduler.StartAsync().Wait();
            });
            lifetime.ApplicationStopping.Register(() =>
            {
                scheduler.StopAsync().Wait();
            });


            return(builder);
        }
Esempio n. 16
0

        
Esempio n. 17
0
 public AppOneClient(IConfiguration configuration, IHostApplicationLifetime hostApplicationLifetime, ILogger <AppOneClient> logger)
     : base(new Uri(configuration.GetServiceUri("appone"), "/AppOneHub"), hostApplicationLifetime)
 {
     _logger = logger;
 }
Esempio n. 18
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="applicationLifetime"></param>
 public WorkflowUsersController(IHostApplicationLifetime applicationLifetime,
                                ExternalConnectorProvider externalConnectorProvider)
 {
     this.applicationLifetime       = applicationLifetime;
     this.externalConnectorProvider = externalConnectorProvider;
 }
Esempio n. 19
0
        // 服务注册

        public static void RegisterConsul(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime)
        {
            string serviceName = configuration.GetValue <string>("ServiceName");

            string serviceIP = configuration.GetValue <string>("ServiceIP");

            int prot = configuration.GetValue <int>("ServicePort");

            string consulClientUrl = configuration.GetValue <string>("ConsulAddress");

            string healthCheckRelativeUrl = configuration.GetValue <string>("ServiceHealthCheck");

            string Weight = configuration.GetValue <string>("Weight");

            var consulClient = new ConsulClient(x => {
                x.Address = new Uri($"{consulClientUrl}");
            });//请求注册的 Consul 地址

            //健康检查
            var httpCheck = new AgentServiceCheck()

            {
                //删除节点  最低配置60S
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60), //服务启动多久后注册

                Interval = TimeSpan.FromSeconds(10),                       //健康检查时间间隔,或者称为心跳间隔

                HTTP = $"{healthCheckRelativeUrl}",                        //健康检查地址

                Timeout = TimeSpan.FromSeconds(5),
            };

            // Register service with consul

            var registration = new AgentServiceRegistration()

            {
                Checks = new[] { httpCheck },

                ID = serviceName + "_" + prot,

                Name = serviceName,

                Address = serviceIP,

                Port = prot,

                Tags = new[] { Weight }//配置权重
            };

            consulClient.Agent.ServiceRegister(registration);//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)

            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
            });

            //return app;
        }
Esempio n. 20
0
 /// <summary>
 /// DI-Constructor of this LifetimeEventsHostedService
 /// </summary>
 /// <param name="logger">ILogger</param>
 /// <param name="hostApplicationLifetime">IHostApplicationLifetime</param>
 public LifetimeEventsHostedService(ILogger <LifetimeEventsHostedService> logger, IHostApplicationLifetime hostApplicationLifetime)
 {
     this.logger = logger;
     this.hostApplicationLifetime = hostApplicationLifetime;
     SomeStaticExampleClass.RegisteredServices.Add(nameof(LifetimeEventsHostedService));
 }
Esempio n. 21
0
 public TestHostedService(IHostApplicationLifetime lifetime)
 {
     _lifetime = lifetime;
 }
Esempio n. 22
0
        public static IApplicationBuilder UseConul(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime)
        {
            var client = new ConsulClient(options =>
            {
                // Consul客户端地址
                options.Address = new Uri(configuration["Consul:Address"]);
            });

            var registration = new AgentServiceRegistration
            {
                // 唯一Id
                ID = Guid.NewGuid().ToString(),
                // 服务名
                Name = configuration["Consul:Name"],
                // 服务绑定IP
                Address = configuration["Consul:Ip"],
                // 服务绑定端口
                Port  = Convert.ToInt32(configuration["Consul:Port"]),
                Check = new AgentServiceCheck
                {
                    // 服务启动多久后注册
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                    // 健康检查时间间隔
                    Interval = TimeSpan.FromSeconds(10),
                    // 健康检查地址
                    HTTP = $"http://{configuration["Consul:Ip"]}:{configuration["Consul:Port"]}{configuration["Consul:HealthCheck"]}",
                    // 超时时间
                    Timeout = TimeSpan.FromSeconds(5)
                }
            };

            // 注册服务
            client.Agent.ServiceRegister(registration).Wait();

            // 应用程序终止时,取消服务注册
            lifetime.ApplicationStopping.Register(() =>
            {
                client.Agent.ServiceDeregister(registration.ID).Wait();
            });

            return(app);
        }
Esempio n. 23
0
 public AppHost(ILogger <AppHost> logger, IHostApplicationLifetime appLifetime)
 {
     this.logger      = logger;
     this.appLifetime = appLifetime;
 }
Esempio n. 24
0
 public EarthToolService(ILogger <EarthToolService> logger, IHostApplicationLifetime appLifetime, IEnumerable <Command> commands)
 {
     _appLifetime = appLifetime;
     _logger      = logger;
     _cmdParser   = BuildParser(commands);
 }
Esempio n. 25
0

        
Esempio n. 26
0
 public WorkerService(ILogger <WorkerService> logger, IHostApplicationLifetime lifetime, IServiceScopeFactory scopeFactory)
 {
     _logger       = logger;
     _lifetime     = lifetime;
     _scopeFactory = scopeFactory;
 }
Esempio n. 27
0

        
Esempio n. 29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
                              IHostApplicationLifetime appLifetime, IOptions <Dictionary <string, string> > options,
                              IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting)
        {
            GlobalContext.HostingEnvironment = env;
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            // //  app.AddRazorRuntimeCompilation();
            //}
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            //    app.UseHsts();
            //}
            app.UseCookiePolicy();
            app.UseHttpsRedirection();

            //添加新的媒体文件类型,静态文件路由
            app.UseAtlassDefaultFiles(options);

            app.UseRouting();
            #region 自定义中间件
            app.UseMiddleware <AtlassHttpRequestMiddleware>();
            //app.UseMiddleware(typeof(AtlassExceptionMiddlerware));
            #endregion
            app.UseAuthorization();
            app.UseSession();

            app.UseEasyCachingResponseCaching();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(name: "areaRoute",
                                             pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            });

            //启动hangfire服务和面板
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                Queues = new[] { "default" }
            });
            //  app.UseHangfireDashboard();
            app.UseHangfireDashboard("/hangfire", new DashboardOptions()
            {
                Authorization = new[] { new HangfireAuthorizeFilter() }
            });


            //关于 UseSenparcGlobal() 的更多用法见 CO2NET Demo:
            //https://github.com/Senparc/Senparc.CO2NET/blob/master/Sample/Senparc.CO2NET.Sample.netcore/Startup.cs
            IRegisterService register = RegisterService.Start(senparcSetting.Value)
                                        .UseSenparcGlobal();

            register.ChangeDefaultCacheNamespace("DefaultCO2NETCache");
            register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value)

            #region 注册公众号(按需)
            //注册公众号(可注册多个)                                                -- DPBMARK MP
            .RegisterMpAccount(senparcWeixinSetting.Value, "doctor_platform_mp")     // DPBMARK_END //注册最新微信支付版本(V3)(可注册多个)
            .RegisterTenpayV3(senparcWeixinSetting.Value, "doctor_platform_tenpay"); //记录到同一个 SenparcWeixinSettingItem 对象中
            #endregion

            //应用程序启动后
            appLifetime.ApplicationStarted.Register(() => {
                try
                {
                    GlobalParamsDto.WebRoot = env.WebRootPath;
                    //SugarDbConn.DbConnectStr = this.Configuration.GetSection("DbConn:mysqlConn").Value;   //为数据库连接字符串赋值
                    GlobalParamsDto.Host = this.Configuration.GetSection("WebHost:Host").Value;

                    //初始化栏目相关的缓存
                    CmsCacheInit.Init();
                }
                catch (Exception e)
                {
                    LogNHelper.Exception(e);
                }
            });
        }
Esempio n. 30
0
        public static void WebStart(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
        {
            SignumServer.Start(app, env, typeof(Startup).Assembly);

            AuthServer.Start(app, () => Starter.Configuration.Value.AuthTokens, "IMPORTANT SECRET FROM Southwind. CHANGE THIS STRING!!!");
            CacheServer.Start(app);
            FilesServer.Start(app);
            UserQueryServer.Start(app);
            DashboardServer.Start(app);
            WordServer.Start(app);
            ExcelServer.Start(app);
            ChartServer.Start(app);
            MapServer.Start(app);
            ToolbarServer.Start(app);
            TranslationServer.Start(app,
                                    new AlreadyTranslatedTranslator(),
                                    new AzureTranslator(
                                        () => Starter.Configuration.Value.Translation.AzureCognitiveServicesAPIKey,
                                        () => Starter.Configuration.Value.Translation.AzureCognitiveServicesRegion),
                                    new DeepLTranslator(() => Starter.Configuration.Value.Translation.DeepLAPIKey)
                                    ); //TranslationServer
            SchedulerServer.Start(app, lifetime);
            ProcessServer.Start(app);
            MailingServer.Start(app);
            ProfilerServer.Start(app);
            DiffLogServer.Start(app);
            RestServer.Start(app);
            RestLogServer.Start(app);
            PredictorServer.Start(app);
            WorkflowServer.Start(app);
            DynamicServer.Start(app);

            OmniboxServer.Start(app,
                                new EntityOmniboxResultGenenerator(),
                                new DynamicQueryOmniboxResultGenerator(),
                                new ChartOmniboxResultGenerator(),
                                new DashboardOmniboxResultGenerator(DashboardLogic.Autocomplete),
                                new UserQueryOmniboxResultGenerator(UserQueryLogic.Autocomplete),
                                new UserChartOmniboxResultGenerator(UserChartLogic.Autocomplete),
                                new MapOmniboxResultGenerator(type => OperationLogic.TypeOperations(type).Any()),
                                new ReactSpecialOmniboxGenerator()
                                   //new HelpModuleOmniboxResultGenerator(),
                                ); //Omnibox

            SignumCultureSelectorFilter.GetCurrentCulture = (ctx) => GetCulture(ctx);
        }