Пример #1
0
        /// <summary>
        /// Gets a compressed javascript file from the cache, if the file doesn't exist it get compressed and added to the cache
        /// </summary>
        /// <param name="path">file path</param>
        /// <param name="contentType">content mime type</param>
        /// <param name="context">current http conext</param>
        /// <returns>compressed script string</returns>
        private string GetAndCompressSingleResource(string path, string url, string contentType, HttpContext context)
        {
            string body = "";

            //check cache first
            if (context.Cache[path] != null)
            {
                body = context.Cache[path].ToString();
            }
            else
            {
                ResourceType type = (contentType == "text/javascript") ? ResourceType.JS : ResourceType.CSS;

                ResourceBuilder builder = new ResourceBuilder();
                body = builder.CreateResource(path, url, type);

                //insert compressed file into cached
                CacheDependency cd = new CacheDependency(path);
                context.Cache.Insert(path, body, cd, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
            }

            return(body);
        }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddOpenTelemetryTracing(builder => builder
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("postman"))
                                             .AddAspNetCoreInstrumentation()
                                             .AddHttpClientInstrumentation((options) => options.Enrich = (activity, eventName, rawObject) =>
            {
                if (eventName.Equals("OnStartActivity"))
                {
                    if (rawObject is HttpRequestMessage httpRequest)
                    {
                        activity.SetTag("mail-message", httpRequest.Headers.First(x => x.Key.Equals("mail-message")).Value);
                    }
                }
            })
                                             .AddJaegerExporter()
                                             );

            services.AddScoped <DbContext, AppDbContext>();
            services.AddDbContext <AppDbContext>();
        }
Пример #3
0
        // To run this example, run the following command from
        // the reporoot\examples\Console\.
        // (eg: C:\repos\opentelemetry-dotnet\examples\Console\)
        //
        // dotnet run httpclient
        internal static object Run()
        {
            System.Console.WriteLine("Hello World!");

            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddHttpClientInstrumentation()
                                      .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("http-service-example"))
                                      .AddSource("http-client-test")
                                      .AddConsoleExporter()
                                      .Build();

            var source = new ActivitySource("http-client-test");

            using (var parent = source.StartActivity("incoming request", ActivityKind.Server))
            {
                using var client = new HttpClient();
                client.GetStringAsync("http://bing.com").GetAwaiter().GetResult();
            }

            System.Console.WriteLine("Press Enter key to exit.");

            return(null);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOpenTelemetryTracing((builder) =>
            {
                builder
                .AddSource(AppActivitySource.Name)
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Sanjay.Plutus"))
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddConsoleExporter()
                .AddJaegerExporter(o => o.AgentHost = "jaeger");
            });

            services.AddControllers();
            services.AddHttpClient("JSON Place holder").ConfigureHttpClient(c => c.BaseAddress = new Uri("https://jsonplaceholder.typicode.com"));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Plutus.Api", Version = "v1"
                });
            });
        }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddLogging(builder =>
        {
            builder.AddConsole();
            builder.SetMinimumLevel(LogLevel.Trace);
        });

        services.AddOpenTelemetryTracing(builder =>
        {
            builder.SetResourceBuilder(ResourceBuilder.CreateDefault()
                                       .AddService("SampleAPI")
                                       .AddTelemetrySdk()
                                       .AddEnvironmentVariableDetector())
            .AddSource("MassTransit")
            .AddAspNetCoreInstrumentation()
            .AddAzureMonitorTraceExporter(o =>
            {
                o.ConnectionString = Configuration["ApplicationInsightsConnectionString"];
            });
        });

        services.AddMassTransit(x =>
        {
            x.UsingAzureServiceBus((ctx, cfg) =>
            {
                cfg.Host(Configuration["AzureServiceBusConnectionString"],
                         h =>
                {
                });
            });
        });

        services.AddOpenApiDocument(cfg => cfg.PostProcess = d => d.Info.Title = "Sample-ApplicationInsights");
    }
        public async void AddAdditionalsAndRemovals_AddNewProperty_And_DeleteExistingProperty_Success()
        {
            var authorChange  = "*****@*****.**";
            var randomKeyword = "RandomKeyword";

            var resourceBuilder = new ResourceBuilder().GenerateSampleData()
                                  .WithEntryLifecycleStatus(ColidEntryLifecycleStatus.Published);
            var publishedResource = resourceBuilder.Build();

            publishedResource.Properties.Remove(Graph.Metadata.Constants.Resource.Keyword);

            var resourceBuilder2 = new ResourceBuilder().GenerateSampleData()
                                   .WithEntryLifecycleStatus(ColidEntryLifecycleStatus.Draft)
                                   .WithKeyword(randomKeyword)
                                   .WithPidUri(publishedResource.PidUri.ToString());

            var draftResource = resourceBuilder2.Build();

            draftResource.Properties.Remove(Graph.Metadata.Constants.Resource.Author);

            _mockMetadataService.Setup(mock => mock.GetMetadataForEntityTypeInConfig(It.IsAny <string>(), It.IsAny <string>())).Returns(_metadata);

            var revisionGraphPrefix = publishedResource.Id + "Rev" + 1;


            Assert.False(publishedResource.Properties.ContainsKey(Graph.Metadata.Constants.Resource.Keyword));
            Assert.True(publishedResource.Properties.ContainsKey(Graph.Metadata.Constants.Resource.Author));
            // Act
            var result = await _service.AddAdditionalsAndRemovals(publishedResource, draftResource);

            // Assert
            Assert.NotNull(result);

            Assert.False(result.Properties.ContainsKey(Graph.Metadata.Constants.Resource.Author));
            Assert.True(result.Properties.ContainsKey(Graph.Metadata.Constants.Resource.Keyword));
            Assert.Equal(result.Properties[Graph.Metadata.Constants.Resource.Keyword][0], randomKeyword);
        }
