private static object ExecuteScalar(
            object command,
            int opCode,
            int mdToken,
            long moduleVersionPtr,
            string sqlClientNamespace)
        {
            const string methodName = AdoNetConstants.MethodNames.ExecuteScalar;
            Func<DbCommand, object> instrumentedMethod;

            try
            {
                var targetType = command.GetInstrumentedType(sqlClientNamespace, SqlCommandTypeName);

                instrumentedMethod =
                    MethodBuilder<Func<DbCommand, object>>
                       .Start(moduleVersionPtr, mdToken, opCode, methodName)
                       .WithConcreteType(targetType)
                       .WithNamespaceAndNameFilters(ClrNames.Object)
                       .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: $"{sqlClientNamespace}.{SqlCommandTypeName}",
                    methodName: methodName,
                    instanceType: command.GetType().AssemblyQualifiedName);
                throw;
            }

            var dbCommand = command as DbCommand;

            using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, dbCommand))
            {
                try
                {
                    return instrumentedMethod(dbCommand);
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
        private static async Task<object> ExecuteScalarAsyncInternal(
            DbCommand command,
            CancellationToken cancellationToken,
            int opCode,
            int mdToken,
            long moduleVersionPtr,
            string sqlClientNamespace)
        {
            const string methodName = AdoNetConstants.MethodNames.ExecuteScalarAsync;
            Func<DbCommand, CancellationToken, Task<object>> instrumentedMethod;

            try
            {
                var targetType = command.GetInstrumentedType(sqlClientNamespace, SqlCommandTypeName);

                instrumentedMethod =
                    MethodBuilder<Func<DbCommand, CancellationToken, Task<object>>>
                       .Start(moduleVersionPtr, mdToken, opCode, methodName)
                       .WithConcreteType(targetType)
                       .WithParameters(cancellationToken)
                       .WithNamespaceAndNameFilters(ClrNames.ObjectTask, ClrNames.CancellationToken)
                       .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: $"{sqlClientNamespace}.{SqlCommandTypeName}",
                    methodName: methodName,
                    instanceType: command.GetType().AssemblyQualifiedName);
                throw;
            }

            using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, command))
            {
                try
                {
                    return await instrumentedMethod(command, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
        public static object ExecuteReaderWithBehavior(
            object command,
            int behavior,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            const string methodName = AdoNetConstants.MethodNames.ExecuteReader;
            Func <object, CommandBehavior, object> instrumentedMethod;
            var commandBehavior = (CommandBehavior)behavior;

            try
            {
                var targetType = command.GetInstrumentedType(NpgsqlCommandTypeName);

                instrumentedMethod =
                    MethodBuilder <Func <object, CommandBehavior, object> >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(targetType)
                    .WithParameters(commandBehavior)
                    .WithNamespaceAndNameFilters(NpgsqlDataReaderTypeName, AdoNetConstants.TypeNames.CommandBehavior)
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: NpgsqlCommandTypeName,
                    methodName: methodName,
                    instanceType: command.GetType().AssemblyQualifiedName);
                throw;
            }

            using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, command as DbCommand))
            {
                try
                {
                    return(instrumentedMethod(command, commandBehavior));
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
예제 #4
0
        private static async Task <HttpResponseMessage> SendAsyncInternal(
            Func <HttpMessageHandler, HttpRequestMessage, CancellationToken, Task <HttpResponseMessage> > sendAsync,
            Type reportedType,
            HttpMessageHandler handler,
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (!(handler is HttpClientHandler || "System.Net.Http.SocketsHttpHandler".Equals(reportedType.FullName, StringComparison.OrdinalIgnoreCase)) ||
                !IsTracingEnabled(request))
            {
                // skip instrumentation
                return(await sendAsync(handler, request, cancellationToken).ConfigureAwait(false));
            }

            string httpMethod = request.Method?.Method;

            using (var scope = ScopeFactory.CreateOutboundHttpScope(Tracer.Instance, httpMethod, request.RequestUri, IntegrationName))
            {
                try
                {
                    if (scope != null)
                    {
                        scope.Span.SetTag("http-client-handler-type", reportedType.FullName);

                        // add distributed tracing headers to the HTTP request
                        B3SpanContextPropagator.Instance.Inject(scope.Span.Context, request.Headers.Wrap());
                    }

                    HttpResponseMessage response = await sendAsync(handler, request, cancellationToken).ConfigureAwait(false);

                    if (scope != null)
                    {
                        // this tag can only be set after the response is returned
                        scope.Span.SetTag(Tags.HttpStatusCode, ((int)response.StatusCode).ToString());
                        if (!response.IsSuccessStatusCode && !string.IsNullOrWhiteSpace(response.ReasonPhrase))
                        {
                            scope.Span.SetTag(Tags.HttpStatusText, response.ReasonPhrase);
                        }
                    }

                    return(response);
                }
                catch (Exception ex) when(scope?.Span.SetExceptionForFilter(ex) ?? false)
                {
                    // unreachable code
                    throw;
                }
            }
        }
        private static async Task <DbDataReader> ExecuteReaderAsyncWithBehaviorAndCancellationInternal(
            DbCommand command,
            CommandBehavior commandBehavior,
            CancellationToken cancellationToken,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            const string methodName = AdoNetConstants.MethodNames.ExecuteReaderAsync;
            Func <DbCommand, CommandBehavior, CancellationToken, Task <DbDataReader> > instrumentedMethod;

            try
            {
                var targetType = command.GetInstrumentedType(NpgsqlCommandTypeName);

                instrumentedMethod =
                    MethodBuilder <Func <DbCommand, CommandBehavior, CancellationToken, Task <DbDataReader> > >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(targetType)
                    .WithParameters(commandBehavior, cancellationToken)
                    .WithNamespaceAndNameFilters(ClrNames.GenericTask, AdoNetConstants.TypeNames.CommandBehavior, ClrNames.CancellationToken)
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: NpgsqlCommandTypeName,
                    methodName: methodName,
                    instanceType: command.GetType().AssemblyQualifiedName);
                throw;
            }

            using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, command, IntegrationName))
            {
                try
                {
                    return(await instrumentedMethod(command, commandBehavior, cancellationToken).ConfigureAwait(false));
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
예제 #6
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            // If we restart our entitlements service, we should just invalidate other services just in case
            var scope           = ScopeFactory.CreateScope();
            var notificationHub = scope.ServiceProvider.GetService <INotificationHubClient>();

            while (!notificationHub.Connected)
            {
                Logger.LogInformation($"Waiting for notification hub to come online...");
                await Task.Delay(10000, cancellationToken);
            }

            Logger.LogInformation($"Notification hub client is online, sending message to invalidate entitlements");
            await notificationHub.Notify(new CacheChangeNotification(EntitlementResponseModel.EntitlementCacheTag));
        }
        public void CleanUri_ResourceName(string uri, string method, string expected)
        {
            // Set up Tracer
            var settings    = new TracerSettings();
            var writerMock  = new Mock <IAgentWriter>();
            var samplerMock = new Mock <ISampler>();
            var tracer      = new Tracer(settings, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null);

            const string integrationName = "HttpMessageHandler";

            using (var automaticScope = ScopeFactory.CreateOutboundHttpScope(tracer, method, new Uri(uri), integrationName))
            {
                Assert.Equal(expected, automaticScope.Span.ResourceName);
            }
        }
예제 #8
0
        private async Task Load()
        {
            using (var scope = ScopeFactory.CreateScope())
            {
                var db = scope.ServiceProvider.GetService <TandemBookingContext>();

                var payments = await db.Payments
                               .Include(p => p.PaymentAccount)
                               .OrderBy(p => p.PaymentDate)
                               .AsNoTracking()
                               .ToListAsync();

                ImportedPayments = payments;
            }
        }
        public static object ExecuteReaderWithBehavior(
            object command,
            int behavior,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            Func <IDbCommand, CommandBehavior, IDataReader> instrumentedMethod;
            var commandBehavior = (CommandBehavior)behavior;

            try
            {
                instrumentedMethod =
                    MethodBuilder <Func <IDbCommand, CommandBehavior, IDataReader> >
                    .Start(moduleVersionPtr, mdToken, opCode, AdoNetConstants.MethodNames.ExecuteReader)
                    .WithConcreteType(typeof(IDbCommand))
                    .WithParameters(commandBehavior)
                    .WithNamespaceAndNameFilters(DataReaderTypeName, AdoNetConstants.TypeNames.CommandBehavior)
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: DbCommandTypeName,
                    methodName: nameof(ExecuteReader),
                    instanceType: command.GetType().AssemblyQualifiedName);
                throw;
            }

            var dbCommand = command as IDbCommand;

            using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, dbCommand, IntegrationName))
            {
                try
                {
                    return(instrumentedMethod(dbCommand, commandBehavior));
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
예제 #10
0
        private static async Task <T> SendAsyncInternal <T>(
            Func <object, object, CancellationToken, object> sendAsync,
            Type reportedType,
            object handler,
            object request,
            CancellationToken cancellationToken)
        {
            var headers = request.GetProperty <object>("Headers").GetValueOrDefault();

            if (!(reportedType.FullName.Equals(HttpClientHandler, StringComparison.OrdinalIgnoreCase) || IsSocketsHttpHandlerEnabled(reportedType)) ||
                !IsTracingEnabled(headers))
            {
                // skip instrumentation
                var task = (Task <T>)sendAsync(handler, request, cancellationToken);
                return(await task.ConfigureAwait(false));
            }

            var httpMethod = request.GetProperty("Method").GetProperty <string>("Method").GetValueOrDefault();
            var requestUri = request.GetProperty <Uri>("RequestUri").GetValueOrDefault();

            using (var scope = ScopeFactory.CreateOutboundHttpScope(Tracer.Instance, httpMethod, requestUri, IntegrationName))
            {
                try
                {
                    if (scope != null)
                    {
                        scope.Span.SetTag("http-client-handler-type", reportedType.FullName);

                        // add distributed tracing headers to the HTTP request
                        SpanContextPropagatorHelpers.InjectHttpHeadersWithReflection(scope.Span.Context, headers);
                    }

                    var task     = (Task <T>)sendAsync(handler, request, cancellationToken);
                    var response = await task.ConfigureAwait(false);

                    // this tag can only be set after the response is returned
                    int statusCode = response.GetProperty <int>("StatusCode").GetValueOrDefault();
                    scope?.Span.SetTag(Tags.HttpStatusCode, (statusCode).ToString());

                    return(response);
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
예제 #11
0
        public static object ExecuteReader(
            object command,
            int opCode,
            int mdToken,
            long moduleVersionPtr)
        {
            const string methodName = AdoNetConstants.MethodNames.ExecuteReader;
            Func <DbCommand, DbDataReader> instrumentedMethod;

            try
            {
                var targetType = command.GetInstrumentedType(DbCommandTypeName);

                instrumentedMethod =
                    MethodBuilder <Func <DbCommand, DbDataReader> >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(targetType)
                    .WithNamespaceAndNameFilters(AdoNetConstants.TypeNames.DbDataReader)
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: DbCommandTypeName,
                    methodName: methodName,
                    instanceType: command.GetType().AssemblyQualifiedName);
                throw;
            }

            var dbCommand = command as DbCommand;

            using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, dbCommand))
            {
                try
                {
                    return(instrumentedMethod(dbCommand));
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
예제 #12
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            Logger.LogInformation($"{typeof(TJob)} job runner is starting.");

            /// Two separate scopes (i.e., one for reading un-finished jobs,
            /// and one for running queued jobs) are created intentionally,
            /// so that creating a separate scope per job execution could be easier.
            IServiceScope scope   = ScopeFactory.CreateScope();
            var           context = scope.ServiceProvider.GetRequiredService <TVQContext>();

            foreach (var job in context.Set <TJob>()
                     .Where(x => x.Status == State.Queued ||
                            x.Status == State.Running))
            {
                Queue.Enqueue(job.ID);
                Logger.LogInformation($"The unfinished job {job.ID} of type {nameof(TJob)} is re-queued.");
            }
            scope.Dispose();
            context = null;

            while (!cancellationToken.IsCancellationRequested)
            {
                var id = await Queue.DequeueAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    scope   = ScopeFactory.CreateScope();
                    context = scope.ServiceProvider.GetRequiredService <TVQContext>();
                    var service = scope.ServiceProvider.GetRequiredService <TService>();
                    var job     = context.Set <TJob>().Find(id);
                    await service.StartAsync(job, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    var message = $"Error occurred executing job {id} of type {nameof(id)}: {e.Message}";
                    Logger.LogError(e, message);
                }
                finally
                {
                    if (scope != null)
                    {
                        scope.Dispose();
                    }
                }
            }

            Logger.LogInformation($"{typeof(TJob)} job runner is stopping.");
        }
        public void CleanUri_HttpUrlTag(string uri, string expected)
        {
            // Set up Tracer
            var settings    = new TracerSettings();
            var writerMock  = new Mock <IAgentWriter>();
            var samplerMock = new Mock <ISampler>();
            var tracer      = new Tracer(settings, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null);

            const string method = "GET";

            using (var automaticScope = ScopeFactory.CreateOutboundHttpScope(tracer, method, new Uri(uri), IntegrationId.HttpMessageHandler, out var tags))
            {
                Assert.Equal(expected, automaticScope.Span.GetTag(Tags.HttpUrl));
                Assert.Equal(expected, tags.HttpUrl);
            }
        }
예제 #14
0
 private void CleanCacheButton_Click(object sender, EventArgs e)
 {
     if (DialogResult.Yes == MessageBox.Show("진행 중인 작업을 취소하고 프로그램을 다시 시작할까요?", Text, MessageBoxButtons.YesNo))
     {
         using (var scope = ScopeFactory.CreateScope())
         {
             var db = scope.ServiceProvider.GetService <BibleContext>();
             db.Database.ExecuteSqlCommand(@"
                 PRAGMA writable_schema = 1;
                 DELETE FROM sqlite_master WHERE type IN ('table', 'index', 'trigger');
                 PRAGMA writable_schema = 0;
             ");
         }
         Application.Restart();
     }
 }
예제 #15
0
        public async Task ShouldReturnAllWhenGetAll()
        {
            // Arrange
            var first = new Hospital
            {
                Name    = "test name",
                Address = "test address"
            };
            var second = new Hospital
            {
                Name    = "test name",
                Address = "test address"
            };

            using (var scope = ScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetService <ApplicationContext>();
                context.Hospitals.Add(first);
                context.Hospitals.Add(second);
                context.SaveChanges();
            }

            // Act
            var response = await Client.GetAsync(Resource);

            var hostpitalList = await response.Content.ReadAsAsync <List <Hospital> >();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.True(hostpitalList.Count >= 2);


            var firstHospital = hostpitalList.OrderByDescending(x => x.Id).Skip(1).FirstOrDefault();

            Assert.Equal(first.Address, firstHospital?.Address);
            Assert.Equal(first.Name, firstHospital?.Name);

            Assert.Equal(second.Address, hostpitalList.Last().Address);
            Assert.Equal(second.Name, hostpitalList.Last().Name);

            using (var scope = ScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetService <ApplicationContext>();
                context.Hospitals.RemoveRange(hostpitalList);
                context.SaveChanges();
            }
        }
예제 #16
0
        public async Task ShouldReturnAllWhenGetAll()
        {
            // Arrange
            var first = new Vaccine
            {
                Name         = "test name",
                RecieveMonth = 1
            };
            var second = new Vaccine
            {
                Name         = "test name 2",
                RecieveMonth = 2
            };

            using (var scope = ScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetService <ApplicationContext>();
                context.Vaccines.Add(first);
                context.Vaccines.Add(second);
                context.SaveChanges();
            }

            // Act
            var response = await Client.GetAsync(Resource);

            var vaccineList = await response.Content.ReadAsAsync <List <Vaccine> >();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.True(vaccineList.Count >= 2);

            var firstVaccine = vaccineList.OrderByDescending(x => x.Id).Skip(1).FirstOrDefault();

            Assert.Equal(first.RecieveMonth, firstVaccine?.RecieveMonth);
            Assert.Equal(first.Name, firstVaccine?.Name);

            Assert.Equal(second.RecieveMonth, vaccineList.Last().RecieveMonth);
            Assert.Equal(second.Name, vaccineList.Last().Name);

            using (var scope = ScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetService <ApplicationContext>();
                context.Vaccines.RemoveRange(vaccineList);
                context.SaveChanges();
            }
        }
예제 #17
0
        async Task MessageConsumer_TestDeletedAsync(TestDeletedMessage arg)
        {
            using var scope = ScopeFactory.CreateScope();
            var sp = scope.ServiceProvider;

            using var db = sp.GetRequiredService <RunnerContext>();

            var runInfo = await db.TestRuns
                          .IncludeGroup(API.Models.EntityGroups.ALL, db)
                          .FirstOrDefaultAsync(r => r.TestId == r.TestId || r.TestName == arg.TestName);

            if (runInfo != null)
            {
                db.TestRuns.Remove(runInfo);
                await db.SaveChangesAsync();
            }
        }
예제 #18
0
        async Task MessageConsumer_TestResultStateAcquiredAsync(TestResultStateAcquiredMessage arg)
        {
            using var scope = ScopeFactory.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService <RunnerContext>();

            var rr = db.RunResults
                     .IncludeGroup(API.Models.EntityGroups.ALL, db)
                     .FirstOrDefault(r => r.Id == arg.ResultId);

            if (rr != null)
            {
                rr.ResultBase.State = arg.NewState;
                await db.SaveChangesAsync();

                MessageProducer.FireTestResultStateUpdated(new TestResultStateUpdatedMessage(rr.ResultBase.TestId, arg.ResultId, arg.NewState));
            }
        }
        public void CreateDbCommandScope_IgnoresReplacementServiceNameWhenNotProvided(IDbCommand command)
        {
            // Set up tracer
            var collection = new NameValueCollection
            {
                { ConfigurationKeys.ServiceNameMappings, $"something:my-custom-type" }
            };
            IConfigurationSource source = new NameValueConfigurationSource(collection);
            var tracerSettings          = new TracerSettings(source);
            var tracer = new Tracer(tracerSettings);

            // Create scope
            using (var outerScope = ScopeFactory.CreateDbCommandScope(tracer, command))
            {
                Assert.NotEqual("my-custom-type", outerScope.Span.ServiceName);
            }
        }
예제 #20
0
        public async Task ShouldRemoveWhenDelete()
        {
            // Arrange
            var first = new Hospital
            {
                Name    = "test name",
                Address = "test address"
            };
            var second = new Hospital
            {
                Name    = "test name 2",
                Address = "test address 2"
            };

            using (var scope = ScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetService <ApplicationContext>();
                context.Hospitals.Add(first);
                context.Hospitals.Add(second);
                context.SaveChanges();
            }

            var token = await AuthenticationHelper.GetAdminToken(Client);

            Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Act
            var response = await Client.DeleteAsync($"{Resource}/{first.Id}");

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            using (var scope = ScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetService <ApplicationContext>();
                Assert.Single(context.Hospitals);

                var last = context.Hospitals.Last();

                Assert.Equal(second.Address, last.Address);
                Assert.Equal(second.Name, last.Name);

                context.Hospitals.RemoveRange(context.Hospitals);
                context.SaveChanges();
            }
        }
        private static async Task <object> SendAsyncInternal(
            Func <object, object, CancellationToken, object> sendAsync,
            Type reportedType,
            HttpRequestMessageStruct requestValue,
            object handler,
            object request,
            CancellationToken cancellationToken)
        {
            var httpMethod = requestValue.Method.Method;
            var requestUri = requestValue.RequestUri;
            var tracer     = Tracer.Instance;

            using (var scope = ScopeFactory.CreateOutboundHttpScope(tracer, httpMethod, requestUri, IntegrationId, out var tags))
            {
                try
                {
                    if (scope != null)
                    {
                        tags.HttpClientHandlerType = reportedType.FullName;

                        // add distributed tracing headers to the HTTP request
                        tracer.Propagator.Inject(scope.Span.Context, new HttpHeadersCollection(requestValue.Headers));
                    }

                    var task = (Task)sendAsync(handler, request, cancellationToken);
                    await task.ConfigureAwait(false);

                    var response = task.DuckCast <TaskObjectStruct>().Result;

                    // this tag can only be set after the response is returned
                    int statusCode = response.DuckCast <HttpResponseMessageStruct>().StatusCode;

                    if (scope != null)
                    {
                        scope.Span.SetHttpStatusCode(statusCode, isServer: false);
                    }

                    return(response);
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
예제 #22
0
        private static async Task <HttpResponseMessage> SendAsyncInternal(
            HttpMessageHandler handler,
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var executeAsync = DynamicMethodBuilder <Func <HttpMessageHandler, HttpRequestMessage, CancellationToken, Task <HttpResponseMessage> > >
                               .GetOrCreateMethodCallDelegate(
                handler.GetType(),
                nameof(SendAsync));

            var handlerTypeName = handler.GetType().FullName;

            if (handlerTypeName != "System.Net.Http.HttpClientHandler" || !IsTracingEnabled(request))
            {
                // skip instrumentation
                return(await executeAsync(handler, request, cancellationToken).ConfigureAwait(false));
            }

            string httpMethod      = request.Method.ToString().ToUpperInvariant();
            string integrationName = typeof(HttpMessageHandlerIntegration).Name.TrimEnd("Integration", StringComparison.OrdinalIgnoreCase);

            using (var scope = ScopeFactory.CreateOutboundHttpScope(httpMethod, request.RequestUri, integrationName))
            {
                try
                {
                    if (scope != null)
                    {
                        // add distributed tracing headers to the HTTP request
                        SpanContextPropagator.Instance.Inject(scope.Span.Context, request.Headers.Wrap());
                    }

                    HttpResponseMessage response = await executeAsync(handler, request, cancellationToken).ConfigureAwait(false);

                    // this tag can only be set after the response is returned
                    scope?.Span.SetTag(Tags.HttpStatusCode, ((int)response.StatusCode).ToString());

                    return(response);
                }
                catch (Exception ex) when(scope?.Span.SetExceptionForFilter(ex) ?? false)
                {
                    // unreachable code
                    throw;
                }
            }
        }
        public async Task Run(RepositorySourceVerb verb)
        {
            using var scopeFactory = new ScopeFactory(Services.RepositorySourceService);
            var scope = scopeFactory.Scope;

            var repositorySourceManager = scope.Resolve <IRepositorySourceManager>();

            switch (verb.Actions)
            {
            case RepositoryActions.Add:
                await repositorySourceManager.Add(verb.ToAddRequest());

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #24
0
        public void ContainsTest()
        {
            Random rnd = new Random(Environment.TickCount);
            var    xs  = Observable.Interval(TimeSpan.FromSeconds(0.5))
                         .Take(15)
                         .Select(_ => rnd.Next(7))
                         .Monitor("Source", 1)
                         .Publish();

            using (ScopeFactory.Create(2))
            {
                var ys = xs.Contains(2);
                ys = ys.Monitor("Contains", 2);
                ys.Subscribe();
                xs.Connect();
            }
            GC.KeepAlive(xs);
        }
        public void CreateDbCommandScope_UsesReplacementServiceNameWhenProvided(IDbCommand command)
        {
            // Set up tracer
            var t          = command.GetType();
            var dbType     = ScopeFactory.GetDbType(t.Namespace, t.Name);
            var collection = new NameValueCollection
            {
                { ConfigurationKeys.ServiceNameMappings, $"{dbType}:my-custom-type" }
            };
            IConfigurationSource source = new NameValueConfigurationSource(collection);
            var tracerSettings          = new TracerSettings(source);
            var tracer = new Tracer(tracerSettings);

            // Create scope
            using (var outerScope = ScopeFactory.CreateDbCommandScope(tracer, command))
            {
                Assert.Equal("my-custom-type", outerScope.Span.ServiceName);
            }
        }
예제 #26
0
 private Task DoInScopeAsync <TModel>(Func <IDataRepository <TModel>, Task> action) where TModel : RestModel
 {
     return(Task.Run(() =>
     {
         try
         {
             using (IServiceScope scope = ScopeFactory.CreateScope())
             {
                 IDataRepository <TModel> repository = scope.ServiceProvider
                                                       .GetRequiredService <IDataRepository <TModel> >();
                 action?.Invoke(repository).Wait();
             }
         }
         catch (Exception ex)
         {
             Logger.LogError(RestLoggingEvents.SERVER_FAILURE, ex, "An exception has been raised while handling request");
         }
     }));
 }
        public static CallTargetState OnMethodBegin <TTarget, TRequest>(TTarget instance, TRequest requestMessage, CancellationToken cancellationToken)
            where TRequest : IHttpRequestMessage
        {
            if (IsTracingEnabled(requestMessage.Headers))
            {
                Scope scope = ScopeFactory.CreateOutboundHttpScope(Tracer.Instance, requestMessage.Method.Method, requestMessage.RequestUri, IntegrationId, out HttpTags tags);
                if (scope != null)
                {
                    tags.HttpClientHandlerType = instance.GetType().FullName;

                    // add distributed tracing headers to the HTTP request
                    SpanContextPropagator.Instance.Inject(scope.Span.Context, new HttpHeadersCollection(requestMessage.Headers));

                    return(new CallTargetState(scope));
                }
            }

            return(CallTargetState.GetDefault());
        }
 /// <summary>
 /// Calls the underlying ExecuteReaderAsync and traces the request.
 /// </summary>
 /// <typeparam name="T">The type of the generic Task instantiation</typeparam>
 /// <param name="command">The object referenced by this in the instrumented method.</param>
 /// <param name="cancellationToken">The cancellation token</param>
 /// <param name="instrumentedMethod">A delegate for the method we are instrumenting</param>
 /// <returns>A task with the result</returns>
 private static async Task <T> ExecuteReaderAsyncInternal <T>(
     DbCommand command,
     CancellationToken cancellationToken,
     Func <DbCommand, CancellationToken, object> instrumentedMethod)
 {
     using (var scope = ScopeFactory.CreateDbCommandScope(Tracer.Instance, command))
     {
         try
         {
             var task = (Task <T>)instrumentedMethod(command, cancellationToken);
             return(await task.ConfigureAwait(false));
         }
         catch (Exception ex)
         {
             scope?.Span.SetException(ex);
             throw;
         }
     }
 }
예제 #29
0
        /// <summary>
        /// OnMethodBegin callback
        /// </summary>
        /// <typeparam name="TTarget">Type of the target</typeparam>
        /// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
        /// <returns>Calltarget state value</returns>
        public static CallTargetState GetResponse_OnMethodBegin <TTarget>(TTarget instance)
        {
            if (instance is HttpWebRequest request && IsTracingEnabled(request))
            {
                Tracer tracer = Tracer.Instance;

                // Check if any headers were injected by a previous call to GetRequestStream
                var spanContext = SpanContextPropagator.Instance.Extract(request.Headers.Wrap());

                // If this operation creates the trace, then we need to re-apply the sampling priority
                bool setSamplingPriority = spanContext?.SamplingPriority != null && tracer.ActiveScope == null;

                Scope scope = null;

                try
                {
                    scope = ScopeFactory.CreateOutboundHttpScope(tracer, request.Method, request.RequestUri, IntegrationId, out _, spanContext?.TraceId, spanContext?.SpanId);

                    if (scope != null)
                    {
                        if (setSamplingPriority && spanContext?.SamplingPriority is not null)
                        {
                            scope.Span.SetTraceSamplingPriority(spanContext.SamplingPriority.Value);
                        }

                        // add distributed tracing headers to the HTTP request
                        SpanContextPropagator.Instance.Inject(scope.Span.Context, request.Headers.Wrap());

                        tracer.TracerManager.Telemetry.IntegrationGeneratedSpan(IntegrationId);

                        return(new CallTargetState(scope));
                    }
                }
                catch
                {
                    scope?.Dispose();
                    throw;
                }
            }

            return(CallTargetState.GetDefault());
        }
        public override void Delete(TEntity[] entities)
        {
            Guard.Against <ArgumentNullException>(CurrentUser == null, string.Format("Ошибка удаления бизнес-процесса типа {0}: не задан тек. пользователь", typeof(TEntity)));
            Guard.Against <ArgumentNullException>(ScopeFactory == null, string.Format("Ошибка удаления бизнес-процесса типа {0}: не определена фабрика транзакций", typeof(TEntity)));
            Guard.Against <ArgumentNullException>(DeleteOperation == null, string.Format("Ошибка удаления бизнес-процесса типа {0}: не определена стратегия удаления", typeof(TEntity)));

            if (entities.IsNullOrEmpty())
            {
                return;
            }

            var _scope = ScopeFactory.Create();

            try
            {
                foreach (var entity in entities)
                {
                    ExecuteOperation(DeleteOperation, op =>
                    {
                        op.DeleteEntity(entity);
                    });

                    if (!IsValidLastOperation)
                    {
                        break;
                    }
                }

                if (IsValidLastOperation)
                {
                    _scope.Commit();
                }
            }
            catch (Exception e)
            {
                throw;
            }
            finally
            {
                _scope.Dispose();
            }
        }