public void SuccessTraceEventTest(
            string commandText,
            bool setDbStatement  = false,
            bool recordException = false,
            bool enableConnectionLevelAttributes = false,
            bool isFailure = false)
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();
            var sampler           = new TestSampler();

            using var shutdownSignal = Sdk.CreateTracerProviderBuilder()
                                       .AddProcessor(activityProcessor.Object)
                                       .SetSampler(sampler)
                                       .AddMySqlDataInstrumentation(options =>
            {
                options.SetDbStatement  = setDbStatement;
                options.RecordException = recordException;
                options.EnableConnectionLevelAttributes = enableConnectionLevelAttributes;
            })
                                       .Build();

            var traceListener = (TraceListener)Assert.Single(MySqlTrace.Listeners);

            this.ExecuteSuccessQuery(traceListener, commandText, isFailure);

            Assert.Equal(3, activityProcessor.Invocations.Count);

            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            VerifyActivityData(commandText, setDbStatement, recordException, enableConnectionLevelAttributes, isFailure, activity);
        }
        public void UnknownMySqlTraceEventType(MySqlTraceEventType eventType)
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();
            var sampler           = new TestSampler();

            using var shutdownSignal = Sdk.CreateTracerProviderBuilder()
                                       .AddProcessor(activityProcessor.Object)
                                       .SetSampler(sampler)
                                       .AddMySqlDataInstrumentation()
                                       .Build();

            var traceListener = (TraceListener)Assert.Single(MySqlTrace.Listeners);

            traceListener?.TraceEvent(
                new TraceEventCache(),
                "mysql",
                TraceEventType.Information,
                (int)eventType,
                "{0}: Connection Opened: connection string = '{1}'",
                1L,
                ConnStr,
                10);

            Assert.Equal(1, activityProcessor.Invocations.Count);
        }
        public void ProcessorDoesNotSendRecordDecisionSpanToExporter()
        {
            var testSampler = new TestSampler();

            testSampler.SamplingAction = (samplingParameters) =>
            {
                return(new SamplingResult(SamplingDecision.Record));
            };

            using var exporter      = new TestActivityExporter(null);
            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .AddSource("random")
                                      .AddProcessor(new SimpleActivityProcessor(exporter))
                                      .SetSampler(testSampler)
                                      .Build();

            using ActivitySource source = new ActivitySource("random");
            var activity = source.StartActivity("somename");

            activity.Stop();

            Assert.True(activity.IsAllDataRequested);
            Assert.Equal(ActivityTraceFlags.None, activity.ActivityTraceFlags);
            Assert.False(activity.Recorded);

            var exported = this.WaitForSpans(exporter, 0, TimeSpan.FromMilliseconds(100));

            Assert.Empty(exported);
        }
        public void Test(
            string commandText,
            bool setDbStatement  = false,
            bool recordException = false,
            bool enableConnectionLevelAttributes = false,
            bool isFailure = false,
            bool warning   = false)
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();
            var sampler           = new TestSampler();

            using var shutdownSignal = Sdk.CreateTracerProviderBuilder()
                                       .AddProcessor(activityProcessor.Object)
                                       .SetSampler(sampler)
                                       .AddMySqlClientInstrumentation(options =>
            {
                options.SetDbStatement  = setDbStatement;
                options.RecordException = recordException;
                options.EnableConnectionLevelAttributes = enableConnectionLevelAttributes;
            })
                                       .Build();

            var connectionStringBuilder = new MySqlConnectionStringBuilder(MySqlConnectionString);

            connectionStringBuilder.Pooling       = false;
            using MySqlConnection mySqlConnection = new MySqlConnection(MySqlConnectionString);
            var dataSource = mySqlConnection.DataSource;

            mySqlConnection.Open();
            mySqlConnection.ChangeDatabase("mysql");

            using MySqlCommand mySqlCommand = new MySqlCommand(commandText, mySqlConnection);

            try
            {
                mySqlCommand.ExecuteNonQuery();
            }
            catch
            {
            }

            Activity activity;

            // select 1/0 will cause the driver execute `SHOW WARNINGS`
            if (warning)
            {
                Assert.Equal(14, activityProcessor.Invocations.Count);
                activity = (Activity)activityProcessor.Invocations[11].Arguments[0];
            }
            else
            {
                Assert.Equal(13, activityProcessor.Invocations.Count);
                activity = (Activity)activityProcessor.Invocations[11].Arguments[0];
            }

            VerifyActivityData(commandText, setDbStatement, recordException, enableConnectionLevelAttributes, isFailure, dataSource, activity);
        }
        public void SuccessfulCommandTestWithKey(string value)
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = true,
            };

            connectionOptions.EndPoints.Add(RedisEndPoint);

            using var connection = ConnectionMultiplexer.Connect(connectionOptions);
            var db = connection.GetDatabase();

            db.KeyDelete("key1");

            var activityProcessor = new Mock <BaseProcessor <Activity> >();
            var sampler           = new TestSampler();

            using (Sdk.CreateTracerProviderBuilder()
                   .AddProcessor(activityProcessor.Object)
                   .SetSampler(sampler)
                   .AddRedisInstrumentation(connection, c => c.SetVerboseDatabaseStatements = true)
                   .Build())
            {
                var prepared = LuaScript.Prepare("redis.call('set', @key, @value)");
                db.ScriptEvaluate(prepared, new { key = (RedisKey)"mykey", value = 123 });

                var redisValue = db.StringGet("key1");

                Assert.False(redisValue.HasValue);

                bool set = db.StringSet("key1", value, TimeSpan.FromSeconds(60));

                Assert.True(set);

                redisValue = db.StringGet("key1");

                Assert.True(redisValue.HasValue);
                Assert.Equal(value, redisValue.ToString());
            }

            // Disposing SDK should flush the Redis profiling session immediately.

            Assert.Equal(11, activityProcessor.Invocations.Count);

            var scriptActivity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            Assert.Equal("EVAL", scriptActivity.DisplayName);
            Assert.Equal("EVAL redis.call('set', ARGV[1], ARGV[2])", scriptActivity.GetTagValue(SemanticConventions.AttributeDbStatement));

            VerifyActivityData((Activity)activityProcessor.Invocations[3].Arguments[0], false, connection.GetEndPoints()[0], true);
            VerifyActivityData((Activity)activityProcessor.Invocations[5].Arguments[0], true, connection.GetEndPoints()[0], true);
            VerifyActivityData((Activity)activityProcessor.Invocations[7].Arguments[0], false, connection.GetEndPoints()[0], true);
            VerifySamplingParameters(sampler.LatestSamplingParameters);
        }
        public void CanEnrichActivityFromCommand(string value)
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = true,
            };

            connectionOptions.EndPoints.Add(RedisEndPoint);

            using var connection = ConnectionMultiplexer.Connect(connectionOptions);

            var activityProcessor = new Mock <BaseProcessor <Activity> >();
            var sampler           = new TestSampler();

            using (Sdk.CreateTracerProviderBuilder()
                   .AddProcessor(activityProcessor.Object)
                   .SetSampler(sampler)
                   .AddRedisInstrumentation(connection, c => c.Enrich = (activity, command) =>
            {
                if (command.ElapsedTime < TimeSpan.FromMilliseconds(100))
                {
                    activity.AddTag("is_fast", true);
                }
            })
                   .Build())
            {
                var db = connection.GetDatabase();

                bool set = db.StringSet("key1", value, TimeSpan.FromSeconds(60));

                Assert.True(set);

                var redisValue = db.StringGet("key1");

                Assert.True(redisValue.HasValue);
                Assert.Equal(value, redisValue.ToString());
            }

            // Disposing SDK should flush the Redis profiling session immediately.

            Assert.Equal(7, activityProcessor.Invocations.Count);

            var setActivity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            Assert.Equal(true, setActivity.GetTagValue("is_fast"));
            var getActivity = (Activity)activityProcessor.Invocations[3].Arguments[0];

            Assert.Equal(true, getActivity.GetTagValue("is_fast"));
        }