Пример #7
0
        // 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("AllowAllPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "OpenTelemetryApi", Version = "v1"
                });
            });

            services.AddHttpClient();

            services.AddSingleton(new ConnectionFactory
            {
                HostName    = Configuration["RabbitMq:HostName"],
                Port        = Configuration.GetValue <int>("RabbitMq:Port"),
                UserName    = Configuration["RabbitMq:UserName"],
                Password    = Configuration["RabbitMq:Password"],
                VirtualHost = Configuration["RabbitMq:VirtualHost"]
            });

            services.AddOpenTelemetryTracing(builder => builder
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(Configuration["Zipkin:AppName"]))
                                             .AddZipkinExporter(o =>
            {
                o.Endpoint = new Uri(Configuration["Zipkin:Url"]);
            })
                                             .AddAspNetCoreInstrumentation()
                                             );
        }
Пример #8
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();

            // Switch between Jaeger/Zipkin by setting UseExporter in appsettings.json.
            var exporter = this.Configuration.GetValue <string>("UseExporter").ToLowerInvariant();

            switch (exporter)
            {
            case "jaeger":
                services.AddOpenTelemetryTracing((builder) => builder
                                                 .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(this.Configuration.GetValue <string>("Jaeger:ServiceName")))
                                                 .AddAspNetCoreInstrumentation()
                                                 .AddJaegerExporter(jaegerOptions =>
                {
                    jaegerOptions.AgentHost = this.Configuration.GetValue <string>("Jaeger:Host");
                    jaegerOptions.AgentPort = this.Configuration.GetValue <int>("Jaeger:Port");
                }));
                break;

            case "zipkin":
                services.AddOpenTelemetryTracing((builder) => builder
                                                 .AddAspNetCoreInstrumentation()
                                                 .AddZipkinExporter(zipkinOptions =>
                {
                    zipkinOptions.ServiceName = this.Configuration.GetValue <string>("Zipkin:ServiceName");
                    zipkinOptions.Endpoint    = new Uri(this.Configuration.GetValue <string>("Zipkin:Endpoint"));
                }));
                break;

            default:
                services.AddOpenTelemetryTracing((builder) => builder
                                                 .AddAspNetCoreInstrumentation()
                                                 .AddConsoleExporter());
                break;
            }
        }
