public HealthCheck(Type source, HealthCheckResult type, String message, String wikiFragment = null) { Source = source; Type = type; Message = message; WikiUrl = MakeWikiUrl(wikiFragment ?? MakeWikiFragment(message)); }
public IHttpActionResult Get() { var result = new HealthCheckResult() {WebServiceOk = true}; var driveInfo = new DriveInfo("C"); double percentAvailable = ((double) driveInfo.TotalFreeSpace/(double) driveInfo.TotalSize); if (percentAvailable > .1) result.DiskSpaceCheckOk = true; return Ok(result); }
public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { return(Task.FromResult(HealthCheckResult.Healthy(description: "Build 1.0.0.0"))); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { RegisterAppInsights(services); // Add framework services. services.AddMvc(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }).AddControllersAsServices(); //Injecting Controllers themselves thru DIFor further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services services.Configure <MarketingSettings>(Configuration); ConfigureAuthService(services); services.AddHealthChecks(checks => { checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok"))); var accountName = Configuration.GetValue <string>("AzureStorageAccountName"); var accountKey = Configuration.GetValue <string>("AzureStorageAccountKey"); if (!string.IsNullOrEmpty(accountName) && !string.IsNullOrEmpty(accountKey)) { checks.AddAzureBlobStorageCheck(accountName, accountKey); } }); services.AddDbContext <MarketingContext>(options => { options.UseSqlServer(Configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); // Changing default behavior when client evaluation occurs to throw. // Default in EF Core would be to log a warning when client evaluation is performed. options.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)); //Check Client vs. Server evaluation: https://docs.microsoft.com/en-us/ef/core/querying/client-eval }); if (Configuration.GetValue <bool>("AzureServiceBusEnabled")) { services.AddSingleton <IServiceBusPersisterConnection>(sp => { var logger = sp.GetRequiredService <ILogger <DefaultServiceBusPersisterConnection> >(); var serviceBusConnectionString = Configuration["EventBusConnection"]; var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString); return(new DefaultServiceBusPersisterConnection(serviceBusConnection, logger)); }); } else { services.AddSingleton <IRabbitMQPersistentConnection>(sp => { var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >(); var factory = new ConnectionFactory() { HostName = Configuration["EventBusConnection"] }; if (!string.IsNullOrEmpty(Configuration["EventBusUserName"])) { factory.UserName = Configuration["EventBusUserName"]; } if (!string.IsNullOrEmpty(Configuration["EventBusPassword"])) { factory.Password = Configuration["EventBusPassword"]; } var retryCount = 5; if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"])) { retryCount = int.Parse(Configuration["EventBusRetryCount"]); } return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount)); }); } // Add framework services. services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "Marketing HTTP API", Version = "v1", Description = "The Marketing Service HTTP API", TermsOfService = "Terms Of Service" }); options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize", TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token", Scopes = new Dictionary <string, string>() { { "marketing", "Marketing API" } } }); options.OperationFilter <AuthorizeCheckOperationFilter>(); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); RegisterEventBus(services); services.AddTransient <IMarketingDataRepository, MarketingDataRepository>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddTransient <IIdentityService, IdentityService>(); services.AddOptions(); //configure autofac var container = new ContainerBuilder(); container.Populate(services); return(new AutofacServiceProvider(container.Build())); }
public static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration) { var hcBuilder = services.AddHealthChecks(); hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy()); hcBuilder .AddSqlServer( configuration["ConnectionString"], name: "OrderingDB-check", tags: new string[] { "orderingdb" }); var cacheID = "PubSubCache"; if (!string.IsNullOrEmpty(configuration["EventBusNCachID"])) { cacheID = configuration["EventBusNCachID"]; } var ipAddresses = configuration.GetValue <string>("PubSubCacheIPAddresses", "").Split('-'); if (ipAddresses.Length == 0) { throw new ArgumentNullException("No IP addresses given for Pub Sub cache"); } List <ServerInfo> servers = new List <ServerInfo>(); foreach (var ipAddress in ipAddresses) { servers.Add(new ServerInfo(ipAddress.Trim())); } hcBuilder .AddNCacheHealthCheck( cacheID: cacheID, name: "ordering-ncacheeventbus-check", failureStatus: HealthStatus.Unhealthy, tags: new string[] { "ncacheeventbus" }, cacheConnectionOptions: new CacheConnectionOptions { ServerList = servers }); if (configuration.GetValue <bool>("CachingEnabled")) { cacheID = "OrderingCache"; if (!string.IsNullOrEmpty(configuration["CacheID"])) { cacheID = configuration["CacheID"]; } ipAddresses = configuration.GetValue <string>("OrderingCacheIPAddresses", "").Split('-'); if (ipAddresses.Length == 0) { throw new ArgumentNullException("No IP addresses given for Ordering cache"); } servers = new List <ServerInfo>(); foreach (var ipAddress in ipAddresses) { servers.Add(new ServerInfo(ipAddress.Trim())); } hcBuilder .AddNCacheHealthCheck( cacheID: cacheID, name: "ordering-cache-check", failureStatus: HealthStatus.Unhealthy, tags: new string[] { "ncache" }, cacheConnectionOptions: new CacheConnectionOptions { ServerList = servers }); } return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy()) .AddSqlServer(Configuration["Database:ConnectionString"], tags: new[] { "services" }); services.AddCors(options => { options.AddPolicy( "CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); services.AddMvc(options => { options.CacheProfiles.Add( "Never", new CacheProfile { Location = ResponseCacheLocation.None, NoStore = true }); options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); options.Filters.Add <AtlasLogEnrichmentFilter>(); options.Filters.Add <ContextInformationFilter>(); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(opt => { opt.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; opt.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat; opt.SerializerSettings.DateParseHandling = DateParseHandling.DateTime; opt.SerializerSettings.Converters.Add(new TrimmingConverter()); }); // This code is added AFTER app.UseMvc(); otherwise it will not work. services.ConfigureInvalidModelStateResponseFactory(); // ApplicationInsights services.AddSingleton <ITelemetryInitializer, ServiceContextTelemetryIntitializer>(); services.AddSingleton <ITelemetryInitializer, UserTelemetryInitializer>(); services.AddApplicationInsightsTelemetry(Configuration); // Register Configuration objects services.Configure <DatabaseConfiguration>(Configuration.GetSection("Database")); services.Configure <ApplicationInsightsConfiguration>(Configuration.GetSection("ApplicationInsights")); services.AddApplicationInsightsKubernetesEnricher(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var tokenValidationParameters = new TokenValidationParameters { NameClaimType = AtlasClaimTypes.UniqueName }; // Add Authentication services. services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cfg => { cfg.Audience = Configuration["OAuth2:ClientId"]; cfg.Authority = Configuration["OAuth2:Authority"]; cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = tokenValidationParameters; }); // Adds a default implementation for IHttpContextAccessor services.AddHttpContextAccessor(); services.AddAtlasIdentityService(); // Add custom authorization services and the authorization handlers to the services services.AddAtlasAuthorizationServices(Configuration) .AddAtlasPrivilegeAuthorizationHandlers(); services.AddReportingAuthorizationPolicies(); // Register Hosted Services services.AddScoped <IDapperContext, DapperContext>(); services.AddScoped <IUnitOfWork, DapperUnitOfWork>(); services.AddScoped <IContextInformation, ContextInformation>(); // Register all Handlers and Pre/PostProcessors in a given assembly. services.AddMediatR(typeof(Startup).Assembly); Mapper.Initialize(cfg => cfg.AddProfile <MappingProfile>()); services.AddAutoMapper(); if (Configuration["SwaggerGen"].Equals(bool.TrueString, StringComparison.InvariantCultureIgnoreCase)) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Reporting API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); c.DescribeAllParametersInCamelCase(); c.OperationFilter <AddResponseHeadersFilter>(); // To use the [SwaggerResponseHeader] attribute c.DocumentFilter <LowercaseDocumentFilter>(); // To lowercase the URIs // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); var security = new System.Collections.Generic.Dictionary <string, System.Collections.Generic.IEnumerable <string> > { { "Bearer", Array.Empty <string>() }, }; c.AddSecurityRequirement(security); }); } var containerBuilder = new ContainerBuilder(); containerBuilder.Populate(services); containerBuilder.RegisterModule(new MediatorModule()); // Register types from LDC.Atlas.Application.Common containerBuilder.RegisterModule(new Atlas.Application.Common.MediatorModule()); return(new AutofacServiceProvider(containerBuilder.Build())); }
private static IWebHostBuilder CustomBuilder() { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .Build(); return(new WebHostBuilder() // .UseUrls("http://wilsoft.site") //.UseSetting("http_port", "80") .UseUrls("http://*:12416") //.UseSetting("http_port", "80") .UseKestrel() .UseIISIntegration() .UseSerilog() .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); logging.SetMinimumLevel(LogLevel.Warning); logging.AddEventLog(); logging.AddEventSourceLogger(); logging.AddFilter("System", LogLevel.Debug) .AddFilter <DebugLoggerProvider>("Microsoft", LogLevel.Trace); }) .UseConfiguration(config) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .UseHealthEndpoints(options => { }) .ConfigureHealth( builder => { builder.OutputHealth.AsPlainText(); }) .ConfigureHealthWithDefaults( builder => { builder.HealthChecks.AddCheck("DatabaseConnected", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("Database Connection OK"))); builder.HealthChecks.AddPingCheck("google ping", "google.com", TimeSpan.FromSeconds(10)); }) .ConfigureAppHealthHostingConfiguration(options => { //options.AllEndpointsPort = 1111; //options.HealthEndpoint = "app-metrics-health"; }) .UseMetricsEndpoints() .UseHealth() .UseMetricsWebTracking() .UseMetrics() .ConfigureKestrel((context, options) => { //options.Listen(IPAddress.Any, 80); //options.Listen(IPAddress.Any, 1994); options.Limits.MaxConcurrentConnections = 100; options.Limits.MaxConcurrentUpgradedConnections = 100; //options.Limits.MaxRequestBodySize = 10 * 1024; //options.Limits.MinRequestBodyDataRate = // new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10)); //options.Limits.MinResponseDataRate = // new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10)); //options.Listen(IPAddress.Loopback, 1994); //options.Listen(IPAddress.Loopback, 5001, listenOptions => //{ // listenOptions.UseHttps("testCert.pfx", "testPassword"); //}); //options.ConfigureHttpsDefaults(httpsOptions => //{ // // certificate is an X509Certificate2 // //httpsOptions.ServerCertificate = certificate; //}); //options.Configure(context.Configuration.GetSection("Kestrel")) // .Endpoint("HTTPS", opt => // { // opt.HttpsOptions.SslProtocols = SslProtocols.Tls12; // }); // options.ListenUnixSocket("/tmp/kestrel-test.sock"); // options.ListenUnixSocket("/tmp/kestrel-test.sock", listenOptions => // { // listenOptions.UseHttps("testCert.pfx", "testpassword"); // }); //options.ListenAnyIP(5005, listenOptions => //{ // listenOptions.Protocols = HttpProtocols.Http1AndHttp2; // //listenOptions.ConnectionAdapters.Add(new TlsFilterAdapter()); // listenOptions.UseHttps(httpsOptions => // { // //var localhostCert = CertificateLoader.LoadFromStoreCert( // // "localhost", "My", StoreLocation.CurrentUser, // // allowInvalid: true); // //var exampleCert = CertificateLoader.LoadFromStoreCert( // // "example.com", "My", StoreLocation.CurrentUser, // // allowInvalid: true); // //var subExampleCert = CertificateLoader.LoadFromStoreCert( // // "sub.example.com", "My", StoreLocation.CurrentUser, // // allowInvalid: true); // //var certs = new Dictionary<string, X509Certificate2>( // // StringComparer.OrdinalIgnoreCase); // //certs["localhost"] = localhostCert; // //certs["example.com"] = exampleCert; // //certs["sub.example.com"] = subExampleCert; // //httpsOptions.ServerCertificateSelector = (connectionContext, name) => // //{ // // if (name != null && certs.TryGetValue(name, out var cert)) // // { // // return cert; // // } // // return exampleCert; // //}; // }); //}); options.AllowSynchronousIO = true; // options.Limits.Http2.InitialStreamWindowSize = 98304; // options.Limits.Http2.InitialConnectionWindowSize = 131072; // options.Limits.Http2.MaxFrameSize = 16384; // options.Limits.Http2.MaxRequestHeaderFieldSize = 8192; // options.Limits.Http2.HeaderTableSize = 4096; // options.Limits.Http2.MaxStreamsPerConnection = 100; //options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(15); //options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(2); })); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IReceiveFromHubService>(new ReceiveFromHubService()); services.AddMvc(config => { if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"])) { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); } }); // Other ConfigureServices() code... services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "JAG LCRB SPD Transfer Service", Version = "v1" }); }); services.AddIdentity <IdentityUser, IdentityRole>() .AddDefaultTokenProviders(); //if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"])) //{ // // Configure JWT authentication // services.AddAuthentication(o => // { // o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; // o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; // }).AddJwtBearer(o => // { // o.SaveToken = true; // o.RequireHttpsMetadata = false; // o.TokenValidationParameters = new TokenValidationParameters() // { // RequireExpirationTime = false, // ValidIssuer = Configuration["JWT_VALID_ISSUER"], // ValidAudience = Configuration["JWT_VALID_AUDIENCE"], // IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT_TOKEN_KEY"])) // }; // }); //} services.AddHangfire(config => { // Change this line if you wish to have Hangfire use persistent storage. config.UseMemoryStorage(); // enable console logs for jobs config.UseConsole(); }); // health checks. services.AddHealthChecks(checks => { checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok"))); }); }
public void Should_append_resolved_health_checks_to_those_explicitly_registered() { // Arrange var services = new ServiceCollection(); services.AddSingleton <IDatabase, Database>(); // Act var unused = new HealthBuilder() .HealthChecks.AddCheck("inline", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy())) .HealthChecks.RegisterFromAssembly(services, _fixture.DependencyContext) .BuildAndAddTo(services); var provider = services.BuildServiceProvider(); var health = provider.GetRequiredService <IHealth>(); // Assert health.Checks.Count().Should().Be(3); health.Checks.FirstOrDefault(c => c.Name == "DatabaseCheck").Should().NotBeNull(); health.Checks.FirstOrDefault(c => c.Name == "Referenced Health Check").Should().NotBeNull(); health.Checks.FirstOrDefault(c => c.Name == "inline").Should().NotBeNull(); }
public void Can_build_and_add_health_to_service_collection() { // Arrange const string checkName = "inline healthy"; var services = new ServiceCollection(); var health = new HealthBuilder(). HealthChecks.AddCheck(checkName, () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy())) .Build(); // Act services.AddHealth(health); var provider = services.BuildServiceProvider(); var resolvedHealth = provider.GetRequiredService <IHealth>(); // Assert resolvedHealth.Checks.Count().Should().Be(1); resolvedHealth.Checks.Single().Name.Should().Be(checkName); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddSerilogging(this.Configuration); var jsonSerializerOptions = new JsonSerializerOptions() { IgnoreNullValues = !String.IsNullOrWhiteSpace(this.Configuration["Serialization:Json:IgnoreNullValues"]) && Boolean.Parse(this.Configuration["Serialization:Json:IgnoreNullValues"]), PropertyNameCaseInsensitive = !String.IsNullOrWhiteSpace(this.Configuration["Serialization:Json:PropertyNameCaseInsensitive"]) && Boolean.Parse(this.Configuration["Serialization:Json:PropertyNameCaseInsensitive"]), PropertyNamingPolicy = this.Configuration["Serialization:Json:PropertyNamingPolicy"] == "CamelCase" ? JsonNamingPolicy.CamelCase : null, WriteIndented = !string.IsNullOrWhiteSpace(this.Configuration["Serialization:Json:WriteIndented"]) && Boolean.Parse(this.Configuration["Serialization:Json:WriteIndented"]) }; services.AddMapster(jsonSerializerOptions, options => { options.Default.IgnoreNonMapped(true); options.Default.IgnoreNullValues(true); options.AllowImplicitDestinationInheritance = true; options.AllowImplicitSourceInheritance = true; options.Default.UseDestinationValue(member => member.SetterModifier == AccessModifier.None && member.Type.IsGenericType && member.Type.GetGenericTypeDefinition() == typeof(ICollection <>)); }); services.Configure <JsonSerializerOptions>(options => { options.IgnoreNullValues = jsonSerializerOptions.IgnoreNullValues; options.PropertyNameCaseInsensitive = jsonSerializerOptions.PropertyNameCaseInsensitive; options.PropertyNamingPolicy = jsonSerializerOptions.PropertyNamingPolicy; options.WriteIndented = jsonSerializerOptions.WriteIndented; options.Converters.Add(new JsonStringEnumConverter()); options.Converters.Add(new Int32ToStringJsonConverter()); }); services.Configure <Core.Http.Configuration.AuthClientOptions>(this.Configuration.GetSection("Keycloak")); services.Configure <Core.Http.Configuration.OpenIdConnectOptions>(this.Configuration.GetSection("Keycloak:OpenIdConnect")); services.Configure <Keycloak.Configuration.KeycloakOptions>(this.Configuration.GetSection("Keycloak")); services.Configure <Pims.Dal.PimsOptions>(this.Configuration.GetSection("Pims")); services.AddOptions(); services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = jsonSerializerOptions.IgnoreNullValues; options.JsonSerializerOptions.PropertyNameCaseInsensitive = jsonSerializerOptions.PropertyNameCaseInsensitive; options.JsonSerializerOptions.PropertyNamingPolicy = jsonSerializerOptions.PropertyNamingPolicy; options.JsonSerializerOptions.WriteIndented = jsonSerializerOptions.WriteIndented; options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.Converters.Add(new Int32ToStringJsonConverter()); options.JsonSerializerOptions.Converters.Add(new GeometryJsonConverter()); }); services.AddMvcCore() .AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = jsonSerializerOptions.IgnoreNullValues; options.JsonSerializerOptions.PropertyNameCaseInsensitive = jsonSerializerOptions.PropertyNameCaseInsensitive; options.JsonSerializerOptions.PropertyNamingPolicy = jsonSerializerOptions.PropertyNamingPolicy; options.JsonSerializerOptions.WriteIndented = jsonSerializerOptions.WriteIndented; options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.Converters.Add(new Int32ToStringJsonConverter()); options.JsonSerializerOptions.Converters.Add(new GeometryJsonConverter()); }); services.AddRouting(options => { options.ConstraintMap.Add("pid", typeof(PidConstraint)); }); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { var key = Encoding.ASCII.GetBytes(Configuration["Keycloak:Secret"]); options.RequireHttpsMetadata = false; options.Authority = Configuration["Keycloak:Authority"]; options.Audience = Configuration["Keycloak:Audience"]; options.SaveToken = true; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuerSigningKey = true, ValidateIssuer = false, ValidateAudience = false }; if (key.Length > 0) { options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(key); } options.Events = new JwtBearerEvents() { OnTokenValidated = context => { return(Task.CompletedTask); }, OnAuthenticationFailed = context => { context.NoResult(); context.Response.StatusCode = StatusCodes.Status401Unauthorized; throw new AuthenticationException("Failed to authenticate", context.Exception); }, OnForbidden = context => { return(Task.CompletedTask); } }; }); services.AddAuthorization(options => { options.AddPolicy("Administrator", policy => policy.Requirements.Add(new RealmAccessRoleRequirement("administrator"))); }); // Generate the database connection string. var csBuilder = new SqlConnectionStringBuilder(this.Configuration.GetConnectionString("PIMS")); var pwd = this.Configuration["DB_PASSWORD"]; if (!String.IsNullOrEmpty(pwd)) { csBuilder.Password = pwd; } services.AddHttpClient(); services.AddPimsContext(this.Environment, csBuilder.ConnectionString); services.AddPimsServices(); services.AddPimsKeycloakService(); services.AddGeocoderService(this.Configuration.GetSection("Geocoder")); // TODO: Determine if a default value could be used instead. services.AddChesService(this.Configuration.GetSection("Ches")); services.AddNotificationsService(); services.AddSingleton <IAuthorizationHandler, RealmAccessRoleHandler>(); services.AddTransient <IClaimsTransformation, KeycloakClaimTransformer>(); services.AddHttpContextAccessor(); services.AddTransient <ClaimsPrincipal>(s => s.GetService <IHttpContextAccessor>().HttpContext.User); services.AddScoped <IProxyRequestClient, ProxyRequestClient>(); services.AddScoped <IOpenIdConnectRequestClient, OpenIdConnectRequestClient>(); services.AddHealthChecks() .AddCheck("liveliness", () => HealthCheckResult.Healthy()) .AddSqlServer(csBuilder.ConnectionString, tags: new[] { "services" }); services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.ApiVersionReader = new HeaderApiVersionReader("api-version"); // options.DefaultApiVersion = new ApiVersion(1, 0); }); services.AddVersionedApiExplorer(options => { // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service // note: the specified format code will format the version as "'v'major[.minor][-status]" options.GroupNameFormat = "'v'VVV"; // note: this option is only necessary when versioning by url segment. the SubstitutionFormat // can also be used to control the format of the API version in route templates options.SubstituteApiVersionInUrl = true; }); services.AddTransient <IConfigureOptions <SwaggerGenOptions>, Helpers.Swagger.ConfigureSwaggerOptions>(); services.AddSwaggerGen(options => { options.EnableAnnotations(false, true); options.CustomSchemaIds(o => o.FullName); options.OperationFilter <Helpers.Swagger.SwaggerDefaultValues>(); options.DocumentFilter <Helpers.Swagger.SwaggerDocumentFilter>(); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Name = "Authorization", In = ParameterLocation.Header, Description = "Please enter into field the word 'Bearer' following by space and JWT", Type = SecuritySchemeType.ApiKey }); options.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List <string>() } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); options.IncludeXmlComments(xmlPath); }); services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.All; options.AllowedHosts = this.Configuration.GetValue <string>("AllowedHosts")?.Split(';').ToList <string>(); }); }
public void ConfigureServices(IServiceCollection services) { var redisConnectionString = configuration.GetValue <string>("REDIS_CONNECTIONSTRING", null); var dataProtectionPath = configuration.GetValue <string>("KEY_RING_PATH", null); var applicationName = configuration.GetValue("APP_NAME", Assembly.GetExecutingAssembly().GetName().Name); if (!string.IsNullOrEmpty(redisConnectionString)) { Log.Information("Configuring {0} to use Redis cache", applicationName); services.AddStackExchangeRedisCache(options => { options.Configuration = redisConnectionString; }); services.AddDataProtection() .SetApplicationName(applicationName) .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConnectionString), "data-protection-keys"); } else { Log.Information("Configuring {0} to use in-memory cache", applicationName); services.AddDistributedMemoryCache(); var dpBuilder = services.AddDataProtection() .SetApplicationName(applicationName); if (!string.IsNullOrEmpty(dataProtectionPath)) { dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(dataProtectionPath)); } } services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { configuration.GetSection("jwt").Bind(options); options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidateIssuer = true, RequireSignedTokens = true, RequireAudience = true, RequireExpirationTime = true, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(60), NameClaimType = ClaimTypes.Upn, RoleClaimType = ClaimTypes.Role, ValidateActor = true, ValidateIssuerSigningKey = true, }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = async c => { await Task.CompletedTask; var logger = c.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger("JwtBearer"); logger.LogError(c.Exception, $"Error authenticating token"); }, OnTokenValidated = async c => { await Task.CompletedTask; var logger = c.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger("JwtBearer"); logger.LogDebug("Token validated for {0}", c.ToString()); // var userService = c.HttpContext.RequestServices.GetRequiredService<IUserService>(); // c.Principal = await userService.CreatePrincipalForUser(c.Principal); // logger.LogDebug("Token validated for {0}", c.Principal.Identity.Name); } }; options.Validate(); }); services.AddAuthorization(options => { options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy => { policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser(); }); options.DefaultPolicy = options.GetPolicy(JwtBearerDefaults.AuthenticationScheme); }); services.AddControllers(options => { options.Filters.Add(new HttpResponseExceptionFilter()); options.Filters.Add(new AuthorizeFilter()); }); services.AddHealthChecks() .AddCheck("Suppliers API ready hc", () => HealthCheckResult.Healthy("API ready"), new[] { HealthCheckReadyTag }) .AddCheck("Suppliers live hc", () => HealthCheckResult.Healthy("API alive"), new[] { HealthCheckAliveTag }); services.AddOpenApiDocument(); services.Configure <OpenApiDocumentMiddlewareSettings>(options => { options.Path = "/api/swagger/{documentName}/swagger.json"; }); services.Configure <SwaggerUi3Settings>(options => { options.Path = "/api/swagger"; options.DocumentPath = "/api/swagger/{documentName}/swagger.json"; }); services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.All; var knownNetworks = configuration.GetValue("KNOWN_NETWORKS", "::ffff:172.51.0.0/16").Split(';'); foreach (var knownNetwork in knownNetworks) { options.KnownNetworks.Add(ParseNetworkFromString(knownNetwork)); } }); services.AddDistributedMemoryCache(); services.AddSingleton <IFileSystem, FileSystem>(); services.AddTransient <ICountriesListProvider, ListsProvider>(); services.AddTransient <IStateProvincesListProvider, ListsProvider>(); services.AddTransient <IJurisdictionsListProvider, ListsProvider>(); services.AddTransient <ISupportsListProvider, ListsProvider>(); services.AddTransient <IListsGateway, DynamicsListsGateway>(); services.Configure <FileBasedCachedListsOptions>(configuration.GetSection("Dynamics:Cache")); services.AddTransient <IListsRepository, FileBasedCachedListsRepository>(); services.Configure <ADFSTokenProviderOptions>(configuration.GetSection("Dynamics:ADFS")); services.AddADFSTokenProvider(); services.AddTransient <ISubmissionRepository, SubmissionRepository>(); services.AddTransient <IReferenceNumberGenerator, ReferenceNumberGenerator>(); services.AddTransient <ISubmissionDynamicsCustomActionHandler, SubmissionDynamicsCustomActionHandler>(); services.AddScoped(sp => { var dynamicsApiEndpoint = configuration.GetValue <string>("Dynamics:DynamicsApiEndpoint"); var tokenProvider = sp.GetRequiredService <ITokenProvider>(); return(new CRMWebAPI(new CRMWebAPIConfig { APIUrl = dynamicsApiEndpoint, GetAccessToken = async(s) => await tokenProvider.AcquireToken() })); }); }
public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { try { using (var connection = new SqlConnection(_connection)) { await connection.OpenAsync(cancellationToken); var command = connection.CreateCommand(); command.CommandText = "select count(id) from produtos"; return(Convert.ToInt32(await command.ExecuteScalarAsync(cancellationToken)) < 0 ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy()); } } catch (System.Exception) { return(HealthCheckResult.Unhealthy()); } }
protected override async Task <HealthCheckResult> ProcessHealthCheck(HealthCheckContext context) { var response = await _amazonSqs.GetQueueUrlAsync(_queueUrl); return(!string.IsNullOrEmpty(response.QueueUrl) ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy()); }
public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { var isOk = await _advertStorageService.CheckHealthAsync(); return(isOk ? HealthCheckResult.Healthy("A healthy result.") : HealthCheckResult.Unhealthy("An unhealthy result.")); }
public async Task Can_register_inline_health_checks() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton <IDatabase, Database>(); services .AddHealthChecks() .AddChecks( factory => { factory.Register("DatabaseConnected", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("Database Connection OK"))); }); var provider = services.BuildServiceProvider(); var healthProvider = provider.GetRequiredService <IProvideHealth>(); var result = await healthProvider.ReadStatusAsync(); result.HasRegisteredChecks.Should().BeTrue(); result.Results.Should().HaveCount(2); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); options.Filters.Add(typeof(ValidateModelStateFilter)); }).AddControllersAsServices(); ConfigureAuthService(services); services.AddHealthChecks(checks => { checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok")), TimeSpan.Zero //No cache for this HealthCheck, better just for demos ); }); services.Configure <BasketSettings>(Configuration); //By connecting here we are making sure that our service //cannot start until redis is ready. This might slow down startup, //but given that there is a delay on resolving the ip address //and then creating the connection it seems reasonable to move //that cost to startup instead of having the first request pay the //penalty. services.AddSingleton <ConnectionMultiplexer>(sp => { var settings = sp.GetRequiredService <IOptions <BasketSettings> >().Value; var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true); configuration.ResolveDns = true; return(ConnectionMultiplexer.Connect(configuration)); }); services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new Info { Title = "Basket HTTP API", Version = "v1", Description = "The Basket Service HTTP API", TermsOfService = "Terms Of Service" }); options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize", TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token", Scopes = new Dictionary <string, string>() { { "basket", "Basket API" } } }); options.OperationFilter <AuthorizeCheckOperationFilter>(); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddTransient <IBasketRepository, RedisBasketRepository>(); services.AddTransient <IIdentityService, IdentityService>(); services.AddOptions(); var containerBuilder = new ContainerBuilder(); containerBuilder.Populate(services); // NServiceBus var container = RegisterEventBus(containerBuilder); return(new AutofacServiceProvider(container)); }
public IServiceProvider ConfigureServices(IServiceCollection services) { RegisterAppInsights(services); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); })); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); services.Configure <AppSettings>(Configuration); if (Configuration.GetValue <string>("IsClusterEnv") == bool.TrueString) { services.AddDataProtection(opts => { opts.ApplicationDiscriminator = "fee.studentidentity"; }) .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(Configuration["DPConnectionString"]), "DataProtection-Keys"); } services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy()) .AddSqlServer(Configuration["ConnectionString"], name: "StudentIdentityDB-check", tags: new string[] { "StudentIdentityDB" }); services.AddTransient <ILoginService <ApplicationUser>, EFLoginService>(); services.AddTransient <IRedirectService, RedirectService>(); var connectionString = Configuration["ConnectionString"]; var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; services.AddIdentityServer(x => { x.IssuerUri = "null"; x.Authentication.CookieLifetime = TimeSpan.FromHours(2); }) .AddDevspacesIfNeeded(Configuration.GetValue("EnableDevspaces", false)) .AddSigningCredential(Certificate.Get()) .AddAspNetIdentity <ApplicationUser>() .AddConfigurationStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(migrationsAssembly); sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }) .AddOperationalStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(migrationsAssembly); sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }) .Services.AddTransient <IProfileService, ProfileService>(); services.AddControllers(); services.AddControllersWithViews(); services.AddRazorPages(); var container = new ContainerBuilder(); container.Populate(services); return(new AutofacServiceProvider(container.Build())); }
public Task <HealthCheckResult> CheckHealthAsync( HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken()) { return(Task.FromResult(HealthCheckResult.Degraded("NOT WELL MICROSERVICE"))); }
public async Task HealthService_RemoveDefault_DefaultNotFound() { // Arrange var healthCheckResult = new HealthCheckResult(HealthStatus.Healthy); var services = new ServiceCollection(); services.AddLogging(); services .AddGrpcHealthChecks(o => { o.Services.Clear(); o.Services.MapService("new", result => true); }) .AddAsyncCheck("", () => Task.FromResult(healthCheckResult)); services.Configure <HealthCheckPublisherOptions>(o => { o.Delay = TimeSpan.FromSeconds(1); o.Period = TimeSpan.FromSeconds(1); }); HealthReport?report = null; var syncPoint = new SyncPoint(runContinuationsAsynchronously: true); var testPublisher = new TestHealthCheckPublisher(); testPublisher.OnHealthReport = async r => { report = r; await syncPoint.WaitToContinue(); }; services.AddSingleton <IHealthCheckPublisher>(testPublisher); var serviceProvider = services.BuildServiceProvider(); var healthService = serviceProvider.GetRequiredService <HealthServiceImpl>(); var hostedService = serviceProvider.GetServices <IHostedService>().Single(); async Task CheckForStatusAsync(string service, HealthCheckResponse.Types.ServingStatus status) { var context = new TestServerCallContext(DateTime.MaxValue, CancellationToken.None); var result = await healthService !.Check(new HealthCheckRequest() { Service = service }, context); Assert.AreEqual(status, result.Status); } // Act await hostedService.StartAsync(CancellationToken.None); // Assert try { await syncPoint.WaitForSyncPoint().DefaultTimeout(); Assert.AreEqual(HealthStatus.Healthy, report !.Status); syncPoint.Continue(); await ExceptionAssert.ThrowsAsync <RpcException>(() => CheckForStatusAsync(service : "", HealthCheckResponse.Types.ServingStatus.ServiceUnknown)); await CheckForStatusAsync(service : "new", HealthCheckResponse.Types.ServingStatus.Serving); } finally { await hostedService.StopAsync(CancellationToken.None); } }
/// <summary> /// Loads the specified settings, overwriting existing settings. /// </summary> /// <param name="updatedEndPointsResult"></param> /// this <see cref="RemoteHostPool"/>. /// <exception cref="ArgumentNullException">Thrown when </exception> /// <exception cref="EnvironmentException"></exception> private void ReloadEndpoints(EndPointsResult updatedEndPointsResult) { lock (_lock) { try { var updatedEndPoints = updatedEndPointsResult.EndPoints; if (updatedEndPoints.Any() == false) { Health.SetHealthFunction(() => { var config = GetConfig(); if (IsHealthCheckSuppressed(config)) { return(HealthCheckResult.Healthy($"No endpoints were discovered from source '{config.Source}' but the remote service was not in use for more than {config.SuppressHealthCheckAfterServiceUnused?.TotalSeconds} seconds.")); } else { return(HealthCheckResult.Unhealthy($"No endpoints were discovered from source '{config.Source}'.")); } }); EndPointsResult = updatedEndPointsResult; ReachableHosts = new List <RemoteHost>(); UnreachableHosts = new List <RemoteHost>(); } else { if (EndPoints != null) { foreach (var removedEndPoint in EndPoints.Except(updatedEndPoints)) { ReachableHosts.SingleOrDefault(h => h.Equals(removedEndPoint))?.StopMonitoring(); ReachableHosts.RemoveAll(h => h.Equals(removedEndPoint)); UnreachableHosts.RemoveAll(h => h.Equals(removedEndPoint)); } } var newHosts = updatedEndPoints .Except(EndPoints ?? Enumerable.Empty <EndPoint>()) .Select(ep => new RemoteHost(ep.HostName, this, _lock, ep.Port)); ReachableHosts.AddRange(newHosts); EndPointsResult = updatedEndPointsResult; Counter = (ulong)_random.Next(0, ReachableHosts.Count); Health.SetHealthFunction(CheckHealth); } _endPointsChanged.Post(EndPointsResult); } catch (Exception ex) { Log.Warn("Failed to process newly discovered endpoints", exception: ex); Health.SetHealthFunction(() => HealthCheckResult.Unhealthy("Failed to process newly discovered endpoints: " + HealthMonitor.GetMessages(ex))); } } }
public async Task HealthService_Watch_WriteResults() { // Arrange var healthCheckResult = new HealthCheckResult(HealthStatus.Healthy); var services = new ServiceCollection(); services.AddLogging(); services.AddGrpcHealthChecks().AddAsyncCheck( "", () => Task.FromResult(healthCheckResult), new string[] { "sample" }); services.Configure <HealthCheckPublisherOptions>(o => { o.Delay = TimeSpan.FromSeconds(1); o.Period = TimeSpan.FromSeconds(1); }); var serviceProvider = services.BuildServiceProvider(); var healthService = serviceProvider.GetRequiredService <HealthServiceImpl>(); var hostedService = serviceProvider.GetServices <IHostedService>().Single(); HealthCheckResponse?response = null; var syncPoint = new SyncPoint(runContinuationsAsynchronously: true); var testServerStreamWriter = new TestServerStreamWriter <HealthCheckResponse>(); testServerStreamWriter.OnWriteAsync = async message => { response = message; await syncPoint.WaitToContinue(); }; var cts = new CancellationTokenSource(); var callTask = healthService.Watch( new HealthCheckRequest(), testServerStreamWriter, new TestServerCallContext(DateTime.MaxValue, cts.Token)); // Act await hostedService.StartAsync(CancellationToken.None); // Assert try { await syncPoint.WaitForSyncPoint().DefaultTimeout(); Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.ServiceUnknown, response !.Status); syncPoint.Continue(); healthCheckResult = new HealthCheckResult(HealthStatus.Unhealthy); syncPoint = new SyncPoint(runContinuationsAsynchronously: true); await syncPoint.WaitForSyncPoint().DefaultTimeout(); Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.NotServing, response !.Status); syncPoint.Continue(); healthCheckResult = new HealthCheckResult(HealthStatus.Healthy); syncPoint = new SyncPoint(runContinuationsAsynchronously: true); await syncPoint.WaitForSyncPoint().DefaultTimeout(); Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.Serving, response !.Status); syncPoint.Continue(); cts.Cancel(); await callTask.DefaultTimeout(); } finally { await hostedService.StopAsync(CancellationToken.None); } }
public async ValueTask <IHealthCheckResult> CheckAsync(CancellationToken cancellationToken = default) { var isStorageOk = await service.CheckHealthAsync(); return(HealthCheckResult.FromStatus(isStorageOk ? CheckStatus.Healthy : CheckStatus.Unhealthy, string.Empty)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // add singleton to allow Controllers to query the Request object services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); // determine if we wire up Dynamics. if (!string.IsNullOrEmpty(Configuration["DYNAMICS_ODATA_URI"])) { SetupDynamics(services); } // Add a memory cache services.AddMemoryCache(); // for security reasons, the following headers are set. services.AddMvc(opts => { // default deny var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); opts.Filters.Add(new AuthorizeFilter(policy)); opts.Filters.Add(typeof(NoCacheHttpHeadersAttribute)); opts.Filters.Add(new XRobotsTagAttribute() { NoIndex = true, NoFollow = true }); opts.Filters.Add(typeof(XContentTypeOptionsAttribute)); opts.Filters.Add(typeof(XDownloadOptionsAttribute)); opts.Filters.Add(typeof(XFrameOptionsAttribute)); opts.Filters.Add(typeof(XXssProtectionAttribute)); //CSPReportOnly opts.Filters.Add(typeof(CspReportOnlyAttribute)); opts.Filters.Add(new CspScriptSrcReportOnlyAttribute { None = true }); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddJsonOptions( opts => { opts.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; opts.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; // ReferenceLoopHandling is set to Ignore to prevent JSON parser issues with the user / roles model. opts.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); // setup siteminder authentication (core 2.0) services.AddAuthentication(options => { options.DefaultAuthenticateScheme = SiteMinderAuthOptions.AuthenticationSchemeName; options.DefaultChallengeScheme = SiteMinderAuthOptions.AuthenticationSchemeName; }).AddSiteminderAuth(options => { }); // setup authorization services.AddAuthorization(options => { options.AddPolicy("Business-User", policy => policy.RequireClaim(User.UserTypeClaim, "Business")); }); services.RegisterPermissionHandler(); // setup key ring to persist in storage. if (!string.IsNullOrEmpty(Configuration["KEY_RING_DIRECTORY"])) { services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(Configuration["KEY_RING_DIRECTORY"])); } // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); // allow for large files to be uploaded services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = 1073741824; // 1 GB }); // health checks services.AddHealthChecks(checks => { checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok"))); }); services.AddSession(); }
HealthCheckResult IHealthStatusProvider.StartHealthCheck() { return(HealthCheckResult.Healthy("default")); }
private ValueTask <HealthCheckResult> HealthCheck() { DisposableHealthCheck[] checks; lock (_locker) { checks = _checks.ToArray(); // get the current state of the health-checks list } // don't call the health check functions inside a lock. It may run for a long time, // and in the worse case it may cause a dead-lock, if the function is locking something else that we depend on var results = checks .Select(c => new { c.Name, c.CheckFunc().Result }) .OrderBy(c => c.Result.Status == HealthCheckStatus.Healthy) .ThenBy(c => c.Name) .ToArray(); bool healthy = results.All(r => r.Result.Status == HealthCheckStatus.Healthy); string message = string.Join(Environment.NewLine, results.Select(r => $"{(r.Result.Status == HealthCheckStatus.Healthy ? "[OK]" : "[Unhealthy]")} {r.Name} - {r.Result.Message}")); return(healthy ? new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy(message)) : new ValueTask <HealthCheckResult>(HealthCheckResult.Unhealthy(message))); }
public IServiceProvider ConfigureServices(IServiceCollection services) { RegisterAppInsights(services); services.AddMvc(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }).AddControllersAsServices(); ConfigureAuthService(services); services.Configure <LocationSettings>(Configuration); if (Configuration.GetValue <bool>("AzureServiceBusEnabled")) { services.AddSingleton <IServiceBusPersisterConnection>(sp => { var logger = sp.GetRequiredService <ILogger <DefaultServiceBusPersisterConnection> >(); var serviceBusConnectionString = Configuration["EventBusConnection"]; var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString); return(new DefaultServiceBusPersisterConnection(serviceBusConnection, logger)); }); } else { services.AddSingleton <IRabbitMQPersistentConnection>(sp => { var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >(); var factory = new ConnectionFactory() { HostName = Configuration["EventBusConnection"] }; if (!string.IsNullOrEmpty(Configuration["EventBusUserName"])) { factory.UserName = Configuration["EventBusUserName"]; } if (!string.IsNullOrEmpty(Configuration["EventBusPassword"])) { factory.Password = Configuration["EventBusPassword"]; } var retryCount = 5; if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"])) { retryCount = int.Parse(Configuration["EventBusRetryCount"]); } return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount)); }); } services.AddHealthChecks(checks => { checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok"))); }); RegisterEventBus(services); // Add framework services. services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "eShopOnContainers - Location HTTP API", Version = "v1", Description = "The Location Microservice HTTP API. This is a Data-Driven/CRUD microservice sample", TermsOfService = "Terms Of Service" }); options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize", TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token", Scopes = new Dictionary <string, string>() { { "locations", "Locations API" } } }); options.OperationFilter <AuthorizeCheckOperationFilter>(); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddTransient <IIdentityService, IdentityService>(); services.AddTransient <ILocationsService, LocationsService>(); services.AddTransient <ILocationsRepository, LocationsRepository>(); //configure autofac var container = new ContainerBuilder(); container.Populate(services); return(new AutofacServiceProvider(container.Build())); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <PaymentSettings>(Configuration); RegisterAppInsights(services); if (Configuration.GetValue <bool>("AzureServiceBusEnabled")) { services.AddSingleton <IServiceBusPersisterConnection>(sp => { var logger = sp.GetRequiredService <ILogger <DefaultServiceBusPersisterConnection> >(); var serviceBusConnectionString = Configuration["EventBusConnection"]; var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString); return(new DefaultServiceBusPersisterConnection(serviceBusConnection, logger)); }); } else { services.AddSingleton <IRabbitMQPersistentConnection>(sp => { var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >(); var factory = new ConnectionFactory() { HostName = Configuration["EventBusConnection"] }; if (!string.IsNullOrEmpty(Configuration["EventBusUserName"])) { factory.UserName = Configuration["EventBusUserName"]; } if (!string.IsNullOrEmpty(Configuration["EventBusPassword"])) { factory.Password = Configuration["EventBusPassword"]; } var retryCount = 5; if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"])) { retryCount = int.Parse(Configuration["EventBusRetryCount"]); } return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount)); }); } services.AddHealthChecks(checks => { checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok"))); }); RegisterEventBus(services); var container = new ContainerBuilder(); container.Populate(services); return(new AutofacServiceProvider(container.Build())); }
public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken()) { var errorData = new Dictionary <string, object>(); if (!gameData.InitializedSuccessful) { errorData.Add(nameof(IGameData), "GameData was not initialized successful"); } if (!kernel.Started) { errorData.Add(nameof(IKernel), "Kernel not started"); } return(Task.FromResult(errorData.Count > 0 ? HealthCheckResult.Unhealthy("The GameServer is not running properly", data: errorData) : HealthCheckResult.Healthy())); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // Add framework services. services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); })); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); services.Configure <AppSettings>(Configuration); if (Configuration.GetValue <string>("IsClusterEnv") == bool.TrueString) { services.AddDataProtection(opts => { opts.ApplicationDiscriminator = "FADY.IdentityServer"; }) .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(Configuration["DPConnectionString"]), "DataProtection-Keys"); } services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy()) .AddSqlServer(Configuration["ConnectionString"], name: "IdentityDB-check", tags: new string[] { "IdentityDB" }); services.AddTransient <ILoginService <ApplicationUser>, EFLoginService>(); services.AddTransient <IRedirectService, RedirectService>(); var connectionString = Configuration["ConnectionString"]; var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; // Adds IdentityServer services.AddIdentityServer(x => { x.IssuerUri = "null"; x.Authentication.CookieLifetime = TimeSpan.FromHours(2); }) //.AddDevspacesIfNeeded(Configuration.GetValue("EnableDevspaces", false)) .AddSigningCredential(Certificate.Get()) .AddAspNetIdentity <ApplicationUser>() .AddConfigurationStore(options => options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(migrationsAssembly); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }) ) .AddOperationalStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(migrationsAssembly); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }) .Services.AddTransient <IProfileService, ProfileService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddControllers(); services.AddControllersWithViews(); services.AddRazorPages(); }
public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration) { var hcBuilder = services.AddHealthChecks(); hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy()); hcBuilder .AddSqlServer( configuration["ConnectionString"], name: "MarketingDB-check", tags: new string[] { "marketingdb" }) .AddMongoDb( configuration["MongoConnectionString"], name: "MarketingDB-mongodb-check", tags: new string[] { "mongodb" }); var accountName = configuration.GetValue <string>("AzureStorageAccountName"); var accountKey = configuration.GetValue <string>("AzureStorageAccountKey"); if (!string.IsNullOrEmpty(accountName) && !string.IsNullOrEmpty(accountKey)) { hcBuilder .AddAzureBlobStorage( $"DefaultEndpointsProtocol=https;AccountName={accountName};AccountKey={accountKey};EndpointSuffix=core.windows.net", name: "marketing-storage-check", tags: new string[] { "marketingstorage" }); } if (configuration.GetValue <bool>("AzureServiceBusEnabled")) { hcBuilder .AddAzureServiceBusTopic( configuration["EventBusConnection"], topicName: "eshop_event_bus", name: "marketing-servicebus-check", tags: new string[] { "servicebus" }); } else if (configuration.GetValue <bool>("RabbitMQBusEnabled")) { hcBuilder .AddRabbitMQ( $"amqp://{configuration["EventBusConnection"]}", name: "marketing-rabbitmqbus-check", tags: new string[] { "rabbitmqbus" }); } else { var cacheID = "PubSubCache"; if (!string.IsNullOrEmpty(configuration["EventBusNCachID"])) { cacheID = configuration["EventBusNCachID"]; } var ipAddresses = configuration.GetValue <string>("PubSubCacheIPAddresses", "").Split('-'); if (ipAddresses.Length == 0) { throw new ArgumentNullException("No IP addresses given for Pub Sub cache"); } List <ServerInfo> servers = new List <ServerInfo>(); foreach (var ipAddress in ipAddresses) { servers.Add(new ServerInfo(ipAddress.Trim())); } hcBuilder .AddNCacheHealthCheck( cacheID: cacheID, name: "marketing-ncacheeventbus-check", failureStatus: HealthStatus.Unhealthy, tags: new string[] { "ncacheeventbus" }, cacheConnectionOptions: new CacheConnectionOptions { ServerList = servers }); } if (configuration.GetValue <bool>("CachingEnabled")) { var cacheID = configuration["MarketingCacheID"]; if (string.IsNullOrEmpty(cacheID)) { cacheID = "MarketingCache"; } var ipAddresses = configuration.GetValue <string>("MarketingCacheIPAddresses", "").Split('-'); if (ipAddresses.Length == 0) { throw new ArgumentNullException("No IP addresses given for the Marketing EF Cache"); } List <ServerInfo> servers = new List <ServerInfo>(); foreach (var ipAddress in ipAddresses) { servers.Add(new ServerInfo(ipAddress.Trim())); } hcBuilder .AddNCacheHealthCheck( cacheID: cacheID, name: "marketing-ncach-check", failureStatus: HealthStatus.Unhealthy, tags: new string[] { "ncache" }, cacheConnectionOptions: new CacheConnectionOptions { ServerList = servers }); } return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Cors setup services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); //in memory caching services.AddSession(); //services.AddScoped<MongoAccess>(); services.Configure <Settings>(options => { options.connectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value; options.database = Configuration.GetSection("MongoConnection:Database").Value; options.addBillerTopic = Configuration.GetSection("AppSettings:kafkaAddBillerTopic").Value; options.brokerList = Configuration.GetSection("AppSettings:kafkaBrokerList").Value; options.redisCancellationToken = Convert.ToInt32(Configuration.GetSection("AppSettings:redisCancellationToken").Value); }); services.Configure <List <nameValuePair> >(Configuration.GetSection("AppSettings:nameValuePair")); //health check services.AddHealthChecks(checks => { checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok"))); }); //Add Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "paypart category gateway", Version = "v1" }); }); services.AddTransient <IBillerCategoryMongoRepository, BillerCategoryMongoRepository>(); services.AddTransient <IBillerCategorySqlServerRepository, BillerCategorySqlServerRepository>(); //Redis services.AddDistributedRedisCache(options => { options.Configuration = Configuration.GetSection("AppSettings:redisIP").Value; options.InstanceName = Configuration.GetSection("AppSettings:redisInstanceName").Value; }); //SQL Server services.AddDbContext <BillerCategorySqlServerContext>(options => options.UseSqlServer( Configuration.GetSection("SqlServerConnection:ConnectionString").Value )); //Jwt Auth var audienceConfig = Configuration.GetSection("Audience"); var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audienceConfig["Secret"])); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = audienceConfig["Iss"], ValidateAudience = true, ValidAudience = audienceConfig["Aud"], ValidateLifetime = true, ClockSkew = TimeSpan.Zero, RequireExpirationTime = true, }; services.AddAuthentication(o => { o.DefaultAuthenticateScheme = "TestKey"; }) .AddJwtBearer("TestKey", x => { x.RequireHttpsMetadata = false; x.TokenValidationParameters = tokenValidationParameters; }); services.AddMvc(); }
public HealthCheck(Type source, HealthCheckResult type, string message) { Source = source; Type = type; Message = message; }
public Result(string name, HealthCheckResult check) { this.Name = name; this.Check = check; }