Ejemplo n.º 7
0
        public void SqlClientCreatesActivityWithDbSystem(
            string beforeCommand)
        {
            using var sqlConnection = new SqlConnection(TestConnectionString);
            using var sqlCommand    = sqlConnection.CreateCommand();

            var sampler = new TestSampler
            {
                SamplingAction = _ => new SamplingResult(SamplingDecision.Drop),
            };

            using (Sdk.CreateTracerProviderBuilder()
                   .AddSqlClientInstrumentation()
                   .SetSampler(sampler)
                   .Build())
            {
                this.fakeSqlClientDiagnosticSource.Write(beforeCommand, new { });
            }

            VerifySamplingParameters(sampler.LatestSamplingParameters);
        }
        public void SuccessfulCommandTest(string value)
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = true,
            };

            connectionOptions.EndPoints.Add(RedisEndPoint);

            using var connection = ConnectionMultiplexer.Connect(connectionOptions);

            var activityProcessor = new Mock <BaseProcessor <Activity> >();
            var sampler           = new TestSampler();

            using (OpenTelemetrySdk.CreateTracerProviderBuilder()
                   .AddProcessor(activityProcessor.Object)
                   .SetSampler(sampler)
                   .AddRedisInstrumentation(connection)
                   .Build())
            {
                var db = connection.GetDatabase();

                bool set = db.StringSet("key1", value, TimeSpan.FromSeconds(60));

                Assert.True(set);

                var redisValue = db.StringGet("key1");

                Assert.True(redisValue.HasValue);
                Assert.Equal(value, redisValue.ToString());
            }

            // Disposing SDK should flush the Redis profiling session immediately.

            Assert.Equal(7, activityProcessor.Invocations.Count);

            VerifyActivityData((Activity)activityProcessor.Invocations[1].Arguments[0], true, connection.GetEndPoints()[0]);
            VerifyActivityData((Activity)activityProcessor.Invocations[3].Arguments[0], false, connection.GetEndPoints()[0]);
            VerifySamplingParameters(sampler.LatestSamplingParameters);
        }