Пример #9
0
        public static IServiceCollection AddTracing(this IServiceCollection services, IHostEnvironment environment, IConfiguration configuration)
        {
            string agentHost;
            int    agentPort;

            if (environment.IsLocal())
            {
                agentHost = configuration["Jaeger:AgentHost"];
                agentPort = int.Parse(configuration["Jaeger:AgentPort"]);
            }
            else
            {
                agentHost = EnvironmentVariableHelper.Get("Jaeger:AgentHost", configuration);
                agentPort = int.Parse(EnvironmentVariableHelper.Get("Jaeger:AgentPort", configuration));
            }

            var connection  = ConnectionMultiplexer.Connect(EnvironmentVariableHelper.Get("Redis:Endpoint", configuration));
            var serviceName = $"{environment.ApplicationName}-{environment.EnvironmentName}";

            services.AddOpenTelemetryTracing(builder =>
            {
                builder.AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddRedisInstrumentation(connection)
                .AddSqlClientInstrumentation()
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName))
                .AddSource(environment.ApplicationName)
                .AddJaegerExporter(options =>
                {
                    options.AgentHost = agentHost;
                    options.AgentPort = agentPort;
                })
                .SetSampler(new AlwaysOnSampler());
            });

            return(services);
        }
Пример #10
0
        internal static object Run(OpenTracingShimOptions options)
        {
            // Enable OpenTelemetry for the source "MyCompany.MyProduct.MyWebServer"
            // and use Console exporter.
            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .AddSource("MyCompany.MyProduct.MyWebServer")
                                       .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyServiceName"))
                                       .AddConsoleExporter()
                                       .Build();

            // Instantiate the OpenTracing shim. The underlying OpenTelemetry tracer will create
            // spans using the "MyCompany.MyProduct.MyWebServer" source.
            var tracer = new TracerShim(
                TracerProvider.Default.GetTracer("MyCompany.MyProduct.MyWebServer"),
                Propagators.DefaultTextMapPropagator);

            // Not necessary for this example, though it is best practice per
            // the OpenTracing project to register a GlobalTracer.
            OpenTracing.Util.GlobalTracer.Register(tracer);

            // The code below is meant to resemble application code that has been instrumented
            // with the OpenTracing API.
            using (IScope parentScope = tracer.BuildSpan("Parent").StartActive(finishSpanOnDispose: true))
            {
                parentScope.Span.SetTag("my", "value");
                parentScope.Span.SetOperationName("parent span new name");

                // The child scope will automatically use parentScope as its parent.
                using IScope childScope = tracer.BuildSpan("Child").StartActive(finishSpanOnDispose: true);
                childScope.Span.SetTag("Child Tag", "Child Tag Value").SetTag("ch", "value").SetTag("more", "attributes");
            }

            System.Console.WriteLine("Press Enter key to exit.");
            System.Console.ReadLine();

            return(null);
        }
Пример #11
0
    public static IHostBuilder ConfigureOpenTelemetry(this IHostBuilder builder, IConfiguration cfg)
    {
        var configuration = cfg.GetSection("dolittle:runtime:opentelemetry").Get <OpenTelemetryConfiguration>();

        if (configuration?.Endpoint is null)
        {
            return(builder);
        }

        if (!Uri.TryCreate(configuration.Endpoint, UriKind.RelativeOrAbsolute, out var otlpEndpoint))
        {
            var logger = LoggerFactory.Create(opt => opt.AddConfiguration(cfg)).CreateLogger(typeof(OpenTelemetryConfigurationExtensions));
#pragma warning disable CA1848
            logger.LogWarning("Unable to parse otlp endpoint {Input}", configuration.Endpoint);
#pragma warning restore CA1848
            return(builder);
        }

        if (otlpEndpoint.Scheme.Equals("http"))
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
        }

        var resourceBuilder = ResourceBuilder.CreateDefault().AddService(configuration.ServiceName);

        if (configuration.Logging)
        {
            builder.AddOpenTelemetryLogging(resourceBuilder, otlpEndpoint);
        }

        if (configuration.Tracing)
        {
            builder.AddOpenTelemetryTracing(resourceBuilder, otlpEndpoint);
        }

        return(builder);
    }
