Exemple #1
0
        public IHttpActionResult GetProduct(int id)
        {
            AWSXRayRecorder recorder = new AWSXRayRecorder();
            Product         product  = null;

            if (id <= 10)
            {
                product = products.FirstOrDefault((p) => p.Id == id);
            }
            else
            {
                try
                {
                    product = GetItem(id);
                }catch (Exception ex)
                {
                    recorder.AddException(ex);
                    throw;
                }
            }
            if (product == null)
            {
                recorder.AddAnnotation("MissingItem", id);
                return(NotFound());
            }

            return(Ok(product));
        }
 public new void TestCleanup()
 {
     base.TestCleanup();
     _recorder.Dispose();
     _recorder = null;
     _subscription.Dispose();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AWSXRayMiddleware" /> class.
 /// </summary>
 /// <param name="next">Instance of <see cref="RequestDelegate"/></param>
 /// <param name="segmentNamingStrategy">The segment naming strategy.</param>
 /// <param name="configuration">The instance of <see cref="IConfiguration" />.</param>
 /// <exception cref="ArgumentNullException">segmentNamingStrategy is null.</exception>
 public AWSXRayMiddleware(RequestDelegate next, SegmentNamingStrategy segmentNamingStrategy, IConfiguration configuration)
 {
     AWSXRayRecorder.InitializeInstance(configuration);
     _recorder             = AWSXRayRecorder.Instance;
     _next                 = next;
     SegmentNamingStrategy = segmentNamingStrategy ?? throw new ArgumentNullException("segmentNamingStrategy");
 }
Exemple #4
0
 public void Initialize()
 {
     Environment.SetEnvironmentVariable(AWSXRayRecorder.LambdaTaskRootKey, "test");
     Environment.SetEnvironmentVariable(AWSXRayRecorder.LambdaTraceHeaderKey, _traceHeaderValue);
     _recorder = new AWSXRayRecorderBuilder().Build();
     AWSXRayRecorder.InitializeInstance(recorder: _recorder);
 }
Exemple #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddAWSProvider(Configuration.GetAWSLoggingConfigSection());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSession();


            //Enable middleware to serve generated Swagger as a JSON endpoint, and generate swagger-ui (HTML, etc)
            app.UseSwagger(x => x.RouteTemplate = "api/cart/{documentName}/swagger.json");
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/api/cart/docs/swagger.json", "re:Invent WIN401 Cart API");
                c.RoutePrefix = "api/cart/swagger";
            });

            AWSXRayRecorder.InitializeInstance(Configuration);
            app.UseXRay("CartService");
            app.MergeAuthorizationHeaderWithSession();
            app.UseAuthentication();
            app.UseCors("AllowAllOrigins");
            app.UseMvc();
        }
Exemple #6
0
 public void TestLoadServiceInfoManifestInvalidPath()
 {
     using (var recorder = new AWSXRayRecorder())
     {
         var handler = new AWSSdkTracingHandler(recorder, @"IncorrectPath.abc");
     }
 }
Exemple #7
0
        public static void ClassInit(TestContext context)
        {
            _recorder = new AWSXRayRecorder();
#if NET45
            _handler = new AWSSdkTracingHandler(_recorder, _path);
#endif
        }
Exemple #8
0
 public void Initialize()
 {
     recorder = new AWSXRayRecorder();
     recorder.BeginSegment("Test EF6");
     connection = new SQLiteConnection(connectionString);
     connection.Open();
 }
 private void InitWithDefaultAWSWhitelist(AWSXRayRecorder recorder)
 {
     using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(DefaultAwsWhitelistManifestResourceName))
     {
         Init(recorder, stream);
     }
 }
Exemple #10
0
        public void TestInitializeInstanceWithRecorder3() // setting custom daemon address to DefaultSamplingStrategy()
        {
            string          daemonAddress       = "udp:127.0.0.2:2001 tcp:127.0.0.1:2000";
            IPEndPoint      expectedUDPEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.2"), 2001);
            IPEndPoint      expectedTCPEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2000);
            AWSXRayRecorder recorder            = BuildAWSXRayRecorder(daemonAddress: daemonAddress);

#if NET45
            AWSXRayRecorder.InitializeInstance(recorder);
#else
            AWSXRayRecorder.InitializeInstance(recorder: recorder);
#endif
            Assert.AreEqual(AWSXRayRecorder.Instance.SamplingStrategy, recorder.SamplingStrategy);
            Assert.AreEqual(typeof(DefaultSamplingStrategy), recorder.SamplingStrategy.GetType()); // Default startegy set
            Assert.AreEqual(typeof(UdpSegmentEmitter), recorder.Emitter.GetType());                // Default emitter set

            var udpEmitter = (UdpSegmentEmitter)recorder.Emitter;
            Assert.AreEqual(expectedUDPEndpoint, udpEmitter.EndPoint);

            var defaultStartegy = (DefaultSamplingStrategy)recorder.SamplingStrategy;
            Assert.AreEqual(expectedUDPEndpoint, defaultStartegy.DaemonCfg.UDPEndpoint);
            Assert.AreEqual(expectedTCPEndpoint, defaultStartegy.DaemonCfg.TCPEndpoint);

            recorder.Dispose();
        }