Ejemplo n.º 9
0
 public ActivitySourceAdapterTest()
 {
     this.testSampler           = new TestSampler();
     this.testProcessor         = new TestActivityProcessor();
     this.activitySourceAdapter = new ActivitySourceAdapter(this.testSampler, this.testProcessor);
 }
Ejemplo n.º 10
0
        public void SuccessfulCommandTest(
            CommandType commandType,
            string commandText,
            bool captureStoredProcedureCommandName,
            bool captureTextCommandContent = false,
            bool isFailure       = false,
            bool recordException = false,
            bool shouldEnrich    = true)
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            activityProcessor.Setup(x => x.OnStart(It.IsAny <Activity>())).Callback <Activity>(c => c.SetTag("enriched", "no"));
            var sampler = new TestSampler();

            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .AddProcessor(activityProcessor.Object)
                                       .SetSampler(sampler)
                                       .AddSqlClientInstrumentation(options =>
            {
#if !NETFRAMEWORK
                options.SetDbStatementForStoredProcedure = captureStoredProcedureCommandName;
                options.SetDbStatementForText            = captureTextCommandContent;
                options.RecordException = recordException;
#else
                options.SetDbStatement = captureStoredProcedureCommandName;
#endif
                if (shouldEnrich)
                {
                    options.Enrich = ActivityEnrichment;
                }
            })
                                       .Build();

#if NETFRAMEWORK
            // RecordException not available on netfx
            recordException = false;
#endif

            using SqlConnection sqlConnection = new SqlConnection(SqlConnectionString);

            sqlConnection.Open();

            string dataSource = sqlConnection.DataSource;

            sqlConnection.ChangeDatabase("master");

            using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection)
                  {
                      CommandType = commandType,
                  };

            try
            {
                sqlCommand.ExecuteNonQuery();
            }
            catch
            {
            }

            Assert.Equal(3, activityProcessor.Invocations.Count);

            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            VerifyActivityData(commandType, commandText, captureStoredProcedureCommandName, captureTextCommandContent, isFailure, recordException, shouldEnrich, dataSource, activity);
            VerifySamplingParameters(sampler.LatestSamplingParameters);
        }