Пример #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <HttpUrl>(Configuration.GetSection("HttpUrl"));

            services.AddControllers();

            services.AddOpenTelemetryTracing((serviceProvider, tracerBuilder) =>
            {
                // Make the logger factory available to the dependency injection
                // container so that it may be injected into the OpenTelemetry Tracer.
                var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

                // Adds the New Relic Exporter & enable distributed tracing in config
                tracerBuilder
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(this.Configuration.GetValue <string>("NewRelic:ServiceName")))
                .AddNewRelicExporter(options =>
                {
                    options.Endpoint = new Uri(this.Configuration.GetValue <string>("NewRelic:Endpoint"));
                    options.ApiKey   = this.Configuration.GetValue <string>("NewRelic:ApiKey");
                })
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation();
            });
        }
Пример #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

            services.AddDbContext <FinanceContext>(options =>
                                                   options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddCors();

            services.AddOpenTelemetryTracing(config => config
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Divergent.Finance.API"))
                                             .AddZipkinExporter(o =>
            {
                o.Endpoint = new Uri("http://localhost:9411/api/v2/spans");
            })
                                             .AddJaegerExporter(c =>
            {
                c.AgentHost = "localhost";
                c.AgentPort = 6831;
            })
                                             .AddAspNetCoreInstrumentation()
                                             .AddSqlClientInstrumentation(opt => opt.SetDbStatementForText = true)
                                             );
        }
        public void SetUp()
        {
            _httpClientWrapper = Substitute.For <IHttpClientWrapper>();
            _authenticate      = Substitute.For <IAuthenticate>();

            _resourceBuilder = new ResourceBuilder();
            _resourceBuilder
            .WithDataTemplate()
            .WithLink("/rels/a /rels/self /rels/b", "web-address")
            .Build();

            var configuration = Substitute.For <IConfiguration>();

            configuration.GetValue <string>("ApiMediaType").Returns("test-media-value");
            _sut = new ApiClient(_httpClientWrapper, _authenticate, configuration);

            _httpClientWrapper
            .Send(
                Arg.Any <string>(),
                Arg.Any <HttpMethod>(),
                Arg.Any <HttpContent>(),
                Arg.Any <IDictionary <string, string> >())
            .Returns(NotFoundResponse);
        }
Пример #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddHttpContextAccessor();

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .WriteTo.File(new CompactJsonFormatter(), @"C:\temp\testlog\log.json", shared: true)
                         .MinimumLevel.Error()
                         .CreateLogger();

            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
            services.AddOpenTelemetryTracing(tracing =>
            {
                tracing.AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .SetSampler(new AlwaysOnSampler())
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(typeof(Startup).Assembly.GetName().Name))
                .AddZipkinExporter(options =>
                {
                    options.Endpoint = new Uri("http://localhost:9411/api/v2/spans");
                });
            });
        }
Пример #16
0
        public void ToOtlpResourceTest(bool includeServiceNameInResource)
        {
            // Targeted test to cover OTel Resource to OTLP Resource
            // conversion, independent of signals.
            var resourceBuilder = ResourceBuilder.CreateEmpty();

            if (includeServiceNameInResource)
            {
                resourceBuilder.AddService("service-name", "ns1");
            }

            var resource     = resourceBuilder.Build();
            var otlpResource = resource.ToOtlpResource();

            if (includeServiceNameInResource)
            {
                Assert.Contains(otlpResource.Attributes, (kvp) => kvp.Key == ResourceSemanticConventions.AttributeServiceName && kvp.Value.StringValue == "service-name");
                Assert.Contains(otlpResource.Attributes, (kvp) => kvp.Key == ResourceSemanticConventions.AttributeServiceNamespace && kvp.Value.StringValue == "ns1");
            }
            else
            {
                Assert.Contains(otlpResource.Attributes, (kvp) => kvp.Key == ResourceSemanticConventions.AttributeServiceName && kvp.Value.ToString().Contains("unknown_service:"));
            }
        }