Exemple #11
0
        public static void ContinueFrom(this AWSXRayRecorder recorder, string serviceName, Message message)
        {
            var traceHeader = message?.GetTraceHeader() ?? new TraceHeader
            {
                RootTraceId = TraceId.NewId(),
                ParentId    = null,
                Sampled     = SampleDecision.Unknown
            };

            string ruleName = null;

            if (traceHeader.Sampled == SampleDecision.Unknown || traceHeader.Sampled == SampleDecision.Requested)
            {
                var samplingInput  = new SamplingInput(serviceName);
                var sampleResponse = recorder.SamplingStrategy.ShouldTrace(samplingInput);
                traceHeader.Sampled = sampleResponse.SampleDecision;
                ruleName            = sampleResponse.RuleName;
            }

            var samplingResponse = new SamplingResponse(ruleName, traceHeader.Sampled);

            recorder
            .BeginSegment
            (
                serviceName,
                traceHeader.RootTraceId,
                traceHeader.ParentId,
                samplingResponse
            );
        }
        public async Task TestXrayContextMissingStrategySendAsync() // Test that respects ContextMissingStrategy
        {
            _recorder = new MockAWSXRayRecorder();

#if NET45
            AWSXRayRecorder.InitializeInstance(_recorder);
#else
            AWSXRayRecorder.InitializeInstance(recorder: _recorder);
#endif

            AWSXRayRecorder.Instance.ContextMissingStrategy = Core.Strategies.ContextMissingStrategy.LOG_ERROR;

            Assert.IsFalse(AWSXRayRecorder.Instance.IsTracingDisabled());

            _recorder.EndSegment();

            // The test should not break. No segment is available in the context, however, since the context missing strategy is log error,
            // no exception should be thrown by below code.

            var request = new HttpRequestMessage(HttpMethod.Get, URL);
            using (var response = await _httpClient.SendAsync(request))
            {
                Assert.IsNotNull(response);
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
Exemple #13
0
        /// <summary>
        /// Instrument tracing configurations, such as pluggins, sampling rules, service name, etc., from AspNet Core application.
        /// </summary>
        public static XRayAutoInstrumentationOptions Register()
        {
            IConfiguration configuration = null;

            try
            {
                // Get the json file
                configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                .Build();
            }
            catch (Exception e)
            {
                _logger.Error(e, "Can't fetch configuration from appsettings.json file.");
            }

            // Initialize a new instance of the AWSXRayRecorder with given instance of IConfiguration.
            // If configuration is null, default value will be set.
            AWSXRayRecorder.InitializeInstance(configuration);

            var xrayAutoInstrumentationOptions = GetXRayAutoInstrumentationOptions(configuration);

            // Set daemon address
            AWSXRayRecorder.Instance.SetDaemonAddress(xrayAutoInstrumentationOptions.DaemonAddress);

            return(xrayAutoInstrumentationOptions);
        }
Exemple #14
0
        public BlogPostsUpdate()
        {
            secrets = GetSecrets.GetSecretsDictionary();
            string connstr = GetSecrets.GetSecretConnectionString();

            bpc = GetConnectionString.GetContext(connstr);
            AWSXRayRecorder.InitializeInstance();
        }
        public void TestExceptionStrategy1() // valid input
        {
            var exceptionStrategy = new DefaultExceptionSerializationStrategy(10);
            var recorder          = new AWSXRayRecorderBuilder().WithExceptionSerializationStrategy(exceptionStrategy).Build(); // set custom stackframe size

            AWSXRayRecorder.InitializeInstance(recorder: recorder);
            Assert.AreSame(exceptionStrategy, AWSXRayRecorder.Instance.ExceptionSerializationStrategy);
        }
Exemple #16
0
        public Startup(IConfiguration configuration)
        {
            AWSXRayRecorder.InitializeInstance(configuration);
            AWSXRayRecorder.RegisterLogger(Amazon.LoggingOptions.Console);
            AWSSDKHandler.RegisterXRayForAllServices();

            Configuration = configuration;
        }
Exemple #17
0
        static Startup() // create log4j instance
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            log = LogManager.GetLogger(typeof(Startup));
            AWSXRayRecorder.RegisterLogger(LoggingOptions.Log4Net);
        }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            // AWS X-Ray
            // pass IConfiguration object that reads appsettings.json file
            AWSXRayRecorder.InitializeInstance(configuration);
        }
 public Startup(IConfiguration configuration, IWebHostEnvironment env)
 {
     _env          = env;
     Configuration = configuration;
     AWSXRayRecorder.InitializeInstance(configuration);
     AWSSDKHandler.RegisterXRayForAllServices();
     AWSXRayRecorder.Instance.ContextMissingStrategy = ContextMissingStrategy.LOG_ERROR;
 }