Ejemplo n.º 11
0
        public void BuildSamplingParametersHandlesCurrentActivity()
        {
            using var activitySource = new ActivitySource(nameof(this.BuildSamplingParametersHandlesCurrentActivity));

            var testSampler = new TestSampler {
                DesiredSamplingResult = new SamplingResult(true)
            };

            using var listener = new ActivityListener
                  {
                      ShouldListenTo = _ => true,
                      GetRequestedDataUsingContext = (ref ActivityCreationOptions <ActivityContext> options) =>
                                                     Sdk.ComputeActivityDataRequest(options, testSampler),
                  };

            ActivitySource.AddActivityListener(listener);

            using (var root = activitySource.StartActivity("root"))
            {
                Assert.Equal(default(ActivitySpanId), root.ParentSpanId);

                // This enforces the current behavior that the traceId passed to the sampler for the
                // root span/activity is not the traceId actually used.
                Assert.NotEqual(root.TraceId, testSampler.LatestSamplingParameters.TraceId);
            }

            using (var parent = activitySource.StartActivity("parent", ActivityKind.Client))
            {
                // This enforces the current behavior that the traceId passed to the sampler for the
                // root span/activity is not the traceId actually used.
                Assert.NotEqual(parent.TraceId, testSampler.LatestSamplingParameters.TraceId);
                using (var child = activitySource.StartActivity("child"))
                {
                    Assert.Equal(parent.TraceId, testSampler.LatestSamplingParameters.TraceId);
                    Assert.Equal(parent.TraceId, child.TraceId);
                    Assert.Equal(parent.SpanId, child.ParentSpanId);
                }
            }

            var customContext = new ActivityContext(
                ActivityTraceId.CreateRandom(),
                ActivitySpanId.CreateRandom(),
                ActivityTraceFlags.None);

            using (var fromCustomContext =
                       activitySource.StartActivity("customContext", ActivityKind.Client, customContext))
            {
                Assert.Equal(customContext.TraceId, fromCustomContext.TraceId);
                Assert.Equal(customContext.SpanId, fromCustomContext.ParentSpanId);
                Assert.NotEqual(customContext.SpanId, fromCustomContext.SpanId);
            }

            // Preserve traceId in case span is propagated but not recorded (sampled per OpenTelemetry parlance) and
            // no data is requested for children spans.
            testSampler.DesiredSamplingResult = new SamplingResult(false);
            using (var root = activitySource.StartActivity("root"))
            {
                Assert.Equal(default(ActivitySpanId), root.ParentSpanId);

                using (var child = activitySource.StartActivity("child"))
                {
                    Assert.Null(child);
                    Assert.Equal(root.TraceId, testSampler.LatestSamplingParameters.TraceId);
                    Assert.Same(Activity.Current, root);
                }
            }
        }
Ejemplo n.º 12
0
        public void SuccessfulCommandTest(
            CommandType commandType,
            string commandText,
            bool captureStoredProcedureCommandName,
            bool captureTextCommandContent = false,
            bool isFailure       = false,
            bool recordException = false,
            bool shouldEnrich    = true)
        {
            var sampler    = new TestSampler();
            var activities = new List <Activity>();

            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .SetSampler(sampler)
                                       .AddInMemoryExporter(activities)
                                       .AddSqlClientInstrumentation(options =>
            {
#if !NETFRAMEWORK
                options.SetDbStatementForStoredProcedure = captureStoredProcedureCommandName;
                options.SetDbStatementForText            = captureTextCommandContent;
                options.RecordException = recordException;
#else
                options.SetDbStatement = captureStoredProcedureCommandName;
#endif
                if (shouldEnrich)
                {
                    options.Enrich = ActivityEnrichment;
                }
            })
                                       .Build();

#if NETFRAMEWORK
            // RecordException not available on netfx
            recordException = false;
#endif

            using SqlConnection sqlConnection = new SqlConnection(SqlConnectionString);

            sqlConnection.Open();

            string dataSource = sqlConnection.DataSource;

            sqlConnection.ChangeDatabase("master");

            using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection)
                  {
                      CommandType = commandType,
                  };

            try
            {
                sqlCommand.ExecuteNonQuery();
            }
            catch
            {
            }

            Assert.Single(activities);
            var activity = activities[0];

            VerifyActivityData(commandType, commandText, captureStoredProcedureCommandName, captureTextCommandContent, isFailure, recordException, shouldEnrich, dataSource, activity);
            VerifySamplingParameters(sampler.LatestSamplingParameters);
        }