Пример #17
0
        public static IServiceCollection RegisterOpenTelemetry(this IServiceCollection services, Settings settings)
        {
            services.AddOpenTelemetryTracing(builder =>
            {
                builder
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(settings.ServiceName))
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation(opt =>
                {
                    opt.Filter = (httpRequestMessage) =>
                    {
                        return(httpRequestMessage.Headers.Contains("X-Amz-Target"));
                    };

                    opt.Enrich = (activity, eventName, rawObject) =>
                    {
                        if (eventName.Equals("OnStartActivity"))
                        {
                            if (rawObject is HttpRequestMessage request && request.Headers.Contains("X-Amz-Target"))
                            {
                                activity.AddDynamoDbTags(settings.TableName, string.Join(",", request.Headers.GetValues("X-Amz-Target")));
                            }
                        }
                        else if (eventName.Equals("OnException"))
                        {
                            if (rawObject is Exception exception)
                            {
                                activity.SetTag("stackTrace", exception.StackTrace);
                            }
                        }
                    };
                })
                .ConfigureExporter(settings.DistributedTracingOptions);
            });
            return(services);
        }
Пример #18
0
        // 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.AddGrpc();
            services.AddGrpcReflection();
            services.AddGrpcHttpApi();
            services.AddSingleton <IDataChunkLedger, DataChunkLedger>();

            services.AddSingleton(new ActivitySource("Workflows"));

            // This one creates a singleton of the type TracerProvider.
            services.AddOpenTelemetryTracing((builder) =>
            {
                builder
                // Set the resource name for prettier printing.
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("DataMaster"))
                // Register the source which emits our own activities.
                .AddSource("Worfklows")
                // For incoming requests
                .AddAspNetCoreInstrumentation()
                // For outgoing requests
                .AddGrpcClientInstrumentation()
                .AddHttpClientInstrumentation()
                // Export everything to the console.
                // .AddConsoleExporter();
                .AddJaegerExporter(o =>
                {
                    o.AgentHost             = Configuration["NODE_IP"];
                    o.MaxPayloadSizeInBytes = 65000;
                });
            });

            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });
        }
Пример #19
0
        // 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)
        {
            string     redisAddress = Configuration["REDIS_ADDR"];
            ICartStore cartStore    = null;

            if (!string.IsNullOrEmpty(redisAddress))
            {
                cartStore = new RedisCartStore(redisAddress);
            }
            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_ADDR environment variable.");
                cartStore = new LocalCartStore();
            }

            // Initialize the redis store
            cartStore.InitializeAsync().GetAwaiter().GetResult();
            Console.WriteLine("Initialization completed");
            services.AddSingleton <ICartStore>(cartStore);

            services.AddGrpc();
            string otelAddress = Configuration["OTEL_COLLECTOR_ADDR"];

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            services.AddOpenTelemetryTracing((builder) => builder
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault()
                                                                 .AddAttributes(new Dictionary <string, object>
            {
                ["telemetry.sdk.language"] = "dotnet",
            })
                                                                 .AddService(this.Configuration.GetValue <string>("Otel:ServiceName")))
                                             .AddAspNetCoreInstrumentation()
                                             .AddRedisInstrumentation(cartStore.GetConnection())
                                             .AddOtlpExporter(opt => opt.Endpoint = new Uri(otelAddress)));
        }
Пример #20
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService <Worker>();

            services.AddStackExchangeRedisCache(options =>
            {
                var connString =
                    $"{hostContext.Configuration["Redis:Host"]}:{hostContext.Configuration["Redis:Port"]}";
                options.Configuration = connString;
            });

            services.AddOpenTelemetryTracing(builder =>
            {
                var provider          = services.BuildServiceProvider();
                IConfiguration config = provider
                                        .GetRequiredService <IConfiguration>();

                builder.AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .Configure((sp, builder) =>
                {
                    RedisCache cache = (RedisCache)sp.GetRequiredService <IDistributedCache>();
                    builder.AddRedisInstrumentation(cache.GetConnection());
                })
                .AddSource(nameof(Worker))
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("App4"))
                .AddJaegerExporter(opts =>
                {
                    opts.AgentHost           = config["Jaeger:AgentHost"];
                    opts.AgentPort           = Convert.ToInt32(config["Jaeger:AgentPort"]);
                    opts.ExportProcessorType = ExportProcessorType.Simple;
                });
            });
        });