Exemple #20
0
 static AWSXRayASPNET()
 {
     if (!AWSXRayRecorder.IsCustomRecorder)                                      // If custom recorder is not set
     {
         AWSXRayRecorder.Instance.SetTraceContext(new HybridContextContainer()); // configure Trace Context
     }
     _recorder = AWSXRayRecorder.Instance;
 }
        public void TestInitialize()
        {
            _recorder = new AWSXRayRecorder();
#if NET45
            AWSXRayRecorder.InitializeInstance(_recorder);
#else
            AWSXRayRecorder.InitializeInstance(recorder: _recorder);
#endif
        }
Exemple #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AWSSdkTracingHandler" /> class.
        /// </summary>
        /// <param name="recorder">An instance of <see cref="AWSXRayRecorder" /> used to start and stop segment</param>
        /// <exception cref="System.ArgumentNullException">Thrown when recorder is null.</exception>
        public AWSSdkTracingHandler(AWSXRayRecorder recorder)
        {
            if (recorder == null)
            {
                throw new ArgumentNullException("recorder");
            }

            InitWithDefaultAWSWhitelist(recorder);
        }
Exemple #23
0
 public void TestOverrideContextMissingStrategyToLogError()
 {
     Environment.SetEnvironmentVariable(AWSXRayRecorder.EnvironmentVariableContextMissingStrategy, "log_error");
     using (var recorder = new AWSXRayRecorder())
     {
         recorder.ContextMissingStrategy = ContextMissingStrategy.RUNTIME_ERROR;
         Assert.AreEqual(ContextMissingStrategy.LOG_ERROR, recorder.ContextMissingStrategy);
     }
 }
        /// <summary>
        /// Configures tracing services on the service collection.
        /// </summary>
        /// <param name="services">The service collection to configure.</param>
        public static void ConfigureTracingServices(this IServiceCollection services)
        {
            AWSXRayRecorder.InitializeInstance();

            services.AddSingleton <DelegatingHandler, HttpClientXRayTracingHandler>();
            services.TryAddSingleton <ITracingService, AwsXRayTracingService>();
            services.TryAddSingleton <ITracingIdService, AwsXRayTracingIdService>();
            services.TryAddSingleton <IAWSXRayRecorder>(AWSXRayRecorder.Instance);
        }
Exemple #25
0
        public void TestInitialize()
        {
            _recorder = new AWSXRayRecorder();
            AWSXRayRecorder.InitializeInstance(recorder: _recorder);

            // In-memory database only exists while the connection is open
            connection = new SqliteConnection("DataSource=:memory:");
            connection.Open();
        }
        public void TestCollecSqlQueriesTrue()
        {
            IConfiguration configuration = BuildConfiguration("CollectSqlQueriesTrue.json");

            _xRayOptions = XRayConfiguration.GetXRayOptions(configuration);
            AWSXRayRecorder.InitializeInstance(configuration);

            Assert.IsTrue(_xRayOptions.CollectSqlQueries);
        }
        public void TestCollectSqlQueriesFalse_WhenNotSpecifiedInJson()
        {
            IConfiguration configuration = BuildConfiguration("DisabledXRayMissing.json");

            _xRayOptions = XRayConfiguration.GetXRayOptions(configuration);
            AWSXRayRecorder.InitializeInstance(configuration);

            Assert.IsFalse(_xRayOptions.CollectSqlQueries);
        }
Exemple #28
0
        public BlogPostsGetAll()
        {
            secrets = GetSecrets.GetSecretsDictionary();
            string connstr = GetSecrets.GetSecretConnectionString();

            Console.WriteLine($"Connection string:: {connstr}");
            bpc = GetConnectionString.GetContext(connstr);
            AWSXRayRecorder.InitializeInstance();
        }
        public void TestExceptionStrategy2() // invalid input
        {
            var exceptionStrategy = new DefaultExceptionSerializationStrategy(-10);
            var recorder          = new AWSXRayRecorderBuilder().WithExceptionSerializationStrategy(exceptionStrategy).Build(); // set custom stackframe size

            AWSXRayRecorder.InitializeInstance(recorder: recorder);
            DefaultExceptionSerializationStrategy actual = AWSXRayRecorder.Instance.ExceptionSerializationStrategy as DefaultExceptionSerializationStrategy;

            Assert.AreEqual(DefaultExceptionSerializationStrategy.DefaultStackFrameSize, actual.MaxStackFrameSize);
        }
Exemple #30
0
        protected static void ClassInit()
        {
            var config = new AmazonXRayConfig();

            config.ServiceURL           = "https://xray.us-east-1.amazonaws.com ";
            config.AuthenticationRegion = "us-east-1";

            XrayClient = new AmazonXRayClient(config);
            Recorder   = new AWSXRayRecorder();
        }