// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSingleton <ITracer>(cli => { Environment.SetEnvironmentVariable("JAEGER_SERVICE_NAME", "dictionary-api"); //if (env.IsDevelopment()) { Environment.SetEnvironmentVariable("JAEGER_AGENT_HOST", "jaeger-agent"); Environment.SetEnvironmentVariable("JAEGER_AGENT_PORT", "6831"); Environment.SetEnvironmentVariable("JAEGER_SAMPLER_TYPE", "const"); } var loggerFactory = new LoggerFactory(); var config = Jaeger.Configuration.FromEnv(loggerFactory); var tracer = config.GetTracer(); /* var sampler = new Configuration.SamplerConfiguration(loggerFactory).WithType("const").WithParam(1); * var reporter = new Configuration.ReporterConfiguration(loggerFactory).WithLogSpans(true); * * var config1 = new Jaeger.Configuration("dictionary-api", loggerFactory) * .WithReporter(reporter) * .WithSampler(sampler); */ if (!GlobalTracer.IsRegistered()) { // Allows code that can't use DI to also access the tracer. GlobalTracer.Register(tracer); } return(tracer); }); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddHttpClient(); services.AddOpenTracing(new System.Collections.Generic.Dictionary <string, LogLevel> { { "AService", LogLevel.Information } }); // Adds the Jaeger Tracer. services.AddSingleton <ITracer>(serviceProvider => { string serviceName = serviceProvider.GetRequiredService <IHostingEnvironment>().ApplicationName; var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); var sampler = new ConstSampler(sample: true); var reporter = new RemoteReporter.Builder() .WithLoggerFactory(loggerFactory) // optional, defaults to no logging //.WithMaxQueueSize(...) // optional, defaults to 100 //.WithFlushInterval(...) // optional, defaults to TimeSpan.FromSeconds(1) .WithSender(new UdpSender("jagerservice", 6831, 0)) // optional, defaults to UdpSender("localhost", 6831, 0) .Build(); // This will log to a default localhost installation of Jaeger. var tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .WithReporter(reporter) .Build(); GlobalTracer.Register(tracer); return(tracer); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <ConsulConfig>(Configuration.GetSection("consulConfig")); services.AddSingleton <IConsulClient, ConsulClient>(p => new ConsulClient(consulConfig => { consulConfig.Address = new Uri(ConsulConfig.Address); })); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Adds the Jaeger Tracer. services.AddSingleton <ITracer>(serviceProvider => { string serviceName = serviceProvider.GetRequiredService <IHostingEnvironment>().ApplicationName; // This will log to a default localhost installation of Jaeger. var tracer = new Tracer.Builder(serviceName) .WithSampler(new ConstSampler(true)) .Build(); // Allows code that can't use DI to also access the tracer. GlobalTracer.Register(tracer); return(tracer); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddMemoryCache(); services.AddOpenTracing(); services.AddSingleton(serviceProvider => { var config = Jaeger.Configuration.FromEnv(serviceProvider.GetRequiredService <ILoggerFactory>()); var tracer = config.GetTracer(); GlobalTracer.Register(tracer); return(tracer); }); services.AddMassTransit(x => { x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg => { cfg.Host("rabbitmq", configurator => { configurator.Username("admin"); configurator.Password("admin"); }); cfg.PropagateOpenTracingContext(); // or, configure the endpoints by convention cfg.ConfigureEndpoints(provider, new KebabCaseEndpointNameFormatter()); })); x.AddRequestClient <FibonacciRequestV1>(); }); services.AddHostedService <BusService>(); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSingleton <ICustomerRepository, CustomerRepository>(); services.AddSingleton <IInformationRepository, InformationRepository>(); services.AddSingleton <ITracer>(serviceProvider => { string serviceName = Assembly.GetEntryAssembly().GetName().Name; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); ISampler sampler = new ConstSampler(sample: true); ITracer tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .Build(); GlobalTracer.Register(tracer); return(tracer); }); }
private static IHostBuilder CreateHostBuilder(string[] args) { return(Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((_, config) => { config.AddEnvironmentVariables(EnvironmentPrefix); config.SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); config.AddCommandLine(args); config.AddJsonFile("appsettings.json"); }) .ConfigureServices((hostContext, services) => { services .Configure <DatabaseOptions>(hostContext.Configuration) .AddSingleton <ITracer>(serviceProvider => { // This will log to a default localhost installation of Jaeger. var tracer = new Tracer.Builder("Collector Service") .WithSampler(new ConstSampler(true)) .Build(); // Allows code that can't use DI to also access the tracer. GlobalTracer.Register(tracer); return tracer; }) .AddSingleton <IWriter, SqlWriter>() .AddSingleton <IGameRepository, CsvGameRepository>() .AddSingleton <ISqlGameRepository, SqlGameRepository>() .AddSingleton <IGamePlayRepository, JsonGamePlayRepository>() .AddSingleton <ICollectorManager, CollectorManager>() .AddSingleton <IMigrator, Migrator>() .AddHostedService <CollectorService>(); }) .UseConsoleLifetime()); }
public Function() { GlobalTracer.Register(LambdaTracer.Instance); }
// Registers and starts Jaeger. // Also registers OpenTracing related services! // Note: IHostEnvironment requires.NET Core 3.0. Either eliminate it if you don't need it, or use IHostingEnvironment // instead. public static IServiceCollection AddJaeger(this IServiceCollection services, IHostEnvironment env, string serviceName = null) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddSingleton <ITracer>(serviceProvider => { // Two sensible alternatives serviceName ??= serviceProvider.GetRequiredService <IHostEnvironment>().ApplicationName; // serviceName ??= Assembly.GetEntryAssembly().GetName().Name; // This will be the service service name logged with the spans, displayed by Jaeger UI Environment.SetEnvironmentVariable("JAEGER_SERVICE_NAME", serviceName); // Based on env we can have different configuration for development and production environments if (env != null && env.IsDevelopment()) { // Check if we receive the specified env vars: if not, set defaults var agentHost = Environment.GetEnvironmentVariable("JAEGER_AGENT_HOST"); // Host name for the jager agent if (agentHost == null) { Environment.SetEnvironmentVariable("JAEGER_AGENT_HOST", "jaeger"); } var agentPort = Environment.GetEnvironmentVariable("JAEGER_AGENT_PORT"); if (agentHost == null) { Environment.SetEnvironmentVariable("JAEGER_AGENT_PORT", "6831"); } var sampler = Environment.GetEnvironmentVariable("JAEGER_SAMPLER_TYPE"); if (agentHost == null) { Environment.SetEnvironmentVariable("JAEGER_SAMPLER_TYPE", "const"); } } else { // As for now do nothing, let's assume all environment variables are // set properly in a production environment } // We could also create a new factory and configure it for our needs ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); // Without this somehow Jeager does not use any sender despite the JAEGER_AGENT_... environmental settings // when Debugging under Visual Studio (you can see this in the docker log of the Catalog and Order service // "No suitable sender found. Using NoopSender, meaning that data will not be sent anywhere!". // The problem did not exist with older Jaeger ("0.3.6") dependency, // or when docker-compose is used to start the services. Anyways, setting the DefaultSenderResolver explicitely // solves the problem. This is not needed when not using an agent (when you send data to the collector // explicitely), or you might need to adjust it. Jaeger.Configuration.SenderConfiguration.DefaultSenderResolver = new Jaeger.Senders.SenderResolver(loggerFactory).RegisterSenderFactory <Jaeger.Senders.Thrift.ThriftSenderFactory>(); // Get Jaeger config from environment var config = Jaeger.Configuration.FromEnv(loggerFactory); // We could further modify Jaeger config here var tracer = config.GetTracer(); if (!GlobalTracer.IsRegistered()) { // Allows code that can't use DI to also access the tracer. GlobalTracer.Register(tracer); } return(tracer); }); // This has significance only when you send spans directly to the collector via HttpSender, // e.g. if JAEGER_ENDPOINT is specified. This is not the case in out setup, but keep it here. // Prevent endless loops when OpenTracing is tracking HTTP requests to Jaeger. // See https://github.com/jaegertracing/jaeger-client-csharp/issues/154 //services.Configure<HttpHandlerDiagnosticOptions>(options => //{ // // Update Url properly // Uri _jaegerUri = new Uri("http://localhost:14268/api/traces"); // options.IgnorePatterns.Add(request => _jaegerUri.IsBaseOf(request.RequestUri)); // // This is not needed, just demonstrates some possibilities // options.OnError = (span, exception, message) => // { // }; // options.OnRequest = (span, request) => // { // }; //}); // Also add Open Tracing related services services.AddOpenTracing(); return(services); }
public static IServiceCollection AddElectJaeger(this IServiceCollection services, [NotNull] Action <ElectJaegerOptions> configure) { services.Configure(configure); var electJaegerOptions = configure.GetValue(); if (!electJaegerOptions.IsEnable) { return(services); } // Add open Tracing services.AddOpenTracing(); // Add ITracer services.AddSingleton(serviceProvider => { var loggerFactory = GetLoggerFactory(serviceProvider); // Sampler var samplerConfig = new Configuration.SamplerConfiguration(loggerFactory); samplerConfig.WithSamplingEndpoint($"http://{electJaegerOptions.SamplerDomain}:{electJaegerOptions.SamplerPort}"); samplerConfig.WithType(ConstSampler.Type); samplerConfig = electJaegerOptions.AfterSamplerConfig?.Invoke(samplerConfig) ?? samplerConfig; // Reporter var reporterConfig = new Configuration.ReporterConfiguration(loggerFactory); reporterConfig.SenderConfig.WithAgentHost(electJaegerOptions.ReporterDomain); reporterConfig.SenderConfig.WithAgentPort(electJaegerOptions.ReporterPort); reporterConfig.SenderConfig.WithEndpoint(electJaegerOptions.TracesEndpoint); if (!string.IsNullOrWhiteSpace(electJaegerOptions.AuthUsername)) { reporterConfig.SenderConfig.WithAuthUsername(electJaegerOptions.AuthUsername); } if (!string.IsNullOrWhiteSpace(electJaegerOptions.AuthPassword)) { reporterConfig.SenderConfig.WithAuthPassword(electJaegerOptions.AuthPassword); } if (!string.IsNullOrWhiteSpace(electJaegerOptions.AuthToken)) { reporterConfig.SenderConfig.WithAuthToken(electJaegerOptions.AuthToken); } reporterConfig = electJaegerOptions.AfterReporterConfig?.Invoke(reporterConfig) ?? reporterConfig; // Global Config var config = new Configuration(electJaegerOptions.ServiceName, loggerFactory) .WithSampler(samplerConfig) .WithReporter(reporterConfig); config = electJaegerOptions.AfterGlobalConfig?.Invoke(config) ?? config; // Tracer var tracer = config.GetTracer(); tracer = electJaegerOptions.AfterTracer?.Invoke(tracer) ?? tracer; // Register Tracer if (!GlobalTracer.IsRegistered()) { GlobalTracer.Register(tracer); } return(tracer); }); services.Configure <HttpHandlerDiagnosticOptions>(options => { options.IgnorePatterns.Add(x => !x.RequestUri.IsLoopback); }); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); GlobalTracer.Register(Tracer); services.AddOpenTracing(); }
public static IConveyBuilder AddJaeger(this IConveyBuilder builder, JaegerOptions options, string sectionName = SectionName, Action <IOpenTracingBuilder> openTracingBuilder = null) { if (Interlocked.Exchange(ref _initialized, 1) == 1) { return(builder); } builder.Services.AddSingleton(options); if (!options.Enabled) { var defaultTracer = ConveyDefaultTracer.Create(); builder.Services.AddSingleton(defaultTracer); return(builder); } if (!builder.TryRegister(RegistryName)) { return(builder); } if (options.ExcludePaths is not null) { builder.Services.Configure <AspNetCoreDiagnosticOptions>(o => { foreach (var path in options.ExcludePaths) { o.Hosting.IgnorePatterns.Add(x => x.Request.Path == path); } }); } builder.Services.AddOpenTracing(x => openTracingBuilder?.Invoke(x)); builder.Services.AddSingleton <ITracer>(sp => { var loggerFactory = sp.GetRequiredService <ILoggerFactory>(); var maxPacketSize = options.MaxPacketSize <= 0 ? 64967 : options.MaxPacketSize; var senderType = string.IsNullOrWhiteSpace(options.Sender) ? "udp" : options.Sender?.ToLowerInvariant(); ISender sender = senderType switch { "http" => BuildHttpSender(options.HttpSender), "udp" => new UdpSender(options.UdpHost, options.UdpPort, maxPacketSize), _ => throw new Exception($"Invalid Jaeger sender type: '{senderType}'.") }; var reporter = new RemoteReporter.Builder() .WithSender(sender) .WithLoggerFactory(loggerFactory) .Build(); var sampler = GetSampler(options); var tracer = new Tracer.Builder(options.ServiceName) .WithLoggerFactory(loggerFactory) .WithReporter(reporter) .WithSampler(sampler) .Build(); GlobalTracer.Register(tracer); return(tracer); }); return(builder); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); // Register the database components services.Configure <Settings>(options => { options.ConnectionString = Environment.GetEnvironmentVariable("MONGODBCONNECTION"); options.Database = Environment.GetEnvironmentVariable("MONGODB"); }); // Use "OpenTracing.Contrib.NetCore" to automatically generate spans for ASP.NET Core services.AddSingleton <ITracer>(serviceProvider => { var loggerFactory = new LoggerFactory(); // use the environment variables to setup the Jaeger endpoints var config = Jaeger.Configuration.FromEnv(loggerFactory); var tracer = config.GetTracer(); GlobalTracer.Register(tracer); return(tracer); }); services.AddOpenTracing(); // Create a new connection factory to create a connection. ConnectionFactory cf = new ConnectionFactory(); // add the options for the server, reconnecting, and the handler events Options opts = ConnectionFactory.GetDefaultOptions(); opts.MaxReconnect = -1; opts.ReconnectWait = 1000; opts.Name = "openrmf-api-template"; opts.Url = Environment.GetEnvironmentVariable("NATSSERVERURL"); opts.AsyncErrorEventHandler += (sender, events) => { logger.Info("NATS client error. Server: {0}. Message: {1}. Subject: {2}", events.Conn.ConnectedUrl, events.Error, events.Subscription.Subject); }; opts.ServerDiscoveredEventHandler += (sender, events) => { logger.Info("A new server has joined the cluster: {0}", events.Conn.DiscoveredServers); }; opts.ClosedEventHandler += (sender, events) => { logger.Info("Connection Closed: {0}", events.Conn.ConnectedUrl); }; opts.ReconnectedEventHandler += (sender, events) => { logger.Info("Connection Reconnected: {0}", events.Conn.ConnectedUrl); }; opts.DisconnectedEventHandler += (sender, events) => { logger.Info("Connection Disconnected: {0}", events.Conn.ConnectedUrl); }; // Creates a live connection to the NATS Server with the above options IConnection conn = cf.CreateConnection(opts); // setup the NATS server services.Configure <NATSServer>(options => { options.connection = conn; }); // add repositories services.AddTransient <ITemplateRepository, TemplateRepository>(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "OpenRMF Template API", Version = "v1", Description = "The Template API that goes with the OpenRMF tool", Contact = new Contact { Name = "Dale Bingham", Email = "*****@*****.**", Url = "https://github.com/Cingulara/openrmf-api-template" } }); }); // add the authentication JWT check that has AuthN and AuthZ in it for the roles needed services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { o.Authority = Environment.GetEnvironmentVariable("JWT-AUTHORITY"); o.Audience = Environment.GetEnvironmentVariable("JWT-CLIENT"); o.IncludeErrorDetails = true; o.RequireHttpsMetadata = false; o.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = false, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidIssuer = Environment.GetEnvironmentVariable("JWT-AUTHORITY"), ValidateLifetime = true }; o.Events = new JwtBearerEvents() { OnAuthenticationFailed = c => { c.NoResult(); c.Response.StatusCode = 401; c.Response.ContentType = "text/plain"; return(c.Response.WriteAsync(c.Exception.ToString())); } }; }); // setup the RBAC for this services.AddAuthorization(options => { options.AddPolicy("Administrator", policy => policy.RequireRole("roles", "[Administrator]")); options.AddPolicy("Editor", policy => policy.RequireRole("roles", "[Editor]")); options.AddPolicy("Reader", policy => policy.RequireRole("roles", "[Reader]")); options.AddPolicy("Assessor", policy => policy.RequireRole("roles", "[Assessor]")); }); // ******************** // USE CORS // ******************** services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); }); // add service for allowing caching of responses services.AddResponseCaching(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddXmlSerializerFormatters(); // add this in memory for now. Persist later. services.AddDistributedMemoryCache(); }
// TODO: Configure B2C // TODO: Add Examples of Custom Authorization Pipeline Auth/AuthZ // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { IdentityModelEventSource.ShowPII = true; services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme) .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options)); services.AddRouting(options => { options.LowercaseUrls = true; options.AppendTrailingSlash = false; }); var handlersAssembly = typeof(PingHandler).Assembly; var validatorsAssembly = typeof(PingValidator).Assembly; services.AddMediatR(handlersAssembly); services.AddHttpContextAccessor(); services.AddTransient <IBearerAccessor, BearerAccessor>(); services.AddTransient <IUserAccessor, UserAccessor>(); services.AddTransient(typeof(IRequestPostProcessor <,>), typeof(PaginationPipeline <,>)); services.AddTransient <ICloudScaleRepository, CloudScaleRepository>(); services.AddControllers() .AddFluentValidation(o => o.RegisterValidatorsFromAssembly(validatorsAssembly)) .AddJsonOptions(options => options.JsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb)); services.AddResponseCaching(); services.AddTransient <IClock>(provider => SystemClock.Instance); services.AddTransient <ICloudScaleClient>(provider => new CloudScaleClient(new CloudScaleClientConfiguration { BaseUrl = "https://localhost:5001" })); services.AddOpenApiDocument(document => { document.AddSecurity("bearer", Enumerable.Empty <string>(), new OpenApiSecurityScheme { Type = OpenApiSecuritySchemeType.OAuth2, Description = "B2C authentication", Flow = OpenApiOAuth2Flow.Implicit, Flows = new OpenApiOAuthFlows() { Implicit = new OpenApiOAuthFlow() { Scopes = new Dictionary <string, string> { { "https://cloudscaledemo.onmicrosoft.com/cloudscale-api/user_impersonation", "Access the api as the signed-in user" }, { "https://cloudscaledemo.onmicrosoft.com/cloudscale-api/read", "Read access to the API" }, }, AuthorizationUrl = "https://cloudscaledemo.b2clogin.com/cloudscaledemo.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_signup_signin", TokenUrl = "https://cloudscaledemo.b2clogin.com/cloudscaledemo.onmicrosoft.com/oauth2/v2.0/token?p=B2C_1_signup_signin" }, } }); document.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("bearer")); }); var sqlConnectionString = Configuration.GetConnectionString("CloudScale"); services.AddDbContext <CloudScaleDbContext>(options => { options.UseSqlServer(sqlConnectionString, o => { o.UseNodaTime(); o.EnableRetryOnFailure(); }); }); services.AddSingleton(Log.Logger); Uri jaegerUri = new Uri("http://localhost:14268/api/traces"); services.AddSingleton(serviceProvider => { string serviceName = Assembly.GetEntryAssembly()?.GetName().Name; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); ISampler sampler = new ConstSampler(sample: true); ITracer tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .Build(); GlobalTracer.Register(tracer); return(tracer); }); // Prevent endless loops when OpenTracing is tracking HTTP requests to Jaeger. services.Configure <HttpHandlerDiagnosticOptions>(options => { options.IgnorePatterns.Add(request => jaegerUri.IsBaseOf(request.RequestUri)); }); services.AddOpenTracing(); services .AddHealthChecks() .AddCheck <AliveHealthCheck>("self", HealthStatus.Unhealthy) .AddSqlServer(sqlConnectionString, name: "database", tags: new[] { "database" }); services .AddHealthChecksUI(setupSettings: setup => { setup.AddHealthCheckEndpoint("self", "/healthz"); }) .AddInMemoryStorage(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { // 加入 OpenTracing services.AddOpenTracing().AddSingleton <ITracer>(serviceProvider => { const string serviceName = "MockSite.Web"; var tracer = new Tracer.Builder(serviceName) .WithSampler(new ConstSampler(true)) .Build(); // 註冊 Jaeger tracer GlobalTracer.Register(tracer); return(tracer); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "MockSite API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", Enumerable.Empty <string>() } }); }); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); // Configure JWT authentication services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidIssuer = AppSettingsHelper.Instance.GetValueFromKey(AppSetting.JwtIssuerKey), ValidAudience = AppSettingsHelper.Instance.GetValueFromKey(AppSetting.JwtAudienceKey), IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(AppSettingsHelper.Instance.GetValueFromKey(AppSetting.JwtSecretKey)) ) }; }); // Configure DI for application services services.AddScoped <IUserService, UserService>(); // Register gRPC Service var userHost = $"{ConsulSettingHelper.Instance.GetValueFromKey(HostNameConst.TestKey)}:{ConsulSettingHelper.Instance.GetValueFromKey(PortConst.TestKey)}"; var tracingInterceptor = new ClientTracingInterceptor(GlobalTracer.Instance); services.AddSingleton(new Message.UserService.UserServiceClient( CreateKeepAliveWithoutCallChannel(userHost).Intercept(tracingInterceptor)) ); }
static Function() { // Register the New Relic OpenTracing LambdaTracer as the Global Tracer GlobalTracer.Register(LambdaTracer.Instance); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); // EF if (Environment.GetEnvironmentVariable("ReviewConnStr") == null) { Environment.SetEnvironmentVariable("ReviewConnStr", "Server=127.0.0.1;Port=5432;Database=reviewDb;User Id=postgres;Password=example;"); } services.AddDbContext <ReviewContext>(options => options.UseNpgsql(Environment.GetEnvironmentVariable("ReviewConnStr"))); // Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Book Reviews API", Version = "v1" }); }); //HealthChecks services.AddHealthChecks() .AddNpgSql(npgsqlConnectionString: Environment.GetEnvironmentVariable("ReviewConnStr"), healthQuery: "SELECT 1;", failureStatus: HealthStatus.Degraded, tags: new[] { Readiness }); // Open Tracing services.AddOpenTracing(); // Adds the Jaeger Tracer. services.AddSingleton <ITracer>(serviceProvider => { string serviceName = serviceProvider.GetRequiredService <Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().ApplicationName; if (Environment.GetEnvironmentVariable("JAEGER_SERVICE_NAME") == null) { Environment.SetEnvironmentVariable("JAEGER_SERVICE_NAME", serviceName); } if (Environment.GetEnvironmentVariable("JAEGER_AGENT_HOST") == null) { Environment.SetEnvironmentVariable("JAEGER_AGENT_HOST", "localhost"); } if (Environment.GetEnvironmentVariable("JAEGER_AGENT_PORT") == null) { Environment.SetEnvironmentVariable("JAEGER_AGENT_PORT", "6831"); } if (Environment.GetEnvironmentVariable("JAEGER_SAMPLER_TYPE") == null) { Environment.SetEnvironmentVariable("JAEGER_SAMPLER_TYPE", "const"); } var loggerFactory = new LoggerFactory(); var config = Jaeger.Configuration.FromEnv(loggerFactory); var tracer = config.GetTracer(); if (!GlobalTracer.IsRegistered()) { // Allows code that can't use DI to also access the tracer. GlobalTracer.Register(tracer); } return(tracer); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { if (Environment.GetEnvironmentVariable("JAEGER_AGENT_HOST") != null && !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("JAEGER_AGENT_HOST"))) { // Use "OpenTracing.Contrib.NetCore" to automatically generate spans for ASP.NET Core services.AddSingleton <ITracer>(serviceProvider => { var loggerFactory = new LoggerFactory(); // use the environment variables to setup the Jaeger endpoints var config = Jaeger.Configuration.FromEnv(loggerFactory); var tracer = config.GetTracer(); GlobalTracer.Register(tracer); return(tracer); }); services.AddOpenTracing(); } // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "OpenRMF Compliance API", Version = "v1", Description = "The Compliance API that goes with the OpenRMF tool", Contact = new OpenApiContact { Name = "Dale Bingham", Email = "*****@*****.**", Url = new Uri("https://github.com/Cingulara/openrmf-api-compliance") } }); }); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { o.Authority = Environment.GetEnvironmentVariable("JWT-AUTHORITY"); o.Audience = Environment.GetEnvironmentVariable("JWT-CLIENT"); o.IncludeErrorDetails = true; o.RequireHttpsMetadata = false; o.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = false, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidIssuer = Environment.GetEnvironmentVariable("JWT-AUTHORITY"), ValidateLifetime = true }; o.Events = new JwtBearerEvents() { OnAuthenticationFailed = c => { c.NoResult(); c.Response.StatusCode = 401; c.Response.ContentType = "text/plain"; return(c.Response.WriteAsync(c.Exception.ToString())); } }; }); // setup the RBAC for this services.AddAuthorization(options => { options.AddPolicy("Administrator", policy => policy.RequireRole("roles", "[Administrator]")); options.AddPolicy("Editor", policy => policy.RequireRole("roles", "[Editor]")); options.AddPolicy("Reader", policy => policy.RequireRole("roles", "[Reader]")); options.AddPolicy("Assessor", policy => policy.RequireRole("roles", "[Assessor]")); }); // add the CORS setup services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, builder => { builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); }); }); // add service for allowing caching of responses services.AddResponseCaching(); services.AddControllers(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(o => o.AddPolicy("MyPolicyCore", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicyCore")); }); services.AddOcelot(Configuration); var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["token:key"])); services.AddAuthentication() .AddJwtBearer("SECURITY-TOKEN", options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["token:issuer"], ValidAudience = Configuration["token:audience"], IssuerSigningKey = signingKey }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { Console.WriteLine("OnAuthenticationFailed" + context.Exception.Message); return(Task.CompletedTask); }, OnTokenValidated = context => { Console.WriteLine("OnTokenValidated" + context.SecurityToken); return(Task.CompletedTask); }, }; }); services.AddSingleton <ITracer>(serviceProvider => { string serviceName = "SERVICE-GATEWAY"; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); ISampler sampler = new ConstSampler(sample: true); ITracer tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .Build(); GlobalTracer.Register(tracer); return(tracer); }); services.AddOpenTracing(); services.Configure <HttpHandlerDiagnosticOptions>(options => { options.IgnorePatterns.Add(x => !x.RequestUri.IsLoopback); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Register the database components services.Configure <Settings>(options => { options.ConnectionString = Environment.GetEnvironmentVariable("MONGODBCONNECTION"); options.Database = Environment.GetEnvironmentVariable("MONGODB"); }); // Use "OpenTracing.Contrib.NetCore" to automatically generate spans for ASP.NET Core services.AddSingleton <ITracer>(serviceProvider => { ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); // use the environment variables to setup the Jaeger endpoints var config = Jaeger.Configuration.FromEnv(loggerFactory); var tracer = config.GetTracer(); GlobalTracer.Register(tracer); return(tracer); }); services.AddOpenTracing(); // add repositories services.AddTransient <IAuditRepository, AuditRepository>(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "OpenRMF Audit API", Version = "v1", Description = "The Audit API that goes with the OpenRMF tool", Contact = new Contact { Name = "Dale Bingham", Email = "*****@*****.**", Url = "https://github.com/Cingulara/openrmf-api-audit" } }); }); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { o.Authority = Environment.GetEnvironmentVariable("JWT-AUTHORITY"); o.Audience = Environment.GetEnvironmentVariable("JWT-CLIENT"); o.IncludeErrorDetails = true; o.RequireHttpsMetadata = false; o.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = false, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidIssuer = Environment.GetEnvironmentVariable("JWT-AUTHORITY"), ValidateLifetime = true }; o.Events = new JwtBearerEvents() { OnAuthenticationFailed = c => { c.NoResult(); c.Response.StatusCode = 401; c.Response.ContentType = "text/plain"; return(c.Response.WriteAsync(c.Exception.ToString())); } }; }); // setup the RBAC for this services.AddAuthorization(options => { options.AddPolicy("Administrator", policy => policy.RequireRole("roles", "[Administrator]")); options.AddPolicy("Assessor", policy => policy.RequireRole("roles", "[Assessor]")); }); // ******************** // USE CORS // ******************** services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddXmlSerializerFormatters(); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); GlobalTracer.Register(Tracer); services.AddOpenTracing(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowFromAll", builder => builder .WithMethods("GET", "POST", "PUT") .AllowAnyOrigin() .AllowAnyHeader()); }); services.AddControllers(); //#if (AddHealthCheck) // Register health checks to be enabled in api services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy()); //#endif //#if (AddSwagger) // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "CMAService API", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); //#endif services.AddScoped <IBusinessAccess, BusinessAccess>(); //#if (!AddSql && !AddMongo) services.AddScoped <IDataAccess, DataAccess>(); //#endif // services.AddScoped<IDataAccess, CouchDataAccess>(); //#if(AddSql) //services.AddScoped<IDataAccess, SqlDataAccess>(); services.AddDbContext <AuthorContext>(options => { options.UseSqlServer( Configuration.GetConnectionString("SqlDatabase")); }); //#endif //#if(AddMongo) // requires using Microsoft.Extensions.Options services.Configure <MongoDbSettings>( Configuration.GetSection(nameof(MongoDbSettings))); services.AddSingleton <IMongoDbSettings>(sp => sp.GetRequiredService <IOptions <MongoDbSettings> >().Value); //services.AddScoped<IDataAccess, MongoDataAccess>(); //#endif //#if (AddPolly) IAsyncPolicy <HttpResponseMessage> httpWaitAndRetryPolicy = GetWaitAndRetryPolicy(); IAsyncPolicy <HttpResponseMessage> circuitBreakerPolicy = GetCircuitBreakerPolicy(); IAsyncPolicy <HttpResponseMessage> fallbackPolicy = GetFallbackPolicy(); IAsyncPolicy <HttpResponseMessage> httpRetryPolicy = GetRetryPolicy(); IAsyncPolicy <HttpResponseMessage> allPoliciesWrapped = Policy.WrapAsync(fallbackPolicy, httpWaitAndRetryPolicy, circuitBreakerPolicy); services.AddHttpClient("WeatherForecastController", client => { client.BaseAddress = new Uri("https://localhost:44358/weatherforecast/GetErrorPollyTest?id=5"); client.DefaultRequestHeaders.Add("Accept", "application/json"); }).AddPolicyHandler(httpRetryPolicy); //#endif //#if(AddKafka) var producerConfig = new ProducerConfig(); var consumerConfig = new ConsumerConfig(); Configuration.Bind("producer", producerConfig); Configuration.Bind("consumer", consumerConfig); services.AddSingleton <ProducerConfig>(producerConfig); services.AddSingleton <ConsumerConfig>(consumerConfig); //#endif //#if(AddJager) services.AddSingleton <ITracer>(serviceProvider => { var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerServiceName, Configuration["JagerConnection:servicename"]); Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerSamplerType, Configuration["JagerConnection:sampletype"]); Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerReporterLogSpans, Configuration["JagerConnection:reportlogspan"]); Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerSamplerParam, Configuration["JagerConnection:samplerparam"]); Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerEndpoint, Configuration["JagerConnection:endpoint"]); // This will log to a default localhost installation of Jaeger. var tracer = Jaeger.Configuration.FromEnv(loggerFactory).GetTracer(); // Allows code that can't use DI to also access the tracer. GlobalTracer.Register(tracer); return(tracer); }); services.AddOpenTracing(); //#endif //#if(AddRedis) services.AddDistributedRedisCache(option => { option.Configuration = Configuration["RedisConnection:hostname"]; option.InstanceName = Configuration["RedisConnection:instancename"]; }); //#endif //#if(AddCouch) var constring = Configuration["Couchbase:Server"]; services.AddSingleton <CouchClient>(new CouchClient(constring)); //#endif }
static void Main(string[] args) { var tracer = Common.Jaeger.Creator.GetLogger(); GlobalTracer.Register(tracer); Console.WriteLine("Client started."); Console.WriteLine("Press any key to start requests . . ."); Console.ReadKey(); Console.WriteLine("Client sending requests."); if (true) { AppServerUtility.MakeRequest((IReportService proxy) => proxy.Touch()); using (tracer.BuildSpan("Client.Touch").StartActive(true)) { AppServerUtility.MakeRequest((IReportService proxy) => proxy.Touch()); } AppServerUtility.MakeRequest((IReportService proxy) => proxy.Silence(7)); using (tracer.BuildSpan("Client.Noise").StartActive(true)) { AppServerUtility.MakeRequest((IReportService proxy) => proxy.Noise(11)); } } if (true) { using (tracer.BuildSpan("ThrowsCLRException").StartActive(true)) { try { AppServerUtility.MakeRequest((IThrowsService proxy) => proxy.ThrowsCLRException()); } catch (FaultException) { /* ignore */ } } using (tracer.BuildSpan("ThrowsCLRExceptionOneWay").StartActive(true)) { try { AppServerUtility.MakeRequest((IThrowsService proxy) => proxy.ThrowsCLRExceptionOneWay()); } catch (FaultException) { /* ignore */ } } using (tracer.BuildSpan("ThrowsFaultException").StartActive(true)) { try { AppServerUtility.MakeRequest((IThrowsService proxy) => proxy.ThrowsFaultException()); } catch (FaultException) { /* ignore */ } } using (tracer.BuildSpan("ThrowsFaultExceptionOneWay").StartActive(true)) { try { AppServerUtility.MakeRequest((IThrowsService proxy) => proxy.ThrowsFaultExceptionOneWay()); } catch (FaultException) { /* ignore */ } } using (tracer.BuildSpan("ThrowsTypedCLRFaultException").StartActive(true)) { try { AppServerUtility.MakeRequest((IThrowsService proxy) => proxy.ThrowsTypedCLRFaultException()); } catch (FaultException) { /* ignore */ } } using (tracer.BuildSpan("ThrowsTypedCustomFaultException").StartActive(true)) { try { AppServerUtility.MakeRequest((IThrowsService proxy) => proxy.ThrowsTypedCustomFaultException()); } catch (FaultException) { /* ignore */ } } } if (true) { var traceId = Guid.NewGuid().ToString("N"); const int reportId = 2209619; var scope = tracer.BuildSpan($"Client.Export(reportId={reportId})").StartActive(true); scope.Span.SetBaggageItem(Common.Objects.Constants.TRACE_ID, traceId); var token = default(string); using (var inner = tracer.BuildSpan("Client.AddTask").AsChildOf(scope.Span.Context).StartActive(true)) { token = AppServerUtility.MakeRequest((IExportService proxy) => proxy.AddTask(reportId)); if (!$"{traceId}-{reportId}".Equals(token)) { inner.Span.Log("Not supported 'token'"); Tags.Error.Set(inner.Span, true); throw new ApplicationException("Not supported 'token'"); } } using (var inner = tracer.BuildSpan("Client.WaitFile").AsChildOf(scope.Span.Context).StartActive(true)) { var file = default(object); do { Thread.Sleep(1000); file = AppServerUtility.MakeRequest((IExportService proxy) => proxy.GetFile(token)); } while (file == null); if (!$"{file}".Equals($"{token}.docx")) { inner.Span.Log("Not supported 'file'"); Tags.Error.Set(inner.Span, true); throw new ApplicationException("Not supported 'file'"); } } scope.Span.Finish(); } Console.WriteLine("Press any key to continue . . ."); Console.ReadKey(); }
public void TestFromEnv() { SetProperty(Configuration.JaegerServiceName, "Test"); Assert.NotNull(Configuration.FromEnv(_loggerFactory).GetTracer()); Assert.False(GlobalTracer.IsRegistered()); }
public static void ConfigureServices(InstanceInfo instanceInfo, IServiceCollection services, bool isPublicWebService) { var jaegerAgentHost = Environment.GetEnvironmentVariable("TRACING_AGENT_HOST");// ?? "localhost"; var samplingRateParam = Environment.GetEnvironmentVariable("TRACING_RATE") ?? "100"; int.TryParse(samplingRateParam, out var samplingRate); if (samplingRate > 100) { samplingRate = 100; } if (samplingRate < 0) { samplingRate = 0; } if (string.IsNullOrEmpty(jaegerAgentHost) || samplingRate == 0) { Console.WriteLine("Tracing is disabled (environments TRACING_AGENT_HOST, TRACING_RATE)"); services.AddSingleton <ITracer>(new NoTracer()); return; } services.AddSingleton <ITracer>(serviceProvider => { var serviceName = Assembly.GetEntryAssembly().GetName().Name; //ILoggerFactory loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>(); //var loggingReporter = new LoggingReporter(loggerFactory); var reporter = new RemoteReporter.Builder() .WithSender(new UdpSender(jaegerAgentHost, 6831, 0)) .Build(); //https://www.jaegertracing.io/docs/sampling/ ISampler sampler = samplingRate == 100 ? new ConstSampler(sample: true) as ISampler : new ProbabilisticSampler(samplingRate / 100) as ISampler; Logger().Information("Tracer use sampler {Sampler}", sampler.GetType().Name); ITracer tracer = new Tracer.Builder(serviceName) //.WithLoggerFactory(loggerFactory) .WithSampler(sampler) .WithReporter(reporter) //.WithReporter(new CompositeReporter(loggingReporter, reporter)) .Build(); GlobalTracer.Register(tracer); return(tracer); }); // Prevent endless loops when OpenTracing is tracking HTTP requests to Jaeger. services.Configure <HttpHandlerDiagnosticOptions>(options => { options.IgnorePatterns.Clear(); options.IgnorePatterns.Add(request => request.RequestUri.Port == 8086 && request.RequestUri.PathAndQuery.Contains("write?db=appmetrics")); }); // Enables OpenTracing instrumentation for ASP.NET Core, CoreFx, EF Core services.AddOpenTracing(builder => { builder.ConfigureAspNetCore(options => { options.Hosting.ExtractEnabled = context => !isPublicWebService; // never trust TraceId from user web-requests options.Hosting.OnRequest = (span, context) => { span.SetTag("InstanceId", instanceInfo.Id.ToString()); }; }); } ); }
/// <summary> /// 添加Jaeger链路追踪,实例对象ITracer /// </summary> /// <param name="services"></param> /// <param name="openTracingBuilder"></param> /// <returns></returns> public static IServiceCollection AddJaeger(this IServiceCollection services, Action <IOpenTracingBuilder> openTracingBuilder = null) { if (openTracingBuilder == null) { openTracingBuilder = builder => { builder.AddCoreFx(); builder.AddAspNetCore(); builder.AddEntityFrameworkCore(); builder.AddLoggerProvider(); builder.ConfigureGenericDiagnostics(options => { }); builder.ConfigureAspNetCore(options => { options.Hosting.OperationNameResolver = (context) => { return(context.Request.Path.ToUriComponent()); }; options.Hosting.IgnorePatterns.Add(a => { return(false); }); }); }; } services.AddOpenTracing(openTracingBuilder); services.AddSingleton <ITracer>(serviceProvider => { var config = serviceProvider.GetService <TracingConfiguration>(); var serviceName = config.SerivceName ?? serviceProvider.GetRequiredService <IHostingEnvironment>().ApplicationName; var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); var endPoint = config.EndPoint; var senderConfiguration = new Jaeger.Configuration.SenderConfiguration(loggerFactory); if (!string.IsNullOrEmpty(config.AgentHost)) { senderConfiguration .WithAgentHost(config.AgentHost) .WithAgentPort(config.AgentPort); } else { senderConfiguration.WithEndpoint(endPoint); } var samplerConfiguration = new Jaeger.Configuration.SamplerConfiguration(loggerFactory) .WithType(config.SamplerType); var reporterConfiguration = new Jaeger.Configuration.ReporterConfiguration(loggerFactory) .WithFlushInterval(TimeSpan.FromSeconds(config.FlushIntervalSeconds)) .WithLogSpans(config.LogSpans) .WithSender(senderConfiguration); ITracer tracer = null; if (config.Open) { tracer = new Jaeger.Configuration(serviceName, loggerFactory) .WithSampler(samplerConfiguration) .WithReporter(reporterConfiguration) .GetTracer(); } else { tracer = new Jaeger.Tracer.Builder(serviceName) .WithSampler(new Jaeger.Samplers.RateLimitingSampler(0)) .WithReporter(new Jaeger.Reporters.NoopReporter()).Build(); } if (!GlobalTracer.IsRegistered()) { GlobalTracer.Register(tracer); } return(tracer); }); return(services); }
public static IServiceCollection AddJaeger(this IServiceCollection services, IConfiguration configuration, bool useAgent = true) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddSingleton <ITracer>(serviceProvider => { var tracingConfig = new TracingConfiguration(); configuration.GetSection("Tracing").Bind(tracingConfig); string serviceName = tracingConfig.ServiceName ?? Assembly.GetEntryAssembly().GetName().Name; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); ITracer tracer; //HACK TIME var useLocalSettigns = tracingConfig.JaegerUrl?.Contains("localhost"); if (!useAgent && useLocalSettigns) { //use lcoalhost defaults. ISampler sampler = new ConstSampler(sample: true); tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .Build(); GlobalTracer.Register(tracer); return(tracer); } //ok we will try and connect to an external jaeger setup if (useAgent) { //use the agent Environment.SetEnvironmentVariable("JAEGER_AGENT_HOST", tracingConfig.JaegerAgent); Environment.SetEnvironmentVariable("JAEGER_AGENT_PORT", "6831"); } else { //use the collector var jaegerUri = $"http://{tracingConfig.JaegerUrl}:14268/api/traces"; Environment.SetEnvironmentVariable("JAEGER_ENDPOINT", jaegerUri); } Environment.SetEnvironmentVariable("JAEGER_SERVICE_NAME", serviceName); Environment.SetEnvironmentVariable("JAEGER_SAMPLER_TYPE", "const"); var config = Jaeger.Configuration.FromEnv(loggerFactory); tracer = config.GetTracer(); GlobalTracer.Register(tracer); return(tracer); }); // Prevent endless loops when OpenTracing is tracking HTTP requests to Jaeger. services.Configure <HttpHandlerDiagnosticOptions>(options => { options.IgnorePatterns.Add(request => request.RequestUri.ToString().ToLower().Contains("/api/traces")); options.IgnorePatterns.Add(request => request.RequestUri.ToString().ToLower().EndsWith("hc")); options.IgnorePatterns.Add(request => request.RequestUri.ToString().ToLower().Contains("datadoghq")); }); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //EF連線字串 services.AddDbContext <SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection"))); //依賴注入 將介面設定建構物建 services.AddScoped <IRepository <Oldwhite, int>, UserRepository>(); services.AddOpenTracing(); //jwt service ConfigureAuthService(services); //Jaeger services.AddSingleton <ITracer>(serviceProvider => { string serviceName = "My Jaeger Demo"; Tracer tracer = new Tracer.Builder(serviceName) .WithSampler(new ConstSampler(true)) .Build(); GlobalTracer.Register(tracer); return(tracer); }); services.AddSwaggerGen(c => { c.SwaggerDoc( name: "v1", info: new Info { Title = "MySwaggerTest", Version = "1.0.0", Description = "This is Jason Test", Contact = new Contact { Email = "*****@*****.**", Name = "Json", Url = "www.xxx.com", }, License = new License { Name = "CC SS-SF-WF 4.0", Url = "", }, }); var filePath = Path.Combine(@".\bin\Debug\netcoreapp2.2", "Api.xml"); c.IncludeXmlComments(filePath); }); //services.AddHttpClient<IBasketService, BasketService>() // .SetHandlerLifetime(TimeSpan.FromMinutes(5)) // .AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>() // .AddPolicyHandler(); //services.AddHttpClient<IBasketService, BasketService>() // .SetHandlerLifetime(TimeSpan.FromMinutes(5)) //Sample. Default lifetime is 2 minutes // .AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>() // .AddPolicyHandler(GetRetryPolicy()) // .AddPolicyHandler(GetCircuitBreakerPolicy()); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Invalid number of arguments supplied"); Environment.Exit(-1); } switch (args[0]) { case "start": Parser.Default.ParseArguments <ServerOptions>(args).MapResult( (ServerOptions options) => { Console.WriteLine($"Started as process with id {System.Diagnostics.Process.GetCurrentProcess().Id}"); // Set hostname/ip address string hostname = options.Host; if (string.IsNullOrEmpty(hostname)) { Console.WriteLine($"Reading host address from {CART_SERVICE_ADDRESS} environment variable"); hostname = Environment.GetEnvironmentVariable(CART_SERVICE_ADDRESS); if (string.IsNullOrEmpty(hostname)) { Console.WriteLine($"Environment variable {CART_SERVICE_ADDRESS} was not set. Setting the host to 0.0.0.0"); hostname = "0.0.0.0"; } } // Set the port int port = options.Port; if (options.Port <= 0) { Console.WriteLine($"Reading cart service port from {CART_SERVICE_PORT} environment variable"); string portStr = Environment.GetEnvironmentVariable(CART_SERVICE_PORT); if (string.IsNullOrEmpty(portStr)) { Console.WriteLine($"{CART_SERVICE_PORT} environment variable was not set. Setting the port to 8080"); port = 8080; } else { port = int.Parse(portStr); } } // Setup LightStep Tracer Console.WriteLine($"Reading Lightstep Access Token {LIGHTSTEP_ACCESS_TOKEN} environment variable"); string serviceName = "cartservice"; string accessToken = Environment.GetEnvironmentVariable(LIGHTSTEP_ACCESS_TOKEN); string lsHost = Environment.GetEnvironmentVariable(LIGHTSTEP_HOST); int lsPort = Int32.Parse(Environment.GetEnvironmentVariable(LIGHTSTEP_PORT)); bool plaintext = (Environment.GetEnvironmentVariable(LIGHTSTEP_PLAINTEXT) == "true"); var satelliteOptions = new SatelliteOptions(lsHost, lsPort, plaintext); // BEGIN // Used for GCP Demo var overrideTags = new Dictionary <string, object> { { LightStepConstants.ComponentNameKey, serviceName }, { "service.version", RedisCartStore.updateUserProfileValue ? RedisCartStore.UnhealthyVersion : RedisCartStore.HealthyVersion }, { "cartservice.identity", "f738e221f8" }, { "lightstep.hostname", serviceName + "-0" }, }; // END var tracerOptions = new Options(accessToken). WithSatellite(satelliteOptions). WithTags(overrideTags); var lightStepTracer = new LightStep.Tracer( tracerOptions, new LightStepSpanRecorder(), new B3Propagator() ); GlobalTracer.Register(lightStepTracer); // Set redis cache host (hostname+port) ICartStore cartStore; string redis = ReadRedisAddress(options.Redis); // Redis was specified via command line or environment variable if (!string.IsNullOrEmpty(redis)) { // If you want to start cart store using local cache in process, you can replace the following line with this: // cartStore = new LocalCartStore(); cartStore = new RedisCartStore(redis); return(StartServer(hostname, port, cartStore)); } else { Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using local store"); Console.WriteLine("If you wanted to use Redis Cache as a backup store, you should provide its address via command line or REDIS_ADDRESS environment variable."); cartStore = new LocalCartStore(); } return(StartServer(hostname, port, cartStore)); }, errs => 1); break; default: Console.WriteLine("Invalid command"); break; } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(CorsPolicy, builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); // 加入 OpenTracing services.AddOpenTracing().AddSingleton <ITracer>(serviceProvider => { const string serviceName = "MockSite.Web"; var tracer = new Tracer.Builder(serviceName) .WithSampler(new ConstSampler(true)) .Build(); // 註冊 Jaeger tracer GlobalTracer.Register(tracer); return(tracer); }); services.AddMvc().AddNewtonsoftJson(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "MockSite API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", //The name of the previously defined security scheme. Type = ReferenceType.SecurityScheme } }, new List <string>(0) } }); }); // In production, the React files will be served from this directory services.AddSpaStaticFiles(config => { config.RootPath = "ClientApp/build"; }); // Configure JWT authentication services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidIssuer = _configuration.GetSection(AppSetting.JwtIssuerKey).Value, ValidAudience = _configuration.GetSection(AppSetting.JwtAudienceKey).Value, IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(_configuration.GetSection(AppSetting.JwtSecretKey).Value) ) }; }); // Configure DI for application services services.AddScoped <IUserService, UserService>(); var consulIp = _configuration.GetSection(ConsulConfigConst.ConsulIp).Value; var consulPort = _configuration.GetSection(ConsulConfigConst.ConsulPort).Value; var consulModule = _configuration.GetSection(ConsulConfigConst.ConsulModule).Value; var consulProvider = ConsulConfigProvider.LoadConsulConfig($"http://{consulIp}:{consulPort}/v1/kv/", consulModule.Split(',')); var consul = new ConfigurationBuilder() .AddJsonFile(consulProvider, "test.json", true, false) .Build(); // Register gRPC Service var userHost = $"{consul[HostNameConst.TestKey]}:{consul[PortConst.TestKey]}"; var tracingInterceptor = new ClientTracingInterceptor(GlobalTracer.Instance); services.AddSingleton(new Message.UserService.UserServiceClient( CreateKeepAliveWithoutCallChannel(userHost).Intercept(tracingInterceptor)) ); services.AddSingleton(new CurrencyService.CurrencyServiceClient( CreateKeepAliveWithoutCallChannel(userHost).Intercept(tracingInterceptor)) ); services.AddSingleton(new LocalizationService.LocalizationServiceClient( CreateKeepAliveWithoutCallChannel(userHost).Intercept(tracingInterceptor)) ); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.AddDiscoveryClient(Configuration); services.Configure <ConsulConfig>(Configuration.GetSection("consulConfig")); services.AddSingleton <IConsulClient, ConsulClient>(p => new ConsulClient(consultConfig => { var address = Configuration["consulConfig:address"]; consultConfig.Address = new Uri(address); })); var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["token:key"])); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["token:issuer"], ValidAudience = Configuration["token:audience"], IssuerSigningKey = signingKey }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { Console.WriteLine("OnAuthenticationFailed" + context.Exception.Message); return(Task.CompletedTask); }, OnTokenValidated = context => { Console.WriteLine("OnTokenValidated" + context.SecurityToken); return(Task.CompletedTask); }, }; }); services.AddSingleton <ITracer>(serviceProvider => { string serviceName = "SERVICE-SECURITY"; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); ISampler sampler = new ConstSampler(sample: true); ITracer tracer = new Tracer.Builder(serviceName) .WithLoggerFactory(loggerFactory) .WithSampler(sampler) .Build(); GlobalTracer.Register(tracer); return(tracer); }); services.AddOpenTracing(); services.Configure <HttpHandlerDiagnosticOptions>(options => { options.IgnorePatterns.Add(x => !x.RequestUri.IsLoopback); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddTransient <IUserService, UserService>(); }