Пример #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "SampleApiDue", Version = "v1"
                });
            });

            services.AddLogging();
            services.AddOpenTelemetryTracing((builder) => builder
                                             .AddSource("SampleDue")
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("SampleApiDueService").AddTelemetrySdk())
                                             .AddAspNetCoreInstrumentation()
                                             .AddHttpClientInstrumentation()
                                             .AddZipkinExporter(b =>
            {
                var zipkinHostName = Environment.GetEnvironmentVariable("ZIPKIN_HOSTNAME") ?? "localhost";
                b.Endpoint         = new Uri($"http://{zipkinHostName}:9411/api/v2/spans");
            }));

            services.Configure <AspNetCoreInstrumentationOptions>(Configuration.GetSection("AspNetCoreInstrumentation"));
        }
Пример #22
0
        private static object RunWithActivitySource()
        {
            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use Console exporter.
            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .AddSource("Samples.SampleClient", "Samples.SampleServer")
                                      .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("console-test"))
                                      .AddConsoleExporter()
                                      .Build();

            // The above line is required only in applications
            // which decide to use OpenTelemetry.
            using (var sample = new InstrumentationWithActivitySource())
            {
                sample.Start();

                System.Console.WriteLine("Traces are being created and exported " +
                                         "to Console in the background. " +
                                         "Press ENTER to stop.");
                System.Console.ReadLine();
            }

            return(null);
        }
Пример #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSwaggerGen();

            services.AddHttpClient("ServiceB")
            .ConfigureHttpClient(options => options.BaseAddress = new Uri(Configuration.GetValue <string>("ServiceB.Api")));

            services.AddHttpClient("ServiceC")
            .ConfigureHttpClient(options => options.BaseAddress = new Uri(Configuration.GetValue <string>("ServiceC.Api")));

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            services.AddOpenTelemetryTracing(builder =>
            {
                builder
                .SetResourceBuilder(ResourceBuilder.CreateDefault()
                                    .AddService("Service A")
                                    .AddAttributes(new [] { new KeyValuePair <string, object>("deployment.environment", Environment.EnvironmentName) }))
                .AddAspNetCoreInstrumentation(options =>
                {
                    options.RecordException = true;
                })
                .AddHttpClientInstrumentation()
                .AddSqlClientInstrumentation(options =>
                {
                    options.SetDbStatementForText            = true;
                    options.SetDbStatementForStoredProcedure = true;
                    options.RecordException = true;
                })
                .AddOtlpExporter(options =>
                {
                    options.Endpoint = new Uri(Configuration.GetValue <string>("OpenTelemetryCollector"));
                });
            });
        }
Пример #24
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();
            services.AddSingleton <IncrementingCounter>();

            if (_configuration.GetValue <bool>(EnableOpenTelemetryKey))
            {
                services.AddOpenTelemetryTracing(telemetry =>
                {
                    telemetry.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("aggregator"));
                    telemetry.AddZipkinExporter();
                    telemetry.AddGrpcClientInstrumentation();
                    telemetry.AddHttpClientInstrumentation();
                    telemetry.AddAspNetCoreInstrumentation();
                });
            }

            // These clients will call back to the server
            services
            .AddGrpcClient <Greeter.GreeterClient>((s, o) => { o.Address = GetCurrentAddress(s); })
            .EnableCallContextPropagation();
            services
            .AddGrpcClient <Counter.CounterClient>((s, o) => { o.Address = GetCurrentAddress(s); })
            .EnableCallContextPropagation();
Пример #25
0
        /// <summary>Mostra o índice</summary>
        private void writeIndex(HtmlTextWriter writer, ResourceBuilder toShow)
        {
            Ruler current = null;

            if (Context.User.IsInRole("ruler"))
            {
                User user = (User)Context.User;
                current = Universe.instance.getRuler(user.RulerId);
            }

            writer.WriteLine("<a name='TOP'></a>");
            writer.WriteLine("<div class='planetInfoZoneTitle'><b>{0}</b></div>", info.getContent(category));
            writer.WriteLine("<table class='planetFrame'>");
            foreach (ResourceFactory factory in toShow.Values)
            {
                writer.WriteLine("<tr>");
                if (current != null && factory.Category == "Research")
                {
                    string img = "no.gif";
                    if (current.isResourceAvailable(category, factory.Name))
                    {
                        img = "yes.gif";
                    }
                    writer.WriteLine("<td><img src='{0}' /></td>", OrionGlobals.getCommonImagePath(img));
                }
                writer.WriteLine("<td class='resource'><a href='#{0}' class='note'>{1}</a></td>",
                                 factory.Name, info.getContent(factory.Name),
                                 info.getContent(factory.Name + "_description")
                                 );
                writer.WriteLine("<td class='resourceCell'>{0}</td>",
                                 info.getContent(factory.Name + "_description")
                                 );
                writer.WriteLine("</tr>");
            }
            writer.WriteLine("</table>");
        }
Пример #26
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureServices((services) =>
        {
            // OpenTelemetry
            services.AddOpenTelemetryTracing((tracerProvider) =>
            {
                // Resource
                tracerProvider.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("CLK-OpenTelemetryLab-Service"));

                // Source
                tracerProvider.AddSource("CLK.OpenTelemetryLab.MainModule");

                // Exporter
                tracerProvider.AddConsoleExporter();
                tracerProvider.AddJaegerExporter(options =>
                {
                    options.AgentHost = "localhost";
                });
            });

            // ProgramService
            services.AddHostedService <ProgramService>();
        });
Пример #27
0
        public async Task Post_CheckDuplicate_ShouldReturn_Error_Duplicate_MultipleEndpointTargetUrisSameAsRepoTargetUris()
        {
            var firstEndpoint = new DistributionEndpointBuilder()
                                .GenerateSampleData()
                                .WithNetworkAddress("http://ID1012")
                                .Build();

            var secondEndpointEndpoint = new DistributionEndpointBuilder()
                                         .GenerateSampleData()
                                         .WithNetworkAddress("http://ID5021")
                                         .Build();

            var endpoints = new List <Entity>()
            {
                firstEndpoint, secondEndpointEndpoint
            };

            var resourceRequestDto = new ResourceBuilder()
                                     .GenerateSampleData()
                                     .WithDistributionEndpoint(endpoints)
                                     .BuildRequestDto();

            var resourceWriteResult = await CheckDuplicate(resourceRequestDto);

            // Assert
            _output.WriteLine(resourceWriteResult.Content);
            Assert.Equal(HttpStatusCode.OK, resourceWriteResult.Response.StatusCode);
            Assert.Equal(2, resourceWriteResult.ValidationResults.Count);
            Assert.All(resourceWriteResult.ValidationResults, property =>
            {
                Assert.Equal(Graph.Metadata.Constants.Resource.DistributionEndpoints.HasNetworkAddress, property.Path);
                Assert.Equal(ValidationResultSeverity.Info, property.ResultSeverity);
            });
            Assert.Contains(resourceWriteResult.ValidationResults, property => property.Node == firstEndpoint.Id);
            Assert.Contains(resourceWriteResult.ValidationResults, property => property.Node == secondEndpointEndpoint.Id);
        }
Пример #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <SampleRepository>();

            services.AddControllers();

            services.AddSwaggerGen();

            services.AddSingleton <IConnectionMultiplexer>(ConnectionMultiplexer.Connect(Configuration.GetConnectionString("Redis")));

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            services.AddOpenTelemetryTracing((serviceProvider, builder) =>
            {
                builder
                .SetResourceBuilder(ResourceBuilder.CreateDefault()
                                    .AddService("Service C")
                                    .AddAttributes(new[] { new KeyValuePair <string, object>("deployment.environment", Environment.EnvironmentName) }))
                .AddAspNetCoreInstrumentation(options =>
                {
                    options.RecordException = true;
                })
                .AddHttpClientInstrumentation()
                .AddSqlClientInstrumentation(options =>
                {
                    options.SetDbStatementForText            = true;
                    options.SetDbStatementForStoredProcedure = true;
                    options.RecordException = true;
                })
                .AddRedisInstrumentation(serviceProvider.GetService <IConnectionMultiplexer>())
                .AddSource("ServiceC.*")
                .AddOtlpExporter(options =>
                {
                    options.Endpoint = new Uri(Configuration.GetValue <string>("OpenTelemetryCollector"));
                });
            });
        }
Пример #29
0
        public void Gets_regions_from_acceptable_values()
        {
            var resource = new ResourceBuilder()
                           .WithDataTemplate()
                           .WithGroup("electricityRegion")
                           .WithItem("region")
                           .WithAcceptableValue("1", "region-1")
                           .WithAcceptableValue("2", "region-2")
                           .WithItem("something-else")
                           .WithAcceptableValue("x", "xxxxxxx")
                           .Build();

            var region = new RegionModel(resource);

            var regions = region.GetRegions();

            Assert.That(
                regions.Select(x => x.Id),
                Is.EquivalentTo(new[] { "1", "2" }));

            Assert.That(
                regions.Select(x => x.Name),
                Is.EquivalentTo(new[] { "region-1", "region-2" }));
        }
Пример #30
0
        public static void Main()
        {
            var resourceAttributes = new Dictionary <string, object> {
                { "service.name", "my-service" }, { "service.namespace", "my-namespace" }, { "service.instance.id", "my-instance" }
            };
            var resourceBuilder = ResourceBuilder.CreateDefault().AddAttributes(resourceAttributes);

            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .SetResourceBuilder(resourceBuilder)
                                       .AddSource("Demo.DemoServer")
                                       .AddSource("Demo.DemoClient")
                                       .AddAzureMonitorTraceExporter(o => {
                o.ConnectionString = $"InstrumentationKey=Ikey;";
            })
                                       .Build();

            using (var sample = new InstrumentationWithActivitySource())
            {
                sample.Start();

                System.Console.WriteLine("Press ENTER to stop.");
                System.Console.ReadLine();
            }
        }
Пример #31
0
        /// <summary>Mostra todos os recursos</summary>
        private void writeEntries( HtmlTextWriter writer, ResourceBuilder toShow )
        {
            foreach( ResourceFactory factory in toShow.Values ) {

                writer.WriteLine("<a name='{0}'></a>", factory.Name);
                writer.WriteLine("<div class='planetInfoZoneTitle'><a href='#TOP'>^</a> <b>{0}</b></div>", info.getContent(factory.Name));
                writer.WriteLine("<table class='planetFrame'>");

                writer.WriteLine("<tr>");
                writer.WriteLine("<td class='resource'>{0}</td>", info.getContent("description"));
                writer.WriteLine("<td class='resourceCell'>{0}</td>", info.getContent(factory.Name + "_description"));
                writer.WriteLine("</tr>");

                writeActions(writer, "dependencies", factory.Dependencies);
                writeActions(writer, "onavailable", factory.OnAvailableActions);
                writeActions(writer, "cost", factory.CostActions);
                writeDuration(writer, factory );
                writeActions(writer, "onturn", factory.OnTurnActions);
                writeActions(writer, "oncomplete", factory.OnCompleteActions);
                writeActions(writer, "onremove", factory.OnRemoveActions);
                writeActions(writer, "onCancelDuringBuild", factory.OnCancelDuringBuild);
                writeModifiers(writer, "modifiers", factory.Modifiers);
                writeAtts(writer, "attributes", factory.Attributes);

                writer.WriteLine("</table>");
            }
        }
Пример #32
0
        /// <summary>Mostra o índice</summary>
        private void writeIndex(HtmlTextWriter writer, ResourceBuilder toShow)
        {
            Ruler current = null;
            if(Context.User.IsInRole("ruler")) {
                User user = (User) Context.User;
                current = Universe.instance.getRuler(user.RulerId);
            }

            writer.WriteLine("<a name='TOP'></a>");
            writer.WriteLine("<div class='planetInfoZoneTitle'><b>{0}</b></div>", info.getContent(category));
            writer.WriteLine("<table class='planetFrame'>");
            foreach( ResourceFactory factory in toShow.Values ) {
                writer.WriteLine("<tr>");
                if( current != null && factory.Category == "Research") {
                    string img = "no.gif";
                    if(current.isResourceAvailable(category, factory.Name) ){
                        img = "yes.gif";
                    }
                    writer.WriteLine("<td><img src='{0}' /></td>", OrionGlobals.getCommonImagePath(img));
                }
                writer.WriteLine("<td class='resource'><a href='#{0}' class='note'>{1}</a></td>",
                        factory.Name, info.getContent(factory.Name),
                        info.getContent(factory.Name + "_description")
                    );
                writer.WriteLine("<td class='resourceCell'>{0}</td>",
                        info.getContent(factory.Name + "_description")
                    );
                writer.WriteLine("</tr>");
            }
            writer.WriteLine("</table>");
        }